techy 0.1.3

A fast, extensible LaTeX parser for Rust
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
//! The [`TokenReader`] trait and its standard implementation, [`StdTokenReader`].
//!
//! A reader turns input into tokens on demand, one at a time, and keeps a position in
//! the resulting stream. Four methods do the work: [`peek`](TokenReader::peek) parses
//! the token at the current position without moving,
//! [`move_to`](TokenReader::move_to) repositions the stream at a named edge of a token,
//! [`move_to_position`](TokenReader::move_to_position) repositions it at a position the
//! reader returned earlier, and [`next`](TokenReader::next) is a peek followed by a move
//! past the token. Construct parsers read their input only through a reader; the
//! [`TokenReader`] documentation states the full contract, for callers and for anyone
//! writing a reader of their own.
//!
//! [`StdTokenReader`] scans in-memory text under the token rules held by the parsing
//! state. Its scanning core, [`StdTokenReader::scan_std_token_at`], is assembled from
//! the scan helpers of this module — one function per construct, each driven by one
//! feature block of the [`TokenRules`](super::TokenRules) — except specials
//! recognition, which [`scan_specials_trigger`] delegates to [`Lang::scan_specials`],
//! calling that hook only where the state's cached
//! [`TriggerChars`](super::TriggerChars) filter admits the character at hand.
//!
//! Whitespace is skipped in one place, [`skip_whitespace`], so that pre-space, command
//! post-space and comment post-space all obey the same rule: while paragraph-break
//! detection is on
//! ([`TokenRules::paragraphs_enabled`](super::TokenRules::paragraphs_enabled)), skipped
//! whitespace never consumes a newline belonging to a `\n\s*\n` sequence. Such a
//! sequence always surfaces as a [`ParagraphBreak`](TokenKind::ParagraphBreak) token.
//! [`ParagraphBreak`](TokenKind::ParagraphBreak) token.

use alloc::boxed::Box;
use alloc::format;
use alloc::string::String;
use alloc::sync::Arc;

use crate::constructs::ImplementationError;
use crate::source::{Source, SourceOrigin, SourcePos, SourceSpan, Span};
use crate::state::{FeaturePresence, Lang, LangFeatures, ParsingState};

use super::error::{ForbiddenChar, TokenError, TokenErrorKind, TokenRecovery, TokenResult};
use super::scan::{
    command_rule_at, scan_command, scan_comment, scan_group_delimiter, scan_paragraph_break,
    scan_specials_trigger, skip_whitespace, GroupDelimiterMatch,
};
use super::token::{StdToken, StdTokenKindData, TokenKind};
use super::tokenization::{StreamPosition, Token, Tokenization};

/// One of the five boundaries of a token, in reading order.
///
/// A token occupies a stretch of the stream with two optional whitespace wings.
/// *Pre-space* is content whitespace read just before the token and lying outside its
/// span; *post-space* is syntactic whitespace consumed just after the token proper and
/// lying inside its span — only [`Command`](TokenKind::Command) and
/// [`Comment`](TokenKind::Comment) tokens have any. Inside the token proper, some kinds
/// begin with a leading marker before their own content: a comment's start delimiter, a
/// command's escape character.
///
/// An edge names one of the five boundaries this creates. Asking a [`TokenReader`] for a
/// position or a span at an edge is how a construct parser talks about where a token is
/// without knowing how the reader stores either.
///
/// The five offsets are in reading order and may coincide:
///
/// ```text
/// StartBeforePreSpace ≤ Start ≤ ContentStart ≤ End ≤ EndPastPostSpace
/// ```
///
/// `ContentStart == Start` for a kind with no leading marker;
/// `End == EndPastPostSpace` for a kind with no post-space;
/// `StartBeforePreSpace == Start` for a token with no preceding whitespace.
///
/// `PartialOrd`/`Ord` compare the variants in declaration order, which is reading order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TokenEdge {
    /// Where the token's pre-space begins — the position the stream stood at when the
    /// token was read.
    StartBeforePreSpace,
    /// Where the token proper begins (its pre-space has been passed).
    Start,
    /// Where the token's own content begins, past its leading marker: after a
    /// [`Comment`](TokenKind::Comment)'s start delimiter, after a
    /// [`Command`](TokenKind::Command)'s escape character. Every other kind has no
    /// leading marker, so this is its [`Start`](TokenEdge::Start).
    ContentStart,
    /// Where the token proper ends — equivalently, where its post-space begins.
    End,
    /// Where the token's post-space ends: the position the stream stands at after
    /// reading the token with [`next`](TokenReader::next).
    EndPastPostSpace,
}

/// The stream position type of [`StdTokenReader`]: an opaque byte offset into the
/// content the reader scans.
///
/// A *stream position* names a place in a reader's token stream. Construct parsers
/// obtain one only from the reader ([`position_here`](TokenReader::position_here),
/// [`position_at`](TokenReader::position_at)) and give it back to the reader
/// ([`move_to_position`](TokenReader::move_to_position),
/// [`source_span_within`](TokenReader::source_span_within)). There is deliberately no
/// public constructor and no arithmetic, so a position cannot be invented or shifted
/// outside the reader that produced it.
///
/// Positions compare with `==` only. Two positions of the same reader are equal exactly
/// when they name the same place, which is what the parse loops need in order to tell
/// whether the reader moved.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StdStreamPosition(usize);

impl StdStreamPosition {
    /// The position at byte offset `offset`. In-crate readers only: producing a
    /// position is the issuing reader's privilege (see the type's documentation).
    pub(crate) fn at(offset: usize) -> Self {
        StdStreamPosition(offset)
    }

    /// The byte offset this position names.
    pub(crate) fn offset(self) -> usize {
        self.0
    }
}

/// The interface a parse reads its input through: tokens on demand, and where they are.
///
/// Two audiences read this documentation.
///
/// **Callers** — construct parsers and the parsing machinery — walk the input with a
/// reader. Exactly three methods move the stream: [`next`](TokenReader::next) reads the
/// token at the current position and moves past it, [`move_to`](TokenReader::move_to)
/// repositions the stream at a named [`TokenEdge`] of a token, and
/// [`move_to_position`](TokenReader::move_to_position) repositions it at a position the
/// reader returned earlier.
///
/// Every other method leaves the position untouched: [`peek`](TokenReader::peek) parses
/// the token at the current position without moving,
/// [`token_kind`](TokenReader::token_kind) says what a token is, and the position and
/// span methods say where a token or a position is.
///
/// A parser can therefore look before it commits: peek, then either consume the token
/// or leave the stream where it stands. To look further ahead, keep a position, move
/// the stream, and rewind to that position afterwards.
///
/// **Implementors** write a reader when tokenization itself has to work differently:
/// catcode-like schemes, non-textual sources, a macro expander that splices content
/// into the stream. The *Contract* section below is what such a reader must satisfy,
/// and the parsing machinery relies on every clause of it. [`StdTokenReader`] is the
/// standard implementation, and *Writing a reader over standard tokens* at the end of
/// this page shows how to reuse it instead of starting from scratch. See also
/// [defining a custom language](crate::guide::custom_lang).
///
/// [`peek`](TokenReader::peek) receives the whole [`ParsingState<L>`], not just the
/// token rules, so that a reader holding tokenization tables of its own can keep them
/// in [`Lang::StateExt`], which only the state makes reachable. Since the state changes
/// during a parse, the same content may tokenize differently at two points of one
/// parse.
///
/// A reader for one parse is built by the language's
/// [`Tokenization::make_token_reader`], which a driver may override with a reader of
/// its own ([`ParseDriver::make_token_reader`](crate::core::ParseDriver::make_token_reader)).
///
/// # Positions, edges, and spans
///
/// A reader is the only interpreter of its own stream. Two kinds of value serve that:
///
/// - A **stream position** ([`StreamPosition<L>`](super::StreamPosition), the type the
///   language's [`Tokenization`](super::Tokenization) declares) names a place in the
///   token stream. Only a reader produces one
///   ([`position_here`](TokenReader::position_here),
///   [`position_at`](TokenReader::position_at)), and a caller only gives it back
///   ([`move_to_position`](TokenReader::move_to_position),
///   [`source_span_within`](TokenReader::source_span_within)). Positions compare for
///   equality, never for order.
/// - A **[`TokenEdge`]** names one of a token's five boundaries: the two whitespace
///   wings, the token proper, and where the token's own content begins past a leading
///   marker such as a comment delimiter or a command's escape character. Asking for a
///   position or a span at an edge is how a caller talks about where a token is without
///   reading anything off the token. The three sub-spans a comment node records are
///   exactly `Start..ContentStart`, `ContentStart..End` and `End..EndPastPostSpace`.
///
/// A reader reports locations in exactly one form: a [`SourceSpan`] or a
/// [`SourcePos`], each of which names its own source. That is what lets a reader serve
/// tokens from more than one source during one parse without its caller having to
/// know.
///
/// A reader may do that at one nesting level only when the language declares
/// [`Lang::OBEYS_SPAN_TILING`] `= false` (contract clause 8). A language that obeys
/// span tiling reads one source per parse; further sources enter such a parse only
/// through a nested parse over another source
/// ([`ParseContext::parse_attached_source`](crate::core::constructs::ParseContext::parse_attached_source)).
///
/// # Contract
///
/// 1. **`peek` is speculative, and idempotent per (stream position, state instance).**
///    Repeated calls at the same stream position with the *same* [`ParsingState`]
///    instance return an equal token, and `peek` alone never moves the stream:
///    [`move_to`](TokenReader::move_to),
///    [`move_to_position`](TokenReader::move_to_position) and
///    [`next`](TokenReader::next) are what commit. A *different* state instance — even
///    one derived with an empty delta — relieves `peek` of any obligation to repeat
///    itself.
///
///    The state arrives as an `&Arc` precisely so that implementations may memoize on
///    that key. Clone the `Arc` into the cache: pointer identity is a sound key *only
///    while a strong reference pins the allocation*, since a dropped state's address
///    can be recycled for a different state.
///
/// 2. **A peeked token's [`StartBeforePreSpace`](TokenEdge::StartBeforePreSpace) edge is
///    the stream position the peek happened at.** `move_to(&tok, StartBeforePreSpace)`
///    right after a `peek` does nothing, and later returns the stream to exactly where
///    that peek happened.
///
/// 3. **Tokens and positions stay usable for the whole parse.** Every token and every
///    position a reader returns remains a valid argument to `move_to`,
///    `move_to_position`, `position_at`, `source_span_between` and
///    `source_span_within` until the parse ends; a reader serving several sources
///    (clause 8) must keep them all addressable.
///
/// 4. **Interpretation stays with the issuing reader**, or with a reader over the same
///    content. Passing a token or a position to a reader that did not produce it
///    violates the caller's side of this contract.
///
///    [`StdTokenReader`] cannot detect that, and answers from the offsets stored in the
///    token. What it answers is deliberately asymmetric:
///    [`token_kind`](TokenReader::token_kind) reads an empty slice where the token's
///    offsets fall outside its content, a wrong answer being preferable to a new panic
///    in library code, while
///    [`source_span_between`](TokenReader::source_span_between) passes those offsets to
///    [`SourceSpan::new`], whose precondition assert then fires.
///
///    A foreign *position* is answered the same way: `StdTokenReader` passes it
///    straight to [`SourcePos::new`] in
///    [`source_position_at`](TokenReader::source_position_at) and to
///    [`SourceSpan::new`] in
///    [`source_span_within`](TokenReader::source_span_within), so a position this
///    reader never produced trips those same asserts —
///    [`ParseContext::here`](crate::core::constructs::ParseContext::here) bottoms out
///    there too, through `source_position_at`. Those asserts are listed in
///    [the panicking items of the API](crate::guide::panics).
///
/// 5. **Absent features yield no tokens.** A token kind belonging to a feature the
///    language declares absent ([`Lang::Features`]) must never be produced: no
///    `GroupOpen`/`GroupClose` without the groups feature, no `Command`, `Comment`,
///    `Specials` or `ParagraphBreak` without theirs. The parsing machinery treats any
///    such token as a violated contract and reports an implementation error instead of
///    processing it, uniformly across token kinds.
///
/// 6. **Edge order does not matter to `source_span_between`.** The result is the span
///    between the two edges in reading order, whichever order they are named in. Two
///    equal edges give the empty span at that edge.
///
/// 7. **Moving sets the position.** After `move_to(&tok, edge)`, `position_here()`
///    equals `position_at(&tok, edge)`; after `move_to_position(&p)`,
///    `position_here()` equals `p`.
///
///    Together with clause 2 this fixes where two consecutive tokens meet: for a token
///    `next` peeked right after the stream was moved past `prev`,
///    `position_at(next, StartBeforePreSpace) == position_at(prev, EndPastPostSpace)`.
///    That holds in every reader, including where `next` is the first token of another
///    source (see *Seams* below).
///
///    Where the standard nodes parser is accumulating a run of content characters, its
///    content loop checks this equality for the token it is about to add to the pending
///    run, and reports a mismatch as an implementation error, whatever the language's
///    [`Lang::OBEYS_SPAN_TILING`] says.
///
/// 8. **One source, in reading order, without gaps** — required of the readers of a
///    language that declares [`OBEYS_SPAN_TILING`](Lang::OBEYS_SPAN_TILING) `= true`
///    (the default).
///
///    Such a reader serves one parse from one source, tokens in reading order, with
///    every byte between the earlier token's [`End`](TokenEdge::End) edge and the later
///    token's [`Start`](TokenEdge::Start) edge belonging to exactly one of them: to the
///    earlier token's post-space or to the later one's pre-space. The source a parse
///    reads changes only where a parser builds a new reader over another source
///    ([`ParseContext::parse_attached_source`](crate::core::constructs::ParseContext::parse_attached_source)).
///
///    This is what makes the language's parse trees span-tiled, and the machinery
///    enforces it: a pair of stream positions that does not delimit one forward range
///    of one source is reported as an implementation error
///    ([`ParseContext::source_span_within`](crate::core::constructs::ParseContext::source_span_within)).
///
///    Under `OBEYS_SPAN_TILING = false` none of this is promised, and the reader
///    answers [`source_span_describing`](TokenReader::source_span_describing) for the
///    spans of multi-token constructs.
///
/// 9. **Every token advances the stream.** For every token but the terminal
///    [`EndOfStream`](TokenKind::EndOfStream),
///    `position_at(&tok, EndPastPostSpace) != position_at(&tok, StartBeforePreSpace)`.
///
///    Clauses 1, 2 and 7 are why: a token whose two ends are the same position is
///    served again by the next `peek`, at the position its consumer moved to, under the
///    same state — a read that never ends.
///
///    What the clause rules out is the equality of the two positions, not an *empty
///    span*. A reader may serve a token with no bytes behind it, a synthesized
///    delimiter for instance, provided it produces two distinct position values for the
///    token's two ends. Positions are the language's own type and compare for equality
///    only, so any two values the reader tells apart will do; clauses 1–3 require them
///    of such a reader anyway, since `move_to(&tok, StartBeforePreSpace)` followed by a
///    fresh `peek` must return that same token — which a reader that stands still and
///    tracks its progress in hidden state cannot deliver.
///
///    The standard nodes parser enforces the clause: a token it consumed that left the
///    stream position unchanged is reported as an implementation error, which aborts
///    the parse under any recovery policy instead of looping. The recovery path, where
///    no token is consumed, is covered separately by the
///    [`TokenRecovery::resume` contract](super::TokenRecovery#contract-resume-must-move-the-stream).
///
/// At the end of the stream, `peek` returns the terminal, idempotent
/// [`EndOfStream`](TokenKind::EndOfStream) token rather than an `Option`, and the
/// input's final whitespace is reported as that token's pre-space.
///
/// # Seams — readers that serve several sources at one nesting level
///
/// A **seam** is a place in the stream where the next token comes from a different
/// source than the previous one. Only a reader of a language with
/// [`OBEYS_SPAN_TILING`](Lang::OBEYS_SPAN_TILING) `= false` has any (clause 8).
/// Clauses 2 and 7 hold at a seam too, and that determines what the positions there
/// mean:
///
/// - The first token drawn from a new source reports the **trigger position** — where
///   the stream stood in the outer source when the new source was entered — as its
///   [`StartBeforePreSpace`](TokenEdge::StartBeforePreSpace) edge. Un-consuming that
///   token (`move_to(&tok, StartBeforePreSpace)`) therefore returns the stream to the
///   trigger, and the next `peek` produces the same first token again (clause 1).
/// - The position past the last token of an exhausted source is the **resume
///   position**, where reading continues in the outer source.
///
/// One position value names such a shared place. Which value that is, and what
/// [`source_position_at`](TokenReader::source_position_at) reports for it, is the
/// reader's choice: an outer coordinate, an inner one, or a composite of both.
/// Reporting the outer coordinate — the trigger or the resume position — is the
/// recommended answer, since that is the location a reader of a diagnostic can act on.
///
/// A token may consequently have edges in two different sources. Its sub-spans are
/// asked for one at a time through
/// [`source_span_between`](TokenReader::source_span_between), and each of those is a
/// span of a single source.
///
/// Because the positions on the two sides of a seam compare equal, a run of content
/// characters may legitimately extend across one. That is why the parsers of such a
/// language record multi-token content as owned text rather than as a span.
///
/// Five further rules apply to these readers:
///
/// - **The pre-space of the first token drawn from a new source must lie within that
///   source.** That token's [`StartBeforePreSpace`](TokenEdge::StartBeforePreSpace)
///   edge is the trigger position, and the trigger position and the start of the new
///   source are one shared place (above), so attributing whitespace of the *outer*
///   source to that token as pre-space would put real whitespace between two equal
///   position values.
///
///   The parsing machinery decides whether a token has pre-space by comparing exactly
///   those two positions: equal values read as no pre-space, the pre-space text is
///   never asked for, and the whitespace disappears from the parsed content without any
///   diagnostic. Outer whitespace that precedes a seam must therefore be served in the
///   outer source — as the post-space of the token before the seam, or by starting the
///   new source's content with that whitespace so the first token's pre-space lies past
///   the seam.
///
///   The mirrored attribution is sound: outer whitespace after an exhausted source may
///   be the last inner token's post-space, because
///   [`EndPastPostSpace`](TokenEdge::EndPastPostSpace) — the resume position, past that
///   whitespace — is then a different position value than [`End`](TokenEdge::End).
/// - **Termination is the reader's responsibility.** An expansion that never ends is
///   simply an endless token stream; the engine's nesting-depth limiter
///   ([`DescentGuard`](crate::core::DescentGuard)) counts parser nesting, not tokens,
///   and will not stop it.
/// - **Positions and tokens stay valid inside sources the stream has already left**
///   (clause 3): parsers rewind across seams — an argument probe that fails, a stop
///   token that is peeked and left unconsumed — and every position they kept must still
///   be accepted by `move_to_position`.
/// - **Create an expansion's source with**
///   [`SourceProvenance::Synthesized`](crate::source::SourceProvenance::Synthesized):
///   its `description` names what produced the content and its `triggered_at` names the
///   span the expansion was triggered at, so that a diagnostic reported inside the
///   expansion can be traced back to the input through the provenance chain. Entering
///   an expansion pushes no [`Frame`](crate::core::Frame), since it is not a construct
///   parse.
/// - **[`EndOfStream`](TokenKind::EndOfStream) is the end of the *whole* input.** An
///   exhausted expansion is not end of stream: the reader continues in the outer
///   source. The rule that the input's final whitespace surfaces as the end-of-stream
///   token's pre-space applies to the end of the whole input only.
///
/// # Writing a reader over standard tokens
///
/// A reader that produces the same tokens as [`StdTokenReader`] but decides differently
/// *which* token comes next — re-classifying a character, splicing in content — does
/// not have to reimplement interpretation. Keep an inner `StdTokenReader` over the same
/// content, build tokens with the [`StdToken`] constructors, and delegate every
/// interpretive method to the inner reader. A token has no readable data, so there is
/// nothing to reimplement: a `StdToken`'s spans are offsets into that content, which
/// the inner reader also answers with
/// [`source_span_between`](TokenReader::source_span_between).
///
/// A reader that keeps one inner `StdTokenReader` per source, wrapping their tokens in
/// a token type of its own (see *Seams* above), instead calls the two inner-reader
/// methods that need no tokenization declaration of their own:
/// [`scan_std_token_at`](StdTokenReader::scan_std_token_at) to read a standard token,
/// and [`token_kind_of_std_token`](StdTokenReader::token_kind_of_std_token) to
/// interpret one. The [`core::token`](crate::core::token) module documentation
/// describes that case in full.
///
/// Because the inner reader is generic over the language, delegation goes through a
/// `&dyn TokenReader<'s, L>` / `&mut dyn TokenReader<'s, L>` view of it: plain method
/// syntax on the concrete inner reader cannot infer the language.
///
/// ```
/// use std::sync::Arc;
/// use techy::core::token::{
///     StdStreamPosition, StdToken, StdTokenReader, TokenEdge, TokenKind, TokenReader,
///     TokenResult,
/// };
/// use techy::core::{ParsingState, TrivialLang};
/// use techy::source::{SourcePos, SourceSpan};
///
/// #[derive(Debug, Clone, Copy)]
/// struct MyLang;
/// impl TrivialLang for MyLang {}
///
/// struct MyReader<'s> {
///     inner: StdTokenReader<'s>,
/// }
///
/// impl<'s> MyReader<'s> {
///     fn inner(&self) -> &dyn TokenReader<'s, MyLang> {
///         &self.inner
///     }
///     fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, MyLang> {
///         &mut self.inner
///     }
/// }
///
/// impl<'s> TokenReader<'s, MyLang> for MyReader<'s> {
///     /// The one method this reader decides for itself.
///     fn peek(
///         &mut self,
///         state: &Arc<ParsingState<MyLang>>,
///     ) -> TokenResult<MyLang, StdToken<MyLang>> {
///         let token = self.inner_mut().peek(state)?;
///         // … re-classify or replace `token`, building it with `StdToken::…` and spans
///         // taken from `self.inner.content()` or from the inner reader's answers.
///         Ok(token)
///     }
///
///     /// Everything interpretive is the inner reader's answer.
///     fn token_kind<'t>(&self, tok: &'t StdToken<MyLang>) -> TokenKind<'t, MyLang>
///     where
///         's: 't,
///     {
///         self.inner().token_kind(tok)
///     }
/// #    fn move_to(&mut self, tok: &StdToken<MyLang>, edge: TokenEdge) {
/// #        self.inner_mut().move_to(tok, edge)
/// #    }
/// #    fn move_to_position(&mut self, at: &StdStreamPosition) {
/// #        self.inner_mut().move_to_position(at)
/// #    }
/// #    fn source_span_between(
/// #        &self,
/// #        tok: &StdToken<MyLang>,
/// #        a: TokenEdge,
/// #        b: TokenEdge,
/// #    ) -> SourceSpan {
/// #        self.inner().source_span_between(tok, a, b)
/// #    }
/// #    fn position_here(&self) -> StdStreamPosition {
/// #        self.inner().position_here()
/// #    }
/// #    fn position_at(&self, tok: &StdToken<MyLang>, edge: TokenEdge) -> StdStreamPosition {
/// #        self.inner().position_at(tok, edge)
/// #    }
/// #    fn source_position_at(&self, at: &StdStreamPosition) -> SourcePos {
/// #        self.inner().source_position_at(at)
/// #    }
/// #    fn source_span_within(
/// #        &self,
/// #        begin: &StdStreamPosition,
/// #        end: &StdStreamPosition,
/// #    ) -> Option<SourceSpan> {
/// #        self.inner().source_span_within(begin, end)
/// #    }
/// #    fn source_span_describing(
/// #        &self,
/// #        begin: &StdStreamPosition,
/// #        end: &StdStreamPosition,
/// #    ) -> SourceSpan {
/// #        self.inner().source_span_describing(begin, end)
/// #    }
///     // … the remaining position and span methods delegate the same way.
/// }
/// ```
pub trait TokenReader<'s, L: Lang> {
    /// Parses the token at the current position, without moving the stream.
    ///
    /// Reading ahead is what this is for: peek, decide, then either consume the token
    /// with [`move_to`](TokenReader::move_to) at
    /// [`EndPastPostSpace`](TokenEdge::EndPastPostSpace) or leave the stream where it
    /// stands. Peeking twice at the same position under the same `state` returns an
    /// equal token (contract clause 1), so nothing is lost by asking again.
    ///
    /// `state` supplies the whole tokenization behavior: the token rules in force here,
    /// and whatever a custom reader keeps in [`Lang::StateExt`].
    ///
    /// # Errors
    ///
    /// A [`TokenError`](super::TokenError) reports a condition in the content, such as
    /// a forbidden character. It offers a
    /// [`TokenRecovery`](super::TokenRecovery) where the reader can describe how to
    /// carry on; whether that recovery is taken is the session's
    /// [`Recovery`](crate::error::Recovery) policy to decide, not the reader's.
    fn peek(&mut self, state: &Arc<ParsingState<L>>) -> TokenResult<L, Token<L>>;

    /// Parses the token at the current position and moves past it, post-space included.
    ///
    /// Equivalent to [`peek`](TokenReader::peek) followed by
    /// [`move_to`](TokenReader::move_to) at
    /// [`EndPastPostSpace`](TokenEdge::EndPastPostSpace). A failing peek leaves the
    /// stream where it stands.
    fn next(&mut self, state: &Arc<ParsingState<L>>) -> TokenResult<L, Token<L>> {
        let token = self.peek(state)?;
        self.move_to(&token, TokenEdge::EndPastPostSpace);
        Ok(token)
    }

    // --- navigation by edge and by position ------------------------------------------

    /// Repositions the stream at `edge` of `tok`, forward or backward.
    ///
    /// This is the navigation the parse loops use. `move_to(&tok,
    /// TokenEdge::EndPastPostSpace)` consumes the token; `move_to(&tok,
    /// TokenEdge::Start)` puts it back to be read again, and
    /// [`StartBeforePreSpace`](TokenEdge::StartBeforePreSpace) gives back the
    /// whitespace before it as well.
    ///
    /// The two inner edges, [`ContentStart`](TokenEdge::ContentStart) and
    /// [`End`](TokenEdge::End), put the stream *inside* the token: past a leading
    /// marker, or before the syntactic post-space (the `\verb` idiom).
    fn move_to(&mut self, tok: &Token<L>, edge: TokenEdge);

    /// Repositions the stream at a position this reader returned earlier.
    ///
    /// The move goes in either direction, serving rewinds as well as resumes, so an
    /// implementation must not assume that `at` lies ahead of the current position.
    ///
    /// When adopting a [`TokenRecovery`](super::TokenRecovery), the *caller* is what
    /// enforces the
    /// [advancement contract](super::TokenRecovery#contract-resume-must-move-the-stream).
    fn move_to_position(&mut self, at: &StreamPosition<L>);

    // --- what a token is --------------------------------------------------------------

    /// The parser-facing view of `tok`: what the token *is*, with the written
    /// spellings this reader resolved.
    ///
    /// This is the only way a construct parser reads a token. The returned
    /// [`TokenKind`] borrows from the token, and from the scanned content for a reader
    /// that scans borrowed content. It never borrows the reader, so a parser may hold
    /// it while it goes on reading and moving the stream.
    ///
    /// The view says nothing about where the token is. That comes from
    /// [`source_span_of`](TokenReader::source_span_of),
    /// [`source_span_between`](TokenReader::source_span_between) and
    /// [`position_at`](TokenReader::position_at): a comment's delimiter span, for
    /// instance, is `source_span_between(tok, Start, ContentStart)`.
    fn token_kind<'t>(&self, tok: &'t Token<L>) -> TokenKind<'t, L>
    where
        's: 't;

    // --- where a token is -------------------------------------------------------------

    /// The source span delimited by two edges of `tok`, in either argument order (see
    /// contract clause 6).
    ///
    /// # Panics
    ///
    /// Passing a token this reader did not produce violates contract clause 4 above,
    /// and an implementation is free to panic on it. [`StdTokenReader`] does: it passes
    /// the token's offsets to [`SourceSpan::new`], whose precondition assert then fires
    /// (see the [list of panicking items](crate::guide::panics)).
    fn source_span_between(
        &self,
        tok: &Token<L>,
        a: TokenEdge,
        b: TokenEdge,
    ) -> SourceSpan<L::SourceOrigin>;

    /// The token's own span, from [`Start`](TokenEdge::Start) to
    /// [`EndPastPostSpace`](TokenEdge::EndPastPostSpace): pre-space excluded,
    /// post-space included.
    ///
    /// # Panics
    ///
    /// This calls [`source_span_between`](TokenReader::source_span_between) and
    /// panics under the same condition: a token the reader did not produce.
    fn source_span_of(&self, tok: &Token<L>) -> SourceSpan<L::SourceOrigin> {
        self.source_span_between(tok, TokenEdge::Start, TokenEdge::EndPastPostSpace)
    }

    // --- where the stream is ----------------------------------------------------------

    /// The stream position the reader stands at.
    fn position_here(&self) -> StreamPosition<L>;

    /// The stream position at `edge` of `tok`.
    fn position_at(&self, tok: &Token<L>, edge: TokenEdge) -> StreamPosition<L>;

    /// Where a stream position lies in text.
    ///
    /// To anchor a diagnostic at a position, build the empty span there with
    /// [`SourceSpan::at`].
    ///
    /// # Panics
    ///
    /// Passing a position this reader did not produce violates contract clause 4
    /// above, and an implementation is free to panic on it. [`StdTokenReader`] does:
    /// it passes the offset to [`SourcePos::new`], whose precondition assert then fires
    /// (see the [list of panicking items](crate::guide::panics)).
    fn source_position_at(&self, at: &StreamPosition<L>) -> SourcePos<L::SourceOrigin>;

    /// The source span running from `begin` to `end`, when the two positions delimit one
    /// range of one source; `None` otherwise.
    ///
    /// `None` means the pair is incoherent: `end` before `begin`, or the two in
    /// different sources. That is a bug in the calling code, not a condition of the
    /// parsed content, and the caller reports it as an implementation error.
    ///
    /// # Panics
    ///
    /// A position this reader did not produce is *not* answered with `None`: it
    /// violates contract clause 4 above, and an implementation is free to panic on it.
    /// [`StdTokenReader`] does: it passes the two offsets to [`SourceSpan::new`], whose
    /// precondition assert then fires (see the [list of panicking
    /// items](crate::guide::panics)).
    fn source_span_within(
        &self,
        begin: &StreamPosition<L>,
        end: &StreamPosition<L>,
    ) -> Option<SourceSpan<L::SourceOrigin>>;

    /// A source span **describing** the stretch of stream from `begin` to `end`, where
    /// the two positions need not delimit one range of one source.
    ///
    /// This is what a node covering several tokens is recorded with when the language
    /// does not obey span tiling ([`Lang::OBEYS_SPAN_TILING`] `= false`). The parsers
    /// of a language that does obey span tiling never call this method: they use
    /// [`source_span_within`](TokenReader::source_span_within) and treat its `None` as
    /// an implementation error.
    ///
    /// The answer is the reader's to choose — any [`SourceSpan`] it considers a useful
    /// description of that stretch. The parsing machinery derives no content, no
    /// structure and no ordering from it; the span becomes the node's span and appears
    /// in diagnostics.
    ///
    /// The recommended answer is `begin`'s source, running from `begin` to wherever the
    /// stream last stood in that source before reaching `end`. Where the two positions
    /// *do* delimit one range of one source, answer that range, which is what
    /// [`source_span_within`](TokenReader::source_span_within) returns.
    ///
    /// This method always answers: the empty span at `begin` — [`SourceSpan::at`] of
    /// [`source_position_at`](TokenReader::source_position_at) — is always available.
    ///
    /// # Panics
    ///
    /// "Always answers" holds for positions the reader produced. A foreign position
    /// violates contract clause 4 above, and an implementation is free to panic on it.
    /// [`StdTokenReader`] does: it passes the offsets to [`SourceSpan::new`], whose
    /// precondition assert then fires (see the [list of panicking
    /// items](crate::guide::panics)).
    fn source_span_describing(
        &self,
        begin: &StreamPosition<L>,
        end: &StreamPosition<L>,
    ) -> SourceSpan<L::SourceOrigin>;
}

/// The standard [`TokenReader`]: it scans in-memory content under the token rules of
/// the parsing state.
///
/// This is the reader a parse uses unless the language or the driver installs another
/// one. A language whose [`Lang::Tokenization`] is
/// [`StdTokenization`](super::StdTokenization) is given one per parse by
/// [`Tokenization::make_token_reader`](super::Tokenization::make_token_reader), and a
/// driver may return one of its own instead
/// ([`ParseDriver::make_token_reader`](crate::core::ParseDriver::make_token_reader)).
/// Outside a parse, [`new`](StdTokenReader::new) builds a reader over any
/// [`Source`].
///
/// The reader itself stores only the content borrow and a position. All tokenization
/// behavior comes from the state passed to [`peek`](TokenReader::peek) — the
/// [`TokenRules`](super::TokenRules) data with its derived caches, and the
/// [`Lang::scan_specials`] hook — which is what lets the rules change mid-parse through
/// state transitions.
///
/// A feature the language declares absent ([`Lang::Features`]) is never detected: its
/// detection branch is eliminated at compile time, and its rules block stores no data
/// to consult in the first place.
///
/// A custom reader that wants standard tokens need not reproduce any of this; see
/// *Writing a reader over standard tokens* in the [`TokenReader`] documentation.
#[derive(Debug, Clone)]
pub struct StdTokenReader<'s, O: SourceOrigin = Option<String>> {
    source: &'s Arc<Source<O>>,
    content: &'s str,
    pos: usize,
}

impl<'s, O: SourceOrigin> StdTokenReader<'s, O> {
    /// Creates a reader positioned at the start of `source`'s content.
    ///
    /// The reader borrows the source rather than cloning the `Arc`, because it needs the
    /// source to answer where its tokens are: every location it returns is a
    /// [`SourceSpan`] or [`SourcePos`] qualified by this source, and cloning the `Arc`
    /// once per location keeps that cheap.
    pub fn new(source: &'s Arc<Source<O>>) -> StdTokenReader<'s, O> {
        StdTokenReader { source, content: source.content(), pos: 0 }
    }

    /// The source being tokenized.
    pub fn source(&self) -> &'s Arc<Source<O>> {
        self.source
    }

    /// The content being tokenized.
    pub fn content(&self) -> &'s str {
        self.content
    }

    /// The largest offset at or before `offset` that is a valid position in the
    /// content: within bounds and on a character boundary. Used to anchor the report of
    /// an invalid position, which by definition is not itself an anchor.
    fn nearest_valid_offset(&self, offset: usize) -> usize {
        let mut offset = offset.min(self.content.len());
        while !self.content.is_char_boundary(offset) {
            offset -= 1;
        }
        offset
    }

    /// Whether the reader is at the end of the content.
    pub fn is_at_end(&self) -> bool {
        self.pos >= self.content.len()
    }

    /// The parser-facing view of `tok`, with `L: Lang` as its only requirement.
    ///
    /// This is the interpretation behind [`TokenReader::token_kind`], reachable without
    /// the trait. A language whose [`Lang::Tokenization`] declares a token type of its
    /// own, and stores standard tokens read by inner `StdTokenReader`s inside it — one
    /// inner reader per source — interprets those stored tokens through this method. It
    /// cannot go through [`TokenReader::token_kind`], because the implementation of that
    /// trait here is available only to languages tokenized in
    /// [`StdToken`]/[`StdStreamPosition`], which such a language is not.
    ///
    /// The returned view borrows the token and this reader's content, never the reader,
    /// so a caller may hold it while it goes on reading and moving the stream.
    ///
    /// Interpreting a token with a reader that did not issue it is ruled out by clause 4
    /// of the [`TokenReader`] contract, and this reader cannot detect it: offsets that
    /// fall outside this reader's content read as empty text, never as a panic.
    pub fn token_kind_of_std_token<'t, L: Lang>(
        &self,
        tok: &'t StdToken<L>,
    ) -> TokenKind<'t, L>
    where
        's: 't,
    {
        // Every written spelling is a run of this reader's content between two of the
        // token's edges — that is where a token's spans live (contract clause 4). A
        // token this reader never issued — a caller-contract violation it cannot
        // detect — may carry offsets this content does not have; such a run reads as
        // empty rather than panicking.
        let text = |a: TokenEdge, b: TokenEdge| -> &'t str {
            self.content.get(tok.edge_offset(a)..tok.edge_offset(b)).unwrap_or("")
        };
        match tok.kind_data() {
            StdTokenKindData::Char(c) => TokenKind::Char(*c),
            StdTokenKindData::GroupOpen { rule } => TokenKind::GroupOpen {
                delim: text(TokenEdge::Start, TokenEdge::End),
                rule,
            },
            StdTokenKindData::GroupClose => {
                TokenKind::GroupClose { delim: text(TokenEdge::Start, TokenEdge::End) }
            }
            StdTokenKindData::Command { escape_char, .. } => TokenKind::Command {
                name: text(TokenEdge::ContentStart, TokenEdge::End),
                escape_char: *escape_char,
            },
            StdTokenKindData::Specials { callable_type, spec } => TokenKind::Specials {
                callable_type: *callable_type,
                name: text(TokenEdge::Start, TokenEdge::End),
                spec,
            },
            StdTokenKindData::Comment { .. } => TokenKind::Comment {
                start_delim: text(TokenEdge::Start, TokenEdge::ContentStart),
                content: text(TokenEdge::ContentStart, TokenEdge::End),
            },
            StdTokenKindData::ParagraphBreak => TokenKind::ParagraphBreak,
            StdTokenKindData::EndOfStream => TokenKind::EndOfStream,
        }
    }

    // --- scanning core ------------------------------------------------------------------

    /// Scans the token beginning at `start` under `state`, without moving this reader.
    ///
    /// This is the scanning core behind [`peek`](TokenReader::peek). Where the reader
    /// itself stands is neither consulted nor changed: `start` says where to read.
    ///
    /// It is also what a reader of a language whose [`Lang::Tokenization`] declares
    /// **its own** token or stream-position types reuses. Such a language is not the
    /// `Token = StdToken<L>, StreamPosition = StdStreamPosition` one this reader's
    /// [`TokenReader`] implementation requires, so it cannot call `peek` here, yet the
    /// tokens it wants are exactly the ones this scan produces. Everything the scan
    /// needs of `L` is `L: Lang<SourceOrigin = O>`, except the recovery step described
    /// under *Failures* below.
    ///
    /// # Priority order
    ///
    /// Whitespace from `start` is skipped first ([`skip_whitespace`]) and becomes the
    /// token's pre-space; none of the steps below sees it. Then the first of these that
    /// matches produces the token — a construct whose feature the language declares
    /// absent, or whose rules block `state` has disabled, never matches:
    ///
    /// 1. a paragraph break ([`scan_paragraph_break`]), which wins over everything, the
    ///    end of the content included;
    /// 2. the close delimiter the state expects
    ///    ([`TokenRules::expecting_group_close`](super::TokenRules::expecting_group_close));
    /// 3. the longest group delimiter of the state's
    ///    [`PrefixTable`](super::PrefixTable) — steps 2 and 3 are
    ///    [`scan_group_delimiter`], and both come before commands, so that a delimiter
    ///    led by an escape character (`\(`) wins over reading a command;
    /// 4. a command ([`command_rule_at`], then [`scan_command`]);
    /// 5. a comment ([`scan_comment`]);
    /// 6. a specials trigger ([`scan_specials_trigger`]);
    /// 7. a forbidden character
    ///    ([`TokenRules::forbidden_chars`](super::TokenRules::forbidden_chars)), reported
    ///    as the failure below;
    /// 8. otherwise a single content character — a [`Char`](TokenKind::Char) token.
    ///
    /// Where the content ends and step 1 did not match, the terminal
    /// [`EndOfStream`](TokenKind::EndOfStream) token is produced instead, with the
    /// skipped whitespace as its pre-space.
    ///
    /// # Where `start` may point
    ///
    /// `start` is validated here. This is the one boundary where an offset reaches the
    /// scan from outside, since [`move_to`](TokenReader::move_to) and
    /// [`move_to_position`](TokenReader::move_to_position) accept caller-held tokens and
    /// positions. A `start` that is out of bounds for the content or not on a `char`
    /// boundary aborts the read with an unrecoverable implementation error, anchored at
    /// the nearest valid offset at or before it — an invalid offset is not itself an
    /// anchor — and never with a panic. The scan helpers the steps above call receive
    /// offsets derived from a validated `start`, which is what lets their own
    /// out-of-bounds precondition be a panic.
    ///
    /// # Failures
    ///
    /// `recovery_for` builds the [`TokenRecovery`] offered with a recoverable failure,
    /// from the placeholder token and the offset to resume at. That is the single step
    /// needing the *language's* token and stream-position types, which the scan cannot
    /// name; a caller that cannot describe a recovery answers `None`.
    ///
    /// Two conditions are reported with such a recovery, when `recovery_for` offers one:
    /// [`EndOfStreamAfterEscape`](super::EndOfStreamAfterEscape), where an escape
    /// character stands as the last character of the content, and [`ForbiddenChar`]
    /// (step 7). Both placeholders cover the offending character as a
    /// [`Char`](TokenKind::Char) token and resume past it.
    ///
    /// The other failures never offer a recovery: a [`Lang::scan_specials`] failure
    /// ([`SpecialsScanError`](super::SpecialsScanError)), since the hook cannot say how
    /// to carry on, and an implementation error — an invalid `start`, or a match end or
    /// error span from that hook that the [`SpecialsMatch`](super::SpecialsMatch)
    /// documentation rules out.
    pub fn scan_std_token_at<L>(
        &self,
        start: usize,
        state: &ParsingState<L>,
        recovery_for: impl FnOnce(StdToken<L>, usize) -> Option<TokenRecovery<L>>,
    ) -> TokenResult<L, StdToken<L>>
    where
        L: Lang<SourceOrigin = O>,
    {
        let s = self.content;
        let rules = state.rules();

        // The position was set through outer-layer hands (`move_to` and
        // `move_to_position` accept caller-held tokens and positions, and a token
        // recovery's resume position comes from a custom reader), so it is validated
        // at this single consumption
        // boundary ([§dd-dr:panic-policy]): an out-of-bounds or non-boundary
        // position aborts the read instead of panicking in the scanners below.
        if s.get(start..).is_none() {
            return Err(TokenError::new(
                TokenErrorKind::Custom(Box::new(ImplementationError::new(format!(
                    "token reader position {} is out of bounds or not a char \
                     boundary (content length {})",
                    start,
                    s.len()
                )))),
                // The offending position is by definition not a valid anchor, so the
                // error is reported at the nearest valid one at or before it (a
                // `SourceSpan` must be in bounds and on char boundaries).
                SourceSpan::new(self.source, Span::empty(self.nearest_valid_offset(start))),
                None,
            ));
        }

        let ws_end = skip_whitespace(s, start, rules);
        let pre_space = Span::new(start, ws_end);

        // skip_whitespace stops right before the first newline of a paragraph break, so a
        // break (which trumps everything, including end-of-stream) is detectable here.
        if let Some(span) = scan_paragraph_break(s, ws_end, rules) {
            return Ok(StdToken::paragraph_break(span, pre_space));
        }

        let pos = ws_end;
        if pos >= s.len() {
            return Ok(StdToken::end_of_stream(pre_space));
        }

        // Group delimiters come before commands so that escape-char-led delimiters like
        // `\(` win over command interpretation (as in pylatexenc, where math delimiters
        // are checked first).
        match scan_group_delimiter(s, pos, state) {
            Some(GroupDelimiterMatch::Open { span, rule }) => {
                return Ok(StdToken::group_open(rule.clone(), span, pre_space));
            }
            // The match carries the rule of a close too; the token drops it, since the
            // parser inside the group knows which close it was waiting for.
            Some(GroupDelimiterMatch::Close { span, .. }) => {
                return Ok(StdToken::group_close(span, pre_space));
            }
            None => {}
        }

        if let Some(rule) = command_rule_at(s, pos, rules) {
            return match scan_command(s, pos, rules, rule) {
                Ok(m) => {
                    Ok(StdToken::command(m.escape_char, m.span, pre_space, m.post_space))
                }
                Err(condition) => {
                    // Recovery: a `Char` placeholder covering the dangling escape byte
                    // itself (the escape character is the content's last character, so
                    // the span ends at `s.len()`), so the byte stays in the tree — it
                    // joins the pending chars run and the tolerant parse keeps the
                    // partition invariant (decided July 2026, Action 02; supersedes the
                    // empty `EndOfStream` placeholder, which dropped the byte from the
                    // AST).
                    let span = Span::new(pos, s.len());
                    let placeholder =
                        StdToken::char(condition.escape_char, span, pre_space);
                    Err(TokenError::new(
                        TokenErrorKind::EndOfStreamAfterEscape(condition),
                        SourceSpan::new(self.source, span),
                        recovery_for(placeholder, span.end()),
                    ))
                }
            };
        }

        if let Some(m) = scan_comment(s, pos, rules) {
            return Ok(StdToken::comment(m.start, m.span, pre_space, m.post_space));
        }

        match scan_specials_trigger(s, pos, state) {
            // A scan failure is unrecoverable here: the hook reported a condition and a
            // byte range, and knows nothing about this reader's tokens or positions, so
            // it cannot describe how to carry on
            // ([`SpecialsScanError`](super::SpecialsScanError)). The reader qualifies the
            // range with its own source and attaches no recovery. The same goes for a
            // hook answer the helper rejected as an implementation error.
            Err(error) => {
                return Err(TokenError::new(
                    error.kind,
                    SourceSpan::new(self.source, error.span),
                    None,
                ));
            }
            // The name is the matched text (what the
            // [`SpecialsMatch`](super::SpecialsMatch) documentation states): the token
            // records only the span, and the reader slices it on demand.
            Ok(Some(m)) => {
                return Ok(StdToken::specials(
                    m.callable_type,
                    m.spec,
                    Span::new(pos, m.end),
                    pre_space,
                ));
            }
            Ok(None) => {}
        }

        let c = s[pos..].chars().next().expect("pos < len checked above");

        if <L::Features as LangFeatures>::ForbiddenChars::PRESENT
            && rules.forbidden_chars().contains(c)
        {
            let span = Span::new(pos, pos + c.len_utf8());
            let placeholder = StdToken::char(c, span, pre_space);
            return Err(TokenError::new(
                TokenErrorKind::ForbiddenChar(ForbiddenChar::new(c)),
                SourceSpan::new(self.source, span),
                recovery_for(placeholder, span.end()),
            ));
        }

        Ok(StdToken::char(c, Span::new(pos, pos + c.len_utf8()), pre_space))
    }
}

impl<'s, O, L> TokenReader<'s, L> for StdTokenReader<'s, O>
where
    O: SourceOrigin,
    L: Lang<SourceOrigin = O>,
    L::Tokenization: Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
{
    fn peek(&mut self, state: &Arc<ParsingState<L>>) -> TokenResult<L, Token<L>> {
        self.scan_std_token_at(self.pos, state, |token, resume| {
            Some(TokenRecovery { token, resume: StdStreamPosition::at(resume) })
        })
    }

    fn move_to(&mut self, tok: &Token<L>, edge: TokenEdge) {
        self.pos = tok.edge_offset(edge);
    }

    fn move_to_position(&mut self, at: &StreamPosition<L>) {
        self.pos = at.offset();
    }

    fn token_kind<'t>(&self, tok: &'t Token<L>) -> TokenKind<'t, L>
    where
        's: 't,
    {
        self.token_kind_of_std_token(tok)
    }

    fn source_span_between(
        &self,
        tok: &Token<L>,
        a: TokenEdge,
        b: TokenEdge,
    ) -> SourceSpan<L::SourceOrigin> {
        let (a, b) = (tok.edge_offset(a), tok.edge_offset(b));
        // Reading order, whichever order the edges were named in; equal edges give the
        // empty span there.
        SourceSpan::new(self.source, a.min(b)..a.max(b))
    }

    fn position_here(&self) -> StreamPosition<L> {
        StdStreamPosition::at(self.pos)
    }

    fn position_at(&self, tok: &Token<L>, edge: TokenEdge) -> StreamPosition<L> {
        StdStreamPosition::at(tok.edge_offset(edge))
    }

    fn source_position_at(&self, at: &StreamPosition<L>) -> SourcePos<L::SourceOrigin> {
        SourcePos::new(self.source, at.offset())
    }

    fn source_span_within(
        &self,
        begin: &StreamPosition<L>,
        end: &StreamPosition<L>,
    ) -> Option<SourceSpan<L::SourceOrigin>> {
        // One source, so the only incoherent pair is an inverted one.
        (begin.offset() <= end.offset())
            .then(|| SourceSpan::new(self.source, begin.offset()..end.offset()))
    }

    fn source_span_describing(
        &self,
        begin: &StreamPosition<L>,
        end: &StreamPosition<L>,
    ) -> SourceSpan<L::SourceOrigin> {
        // This reader serves one source, so an ordered pair describes its own exact
        // range. An inverted pair is a caller bug — the same one `source_span_within`
        // answers `None` to; here the answer is the empty span at `begin`.
        match begin.offset() <= end.offset() {
            true => SourceSpan::new(self.source, begin.offset()..end.offset()),
            false => SourceSpan::new(self.source, begin.offset()..begin.offset()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::DiagnosticInfo;
    use crate::scopes::ScopeStack;
    use crate::spec::CallableSpec;
    use crate::state::StateData;
    use crate::token::{
        CommandRule, CommandRules, CommentRule, CommentRules, EndOfStreamAfterEscape,
        ForbiddenCharsRules, GroupRule, GroupRules, ParagraphRules, SpecialsMatch,
        SpecialsRules, SpecialsScanError, TokenRules, TriggerChars, WhitespaceRules,
    };
    use alloc::string::String;
    use alloc::sync::Arc;
    use alloc::vec;
    use alloc::vec::Vec;

    // Group classes used by the hardcoded latexlike-flavored test rules (the test langs
    // use the TrivialLang-style `u32` class space; a real preset would use a small enum,
    // with several rules sharing a class). Distinct per rule here so tests can look
    // rules up by class.
    const BRACES: u32 = 0;
    const BRACKETS: u32 = 1;
    const MATH_INLINE: u32 = 2;
    const MATH_DISPLAY: u32 = 3;
    const MATH_INLINE_PAREN: u32 = 4;
    const MATH_DISPLAY_BRACKET: u32 = 5;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct TestLang;
    impl Lang for TestLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = ();
        type StateExt = ();
        type Event = ();
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = ();
        type InvocationSyntax = ();
        type Driver = crate::engine::StdParseDriver;
        fn make_node_ext(
            _kind: &crate::node::NodeKind<Self>,
            _span: &crate::source::SourceSpan<Self::SourceOrigin>,
            _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
            _children: crate::node::StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    /// Hardcoded LaTeX-flavored rules; the real defaults arrive with the latexlike
    /// preset. Generic so the several test langs of this module can share it.
    // `Features = AllLangFeatures` (all test languages here declare it): the plain
    // block literals below only typecheck once the per-feature stores normalize to
    // the blocks themselves.
    fn latex_rules<L: Lang<GroupTypeId = u32, Features = crate::state::AllLangFeatures>>(
    ) -> TokenRules<L> {
        TokenRules {
            whitespace: WhitespaceRules { enabled: true, chars: " \t\n\r\u{000B}\u{000C}".into() },
            paragraphs: ParagraphRules { enabled: true },
            groups: GroupRules {
                enabled: true,
                rules: vec![
                    group(BRACES, "{", "}"),
                    group(BRACKETS, "[", "]"),
                    group(MATH_INLINE, "$", "$"),
                    group(MATH_DISPLAY, "$$", "$$"),
                    group(MATH_INLINE_PAREN, r"\(", r"\)"),
                    group(MATH_DISPLAY_BRACKET, r"\[", r"\]"),
                ],
                temporary: Vec::new(),
                expecting_close: None,
            },
            commands: CommandRules {
                enabled: true,
                rules: vec![Arc::new(CommandRule {
                    escape_char: '\\',
                    name_chars: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".into(),
                })],
            },
            comments: CommentRules {
                enabled: true,
                rules: vec![Arc::new(CommentRule { start: "%".into() })],
            },
            specials: SpecialsRules { enabled: true },
            forbidden_chars: ForbiddenCharsRules { chars: "".into() },
        }
    }

    fn group<L: Lang<GroupTypeId = u32>>(
        group_type: u32,
        open: &str,
        close: &str,
    ) -> Arc<GroupRule<L>> {
        Arc::new(GroupRule { group_type, open: open.into(), close: close.into() })
    }

    fn state(rules: TokenRules<TestLang>) -> Arc<ParsingState<TestLang>> {
        Arc::new(ParsingState::new(StateData { rules, scopes: ScopeStack::new(), mode: (), ext: () }))
    }

    /// The `latex_rules` rule of the given class (unique per rule in these tests).
    fn rule_of(group_type: u32) -> Arc<GroupRule<TestLang>> {
        latex_rules::<TestLang>()
            .groups
            .rules
            .into_iter()
            .find(|g| g.group_type == group_type)
            .expect("class present in latex_rules")
    }

    /// Rules with the given rule's close delimiter expected (as the group parser sets up
    /// when entering an ambiguously-delimited group).
    fn expecting_close(group_type: u32) -> Arc<ParsingState<TestLang>> {
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.groups.expecting_close = Some(rule_of(group_type));
        state(rules)
    }

    fn sp(start: usize, end: usize) -> Span {
        Span::new(start, end)
    }

    fn peek(
        tr: &mut StdTokenReader<'_>,
        st: &Arc<ParsingState<TestLang>>,
    ) -> StdToken<TestLang> {
        TokenReader::peek(tr, st).unwrap()
    }

    fn next(
        tr: &mut StdTokenReader<'_>,
        st: &Arc<ParsingState<TestLang>>,
    ) -> StdToken<TestLang> {
        TokenReader::next(tr, st).unwrap()
    }

    /// The reader's view of a token — the only way to read one, in the reader's own
    /// tests as in a construct parser. Generic over the language, since this module
    /// exercises several.
    fn kind_of<'s: 't, 't, L>(
        tr: &StdTokenReader<'s>,
        tok: &'t StdToken<L>,
    ) -> TokenKind<'t, L>
    where
        L: Lang<SourceOrigin = Option<String>>,
        L::Tokenization:
            Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
    {
        let reader: &dyn TokenReader<'s, L> = tr;
        reader.token_kind(tok)
    }

    fn char_token(c: char, at: usize, pre_space: Span) -> StdToken<TestLang> {
        StdToken::char(c, sp(at, at + c.len_utf8()), pre_space)
    }

    /// Put the reader at a byte offset. The scanner's own tests read from places no
    /// token walk reaches (mid-content starts, deliberately invalid offsets), and this
    /// module — the reader's own — is where positions may be built from offsets.
    fn seek<L>(tr: &mut StdTokenReader<'_>, offset: usize)
    where
        L: Lang<SourceOrigin = Option<String>>,
        L::Tokenization:
            Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
    {
        let reader: &mut dyn TokenReader<'_, L> = tr;
        reader.move_to_position(&StdStreamPosition::at(offset));
    }

    /// Where the reader stands, as a byte offset.
    fn at<L>(tr: &StdTokenReader<'_>) -> usize
    where
        L: Lang<SourceOrigin = Option<String>>,
        L::Tokenization:
            Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
    {
        let reader: &dyn TokenReader<'_, L> = tr;
        reader.source_position_at(&reader.position_here()).pos()
    }

    // --- chars ------------------------------------------------------------------------

    #[test]
    fn single_char_tokens() {
        // pylatexenc parity: one token per content character; whitespace between tokens
        // becomes the next token's pre_space.
        let source = Arc::new(Source::new("ab c"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());

        assert_eq!(next(&mut tr, &st), char_token('a', 0, Span::empty(0)));
        assert_eq!(next(&mut tr, &st), char_token('b', 1, Span::empty(1)));
        assert_eq!(next(&mut tr, &st), char_token('c', 3, sp(2, 3)));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::EndOfStream);
    }

    #[test]
    fn char_with_pre_space() {
        let pre_space = "   \t\n \t";
        let text = format!("{}Some", pre_space);
        let source = Arc::new(Source::new(&text));
        let mut tr = StdTokenReader::new(&source);
        assert_eq!(peek(&mut tr, &state(latex_rules())), char_token('S', 7, sp(0, 7)));
    }

    #[test]
    fn peek_does_not_advance() {
        let source = Arc::new(Source::new("abc"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let first = peek(&mut tr, &st);
        assert_eq!(peek(&mut tr, &st), first);
        assert_eq!(at::<TestLang>(&tr), 0);
    }

    #[test]
    fn char_multibyte() {
        let text = "héllo→";
        let source = Arc::new(Source::new(text));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('h'));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('é'));
        assert_eq!(token.span().slice(text), "é");
        assert_eq!(at::<TestLang>(&tr), 1 + 'é'.len_utf8());
    }

    // --- commands -----------------------------------------------------------------------

    #[test]
    fn command_with_post_space() {
        let text = r"\somemacro and more stuff";
        let source = Arc::new(Source::new(text));
        let mut tr = StdTokenReader::new(&source);

        // span includes the post_space (pylatexenc: pos_end past post_space).
        assert_eq!(
            peek(&mut tr, &state(latex_rules())),
            StdToken::command('\\', sp(0, 11), Span::empty(0), sp(10, 11)),
        );
    }

    #[test]
    fn command_with_pre_space() {
        let pre_space = "   \t\n \t";
        let text = format!("{}\\somemacro and more stuff", pre_space);
        let source = Arc::new(Source::new(&text));
        let mut tr = StdTokenReader::new(&source);

        assert_eq!(
            peek(&mut tr, &state(latex_rules())),
            StdToken::command('\\', sp(7, 18), sp(0, 7), sp(17, 18)),
        );
    }

    #[test]
    fn single_char_command_takes_no_post_space() {
        let source = Arc::new(Source::new(r"\& also"));
        let mut tr = StdTokenReader::new(&source);
        assert_eq!(
            peek(&mut tr, &state(latex_rules())),
            StdToken::command('\\', sp(0, 2), Span::empty(0), Span::empty(2)),
        );
    }

    #[test]
    fn accent_command_then_char() {
        let source = Arc::new(Source::new(r"\`accent"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Command { name: "`", escape_char: '\\' });
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('a'));
    }

    #[test]
    fn command_post_space_stops_before_paragraph_break() {
        // Whitespace after the command starts with the break sequence: no post_space at
        // all (pylatexenc: "put back whitespace that breaks into a new paragraph").
        let source = Arc::new(Source::new("\\macroname\n  \n "));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        assert_eq!(
            next(&mut tr, &st),
            StdToken::command('\\', sp(0, 10), Span::empty(0), Span::empty(10)),
        );
        // ... and the paragraph break follows as its own token.
        assert_eq!(
            next(&mut tr, &st),
            StdToken::paragraph_break(sp(10, 14), Span::empty(10)),
        );
    }

    #[test]
    fn command_post_space_kept_up_to_paragraph_break() {
        let source = Arc::new(Source::new("\\macroname   \n  \n "));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        assert_eq!(
            next(&mut tr, &st),
            StdToken::command('\\', sp(0, 13), Span::empty(0), sp(10, 13)),
        );
        assert_eq!(
            next(&mut tr, &st),
            StdToken::paragraph_break(sp(13, 17), Span::empty(13)),
        );
    }

    #[test]
    fn command_custom_name_chars() {
        let text = r"\zzz1234567890-haha_works! is a macro here";
        let source = Arc::new(Source::new(text));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.commands.rules = vec![Arc::new(CommandRule {
            escape_char: '\\',
            name_chars: "0123456789abcdefghijklmnopqrstuvwxyz\
                         ABCDEFGHIJKLMNOPQRSTUVWXYZ_+!-"
                .into(),
        })];
        let st = state(rules);

        let name = "zzz1234567890-haha_works!";
        assert_eq!(
            peek(&mut tr, &st),
            StdToken::command(
                '\\',
                sp(0, 1 + name.len() + 1),
                Span::empty(0),
                sp(1 + name.len(), 1 + name.len() + 1),
            ),
        );
    }

    #[test]
    fn command_records_the_fired_rules_escape_char() {
        // Two coexisting command syntaxes: each token records which rule's escape
        // character fired (parse-time lookup disambiguates by it — DESIGN_RATIONALE [§dd-dr:tokens]).
        let names = "abcdefghijklmnopqrstuvwxyz";
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.commands.rules = vec![
            Arc::new(CommandRule { escape_char: '\\', name_chars: names.into() }),
            Arc::new(CommandRule { escape_char: '@', name_chars: names.into() }),
        ];
        let st = state(rules);
        let source = Arc::new(Source::new("\\foo @bar"));
        let mut tr = StdTokenReader::new(&source);
        assert_eq!(
            next(&mut tr, &st),
            StdToken::command('\\', sp(0, 5), Span::empty(0), sp(4, 5)),
        );
        assert_eq!(
            next(&mut tr, &st),
            StdToken::command('@', sp(5, 9), Span::empty(5), Span::empty(9)),
        );
    }

    #[test]
    fn commands_disabled_escape_is_plain_content() {
        let source = Arc::new(Source::new(r"\foo"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.commands.rules = Vec::new();
        let st = state(rules);
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('\\'));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('f'));
    }

    #[test]
    fn commands_gate_off_is_the_scoped_disable() {
        // The gate variant of the test above: the command rules stay in the data (a
        // later enabled: Some(true) delta restores recognition without carrying them).
        let source = Arc::new(Source::new(r"\foo"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.commands.enabled = false;
        let st = state(rules);
        assert!(!st.rules().command_rules().is_empty());
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('\\'));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('f'));
    }

    // --- \begin is NOT special at the token level ---------------------------------------

    #[test]
    fn begin_environment_is_ordinary_tokens() {
        // \begin{equation} tokenizes as command + group open + chars (+ group close):
        // "as far as token parsing is concerned, \begin is a command just like \foobar".
        // Environment recognition is entirely a parse-time (preset) concern.
        let source = Arc::new(Source::new(r"\begin{equation}"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());

        assert_eq!(
            next(&mut tr, &st),
            // No post_space: '{' follows the name directly.
            StdToken::command('\\', sp(0, 6), Span::empty(0), Span::empty(6)),
        );
        let token = next(&mut tr, &st);
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::GroupOpen { delim: "{", rule: &rule_of(BRACES) },
        );
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('e'));
    }

    #[test]
    fn begin_prefixed_command_name_reads_fully() {
        let source = Arc::new(Source::new(r"\beginMacroWithConfusingName"));
        let mut tr = StdTokenReader::new(&source);
        let token = peek(&mut tr, &state(latex_rules()));
        match kind_of(&tr, &token) {
            TokenKind::Command { name, .. } => assert_eq!(name, "beginMacroWithConfusingName"),
            other => panic!("expected command, got {:?}", other),
        }
    }

    // --- groups -----------------------------------------------------------------------

    #[test]
    fn group_open_and_close() {
        let st = state(latex_rules());

        let source = Arc::new(Source::new("{begin group here"));
        let mut tr = StdTokenReader::new(&source);
        assert_eq!(
            peek(&mut tr, &st),
            StdToken::group_open(rule_of(BRACES), sp(0, 1), Span::empty(0)),
        );

        let source = Arc::new(Source::new("} a braced group just ended here"));
        let mut tr = StdTokenReader::new(&source);
        assert_eq!(
            peek(&mut tr, &st),
            StdToken::group_close(sp(0, 1), Span::empty(0)),
        );
    }

    #[test]
    fn group_delimiters_with_pre_space() {
        let pre_space = "   \t\n \t";
        let text = format!("{}{{begin group here", pre_space);
        let source = Arc::new(Source::new(&text));
        let mut tr = StdTokenReader::new(&source);
        assert_eq!(
            peek(&mut tr, &state(latex_rules())),
            StdToken::group_open(rule_of(BRACES), sp(7, 8), sp(0, 7)),
        );
    }

    #[test]
    fn optional_argument_brackets_are_group_tokens() {
        let source = Arc::new(Source::new("[(i)]"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let token = next(&mut tr, &st);
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::GroupOpen { delim: "[", rule: &rule_of(BRACKETS) },
        );
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('('));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('i'));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char(')'));
        let token = next(&mut tr, &st);
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::GroupClose { delim: "]" },
        );
    }

    // --- math-style ambiguous group delimiters ------------------------------------------

    #[test]
    fn ambiguous_delimiter_reads_as_open_by_default() {
        let source = Arc::new(Source::new("$x$"));
        let mut tr = StdTokenReader::new(&source);
        let token = peek(&mut tr, &state(latex_rules()));
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::GroupOpen { delim: "$", rule: &rule_of(MATH_INLINE) },
        );
    }

    #[test]
    fn expected_close_wins_over_open_interpretation() {
        let source = Arc::new(Source::new("$ and more"));
        let mut tr = StdTokenReader::new(&source);
        let token = peek(&mut tr, &expecting_close(MATH_INLINE));
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::GroupClose { delim: "$" },
        );
    }

    #[test]
    fn close_only_delimiter_reads_as_close_even_unexpected() {
        // "report closing '\)' also with incorrect parsing state -- it's not the
        // tokenizer's job to report syntax errors" (pylatexenc test suite).
        let source = Arc::new(Source::new(r"\) rest"));
        let mut tr = StdTokenReader::new(&source);
        let token = peek(&mut tr, &state(latex_rules()));
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::GroupClose { delim: r"\)" },
        );
    }

    #[test]
    fn escape_led_delimiters_win_over_command_interpretation() {
        let st = state(latex_rules());

        let source = Arc::new(Source::new(r" \(x\)"));
        let mut tr = StdTokenReader::new(&source);
        assert_eq!(
            next(&mut tr, &st),
            StdToken::group_open(rule_of(MATH_INLINE_PAREN), sp(1, 3), sp(0, 1)),
        );

        let source = Arc::new(Source::new("\n\\[ cx^2 \\]"));
        let mut tr = StdTokenReader::new(&source);
        assert_eq!(
            peek(&mut tr, &st),
            StdToken::group_open(rule_of(MATH_DISPLAY_BRACKET), sp(1, 3), sp(0, 1)),
        );
    }

    #[test]
    fn dollar_dollar_disambiguation() {
        // Port of pylatexenc's test_get_token_mathmodes_dollardollar.
        // pos:            0         10        20        30
        //                 x$\dagger$$\dagger$$$A=B\mbox{$b=a$}$$
        let text = r"x$\dagger$$\dagger$$$A=B\mbox{$b=a$}$$";
        let plain = state(latex_rules());
        let in_inline = expecting_close(MATH_INLINE);
        let in_display = expecting_close(MATH_DISPLAY);

        // The views below borrow the rules they name, so the two live in bindings.
        let inline = rule_of(MATH_INLINE);
        let display = rule_of(MATH_DISPLAY);

        #[allow(clippy::type_complexity)]
        let cases: [(usize, &Arc<ParsingState<TestLang>>, TokenKind<'_, TestLang>, usize); 8] = [
            // (pos, state, expected kind, expected end)
            (1, &plain, TokenKind::GroupOpen { delim: "$", rule: &inline }, 2),
            // expected close beats the longest ('$$') match:
            (9, &in_inline, TokenKind::GroupClose { delim: "$" }, 10),
            (10, &plain, TokenKind::GroupOpen { delim: "$", rule: &inline }, 11),
            (18, &in_inline, TokenKind::GroupClose { delim: "$" }, 19),
            // not expecting a close: longest match wins -> display '$$':
            (19, &plain, TokenKind::GroupOpen { delim: "$$", rule: &display }, 21),
            (30, &plain, TokenKind::GroupOpen { delim: "$", rule: &inline }, 31),
            (34, &in_inline, TokenKind::GroupClose { delim: "$" }, 35),
            (36, &in_display, TokenKind::GroupClose { delim: "$$" }, 38),
        ];

        for (pos, st, kind, end) in cases {
            let source = Arc::new(Source::new(text));
            let mut tr = StdTokenReader::new(&source);
            seek::<TestLang>(&mut tr, pos);
            let token = peek(&mut tr, st);
            assert_eq!(kind_of(&tr, &token), kind, "at pos {}", pos);
            assert_eq!(token.span(), sp(pos, end), "at pos {}", pos);
        }
    }

    // --- comments (whole-comment tokens) -------------------------------------------------

    #[test]
    fn comment_token_covers_content_and_post_space() {
        // "% Comment here\n  more": content sans delimiter and newline; post_space =
        // newline + indentation (syntactic whitespace, consumed by the comment).
        let source = Arc::new(Source::new("% Comment here\n  more stuff"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        assert_eq!(
            next(&mut tr, &st),
            StdToken::comment(sp(0, 1), sp(0, 17), Span::empty(0), sp(14, 17)),
        );
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('m'));
    }

    #[test]
    fn comment_with_pre_space() {
        let pre_space = "   \t\n \t";
        let text = format!("{}% Comment here\n  more stuff", pre_space);
        let source = Arc::new(Source::new(&text));
        let mut tr = StdTokenReader::new(&source);
        let token = peek(&mut tr, &state(latex_rules()));
        assert_eq!(token.pre_space(), sp(0, 7));
        assert_eq!(token.span(), sp(7, 24));
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::Comment { start_delim: "%", content: " Comment here" },
        );
        // The post-space is a reader answer, not a token field.
        let reader: &dyn TokenReader<'_, TestLang> = &tr;
        assert_eq!(
            reader.source_span_between(&token, TokenEdge::End, TokenEdge::EndPastPostSpace),
            SourceSpan::new(&source, sp(21, 24)),
        );
    }

    #[test]
    fn comment_before_paragraph_break_takes_no_post_space() {
        // "a% c\n\nb": the comment's terminating newline belongs to a \n\s*\n sequence,
        // so the comment takes no post-space and the paragraph break survives as its own
        // token (TeX-wise: the blank line still yields \par).
        let source = Arc::new(Source::new("a% c\n\nb"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('a'));
        assert_eq!(
            next(&mut tr, &st),
            StdToken::comment(sp(1, 2), sp(1, 4), Span::empty(1), Span::empty(4)),
        );
        assert_eq!(
            next(&mut tr, &st),
            StdToken::paragraph_break(sp(4, 6), Span::empty(4)),
        );
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('b'));
    }

    #[test]
    fn comment_at_end_of_input_without_newline() {
        let source = Arc::new(Source::new("x% trailing"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('x'));
        assert_eq!(
            next(&mut tr, &st),
            StdToken::comment(sp(1, 2), sp(1, 11), Span::empty(1), Span::empty(11)),
        );
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::EndOfStream);
    }

    #[test]
    fn comment_crlf_carriage_return_is_ordinary_content() {
        // Deliberate (July 2026, Action-02 follow-up): '\n' is the sole line
        // terminator, and the tokenizer gives '\r' no special treatment whatsoever —
        // input is expected text-mode-normalized by the embedder (the no_std core
        // never reads files). On CRLF input the '\r' therefore stays inside the
        // comment content, as in pylatexenc.
        let source = Arc::new(Source::new("% note\r\n  more"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        assert_eq!(
            next(&mut tr, &st),
            StdToken::comment(sp(0, 1), sp(0, 10), Span::empty(0), sp(7, 10)),
        );
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('m'));
    }

    #[test]
    fn comment_alternative_start_string_longest_wins() {
        let text = "%!!COMMENT!! Comment here\nmore";
        let source = Arc::new(Source::new(text));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.comments.rules = vec![
            Arc::new(CommentRule { start: "%".into() }),
            Arc::new(CommentRule { start: "%!!COMMENT!!".into() }),
        ];
        let st = state(rules);
        assert_eq!(
            peek(&mut tr, &st),
            StdToken::comment(sp(0, 12), sp(0, 26), Span::empty(0), sp(25, 26)),
        );
    }

    #[test]
    fn comments_disabled_percent_is_plain_content() {
        let source = Arc::new(Source::new("a %b"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.comments.rules = Vec::new();
        let st = state(rules);
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('a'));
        assert_eq!(next(&mut tr, &st), char_token('%', 2, sp(1, 2)));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('b'));
    }

    #[test]
    fn comments_gate_off_is_the_scoped_disable() {
        let source = Arc::new(Source::new("a %b"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.comments.enabled = false;
        let st = state(rules);
        assert!(!st.rules().comment_rules().is_empty());
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('a'));
        assert_eq!(next(&mut tr, &st), char_token('%', 2, sp(1, 2)));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('b'));
    }

    // --- paragraph breaks ---------------------------------------------------------------

    #[test]
    fn paragraph_break_token() {
        // "Abc    \n\n  z": break spans first..last newline; leading run is pre_space,
        // whitespace after the last newline is left for the next token.
        let source = Arc::new(Source::new("Abc    \n\n  z"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        seek::<TestLang>(&mut tr, 3);

        assert_eq!(
            next(&mut tr, &st),
            StdToken::paragraph_break(sp(7, 9), sp(3, 7)),
        );
        assert_eq!(next(&mut tr, &st), char_token('z', 11, sp(9, 11)));
    }

    #[test]
    fn paragraph_break_with_inner_whitespace() {
        let source = Arc::new(Source::new("Abc  \t \n   \t\nz"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        seek::<TestLang>(&mut tr, 3);
        assert_eq!(
            next(&mut tr, &st),
            StdToken::paragraph_break(sp(7, 13), sp(3, 7)),
        );
    }

    #[test]
    fn paragraph_break_in_trailing_whitespace_still_emitted() {
        let source = Arc::new(Source::new("x  \n\n  "));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('x'));
        assert_eq!(
            next(&mut tr, &st),
            StdToken::paragraph_break(sp(3, 5), sp(1, 3)),
        );
        // The whitespace after the break's last newline is the end-of-stream token's
        // pre_space — nothing is lost.
        assert_eq!(
            next(&mut tr, &st),
            StdToken::end_of_stream(sp(5, 7)),
        );
    }

    #[test]
    fn paragraph_breaks_disabled() {
        let source = Arc::new(Source::new("Abc\n\nNew"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.paragraphs.enabled = false;
        let st = state(rules);
        seek::<TestLang>(&mut tr, 2);
        assert_eq!(next(&mut tr, &st), char_token('c', 2, Span::empty(2)));
        // The double newline is ordinary consumable whitespace now.
        assert_eq!(next(&mut tr, &st), char_token('N', 5, sp(3, 5)));
    }

    // --- specials (via the Lang scan hook) ------------------------------------------------

    #[derive(Debug)]
    struct StubSpec;
    impl crate::serialize::SerializableObject<SpecialsLang> for StubSpec {}
    impl CallableSpec<SpecialsLang> for StubSpec {}

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct SpecialsLang;
    impl Lang for SpecialsLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = ();
        type StateExt = ();
        type Event = ();
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = ();
        type InvocationSyntax = ();
        type Driver = crate::engine::StdParseDriver;

        fn specials_trigger_chars(_data: &StateData<Self>) -> TriggerChars {
            TriggerChars::Only("~&-".into())
        }

        fn scan_specials(
            _state: &ParsingState<Self>,
            content: &str,
            pos: usize,
        ) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
            // Longest-first over a hardcoded trigger list — a stand-in for the preset
            // dispatching to its libraries (Phase 4+).
            for trigger in ["---", "~~", "~", "&"] {
                if content[pos..].starts_with(trigger) {
                    return Ok(Some(SpecialsMatch {
                        end: pos + trigger.len(),
                        callable_type: 7,
                        spec: Arc::new(StubSpec),
                    }));
                }
            }
            Ok(None)
        }
        fn make_node_ext(
            _kind: &crate::node::NodeKind<Self>,
            _span: &crate::source::SourceSpan<Self::SourceOrigin>,
            _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
            _children: crate::node::StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    fn specials_state(rules: TokenRules<SpecialsLang>) -> Arc<ParsingState<SpecialsLang>> {
        Arc::new(ParsingState::new(StateData { rules, scopes: ScopeStack::new(), mode: (), ext: () }))
    }

    #[test]
    fn specials_recognized_with_spec_attached() {
        let source = Arc::new(Source::new("a&b"));
        let mut tr = StdTokenReader::new(&source);
        let st = specials_state(latex_rules());

        let token = TokenReader::next(&mut tr, &st).unwrap();
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('a'));
        let token = TokenReader::next(&mut tr, &st).unwrap();
        match kind_of(&tr, &token) {
            TokenKind::Specials { callable_type, name, spec } => {
                assert_eq!(callable_type, 7);
                assert_eq!(name, "&");
                assert_eq!(format!("{:?}", spec), "StubSpec");
            }
            other => panic!("expected specials, got {:?}", other),
        }
        assert_eq!(token.span(), sp(1, 2));
        let token = TokenReader::next(&mut tr, &st).unwrap();
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('b'));
    }

    #[test]
    fn specials_longest_match_is_the_scanners_business() {
        let source = Arc::new(Source::new("---x"));
        let mut tr = StdTokenReader::new(&source);
        let st = specials_state(latex_rules());
        let token = TokenReader::peek(&mut tr, &st).unwrap();
        match kind_of(&tr, &token) {
            TokenKind::Specials { name, .. } => assert_eq!(name, "---"),
            other => panic!("expected specials, got {:?}", other),
        }
        assert_eq!(token.span(), sp(0, 3));
    }

    #[test]
    fn specials_scan_miss_falls_through_to_char() {
        // '-' is a trigger char, but a lone '-' matches no trigger: plain content.
        let source = Arc::new(Source::new("-x"));
        let mut tr = StdTokenReader::new(&source);
        let st = specials_state(latex_rules());
        let token = TokenReader::next(&mut tr, &st).unwrap();
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('-'));
    }

    // --- outer-layer contract violations are reported, never panicking or hanging
    // --- ([§dd-dr:panic-policy]) ----------------------------------------------------------

    /// A lang whose scan hook violates the match-end contract: a zero-width match
    /// (`end == pos`) that would hang the dispatch loop if the reader emitted it.
    #[derive(Debug, Clone, Copy)]
    struct BadEndLang;
    impl Lang for BadEndLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = ();
        type StateExt = ();
        type Event = ();
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = ();
        type InvocationSyntax = ();
        type Driver = crate::engine::StdParseDriver;
        fn specials_trigger_chars(_data: &StateData<Self>) -> TriggerChars {
            TriggerChars::Only("~".into())
        }
        fn scan_specials(
            _state: &ParsingState<Self>,
            _content: &str,
            pos: usize,
        ) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
            Ok(Some(SpecialsMatch {
                end: pos, // contract violation: a match must advance
                callable_type: 7,
                spec: Arc::new(BadEndStubSpec),
            }))
        }
        fn make_node_ext(
            _kind: &crate::node::NodeKind<Self>,
            _span: &crate::source::SourceSpan<Self::SourceOrigin>,
            _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
            _children: crate::node::StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    #[derive(Debug)]
    struct BadEndStubSpec;
    impl crate::serialize::SerializableObject<BadEndLang> for BadEndStubSpec {}
    impl CallableSpec<BadEndLang> for BadEndStubSpec {}

    /// A lang whose scan hook always fails, with a span chosen by the trigger:
    /// `!` reports a well-formed span, `?` a span past the end of the content, and `~`
    /// a span cutting the two-byte character the test content starts with.
    #[derive(Debug, Clone, Copy)]
    struct ScanErrorLang;
    impl Lang for ScanErrorLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = ();
        type StateExt = ();
        type Event = ();
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = ();
        type InvocationSyntax = ();
        type Driver = crate::engine::StdParseDriver;
        fn specials_trigger_chars(_data: &StateData<Self>) -> TriggerChars {
            TriggerChars::Only("!?~".into())
        }
        fn scan_specials(
            _state: &ParsingState<Self>,
            content: &str,
            pos: usize,
        ) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
            let span = match content[pos..].chars().next() {
                Some('!') => Span::new(pos, pos + 1),
                Some('?') => Span::new(0, 99), // out of the content's bounds
                _ => Span::new(1, 2),          // cuts the leading two-byte character
            };
            Err(SpecialsScanError {
                kind: TokenErrorKind::Custom(Box::new(ImplementationError::new(
                    String::from("the scan declined loudly"),
                ))),
                span,
            })
        }
        fn make_node_ext(
            _kind: &crate::node::NodeKind<Self>,
            _span: &crate::source::SourceSpan<Self::SourceOrigin>,
            _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
            _children: crate::node::StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    fn scan_error_state() -> Arc<ParsingState<ScanErrorLang>> {
        let rules: TokenRules<ScanErrorLang> = latex_rules();
        Arc::new(ParsingState::new(StateData {
            rules,
            scopes: ScopeStack::new(),
            mode: (),
            ext: (),
        }))
    }

    #[test]
    fn a_lifted_specials_scan_error_carries_no_recovery() {
        let source = Arc::new(Source::new("!x"));
        let mut tr = StdTokenReader::new(&source);
        let err = TokenReader::peek(&mut tr, &scan_error_state()).unwrap_err();

        // The reader qualifies the hook's range with its own source, and the failure is
        // unrecoverable: the hook cannot describe how to carry on.
        assert_eq!(err.span(), &SourceSpan::new(&source, sp(0, 1)));
        assert!(err.into_recovery().is_none());
    }

    #[test]
    fn a_specials_scan_error_at_an_invalid_span_is_reported_not_panicked() {
        // The hook is outer-layer code: a span out of bounds or cutting a character
        // must not reach `SourceSpan::new`'s assert ([§dd-dr:panic-policy]).
        //                                    'é' occupies bytes 0..2, so 1 cuts it
        for (content, at, trigger) in [("?x", 0, "out of bounds"), ("\u{e9}~", 2, "mid-character")]
        {
            let source = Arc::new(Source::new(content));
            let mut tr = StdTokenReader::new(&source);
            let st = scan_error_state();
            seek::<ScanErrorLang>(&mut tr, at);

            let err = TokenReader::peek(&mut tr, &st).unwrap_err();
            match err.kind() {
                TokenErrorKind::Custom(data) => {
                    assert_eq!(
                        data.identifier(),
                        crate::constructs::ImplementationError::IDENTIFIER,
                        "{trigger}"
                    );
                    assert!(
                        data.to_string().contains("Lang::scan_specials"),
                        "{trigger}: {}",
                        data
                    );
                }
                other => panic!("{trigger}: expected a Custom error, got {:?}", other),
            }
            // Anchored at a valid offset, and unrecoverable under either policy.
            assert!(err.span().is_empty());
            assert!(err.into_recovery().is_none());
        }
    }

    #[test]
    fn scan_specials_invalid_match_end_is_an_unrecoverable_implementation_error() {
        let source = Arc::new(Source::new("~x"));
        let mut tr = StdTokenReader::new(&source);
        let rules: TokenRules<BadEndLang> = latex_rules();
        let st = Arc::new(ParsingState::new(StateData {
            rules,
            scopes: ScopeStack::new(),
            mode: (),
            ext: (),
        }));
        let err = TokenReader::peek(&mut tr, &st).unwrap_err();
        match err.kind() {
            TokenErrorKind::Custom(data) => assert_eq!(
                data.identifier(),
                crate::constructs::ImplementationError::IDENTIFIER
            ),
            other => panic!("expected a Custom implementation error, got {:?}", other),
        }
        // No recovery: an implementation bug aborts even under tolerant recovery.
        assert!(err.into_recovery().is_none());
    }

    #[test]
    fn invalid_reader_position_is_an_unrecoverable_implementation_error_at_peek() {
        let st = state(latex_rules());

        // Out of bounds (a resume position comes from outer-layer hands, so the
        // violation is reported at the next read, not panicked).
        let source = Arc::new(Source::new("ab"));
        let mut tr = StdTokenReader::new(&source);
        seek::<TestLang>(&mut tr, 5);
        let err = TokenReader::peek(&mut tr, &st).unwrap_err();
        assert!(matches!(err.kind(), TokenErrorKind::Custom(data)
            if data.identifier() == crate::constructs::ImplementationError::IDENTIFIER));
        assert!(err.into_recovery().is_none());

        // Not a char boundary.
        let source = Arc::new(Source::new("é"));
        let mut tr = StdTokenReader::new(&source);
        seek::<TestLang>(&mut tr, 1);
        let err = TokenReader::peek(&mut tr, &st).unwrap_err();
        assert!(matches!(err.kind(), TokenErrorKind::Custom(data)
            if data.identifier() == crate::constructs::ImplementationError::IDENTIFIER));
    }

    #[test]
    fn specials_gate_off_freezes_the_empty_filter() {
        // The gate is baked at freeze: the state stores the empty TriggerChars, so the
        // scan hook is unreachable and triggers read as plain content — this is what
        // makes "no specials here" delta-expressible (DESIGN_RATIONALE [§dd-dr:tokens], ex-[§dd-dr:open-questions]).
        let source = Arc::new(Source::new("a&b"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<SpecialsLang> = latex_rules();
        rules.specials.enabled = false;
        let st = specials_state(rules);
        assert_eq!(
            st.trigger_chars().expect("all-present test language"),
            &TriggerChars::default()
        );
        let token = TokenReader::next(&mut tr, &st).unwrap();
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('a'));
        let token = TokenReader::next(&mut tr, &st).unwrap();
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('&'));
        let token = TokenReader::next(&mut tr, &st).unwrap();
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('b'));
    }

    #[test]
    fn scan_hook_not_consulted_outside_trigger_chars() {
        #[derive(Debug, Clone, Copy)]
        struct PanickyLang;
        impl Lang for PanickyLang {
            type Features = crate::state::AllLangFeatures;
            type GroupTypeId = u32;
            type CallableTypeId = u32;
            type ModeId = ();
            type StateExt = ();
            type Event = ();
            type SessionExt = ();
            type SourceOrigin = Option<String>;
            type Tokenization = crate::token::StdTokenization;
            type NodeExts = ();
            type InvocationSyntax = ();
            type Driver = crate::engine::StdParseDriver;
            fn specials_trigger_chars(_data: &StateData<Self>) -> TriggerChars {
                TriggerChars::Only("~".into())
            }
            fn scan_specials(
                _state: &ParsingState<Self>,
                _content: &str,
                _pos: usize,
            ) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
                panic!("scan_specials consulted for a non-trigger character");
            }
            fn make_node_ext(
                _kind: &crate::node::NodeKind<Self>,
                _span: &crate::source::SourceSpan<Self::SourceOrigin>,
                _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
                _children: crate::node::StagedChildren<'_, Self>,
            ) -> Result<(), crate::node::NodeBuildError> {
                Ok(())
            }
        }
        let st: Arc<ParsingState<PanickyLang>> = Arc::new(ParsingState::new(StateData {
            rules: latex_rules(),
            scopes: ScopeStack::new(),
            mode: (),
            ext: (),
        }));
        let source = Arc::new(Source::new("x"));
        let mut tr = StdTokenReader::new(&source);
        let token = TokenReader::next(&mut tr, &st).unwrap();
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('x'));
    }

    #[test]
    fn the_content_start_edge_lies_past_a_kinds_leading_marker() {
        //                                    0....5....10...15
        let source = Arc::new(Source::new("%% note\n\\vec  x"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        // A comment: `ContentStart` is right after the start delimiter, so the
        // delimiter, the text and the post-space are three plain reader answers.
        let comment = reader.next(&st).unwrap();
        assert_eq!(
            reader.source_span_between(&comment, TokenEdge::Start, TokenEdge::ContentStart),
            SourceSpan::new(&source, sp(0, 1))
        );
        assert_eq!(
            reader
                .source_span_between(&comment, TokenEdge::ContentStart, TokenEdge::End)
                .content(),
            "% note"
        );
        assert_eq!(
            reader.source_span_between(&comment, TokenEdge::End, TokenEdge::EndPastPostSpace),
            SourceSpan::new(&source, sp(7, 8))
        );

        // A command: `ContentStart` is right after the escape character, so the name is
        // `ContentStart..End`.
        let command = reader.next(&st).unwrap();
        assert_eq!(
            reader
                .source_span_between(&command, TokenEdge::Start, TokenEdge::ContentStart)
                .content(),
            "\\"
        );
        assert_eq!(
            reader
                .source_span_between(&command, TokenEdge::ContentStart, TokenEdge::End)
                .content(),
            "vec"
        );

        // A kind with no leading marker: `ContentStart` is its `Start`.
        let plain = reader.next(&st).unwrap();
        assert_eq!(
            reader.position_at(&plain, TokenEdge::ContentStart),
            reader.position_at(&plain, TokenEdge::Start)
        );
    }

    #[test]
    fn a_multi_byte_escape_character_moves_content_start_by_its_own_width() {
        // `§` is two bytes: the command's name starts two bytes past its start.
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.commands.rules = vec![Arc::new(CommandRule {
            escape_char: '§',
            name_chars: "abcdefghijklmnopqrstuvwxyz".into(),
        })];
        let source = Arc::new(Source::new("§vec x"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(rules);
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let command = reader.next(&st).unwrap();
        assert_eq!(
            reader.source_span_between(&command, TokenEdge::Start, TokenEdge::ContentStart),
            SourceSpan::new(&source, sp(0, '§'.len_utf8()))
        );
        assert_eq!(
            reader
                .source_span_between(&command, TokenEdge::ContentStart, TokenEdge::End)
                .content(),
            "vec"
        );
    }

    #[test]
    fn the_five_edges_are_in_reading_order_for_every_kind() {
        // `StartBeforePreSpace ≤ Start ≤ ContentStart ≤ End ≤ EndPastPostSpace`, with
        // equality where a kind has no pre-space, no leading marker, or no post-space.
        let source = Arc::new(Source::new("a {%c\n} \\vec  b\n\nz"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;
        loop {
            let token = reader.next(&st).unwrap();
            // Measured from the earliest edge, so each span's end *is* the edge's
            // own offset.
            let offsets: Vec<usize> = [
                TokenEdge::StartBeforePreSpace,
                TokenEdge::Start,
                TokenEdge::ContentStart,
                TokenEdge::End,
                TokenEdge::EndPastPostSpace,
            ]
            .into_iter()
            .map(|edge| {
                reader
                    .source_span_between(&token, TokenEdge::StartBeforePreSpace, edge)
                    .range()
                    .end
            })
            .collect();
            let kind = reader.token_kind(&token);
            assert!(
                offsets.windows(2).all(|w| w[0] <= w[1]),
                "{kind:?} edges out of order: {offsets:?}"
            );
            if matches!(kind, TokenKind::EndOfStream) {
                break;
            }
        }
    }

    // --- the token view ---------------------------------------------------------------

    #[test]
    fn the_view_reports_what_each_token_kind_is() {
        //                                    0....5....10...15...20
        let source = Arc::new(Source::new("a{\\vec  }% note\nb"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let token = reader.next(&st).unwrap();
        assert_eq!(reader.token_kind(&token), TokenKind::Char('a'));

        let token = reader.next(&st).unwrap();
        match reader.token_kind(&token) {
            TokenKind::GroupOpen { delim, rule } => {
                assert_eq!(delim, "{");
                assert_eq!(rule.group_type, BRACES);
            }
            other => panic!("expected a group open, got {other:?}"),
        }

        let token = reader.next(&st).unwrap();
        assert_eq!(
            reader.token_kind(&token),
            TokenKind::Command { name: "vec", escape_char: '\\' }
        );

        let token = reader.next(&st).unwrap();
        assert_eq!(reader.token_kind(&token), TokenKind::GroupClose { delim: "}" });

        // The comment's two texts, as this reader resolves them: `%` then ` note`,
        // the newline being post-space.
        let token = reader.next(&st).unwrap();
        assert_eq!(
            reader.token_kind(&token),
            TokenKind::Comment { start_delim: "%", content: " note" }
        );
        let body = reader.source_span_between(&token, TokenEdge::Start, TokenEdge::End);
        assert_eq!(body.content(), "% note");

        let token = reader.next(&st).unwrap();
        assert_eq!(reader.token_kind(&token), TokenKind::Char('b'));

        let token = reader.next(&st).unwrap();
        assert_eq!(reader.token_kind(&token), TokenKind::EndOfStream);
    }

    #[test]
    fn the_view_of_a_paragraph_break_carries_no_data() {
        let source = Arc::new(Source::new("a\n\nb"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;
        let _ = reader.next(&st).unwrap();
        let token = reader.next(&st).unwrap();
        assert_eq!(reader.token_kind(&token), TokenKind::ParagraphBreak);
        assert_eq!(reader.token_kind(&token).as_str(), "ParagraphBreak");
    }

    #[test]
    fn the_view_of_a_specials_token_carries_its_resolution() {
        let source = Arc::new(Source::new("a&b"));
        let mut tr = StdTokenReader::new(&source);
        let st = specials_state(latex_rules());
        let reader: &mut dyn TokenReader<'_, SpecialsLang> = &mut tr;

        let _ = reader.next(&st).unwrap();
        let token = reader.next(&st).unwrap();
        match reader.token_kind(&token) {
            TokenKind::Specials { callable_type, name, spec } => {
                assert_eq!(callable_type, 7);
                assert_eq!(name, "&");
                assert_eq!(format!("{:?}", spec), "StubSpec");
            }
            other => panic!("expected specials, got {other:?}"),
        }
        // Two views of the same token are equal (the spec compares by `Arc` identity).
        assert_eq!(reader.token_kind(&token), reader.token_kind(&token));
    }

    #[test]
    fn a_view_is_copy_and_survives_further_reading() {
        let source = Arc::new(Source::new("\\vec  x"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let token = reader.next(&st).unwrap();
        let kind = reader.token_kind(&token);
        // The view borrows the token and the content, never the reader: reading on and
        // moving the stream leaves it usable, and it copies rather than moves.
        let _next = reader.next(&st).unwrap();
        reader.move_to(&token, TokenEdge::Start);
        let copy = kind;
        assert_eq!(kind, copy);
        assert_eq!(kind.to_string(), "Command(\\vec)");
    }

    // --- positions, edges, spans -----------------------------------------------------

    #[test]
    fn the_four_edges_of_a_token_delimit_its_pre_space_body_and_post_space() {
        //                                    0....5....1
        let source = Arc::new(Source::new("a \\vec  b"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let _ = reader.next(&st).unwrap(); // the leading `a`
        let token = reader.peek(&st).unwrap();
        // ` \vec  `: pre-space 1..2, the command 2..6, its post-space 6..8.
        assert_eq!(
            reader.source_span_between(
                &token,
                TokenEdge::StartBeforePreSpace,
                TokenEdge::Start
            ),
            SourceSpan::new(&source, sp(1, 2))
        );
        assert_eq!(
            reader.source_span_between(&token, TokenEdge::Start, TokenEdge::End),
            SourceSpan::new(&source, sp(2, 6))
        );
        assert_eq!(
            reader.source_span_between(&token, TokenEdge::End, TokenEdge::EndPastPostSpace),
            SourceSpan::new(&source, sp(6, 8))
        );
        // `source_span_of` is Start..EndPastPostSpace — the token's own span.
        assert_eq!(reader.source_span_of(&token), SourceSpan::new(&source, sp(2, 8)));
        assert_eq!(reader.source_span_of(&token).span(), token.span());
    }

    #[test]
    fn source_span_between_ignores_edge_order_and_empties_on_equal_edges() {
        let source = Arc::new(Source::new(" x"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let token = reader.peek(&st).unwrap();
        let forward =
            reader.source_span_between(&token, TokenEdge::StartBeforePreSpace, TokenEdge::End);
        let backward =
            reader.source_span_between(&token, TokenEdge::End, TokenEdge::StartBeforePreSpace);
        assert_eq!(forward, backward);
        assert_eq!(forward, SourceSpan::new(&source, sp(0, 2)));

        let empty = reader.source_span_between(&token, TokenEdge::Start, TokenEdge::Start);
        assert!(empty.is_empty());
        assert_eq!(empty, SourceSpan::new(&source, sp(1, 1)));
    }

    #[test]
    fn a_peeked_tokens_first_edge_is_the_position_the_peek_happened_at() {
        // Contract clause 2: `move_to(&tok, StartBeforePreSpace)` returns the
        // stream to where the peek happened.
        let source = Arc::new(Source::new("a  b"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let first = reader.next(&st).unwrap();
        let before = reader.position_here();
        let token = reader.peek(&st).unwrap();
        assert_eq!(reader.position_at(&token, TokenEdge::StartBeforePreSpace), before);

        reader.move_to(&token, TokenEdge::EndPastPostSpace);
        assert_ne!(reader.position_here(), before);
        reader.move_to(&token, TokenEdge::StartBeforePreSpace);
        assert_eq!(reader.position_here(), before);
        assert_eq!(reader.peek(&st).unwrap(), token);

        // And back to the very beginning, through the first token.
        reader.move_to(&first, TokenEdge::StartBeforePreSpace);
        assert_eq!(reader.position_here(), reader.position_at(&first, TokenEdge::Start));
    }

    #[test]
    fn positions_answer_text_locations_and_delimit_spans() {
        let source = Arc::new(Source::new("ab cd"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let begin = reader.position_here();
        assert_eq!(reader.source_position_at(&begin), SourcePos::new(&source, 0));

        let _ = reader.next(&st).unwrap();
        let _ = reader.next(&st).unwrap();
        let end = reader.position_here();

        assert_eq!(
            reader.source_span_within(&begin, &end),
            Some(SourceSpan::new(&source, sp(0, 2)))
        );
        // An inverted pair does not delimit a range: the caller lifts `None` to an
        // implementation error.
        assert_eq!(reader.source_span_within(&end, &begin), None);
        // Equal positions delimit the empty span there.
        assert_eq!(
            reader.source_span_within(&end, &end),
            Some(SourceSpan::new(&source, sp(2, 2)))
        );
    }

    #[test]
    fn a_described_span_is_the_exact_range_and_never_absent() {
        let source = Arc::new(Source::new("ab cd"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let begin = reader.position_here();
        let _ = reader.next(&st).unwrap();
        let _ = reader.next(&st).unwrap();
        let end = reader.position_here();

        // This reader serves one source, so an ordered pair describes its own range —
        // the same answer `source_span_within` gives.
        assert_eq!(
            reader.source_span_describing(&begin, &end),
            SourceSpan::new(&source, sp(0, 2))
        );
        // Equal positions: the empty span there.
        assert_eq!(
            reader.source_span_describing(&end, &end),
            SourceSpan::new(&source, sp(2, 2))
        );
        // An inverted pair is a caller bug, and this method still answers: the empty
        // span at `begin`.
        assert_eq!(
            reader.source_span_describing(&end, &begin),
            SourceSpan::new(&source, sp(2, 2))
        );
    }

    #[test]
    fn a_position_returns_the_stream_to_where_it_was_taken() {
        let source = Arc::new(Source::new("a{b}c"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let _ = reader.next(&st).unwrap();
        let mark = reader.position_here();
        let open = reader.next(&st).unwrap();
        assert!(matches!(reader.token_kind(&open), TokenKind::GroupOpen { .. }));

        reader.move_to_position(&mark);
        assert_eq!(reader.position_here(), mark);
        assert_eq!(reader.peek(&st).unwrap(), open);
    }

    // --- errors and recovery -------------------------------------------------------------

    #[test]
    fn forbidden_char_error_with_recovery() {
        let source = Arc::new(Source::new("% forbidden here"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.comments.rules = Vec::new();
        rules.forbidden_chars.chars = "%$".into();
        let st = state(rules);

        let err = TokenReader::peek(&mut tr, &st).unwrap_err();
        assert!(matches!(
            err.kind(),
            TokenErrorKind::ForbiddenChar(ForbiddenChar { ch: '%' })
        ));
        assert_eq!(err.span(), &SourceSpan::new(&source, sp(0, 1)));

        // Tolerant continuation: use the recovery token, resume past it.
        let recovery = err.into_recovery().unwrap();
        assert_eq!(recovery.token, char_token('%', 0, Span::empty(0)));
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;
        assert_eq!(recovery.resume, StdStreamPosition::at(1));
        reader.move_to_position(&recovery.resume);
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('f'));
    }

    #[test]
    fn end_of_stream_after_escape_error_with_recovery() {
        let source = Arc::new(Source::new(r"a \"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());

        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('a'));

        let err = TokenReader::peek(&mut tr, &st).unwrap_err();
        assert!(matches!(
            err.kind(),
            TokenErrorKind::EndOfStreamAfterEscape(EndOfStreamAfterEscape {
                escape_char: '\\',
            })
        ));
        assert_eq!(err.span(), &SourceSpan::new(&source, sp(2, 3)));

        // Recovery: a Char placeholder covering the dangling escape byte itself, so the
        // byte stays in the tree (the tolerant parse keeps span tiling).
        let recovery = err.into_recovery().unwrap();
        assert_eq!(
            recovery.token,
            StdToken::char('\\', sp(2, 3), sp(1, 2)),
        );
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;
        assert_eq!(recovery.resume, StdStreamPosition::at(3));
        reader.move_to_position(&recovery.resume);
        let token = peek(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::EndOfStream);
    }

    // --- end of stream --------------------------------------------------------------------

    #[test]
    fn end_of_stream_token_is_terminal_and_idempotent() {
        let st = state(latex_rules());

        let source = Arc::new(Source::new(""));
        let mut tr = StdTokenReader::new(&source);
        assert_eq!(
            peek(&mut tr, &st),
            StdToken::end_of_stream(Span::empty(0)),
        );

        // Trailing whitespace (no paragraph break) is the end-of-stream token's
        // pre_space — reported, so it can land in the node tree.
        let source = Arc::new(Source::new("x   "));
        let mut tr = StdTokenReader::new(&source);
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('x'));
        let eos = StdToken::end_of_stream(sp(1, 4));
        assert_eq!(next(&mut tr, &st), eos);
        assert_eq!(at::<TestLang>(&tr), 4);
        assert!(tr.is_at_end());
        // Terminal: further reads yield end-of-stream again (now with empty pre_space,
        // the earlier trailing whitespace having been consumed).
        assert_eq!(
            next(&mut tr, &st),
            StdToken::end_of_stream(Span::empty(4)),
        );
    }

    // --- whitespace handling disabled ------------------------------------------------------

    #[test]
    fn whitespace_disabled_gives_character_level_content() {
        let source = Arc::new(Source::new("a b{"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.whitespace.enabled = false;
        let st = state(rules);
        assert_eq!(next(&mut tr, &st), char_token('a', 0, Span::empty(0)));
        assert_eq!(next(&mut tr, &st), char_token(' ', 1, Span::empty(1)));
        assert_eq!(next(&mut tr, &st), char_token('b', 2, Span::empty(2)));
        let token = next(&mut tr, &st);
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::GroupOpen { delim: "{", rule: &rule_of(BRACES) },
        );
    }

    // --- the groups gate (baked into the prefix table) -------------------------------------

    #[test]
    fn groups_gate_off_delimiters_are_plain_content() {
        let source = Arc::new(Source::new("{a}"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.groups.enabled = false;
        let st = state(rules);
        assert!(!st.rules().group_rules().is_empty());
        // Baked-in empty table (present feature, disabled at runtime: `Some`).
        assert!(st
            .prefix_table()
            .expect("all-present test language")
            .match_at("{a}")
            .is_none());
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('{'));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('a'));
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('}'));
    }

    #[test]
    fn groups_gate_off_does_not_gate_the_expected_close() {
        // The decided interaction (DESIGN_RATIONALE [§dd-dr:tokens]): expecting_group_close is
        // positional data, not a feature — a group interior that disables groups
        // entirely still finds its own close, so the entered group always terminates.
        let source = Arc::new(Source::new("a{$"));
        let mut tr = StdTokenReader::new(&source);
        let mut rules: TokenRules<TestLang> = latex_rules();
        rules.groups.enabled = false;
        rules.groups.expecting_close = Some(rule_of(MATH_INLINE));
        let st = state(rules);
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('a'));
        // The table is off: `{` is plain content …
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::Char('{'));
        // … but the expected `$` close still tokenizes as GroupClose.
        let token = next(&mut tr, &st);
        assert_eq!(kind_of(&tr, &token), TokenKind::GroupClose { delim: "$" });
    }

    // --- movement -----------------------------------------------------------------------

    #[test]
    fn move_to_lands_at_each_of_the_five_edges() {
        let text = "  \\vec b";
        let source = Arc::new(Source::new(text));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let token = reader.peek(&st).unwrap();
        assert_eq!(
            reader.token_kind(&token),
            TokenKind::Command { name: "vec", escape_char: '\\' }
        );
        assert_eq!(token.span(), sp(2, 7)); // includes post_space
        assert_eq!(token.pre_space(), sp(0, 2));

        // Each edge, checked through the text location the reader answers for the
        // position it lands on.
        let at = |reader: &dyn TokenReader<'_, TestLang>| {
            reader.source_position_at(&reader.position_here())
        };
        for (edge, offset) in [
            (TokenEdge::EndPastPostSpace, 7), // past post-space
            (TokenEdge::End, 6),              // before it (the `\verb`-style read)
            (TokenEdge::ContentStart, 3),     // past the escape character
            (TokenEdge::Start, 2),            // at the token, to read it again
            (TokenEdge::StartBeforePreSpace, 0), // giving back the pre-space too
        ] {
            // Contract clause 7, first half: moving to an edge sets the position to
            // that edge's.
            reader.move_to(&token, edge);
            assert_eq!(at(reader), SourcePos::new(&source, offset), "{edge:?}");
            assert_eq!(reader.position_here(), reader.position_at(&token, edge));

            // Clause 7, second half: moving to a position sets the position to it —
            // from wherever the stream happens to stand.
            let mark = reader.position_at(&token, edge);
            reader.move_to(&token, TokenEdge::EndPastPostSpace);
            reader.move_to_position(&mark);
            assert_eq!(reader.position_here(), mark, "{edge:?}");
            assert_eq!(at(reader), SourcePos::new(&source, offset), "{edge:?}");
        }

        // Reading again after the rewind yields the same token.
        assert_eq!(reader.peek(&st).unwrap(), token);
    }

    #[test]
    fn consecutive_tokens_meet_at_one_position() {
        // Contract clause 7's corollary with clause 2: a token peeked right after the
        // stream moved past its predecessor starts where the predecessor ended.
        let source = Arc::new(Source::new("a \\vec  b% c\nd"));
        let mut tr = StdTokenReader::new(&source);
        let st = state(latex_rules());
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut tr;

        let mut prev = reader.next(&st).unwrap();
        loop {
            let next = reader.peek(&st).unwrap();
            assert_eq!(
                reader.position_at(&next, TokenEdge::StartBeforePreSpace),
                reader.position_at(&prev, TokenEdge::EndPastPostSpace),
                "tokens {prev:?} and {next:?} do not meet at one position"
            );
            if matches!(reader.token_kind(&next), TokenKind::EndOfStream) {
                break;
            }
            reader.move_to(&next, TokenEdge::EndPastPostSpace);
            prev = next;
        }
    }

    // --- an end-to-end walk (adapted from pylatexenc's multiple-tokens test) ---------------

    #[test]
    fn multiple_tokens_walk() {
        let text = "Text \\`accent and \\textbf{bold text} and $\\vec b$ \
                    vector \\& also Fran\\c cois\n\
                    \\begin{enumerate}[(i)]\n\
                    \\item Hi there!  % here goes a comment\n\
                    \\item[a] Hello!  @@@\n     \
                    \\end{enumerate}\n\
                    \\mymacro\n\n\
                    New paragraph\n";
        let st = state(latex_rules());
        let source = Arc::new(Source::new(text));
        let mut tr = StdTokenReader::new(&source);

        let find = |needle: &str| text.find(needle).unwrap();

        assert_eq!(next(&mut tr, &st), char_token('T', 0, Span::empty(0)));

        let p = find(r"\`");
        seek::<TestLang>(&mut tr, p);
        assert_eq!(
            next(&mut tr, &st),
            StdToken::command('\\', sp(p, p + 2), Span::empty(p), Span::empty(p + 2)),
        );

        let p = find(r"\textbf") - 1; // pre space
        seek::<TestLang>(&mut tr, p);
        assert_eq!(
            next(&mut tr, &st),
            // '{' follows the name: no post_space.
            StdToken::command('\\', sp(p + 1, p + 8), sp(p, p + 1), Span::empty(p + 8)),
        );
        let token = next(&mut tr, &st);
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::GroupOpen { delim: "{", rule: &rule_of(BRACES) },
        );

        let p = find(r"\vec"); // post-space present
        seek::<TestLang>(&mut tr, p);
        assert_eq!(
            next(&mut tr, &st),
            StdToken::command('\\', sp(p, p + 5), Span::empty(p), sp(p + 4, p + 5)),
        );

        let p = find(r"\&") - 1; // pre-space and *no* post-space
        seek::<TestLang>(&mut tr, p);
        assert_eq!(
            next(&mut tr, &st),
            StdToken::command('\\', sp(p + 1, p + 3), sp(p, p + 1), Span::empty(p + 3)),
        );

        // \begin is just a command token; the environment name is ordinary group+chars.
        let p = find(r"\begin");
        seek::<TestLang>(&mut tr, p);
        let token = next(&mut tr, &st);
        assert_eq!(
            kind_of(&tr, &token),
            TokenKind::Command { name: "begin", escape_char: '\\' },
        );

        let p = find("@@@") + 3; // pre space up to \end
        seek::<TestLang>(&mut tr, p);
        assert_eq!(
            next(&mut tr, &st),
            StdToken::command('\\', sp(p + 6, p + 10), sp(p, p + 6), Span::empty(p + 10)),
        );

        // The whole comment is one token: content to end of line, newline as post_space.
        let p = find("%") - 2;
        seek::<TestLang>(&mut tr, p);
        let nl = find(" % here goes a comment") + " % here goes a comment".len();
        assert_eq!(
            next(&mut tr, &st),
            StdToken::comment(sp(p + 2, p + 3), sp(p + 2, nl + 1), sp(p, p + 2), sp(nl, nl + 1)),
        );

        // \mymacro directly precedes a paragraph break: no post_space.
        let p = find(r"\mymacro");
        seek::<TestLang>(&mut tr, p);
        assert_eq!(
            next(&mut tr, &st),
            StdToken::command('\\', sp(p, p + 8), Span::empty(p), Span::empty(p + 8)),
        );
        let p2 = find("\n\n");
        assert_eq!(
            next(&mut tr, &st),
            StdToken::paragraph_break(sp(p2, p2 + 2), Span::empty(p2)),
        );

        // ... and the file's trailing newline is the end-of-stream token's pre_space.
        let p = find("New paragraph");
        seek::<TestLang>(&mut tr, p + "New paragraph".len());
        assert_eq!(
            next(&mut tr, &st),
            StdToken::end_of_stream(sp(text.len() - 1, text.len())),
        );
    }
}