techy 0.2.0

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
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
//! [`NodesParser`], the content dispatch loop, and its stop machinery
//! ([`StopSpec`], [`TokenStopCondition`], [`StopCause`]).
//!
//! The loop peeks one token at a time and dispatches on the token's kind, never on a
//! registry of parsers keyed by syntax. The content arms stage directly: character
//! accumulation, paragraph breaks (whose node kind comes from
//! [`ParseDriver::make_paragraph_break_node`]), comments, and end of stream.
//!
//! The `GroupOpen` arm descends. It resolves the interior's base state through the
//! per-use [`ChildStateSpec`] policy, consumes the trigger token, and runs a
//! group parser under the policy's state — [`GroupParser`] unless the driver's
//! factory supplies another — reverting to the loop's own state afterwards. A group normally returns no state delta; one leaks an after-effect only
//! where the language installed [`GroupAfterEffectsFn`].
//!
//! The `Command` and `Specials` arms descend the same way. A `Command` token resolves
//! through [`ParseDriver::resolve_command`] under the loop's own state, so resolution
//! precedes the descent policy; a `Specials` token already carries its resolution. The
//! arm then consumes the trigger whole, builds the [`Invocation`], and runs the parser
//! the spec's
//! [`make_invocation_parser`](crate::core::specs::CallableSpec::make_invocation_parser)
//! factory returns, under the policy's state.
//!
//! The state delta an invocation parser returns becomes the invocation's after-effect
//! for the following siblings (`\newcommand`). It is applied to the loop's own state
//! through the session, so state transitions are observed, and the applied deltas are
//! also merged into the single record [`NodesOutcome::after_effects`] exports.
//!
//! The user-facing contract — the stop conditions, the whitespace and span invariants,
//! and the recovery behavior — is documented on [`NodesParser`] itself.

use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use core::mem;

use crate::error::{DiagnosticInfo, ParseError, ToDiagnosticValue};
use crate::node::{BuildId, NodeKind, StagedNodeView};
use crate::source::{SourceSpan, TextContent};
use crate::engine::{CommandResolution, ParseDriver};
use crate::state::{FeaturePresence, Lang, LangFeatures, ParsingState, ParsingStateDelta};
use crate::token::{StreamPosition, Token, TokenEdge, TokenKind, TokenReader};

use super::child_state::{ChildStateSpec, GroupChildState, InvocationChildState};
use super::{
    ImplementationErrorKind,
    comment_node_kind, push_pre_space_text, push_token_text, ConstructParser,
    ConstructParserResult, FromInvocation, Invocation, invocation_frame, ParseContext,
};

/// The error that is reported when a document uses a command that has no definition (id
/// `core.specs.unresolvable-command`).
///
/// The parser resolves each command, such as `\emph`, with
/// [`ParseDriver::resolve_command`](crate::core::ParseDriver::resolve_command), which
/// looks up the definition of the command (for instance in the scope stack of the
/// parsing state). This error is reported when `resolve_command` returns
/// [`CommandResolution::Unresolved`](crate::core::specs::CommandResolution::Unresolved).
/// When the resolver itself fails, `resolve_command` returns
/// [`CommandResolution::Failed`](crate::core::specs::CommandResolution::Failed) and the
/// parser reports [`CommandResolutionFailed`] instead.
///
/// Reported by [`NodesParser`] for a command in content, and by the argument parsers for
/// a command that forms an argument on its own. The span of the diagnostic is the
/// command. In a tolerant parse, the command is parsed into a `Chars` node that contains
/// its source text, and the parse continues. A strict parse stops with this error.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.specs.unresolvable-command")]
pub struct UnresolvableCommand {
    /// The command name, as written (without the escape character).
    pub name: String,
    /// The escape character that introduced the command.
    pub escape_char: char,
    /// Additional information from the resolver, or `None`.
    ///
    /// The message shows the detail after a colon, as in `Unknown command ‘\foo’:
    /// <detail>`, so the detail continues the sentence and begins with a lowercase
    /// letter. For instance,
    /// [`resolve_command_in_scopes`](crate::core::specs::resolve_command_in_scopes)
    /// lists the definition providers that it searched and suggests similar command
    /// names, and the default resolver of [`ParseDriver`] states that the driver has no
    /// command resolver.
    pub detail: Option<String>,
}

// Hand-written wording: the detail suffix is conditional (a branch the derive's
// message format string cannot express).
impl fmt::Display for UnresolvableCommand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Unknown command ‘{}{}’", self.escape_char, self.name)?;
        if let Some(detail) = &self.detail {
            write!(f, ": {detail}")?;
        }
        Ok(())
    }
}

/// The error that is reported when the resolution of a command fails (id
/// `core.specs.command-resolution-failed`).
///
/// The parser resolves each command, such as `\emph`, with
/// [`ParseDriver::resolve_command`](crate::core::ParseDriver::resolve_command). This
/// error is reported when `resolve_command` returns
/// [`CommandResolution::Failed`](crate::core::specs::CommandResolution::Failed): the
/// resolver could not look up the command, for instance because a definition provider
/// reported an error. A command that has no definition is reported as
/// [`UnresolvableCommand`]. The two errors let a program tell an unknown command from a
/// faulty resolver.
///
/// Reported by [`NodesParser`] for a command in content, and by the argument parsers for
/// a command that forms an argument on its own. The span of the diagnostic is the
/// command. In a tolerant parse, the command is parsed into a `Chars` node that contains
/// its source text, and the parse continues. A strict parse stops with this error.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.specs.command-resolution-failed")]
pub struct CommandResolutionFailed {
    /// The command name, as written (without the escape character).
    pub name: String,
    /// The escape character that introduced the command.
    pub escape_char: char,
    /// The description of the failure from the resolver, or `None`.
    ///
    /// The message shows the detail after a colon, as in `Failed to resolve command
    /// ‘\foo’: <detail>`. The detail is a complete message and begins with a capital
    /// letter. For instance,
    /// [`resolve_command_in_scopes`](crate::core::specs::resolve_command_in_scopes) sets
    /// it to the `Display` text of the
    /// [`ScopeStackError`](crate::core::specs::ScopeStackError) that
    /// [`ScopeStack::retrieve_spec`](crate::core::specs::ScopeStack::retrieve_spec)
    /// returns. This text contains the name of the definition provider that failed, as
    /// in `Definition provider ‘user’ failed: <error>`.
    pub detail: Option<String>,
}

// Hand-written wording: the detail suffix is conditional (as for UnresolvableCommand).
impl fmt::Display for CommandResolutionFailed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Failed to resolve command ‘{}{}’",
            self.escape_char, self.name
        )?;
        if let Some(detail) = &self.detail {
            write!(f, ": {detail}")?;
        }
        Ok(())
    }
}

/// The error that is reported when a callable that requires arguments or a body forms an
/// argument on its own (id `core.arguments.expression-callable-requires-content`).
///
/// Some arguments consist of a single expression: a group, a single character, or a
/// callable. For instance, an argument parsed by
/// [`ExpressionParser`](super::ExpressionParser) is such an argument, as in `\frac12`. A
/// callable can form this argument on its own only if it requires no content, that is, if
/// [`CallableSpec::requires_content`](crate::core::specs::CallableSpec::requires_content)
/// returns `false`. A callable with a mandatory argument must be enclosed in a group
/// together with its arguments, as in `\frac{\sqrt{2}}{3}`.
///
/// Reported by the argument parser that parses the argument. The span of the diagnostic
/// is the callable. In a tolerant parse, the argument consists of the callable alone,
/// with every declared argument of the callable absent, and the parse continues after the
/// callable. A strict parse stops with this error.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.arguments.expression-callable-requires-content",
    message = "‘{callable}’ may not be used alone as an argument: it requires \
               arguments or a body"
)]
pub struct ExpressionCallableRequiresContent {
    /// The callable as written in the source, for instance `\frac` or `~`.
    pub callable: String,
}

/// The error that is reported when a token reader recovers from a tokenization error
/// with a placeholder token that cannot be parsed (id
/// `core.recovery.unusable-recovery-token`).
///
/// When a token reader fails to read a token, it can return a
/// [`TokenRecovery`](crate::core::token::TokenRecovery) with a placeholder token, and a
/// tolerant parse continues with this placeholder. Reading then continues at the resume
/// position of the recovery
/// ([`TokenRecovery::resume`](crate::core::token::TokenRecovery::resume)), so the
/// placeholder is not part of the token stream. Therefore [`NodesParser`] cannot parse a
/// command invocation, a specials invocation or a group that begins with a placeholder.
/// This error is reported when the placeholder is a
/// [`Command`](crate::core::token::TokenKind::Command), a
/// [`Specials`](crate::core::token::TokenKind::Specials) or a
/// [`GroupOpen`](crate::core::token::TokenKind::GroupOpen) token.
///
/// The standard token reader returns only [`Char`](crate::core::token::TokenKind::Char)
/// placeholder tokens. Therefore a document cannot cause this error; only a custom token
/// reader can.
///
/// Reported by [`NodesParser`]. The span of the diagnostic is the span of the placeholder
/// token. In a tolerant parse, the placeholder is parsed into a `Chars` node over this
/// span, and the parse continues. A strict parse stops at the tokenization error and never
/// reports this error.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.recovery.unusable-recovery-token")]
pub struct UnusableRecoveryToken {
    /// The text of the placeholder token: the escape character and the name of a command
    /// (for instance `\c`), the characters of a specials token, or the opening delimiter
    /// of a group.
    pub spelling: String,
    /// The kind of the placeholder token.
    pub kind: UnusableRecoveryTokenKind,
}

/// The kind of the placeholder token of an [`UnusableRecoveryToken`] error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToDiagnosticValue)]
#[non_exhaustive]
pub enum UnusableRecoveryTokenKind {
    /// A [`Command`](crate::core::token::TokenKind::Command) token.
    Command,
    /// A [`Specials`](crate::core::token::TokenKind::Specials) token.
    Specials,
    /// A [`GroupOpen`](crate::core::token::TokenKind::GroupOpen) token.
    GroupOpen,
}

// Hand-written wording: the message varies by placeholder kind (a match, which the
// message format string cannot express).
impl fmt::Display for UnusableRecoveryToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            UnusableRecoveryTokenKind::Command => write!(
                f,
                "Misconfigured token reader: the recovery placeholder ‘{}’ of a \
                 tokenization error may not be a command",
                self.spelling
            ),
            UnusableRecoveryTokenKind::Specials => write!(
                f,
                "Misconfigured token reader: the recovery placeholder ‘{}’ of a \
                 tokenization error may not be a specials token",
                self.spelling
            ),
            UnusableRecoveryTokenKind::GroupOpen => write!(
                f,
                "Misconfigured token reader: the recovery placeholder ‘{}’ of a \
                 tokenization error may not be an opening delimiter",
                self.spelling
            ),
        }
    }
}

/// Which peeked token matches a [`TokenStopCondition`] and so ends a [`NodesParser`]
/// run.
///
/// The common cases are named variants; [`Predicate`](Self::Predicate) covers everything
/// else. This is the typed form of pylatexenc's `stop_token_condition`.
pub enum TokenStopKind<'p, L: Lang> {
    /// Stop at a [`Command`](crate::core::token::TokenKind::Command) token with this
    /// name — how an environment body stops at `\end`.
    Command {
        /// The command name to stop at (as written, without the escape character).
        name: &'p str,
    },
    /// Stop at a [`GroupClose`](crate::core::token::TokenKind::GroupClose) token that
    /// spells `close` *and* whose group class is `group_type` — the exact pairing the
    /// enclosing group opened with.
    ///
    /// Both halves must match. A group opened with `{` stops at `}`, but not at a `]`
    /// that merely shares its class, and not at a `}` that a state change has re-classed
    /// to a different group class. A close that does not match ends the run as
    /// [`StopCause::UnexpectedGroupClose`] instead.
    ///
    /// A `GroupClose` token records only its delimiter, so the class is resolved again
    /// against the parsing state the loop currently holds — the same state the tokenizer
    /// used to emit the token, including the sibling deltas applied so far. A delta that
    /// re-classes a delimiter is therefore reflected here.
    GroupClose {
        /// The group class the enclosing group belongs to (resolved for the arriving
        /// close against the current state — the expected close, then the delimiter table).
        group_type: L::GroupTypeId,
        /// The closing delimiter (as written, e.g. `}`) the enclosing group expects.
        close: &'p str,
    },
    /// Stop at a [`ParagraphBreak`](crate::core::token::TokenKind::ParagraphBreak)
    /// token.
    ParagraphBreak,
    /// Stop at any token the predicate matches.
    ///
    /// The predicate receives the peeked token and a shared, call-scoped reference to
    /// the reader that produced it, so it can ask whatever it needs about the token —
    /// [`token_kind`](crate::core::token::TokenReader::token_kind) for what the token
    /// is, [`source_span_of`](crate::core::token::TokenReader::source_span_of) for where
    /// it is — while being unable to move the stream. A predicate belongs in the
    /// short-lived parser value that sets up the run, not in spec data.
    ///
    /// An `Err` from the predicate aborts the parse under any recovery policy: a
    /// predicate that cannot answer leaves no sound way to decide where the run ends.
    /// Carry [`HookFailed`](crate::error::HookFailed) for an operational failure in the
    /// predicate's own code, [`ImplementationError`](super::ImplementationError) for a
    /// violated library contract, or a document condition for a diagnosis made
    /// deliberately. The parser attaches the live traceback when the error carries no
    /// frames of its own. An infallible predicate returns `Ok(...)`.
    // The predicate signature is the variant's whole documented meaning; hiding it
    // behind an alias would only make callers look the signature up elsewhere.
    #[allow(clippy::type_complexity)]
    Predicate(
        &'p dyn Fn(
            &Token<L>,
            &dyn TokenReader<'_, L>,
        ) -> Result<bool, ParseError<L::SourceOrigin>>,
    ),
}

/// The token-condition half of a [`StopSpec`]: which peeked token ends the parse, and
/// whether [`NodesParser`] consumes it on a match.
///
/// On a match the run ends with [`StopCause::TokenCondition`], carrying the matched
/// token's span.
///
/// With [`consume`](Self::consume) `= false` the token is left unconsumed at its own
/// `span.start`, so the caller can peek it again. With `consume = true` it is taken
/// whole, including any syntactic post-space such as a command name's terminating
/// whitespace, so no byte is re-read as content.
///
/// The switch only decides whether to consume; unlike pylatexenc's
/// `handle_stop_condition_token`, there is no hook that reinterprets the token.
pub struct TokenStopCondition<'p, L: Lang> {
    /// Which token ends the parse.
    pub kind: TokenStopKind<'p, L>,
    /// Whether [`NodesParser`] consumes the matched token (`true`) or leaves it
    /// unconsumed for the caller (`false`).
    pub consume: bool,
}

/// What ends a [`NodesParser`] run: a token condition, a node condition, or neither.
///
/// The two triggers are independent and both optional. [`none`](Self::none) parses to
/// end of input; [`at_token`](Self::at_token) sets only the token condition. When both
/// are set and both would fire at once, the token condition wins — see
/// [`node`](Self::node).
///
/// The `'p` lifetime ties borrowed conditions, such as command names and predicates, to
/// the short-lived parser value that owns the spec, so a condition may borrow from its
/// surroundings rather than be cloned into spec data.
pub struct StopSpec<'p, L: Lang> {
    /// Token condition, tested on peek; a match ends the parse, consuming the token or
    /// leaving it per its [`consume`](TokenStopCondition::consume) switch.
    ///
    /// Only cleanly read tokens are tested. A recovery placeholder standing in for a
    /// tokenization error is processed as content instead: its site has already
    /// diagnosed it, and a token that cannot be read again cannot be left for the
    /// caller.
    pub token: Option<TokenStopCondition<'p, L>>,
    /// Node condition, tested after each staged node; a match includes that node and
    /// ends the run with [`StopCause::NodeCondition`].
    ///
    /// The condition receives the number of nodes staged so far and a view of the node
    /// just staged, rather than the whole sibling list as pylatexenc rescans it.
    ///
    /// It is not consulted on the final flush that a matched token condition triggers.
    /// The token condition wins outright there: the run would end as
    /// [`TokenCondition`](StopCause::TokenCondition) either way, and honoring the node
    /// condition instead would leave a `consume = true` stop token unconsumed. Since the
    /// condition is a stateful `FnMut`, even a consulted-but-ignored call would be an
    /// observable side effect, so it is not called at all.
    ///
    /// An `Err` from the condition aborts the parse under any recovery policy: a
    /// condition that cannot answer leaves no sound way to decide where the run ends.
    /// Carry [`HookFailed`](crate::error::HookFailed) for an operational failure in the
    /// condition's own code, [`ImplementationError`](super::ImplementationError) for a
    /// violated library contract, or a document condition for a diagnosis made
    /// deliberately. The parser attaches the live traceback when the error carries no
    /// frames of its own. An infallible condition returns `Ok(...)`.
    // The decided signature (DESIGN_RATIONALE.md [§dd-dr:parsers-engine]); an alias would only rename it.
    #[allow(clippy::type_complexity)]
    pub node: Option<
        &'p mut dyn FnMut(
            usize,
            StagedNodeView<'_, L>,
        ) -> Result<bool, ParseError<L::SourceOrigin>>,
    >,
}

impl<'p, L: Lang> StopSpec<'p, L> {
    /// Returns a spec with no stop conditions: the run continues to end of input.
    pub fn none() -> StopSpec<'p, L> {
        StopSpec { token: None, node: None }
    }

    /// Returns a spec with only a token condition: stop at `kind`, consuming the
    /// matched token or leaving it for the caller as `consume` says.
    pub fn at_token(kind: TokenStopKind<'p, L>, consume: bool) -> StopSpec<'p, L> {
        StopSpec { token: Some(TokenStopCondition { kind, consume }), node: None }
    }
}

impl<L: Lang> Default for StopSpec<'_, L> {
    fn default() -> Self {
        StopSpec::none()
    }
}

/// The error that is reported when a closing delimiter appears where no group is open
/// (id `core.groups.stray-group-close`).
///
/// Each closing delimiter must close a group that is open, as in `{a b}`. Inside a group,
/// a closing delimiter of another group rule is reported by
/// [`GroupParser`](super::GroupParser) as [`UnclosedGroup`](super::UnclosedGroup), and it
/// closes the groups up to an enclosing group of its own rule. A closing delimiter that
/// reaches the outermost level, because no enclosing group is of its rule, is reported
/// as this error.
///
/// Reported by [`RootNodesParser`](super::RootNodesParser) for the source of the parse,
/// and by [`ParseContext::parse_attached_source`] for an attached source, such as an
/// included file. A custom root parser can report it in the same situation. The span of
/// the diagnostic is the closing delimiter. In a tolerant parse, the closing delimiter is
/// parsed into a `Chars` node, and the parse continues after it. A strict parse stops
/// with this error.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.groups.stray-group-close",
    message = "Unmatched closing delimiter ‘{delim}’: no group is open"
)]
pub struct StrayGroupClose {
    /// The closing delimiter as written, for instance `}`.
    pub delim: String,
}

/// How a [`NodesParser`] run ended.
///
/// An abnormal ending is reported as data rather than as an error, because only the
/// caller knows whether it is a problem: reaching end of input matters to an environment
/// body still waiting for `\end{align}`, and not at all to the top level. The run's
/// [`NodesOutcome`] carries this value alongside the nodes staged before the stop.
pub enum StopCause<L: Lang> {
    /// The token stop condition matched.
    ///
    /// Whether the token was consumed is the
    /// [`consume`](TokenStopCondition::consume) the caller set. If it was, the reader
    /// stands just past the token; if it was not, the token sits unconsumed at its own
    /// start. Either way its pre-space is already staged as sibling content.
    TokenCondition {
        /// The matched stop token's span.
        span: SourceSpan<L::SourceOrigin>,
        /// The stream position just past the matched token (its post-space
        /// included) — where a caller that wants the token skipped repositions the
        /// reader ([`move_to_position`](crate::core::token::TokenReader::move_to_position)),
        /// whether or not the condition consumed it.
        after: StreamPosition<L>,
    },
    /// The node stop condition fired on the last staged node.
    ///
    /// The reader stands where that node ended: a node staged directly has been
    /// consumed, whereas a node produced by flushing a pending character run leaves the
    /// token that triggered the flush unconsumed at its own start.
    NodeCondition,
    /// [`EndOfStream`](crate::core::token::TokenKind::EndOfStream) was reached. Any
    /// trailing whitespace is already staged as a final `Chars` node.
    EndOfInput,
    /// A group close arrived that no stop condition asked for.
    ///
    /// The close token is left unconsumed at its own start and the caller decides what
    /// to do: the root parser diagnoses it and skips it, a group parser unwinds.
    ///
    /// The span covers the delimiter exactly as matched, since a
    /// [`GroupClose`](crate::core::token::TokenKind::GroupClose) token carries nothing
    /// but its delimiter. Read the delimiter off the span with
    /// [`SourceSpan::content`](crate::source::SourceSpan::content) rather than peeking
    /// again — a peek under any state but the loop's own could tokenize different bytes.
    UnexpectedGroupClose {
        /// The unexpected close token's span.
        span: SourceSpan<L::SourceOrigin>,
        /// The stream position just past the unconsumed close token — the skip
        /// target of a caller that recovers from it.
        after: StreamPosition<L>,
    },
}

// Manual impls: derives would demand `L: Debug`/`L: Clone`/`L: PartialEq`, although
// only the (already bounded) associated types are stored.
impl<L: Lang> fmt::Debug for StopCause<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StopCause::TokenCondition { span, after } => f
                .debug_struct("TokenCondition")
                .field("span", span)
                .field("after", after)
                .finish(),
            StopCause::NodeCondition => f.write_str("NodeCondition"),
            StopCause::EndOfInput => f.write_str("EndOfInput"),
            StopCause::UnexpectedGroupClose { span, after } => f
                .debug_struct("UnexpectedGroupClose")
                .field("span", span)
                .field("after", after)
                .finish(),
        }
    }
}

impl<L: Lang> Clone for StopCause<L> {
    fn clone(&self) -> Self {
        match self {
            StopCause::TokenCondition { span, after } => StopCause::TokenCondition {
                span: span.clone(),
                after: after.clone(),
            },
            StopCause::NodeCondition => StopCause::NodeCondition,
            StopCause::EndOfInput => StopCause::EndOfInput,
            StopCause::UnexpectedGroupClose { span, after } => {
                StopCause::UnexpectedGroupClose {
                    span: span.clone(),
                    after: after.clone(),
                }
            }
        }
    }
}

impl<L: Lang> PartialEq for StopCause<L> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                StopCause::TokenCondition { span, after },
                StopCause::TokenCondition { span: other_span, after: other_after },
            ) => span == other_span && after == other_after,
            (StopCause::NodeCondition, StopCause::NodeCondition) => true,
            (StopCause::EndOfInput, StopCause::EndOfInput) => true,
            (
                StopCause::UnexpectedGroupClose { span, after },
                StopCause::UnexpectedGroupClose { span: other_span, after: other_after },
            ) => span == other_span && after == other_after,
            _ => false,
        }
    }
}

impl<L: Lang> Eq for StopCause<L> {}

/// What a [`NodesParser`] run produces: the staged sibling nodes in source order, how
/// the run ended, the parsing state it reached, and the state after-effects it applied.
///
/// A caller that resumes content where the run stopped continues under
/// [`state`](Self::state). A caller that has to carry the run's state effects somewhere
/// else instead wants [`after_effects`](Self::after_effects).
pub struct NodesOutcome<L: Lang> {
    /// The staged nodes, in source order (the caller claims them as children).
    pub nodes: Vec<BuildId>,
    /// How the parse ended.
    pub stop: StopCause<L>,
    /// The parsing state when the run returned: the state it started from, evolved by
    /// the sibling after-effect deltas it applied.
    ///
    /// A caller that resumes content at the stop position — as the root parser does
    /// after skipping a stray group close — must continue under this state. Resuming
    /// under its own copy of the entry state would silently roll those after-effects
    /// back.
    pub state: Arc<ParsingState<L>>,
    /// The sibling after-effect deltas this run applied, merged into a single
    /// [`ParsingStateDelta`] in application order. `None` when the run applied none.
    ///
    /// Use this to *propagate* the run's state effects elsewhere. The `\input`
    /// composition that persists state forwards it as the invocation's own after-effect
    /// (see [`AttachedSourceOutcome`](super::AttachedSourceOutcome)). To merely resume
    /// where the run stopped, use [`state`](NodesOutcome::state) instead: re-deriving
    /// from this record would re-run fallible scope operations and observe the state
    /// transitions a second time.
    ///
    /// Each merged component is the delta as it was actually applied, with
    /// context-dependent events already lowered into the override patches they produced
    /// at the loop's own position. The record is therefore replayable against a base its
    /// producers never saw: later field overrides win, and scope operations and
    /// context-free events concatenate in application order.
    ///
    /// A scope operation that failed when first applied stays in the record — nothing is
    /// silently stripped — so a replay attempts it again and may report the same failure
    /// at the propagation site.
    pub after_effects: Option<Box<ParsingStateDelta<L>>>,
}

// Manual impls: derives would demand `L: Debug`/`L: Clone`, but the state rides behind
// an `Arc` and `ParsingState` is `Debug` for every `L: Lang`.
impl<L: Lang> fmt::Debug for NodesOutcome<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NodesOutcome")
            .field("nodes", &self.nodes)
            .field("stop", &self.stop)
            .field("state", &self.state)
            .field("after_effects", &self.after_effects)
            .finish()
    }
}

impl<L: Lang> Clone for NodesOutcome<L> {
    fn clone(&self) -> Self {
        NodesOutcome {
            nodes: self.nodes.clone(),
            stop: self.stop.clone(),
            state: Arc::clone(&self.state),
            after_effects: self.after_effects.clone(),
        }
    }
}

/// Parses a run of sibling nodes, stopping at a stop condition, an unexpected group
/// close, or end of input.
///
/// This is the content dispatch loop: the top-level content, a group's interior and an
/// environment's body each run one. It peeks one token at a time and dispatches on the
/// token's kind. Character runs, comments and paragraph breaks are staged directly;
/// a group open, a command, or a specials trigger starts a descent into a child
/// construct parser. [The parsing
/// model](crate::guide::parsing_model#the-content-dispatch-loop) walks through the
/// dispatch; [custom construct parsers](crate::guide::construct_parsers) covers writing
/// the parsers it descends into. This is pylatexenc's `LatexGeneralNodesParser`
/// together with its nodes collector.
///
/// Build one with [`new`](Self::new), giving it the [`StopSpec`] that says where the run
/// ends, and add [`with_child_states`](Self::with_child_states) to change the parsing
/// state child constructs are parsed under. Run it like any other [`ConstructParser`];
/// it produces a [`NodesOutcome`]. The value holds its working state in fields and is
/// meant to be built for one run and dropped.
///
/// The run starts from the parsing state the caller put in the context. Deltas returned
/// by invocation parsers are applied as the loop proceeds, so a `\newcommand` is in
/// effect for the siblings that follow it, and the parser itself returns `None` as its
/// own pass-through delta. Those applied deltas reach the caller through the outcome:
/// [`NodesOutcome::state`] for a caller that resumes content at the stop position, and
/// [`NodesOutcome::after_effects`] for one that propagates the run's state effects
/// elsewhere.
///
/// # Where a run stops
///
/// A [`StopSpec`] carries two independent triggers. The token condition is tested on
/// each peeked token; a match ends the run and, per its
/// [`consume`](TokenStopCondition::consume) switch, either leaves the token unconsumed
/// for the caller or consumes it here. The node condition is tested after each staged
/// node; a match includes that node and stops after it. Both are tested only at this
/// parser's own nesting level — a nested group is consumed whole by the group parser.
///
/// An abnormal ending is reported as data rather than as an error: the run returns its
/// [`StopCause`] and the caller decides what it means. An unexpected group close is left
/// unconsumed.
///
/// Whenever a run ends at a token — a matched stop token, an unexpected group close, or
/// end of input — that token's pre-space is flushed into the sibling nodes first. The
/// whitespace before a `}` or an `\end` is interior content and belongs to a sibling
/// node. A token left behind then sits at its own `span.start`, so peeking it
/// again yields it with empty pre-space and no byte is represented twice; a consumed
/// stop token is taken whole, including any syntactic post-space such as a command
/// name's terminating whitespace, so the reader stands just past it. Either way the
/// matched span is reported in [`StopCause::TokenCondition`].
///
/// When both triggers would fire at once — the pre-stop flush stages a node the node
/// condition would match — the token condition wins, and the node condition is not
/// consulted for that flush. See [`StopSpec::node`].
///
/// # Whitespace and spans
///
/// Character tokens accumulate into *maximal* `Chars` nodes. Every token's pre-space
/// joins the pending run, and pending whitespace with no adjacent characters becomes a
/// whitespace-only `Chars` node — including the trailing whitespace the end-of-stream
/// token carries.
///
/// A paragraph break is always its own node, staged over the whole token span with the
/// kind
/// [`ParseDriver::make_paragraph_break_node`](crate::core::ParseDriver::make_paragraph_break_node)
/// chooses; character runs flush at a break and never merge across one. A comment node
/// comes straight from a whole-comment token, recording the start delimiter, the
/// content, and the post-space separately.
///
/// A `Chars` node records its content as
/// [`TextContent::Spanned`](crate::source::TextContent::Spanned), the exact span slice,
/// for a language that sets
/// [`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING). For a language
/// that does not, a run's tokens need not form one contiguous stretch of one source —
/// they may cross a seam between two sources, where a span would name the wrong bytes —
/// so the content is [`TextContent::Owned`](crate::source::TextContent::Owned),
/// accumulated token by token from what the reader reports about each of them.
///
/// A language that obeys span tiling therefore gets span tiling: the staged sibling
/// spans cover the parsed extent exactly, with no gaps and no byte counted twice. No
/// such accounting is claimed for a language that does not; its nodes carry the spans
/// the reader reported and the content it reported.
///
/// # Recovery
///
/// The parser handles each problem where it detects it, according to the
/// [`Recovery`](crate::error::Recovery) policy of the parse. A strict parse stops with
/// an error. A tolerant parse reports a diagnostic and continues as follows:
///
/// - After a tokenization error that offers a
///   [`TokenRecovery`](crate::core::token::TokenRecovery), the parser continues with
///   the placeholder token of the recovery, and the token reader continues reading at
///   the resume position of the recovery.
/// - A command that has no definition ([`UnresolvableCommand`]), or whose resolver
///   failed ([`CommandResolutionFailed`]), is parsed into a `Chars` node that contains
///   the source text of the command.
/// - A placeholder command, specials or group-open token ([`UnusableRecoveryToken`]) is
///   parsed into a `Chars` node over the span of the placeholder.
///
/// Such a `Chars` node always comes with a diagnostic, and the parser does not merge it
/// with the neighboring runs of characters. Unclosed and mismatched groups are handled
/// by [`GroupParser`](super::GroupParser).
///
/// An `Err` ends the parse.
pub struct NodesParser<'p, L: Lang> {
    stop: StopSpec<'p, L>,
    /// Descent-state policy for child constructs (groups and invocations); defaults to
    /// inherit-everywhere.
    child_states: ChildStateSpec<'p, L>,
    nodes: Vec<BuildId>,
    /// The pending maximal chars run: extended by `Char` tokens and every token's
    /// pre-space, flushed when a non-`Char` construct starts.
    run: Option<PendingRun<L>>,
    /// The merged record of the sibling after-effect deltas applied so far
    /// ([`NodesOutcome::after_effects`]); drained at every return like `nodes`.
    after_effects: Option<Box<ParsingStateDelta<L>>>,
}

/// The pending maximal chars run of a [`NodesParser`]: the two stream positions it
/// spans and, for a language that does not obey span tiling, the text accumulated along
/// the way.
struct PendingRun<L: Lang> {
    /// Where the run starts.
    start: StreamPosition<L>,
    /// Where the run currently ends — the position the next extension must start at,
    /// by the [`TokenReader`] contract's clause 7 corollary.
    end: StreamPosition<L>,
    /// The run's text as the reader reported it, token by token. `Some` exactly when
    /// the language does not obey span tiling
    /// ([`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`),
    /// where the run's tokens need not form one contiguous stretch of one source and a
    /// span could not describe their text.
    text: Option<String>,
}

// Hand-written: a derive would demand `L: Debug` although only the language's stream
// position type (already `Debug`) is stored.
impl<L: Lang> fmt::Debug for PendingRun<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PendingRun")
            .field("start", &self.start)
            .field("end", &self.end)
            .field("text", &self.text)
            .finish()
    }
}

/// Builds the `Chars` node a pending run becomes.
///
/// The span runs from the run's start to its end, through
/// [`ParseContext::source_span_within`], which follows the language's
/// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) declaration. The content
/// is the exact span slice where the language obeys span tiling, and the text
/// accumulated from the reader's reports where it does not.
fn chars_run_node<L: Lang>(
    cx: &ParseContext<'_, '_, L>,
    run: PendingRun<L>,
) -> ConstructParserResult<L, (NodeKind<L>, SourceSpan<L::SourceOrigin>)> {
    let span = cx.source_span_within(&run.start, &run.end)?;
    let content = match run.text {
        Some(text) => TextContent::Owned(text.into()),
        None => TextContent::Spanned(span.span()),
    };
    Ok((NodeKind::chars(content), span))
}

impl<'p, L: Lang> NodesParser<'p, L> {
    /// Creates a parser that stages the nodes it reads and stops as `stop` says.
    ///
    /// Child constructs are parsed under the state the parser itself holds; call
    /// [`with_child_states`](Self::with_child_states) to change that.
    pub fn new(stop: StopSpec<'p, L>) -> NodesParser<'p, L> {
        NodesParser {
            stop,
            child_states: ChildStateSpec::inherit(),
            nodes: Vec::new(),
            run: None,
            after_effects: None,
        }
    }

    /// Sets the parsing state that groups and invocations are parsed under, replacing
    /// the default of inheriting the loop's own state everywhere.
    ///
    /// See [`ChildStateSpec`] for the policies available.
    pub fn with_child_states(mut self, child_states: ChildStateSpec<'p, L>) -> Self {
        self.child_states = child_states;
        self
    }

    /// Extends the pending run with a token's pre-space: content whitespace joins the
    /// run, and pending whitespace with no adjacent characters becomes a
    /// whitespace-only run.
    ///
    /// The token's `StartBeforePreSpace` edge must be the position the pending run ends
    /// at, by the [`TokenReader`] contract's clause 7 corollary.
    /// [`extend_run_to`](Self::extend_run_to) checks that and returns the violation as
    /// an `Err` detail; it never panics.
    ///
    /// For a language with
    /// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`, the
    /// pre-space text the reader reports for *this* token joins the run's owned text.
    ///
    /// Equal `StartBeforePreSpace` and `Start` positions read as no pre-space. The two
    /// edges of the first token drawn from a new source compare equal unless its
    /// pre-space lies within that source, which is exactly what the [`TokenReader`]
    /// contract's seam rules require of such a token (see *Seams* there).
    fn take_pre_space(
        &mut self,
        cx: &ParseContext<'_, '_, L>,
        token: &Token<L>,
    ) -> Result<(), String> {
        let start = cx.tokens.position_at(token, TokenEdge::StartBeforePreSpace);
        let end = cx.tokens.position_at(token, TokenEdge::Start);
        if start == end {
            return Ok(());
        }
        let mut text = (!L::OBEYS_SPAN_TILING).then(String::new);
        push_pre_space_text(&mut text, cx, token);
        self.extend_run_to(start, end, text)
    }

    /// The `Char` arm: extends the pending run with the token's pre-space and its
    /// character in one step, over the token's whole extent — from where its pre-space
    /// begins to where the token ends. The two coincide when the token has no
    /// pre-space.
    ///
    /// Same position check, and the same `Err` reporting, as
    /// [`take_pre_space`](Self::take_pre_space).
    ///
    /// For a language with
    /// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`, the run's
    /// owned text grows by three things the reader reports about this one token: its
    /// pre-space text, the character it was classified as (`c`), and its syntactic
    /// post-space text.
    fn extend_run(
        &mut self,
        cx: &ParseContext<'_, '_, L>,
        token: &Token<L>,
        c: char,
    ) -> Result<(), String> {
        let start = cx.tokens.position_at(token, TokenEdge::StartBeforePreSpace);
        let end = cx.tokens.position_at(token, TokenEdge::EndPastPostSpace);
        let mut text = (!L::OBEYS_SPAN_TILING).then(String::new);
        push_token_text(&mut text, cx, token, c.encode_utf8(&mut [0u8; 4]));
        self.extend_run_to(start, end, text)
    }

    /// The shared run extension. `start` must be the position the pending run ends at.
    ///
    /// That is the [`TokenReader`] contract's clause 7 corollary: a peeked token's
    /// `StartBeforePreSpace` edge is where the peek happened, and moving to an edge sets
    /// the position. It holds for every reader, whatever the language's
    /// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) says, so the check
    /// runs in both cases. A violation comes from an outer layer, and is returned as an
    /// `Err` detail; it is never asserted.
    ///
    /// `text` is the extension's text for a run that accumulates owned text — `Some`
    /// exactly when the language does not obey span tiling.
    fn extend_run_to(
        &mut self,
        start: StreamPosition<L>,
        end: StreamPosition<L>,
        text: Option<String>,
    ) -> Result<(), String> {
        match &mut self.run {
            Some(run) => {
                if run.end != start {
                    return Err(alloc::format!(
                        "Inconsistent token reader: the token peeked at {:?} begins at \
                         {:?}; a peeked token, including its pre-space, must begin at \
                         the position of the peek",
                        run.end,
                        start
                    ));
                }
                run.end = end;
                if let (Some(accumulated), Some(text)) = (&mut run.text, text) {
                    accumulated.push_str(&text);
                }
            }
            None => self.run = Some(PendingRun { start, end, text }),
        }
        Ok(())
    }

    /// Flushes the pending run as a `Chars` node ([`chars_run_node`]). Returns whether
    /// the node stop condition fired on it.
    fn flush(&mut self, cx: &mut ParseContext<'_, '_, L>) -> ConstructParserResult<L, bool> {
        match self.run.take() {
            Some(run) => {
                let (kind, span) = chars_run_node(cx, run)?;
                self.stage_node(cx, kind, span)
            }
            None => Ok(false),
        }
    }

    /// Extends the pending run with the token's pre-space, then flushes it: the path
    /// taken when a non-`Char` construct starts.
    ///
    /// A matched *stop* token's flush goes through
    /// [`flush_for_token_stop`](Self::flush_for_token_stop) instead — same staging, no
    /// node-condition test.
    fn flush_through(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
        token: &Token<L>,
    ) -> ConstructParserResult<L, bool> {
        self.take_pre_space(cx, token).map_err(|detail| {
            let span = cx.tokens.source_span_between(
                token,
                TokenEdge::StartBeforePreSpace,
                TokenEdge::Start,
            );
            cx.implementation_error_with_kind(
                ImplementationErrorKind::TokenPositionMismatch,
                detail,
                span,
            )
        })?;
        self.flush(cx)
    }

    /// [`flush_through`](Self::flush_through) minus the node-condition test: the flush
    /// performed when the token stop condition has matched.
    ///
    /// The stop token's pre-space is interior content and must land in a sibling node,
    /// but the token condition has already ended the parse and wins outright. A
    /// node-condition match here could not change the outcome, and honoring it instead
    /// would leave a `consume = true` stop token unconsumed, forfeiting the consume
    /// flag's atomicity guarantee. The predicate is a stateful `FnMut`, so even a
    /// consulted-but-ignored call would be an observable side effect — it is not
    /// consulted at all.
    fn flush_for_token_stop(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
        token: &Token<L>,
    ) -> ConstructParserResult<L, ()> {
        self.take_pre_space(cx, token).map_err(|detail| {
            let span = cx.tokens.source_span_between(
                token,
                TokenEdge::StartBeforePreSpace,
                TokenEdge::Start,
            );
            cx.implementation_error_with_kind(
                ImplementationErrorKind::TokenPositionMismatch,
                detail,
                span,
            )
        })?;
        if let Some(run) = self.run.take() {
            let (kind, span) = chars_run_node(cx, run)?;
            self.stage(cx, kind, span)?;
        }
        Ok(())
    }

    /// Stages a childless node under the current state and records it as a sibling,
    /// without testing the node stop condition.
    ///
    /// Testing the condition is [`stage_node`](Self::stage_node)'s job; the token-stop
    /// flush stages through this one directly.
    fn stage(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
        kind: NodeKind<L>,
        span: SourceSpan<L::SourceOrigin>,
    ) -> ConstructParserResult<L, BuildId> {
        let id = cx
            .stage_node(kind, span.clone(), Arc::clone(&cx.state), vec![])
            .map_err(|error| cx.staging_error(error, span))?;
        self.nodes.push(id);
        Ok(id)
    }

    /// Stages a childless node ([`stage`](Self::stage)) and tests the node stop
    /// condition on it.
    fn stage_node(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
        kind: NodeKind<L>,
        span: SourceSpan<L::SourceOrigin>,
    ) -> ConstructParserResult<L, bool> {
        let id = self.stage(cx, kind, span)?;
        self.test_node_stop(cx, id)
    }

    /// Tests the node stop condition against an already-recorded sibling: the last
    /// entry of `self.nodes`, staged either by [`stage`](Self::stage) or by a child
    /// construct parser.
    ///
    /// A condition `Err` aborts under any recovery policy, as [`StopSpec::node`]
    /// promises. The live traceback is attached here, since the callback has no session
    /// access of its own.
    fn test_node_stop(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
        id: BuildId,
    ) -> ConstructParserResult<L, bool> {
        let Some(condition) = &mut self.stop.node else {
            return Ok(false);
        };
        let staged = cx.staged_nodes();
        // A miss means a child construct parser handed back a foreign id (an
        // implementation bug — the builder diagnoses it when the id lands in a child
        // list); treat it as "condition did not fire" rather than panic (panic policy).
        let Some(view) = staged.get(id) else {
            return Ok(false);
        };
        condition(self.nodes.len(), view).map_err(|error| cx.attach_hook_frames(error))
    }

    /// Returns whether the matched stop token is to be consumed
    /// ([`TokenStopCondition::consume`]) when the token stop condition matches the
    /// peeked token, and `None` when no token condition matches.
    ///
    /// A predicate `Err` aborts under any recovery policy, as
    /// [`TokenStopKind::Predicate`] promises; the caller attaches the live traceback.
    fn token_stop(
        &self,
        state: &ParsingState<L>,
        token: &Token<L>,
        token_kind: TokenKind<'_, L>,
        tokens: &dyn TokenReader<'_, L>,
    ) -> Result<Option<bool>, ParseError<L::SourceOrigin>> {
        let Some(cond) = self.stop.token.as_ref() else {
            return Ok(None);
        };
        let matches = match &cond.kind {
            TokenStopKind::Command { name } => {
                matches!(token_kind, TokenKind::Command { name: n, .. } if n == *name)
            }
            // Both the spelling and the state-resolved class must match the pairing the
            // group opened with (a `]` sharing the class, or a `}` a delta re-classed,
            // must not close it).
            TokenStopKind::GroupClose { group_type, close } => match token_kind {
                TokenKind::GroupClose { delim } => {
                    delim == *close && group_close_type(state, delim) == Some(*group_type)
                }
                _ => false,
            },
            TokenStopKind::ParagraphBreak => {
                matches!(token_kind, TokenKind::ParagraphBreak)
            }
            TokenStopKind::Predicate(predicate) => predicate(token, tokens)?,
        };
        Ok(matches.then_some(cond.consume))
    }

    /// The shared tolerant recovery for a token the loop cannot dispatch — an
    /// unresolvable command, a resolver failure, or an unusable recovery placeholder.
    ///
    /// Flushes the pending run, records `condition` (or aborts under a strict policy),
    /// consumes the token, and stages a chars fallback node over its full span. Returns
    /// whether a stop condition fired.
    ///
    /// For a `Command` token that span includes the post-space, which the fallback
    /// deliberately swallows: consuming the token without its post-space would
    /// desynchronize the fixed list of [`TokenListReader`], as its module documentation
    /// notes, and the fallback is a diagnosed artifact anyway.
    ///
    /// [`TokenListReader`]: crate::token::TokenListReader
    fn recover_as_chars<'s>(
        &mut self,
        cx: &mut ParseContext<'_, 's, L>,
        token: &Token<L>,
        recovered: bool,
        condition: impl DiagnosticInfo,
    ) -> ConstructParserResult<L, bool> {
        if self.flush_through(cx, token)? {
            if !recovered {
                cx.tokens.move_to(token, TokenEdge::Start);
            }
            return Ok(true);
        }
        let span = cx.tokens.source_span_of(token);
        cx.recover(condition, span.clone())?;
        if !recovered {
            cx.tokens.move_to(token, TokenEdge::EndPastPostSpace);
        }
        self.stage_node(cx, NodeKind::chars(span.span()), span)
    }

    /// Dispatches a resolved invocation — the `Command` and `Specials` arms.
    ///
    /// Resolves the descent base state through the
    /// [`invocation`](ChildStateSpec::invocation) policy; command resolution itself
    /// already ran under the loop's own state, since resolution precedes the policy.
    /// Consumes the trigger token whole, syntactic post-space included, mirroring the
    /// `GroupOpen` arm so that loop progress holds by construction. Runs the spec's
    /// invocation parser under the policy state, reverting afterwards, and records the
    /// staged node.
    ///
    /// The parser's after-effect delta is then applied to the loop's own state, so it
    /// holds for the following siblings (`\newcommand`); the application goes through
    /// the session, so the state transition is observed.
    ///
    /// Returns whether the node stop condition fired.
    fn dispatch_invocation<'s>(
        &mut self,
        cx: &mut ParseContext<'_, 's, L>,
        invocation: Invocation<'_, L>,
    ) -> ConstructParserResult<L, bool>
    where
        L::InvocationSyntax: FromInvocation<L>,
    {
        // `Arc` in, `Arc` out — pass-through policies preserve pointer identity.
        // A failing Compute aborts under any policy (the hook fallibility
        // contract), with the live traceback attached here — the callback has no
        // session access.
        let base = match &self.child_states.invocation {
            InvocationChildState::Inherit => Arc::clone(&cx.state),
            InvocationChildState::Fixed(state) => Arc::clone(state),
            InvocationChildState::Compute(compute) => compute(&cx.state, &invocation)
                .map_err(|error| cx.attach_hook_frames(error))?,
        };
        // The invocation's traceback frame — built before the `Invocation` moves into
        // the factory, pushed around the factory call and the parser run alike (the
        // dispatch push site, [§dd-dr:errors]): a failing factory's traceback names
        // the failing spec too.
        let frame = invocation_frame(cx, &invocation);
        cx.tokens.move_to(invocation.token, TokenEdge::EndPastPostSpace);
        let driver = cx.driver;
        let result = cx.with_frame(frame, |cx| {
            // The parser comes from the driver's interception seam (default: the
            // spec's own factory) — Phase 7.2. A factory Err aborts under any
            // policy ("could not build the parser"), with the live traceback
            // attached here.
            let mut parser = driver
                .make_invocation_parser(invocation)
                .map_err(|error| cx.attach_hook_frames(error))?;
            // The frame is already live — `parse_construct` gets `None`, not a
            // second copy of it.
            let result = cx.parse_construct(&mut *parser, Some(base), None);
            drop(parser);
            result
        });
        let (id, delta) = result?;
        self.nodes.push(id);
        if let Some(delta) = delta {
            // The after-effect applies to the loop's own state, not the policy base
            // (decided semantics 4, [§dd-dr:parsers-engine] — [§dd-dr:parsing-state]'s outward propagation blesses applying
            // a delta to a base the producer never saw) — and its effective,
            // as-applied form joins the run's merged record
            // ([`NodesOutcome::after_effects`]).
            cx.state = cx.derive_state_recording(&delta, &mut self.after_effects)?;
        }
        self.test_node_stop(cx, id)
    }

    /// Drains the collected siblings and the merged after-effect record into the
    /// outcome.
    fn outcome(&mut self, state: &Arc<ParsingState<L>>, stop: StopCause<L>) -> NodesOutcome<L> {
        NodesOutcome {
            nodes: mem::take(&mut self.nodes),
            stop,
            state: Arc::clone(state),
            // `Some` yet empty would be a pathological construct's empty after-effect
            // delta; the exported spelling for "no after-effects" is `None`.
            after_effects: self.after_effects.take().filter(|delta| !delta.is_empty()),
        }
    }
}

impl<L: Lang> ConstructParser<L> for NodesParser<'_, L>
where
    L::InvocationSyntax: FromInvocation<L>,
{
    type Output = NodesOutcome<L>;

    /// Runs the content loop from the context's current position, staging sibling nodes
    /// until the run stops.
    ///
    /// The second element of the returned pair is this parser's own pass-through state
    /// delta, always `None`. The deltas that invocation parsers return are applied to
    /// the loop's own state as it proceeds and reported through
    /// [`NodesOutcome::after_effects`] instead.
    ///
    /// # Errors
    ///
    /// An abnormal *ending* is not an error — it is reported as a [`StopCause`]. The
    /// parse is abandoned, and nothing continues past the error, when:
    ///
    /// - a condition is diagnosed under a strict recovery policy, or a token error
    ///   offers no recovery to continue from;
    /// - a hook or callback returns an `Err`: a stop condition ([`StopSpec::token`],
    ///   [`StopSpec::node`]), a child-state policy ([`ChildStateSpec`]), command
    ///   resolution, or a parser factory. These abort under any recovery policy,
    ///   because without an answer the loop cannot tell where the run ends or what to
    ///   descend into;
    /// - the token source violates its contract — it serves a token whose kind belongs
    ///   to a language feature the language declares absent, a token that does not
    ///   start where it was peeked, or a token that leaves the stream position
    ///   unchanged, which would otherwise make the loop read it forever. These are
    ///   reported as [`ImplementationError`](super::ImplementationError), never as a
    ///   panic;
    /// - staging a node into the tree fails.
    fn parse(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
    ) -> ConstructParserResult<L, (NodesOutcome<L>, Option<Box<ParsingStateDelta<L>>>)> {
        // Where the stream stood at the head of the previous iteration — the one piece of
        // loop state the termination guard below needs.
        let mut last_position: Option<StreamPosition<L>> = None;
        loop {
            // Termination guard, one position compare per iteration. Every arm that
            // continues the loop consumes its token (or descends into a parser that
            // consumes it), so an iteration that continues must leave the stream at a
            // different position than it started at — `TokenReader` contract clause 9:
            // every token other than `EndOfStream` advances the stream position. A source
            // that serves a token whose two ends are the same position breaks that, and
            // the loop would re-read it forever (clauses 1, 2 and 7 oblige the reader to
            // return the same token again at the same position under the same state), so
            // report the violation as an implementation error — an abort under any
            // recovery policy, never a hang. A sub-parser descent that consumed nothing
            // and moved nothing is caught by the same compare, which is intended: it is
            // the same non-terminating loop. The compare also fires on a descent that
            // rewound past its own trigger to re-tokenize under a new state — which
            // clause 1 counts as progress, but a position compare cannot see it: that is
            // the accepted cost of comparing positions only, and no in-crate parser
            // rewinds that way ([§dd-dr:token-progress-guard]).
            //
            // The check runs before the peek, which keeps it independent of the recovery
            // arm below: that arm has its own guard on `TokenRecovery::resume` (the arm
            // consumes no token, so only the resume position can move the stream), and it
            // moves the stream *after* this compare — so a recovered iteration reaches the
            // next head at its resume position, which its own guard already proved
            // different from the position recorded here. Stream positions compare only for
            // equality, so the check is "different", not "greater"; an empty-span token is
            // not the case being caught — a reader may serve one, provided its two ends
            // are distinct positions.
            let position = cx.tokens.position_here();
            if last_position.as_ref() == Some(&position) {
                return Err(cx.implementation_error_with_kind(
                    ImplementationErrorKind::StalledTokenReader,
                    alloc::format!(
                        "Inconsistent token reader: the stream position did not advance \
                         past the token read at {position:?}; every token other than \
                         ‘EndOfStream’ must advance the stream position"
                    ),
                    cx.here(),
                ));
            }
            last_position = Some(position);

            // Read one token. On a tokenizer error: strict mode aborts, tolerant mode
            // records the diagnostic and adopts the error's recovery — the placeholder
            // token below, with the reader repositioned to the explicit resume position
            // (so the error is never re-read; `recovered` marks that the reader must
            // not be moved for this token).
            let (token, recovered) = match cx.tokens.peek(&cx.state) {
                Ok(token) => (token, false),
                Err(error) => {
                    let kind = error.kind().clone();
                    // The error's location is already source-qualified: only the reader
                    // knows which source it was reading.
                    let span = error.span().clone();
                    match error.into_recovery() {
                        None => {
                            return Err(ParseError::from_token_error(kind, span)
                                .with_frames(cx.session.snapshot_frames()))
                        }
                        Some(recovery) => {
                            // The lift boxes the built-in token conditions and unwraps
                            // a `Custom` payload (never double-boxed) — [§dd-dr:errors].
                            cx.recover_boxed(kind.clone().into_condition(), span.clone())?;
                            // The recovery arm is the one arm that consumes no token,
                            // so loop progress rests entirely on the resume position
                            // moving the stream (the `TokenRecovery::resume`
                            // contract). A violating token source — a custom reader —
                            // would otherwise re-read the same error forever; degrade
                            // the hang into an abort, even in tolerant mode: its
                            // promise is a best-effort tree, not tolerance of
                            // non-termination. Stream positions compare only for
                            // equality, so the check is "different", not "greater".
                            let before = cx.tokens.position_here();
                            cx.tokens.move_to_position(&recovery.resume);
                            if cx.tokens.position_here() == before {
                                return Err(ParseError::from_token_error(kind, span)
                                    .with_frames(cx.session.snapshot_frames()));
                            }
                            (recovery.token, true)
                        }
                    }
                }
            };

            // Token stop condition — consulted for cleanly read tokens only: a recovery
            // placeholder is processed as content (its site already diagnosed it, and a
            // stop token that cannot be re-read cannot be left for the caller). A
            // predicate Err aborts under any policy, the live traceback attached
            // here — the callback has no session access.
            // The one query per iteration: what this token is. Where it is stays a
            // separate reader answer, asked for by the arms that need it.
            let kind = cx.tokens.token_kind(&token);

            if !recovered {
                if let Some(consume) = self
                    .token_stop(&cx.state, &token, kind, &*cx.tokens)
                    .map_err(|error| cx.attach_hook_frames(error))?
                {
                    self.flush_for_token_stop(cx, &token)?;
                    let span = cx.tokens.source_span_of(&token);
                    let after = cx.tokens.position_at(&token, TokenEdge::EndPastPostSpace);
                    if consume {
                        // Take the whole token, syntactic post-space included; its
                        // pre-space is already housed in the flushed sibling nodes.
                        cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
                    } else {
                        cx.tokens.move_to(&token, TokenEdge::Start);
                    }
                    return Ok((
                        self.outcome(&cx.state, StopCause::TokenCondition { span, after }),
                        None,
                    ));
                }
            }

            match kind {
                TokenKind::Char(c) => {
                    self.extend_run(cx, &token, c).map_err(|detail| {
                        let span = cx.tokens.source_span_of(&token);
                        cx.implementation_error_with_kind(
                            ImplementationErrorKind::TokenPositionMismatch,
                            detail,
                            span,
                        )
                    })?;
                    if !recovered {
                        cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
                    }
                }

                TokenKind::EndOfStream => {
                    // Invariant 4: the terminal token's pre-space is the input's
                    // trailing whitespace and reaches the tree.
                    let fired = self.flush_through(cx, &token)?;
                    if !recovered {
                        cx.tokens.move_to(&token, TokenEdge::Start);
                    }
                    let cause =
                        if fired { StopCause::NodeCondition } else { StopCause::EndOfInput };
                    return Ok((self.outcome(&cx.state, cause), None));
                }

                TokenKind::GroupClose { .. } => {
                    // A close the stop condition did not ask for: report it as data and
                    // let the caller decide ([§dd-dr:panic-policy] rule 2); the token stays unconsumed.
                    let fired = self.flush_through(cx, &token)?;
                    if !recovered {
                        cx.tokens.move_to(&token, TokenEdge::Start);
                    }
                    let cause = if fired {
                        StopCause::NodeCondition
                    } else {
                        StopCause::UnexpectedGroupClose {
                            span: cx.tokens.source_span_of(&token),
                            after: cx
                                .tokens
                                .position_at(&token, TokenEdge::EndPastPostSpace),
                        }
                    };
                    return Ok((self.outcome(&cx.state, cause), None));
                }

                TokenKind::ParagraphBreak => {
                    // Impossible under a language that declares paragraphs absent:
                    // the token source violated its contract (`TokenReader` docs) —
                    // an implementation bug aborts under any policy, never a panic.
                    if !<L::Features as LangFeatures>::Paragraphs::PRESENT {
                        return Err(cx.implementation_error_with_kind(
                            ImplementationErrorKind::UnexpectedToken,
                            "Invalid ‘ParagraphBreak’ token returned by the token reader: \
                             the language declares the paragraphs feature absent",
                            cx.tokens.source_span_of(&token),
                        ));
                    }
                    if self.flush_through(cx, &token)? {
                        if !recovered {
                            cx.tokens.move_to(&token, TokenEdge::Start);
                        }
                        return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                    }
                    // Invariant 2: the break is its own node — the hook's kind, staged
                    // by the loop over the full token span (a driver cannot stage nodes
                    // itself); runs never merge across it. The hook receives the
                    // break's span so a callable-shaped kind can record the break's
                    // actual spelling (name-as-written).
                    let span = cx.tokens.source_span_of(&token);
                    let kind = cx.driver.make_paragraph_break_node(&cx.state, &span);
                    if !recovered {
                        cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
                    }
                    if self.stage_node(cx, kind, span)? {
                        return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                    }
                }

                TokenKind::Comment { .. } => {
                    // Impossible under a language that declares comments absent: the
                    // token source violated its contract (`TokenReader` docs) — an
                    // implementation bug aborts under any policy, never a panic.
                    if !<L::Features as LangFeatures>::Comments::PRESENT {
                        return Err(cx.implementation_error_with_kind(
                            ImplementationErrorKind::UnexpectedToken,
                            "Invalid ‘Comment’ token returned by the token reader: \
                             the language declares the comments feature absent",
                            cx.tokens.source_span_of(&token),
                        ));
                    }
                    if self.flush_through(cx, &token)? {
                        if !recovered {
                            cx.tokens.move_to(&token, TokenEdge::Start);
                        }
                        return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                    }
                    let (kind, span) = comment_node_kind(cx, &token);
                    if !recovered {
                        cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
                    }
                    if self.stage_node(cx, kind, span)? {
                        return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                    }
                }

                TokenKind::Command { name, escape_char } => {
                    // Impossible under a language that declares commands absent: the
                    // token source violated its contract (`TokenReader` docs) — an
                    // implementation bug aborts under any policy, never a panic.
                    if !<L::Features as LangFeatures>::Commands::PRESENT {
                        return Err(cx.implementation_error_with_kind(
                            ImplementationErrorKind::UnexpectedToken,
                            "Invalid ‘Command’ token returned by the token reader: \
                             the language declares the commands feature absent",
                            cx.tokens.source_span_of(&token),
                        ));
                    }
                    // A recovery placeholder is never resolved or dispatched: a token
                    // with no real bytes behind it cannot be consumed by the arm. It is
                    // diagnosed as unusable and staged as chars, as for specials.
                    if recovered {
                        let condition = UnusableRecoveryToken::new(
                            alloc::format!("{escape_char}{name}"),
                            UnusableRecoveryTokenKind::Command,
                        );
                        if self.recover_as_chars(cx, &token, recovered, condition)? {
                            return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                        }
                        continue;
                    }
                    // Resolution runs under the loop's own state — coherent with the
                    // state that tokenized the token (resolution precedes policy,
                    // [§dd-dr:parsers-engine]). A hook Err aborts under any policy
                    // (resolve_command's contract); the recoverable channels are the
                    // Ok values.
                    let resolved = cx
                        .driver
                        .resolve_command(&cx.state, &token, &*cx.tokens)
                        .map_err(|error| cx.attach_hook_frames(error))?;
                    match resolved {
                        CommandResolution::Resolved(resolved) => {
                            if self.flush_through(cx, &token)? {
                                cx.tokens.move_to(&token, TokenEdge::Start);
                                return Ok((
                                    self.outcome(&cx.state, StopCause::NodeCondition),
                                    None,
                                ));
                            }
                            let invocation = Invocation {
                                callable_type: resolved.callable_type,
                                name,
                                spec: &resolved.spec,
                                token: &token,
                            };
                            if self.dispatch_invocation(cx, invocation)? {
                                return Ok((
                                    self.outcome(&cx.state, StopCause::NodeCondition),
                                    None,
                                ));
                            }
                        }
                        CommandResolution::Unresolved { detail } => {
                            // Unresolvable command ([§dd-dr:errors]): diagnostic plus span-backed
                            // chars fallback.
                            let condition =
                                UnresolvableCommand::new(name, escape_char, detail);
                            if self.recover_as_chars(cx, &token, recovered, condition)? {
                                return Ok((
                                    self.outcome(&cx.state, StopCause::NodeCondition),
                                    None,
                                ));
                            }
                        }
                        CommandResolution::Failed { detail } => {
                            // Operational resolver failure ([§dd-dr:errors]): a distinct condition
                            // from a clean miss, same span-backed chars recovery.
                            let condition =
                                CommandResolutionFailed::new(name, escape_char, detail);
                            if self.recover_as_chars(cx, &token, recovered, condition)? {
                                return Ok((
                                    self.outcome(&cx.state, StopCause::NodeCondition),
                                    None,
                                ));
                            }
                        }
                    }
                }

                TokenKind::Specials { callable_type, name, spec } => {
                    // Impossible under a language that declares specials absent: the
                    // token source violated its contract (`TokenReader` docs) — an
                    // implementation bug aborts under any policy, never a panic.
                    if !<L::Features as LangFeatures>::Specials::PRESENT {
                        return Err(cx.implementation_error_with_kind(
                            ImplementationErrorKind::UnexpectedToken,
                            "Invalid ‘Specials’ token returned by the token reader: \
                             the language declares the specials feature absent",
                            cx.tokens.source_span_of(&token),
                        ));
                    }
                    // Recognition = resolution: the token carries the full resolution
                    // (callable type + spec). Recovery placeholders are never
                    // dispatched.
                    if recovered {
                        let condition = UnusableRecoveryToken::new(
                            name,
                            UnusableRecoveryTokenKind::Specials,
                        );
                        if self.recover_as_chars(cx, &token, recovered, condition)? {
                            return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                        }
                        continue;
                    }
                    if self.flush_through(cx, &token)? {
                        cx.tokens.move_to(&token, TokenEdge::Start);
                        return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                    }
                    let invocation =
                        Invocation { callable_type, name, spec, token: &token };
                    if self.dispatch_invocation(cx, invocation)? {
                        return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                    }
                }

                TokenKind::GroupOpen { delim, rule } => {
                    // Impossible under a language that declares groups absent: the
                    // token source violated its contract (`TokenReader` docs) — an
                    // implementation bug aborts under any policy, never a panic.
                    if !<L::Features as LangFeatures>::Groups::PRESENT {
                        return Err(cx.implementation_error_with_kind(
                            ImplementationErrorKind::UnexpectedToken,
                            "Invalid ‘GroupOpen’ token returned by the token reader: \
                             the language declares the groups feature absent",
                            cx.tokens.source_span_of(&token),
                        ));
                    }
                    // A recovery placeholder GroupOpen (no current TokenRecovery emits
                    // one) has no real bytes behind it and cannot be parsed as a group:
                    // chars fallback, reader untouched.
                    if recovered {
                        let condition = UnusableRecoveryToken::new(
                            delim,
                            UnusableRecoveryTokenKind::GroupOpen,
                        );
                        if self.recover_as_chars(cx, &token, recovered, condition)? {
                            return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                        }
                        continue;
                    }
                    if self.flush_through(cx, &token)? {
                        cx.tokens.move_to(&token, TokenEdge::Start);
                        return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                    }
                    // The interior's *base* state per the descent policy (the group
                    // parser derives expecting_group_close from it); `Arc` in, `Arc`
                    // out — pass-through policies preserve pointer identity. A
                    // failing Compute aborts under any policy (the hook fallibility
                    // contract), with the live traceback attached here.
                    let base = match &self.child_states.group {
                        GroupChildState::Inherit => Arc::clone(&cx.state),
                        GroupChildState::Fixed(state) => Arc::clone(state),
                        GroupChildState::Compute(compute) => {
                            compute(&cx.state, &token, &*cx.tokens)
                                .map_err(|error| cx.attach_hook_frames(error))?
                        }
                    };
                    // Consume the trigger token here, at the site that peeked it and
                    // under the state that tokenized it (the at-match-time atomicity
                    // rule); the group parser gets its two facts — open span and rule.
                    cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
                    // The parser's input state is the policy's answer, scoped to the
                    // descent; the parser itself comes from the driver's factory
                    // (Phase 7.2 uniform routing).
                    let (id, delta) = cx.parse_group(
                        base,
                        &token,
                        Arc::clone(rule),
                        ChildStateSpec::inherit(),
                        None,
                    )?;
                    self.nodes.push(id);
                    if let Some(delta) = delta {
                        // A group that leaks an after-effect (the `\gdef` shape — a
                        // language installs
                        // [`GroupAfterEffectsFn`](super::GroupAfterEffectsFn) through its
                        // `make_group_parser`; the standard group returns `None` here).
                        // Applied and recorded exactly like an invocation's after-effect:
                        // to the loop's own state, so it holds for the following
                        // siblings, and into this run's merged record — which is what
                        // makes an escape compose outward, one level per enclosing group's
                        // own hook.
                        cx.state = cx.derive_state_recording(&delta, &mut self.after_effects)?;
                    }
                    if self.test_node_stop(cx, id)? {
                        return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
                    }
                }
            }
        }
    }
}

/// Returns the group class a close delimiter belongs to under `state`'s rules, or
/// `None` when the delimiter belongs to no close rule in scope.
///
/// The expected close takes precedence, then the delimiter table — the same priority the
/// tokenizer applies in
/// [`scan_group_delimiter`](crate::core::token::scan_group_delimiter).
fn group_close_type<L: Lang>(state: &ParsingState<L>, delim: &str) -> Option<L::GroupTypeId> {
    if let Some(rule) = state.rules().expecting_group_close() {
        if rule.close == delim {
            return Some(rule.group_type);
        }
    }
    state
        .prefix_table() // `None` when the language declares the groups feature absent
        .and_then(|table| table.match_at(delim))
        .filter(|entry| entry.delim() == delim)
        .and_then(|entry| entry.close())
        .map(|rule| rule.group_type)
}

// Manual impls: predicates have no useful Debug, and derives would demand `L:` bounds.

impl<L: Lang> fmt::Debug for TokenStopKind<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TokenStopKind::Command { name } => {
                f.debug_struct("Command").field("name", name).finish()
            }
            TokenStopKind::GroupClose { group_type, close } => f
                .debug_struct("GroupClose")
                .field("group_type", group_type)
                .field("close", close)
                .finish(),
            TokenStopKind::ParagraphBreak => write!(f, "ParagraphBreak"),
            TokenStopKind::Predicate(_) => write!(f, "Predicate(..)"),
        }
    }
}

impl<L: Lang> fmt::Debug for TokenStopCondition<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TokenStopCondition")
            .field("kind", &self.kind)
            .field("consume", &self.consume)
            .finish()
    }
}

impl<L: Lang> fmt::Debug for StopSpec<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StopSpec")
            .field("token", &self.token)
            .field("node", &self.node.as_ref().map(|_| "FnMut(..)"))
            .finish()
    }
}

impl<L: Lang> fmt::Debug for NodesParser<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NodesParser")
            .field("stop", &self.stop)
            .field("nodes", &self.nodes.len())
            .field("run", &self.run)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::source::Span;
    use crate::constructs::tests::{relaxed_driver, RelaxedStdLang, RELAXED_MACRO};
    use crate::engine::{
        resolve_command_in_scopes, ParseResult, ParserSession, ScopesCommandResolver,
        StdParseDriver,
    };
    use crate::error::Recovery;
    use crate::scopes::{
        CallableQuery, CallableSyntax, Package, ProviderError, ScopeStack, SpecsProvider,
    };
    use crate::node::GroupData;
    use crate::source::{Source, SourcePos, TextContent};
    use crate::spec::{ArgumentSpec, CallableSpec, StdCallableSpec};
    use super::super::argument_parsers::{GroupArgumentParser, MarkerArgumentParser};
    use super::super::{InvocationChildState, StdInvocationParser};
    use crate::state::{
        CommentOverrides, NodeExtTypes, TrivialLang, StateData, TokenRulesOverrides,
    };
    use crate::token::{
        CommandRule, CommandRules, CommentRule, CommentRules, ForbiddenCharsRules, GroupRule,
        GroupRules, ParagraphRules, SpecialsMatch, SpecialsRules, SpecialsScanError,
        StdStreamPosition, StdToken, StdTokenReader, TokenEdge, TokenError,
        TokenErrorKind, TokenKind, TokenListReader, TokenReader,
        TokenRecovery, TokenResult, TokenRules, Tokenization, TriggerChars, WhitespaceRules,
    };
    use alloc::boxed::Box;
    use alloc::string::ToString;

    const GT_BRACE: u32 = 0;
    const GT_MATH: u32 = 1;
    const CT_MACRO: u32 = 10;
    const CT_SPECIALS: u32 = 11;

    #[derive(Debug, Clone, Copy)]
    struct TestLang;
    impl TrivialLang for TestLang {}

    /// The preset resolution pattern, shared by the 6.4 test langs: dispatch a
    /// `Command` token to the state's scope stack under the `CT_MACRO` form. Delegates
    /// to the standard [`resolve_command_in_scopes`] so the test langs and
    /// the latexlike preset share one query-and-dispatch implementation.
    fn resolve_macro_in_scopes<L: Lang<CallableTypeId = u32>>(
        state: &ParsingState<L>,
        token: &Token<L>,
        tokens: &dyn TokenReader<'_, L>,
    ) -> Result<CommandResolution<L>, ParseError<L::SourceOrigin>> {
        Ok(resolve_command_in_scopes(state, token, tokens, CT_MACRO))
    }

    /// Test-side driver factory: the generic run helpers construct each lang's
    /// driver from the recovery setting alone (drivers carry the policy).
    trait TestDriver {
        fn with_recovery(recovery: Recovery) -> Self;
    }

    impl TestDriver for StdParseDriver {
        fn with_recovery(recovery: Recovery) -> Self {
            StdParseDriver::new(recovery, ())
        }
    }

    /// Test lang resolving `Command` tokens against the state's libraries under the
    /// `CT_MACRO` form (the resolution hook is on the driver).
    #[derive(Debug, Clone, Copy)]
    struct CmdLang;
    impl Lang for CmdLang {
        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 = CmdDriver;
        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, Clone, Copy)]
    struct CmdDriver {
        recovery: Recovery,
    }

    impl TestDriver for CmdDriver {
        fn with_recovery(recovery: Recovery) -> Self {
            CmdDriver { recovery }
        }
    }

    impl ParseDriver<CmdLang> for CmdDriver {
        fn recovery(&self) -> Recovery {
            self.recovery
        }

        fn resolve_command(
            &self,
            state: &ParsingState<CmdLang>,
            token: &StdToken<CmdLang>,
            tokens: &dyn TokenReader<'_, CmdLang>,
        ) -> Result<CommandResolution<CmdLang>, ParseError> {
            resolve_macro_in_scopes(state, token, tokens)
        }
    }

    /// Test lang recognizing `~` as a specials trigger resolving to a zero-arg spec
    /// under the `CT_SPECIALS` form.
    #[derive(Debug, Clone, Copy)]
    struct TildeLang;
    impl Lang for TildeLang {
        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 scan_specials(
            _state: &ParsingState<Self>,
            content: &str,
            pos: usize,
        ) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
            if content[pos..].starts_with('~') {
                Ok(Some(SpecialsMatch {
                    end: pos + 1,
                    callable_type: CT_SPECIALS,
                    spec: Arc::new(StdCallableSpec::default()),
                }))
            } else {
                Ok(None)
            }
        }

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

    /// A library defining each of `names` as a zero-arg `CT_MACRO` callable (all of them
    /// sharing one spec value).
    fn macro_library<L: Lang<CallableTypeId = u32> + 'static>(names: &[&str]) -> Arc<Package<L>> {
        let mut lib = Package::new("test-macros");
        let spec: Arc<dyn CallableSpec<L>> = Arc::new(StdCallableSpec::default());
        for name in names {
            lib.insert(CT_MACRO, *name, Arc::clone(&spec));
        }
        Arc::new(lib)
    }

    /// A `CmdLang` state whose library stack defines `names` as zero-arg macros.
    fn state_with_macros(names: &[&str]) -> Arc<ParsingState<CmdLang>> {
        let mut scopes = ScopeStack::new();
        scopes.push(macro_library(names));
        Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }))
    }

    fn math_rule<L: Lang<GroupTypeId = u32>>() -> Arc<GroupRule<L>> {
        Arc::new(GroupRule { group_type: GT_MATH, open: "$".into(), close: "$".into() })
    }

    // `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 rules<L: Lang<GroupTypeId = u32, Features = crate::state::AllLangFeatures>>(
    ) -> TokenRules<L> {
        TokenRules {
            whitespace: WhitespaceRules { enabled: true, chars: " \t\n".into() },
            paragraphs: ParagraphRules { enabled: true },
            groups: GroupRules {
                enabled: true,
                rules: vec![Arc::new(GroupRule {
                    group_type: GT_BRACE,
                    open: "{".into(),
                    close: "}".into(),
                })],
                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 state_with<L: Lang<GroupTypeId = u32, StateExt = ()>>(
        rules: TokenRules<L>,
    ) -> Arc<ParsingState<L>> {
        Arc::new(ParsingState::new(StateData {
            rules,
            scopes: ScopeStack::new(),
            mode: Default::default(),
            ext: (),
        }))
    }

    fn state() -> Arc<ParsingState<TestLang>> {
        state_with(rules())
    }

    // --- harness ------------------------------------------------------------------------

    struct Parsed<L: Lang> {
        result: ParseResult<L>,
        stop: StopCause<L>,
        /// The reader's exit position, as a byte offset (for assertions).
        pos: usize,
        /// The reader's exit position itself — what a test resumes a fresh reader
        /// over the same content from.
        position: StreamPosition<L>,
    }

    /// A stop cause rendered for assertions: the variant, plus the matched span's
    /// byte range where the variant carries one. (The `after` position is opaque;
    /// tests that care about it resume the reader from it.)
    fn stop_shape<L: Lang>(stop: &StopCause<L>) -> String {
        match stop {
            StopCause::TokenCondition { span, .. } => {
                alloc::format!("token {:?}", span.range())
            }
            StopCause::UnexpectedGroupClose { span, .. } => {
                alloc::format!("close {:?}", span.range())
            }
            StopCause::NodeCondition => String::from("node"),
            StopCause::EndOfInput => String::from("end of input"),
        }
    }

    impl<L: Lang> fmt::Debug for Parsed<L> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("Parsed")
                .field("shapes", &shapes(&self.result))
                .field("stop", &self.stop)
                .field("pos", &self.pos)
                .field("position", &self.position)
                .finish()
        }
    }

    /// Drive a `NodesParser` over `tokens`, stage the outcome under a root `List`
    /// spanning exactly the parsed extent, freeze, and run the invariant checker over
    /// the finished tree. The reader must be reading `content`.
    fn try_run<'s, L: Lang<SourceOrigin = Option<String>>>(
        source: &'s Arc<Source>,
        tokens: &mut dyn TokenReader<'s, L>,
        state: &Arc<ParsingState<L>>,
        recovery: Recovery,
        stop: StopSpec<'_, L>,
    ) -> Result<Parsed<L>, ParseError>
    where
        L::Driver: TestDriver,
        L::InvocationSyntax: FromInvocation<L>,
    {
        try_run_with(source, tokens, state, recovery, stop, ChildStateSpec::inherit())
    }

    /// [`try_run`] with an explicit descent-state policy.
    fn try_run_with<'s, 'p, L: Lang<SourceOrigin = Option<String>>>(
        source: &'s Arc<Source>,
        tokens: &mut dyn TokenReader<'s, L>,
        state: &Arc<ParsingState<L>>,
        recovery: Recovery,
        stop: StopSpec<'p, L>,
        child_states: ChildStateSpec<'p, L>,
    ) -> Result<Parsed<L>, ParseError>
    where
        L::Driver: TestDriver,
        L::InvocationSyntax: FromInvocation<L>,
    {
        let mut session = ParserSession::new();
        let driver = L::Driver::with_recovery(recovery);
        let mut cx =
            ParseContext::new(tokens, Arc::clone(state), &mut session, &driver);
        let mut parser = NodesParser::new(stop).with_child_states(child_states);
        let (outcome, delta) = parser.parse(&mut cx)?;
        assert!(delta.is_none(), "NodesParser returns no pass-through delta");
        // The reader's exit position: as a byte offset (for assertions) and as
        // itself (for resuming).
        let position = cx.tokens.position_here();
        let pos = cx.here().start();
        // The root `List` spans exactly the parsed extent (its content interior — the
        // tiling the checker verifies); a consumed stop token lies outside.
        let root_span = {
            let staged = session.builder.staged_nodes();
            match (outcome.nodes.first(), outcome.nodes.last()) {
                (Some(&first), Some(&last)) => Span::new(
                    staged.get(first).unwrap().span().start(),
                    staged.get(last).unwrap().span().end(),
                ),
                _ => Span::empty(0),
            }
        };
        let root = {
            // The generic test harness stages its root list via the explicit recipe
            // (the harness plays the transform-author role here).
            let kind = NodeKind::list();
            let span = SourceSpan::new(source, root_span);
            let ext = L::make_node_ext(
                &kind,
                &span,
                state,
                session.builder.staged_children(&outcome.nodes),
            )
            .expect("mint node ext");
            session.builder.add(kind, span, Arc::clone(state), outcome.nodes, ext, ()).unwrap()
        };
        let result = session.finish(root).unwrap();
        crate::node::check_tree_invariants(&result.tree);
        Ok(Parsed { result, stop: outcome.stop, pos, position })
    }

    /// Scan `source` into the full token list (including the terminal `EndOfStream`).
    fn scan<L>(source: &Arc<Source>, state: &Arc<ParsingState<L>>) -> Vec<Token<L>>
    where
        L: Lang<SourceOrigin = Option<String>>,
        L::Tokenization:
            Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
    {
        let mut reader = StdTokenReader::new(source);
        let mut tokens = Vec::new();
        loop {
            let token = TokenReader::next(&mut reader, state).expect("clean scan");
            let reader_ref: &dyn TokenReader<'_, L> = &reader;
            let done = matches!(reader_ref.token_kind(&token), TokenKind::EndOfStream);
            tokens.push(token);
            if done {
                break;
            }
        }
        tokens
    }

    /// Run the same parse against `StdTokenReader` and `TokenListReader` (report R6) and
    /// assert they agree on shapes, stop cause, position, and diagnostics count. The two
    /// stop specs must be equivalent (node predicates are `&mut`, so each run needs its
    /// own).
    fn run_both<'p, L>(
        content: &str,
        state: &Arc<ParsingState<L>>,
        recovery: Recovery,
        stop_std: StopSpec<'p, L>,
        stop_list: StopSpec<'p, L>,
    ) -> Parsed<L>
    where
        L: Lang<SourceOrigin = Option<String>>,
        L::Tokenization:
            Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
        L::Driver: TestDriver,
        L::InvocationSyntax: FromInvocation<L>,
    {
        run_both_with(content, state, recovery, stop_std, stop_list, ChildStateSpec::inherit())
    }

    /// [`run_both`] with an explicit descent-state policy (cloned per reader — it is
    /// shallow: `Arc`s and borrows).
    fn run_both_with<'p, L>(
        content: &str,
        state: &Arc<ParsingState<L>>,
        recovery: Recovery,
        stop_std: StopSpec<'p, L>,
        stop_list: StopSpec<'p, L>,
        child_states: ChildStateSpec<'p, L>,
    ) -> Parsed<L>
    where
        L: Lang<SourceOrigin = Option<String>>,
        L::Tokenization:
            Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
        L::Driver: TestDriver,
        L::InvocationSyntax: FromInvocation<L>,
    {
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut std_reader = StdTokenReader::new(&source);
        let a = try_run_with(
            &source,
            &mut std_reader,
            state,
            recovery,
            stop_std,
            child_states.clone(),
        )
        .expect("std reader");
        let mut list_reader = TokenListReader::new(&source, scan(&source, state));
        let b =
            try_run_with(&source, &mut list_reader, state, recovery, stop_list, child_states)
                .expect("list reader");
        assert_eq!(shapes(&a.result), shapes(&b.result), "readers disagree on {:?}", content);
        assert_eq!(a.stop, b.stop, "stop causes disagree on {:?}", content);
        assert_eq!(a.pos, b.pos, "positions disagree on {:?}", content);
        assert_eq!(a.result.diagnostics.len(), b.result.diagnostics.len());
        a
    }

    /// One readable line per root child: kind, exact span, resolved contents.
    fn shapes<L: Lang>(result: &ParseResult<L>) -> Vec<String> {
        result
            .tree
            .root()
            .children()
            .iter().map(|node| {
                let span = format!("{}..{}", node.span().start(), node.span().end());
                match node.kind() {
                    NodeKind::Chars { .. } => {
                        format!("chars {} {:?}", span, node.chars().unwrap())
                    }
                    NodeKind::Comment(_) => {
                        let data = node.comment().unwrap();
                        format!(
                            "comment {} start={:?} content={:?} post={:?}",
                            span,
                            data.start.resolve(node.source()),
                            data.content.resolve(node.source()),
                            data.post_space.resolve(node.source())
                        )
                    }
                    NodeKind::Group(_) => format!("group {}", span),
                    NodeKind::Callable(_) => format!("callable {}", span),
                    NodeKind::List => format!("list {}", span),
                }
            })
            .collect()
    }

    /// Span tiling at the root (the byte accounting of
    /// [`check_tree_invariants`](crate::node::check_tree_invariants)): the root's
    /// children tile `interior` exactly — no gaps, no double counting.
    fn assert_partition<L: Lang>(result: &ParseResult<L>, interior: core::ops::Range<usize>) {
        let mut pos = interior.start;
        for child in result.tree.root().children() {
            assert_eq!(child.span().start(), pos, "gap before a sibling: {:?}", shapes(result));
            pos = child.span().end();
        }
        assert_eq!(pos, interior.end, "siblings fall short: {:?}", shapes(result));
    }

    // --- content shapes (invariants 1–4) --------------------------------------------------

    #[test]
    fn empty_input_is_an_empty_list() {
        let st = state();
        let parsed = run_both("", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_eq!(parsed.result.tree.root().child_count(), 0);
        assert_eq!(parsed.pos, 0);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn chars_accumulate_into_one_maximal_node() {
        let st = state();
        let parsed =
            run_both("ab cd", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["chars 0..5 \"ab cd\""]);
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_eq!(parsed.pos, 5);
        assert_partition(&parsed.result, 0..5);
    }

    #[test]
    fn leading_and_trailing_whitespace_joins_the_run() {
        let st = state();
        let parsed =
            run_both("  ab  ", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["chars 0..6 \"  ab  \""]);
        assert_eq!(parsed.pos, 6);
        assert_partition(&parsed.result, 0..6);
    }

    #[test]
    fn whitespace_only_input_is_a_whitespace_chars_node() {
        let st = state();
        let parsed = run_both("  ", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"  \""]);
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_partition(&parsed.result, 0..2);
    }

    #[test]
    fn paragraph_break_gets_its_own_node_runs_do_not_merge_across() {
        let st = state();
        let parsed =
            run_both("a \n \n b", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        // The break token spans first through last newline; the whitespace before it
        // joins the preceding run, the whitespace after it the following run.
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"a \"", "chars 2..5 \"\\n \\n\"", "chars 5..7 \" b\""]
        );
        assert_partition(&parsed.result, 0..7);
    }

    #[test]
    fn paragraph_break_node_comes_from_the_driver_hook() {
        #[derive(Debug, Clone, Copy)]
        struct MarkLang;
        impl Lang for MarkLang {
            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 = MarkDriver;
            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, Clone, Copy)]
        struct MarkDriver {
            recovery: Recovery,
        }

        impl TestDriver for MarkDriver {
            fn with_recovery(recovery: Recovery) -> Self {
                MarkDriver { recovery }
            }
        }

        impl ParseDriver<MarkLang> for MarkDriver {
            fn recovery(&self) -> Recovery {
                self.recovery
            }

            fn make_paragraph_break_node(
                &self,
                _state: &ParsingState<MarkLang>,
                _break_span: &SourceSpan,
            ) -> NodeKind<MarkLang> {
                NodeKind::chars("¶") // owned content, unlike the spanned default
            }
        }

        let st = state_with(rules::<MarkLang>());
        let parsed =
            run_both("a\n\nb", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..1 \"a\"", "chars 1..3 \"¶\"", "chars 3..4 \"b\""]
        );
        // The loop stages the hook's kind as-is, over the token's span.
        let break_node = parsed.result.tree.root().child(1).unwrap();
        assert!(matches!(
            break_node.kind(),
            NodeKind::Chars { content: TextContent::Owned(_), .. }
        ));
        assert_partition(&parsed.result, 0..4);
    }

    #[test]
    fn comment_node_records_start_content_and_post_space() {
        let st = state();
        let parsed = run_both(
            "x % note\n  y",
            &st,
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
        );
        assert_eq!(
            shapes(&parsed.result),
            [
                "chars 0..2 \"x \"",
                "comment 2..11 start=\"%\" content=\" note\" post=\"\\n  \"",
                "chars 11..12 \"y\"",
            ]
        );
        assert_partition(&parsed.result, 0..12);
    }

    #[test]
    fn comment_bordering_a_paragraph_break_has_empty_post_space() {
        let st = state();
        let parsed =
            run_both("x %n\n\ny", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            [
                "chars 0..2 \"x \"",
                "comment 2..4 start=\"%\" content=\"n\" post=\"\"",
                "chars 4..6 \"\\n\\n\"",
                "chars 6..7 \"y\"",
            ]
        );
        assert_partition(&parsed.result, 0..7);
    }

    #[test]
    fn comment_at_end_of_input() {
        let st = state();
        let parsed =
            run_both("x %n", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"x \"", "comment 2..4 start=\"%\" content=\"n\" post=\"\""]
        );
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_partition(&parsed.result, 0..4);
    }

    // --- stop conditions -------------------------------------------------------------------

    #[test]
    fn stop_at_command_leaves_the_token_peekable_with_pre_space_housed() {
        let st = state();
        let content = "ab \\end rest";
        let parsed = run_both(
            content,
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
            StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
        );
        // The stop token's pre-space is interior content: it lands in the flushed run.
        assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
        // The reported span covers the whole `\end` token (name + terminating space).
        assert_eq!(stop_shape(&parsed.stop), "token 3..8");
        assert_eq!(parsed.pos, 3);

        // Re-peeking from the seam yields the stop token itself, with empty pre-space —
        // no byte is represented twice.
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        TokenReader::<'_, TestLang>::move_to_position(&mut reader, &parsed.position);
        let token: StdToken<TestLang> = TokenReader::peek(&mut reader, &st).unwrap();
        let reader: &dyn TokenReader<'_, TestLang> = &reader;
        assert!(matches!(
            reader.token_kind(&token),
            TokenKind::Command { name: "end", .. }
        ));
        assert!(reader
            .source_span_between(&token, TokenEdge::StartBeforePreSpace, TokenEdge::Start)
            .is_empty());
    }

    #[test]
    fn the_stop_causes_after_position_skips_the_unconsumed_token() {
        // An unconsumed stop token sits at its own start; the cause's `after`
        // position is where a caller that skips it resumes — no re-peek needed.
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("ab}c"));
        let mut reader = StdTokenReader::new(&source);
        let parsed: Parsed<TestLang> =
            try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap();
        let StopCause::UnexpectedGroupClose { span, after } = parsed.stop else {
            panic!("expected an unexpected group close");
        };
        assert_eq!(span.range(), 2..3);
        assert_eq!(span.content(), "}");
        // The close is left unconsumed, at its own start …
        assert_eq!(parsed.pos, 2);
        // … and `after` stands just past it.
        TokenReader::<'_, TestLang>::move_to_position(&mut reader, &after);
        let token: StdToken<TestLang> = TokenReader::peek(&mut reader, &st).unwrap();
        let reader_ref: &dyn TokenReader<'_, TestLang> = &reader;
        assert!(matches!(reader_ref.token_kind(&token), TokenKind::Char('c')));
    }

    #[test]
    fn lone_pre_space_before_a_stop_token_becomes_a_whitespace_node() {
        let st = state();
        let parsed = run_both(
            " \\end",
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
            StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..1 \" \""]);
        assert_eq!(stop_shape(&parsed.stop), "token 1..5");
        assert_eq!(parsed.pos, 1);
    }

    #[test]
    fn stop_at_group_close_produced_by_the_delimiter_table() {
        let st = state();
        let parsed = run_both(
            "ab}c",
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
        assert_eq!(stop_shape(&parsed.stop), "token 2..3");
        assert_eq!(parsed.pos, 2);
    }

    #[test]
    fn stop_at_group_close_produced_by_the_expected_close() {
        // `$` closes only through `expecting_group_close` (ambiguous delimiter read as
        // an opener otherwise) — the 6.3 group parser's configuration, exercised here.
        let mut r = rules::<TestLang>();
        r.groups.rules.push(math_rule());
        r.groups.expecting_close = Some(math_rule());
        let st = state_with(r);
        let parsed = run_both(
            "a b$c",
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_MATH, close: "$" }, false),
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_MATH, close: "$" }, false),
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..3 \"a b\""]);
        assert_eq!(stop_shape(&parsed.stop), "token 3..4");
        assert_eq!(parsed.pos, 3);
    }

    #[test]
    fn group_close_of_a_different_delimiter_is_unexpected() {
        // The stop condition waits for the math `$` close; a `}` arrives: the delimiter
        // does not match — reported as data, token unconsumed, no diagnostic (the caller
        // decides).
        let mut r = rules::<TestLang>();
        r.groups.rules.push(math_rule());
        r.groups.expecting_close = Some(math_rule());
        let st = state_with(r);
        let parsed = run_both(
            "ab}c",
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_MATH, close: "$" }, false),
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_MATH, close: "$" }, false),
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
        assert_eq!(stop_shape(&parsed.stop), "close 2..3");
        assert_eq!(parsed.pos, 2);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn group_close_of_a_shared_class_but_different_delimiter_is_unexpected() {
        // `[`/`]` and `{`/`}` share the class GT_BRACE. A group opened with `{` must not
        // be closed by a `]`: same class, different delimiter — the `close` field
        // disambiguates within a class.
        let mut r = rules::<TestLang>();
        r.groups.rules.push(Arc::new(GroupRule {
            group_type: GT_BRACE,
            open: "[".into(),
            close: "]".into(),
        }));
        let st = state_with(r);
        let parsed = run_both(
            "ab]c",
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
        assert_eq!(stop_shape(&parsed.stop), "close 2..3");
        assert_eq!(parsed.pos, 2);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn group_close_reclassified_to_another_class_is_unexpected() {
        // A `{`-opened GT_BRACE group; a state delta has re-classed `}` to close a
        // GT_MATH group (same delimiter, different class). The `}` must not close the
        // GT_BRACE group: `group_type` disambiguates within a delimiter spelling. Modeled
        // by an `expecting_group_close` whose close is `}` but whose class is GT_MATH.
        let mut r = rules::<TestLang>();
        r.groups.expecting_close = Some(Arc::new(GroupRule {
            group_type: GT_MATH,
            open: "{".into(),
            close: "}".into(),
        }));
        let st = state_with(r);
        let parsed = run_both(
            "ab}c",
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
        assert_eq!(stop_shape(&parsed.stop), "close 2..3");
        assert_eq!(parsed.pos, 2);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn group_close_without_any_stop_condition_is_unexpected() {
        let st = state();
        let parsed =
            run_both("ab}c", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
        assert_eq!(stop_shape(&parsed.stop), "close 2..3");
        assert_eq!(parsed.pos, 2);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn stop_at_paragraph_break() {
        let st = state();
        let parsed = run_both(
            "ab\n\ncd",
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::ParagraphBreak, false),
            StopSpec::at_token(TokenStopKind::ParagraphBreak, false),
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
        assert_eq!(stop_shape(&parsed.stop), "token 2..4");
        assert_eq!(parsed.pos, 2);
    }

    #[test]
    fn stop_at_a_token_predicate() {
        let st = state();
        // The predicate reads the token through the reader it is handed.
        let predicate = |token: &StdToken<TestLang>,
                         tokens: &dyn TokenReader<'_, TestLang>| {
            Ok(matches!(tokens.token_kind(token), TokenKind::Comment { .. }))
        };
        let parsed = run_both(
            "ab %c\nd",
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::Predicate(&predicate), false),
            StopSpec::at_token(TokenStopKind::Predicate(&predicate), false),
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
        assert_eq!(stop_shape(&parsed.stop), "token 3..6");
        assert_eq!(parsed.pos, 3);
    }

    #[test]
    fn a_failing_stop_predicate_aborts_under_any_policy() {
        // The hook-fallibility contract on `TokenStopKind::Predicate`: an Err ends
        // the parse even under tolerant recovery — a predicate that cannot answer
        // leaves no sound way to decide where the run ends — and the consultation
        // site attaches the live traceback (the predicate has no session access).
        let st = state();
        let failing = |_: &StdToken<TestLang>,
                       _: &dyn TokenReader<'_, TestLang>|
         -> Result<bool, ParseError> {
            let scratch: Arc<Source> = Arc::new(Source::new(""));
            Err(ParseError::new(
                crate::error::HookFailed::new("stop table unavailable", None),
                SourceSpan::new(&scratch, 0..0),
            ))
        };
        let content = "ab";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let mut session: ParserSession<TestLang> = ParserSession::new();
        let driver: StdParseDriver = StdParseDriver::new(Recovery::Tolerant, ());
        let mut cx = ParseContext::new(
            &mut reader,
            Arc::clone(&st),
            &mut session,
            &driver);
        let mut parser = NodesParser::new(StopSpec::at_token(
            TokenStopKind::Predicate(&failing),
            false,
        ));
        let frame = crate::engine::Frame {
            title: crate::engine::FrameTitle::Static("test descent"),
            span: SourceSpan::new(&source, 0..0),
        };
        let error = cx.with_frame(frame, |cx| parser.parse(cx)).unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        assert_eq!(
            error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
            Some("stop table unavailable")
        );
        // The live traceback, attached at the consultation site.
        assert_eq!(error.frames().len(), 1);
        assert_eq!(error.frames()[0].title(), "test descent");
    }

    #[test]
    fn consume_flag_swallows_a_command_stop_token_with_its_post_space() {
        let st = state();
        let content = "ab \\end rest";
        let parsed = run_both(
            content,
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::Command { name: "end" }, true),
            StopSpec::at_token(TokenStopKind::Command { name: "end" }, true),
        );
        // Same sibling content as the leave-it case; the command's terminating space is
        // syntactic post-space, taken with the token — so the reader lands past it (8),
        // not at the token start (3).
        assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
        assert_eq!(stop_shape(&parsed.stop), "token 3..8");
        assert_eq!(parsed.pos, 8);

        // The next read is the following content, its pre-space empty (nothing re-read).
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        TokenReader::<'_, TestLang>::move_to_position(&mut reader, &parsed.position);
        let token: StdToken<TestLang> = TokenReader::peek(&mut reader, &st).unwrap();
        let reader: &dyn TokenReader<'_, TestLang> = &reader;
        assert!(matches!(reader.token_kind(&token), TokenKind::Char('r')));
        assert!(reader
            .source_span_between(&token, TokenEdge::StartBeforePreSpace, TokenEdge::Start)
            .is_empty());
    }

    #[test]
    fn consume_flag_swallows_a_group_close_stop_token() {
        let st = state();
        let parsed = run_both(
            "ab} c",
            &st,
            Recovery::Strict,
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, true),
            StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, true),
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
        assert_eq!(stop_shape(&parsed.stop), "token 2..3");
        // The close is consumed (reader past `}`); `}` carries no post-space, so the
        // following space is not the close's — it stays for the enclosing content as the
        // next token's pre-space, unclaimed here.
        assert_eq!(parsed.pos, 3);
    }

    #[test]
    fn node_condition_stops_after_a_flushed_chars_node() {
        let st = state();
        let mut c1 = |count: usize, _: StagedNodeView<'_, TestLang>| Ok(count >= 1);
        let mut c2 = |count: usize, _: StagedNodeView<'_, TestLang>| Ok(count >= 1);
        let parsed = run_both(
            "ab %c\nde",
            &st,
            Recovery::Strict,
            StopSpec { token: None, node: Some(&mut c1) },
            StopSpec { token: None, node: Some(&mut c2) },
        );
        // The comment token triggered the flush; the condition fired on the flushed
        // node, so the comment stays unconsumed at its own start.
        assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
        assert_eq!(parsed.stop, StopCause::NodeCondition);
        assert_eq!(parsed.pos, 3);
        assert_partition(&parsed.result, 0..3);
    }

    #[test]
    fn node_condition_stops_after_a_directly_staged_node() {
        let st = state();
        let mut c1 = |count: usize, view: StagedNodeView<'_, TestLang>| {
            Ok(count >= 1 && matches!(view.kind(), NodeKind::Comment { .. }))
        };
        let mut c2 = |count: usize, view: StagedNodeView<'_, TestLang>| {
            Ok(count >= 1 && matches!(view.kind(), NodeKind::Comment { .. }))
        };
        let parsed = run_both(
            "%c\nab",
            &st,
            Recovery::Strict,
            StopSpec { token: None, node: Some(&mut c1) },
            StopSpec { token: None, node: Some(&mut c2) },
        );
        // The triggering node is included, and the parse stops right after it — the
        // comment token was consumed (post-space and all).
        assert_eq!(
            shapes(&parsed.result),
            ["comment 0..3 start=\"%\" content=\"c\" post=\"\\n\""]
        );
        assert_eq!(parsed.stop, StopCause::NodeCondition);
        assert_eq!(parsed.pos, 3);
    }

    #[test]
    fn node_condition_on_the_trailing_whitespace_node_wins_over_end_of_input() {
        let st = state();
        let mut c1 = |count: usize, _: StagedNodeView<'_, TestLang>| Ok(count >= 1);
        let mut c2 = |count: usize, _: StagedNodeView<'_, TestLang>| Ok(count >= 1);
        let parsed = run_both(
            "ab",
            &st,
            Recovery::Strict,
            StopSpec { token: None, node: Some(&mut c1) },
            StopSpec { token: None, node: Some(&mut c2) },
        );
        // The final flush (at end of stream) staged the only node; the node condition
        // fired on it, so the cause is the condition, not EndOfInput.
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
        assert_eq!(parsed.stop, StopCause::NodeCondition);
    }

    #[test]
    fn a_failing_node_stop_condition_aborts_under_any_policy() {
        // The hook-fallibility contract on `StopSpec::node`: an Err ends the parse
        // even under tolerant recovery — a condition that cannot answer leaves no
        // sound way to decide where the run ends — and the consultation site
        // attaches the live traceback (the callback has no session access).
        let st = state();
        let mut failing =
            |_: usize, _: StagedNodeView<'_, TestLang>| -> Result<bool, ParseError> {
                let scratch: Arc<Source> = Arc::new(Source::new(""));
                Err(ParseError::new(
                    crate::error::HookFailed::new("node table unavailable", None),
                    SourceSpan::new(&scratch, 0..0),
                ))
            };
        let content = "ab";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let mut session: ParserSession<TestLang> = ParserSession::new();
        let driver: StdParseDriver = StdParseDriver::new(Recovery::Tolerant, ());
        let mut cx = ParseContext::new(
            &mut reader,
            Arc::clone(&st),
            &mut session,
            &driver);
        let mut parser =
            NodesParser::new(StopSpec { token: None, node: Some(&mut failing) });
        let frame = crate::engine::Frame {
            title: crate::engine::FrameTitle::Static("test descent"),
            span: SourceSpan::new(&source, 0..0),
        };
        let error = cx.with_frame(frame, |cx| parser.parse(cx)).unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        // The live traceback, attached at the consultation site.
        assert_eq!(error.frames().len(), 1);
        assert_eq!(error.frames()[0].title(), "test descent");
    }

    #[test]
    fn token_stop_flush_does_not_consult_the_node_condition() {
        // Both triggers collide: the `\end` match flushes the pending run, and the
        // (always-true) node condition would fire on the flushed node. The token
        // condition wins outright — the run is staged, the predicate is never invoked
        // (a stateful `FnMut` must not observe a consulted-but-ignored call), and the
        // `consume = true` token is taken atomically.
        let st = state();
        let mut calls_std = 0usize;
        let mut calls_list = 0usize;
        let mut c1 = |_: usize, _: StagedNodeView<'_, TestLang>| {
            calls_std += 1;
            Ok(true)
        };
        let mut c2 = |_: usize, _: StagedNodeView<'_, TestLang>| {
            calls_list += 1;
            Ok(true)
        };
        let parsed = run_both(
            "ab \\end rest",
            &st,
            Recovery::Strict,
            StopSpec {
                token: Some(TokenStopCondition {
                    kind: TokenStopKind::Command { name: "end" },
                    consume: true,
                }),
                node: Some(&mut c1),
            },
            StopSpec {
                token: Some(TokenStopCondition {
                    kind: TokenStopKind::Command { name: "end" },
                    consume: true,
                }),
                node: Some(&mut c2),
            },
        );
        assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
        assert_eq!(stop_shape(&parsed.stop), "token 3..8");
        assert_eq!(parsed.pos, 8);
        assert_eq!(calls_std, 0, "the token-stop flush consulted the node condition");
        assert_eq!(calls_list, 0, "the token-stop flush consulted the node condition");
    }

    // --- tokenizer-error recovery (std reader only: the list reader cannot fail) ---------

    #[test]
    fn forbidden_char_tolerant_adopts_the_recovery_token() {
        let mut r = rules::<TestLang>();
        r.forbidden_chars.chars = "#".into();
        let st = state_with(r);
        let source: Arc<Source> = Arc::new(Source::new("ab#cd"));
        let mut reader = StdTokenReader::new(&source);
        let parsed =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
        // The placeholder Char joins the run: one maximal chars node, plus a diagnostic.
        assert_eq!(shapes(&parsed.result), ["chars 0..5 \"ab#cd\""]);
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        assert_eq!(
            diagnostic.data().downcast_ref::<crate::token::ForbiddenChar>().map(|c| c.ch),
            Some('#')
        );
        assert_eq!(diagnostic.span().range(), 2..3);
        assert_partition(&parsed.result, 0..5);
    }

    #[test]
    fn forbidden_char_strict_aborts() {
        let mut r = rules::<TestLang>();
        r.forbidden_chars.chars = "#".into();
        let st = state_with(r);
        let source: Arc<Source> = Arc::new(Source::new("ab#cd"));
        let mut reader = StdTokenReader::new(&source);
        let err =
            try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap_err();
        // The token error was lifted into the structured condition ([§dd-dr:errors]): compare
        // identifier and downcast fields (no PartialEq on the carriers).
        assert_eq!(err.identifier(), crate::token::ForbiddenChar::IDENTIFIER);
        assert_eq!(
            err.data().downcast_ref::<crate::token::ForbiddenChar>().map(|c| c.ch),
            Some('#')
        );
        assert_eq!(err.span().range(), 2..3);
    }

    /// Which kind of recovery placeholder [`PlaceholderReader`] mints.
    #[derive(Debug, Clone, Copy)]
    enum PlaceholderKind {
        /// A command placeholder over a backslash and the one character after it.
        Command,
        Specials,
        GroupOpen,
    }

    /// A token source that offers a recovery placeholder of a chosen kind at one
    /// offset: peeking there reports a recoverable error whose placeholder token
    /// stands over that single character (two for a command), with the resume
    /// position just past it.
    ///
    /// No standard reader mints a `Command`, `Specials` or `GroupOpen` placeholder — the standard
    /// forbidden-character recovery offers a `Char` — so this is the only way to reach
    /// the content loop's unusable-placeholder arms.
    struct PlaceholderReader<'s> {
        inner: StdTokenReader<'s>,
        /// The offset the placeholder is offered at.
        at: usize,
        kind: PlaceholderKind,
    }

    impl<'s> PlaceholderReader<'s> {
        /// Delegation goes through a `dyn` view, as in [`StuckRecoveryReader`].
        fn inner(&self) -> &dyn TokenReader<'s, TestLang> {
            &self.inner
        }

        fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, TestLang> {
            &mut self.inner
        }
    }

    impl<'s> TokenReader<'s, TestLang> for PlaceholderReader<'s> {
        fn peek(
            &mut self,
            state: &Arc<ParsingState<TestLang>>,
        ) -> TokenResult<TestLang, StdToken<TestLang>> {
            let here = self.inner().position_here();
            if here.offset() != self.at {
                return self.inner_mut().peek(state);
            }
            let span = Span::new(self.at, self.at + 1);
            let token = match self.kind {
                PlaceholderKind::Command => StdToken::command(
                    '\\',
                    Span::new(self.at, self.at + 2),
                    Span::empty(self.at),
                    Span::empty(self.at + 2),
                ),
                PlaceholderKind::Specials => {
                    let spec: Arc<dyn CallableSpec<TestLang>> =
                        Arc::new(StdCallableSpec::default());
                    StdToken::specials(CT_SPECIALS, spec, span, Span::empty(self.at))
                }
                PlaceholderKind::GroupOpen => StdToken::group_open(
                    Arc::new(GroupRule {
                        group_type: GT_BRACE,
                        open: "{".into(),
                        close: "}".into(),
                    }),
                    span,
                    Span::empty(self.at),
                ),
            };
            let resume = self.inner().position_at(&token, TokenEdge::EndPastPostSpace);
            Err(TokenError::new(
                TokenErrorKind::ForbiddenChar(crate::token::ForbiddenChar::new('#')),
                SourceSpan::new(self.inner.source(), span),
                Some(TokenRecovery { token, resume }),
            ))
        }

        fn move_to(&mut self, tok: &StdToken<TestLang>, 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 token_kind<'t>(&self, tok: &'t StdToken<TestLang>) -> TokenKind<'t, TestLang>
        where
            's: 't,
        {
            self.inner().token_kind(tok)
        }

        fn source_span_between(
            &self,
            tok: &StdToken<TestLang>,
            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<TestLang>, 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 `UnusableRecoveryToken` the run recorded, with the token error that came
    /// ahead of it checked in passing.
    fn unusable_placeholder<L: Lang>(result: &ParseResult<L>) -> UnusableRecoveryToken {
        let diagnostics: Vec<_> = result.diagnostics.iter().collect();
        assert_eq!(diagnostics.len(), 2, "{diagnostics:?}");
        // First the read failure itself, then the loop's refusal to use the
        // placeholder it was offered.
        assert_eq!(diagnostics[0].identifier(), crate::token::ForbiddenChar::IDENTIFIER);
        assert_eq!(diagnostics[1].identifier(), UnusableRecoveryToken::IDENTIFIER);
        diagnostics[1]
            .data()
            .downcast_ref::<UnusableRecoveryToken>()
            .expect("the unusable-placeholder condition")
            .clone()
    }

    #[test]
    fn a_specials_placeholder_is_unusable_and_recovers_as_chars() {
        // Recognition is resolution for specials, but a placeholder has no source
        // bytes to invoke anything over: the loop diagnoses it and stages the span as
        // ordinary chars instead.
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("ab~cd"));
        let mut reader = PlaceholderReader {
            inner: StdTokenReader::new(&source),
            at: 2,
            kind: PlaceholderKind::Specials,
        };
        let parsed =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"ab\"", "chars 2..3 \"~\"", "chars 3..5 \"cd\""]
        );
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        let condition = unusable_placeholder(&parsed.result);
        assert_eq!(condition.kind, UnusableRecoveryTokenKind::Specials);
        assert_eq!(condition.spelling, "~");
        assert_partition(&parsed.result, 0..5);
    }

    #[test]
    fn a_group_open_placeholder_is_unusable_and_recovers_as_chars() {
        // The same for a group open: there is no group to parse behind a delimiter
        // with no bytes, so the placeholder's span becomes a chars node.
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("ab{cd"));
        let mut reader = PlaceholderReader {
            inner: StdTokenReader::new(&source),
            at: 2,
            kind: PlaceholderKind::GroupOpen,
        };
        let parsed =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"ab\"", "chars 2..3 \"{\"", "chars 3..5 \"cd\""]
        );
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        let condition = unusable_placeholder(&parsed.result);
        assert_eq!(condition.kind, UnusableRecoveryTokenKind::GroupOpen);
        assert_eq!(condition.spelling, "{");
        assert_partition(&parsed.result, 0..5);
    }

    #[test]
    fn a_command_placeholder_is_unusable_and_recovers_as_chars() {
        // A command placeholder is never resolved: there are no source bytes behind it
        // to parse arguments from, so the loop reports it as unusable, not as an
        // unknown command, and stages its span as chars.
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("ab\\cd"));
        let mut reader = PlaceholderReader {
            inner: StdTokenReader::new(&source),
            at: 2,
            kind: PlaceholderKind::Command,
        };
        let parsed =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"ab\"", "chars 2..4 \"\\\\c\"", "chars 4..5 \"d\""]
        );
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        let condition = unusable_placeholder(&parsed.result);
        assert_eq!(condition.kind, UnusableRecoveryTokenKind::Command);
        assert_eq!(condition.spelling, "\\c");
        assert_partition(&parsed.result, 0..5);
    }

    #[test]
    fn a_specials_placeholder_aborts_under_strict_recovery() {
        // Strict recovery never adopts a token recovery: the read failure itself ends
        // the parse, and the placeholder arm is never reached.
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("ab~cd"));
        let mut reader = PlaceholderReader {
            inner: StdTokenReader::new(&source),
            at: 2,
            kind: PlaceholderKind::Specials,
        };
        let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
            .unwrap_err();
        assert_eq!(err.identifier(), crate::token::ForbiddenChar::IDENTIFIER);
        assert_eq!(err.span().range(), 2..3);
    }

    /// A token source that violates the `TokenRecovery::resume` advancement contract:
    /// every `peek` reports a recoverable forbidden-char error whose `resume` is the
    /// position the reader already stands at, so adopting the recovery re-reads the
    /// same error.
    struct StuckRecoveryReader<'s> {
        inner: StdTokenReader<'s>,
    }

    impl<'s> StuckRecoveryReader<'s> {
        /// Delegation goes through a `dyn` view: the inner reader's `TokenReader` impl is
        /// generic over the language, which plain method syntax cannot infer here.
        fn inner(&self) -> &dyn TokenReader<'s, TestLang> {
            &self.inner
        }

        fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, TestLang> {
            &mut self.inner
        }
    }

    impl<'s> TokenReader<'s, TestLang> for StuckRecoveryReader<'s> {
        fn peek(
            &mut self,
            _state: &Arc<ParsingState<TestLang>>,
        ) -> TokenResult<TestLang, StdToken<TestLang>> {
            let here = self.inner().position_here();
            let pos = here.offset();
            let span = Span::new(pos, pos + 1);
            Err(TokenError::new(
                TokenErrorKind::ForbiddenChar(crate::token::ForbiddenChar::new('#')),
                SourceSpan::new(self.inner.source(), span),
                Some(TokenRecovery {
                    token: StdToken::char('#', span, Span::empty(pos)),
                    resume: here, // the violation: the stream does not move
                }),
            ))
        }


        fn move_to(&mut self, tok: &StdToken<TestLang>, 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 token_kind<'t>(&self, tok: &'t StdToken<TestLang>) -> TokenKind<'t, TestLang>
        where
            's: 't,
        {
            self.inner().token_kind(tok)
        }

        fn source_span_between(
            &self,
            tok: &StdToken<TestLang>,
            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<TestLang>, 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)
        }
    }

    #[test]
    fn non_advancing_token_recovery_aborts_instead_of_spinning() {
        // Without the advancement guard this parse never terminates in tolerant mode
        // (the recovery arm consumes no token), pushing one diagnostic per iteration.
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let mut reader = StuckRecoveryReader { inner: StdTokenReader::new(&source) };
        let err = try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
            .expect_err("a non-advancing resume position must abort the parse");
        assert_eq!(err.identifier(), crate::token::ForbiddenChar::IDENTIFIER);
        assert_eq!(
            err.data().downcast_ref::<crate::token::ForbiddenChar>().map(|c| c.ch),
            Some('#')
        );
        assert_eq!(err.span().range(), 0..1);
    }

    /// A token source that violates `TokenReader` contract clause 9: every `peek` serves
    /// a `Char` token whose two ends are the same stream position, so consuming it leaves
    /// the stream where it was and the content loop reads the same token again.
    struct NonAdvancingTokenReader<'s> {
        inner: StdTokenReader<'s>,
    }

    impl<'s> NonAdvancingTokenReader<'s> {
        fn inner(&self) -> &dyn TokenReader<'s, TestLang> {
            &self.inner
        }

        fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, TestLang> {
            &mut self.inner
        }
    }

    impl<'s> TokenReader<'s, TestLang> for NonAdvancingTokenReader<'s> {
        fn peek(
            &mut self,
            _state: &Arc<ParsingState<TestLang>>,
        ) -> TokenResult<TestLang, StdToken<TestLang>> {
            let pos = self.inner().position_here().offset();
            // Empty span, empty pre-space: every edge of this token sits at `pos`, so
            // `position_at(&tok, EndPastPostSpace) == position_at(&tok, StartBeforePreSpace)`.
            Ok(StdToken::char('x', Span::empty(pos), Span::empty(pos)))
        }

        fn move_to(&mut self, tok: &StdToken<TestLang>, 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 token_kind<'t>(&self, tok: &'t StdToken<TestLang>) -> TokenKind<'t, TestLang>
        where
            's: 't,
        {
            self.inner().token_kind(tok)
        }

        fn source_span_between(
            &self,
            tok: &StdToken<TestLang>,
            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<TestLang>, 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)
        }
    }

    /// Without the loop's termination guard this parse never ends: the token is consumed
    /// every iteration and the stream never moves. The guard reports the violation as an
    /// implementation error, which aborts under any recovery policy — tolerant included.
    #[test]
    fn a_token_that_does_not_advance_the_stream_is_an_implementation_error() {
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let mut reader = NonAdvancingTokenReader { inner: StdTokenReader::new(&source) };
        let error = try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
            .expect_err("a token that does not advance the stream must abort the parse");
        let condition = error
            .data()
            .downcast_ref::<crate::constructs::ImplementationError>()
            .expect("an ImplementationError condition");
        assert_eq!(condition.kind, ImplementationErrorKind::StalledTokenReader);
        assert_eq!(error.span().range(), 0..0);
    }

    // --- TokenErrorKind::Custom ([§dd-dr:errors]: one extension mechanism serves both layers) --------

    /// A language-defined token condition, carried by `TokenErrorKind::Custom`.
    #[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
    #[diagnostic(
        id = "taboolang.token.taboo-char",
        message = "the character ‘{ch}’ is taboo here",
        no_constructor
    )]
    struct TabooChar {
        ch: char,
    }

    /// A `scan_specials` reporting a recoverable `Custom` token error on `!` — the
    /// extension point the variant exists for.
    #[derive(Debug, Clone, Copy)]
    struct TabooLang;
    impl Lang for TabooLang {
        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 scan_specials(
            _state: &ParsingState<Self>,
            content: &str,
            pos: usize,
        ) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
            if content[pos..].starts_with('!') {
                Err(SpecialsScanError {
                    kind: TokenErrorKind::Custom(Box::new(TabooChar { ch: '!' })),
                    span: Span::new(pos, pos + 1),
                })
            } else {
                Ok(None)
            }
        }

        fn specials_trigger_chars(_data: &StateData<Self>) -> TriggerChars {
            TriggerChars::Only("!".into())
        }
        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(())
        }
    }

    /// A reader that reports a recoverable `Custom` token error on `!`, delegating
    /// everything else to an inner `StdTokenReader`.
    ///
    /// A scan hook can no longer describe a recovery (`SpecialsScanError` carries a
    /// condition and a range, nothing else), so the *recoverable* half of the `Custom`
    /// extension point is exercised where recoveries live: in a reader.
    struct TabooReader<'s> {
        inner: StdTokenReader<'s>,
    }

    impl<'s> TabooReader<'s> {
        /// Delegation goes through a `dyn` view: the inner reader's `TokenReader` impl is
        /// generic over the language, which plain method syntax cannot infer here.
        fn inner(&self) -> &dyn TokenReader<'s, TabooLang> {
            &self.inner
        }

        fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, TabooLang> {
            &mut self.inner
        }
    }

    impl<'s> TokenReader<'s, TabooLang> for TabooReader<'s> {
        fn peek(
            &mut self,
            state: &Arc<ParsingState<TabooLang>>,
        ) -> TokenResult<TabooLang, StdToken<TabooLang>> {
            let pos = TokenReader::<TabooLang>::position_here(&self.inner).offset();
            if self.inner.content()[pos..].starts_with('!') {
                let span = Span::new(pos, pos + 1);
                return Err(TokenError::new(
                    TokenErrorKind::Custom(Box::new(TabooChar { ch: '!' })),
                    SourceSpan::new(self.inner.source(), span),
                    Some(TokenRecovery {
                        token: StdToken::char('!', span, Span::empty(pos)),
                        // In-crate test infrastructure may build a position directly.
                        resume: StdStreamPosition::at(span.end()),
                    }),
                ));
            }
            TokenReader::peek(&mut self.inner, state)
        }


        fn move_to(&mut self, tok: &StdToken<TabooLang>, 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 token_kind<'t>(&self, tok: &'t StdToken<TabooLang>) -> TokenKind<'t, TabooLang>
        where
            's: 't,
        {
            self.inner().token_kind(tok)
        }

        fn source_span_between(
            &self,
            tok: &StdToken<TabooLang>,
            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<TabooLang>, 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)
        }
    }

    #[test]
    fn custom_token_condition_flows_through_the_lift_unwrapped() {
        let st = state_with(rules::<TabooLang>());

        // A scan-hook failure is unrecoverable: both policies abort, carrying the
        // language's own condition.
        for recovery in [Recovery::Tolerant, Recovery::Strict] {
            let source: Arc<Source> = Arc::new(Source::new("a!b"));
            let mut reader = StdTokenReader::new(&source);
            let err = try_run(&source, &mut reader, &st, recovery, StopSpec::none())
                .expect_err("a specials scan error carries no recovery");
            assert_eq!(err.identifier(), TabooChar::IDENTIFIER);
            // The downcast reaches the payload directly: the lift unwraps `Custom` —
            // never double-boxed.
            assert!(err.data().downcast_ref::<TabooChar>().is_some());
        }

        // The same condition reported *recoverably* by a reader: tolerant mode records
        // the diagnostic (payload unwrapped) and the placeholder char joins the run.
        let source: Arc<Source> = Arc::new(Source::new("a!b"));
        let mut reader = TabooReader { inner: StdTokenReader::new(&source) };
        let parsed =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
        assert_eq!(shapes(&parsed.result), ["chars 0..3 \"a!b\""]);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), TabooChar::IDENTIFIER);
        assert_eq!(
            diagnostic.data().downcast_ref::<TabooChar>(),
            Some(&TabooChar { ch: '!' })
        );

        // Strict: the same condition rides the ParseError.
        let source: Arc<Source> = Arc::new(Source::new("a!b"));
        let mut reader = TabooReader { inner: StdTokenReader::new(&source) };
        let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
            .unwrap_err();
        assert_eq!(err.identifier(), TabooChar::IDENTIFIER);
        assert!(err.data().downcast_ref::<TabooChar>().is_some());
    }

    #[test]
    fn escape_at_end_of_input_tolerant_recovers_and_repositions() {
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("ab \\"));
        let mut reader = StdTokenReader::new(&source);
        let parsed =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
        // The placeholder is a Char covering the dangling escape byte: it joins the
        // pending chars run, so the recovery is partition-clean ([§dd-dr:errors]) — the escape
        // byte stays in the tree, accompanied by its diagnostic.
        assert_eq!(shapes(&parsed.result), ["chars 0..4 \"ab \\\\\""]);
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_eq!(parsed.pos, 4);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_partition(&parsed.result, 0..4);
    }

    #[test]
    fn escape_at_end_of_input_strict_aborts() {
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("ab \\"));
        let mut reader = StdTokenReader::new(&source);
        let err =
            try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap_err();
        assert_eq!(err.identifier(), crate::token::EndOfStreamAfterEscape::IDENTIFIER);
        assert_eq!(
            err.data()
                .downcast_ref::<crate::token::EndOfStreamAfterEscape>()
                .map(|c| c.escape_char),
            Some('\\')
        );
    }

    // --- unresolvable-command recovery ([§dd-dr:errors]) ---------------------------------------------

    #[test]
    fn unresolved_command_recovers_as_a_chars_fallback() {
        let st = state();
        let parsed =
            run_both("a \\foo  b", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
        // The fallback covers the token's full span (post-space included) and is not
        // merged into neighboring runs — a diagnosed artifact, not content accumulation.
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"a \"", "chars 2..8 \"\\\\foo  \"", "chars 8..9 \"b\""]
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
        // `TestLang` keeps the default `resolve_command`: its detail — command
        // resolution is not implemented — rides the condition.
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        let condition = diagnostic.data().downcast_ref::<UnresolvableCommand>().unwrap();
        assert_eq!(condition.name, "foo");
        assert_eq!(condition.escape_char, '\\');
        assert!(condition.detail.is_some());
        assert_eq!(diagnostic.span().range(), 2..8);
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_partition(&parsed.result, 0..9);
    }

    #[test]
    fn diagnostics_inside_a_group_carry_the_group_frame() {
        // `{\foo` (tolerant): the unresolvable command fires *inside* the group, so its
        // snapshot carries the group frame; the unclosed-group condition fires after
        // the interior frame is popped, so its snapshot is empty (root level).
        let st = state();
        let parsed =
            run_both("{\\foo", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
        assert_eq!(parsed.result.diagnostics.len(), 2);

        let unresolvable = parsed
            .result
            .diagnostics
            .with_identifier(UnresolvableCommand::IDENTIFIER)
            .next()
            .unwrap();
        // One frame, over the group's open delimiter.
        assert_eq!(unresolvable.frames().len(), 1);
        assert_eq!(unresolvable.frames()[0].span().range(), 0..1);
        // render() appends the traceback.
        assert!(unresolvable.render().contains(unresolvable.frames()[0].title()));

        let unclosed = parsed
            .result
            .diagnostics
            .with_identifier(super::super::UnclosedGroup::IDENTIFIER)
            .next()
            .unwrap();
        assert!(unclosed.frames().is_empty());
    }

    #[test]
    fn unresolved_command_strict_aborts() {
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("a \\foo  b"));
        let mut reader = StdTokenReader::new(&source);
        let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
            .unwrap_err();
        let condition = err.data().downcast_ref::<UnresolvableCommand>().unwrap();
        assert_eq!(condition.name, "foo");
        assert!(condition.detail.is_some());
        assert_eq!(err.span().range(), 2..8);
    }

    #[test]
    fn library_miss_takes_the_unresolvable_command_recovery() {
        // Same recovery, reached through a resolve_command that consults libraries and
        // misses (no fallback registered).
        let st = state_with_macros(&[]);
        let parsed =
            run_both("a \\foo b", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"a \"", "chars 2..7 \"\\\\foo \"", "chars 7..8 \"b\""]
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
        // `CmdLang` resolves through the shared `resolve_command_in_scopes`,
        // which reports the searched providers as the miss detail — one behavior across
        // the test langs and the latexlike preset (unified in the 7.5 review).
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        let condition = diagnostic.data().downcast_ref::<UnresolvableCommand>().unwrap();
        assert_eq!(condition.name, "foo");
        let detail = condition.detail.as_deref().expect("a miss detail");
        assert!(detail.contains("test-macros"), "the searched provider is named: {detail}");
        assert_partition(&parsed.result, 0..8);
    }

    #[test]
    fn provider_failure_takes_the_command_resolution_failed_recovery() {
        // An operational provider failure (vs. a clean miss) surfaces the distinct
        // CommandResolutionFailed condition through resolve_command_in_scopes, recovered as
        // chars like an unresolvable command.
        #[derive(Debug)]
        struct BrokenProvider;
        impl crate::serialize::SerializableObject<CmdLang> for BrokenProvider {}
        impl SpecsProvider<CmdLang> for BrokenProvider {
            fn name(&self) -> &str {
                "broken"
            }
            fn retrieve_spec(
                &self,
                _query: &CallableQuery<'_, CmdLang>,
                _state: &ParsingState<CmdLang>,
            ) -> Result<Option<Arc<dyn CallableSpec<CmdLang>>>, ProviderError> {
                Err(ProviderError::Failed("provider is down".into()))
            }
        }

        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(BrokenProvider));
        let st = Arc::new(ParsingState::new(StateData {
            rules: rules(),
            scopes,
            mode: (),
            ext: (),
        }));

        let parsed = run_both(
            "a \\foo b",
            &st,
            Recovery::Tolerant,
            StopSpec::none(),
            StopSpec::none(),
        );
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"a \"", "chars 2..7 \"\\\\foo \"", "chars 7..8 \"b\""]
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), CommandResolutionFailed::IDENTIFIER);
        let condition = diagnostic.data().downcast_ref::<CommandResolutionFailed>().unwrap();
        assert_eq!(condition.name, "foo");
        // The detail carries the failing provider's name and its error.
        let detail = condition.detail.as_deref().expect("a failure detail");
        assert!(
            detail.contains("broken") && detail.contains("provider is down"),
            "unexpected detail: {detail}"
        );
    }

    /// A driver whose resolver supplies its own failure detail — the channel a
    /// library-backed resolver would use for hints like "load this library".
    #[derive(Debug, Clone, Copy)]
    struct HintLang;
    impl Lang for HintLang {
        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 = HintDriver;
        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, Clone, Copy)]
    struct HintDriver {
        recovery: Recovery,
    }

    impl TestDriver for HintDriver {
        fn with_recovery(recovery: Recovery) -> Self {
            HintDriver { recovery }
        }
    }

    impl ParseDriver<HintLang> for HintDriver {
        fn recovery(&self) -> Recovery {
            self.recovery
        }

        fn resolve_command(
            &self,
            _state: &ParsingState<HintLang>,
            _token: &StdToken<HintLang>,
            _tokens: &dyn TokenReader<'_, HintLang>,
        ) -> Result<CommandResolution<HintLang>, ParseError> {
            Ok(CommandResolution::Unresolved {
                detail: Some("load the {amsmath} library for this command".into()),
            })
        }
    }

    #[test]
    fn resolver_supplied_detail_rides_the_diagnostic() {
        let st = state_with(rules::<HintLang>());
        let parsed =
            run_both("a \\foo b", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        let condition = diagnostic.data().downcast_ref::<UnresolvableCommand>().unwrap();
        assert_eq!(condition.name, "foo");
        assert_eq!(
            condition.detail.as_deref(),
            Some("load the {amsmath} library for this command")
        );
    }

    /// A driver whose resolver fails hard — the hook-fallibility **abort**
    /// channel (`Err`), as opposed to `HintLang`'s recoverable `Unresolved` and
    /// the diagnosed `Failed` resolution.
    #[derive(Debug, Clone, Copy)]
    struct AbortLang;
    impl Lang for AbortLang {
        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 = AbortDriver;
        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, Clone, Copy)]
    struct AbortDriver {
        recovery: Recovery,
    }

    impl ParseDriver<AbortLang> for AbortDriver {
        fn recovery(&self) -> Recovery {
            self.recovery
        }

        fn resolve_command(
            &self,
            _state: &ParsingState<AbortLang>,
            _token: &StdToken<AbortLang>,
            _tokens: &dyn TokenReader<'_, AbortLang>,
        ) -> Result<CommandResolution<AbortLang>, ParseError> {
            let source: Arc<Source> = Arc::new(Source::new(""));
            Err(ParseError::new(
                crate::error::HookFailed::new("resolver backend is down", None),
                SourceSpan::new(&source, 0..0),
            ))
        }
    }

    impl TestDriver for AbortDriver {
        fn with_recovery(recovery: Recovery) -> Self {
            AbortDriver { recovery }
        }
    }

    #[test]
    fn a_failing_resolve_command_aborts_under_any_policy() {
        // The abort channel: an Err from resolve_command stops the parse even in
        // tolerant mode — nothing is diagnosed-and-recovered (that is what the
        // Unresolved/Failed resolution values are for) — and the descent site
        // attaches the live traceback (the hook has no session access).
        let st = state_with(rules::<AbortLang>());
        let content = "a {\\foo} b";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let error =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
                .unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        assert_eq!(
            error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
            Some("resolver backend is down")
        );
        // The command sits inside a group: the group frame, over the open delimiter, is
        // on the traceback (resolution precedes the invocation frame, so it is the only
        // frame).
        assert_eq!(error.frames().len(), 1);
        assert_eq!(error.frames()[0].span().range(), 2..3);
    }

    // --- ParseDriver::refine_diagnostic ([§dd-dr:errors]) ----------------------------------------------

    /// The refinement demonstration's own condition: structured, so tools see it — not
    /// just better prose.
    #[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
    #[diagnostic(
        id = "refinelang.commands.not-available",
        message = "command ‘\\{name}’ is not available: this language defines no commands",
        no_constructor
    )]
    struct CommandsNotAvailable {
        name: String,
    }

    /// A Lang that refines the core's [`UnresolvableCommand`] into its own condition —
    /// the funnel applies the hook exactly once, on both the tolerant and strict paths.
    #[derive(Debug, Clone, Copy)]
    struct RefineLang;
    impl Lang for RefineLang {
        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 = RefineDriver;
        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, Clone, Copy)]
    struct RefineDriver {
        recovery: Recovery,
    }

    impl TestDriver for RefineDriver {
        fn with_recovery(recovery: Recovery) -> Self {
            RefineDriver { recovery }
        }
    }

    impl ParseDriver<RefineLang> for RefineDriver {
        fn recovery(&self) -> Recovery {
            self.recovery
        }

        fn refine_diagnostic(
            &self,
            data: alloc::boxed::Box<dyn crate::error::DiagnosticData>,
            _state: &ParsingState<RefineLang>,
        ) -> alloc::boxed::Box<dyn crate::error::DiagnosticData> {
            match data.downcast_ref::<UnresolvableCommand>() {
                Some(condition) => alloc::boxed::Box::new(CommandsNotAvailable {
                    name: condition.name.clone(),
                }),
                None => data,
            }
        }
    }

    #[test]
    fn refine_diagnostic_replaces_the_condition_in_the_funnel() {
        let st = state_with(rules::<RefineLang>());
        let parsed = run_both(
            "a \\foo b",
            &st,
            Recovery::Tolerant,
            StopSpec::none(),
            StopSpec::none(),
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), CommandsNotAvailable::IDENTIFIER);
        assert_eq!(
            diagnostic.data().downcast_ref::<CommandsNotAvailable>().unwrap().name,
            "foo"
        );
        assert!(diagnostic.message().contains("is not available"));

        // Strict mode: the refined condition rides the ParseError too (one funnel).
        let source: Arc<Source> = Arc::new(Source::new("a \\foo b"));
        let mut reader = StdTokenReader::new(&source);
        let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
            .unwrap_err();
        assert_eq!(err.identifier(), CommandsNotAvailable::IDENTIFIER);
    }

    // --- invocation dispatch (6.4) ----------------------------------------------------------

    #[test]
    fn zero_arg_macro_end_to_end() {
        let st = state_with_macros(&["foo"]);
        let parsed =
            run_both("ab \\foo cd", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        // The callable's span is the whole trigger token: escape + name + syntactic
        // post-space. The pre-space is sibling content.
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..3 \"ab \"", "callable 3..8", "chars 8..10 \"cd\""]
        );
        let node = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(node.callable_type(), Some(CT_MACRO));
        assert_eq!(node.name(), Some("foo"));
        let data = node.callable().unwrap();
        assert!(data.arguments.is_empty() && data.slots.is_empty());
        // The node records the package's spec (the flyweight Arc).
        let expected = st
            .scopes()
            .retrieve_spec(
                &CallableQuery::new(
                    CT_MACRO,
                    "foo",
                    CallableSyntax::Command { escape_char: '\\' },
                ),
                &st,
            )
            .unwrap()
            .unwrap();
        assert!(Arc::ptr_eq(&data.spec, &expected));
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert!(parsed.result.diagnostics.is_empty());
        assert_partition(&parsed.result, 0..10);
    }

    #[test]
    fn macro_post_space_is_the_trigger_tokens_own_and_nothing_more() {
        // `\foo bar`: the name-terminating space is the token's syntactic post-space —
        // recorded on the node, inside its span (the user-decided 6.4 rule: nothing
        // beyond the token's own post-space is ever claimed).
        let st = state_with_macros(&["foo", "&"]);
        let parsed =
            run_both("\\foo bar", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["callable 0..5", "chars 5..8 \"bar\""]);
        assert_partition(&parsed.result, 0..8);

        // A single non-name-char command (`\&`) takes no post-space at the token level,
        // and the invocation claims nothing beyond the token: the space is sibling
        // content (TeX/pylatexenc parity).
        let parsed =
            run_both("\\& b", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["callable 0..2", "chars 2..4 \" b\""]);
        assert_partition(&parsed.result, 0..4);
    }

    #[test]
    fn macro_post_space_stops_at_a_paragraph_break() {
        let st = state_with_macros(&["foo"]);
        let parsed = run_both(
            "\\foo \n\nb",
            &st,
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
        );
        // The token's post-space is cut off before the paragraph break (a token-rules
        // guarantee); the break is its own node.
        assert_eq!(
            shapes(&parsed.result),
            ["callable 0..5", "chars 5..7 \"\\n\\n\"", "chars 7..8 \"b\""]
        );
        assert_partition(&parsed.result, 0..8);
    }

    #[test]
    fn specials_dispatch_through_the_resolution_riding_on_the_token() {
        // Recognition = resolution: a recognized specials trigger always dispatches
        // (6.4) — the pre-6.4 chars-fallback recovery no longer applies to specials.
        let st = state_with(rules::<TildeLang>());
        let parsed =
            run_both("a~b", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..1 \"a\"", "callable 1..2", "chars 2..3 \"b\""]
        );
        let node = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(node.callable_type(), Some(CT_SPECIALS));
        assert_eq!(node.name(), Some("~"));
        assert!(parsed.result.diagnostics.is_empty());
        assert_partition(&parsed.result, 0..3);
    }

    #[test]
    fn invocation_inside_a_group_dispatches_at_that_level() {
        let st = state_with_macros(&["foo"]);
        let parsed =
            run_both("{\\foo x}", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["group 0..8"]);
        let group = parsed.result.tree.root().child(0).unwrap();
        assert_eq!(group.child_count(), 2);
        assert_eq!(group.child(0).unwrap().name(), Some("foo"));
        assert_eq!(group.child(1).unwrap().chars(), Some("x"));
        assert_partition(&parsed.result, 0..8);
    }

    #[test]
    fn invocation_delta_defines_later_siblings() {
        // The `\newcommand` shape: `\def`'s parser delegates to the standard parser
        // for its own node, then returns a push-library delta as its after-effect;
        // the later sibling `\late` resolves against the pushed library.
        #[derive(Debug)]
        struct DefSpec;
        impl crate::serialize::SerializableObject<CmdLang> for DefSpec {}
        impl CallableSpec<CmdLang> for DefSpec {
            fn make_invocation_parser<'a>(
                &'a self,
                invocation: Invocation<'a, CmdLang>,
            ) -> Result<Box<dyn ConstructParser<CmdLang, Output = BuildId> + 'a>, ParseError>
            {
                Ok(Box::new(DefParser { inner: StdInvocationParser::new(invocation) }))
            }
        }

        struct DefParser<'a> {
            inner: StdInvocationParser<'a, CmdLang>,
        }

        impl ConstructParser<CmdLang> for DefParser<'_> {
            type Output = BuildId;

            fn parse(
                &mut self,
                cx: &mut ParseContext<'_, '_, CmdLang>,
            ) -> ConstructParserResult<
                CmdLang,
                (BuildId, Option<Box<ParsingStateDelta<CmdLang>>>),
            > {
                let (id, _) = self.inner.parse(cx)?;
                let delta =
                    ParsingStateDelta::new().push_provider(macro_library(&["late"]));
                Ok((id, Some(Box::new(delta))))
            }
        }

        let mut lib: Package<CmdLang> = Package::new("cmds");
        lib.insert(CT_MACRO, "def", Arc::new(DefSpec));
        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(lib));
        let st: Arc<ParsingState<CmdLang>> =
            Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));

        let parsed = run_both(
            "\\def \\late x",
            &st,
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
        );
        assert_eq!(
            shapes(&parsed.result),
            ["callable 0..5", "callable 5..11", "chars 11..12 \"x\""]
        );
        let def = parsed.result.tree.root().child(0).unwrap();
        let late = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(def.name(), Some("def"));
        assert_eq!(late.name(), Some("late"));
        // The after-effect was applied to the loop's state: the later sibling records
        // the derived state (session-mediated), not the initial one.
        assert!(Arc::ptr_eq(def.parsing_state(), &st));
        assert!(!Arc::ptr_eq(late.parsing_state(), &st));
        assert!(parsed.result.diagnostics.is_empty());
        assert_partition(&parsed.result, 0..12);

        // Control: without the preceding `\def`, `\late` is unresolvable.
        let st = state_with_macros(&[]);
        let parsed = run_both(
            "\\late x",
            &st,
            Recovery::Tolerant,
            StopSpec::none(),
            StopSpec::none(),
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
    }

    #[test]
    fn takeover_parser_reads_raw_tokens_stages_custom_shape_and_returns_a_delta() {
        // The full-takeover escape hatch ([§dd-dr:parsers-engine], the C6 obligation): an overridden
        // factory returns a custom parser that consumes tokens up to a `!` marker —
        // markup included, no group descent — stages its own node shape (an untyped
        // group holding the raw chars), and returns a tokenization-affecting delta
        // (comments disabled) as its after-effect.
        #[derive(Debug)]
        struct TakeSpec;
        impl crate::serialize::SerializableObject<CmdLang> for TakeSpec {}
        impl CallableSpec<CmdLang> for TakeSpec {
            fn make_invocation_parser<'a>(
                &'a self,
                invocation: Invocation<'a, CmdLang>,
            ) -> Result<Box<dyn ConstructParser<CmdLang, Output = BuildId> + 'a>, ParseError>
            {
                Ok(Box::new(TakeParser { invocation }))
            }
        }

        struct TakeParser<'a> {
            invocation: Invocation<'a, CmdLang>,
        }

        impl ConstructParser<CmdLang> for TakeParser<'_> {
            type Output = BuildId;

            fn parse(
                &mut self,
                cx: &mut ParseContext<'_, '_, CmdLang>,
            ) -> ConstructParserResult<
                CmdLang,
                (BuildId, Option<Box<ParsingStateDelta<CmdLang>>>),
            > {
                // The trigger is already consumed whole; its span becomes the "open
                // delimiter". Raw content runs from there to the `!` marker.
                let open_span = cx.tokens.source_span_of(self.invocation.token);
                let content_start = cx.tokens.position_here();
                let (content_end, close_span, end) = loop {
                    let token = cx.tokens.peek(&cx.state).expect("clean test content");
                    let at = cx.tokens.position_at(&token, TokenEdge::Start);
                    cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
                    match cx.tokens.token_kind(&token) {
                        TokenKind::Char('!') => {
                            break (
                                at,
                                cx.tokens.source_span_of(&token),
                                cx.tokens.position_here(),
                            )
                        }
                        TokenKind::EndOfStream => {
                            panic!("test content has a marker")
                        }
                        _ => {}
                    }
                };
                let content = cx.source_span_within(&content_start, &content_end)?;
                let child = cx.stage_node(
                    NodeKind::chars(content.span()),
                    content,
                    Arc::clone(&cx.state),
                    vec![],
                ).unwrap();
                let span = cx.source_span_within(
                    &cx.tokens.position_at(self.invocation.token, TokenEdge::Start),
                    &end,
                )?;
                // Node data sub-spans go through the shared recording rule, exactly
                // as the production sites do.
                let delimiter =
                    |at: &SourceSpan| super::super::node_text_content(at, &span);
                let data: GroupData<CmdLang> =
                    GroupData::untyped(delimiter(&open_span), delimiter(&close_span));
                let id = cx.stage_node(
                    NodeKind::group(data),
                    span,
                    Arc::clone(&cx.state),
                    vec![child],
                ).unwrap();
                let delta = ParsingStateDelta::new().rules(TokenRulesOverrides {
                    comments: CommentOverrides::disable(),
                    ..TokenRulesOverrides::default()
                });
                Ok((id, Some(Box::new(delta))))
            }
        }

        let mut lib: Package<CmdLang> = Package::new("cmds");
        lib.insert(CT_MACRO, "take", Arc::new(TakeSpec));
        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(lib));
        let st: Arc<ParsingState<CmdLang>> =
            Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));

        // `a{b` would normally open a group (and diagnose it unclosed); the takeover
        // parser consumes it raw. ` %c` would normally be a comment; the returned
        // delta disables comments, so it parses as plain chars. StdTokenReader only:
        // a pre-scanned token list can neither re-serve raw bytes nor re-tokenize
        // under mid-parse rule changes (TokenListReader's documented fidelity limit).
        let content = "\\take a{b! %c";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let parsed =
            try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap();
        assert_eq!(
            shapes(&parsed.result),
            ["group 0..10", "chars 10..13 \" %c\""]
        );
        let take = parsed.result.tree.root().child(0).unwrap();
        assert_eq!(take.group_type(), None); // untyped: no language group class
        assert_eq!(take.group_delimiters(), Some(("\\take ", "!")));
        assert_eq!(take.child(0).unwrap().chars(), Some("a{b"));
        assert!(parsed.result.diagnostics.is_empty());
        assert_partition(&parsed.result, 0..13);
    }

    #[test]
    fn make_node_ext_mints_through_the_dispatch_loop() {
        // FLM pattern rehearsal ([§dd-dr:ext-minting]): parse staging goes through the
        // one automatic minting site (`cx.stage_node`), so every node the dispatch
        // loop stages — third-party construct parsers included — carries a properly
        // minted ext. The mint sees the kind: a preset downcasts a `Callable`'s
        // `data.spec` to its concrete spec type (the `Any` supertrait contract) and
        // derives ext data from spec + invocation facts. A preset dispatching on an
        // *open* set of spec types funnels them through one concrete wrapper first
        // (DESIGN_RATIONALE.md [§dd-dr:specs]).
        struct ExtBundle;
        impl NodeExtTypes for ExtBundle {
            type NodeExt = Option<Box<str>>; // Some for callables, None elsewhere
            type ArgumentExt = ();
            type SlotExt = ();
        }

        #[derive(Debug, Clone, Copy)]
        struct ExtLang;

        #[derive(Debug, Clone, Copy)]
        struct ExtDriver {
            recovery: Recovery,
        }

        impl TestDriver for ExtDriver {
            fn with_recovery(recovery: Recovery) -> Self {
                ExtDriver { recovery }
            }
        }

        impl ParseDriver<ExtLang> for ExtDriver {
            fn recovery(&self) -> Recovery {
                self.recovery
            }

            fn resolve_command(
                &self,
                state: &ParsingState<ExtLang>,
                token: &StdToken<ExtLang>,
                tokens: &dyn TokenReader<'_, ExtLang>,
            ) -> Result<CommandResolution<ExtLang>, ParseError> {
                resolve_macro_in_scopes(state, token, tokens)
            }
        }

        impl Lang for ExtLang {
            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 = ExtBundle;
            type InvocationSyntax = ();
            type Driver = ExtDriver;

            fn make_node_ext(
                kind: &NodeKind<Self>,
                _span: &SourceSpan<Self::SourceOrigin>,
                _state: &Arc<ParsingState<Self>>,
                _children: crate::node::StagedChildren<'_, Self>,
            ) -> Result<Option<Box<str>>, crate::node::NodeBuildError> {
                let NodeKind::Callable(data) = kind else { return Ok(None) };
                // The downcast: trait-upcast the stored spec to `&dyn Any`, then
                // recover the concrete type — field access included.
                let spec = (&*data.spec as &dyn core::any::Any)
                    .downcast_ref::<StdCallableSpec<ExtLang>>()
                    .expect("the test library registers StdCallableSpec");
                Ok(Some(format!("{}#{}", data.name, spec.arguments.len()).into_boxed_str()))
            }
        }

        let mut scopes = ScopeStack::new();
        scopes.push(macro_library::<ExtLang>(&["foo"]));
        let st: Arc<ParsingState<ExtLang>> =
            Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));

        let parsed =
            run_both("\\foo x", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        let node = parsed.result.tree.root().child(0).unwrap();
        assert_eq!(node.ext().as_deref(), Some("foo#0"));
        // Non-callable siblings got the mint's other arm.
        assert_eq!(*parsed.result.tree.root().child(1).unwrap().ext(), None);
    }

    #[test]
    fn invocation_child_state_policy_fixed_and_compute() {
        let st = state_with_macros(&["foo"]);
        let other = Arc::new(st.derived(&ParsingStateDelta::new()).unwrap());

        // Fixed: the invocation parser runs under (and its node records) the fixed
        // state; the policy scopes the descent only — the next sibling is back on the
        // loop's own state.
        let parsed = run_both_with(
            "\\foo x",
            &st,
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
            ChildStateSpec {
                group: GroupChildState::Inherit,
                invocation: InvocationChildState::Fixed(Arc::clone(&other)),
            },
        );
        let node = parsed.result.tree.root().child(0).unwrap();
        assert!(Arc::ptr_eq(node.parsing_state(), &other));
        let sibling = parsed.result.tree.root().child(1).unwrap();
        assert!(Arc::ptr_eq(sibling.parsing_state(), &st));

        // Compute: a pure selection receiving the resolved invocation (resolution
        // precedes policy); returning an input preserves pointer identity.
        let compute = |state: &Arc<ParsingState<CmdLang>>,
                       invocation: &Invocation<'_, CmdLang>|
         -> Result<Arc<ParsingState<CmdLang>>, ParseError> {
            assert_eq!(invocation.name, "foo");
            assert_eq!(invocation.callable_type, CT_MACRO);
            Ok(Arc::clone(state))
        };
        let parsed = run_both_with(
            "\\foo x",
            &st,
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
            ChildStateSpec {
                group: GroupChildState::Inherit,
                invocation: InvocationChildState::Compute(&compute),
            },
        );
        let node = parsed.result.tree.root().child(0).unwrap();
        assert!(Arc::ptr_eq(node.parsing_state(), &st));
    }

    // --- groups (6.3) ----------------------------------------------------------------------

    #[test]
    fn group_round_trips_with_exact_spans_and_delimiters() {
        let st = state();
        let parsed =
            run_both("a {b} c", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"a \"", "group 2..5", "chars 5..7 \" c\""]
        );
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert!(parsed.result.diagnostics.is_empty());
        let group = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(group.group_type(), Some(GT_BRACE));
        assert_eq!(group.group_delimiters(), Some(("{", "}")));
        assert_eq!(group.child_count(), 1);
        assert_eq!(group.child(0).unwrap().chars(), Some("b"));
        // The space after `}` is enclosing content, not a group post-space.
        assert_partition(&parsed.result, 0..7);
    }

    #[test]
    fn nested_groups_with_exact_spans() {
        let st = state();
        let parsed =
            run_both("{a{b}c}", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["group 0..7"]);
        let outer = parsed.result.tree.root().child(0).unwrap();
        assert_eq!(outer.child_count(), 3);
        assert_eq!(outer.child(0).unwrap().chars(), Some("a"));
        let inner = outer.child(1).unwrap();
        assert!(inner.is_group());
        assert_eq!(inner.span().range(), 2..5);
        assert_eq!(inner.child(0).unwrap().chars(), Some("b"));
        assert_eq!(outer.child(2).unwrap().chars(), Some("c"));
    }

    #[test]
    fn empty_group_has_no_children() {
        let st = state();
        let parsed =
            run_both("x{}y", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..1 \"x\"", "group 1..3", "chars 3..4 \"y\""]
        );
        let group = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(group.child_count(), 0);
        assert_eq!(group.group_delimiters(), Some(("{", "}")));
    }

    #[test]
    fn paragraph_break_inside_a_group_stays_inside() {
        let st = state();
        let parsed =
            run_both("{a\n\nb}", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["group 0..6"]);
        let group = parsed.result.tree.root().child(0).unwrap();
        assert_eq!(group.child_count(), 3); // "a", the break node, "b"
        assert_eq!(group.child(1).unwrap().chars(), Some("\n\n"));
    }

    #[test]
    fn ambiguous_dollar_group_closes_via_the_derived_expected_close() {
        // `$` opens and closes GT_MATH groups. As a *closer* it is only recognizable
        // through `expecting_group_close` — which the interior state carries precisely
        // because the group parser derives it (session-memoized); without it the
        // interior `$` would read as another opener. Std reader only: a pre-scanned
        // token list is tokenized under the base state and cannot see the interior
        // state's reclassification.
        let mut r = rules::<TestLang>();
        r.groups.rules.push(math_rule());
        let st = state_with(r);
        let source: Arc<Source> = Arc::new(Source::new("a $x$ b"));
        let mut reader = StdTokenReader::new(&source);
        let parsed =
            try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap();
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"a \"", "group 2..5", "chars 5..7 \" b\""]
        );
        let group = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(group.group_type(), Some(GT_MATH));
        assert_eq!(group.group_delimiters(), Some(("$", "$")));
        assert_eq!(group.child(0).unwrap().chars(), Some("x"));
    }

    #[test]
    fn node_condition_counts_a_group_as_one_node() {
        let st = state();
        let mut c1 = |count: usize, view: StagedNodeView<'_, TestLang>| {
            Ok(count >= 1 && matches!(view.kind(), NodeKind::Group(_)))
        };
        let mut c2 = |count: usize, view: StagedNodeView<'_, TestLang>| {
            Ok(count >= 1 && matches!(view.kind(), NodeKind::Group(_)))
        };
        let parsed = run_both(
            "{a}b",
            &st,
            Recovery::Strict,
            StopSpec { token: None, node: Some(&mut c1) },
            StopSpec { token: None, node: Some(&mut c2) },
        );
        // The condition fired on the group (one staged sibling, consumed whole); the
        // parse stops right after it.
        assert_eq!(shapes(&parsed.result), ["group 0..3"]);
        assert_eq!(parsed.stop, StopCause::NodeCondition);
        assert_eq!(parsed.pos, 3);
    }

    #[test]
    fn stop_conditions_are_not_consulted_inside_a_group() {
        // Conditions are tested only at the parser's own nesting level ([§dd-dr:parsers-engine]): the
        // `\end` inside the group is the *interior* parser's business (here the
        // 6.4-pending unresolvable-command recovery), never an outer stop.
        let st = state();
        let parsed = run_both(
            "a{\\end}b",
            &st,
            Recovery::Tolerant,
            StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
            StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
        );
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let group = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(group.child(0).unwrap().chars(), Some("\\end"));
    }

    // --- group recovery (6.3) --------------------------------------------------------------

    #[test]
    fn unclosed_group_at_end_of_input_recovers_with_an_empty_close() {
        let st = state();
        let parsed =
            run_both("a {bc", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["chars 0..2 \"a \"", "group 2..5"]);
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_eq!(parsed.pos, 5);
        let group = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(group.group_delimiters(), Some(("{", "")));
        assert_eq!(group.child(0).unwrap().chars(), Some("bc"));
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        let condition = diagnostic.data().downcast_ref::<super::super::UnclosedGroup>().unwrap();
        assert_eq!(condition.expected_close, "}");
        assert_eq!(condition.found, super::super::UnclosedGroupFound::EndOfInput);
        assert_eq!(diagnostic.span().range(), 2..3);
    }

    #[test]
    fn unclosed_group_strict_aborts() {
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new("a {bc"));
        let mut reader = StdTokenReader::new(&source);
        let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
            .unwrap_err();
        let condition = err.data().downcast_ref::<super::super::UnclosedGroup>().unwrap();
        assert_eq!(condition.expected_close, "}");
        assert_eq!(condition.found, super::super::UnclosedGroupFound::EndOfInput);
        // The diagnostic points at the open delimiter that was never closed.
        assert_eq!(err.span().range(), 2..3);
    }

    #[test]
    fn mismatched_close_inside_a_group_unwinds_without_consuming() {
        // `[`/`]` shares class GT_BRACE. Inside the `{` group, the `]` matches neither
        // the expected close spelling nor rules it out by class alone: the interior
        // reports it as data, the group parser diagnoses and closes *without consuming*
        // (unwinding — every level consumes or unwinds, [§dd-dr:parsers-engine]), and the stray close then
        // surfaces at this level, still unconsumed, for the root driver to adjudicate.
        let mut r = rules::<TestLang>();
        r.groups.rules.push(Arc::new(GroupRule {
            group_type: GT_BRACE,
            open: "[".into(),
            close: "]".into(),
        }));
        let st = state_with(r);
        let parsed =
            run_both("{a]}", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
        assert_eq!(shapes(&parsed.result), ["group 0..2"]);
        let group = parsed.result.tree.root().child(0).unwrap();
        assert_eq!(group.group_delimiters(), Some(("{", "")));
        assert_eq!(group.child(0).unwrap().chars(), Some("a"));
        assert_eq!(stop_shape(&parsed.stop), "close 2..3");
        assert_eq!(parsed.pos, 2);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        let condition = diagnostic.data().downcast_ref::<super::super::UnclosedGroup>().unwrap();
        assert_eq!(condition.expected_close, "}");
        assert_eq!(condition.found, super::super::UnclosedGroupFound::StrayClose);
        assert_eq!(diagnostic.span().range(), 2..3);
    }

    #[test]
    fn mismatched_close_inside_a_group_strict_aborts() {
        let mut r = rules::<TestLang>();
        r.groups.rules.push(Arc::new(GroupRule {
            group_type: GT_BRACE,
            open: "[".into(),
            close: "]".into(),
        }));
        let st = state_with(r);
        let source: Arc<Source> = Arc::new(Source::new("{a]}"));
        let mut reader = StdTokenReader::new(&source);
        let err =
            try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap_err();
        let condition = err.data().downcast_ref::<super::super::UnclosedGroup>().unwrap();
        assert_eq!(condition.expected_close, "}");
        assert_eq!(condition.found, super::super::UnclosedGroupFound::StrayClose);
        assert_eq!(err.span().range(), 2..3);
    }

    #[test]
    fn root_driver_skips_a_stray_close_and_continues() {
        // The root always consumes ([§dd-dr:parsers-engine]): `UnexpectedGroupClose` is data, and the
        // *root driver* — here the test; the core `Language::parse` entry drives this
        // same loop since Phase 7.4 — diagnoses, skips the token, and resumes. The
        // skipped byte is dropped from the tree: an accepted tolerant byte-accounting
        // break, so this is the one tree the invariant checker is deliberately not
        // applied to.
        //
        // The condition here is deliberately the driver's own, third-party style
        // ([§dd-dr:errors]): a custom root driver defines its diagnoses like any downstream
        // language would (or reuses the core `StrayGroupClose`, which is what
        // `Language::parse` reports).
        #[derive(Debug, Clone, DiagnosticInfo)]
        #[diagnostic(
            id = "test.root-driver.stray-group-close",
            message = "unexpected closing ‘{delim}’",
            no_constructor
        )]
        struct StrayGroupClose {
            delim: String,
        }

        let content = "a}b";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let st = state();
        let mut reader = StdTokenReader::new(&source);
        let mut session: ParserSession<TestLang> = ParserSession::new();
        let driver = StdParseDriver::new(Recovery::Tolerant, ());
        let mut nodes = Vec::new();
        let stop = loop {
            let mut cx = ParseContext::new(
                &mut reader,
                Arc::clone(&st),
                &mut session,
                &driver);
            let mut parser = NodesParser::new(StopSpec::none());
            let (outcome, _) = parser.parse(&mut cx).unwrap();
            nodes.extend(outcome.nodes);
            match outcome.stop {
                StopCause::UnexpectedGroupClose { span, after } => {
                    session
                        .recover(
                            Recovery::Tolerant,
                            Box::new(StrayGroupClose { delim: "}".into() }),
                            span,
                        )
                        .unwrap();
                    // The skip target rides on the cause: no re-peek.
                    <dyn TokenReader<'_, TestLang>>::move_to_position(&mut reader, &after);
                }
                other => break other,
            }
        };
        assert_eq!(stop, StopCause::EndOfInput);
        let root = session.builder.add(
            NodeKind::list(),
            SourceSpan::entire(&source),
            Arc::clone(&st),
            nodes, (), (),
        ).unwrap();
        let result = session.finish(root).unwrap();
        let texts: Vec<_> = result
            .tree
            .root()
            .children()
            .iter().map(|c| c.chars().unwrap().to_string())
            .collect();
        assert_eq!(texts, ["a", "b"]);
        assert_eq!(result.diagnostics.len(), 1);
    }

    // --- descent-state policy + the session seam (6.3) --------------------------------------

    #[test]
    fn child_state_fixed_reverts_group_interiors_to_the_outer_state() {
        // The chars-except-groups motivating case ([§dd-dr:parsers-engine]): a restricted outer state
        // (comments disabled) whose group interiors revert to the full state. Std
        // reader only: a pre-scanned list cannot see the interior reclassification.
        let full = state();
        let restricted = Arc::new(full.derived(&ParsingStateDelta::new().rules(
            TokenRulesOverrides { comments: CommentOverrides::disable(), ..Default::default() },
        )).unwrap());
        let content = "%x{%y\n}z";

        // Under the restricted state alone, `%` is ordinary content everywhere.
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let plain =
            try_run(&source, &mut reader, &restricted, Recovery::Strict, StopSpec::none())
                .unwrap();
        let group = plain.result.tree.root().child(1).unwrap();
        assert!(group.children().iter().all(|c| c.is_chars()));

        // With `group: Fixed(full)` the interior reverts: `%y` is a comment again.
        let policy = ChildStateSpec {
            group: GroupChildState::Fixed(Arc::clone(&full)),
            invocation: InvocationChildState::Inherit,
        };
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let parsed = try_run_with(&source,
            &mut reader,
            &restricted,
            Recovery::Strict,
            StopSpec::none(),
            policy,
        )
        .unwrap();
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"%x\"", "group 2..7", "chars 7..8 \"z\""]
        );
        let group = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(group.child_count(), 1);
        let comment = group.child(0).unwrap();
        assert_eq!(
            comment.comment().map(|data| data.content.resolve(comment.source())),
            Some("y")
        );
        // The group node itself records the policy's base state (its input state).
        assert!(Arc::ptr_eq(group.parsing_state(), &full));
    }

    #[test]
    fn child_state_compute_selects_by_the_open_token() {
        // The callback receives the loop's state and the open token (delim + resolved
        // rule): comments stay enabled inside `{…}` (pass-through) but are disabled
        // inside `[…]` (precomputed state selected by group class). Std reader only.
        const GT_OPT: u32 = 2;
        let mut r = rules::<TestLang>();
        r.groups.rules.push(Arc::new(GroupRule {
            group_type: GT_OPT,
            open: "[".into(),
            close: "]".into(),
        }));
        let full = state_with(r);
        let no_comments = Arc::new(full.derived(&ParsingStateDelta::new().rules(
            TokenRulesOverrides { comments: CommentOverrides::disable(), ..Default::default() },
        )).unwrap());
        let compute = |state: &Arc<ParsingState<TestLang>>,
                       token: &StdToken<TestLang>,
                       tokens: &dyn TokenReader<'_, TestLang>| {
            Ok(match tokens.token_kind(token) {
                TokenKind::GroupOpen { rule, .. } if rule.group_type == GT_OPT => {
                    Arc::clone(&no_comments)
                }
                _ => Arc::clone(state), // pass-through preserves pointer identity
            })
        };
        let policy = ChildStateSpec {
            group: GroupChildState::Compute(&compute),
            invocation: InvocationChildState::Inherit,
        };

        let content = "{%a\n}[%b\n]";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let parsed = try_run_with(&source,
            &mut reader,
            &full,
            Recovery::Strict,
            StopSpec::none(),
            policy,
        )
        .unwrap();
        let braces = parsed.result.tree.root().child(0).unwrap();
        assert_eq!(braces.child_count(), 1);
        let comment = braces.child(0).unwrap();
        assert_eq!(
            comment.comment().map(|data| data.content.resolve(comment.source())),
            Some("a")
        );
        assert!(Arc::ptr_eq(braces.parsing_state(), &full)); // pass-through identity
        let brackets = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(brackets.group_type(), Some(GT_OPT));
        assert_eq!(brackets.child_count(), 1);
        assert_eq!(brackets.child(0).unwrap().chars(), Some("%b\n"));
        assert!(Arc::ptr_eq(brackets.parsing_state(), &no_comments));
    }

    #[test]
    fn a_failing_child_state_compute_aborts_under_any_policy() {
        // The hook-fallibility contract on the Compute arms: an Err is an abort
        // even under tolerant recovery — the descent-state seam has no recovery
        // channel — and the callback's condition rides the abort error. The
        // demonstrated body is the documented DeriveError lift: HookFailed with
        // the derivation failure as the cause.
        let full = state_with(rules::<TestLang>());
        let compute = |state: &Arc<ParsingState<TestLang>>,
                       _token: &StdToken<TestLang>,
                       _tokens: &dyn TokenReader<'_, TestLang>| {
            // A derivation the policy needs, failing operationally (a scope op
            // against a provider name that does not exist).
            let delta = ParsingStateDelta::new()
                .scope_op(crate::scopes::ScopeOp::Unload { name: "no-such-provider".into() });
            match state.derived(&delta) {
                Ok(state) => Ok(Arc::new(state)),
                Err(error) => {
                    let scratch: Arc<Source> = Arc::new(Source::new(""));
                    Err(ParseError::new(
                        crate::error::HookFailed::new(error.to_string(), None)
                            .with_cause(error),
                        SourceSpan::new(&scratch, 0..0),
                    ))
                }
            }
        };
        let policy = ChildStateSpec {
            group: GroupChildState::Compute(&compute),
            invocation: InvocationChildState::Inherit,
        };

        let content = "{a}";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let error = try_run_with(&source,
            &mut reader,
            &full,
            Recovery::Tolerant,
            StopSpec::none(),
            policy,
        )
        .unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        // The DeriveError cause chain is reachable off the carried condition.
        let condition =
            error.data().downcast_ref::<crate::error::HookFailed>().unwrap();
        let cause: &(dyn core::error::Error + 'static) = &**condition.cause.as_ref().unwrap();
        let derive_error = cause
            .downcast_ref::<crate::state::DeriveError<TestLang>>()
            .expect("the cause is the DeriveError");
        assert!(derive_error.finalize_error.is_none());
        assert_eq!(derive_error.failures.len(), 1);
        assert!(matches!(
            &derive_error.failures[0],
            crate::scopes::ScopeOpError::UnknownProvider { name } if &**name == "no-such-provider"
        ));
        // The policy computes the descent base *before* the group frame is pushed,
        // and the harness drives the root loop with no frame of its own — the
        // attached snapshot is exactly empty.
        assert_eq!(error.frames().len(), 0);
    }

    #[test]
    fn sibling_group_interiors_share_one_memoized_state() {
        let st = state();
        let parsed =
            run_both("{a}{b}", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        let root = parsed.result.tree.root();
        let g1 = root.child(0).unwrap();
        let g2 = root.child(1).unwrap();
        // The group nodes record the outer state (structural revert restores the Arc)…
        assert!(Arc::ptr_eq(g1.parsing_state(), &st));
        assert!(Arc::ptr_eq(g2.parsing_state(), &st));
        // …while their interior children share one derived Arc (the session memo) that
        // carries the expected close.
        let a = g1.child(0).unwrap();
        let b = g2.child(0).unwrap();
        assert!(Arc::ptr_eq(a.parsing_state(), b.parsing_state()));
        assert!(!Arc::ptr_eq(a.parsing_state(), &st));
        assert_eq!(
            a.parsing_state()
                .rules()
                .expecting_group_close()
                .map(|rule| rule.close.as_str()),
            Some("}")
        );
    }

    #[test]
    fn observe_transition_fires_per_descent_finalize_once_per_derivation() {
        // The two-level transition doctrine ([§dd-dr:parsers-engine]): `{a}{b}` makes two group descents —
        // both reach observe_transition (memo hits included) — but only one actual
        // derivation runs finalize_transition.
        use core::sync::atomic::{AtomicUsize, Ordering};
        static FINALIZE_RUNS: AtomicUsize = AtomicUsize::new(0);

        #[derive(Debug, Default)]
        struct Counts {
            observed: usize,
        }

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

            fn finalize_transition(
                _new: &mut StateData<Self>,
                _prev: &ParsingState<Self>,
                _events: &[()],
            ) -> Result<(), crate::state::FinalizeError> {
                FINALIZE_RUNS.fetch_add(1, Ordering::Relaxed);
                Ok(())
            }
            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(())
            }
        }

        /// Counts observations (the hook moved to the driver in 7.2); strict by
        /// default, which is what the manual drive below wants.
        #[derive(Debug, Clone, Copy)]
        struct CountDriver;

        impl ParseDriver<CountLang> for CountDriver {
            fn observe_transition(
                &self,
                ext: &mut Counts,
                _diagnostics: &mut crate::error::Diagnostics,
                _prev: &ParsingState<CountLang>,
                _new: &ParsingState<CountLang>,
                _delta: &ParsingStateDelta<CountLang>,
            ) -> Result<(), ParseError> {
                ext.observed += 1;
            Ok(())
            }
        }

        // Driven manually so the session stays inspectable after the parse.
        let content = "{a}{b}";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let st = state_with(rules::<CountLang>());
        let mut reader = StdTokenReader::new(&source);
        let mut session: ParserSession<CountLang> = ParserSession::new();
        let driver = CountDriver;
        let mut cx = ParseContext::new(
            &mut reader,
            Arc::clone(&st),
            &mut session,
            &driver);
        let mut parser = NodesParser::new(StopSpec::none());
        let (outcome, _) = parser.parse(&mut cx).unwrap();
        assert!(matches!(outcome.stop, StopCause::EndOfInput));
        assert_eq!(session.ext.observed, 2);
        assert_eq!(FINALIZE_RUNS.load(Ordering::Relaxed), 1);
    }

    /// The two `observe_transition` reporting channels, exercised separately: the
    /// diagnostics sink records without affecting the parse (an error-severity
    /// entry does **not** abort — record-versus-abort for source conditions is
    /// `recover`'s business), while an `Err` aborts under any recovery policy.
    #[derive(Debug, Default)]
    struct Seen {
        transitions: usize,
    }

    #[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
    #[diagnostic(
        id = "testlang.observe.transition-observed",
        message = "a state transition was observed",
        no_constructor
    )]
    struct TransitionObserved;

    #[test]
    fn observe_transition_diagnostics_sink_records_without_aborting() {
        #[derive(Debug, Clone, Copy)]
        struct SinkLang;
        impl Lang for SinkLang {
            type Features = crate::state::AllLangFeatures;
            type GroupTypeId = u32;
            type CallableTypeId = u32;
            type ModeId = ();
            type StateExt = ();
            type Event = ();
            type SessionExt = Seen;
            type SourceOrigin = Option<String>;
            type Tokenization = crate::token::StdTokenization;
            type NodeExts = ();
            type InvocationSyntax = ();
            type Driver = SinkDriver;
            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, Clone, Copy)]
        struct SinkDriver;
        impl TestDriver for SinkDriver {
            fn with_recovery(_recovery: Recovery) -> Self {
                SinkDriver // strict — the sink must not abort even so
            }
        }
        impl ParseDriver<SinkLang> for SinkDriver {
            fn observe_transition(
                &self,
                ext: &mut Seen,
                diagnostics: &mut crate::error::Diagnostics,
                _prev: &ParsingState<SinkLang>,
                _new: &ParsingState<SinkLang>,
                _delta: &ParsingStateDelta<SinkLang>,
            ) -> Result<(), ParseError> {
                ext.transitions += 1;
                // An error-severity observation: recorded, never an abort.
                let scratch: Arc<Source> = Arc::new(Source::new(""));
                diagnostics.push(crate::error::Diagnostic::error(
                    TransitionObserved,
                    SourceSpan::new(&scratch, 0..0),
                ));
                Ok(())
            }
        }

        // One group descent = one observed transition; the parse completes.
        let st = state_with(rules::<SinkLang>());
        let content = "{a}";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let parsed =
            try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
                .expect("the sink records; it never aborts");
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let recorded = parsed.result.diagnostics.iter().next().unwrap();
        assert_eq!(recorded.severity(), crate::error::Severity::Error);
        assert_eq!(recorded.identifier(), "testlang.observe.transition-observed");
        assert_eq!(shapes(&parsed.result), ["group 0..3"]);
    }

    #[test]
    fn a_failing_observe_transition_aborts_under_any_policy() {
        #[derive(Debug, Clone, Copy)]
        struct FailObserveLang;
        impl Lang for FailObserveLang {
            type Features = crate::state::AllLangFeatures;
            type GroupTypeId = u32;
            type CallableTypeId = u32;
            type ModeId = ();
            type StateExt = ();
            type Event = ();
            type SessionExt = Seen;
            type SourceOrigin = Option<String>;
            type Tokenization = crate::token::StdTokenization;
            type NodeExts = ();
            type InvocationSyntax = ();
            type Driver = FailObserveDriver;
            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, Clone, Copy)]
        struct FailObserveDriver;
        impl TestDriver for FailObserveDriver {
            fn with_recovery(_recovery: Recovery) -> Self {
                FailObserveDriver // tolerant by hand: recovery() below
            }
        }
        impl ParseDriver<FailObserveLang> for FailObserveDriver {
            fn recovery(&self) -> Recovery {
                Recovery::Tolerant
            }
            fn observe_transition(
                &self,
                ext: &mut Seen,
                _diagnostics: &mut crate::error::Diagnostics,
                _prev: &ParsingState<FailObserveLang>,
                _new: &ParsingState<FailObserveLang>,
                _delta: &ParsingStateDelta<FailObserveLang>,
            ) -> Result<(), ParseError> {
                ext.transitions += 1;
                if ext.transitions < 2 {
                    return Ok(());
                }
                // The second transition (the inner group's interior derivation,
                // inside the outer group's frame) is the truly problematic state.
                let scratch: Arc<Source> = Arc::new(Source::new(""));
                Err(ParseError::new(
                    crate::error::HookFailed::new("observer backend gone", None),
                    SourceSpan::new(&scratch, 0..0),
                ))
            }
        }

        let st = state_with(rules::<FailObserveLang>());
        let content = "{{a}}";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let error =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
                .unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        assert_eq!(
            error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
            Some("observer backend gone")
        );
        // The inner descent's consultation runs inside the outer group's frame.
        assert!(!error.frames().is_empty());
    }

    // --- everything at once ----------------------------------------------------------------

    #[test]
    fn mixed_content_with_groups_partitions_exactly() {
        let st = state();
        let content = "ab {cd %e\nf} g\n\nh";
        let parsed =
            run_both(content, &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            [
                "chars 0..3 \"ab \"",
                "group 3..12",
                "chars 12..14 \" g\"",
                "chars 14..16 \"\\n\\n\"",
                "chars 16..17 \"h\"",
            ]
        );
        let group = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(group.child_count(), 3);
        assert_eq!(group.child(0).unwrap().chars(), Some("cd "));
        let comment = group.child(1).unwrap();
        assert_eq!(
            comment.comment().map(|data| data.content.resolve(comment.source())),
            Some("e")
        );
        assert_eq!(group.child(2).unwrap().chars(), Some("f"));
        assert_partition(&parsed.result, 0..content.len());
    }

    #[test]
    fn mixed_content_shapes_and_partition() {
        let st = state();
        let content = "ab %c\nd\n\n e \\foo f";
        let parsed =
            run_both(content, &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            [
                "chars 0..3 \"ab \"",
                "comment 3..6 start=\"%\" content=\"c\" post=\"\\n\"",
                "chars 6..7 \"d\"",
                "chars 7..9 \"\\n\\n\"",
                "chars 9..12 \" e \"",
                "chars 12..17 \"\\\\foo \"",
                "chars 17..18 \"f\"",
            ]
        );
        assert_eq!(parsed.stop, StopCause::EndOfInput);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_partition(&parsed.result, 0..content.len());
    }

    // --- the driver's construct provision + descent-delta channel, end to end (7.2) -----

    /// One custom driver exercising every provision seam at once: all three factories
    /// intercepted (counted, then delegating to the standard parsers), command
    /// resolution via libraries, and the D2 math plug — `group_interior_delta` returns
    /// a mode-entering delta for the math group class, so `$…$` interiors parse (and
    /// record their nodes) in math mode with zero core changes.
    #[test]
    fn custom_driver_intercepts_every_factory_and_math_groups_enter_math_mode() {
        use core::sync::atomic::{AtomicUsize, Ordering};

        use super::super::GroupParser;

        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
        enum Mode {
            #[default]
            Text,
            Math,
        }

        #[derive(Debug, Clone, Copy)]
        struct DriveLang;
        impl Lang for DriveLang {
            type Features = crate::state::AllLangFeatures;
            type GroupTypeId = u32;
            type CallableTypeId = u32;
            type ModeId = Mode;
            type StateExt = ();
            type Event = ();
            type SessionExt = ();
            type SourceOrigin = Option<String>;
            type Tokenization = crate::token::StdTokenization;
            type NodeExts = ();
            type InvocationSyntax = ();
            type Driver = DriveDriver;
            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, Default)]
        struct DriveDriver {
            nodes_parsers: AtomicUsize,
            group_parsers: AtomicUsize,
            invocation_parsers: AtomicUsize,
        }

        impl ParseDriver<DriveLang> for DriveDriver {
            fn resolve_command(
                &self,
                state: &ParsingState<DriveLang>,
                token: &StdToken<DriveLang>,
                tokens: &dyn TokenReader<'_, DriveLang>,
            ) -> Result<CommandResolution<DriveLang>, ParseError> {
                resolve_macro_in_scopes(state, token, tokens)
            }

            fn group_interior_delta(
                &self,
                _base: &ParsingState<DriveLang>,
                rule: &Arc<GroupRule<DriveLang>>,
            ) -> Option<ParsingStateDelta<DriveLang>> {
                (rule.group_type == GT_MATH)
                    .then(|| ParsingStateDelta::new().mode(Mode::Math))
            }

            fn make_nodes_parser<'p>(
                &'p self,
                stop: StopSpec<'p, DriveLang>,
                child_states: ChildStateSpec<'p, DriveLang>,
            ) -> Result<
                Box<dyn ConstructParser<DriveLang, Output = NodesOutcome<DriveLang>> + 'p>,
                ParseError,
            > {
                self.nodes_parsers.fetch_add(1, Ordering::Relaxed);
                Ok(Box::new(NodesParser::new(stop).with_child_states(child_states)))
            }

            fn make_group_parser<'p>(
                &'p self,
                open: &StdToken<DriveLang>,
                rule: Arc<GroupRule<DriveLang>>,
                child_states: ChildStateSpec<'p, DriveLang>,
            ) -> Result<Box<dyn ConstructParser<DriveLang, Output = BuildId> + 'p>, ParseError>
            {
                self.group_parsers.fetch_add(1, Ordering::Relaxed);
                Ok(Box::new(
                    GroupParser::new(open.clone(), rule).with_child_states(child_states),
                ))
            }

            fn make_invocation_parser<'a>(
                &'a self,
                invocation: Invocation<'a, DriveLang>,
            ) -> Result<Box<dyn ConstructParser<DriveLang, Output = BuildId> + 'a>, ParseError>
            {
                self.invocation_parsers.fetch_add(1, Ordering::Relaxed);
                let spec = invocation.spec;
                spec.make_invocation_parser(invocation)
            }
        }

        // `{a}$m$\m {y}`: a brace group, a math group, a zero-arg macro, a sibling
        // brace group — one root drive, three group descents, one invocation.
        let content = "{a}$m$\\m {y}";
        let mut rules = rules::<DriveLang>();
        rules.groups.rules.push(math_rule());
        let mut scopes = ScopeStack::new();
        scopes.push(macro_library::<DriveLang>(&["m"]));
        let st = Arc::new(ParsingState::new(StateData {
            rules,
            scopes,
            mode: Mode::Text,
            ext: (),
        }));
        let st = Arc::new(st.derived(&ParsingStateDelta::new()).unwrap()); // through the choke point
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let mut session: ParserSession<DriveLang> = ParserSession::new();
        let driver = DriveDriver::default();
        let mut cx = ParseContext::new(
            &mut reader,
            Arc::clone(&st),
            &mut session,
            &driver);

        // The top-level drive goes through the same seam as every interior descent.
        let (outcome, delta) = cx
            .parse_nodes(Arc::clone(&st), StopSpec::none(), ChildStateSpec::inherit())
            .unwrap();
        assert!(delta.is_none());
        assert!(matches!(outcome.stop, StopCause::EndOfInput));

        let root = session
            .builder
            .add(
                NodeKind::list(),
                SourceSpan::new(&source, 0..content.len()),
                Arc::clone(&st),
                outcome.nodes, (), (),
            )
            .unwrap();
        let result = session.finish(root).unwrap();
        crate::node::check_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty());
        assert_eq!(
            shapes(&result),
            ["group 0..3", "group 3..6", "callable 6..9", "group 9..12"]
        );

        // Factory counts: 1 root + 3 group interiors = 4 nodes descents; 3 group
        // descents; 1 invocation.
        assert_eq!(driver.nodes_parsers.load(Ordering::Relaxed), 4);
        assert_eq!(driver.group_parsers.load(Ordering::Relaxed), 3);
        assert_eq!(driver.invocation_parsers.load(Ordering::Relaxed), 1);

        // The math plug: the `$…$` interior's nodes record a Math-mode state; the
        // brace interiors stay in Text mode (the driver's delta keyed on the class).
        let math_child = result.tree.root().child(1).unwrap().child(0).unwrap();
        assert_eq!(math_child.chars(), Some("m"));
        assert_eq!(math_child.parsing_state().mode(), Mode::Math);
        let brace_child = result.tree.root().child(0).unwrap().child(0).unwrap();
        assert_eq!(brace_child.chars(), Some("a"));
        assert_eq!(brace_child.parsing_state().mode(), Mode::Text);
        // The mode scoped structurally: content after the math group is Text again.
        let after = result.tree.root().child(3).unwrap().child(0).unwrap();
        assert_eq!(after.chars(), Some("y"));
        assert_eq!(after.parsing_state().mode(), Mode::Text);
    }

    // --- the group after-effect leak channel (the `\gdef` shape) -----------------------

    /// End to end: a driver installs a [`GroupAfterEffectsFn`](super::super::GroupAfterEffectsFn)
    /// on every group descent, `\gdef` tags its definition op with a globally-named
    /// scope and `\def` with a local one, and the hook keeps exactly the
    /// globally-targeted ops. `\gdef`'s definition then outlives its group — through
    /// nesting, one hook per level — while `\def`'s dies with it, and the same driver
    /// with the hook uninstalled leaks nothing at all.
    #[test]
    fn a_group_leaks_the_after_effects_its_hook_keeps() {
        use core::sync::atomic::{AtomicUsize, Ordering};

        use super::super::{GroupAfterEffectsFn, GroupParser};
        use crate::scopes::{Scope, ScopeOp};
        use crate::state::{FeaturePresence, LangFeatures};

        /// The scope `\gdef` defines into — the tag that survives the group.
        const GLOBAL: &str = "global";
        /// The scope `\def` defines into — dropped at the group boundary.
        const LOCAL: &str = "local";

        #[derive(Debug, Clone, Copy)]
        struct GdefLang;
        impl Lang for GdefLang {
            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 = GdefDriver;
            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(())
            }
        }

        /// A definition macro: the standard node, plus a scope-op delta as its
        /// after-effect (the `\newcommand` shape, `MacroSpec::with_after_effect`'s
        /// mechanism spelled out for a bare test lang).
        #[derive(Debug)]
        struct DefiningSpec {
            delta: ParsingStateDelta<GdefLang>,
        }

        impl crate::serialize::SerializableObject<GdefLang> for DefiningSpec {}

        impl CallableSpec<GdefLang> for DefiningSpec {
            fn make_invocation_parser<'a>(
                &'a self,
                invocation: Invocation<'a, GdefLang>,
            ) -> Result<Box<dyn ConstructParser<GdefLang, Output = BuildId> + 'a>, ParseError>
            {
                Ok(Box::new(DefiningParser {
                    inner: StdInvocationParser::new(invocation),
                    delta: &self.delta,
                }))
            }
        }

        struct DefiningParser<'a> {
            inner: StdInvocationParser<'a, GdefLang>,
            delta: &'a ParsingStateDelta<GdefLang>,
        }

        impl ConstructParser<GdefLang> for DefiningParser<'_> {
            type Output = BuildId;

            fn parse(
                &mut self,
                cx: &mut ParseContext<'_, '_, GdefLang>,
            ) -> ConstructParserResult<
                GdefLang,
                (BuildId, Option<Box<ParsingStateDelta<GdefLang>>>),
            > {
                let (id, _) = self.inner.parse(cx)?;
                Ok((id, Some(Box::new(self.delta.clone()))))
            }
        }

        /// `scope`-targeted definition of the zero-arg macro `name`.
        fn defining(scope: &str, name: &str) -> ParsingStateDelta<GdefLang> {
            ParsingStateDelta::new().scope_op(ScopeOp::Define {
                scope: scope.into(),
                callable_type: CT_MACRO,
                name: name.into(),
                spec: Arc::new(StdCallableSpec::default()),
            })
        }

        /// Is `name` resolvable as a macro under `state`?
        fn defined(state: &ParsingState<GdefLang>, name: &str) -> bool {
            let query =
                CallableQuery::new(CT_MACRO, name, CallableSyntax::Command { escape_char: '\\' });
            state.scopes().retrieve_spec(&query, state).unwrap().is_some()
        }

        /// The leak hook: keep the ops the language tagged as global, drop the rest.
        /// The merged record carries no provenance — a `\gdef`-vs-`\def` split *is* this
        /// structural filter (the type's documentation).
        #[allow(clippy::type_complexity)]
        type Hook = Box<
            dyn Fn(
                    &Arc<GroupRule<GdefLang>>,
                    &Arc<ParsingState<GdefLang>>,
                    &Arc<ParsingState<GdefLang>>,
                    Option<Box<ParsingStateDelta<GdefLang>>>,
                ) -> Result<Option<Box<ParsingStateDelta<GdefLang>>>, ParseError>
                + Send
                + Sync,
        >;

        struct GdefDriver {
            /// `None` = the stock behavior (nothing escapes a group).
            hook: Option<Hook>,
            /// Hook calls, so the test can pin one call per group descent.
            calls: Arc<AtomicUsize>,
        }

        impl fmt::Debug for GdefDriver {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_struct("GdefDriver").finish_non_exhaustive()
            }
        }

        impl GdefDriver {
            fn new(leak: bool) -> GdefDriver {
                let calls = Arc::new(AtomicUsize::new(0));
                // The closure captures the counter — the reason the hook is a borrowed
                // `dyn Fn` and not a bare `fn` pointer.
                let counter = Arc::clone(&calls);
                let hook: Hook = Box::new(move |rule, initial, exit, record| {
                    counter.fetch_add(1, Ordering::Relaxed);
                    // Argument 1: the class of the group that is closing.
                    assert_eq!(rule.group_type, GT_BRACE);
                    // Arguments 2 and 3: the interior's own two states. The exit state
                    // is the only reader of what the interior defined — it dies with
                    // the descent right after this call.
                    assert!(!defined(initial, "g") && !defined(initial, "d"));
                    let Some(record) = record else {
                        assert!(Arc::ptr_eq(initial, exit));
                        return Ok(None);
                    };
                    // Argument 4: one merged delta, no provenance — so the filter is
                    // structural, over the ops the language tagged.
                    let ops = <<GdefLang as Lang>::Features as LangFeatures>::Scopes::store_get(
                        &record.scope_ops,
                    )
                    .expect("the lang declares the scopes feature present");
                    let kept: Vec<ScopeOp<GdefLang>> = ops
                        .iter()
                        .filter(|op| matches!(op, ScopeOp::Define { scope, .. } if &**scope == GLOBAL))
                        .cloned()
                        .collect();
                    if kept.is_empty() {
                        return Ok(None);
                    }
                    let mut escaping = ParsingStateDelta::new();
                    for op in kept {
                        escaping = escaping.scope_op(op);
                    }
                    Ok(Some(Box::new(escaping)))
                });
                GdefDriver { hook: leak.then_some(hook), calls }
            }
        }

        impl ParseDriver<GdefLang> for GdefDriver {
            fn make_token_reader<'s>(
                &'s self,
                source: &'s alloc::sync::Arc<crate::source::Source>,
            ) -> alloc::boxed::Box<dyn crate::token::TokenReader<'s, GdefLang> + 's> {
                alloc::boxed::Box::new(crate::token::StdTokenReader::new(source))
            }

            fn recovery(&self) -> Recovery {
                Recovery::Tolerant
            }

            fn resolve_command(
                &self,
                state: &ParsingState<GdefLang>,
                token: &StdToken<GdefLang>,
                tokens: &dyn TokenReader<'_, GdefLang>,
            ) -> Result<CommandResolution<GdefLang>, ParseError> {
                resolve_macro_in_scopes(state, token, tokens)
            }

            /// The plug-in point: every group descent of this language carries the hook,
            /// which is what makes an escape compose outward through nested groups.
            fn make_group_parser<'p>(
                &'p self,
                open: &StdToken<GdefLang>,
                rule: Arc<GroupRule<GdefLang>>,
                child_states: ChildStateSpec<'p, GdefLang>,
            ) -> Result<Box<dyn ConstructParser<GdefLang, Output = BuildId> + 'p>, ParseError>
            {
                Ok(match &self.hook {
                    None => Box::new(
                        GroupParser::new(open.clone(), rule).with_child_states(child_states),
                    ),
                    Some(hook) => {
                        let hook: GroupAfterEffectsFn<'p, GdefLang> = &**hook;
                        Box::new(
                            GroupParser::new_with_after_effects(open.clone(), rule, hook)
                                .with_child_states(child_states),
                        )
                    }
                })
            }
        }

        /// Parse `content` at the root and report the final root state plus the
        /// diagnostics count.
        fn run(
            content: &str,
            driver: &GdefDriver,
        ) -> (ParseResult<GdefLang>, Arc<ParsingState<GdefLang>>) {
            let mut scopes = ScopeStack::new();
            let mut base: Scope<GdefLang> = Scope::new("base");
            base.insert(CT_MACRO, "gdef", Arc::new(DefiningSpec { delta: defining(GLOBAL, "g") }));
            base.insert(CT_MACRO, "def", Arc::new(DefiningSpec { delta: defining(LOCAL, "d") }));
            scopes.push(Arc::new(base));
            // The document-level scope `\gdef` defines into.
            scopes.push(Arc::new(Scope::<GdefLang>::new(GLOBAL)));
            let st = Arc::new(ParsingState::new(StateData {
                rules: rules(),
                scopes,
                mode: (),
                ext: (),
            }));
            let source: Arc<Source> = Arc::new(Source::new(content));
            let mut reader = StdTokenReader::new(&source);
            let mut session: ParserSession<GdefLang> = ParserSession::new();
            let mut cx =
                ParseContext::new(&mut reader, Arc::clone(&st), &mut session, driver);
            let (outcome, delta) = cx
                .parse_nodes(Arc::clone(&st), StopSpec::none(), ChildStateSpec::inherit())
                .unwrap();
            // The content loop never reports a pass-through delta of its own; its run's
            // effects travel on the outcome.
            assert!(delta.is_none());
            let exit = Arc::clone(&outcome.state);
            let root = session
                .builder
                .add(
                    NodeKind::list(),
                    SourceSpan::new(&source, 0..content.len()),
                    Arc::clone(&st),
                    outcome.nodes,
                    (),
                    (),
                )
                .unwrap();
            (session.finish(root).unwrap(), exit)
        }

        // `\gdef` and `\def` both define inside the group — both `\g` and `\d` resolve
        // there — but only the globally-tagged one is still resolvable after the close.
        let driver = GdefDriver::new(true);
        let (result, exit) = run("{\\gdef\\def\\g\\d}\\g\\d", &driver);
        crate::node::check_tree_invariants(&result.tree);
        assert_eq!(driver.calls.load(Ordering::Relaxed), 1);
        let root = result.tree.root();
        // The group's four children all parsed cleanly…
        assert_eq!(root.child(0).unwrap().child_count(), 4);
        // …and after it, `\g` is a callable while `\d` fell back to chars.
        assert_eq!(root.child(1).unwrap().name(), Some("g"));
        assert_eq!(root.child(2).unwrap().chars(), Some("\\d"));
        assert_eq!(result.diagnostics.len(), 1);
        // The escaped op reached the enclosing run's state — and only it.
        assert!(defined(&exit, "g"));
        assert!(!defined(&exit, "d"));

        // Nesting: one hook per level, so the escape composes outward.
        let driver = GdefDriver::new(true);
        let (result, exit) = run("{{\\gdef}}\\g", &driver);
        crate::node::check_tree_invariants(&result.tree);
        assert_eq!(driver.calls.load(Ordering::Relaxed), 2);
        assert_eq!(result.tree.root().child(1).unwrap().name(), Some("g"));
        assert!(result.diagnostics.is_empty());
        assert!(defined(&exit, "g"));

        // Control: the same language with no hook installed keeps the stock behavior —
        // the interior record dies with the descent, both definitions with it.
        let driver = GdefDriver::new(false);
        let (result, exit) = run("{\\gdef\\def}\\g\\d", &driver);
        crate::node::check_tree_invariants(&result.tree);
        assert_eq!(driver.calls.load(Ordering::Relaxed), 0);
        assert_eq!(result.diagnostics.len(), 2);
        assert!(!defined(&exit, "g"));
        assert!(!defined(&exit, "d"));
    }

    #[test]
    fn a_failing_invocation_parser_factory_aborts_under_any_policy() {
        // The hook-fallibility contract on the parser factories: a factory Err
        // means "the parser could not be built" and stops the parse even in
        // tolerant mode; the dispatch site attaches the live traceback (the
        // factory has no session access). Distinct from a depth refusal — that
        // stays the descent guard's business (`DescentLimitExceeded`).
        #[derive(Debug)]
        struct BrokenFactorySpec;
        impl crate::serialize::SerializableObject<CmdLang> for BrokenFactorySpec {}
        impl CallableSpec<CmdLang> for BrokenFactorySpec {
            fn make_invocation_parser<'a>(
                &'a self,
                _invocation: Invocation<'a, CmdLang>,
            ) -> Result<Box<dyn ConstructParser<CmdLang, Output = BuildId> + 'a>, ParseError>
            {
                let scratch: Arc<Source> = Arc::new(Source::new(""));
                Err(ParseError::new(
                    crate::error::HookFailed::new("parser backend unavailable", None),
                    SourceSpan::new(&scratch, 0..0),
                ))
            }
        }

        let mut lib = Package::new("broken");
        lib.insert(CT_MACRO, "fail", BrokenFactorySpec);
        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(lib));
        let st: Arc<ParsingState<CmdLang>> =
            Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));

        let content = "a {\\fail} b";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let error =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
                .unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        assert_eq!(
            error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
            Some("parser backend unavailable")
        );
        // The dispatch pushes the invocation's own frame (over the `\\fail` trigger)
        // around the factory call, inside the group's frame (over its `{`).
        assert_eq!(error.frames().len(), 2);
        assert_eq!(error.frames()[0].span().range(), 3..8);
        assert_eq!(error.frames()[1].span().range(), 2..3);
        // The invocation frame is titled by the failing spec's own hook.
        assert_eq!(
            error.frames()[0].title(),
            BrokenFactorySpec.stack_frame_title(crate::spec::FrameRole::Invocation, "\\fail")
        );
    }

    #[test]
    fn a_failing_nodes_parser_factory_aborts_under_any_policy() {
        // The same contract on the driver's content-loop factory, exercised at a
        // group descent (the interior's nodes run is built through
        // `ParseContext::parse_nodes`, which lifts the factory Err and attaches
        // the live traceback).
        #[derive(Debug, Clone, Copy)]
        struct BrokenLang;
        impl Lang for BrokenLang {
            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 = BrokenDriver;
            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, Clone, Copy)]
        struct BrokenDriver;
        impl TestDriver for BrokenDriver {
            fn with_recovery(_recovery: Recovery) -> Self {
                BrokenDriver // tolerant by hand: recovery() below
            }
        }
        impl ParseDriver<BrokenLang> for BrokenDriver {
            fn recovery(&self) -> Recovery {
                Recovery::Tolerant
            }
            fn make_nodes_parser<'p>(
                &'p self,
                _stop: StopSpec<'p, BrokenLang>,
                _child_states: ChildStateSpec<'p, BrokenLang>,
            ) -> Result<
                Box<dyn ConstructParser<BrokenLang, Output = NodesOutcome<BrokenLang>> + 'p>,
                ParseError,
            > {
                let scratch: Arc<Source> = Arc::new(Source::new(""));
                Err(ParseError::new(
                    crate::error::HookFailed::new("content-loop backend unavailable", None),
                    SourceSpan::new(&scratch, 0..0),
                ))
            }
        }

        // The harness drives the root loop directly, so the factory is first
        // consulted at the `{…}` descent — inside the group's frame.
        let st = state_with(rules::<BrokenLang>());
        let content = "{a}";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let error =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
                .unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        assert_eq!(error.frames().len(), 1);
        assert_eq!(error.frames()[0].span().range(), 0..1);
    }

    #[test]
    fn a_failing_make_node_ext_aborts_as_a_hook_failure() {
        // The mint's error channel inside a parse: `Lang::make_node_ext` errs with
        // the builder-level `NodeBuildError::ExtMintFailed`; the staging entry
        // point reports it like any other builder error, and the staging caller's
        // lift applies the condition split — the mint's reported operational
        // failure becomes `HookFailed`, while every other builder error stays
        // `ImplementationError` — an abort under any recovery policy, with the
        // live traceback attached.
        #[derive(Debug, Clone, Copy)]
        struct MintFailLang;
        impl Lang for MintFailLang {
            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 = 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> {
                if matches!(kind, NodeKind::Chars { .. }) {
                    return Err(crate::node::NodeBuildError::ExtMintFailed {
                        detail: "ext backend unavailable".into(),
                    });
                }
                Ok(())
            }
        }

        // The first chars node is staged inside the group, so the group frame is
        // live when the mint fails.
        let st = state_with(rules::<MintFailLang>());
        let content = "{a}";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let error =
            try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
                .unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        assert_eq!(
            error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
            Some("ext backend unavailable")
        );
        // The chars node is staged inside the group, so the group frame is live.
        assert_eq!(error.frames().len(), 1);
        assert_eq!(error.frames()[0].span().range(), 0..1);
    }

    // --- the scope stack in a driven parse (7.3): error specs, op failures, specials ---

    #[test]
    fn error_callable_spec_diagnoses_and_recovers_as_chars() {
        use crate::scopes::{CallableDefinedAsError, ErrorCallableSpec};

        let mut package: Package<CmdLang> = Package::new("cmds");
        package.insert(
            CT_MACRO,
            "gone",
            Arc::new(ErrorCallableSpec::with_detail("removed upstream"))
                as Arc<dyn CallableSpec<CmdLang>>,
        );
        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(package));
        let st: Arc<ParsingState<CmdLang>> =
            Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));

        // Tolerant: the resolved error spec diagnoses and stages the trigger as a
        // chars fallback (post-space included — the token was consumed whole); the
        // parse continues past it.
        let parsed =
            run_both("a\\gone b", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..1 \"a\"", "chars 1..7 \"\\\\gone \"", "chars 7..8 \"b\""]
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        let condition =
            diagnostic.data().downcast_ref::<CallableDefinedAsError>().unwrap();
        assert_eq!(condition.name, "gone");
        assert_eq!(condition.detail.as_deref(), Some("removed upstream"));
        assert_partition(&parsed.result, 0..8);

        // Strict: the same condition aborts (through the recover funnel).
        let source: Arc<Source> = Arc::new(Source::new("a\\gone b"));
        let mut reader = StdTokenReader::new(&source);
        let error =
            try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
                .unwrap_err();
        assert_eq!(error.data().identifier(), CallableDefinedAsError::IDENTIFIER);
    }

    /// A lang whose driver returns a *failing* scope op as the descent delta of math
    /// groups — the in-parse op-failure path (7.3).
    #[derive(Debug, Clone, Copy)]
    struct FailingMathLang;
    impl Lang for FailingMathLang {
        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 = FailingMathDriver;
        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, Clone, Copy)]
    struct FailingMathDriver {
        recovery: Recovery,
    }

    impl TestDriver for FailingMathDriver {
        fn with_recovery(recovery: Recovery) -> Self {
            FailingMathDriver { recovery }
        }
    }

    impl ParseDriver<FailingMathLang> for FailingMathDriver {
        fn recovery(&self) -> Recovery {
            self.recovery
        }

        fn group_interior_delta(
            &self,
            _base: &ParsingState<FailingMathLang>,
            rule: &Arc<GroupRule<FailingMathLang>>,
        ) -> Option<ParsingStateDelta<FailingMathLang>> {
            use crate::scopes::ScopeOp;
            (rule.group_type == GT_MATH).then(|| {
                ParsingStateDelta::new().scope_op(ScopeOp::Unload { name: "absent".into() })
            })
        }
    }

    #[test]
    fn descent_scope_op_failure_recovers_tolerantly_and_aborts_strictly() {
        use crate::constructs::ScopeOpFailed;

        let mut math_rules = rules::<FailingMathLang>();
        math_rules.groups.rules.push(math_rule());
        let st = state_with(math_rules);

        // Tolerant: the failure is reported through the recover funnel as a
        // ScopeOpFailed condition and the group parses under the ops-skipped state.
        // (Std reader only: a pre-scanned token list cannot disambiguate the closing
        // `$` of a same-delimiter group — that is expecting_group_close's job.)
        let source: Arc<Source> = Arc::new(Source::new("a$m$b"));
        let mut reader = StdTokenReader::new(&source);
        let parsed = try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
            .expect("tolerant parse continues");
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..1 \"a\"", "group 1..4", "chars 4..5 \"b\""]
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
        let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
        // The rendered failure is the op's error: no provider named `absent`.
        let detail = &diagnostic.data().downcast_ref::<ScopeOpFailed>().unwrap().detail;
        assert_eq!(
            *detail,
            crate::scopes::ScopeOpError::UnknownProvider { name: "absent".into() }.to_string()
        );
        assert_partition(&parsed.result, 0..5);

        // Strict: the first failing op aborts the parse.
        let source: Arc<Source> = Arc::new(Source::new("a$m$b"));
        let mut reader = StdTokenReader::new(&source);
        let error = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
            .unwrap_err();
        assert_eq!(error.data().identifier(), ScopeOpFailed::IDENTIFIER);
    }

    /// A lang whose specials hooks consult the state's scope stack — the standard
    /// preset wiring of provider-based specials.
    #[derive(Debug, Clone, Copy)]
    struct StackSpecialsLang;
    impl Lang for StackSpecialsLang {
        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 scan_specials(
        state: &ParsingState<Self>,
        content: &str,
        pos: usize,
    ) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
            state.scopes().scan_specials(state, content, pos)
        }

        fn specials_trigger_chars(data: &StateData<Self>) -> TriggerChars {
            data.scopes.specials_trigger_chars()
        }
        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(())
        }
    }

    #[test]
    fn package_specials_resolve_through_the_stack_fold_end_to_end() {
        let inner_short: Arc<dyn CallableSpec<StackSpecialsLang>> =
            Arc::new(StdCallableSpec::default());
        let outer_short: Arc<dyn CallableSpec<StackSpecialsLang>> =
            Arc::new(StdCallableSpec::default());
        let outer_long: Arc<dyn CallableSpec<StackSpecialsLang>> =
            Arc::new(StdCallableSpec::default());

        let mut inner: Package<StackSpecialsLang> = Package::new("inner");
        inner.insert_specials(CT_SPECIALS, "--", Arc::clone(&inner_short));
        let mut outer: Package<StackSpecialsLang> = Package::new("outer");
        outer.insert_specials(CT_SPECIALS, "--", Arc::clone(&outer_short));
        outer.insert_specials(CT_SPECIALS, "---", Arc::clone(&outer_long));

        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(outer));
        scopes.push(Arc::new(inner));
        let st: Arc<ParsingState<StackSpecialsLang>> =
            Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));

        // `x---y--z`: the longest match wins across providers (`---`, defined outer),
        // and the equal-length tie goes innermost (`--` resolves to the inner spec).
        let parsed =
            run_both("x---y--z", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
        assert_eq!(
            shapes(&parsed.result),
            [
                "chars 0..1 \"x\"",
                "callable 1..4",
                "chars 4..5 \"y\"",
                "callable 5..7",
                "chars 7..8 \"z\""
            ]
        );
        let long = parsed.result.tree.root().child(1).unwrap();
        assert_eq!(long.name(), Some("---"));
        assert_eq!(long.callable_type(), Some(CT_SPECIALS));
        assert!(Arc::ptr_eq(&long.callable().unwrap().spec, &outer_long));
        let short = parsed.result.tree.root().child(3).unwrap();
        assert_eq!(short.name(), Some("--"));
        assert!(Arc::ptr_eq(&short.callable().unwrap().spec, &inner_short));
        assert!(parsed.result.diagnostics.is_empty());
        assert_partition(&parsed.result, 0..8);
    }
    // --- languages that do not obey span tiling (PLAN §1.5 R1–R7) -----------------------

    /// The shared relaxed test language ([`RelaxedStdLang`]) drives through the
    /// standard driver over a scope-stack command resolver, so the test harness can
    /// build it from a recovery setting like every other test driver.
    impl TestDriver for StdParseDriver<ScopesCommandResolver<RelaxedStdLang>> {
        fn with_recovery(recovery: Recovery) -> Self {
            relaxed_driver(recovery)
        }
    }

    // The relaxed language resolves commands under the same callable type id the test
    // languages here use, so one package definition serves both runs.
    const _: () = assert!(CT_MACRO == RELAXED_MACRO);

    /// A package defining `\foo` as a zero-argument macro and `\arg` as a macro with
    /// one mandatory `{…}` argument — the same definitions for a tiled and a relaxed
    /// language.
    fn span_tiling_macros<L>() -> Arc<Package<L>>
    where
        L: crate::state::LangHasGroups<CallableTypeId = u32, GroupTypeId = u32> + 'static,
        crate::node::ArgumentExt<L>: Default,
        L::InvocationSyntax: FromInvocation<L>,
    {
        let mut lib = Package::new("span-tiling-macros");
        lib.insert(CT_MACRO, "foo", Arc::new(StdCallableSpec::default()));
        lib.insert(
            CT_MACRO,
            "arg",
            Arc::new(StdCallableSpec::new([ArgumentSpec::new_unnamed(Arc::new(
                GroupArgumentParser::new(GT_BRACE),
            ))])),
        );
        // A two-character marker: one token per character, so the argument's node
        // covers several tokens.
        lib.insert(
            CT_MACRO,
            "opt",
            Arc::new(StdCallableSpec::new([ArgumentSpec::new_unnamed(Arc::new(
                MarkerArgumentParser::new("**"),
            ))])),
        );
        Arc::new(lib)
    }

    /// A state over [`span_tiling_macros`], for whichever language the caller names.
    fn span_tiling_state<L>() -> Arc<ParsingState<L>>
    where
        L: crate::state::LangHasGroups<
                CallableTypeId = u32,
                GroupTypeId = u32,
                Features = crate::state::AllLangFeatures,
                ModeId = (),
                StateExt = (),
            > + 'static,
        crate::node::ArgumentExt<L>: Default,
        L::InvocationSyntax: FromInvocation<L>,
    {
        let mut scopes = ScopeStack::new();
        scopes.push(span_tiling_macros::<L>());
        Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }))
    }

    /// How each `Chars` node of a parse records its content, in storage order.
    fn chars_representations<L: Lang>(result: &ParseResult<L>) -> Vec<&'static str> {
        result
            .tree
            .iter_storage_order()
            .filter_map(|node| match node.kind() {
                NodeKind::Chars { content: TextContent::Spanned(_), .. } => Some("spanned"),
                NodeKind::Chars { content: TextContent::Owned(_), .. } => Some("owned"),
                _ => None,
            })
            .collect()
    }

    /// One representative input — chars runs, a group, a comment, a paragraph break, a
    /// zero-argument macro with syntactic post-space, and a macro with a `{…}`
    /// argument — parsed by a tiled language and by one declaring
    /// `OBEYS_SPAN_TILING = false`.
    const SPAN_TILING_INPUT: &str = "a b{c d}%note\n\ne \\foo f \\arg{g} h";

    #[test]
    fn a_language_that_does_not_obey_span_tiling_parses_the_same_tree() {
        let tiled = run_both::<CmdLang>(
            SPAN_TILING_INPUT,
            &span_tiling_state(),
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
        );
        let relaxed = run_both::<RelaxedStdLang>(
            SPAN_TILING_INPUT,
            &span_tiling_state(),
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
        );

        // Same kinds, same child counts, same spans, same text — `shapes` renders all
        // four, and the chars lines resolve the content whichever way it is recorded.
        assert_eq!(shapes(&tiled.result), shapes(&relaxed.result));
        assert_eq!(
            shapes(&relaxed.result),
            [
                "chars 0..3 \"a b\"",
                "group 3..8",
                "comment 8..13 start=\"%\" content=\"note\" post=\"\"",
                // The paragraph break, staged by the loop over the hook's kind.
                "chars 13..15 \"\\n\\n\"",
                "chars 15..17 \"e \"",
                "callable 17..22",
                "chars 22..24 \"f \"",
                "callable 24..31",
                "chars 31..33 \" h\"",
            ]
        );
        assert_eq!(
            tiled.result.tree.node_count(),
            relaxed.result.tree.node_count(),
            "the two trees differ in node count"
        );

        // The content representation is what differs: a tiled language records the
        // exact span slice, a relaxed one the text its reader answered for each token
        // of the run. The exception is the paragraph-break node, whose kind the driver
        // hook builds over the break token's own span — a node whose span *is* the
        // fact's span keeps the bare span in both cases (the node-data rule).
        assert!(chars_representations(&tiled.result).iter().all(|it| *it == "spanned"));
        assert_eq!(
            chars_representations(&relaxed.result),
            ["owned", "spanned", "owned", "owned", "owned", "owned", "owned"]
        );

        // The all-trees law holds for both (`try_run` already ran the oracle, which
        // stops at this law for the relaxed language).
        crate::node::validate_tree(&tiled.result.tree).expect("the all-trees law holds");
        crate::node::validate_tree(&relaxed.result.tree).expect("the all-trees law holds");
    }

    #[test]
    fn a_relaxed_chars_run_owns_the_text_the_reader_answered() {
        let parsed = run_both::<RelaxedStdLang>(
            "  hi there ",
            &span_tiling_state(),
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
        );
        let node = parsed.result.tree.root().child(0).unwrap();
        // One maximal run over the whole input, its text owned — pre-space, characters
        // and the end-of-stream token's trailing whitespace alike.
        assert_eq!(node.chars(), Some("  hi there "));
        assert!(matches!(
            node.kind(),
            NodeKind::Chars { content: TextContent::Owned(_), .. }
        ));
        assert_eq!(node.span().range(), 0..11);
    }

    /// A reader that answers a *wrong* [`StartBeforePreSpace`](TokenEdge::StartBeforePreSpace)
    /// edge — one byte past where the peek happened — breaking the [`TokenReader`]
    /// contract's clause 7 corollary. Everything else delegates to an inner
    /// [`StdTokenReader`].
    struct SlippingReader<'s, L: Lang> {
        inner: StdTokenReader<'s>,
        lang: core::marker::PhantomData<L>,
    }

    impl<'s, L> SlippingReader<'s, L>
    where
        L: Lang<SourceOrigin = Option<String>>,
        L::Tokenization:
            Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
    {
        fn new(source: &'s Arc<Source>) -> SlippingReader<'s, L> {
            SlippingReader {
                inner: StdTokenReader::new(source),
                lang: core::marker::PhantomData,
            }
        }

        fn inner(&self) -> &dyn TokenReader<'s, L> {
            &self.inner
        }

        fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, L> {
            &mut self.inner
        }
    }

    impl<'s, L> TokenReader<'s, L> for SlippingReader<'s, L>
    where
        L: Lang<SourceOrigin = Option<String>>,
        L::Tokenization:
            Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
    {
        fn peek(
            &mut self,
            state: &Arc<ParsingState<L>>,
        ) -> TokenResult<L, StdToken<L>> {
            TokenReader::peek(&mut self.inner, state)
        }

        fn move_to(&mut self, tok: &StdToken<L>, 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 token_kind<'t>(&self, tok: &'t StdToken<L>) -> TokenKind<'t, L>
        where
            's: 't,
        {
            self.inner().token_kind(tok)
        }

        fn source_span_between(
            &self,
            tok: &StdToken<L>,
            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<L>, edge: TokenEdge) -> StdStreamPosition {
            let at = self.inner().position_at(tok, edge);
            match edge {
                // The contract violation: the token does not start where the peek
                // happened.
                TokenEdge::StartBeforePreSpace => StdStreamPosition::at(at.offset() + 1),
                _ => at,
            }
        }

        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 content loop checks the clause 7 corollary whatever the language declares
    /// about span tiling: the check is about the reader's own answers, not about where
    /// the tokens come from.
    #[test]
    fn a_token_not_starting_where_it_was_peeked_is_an_implementation_error() {
        fn detail_of(error: &ParseError) -> String {
            error
                .data()
                .downcast_ref::<crate::constructs::ImplementationError>()
                .expect("an ImplementationError condition")
                .detail
                .to_string()
        }

        let source: Arc<Source> = Arc::new(Source::new("ab"));

        let mut tiled = SlippingReader::<CmdLang>::new(&source);
        let error = try_run(
            &source,
            &mut tiled,
            &span_tiling_state::<CmdLang>(),
            Recovery::Strict,
            StopSpec::none(),
        )
        .expect_err("the reader breaks clause 7");
        assert_eq!(
            error
                .data()
                .downcast_ref::<crate::constructs::ImplementationError>()
                .expect("an ImplementationError condition")
                .kind,
            ImplementationErrorKind::TokenPositionMismatch,
        );
        let detail = detail_of(&error);
        let span = error.span().range();

        let mut relaxed = SlippingReader::<RelaxedStdLang>::new(&source);
        let error = try_run(
            &source,
            &mut relaxed,
            &span_tiling_state::<RelaxedStdLang>(),
            Recovery::Strict,
            StopSpec::none(),
        )
        .expect_err("the reader breaks clause 7 whatever the language declares");
        // The same violation, reported the same way for both languages.
        assert_eq!(detail_of(&error), detail);
        assert_eq!(error.span().range(), span);
    }
    /// A marker argument's node covers one token per marker character, so its content
    /// follows the same rule as a chars run: the text for a language with
    /// `OBEYS_SPAN_TILING = false`, the exact span slice for a tiled one.
    #[test]
    fn a_marker_argument_owns_its_text_where_the_language_does_not_obey_span_tiling() {
        fn marker_node<L: Lang>(result: &ParseResult<L>) -> crate::node::NodeRef<'_, L> {
            let call = result.tree.root().child(0).expect("the callable");
            let region: Vec<_> =
                call.argument_nodes(0).expect("provided argument").iter().collect();
            *region.last().expect("the marker node ends the region")
        }

        let tiled = run_both::<CmdLang>(
            "\\opt** x",
            &span_tiling_state(),
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
        );
        let relaxed = run_both::<RelaxedStdLang>(
            "\\opt** x",
            &span_tiling_state(),
            Recovery::Strict,
            StopSpec::none(),
            StopSpec::none(),
        );
        assert_eq!(shapes(&tiled.result), shapes(&relaxed.result));

        let tiled_marker = marker_node(&tiled.result);
        assert_eq!(tiled_marker.chars(), Some("**"));
        assert!(matches!(
            tiled_marker.kind(),
            NodeKind::Chars { content: TextContent::Spanned(_), .. }
        ));

        let relaxed_marker = marker_node(&relaxed.result);
        assert_eq!(relaxed_marker.chars(), Some("**"));
        assert!(
            matches!(
                relaxed_marker.kind(),
                NodeKind::Chars { content: TextContent::Owned(_), .. }
            ),
            "a relaxed parse records the marker as text, got {:?}",
            relaxed_marker.kind()
        );
        assert_eq!(tiled_marker.span().range(), relaxed_marker.span().range());
    }
}