techy 0.1.1

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
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use core::fmt;

use crate::engine::{Frame, FrameTitle};
use crate::error::{DiagnosticInfo, ToDiagnosticValue};
use crate::node::{BuildId, ContentNodes, NodeKind};
use crate::source::SourceSpan;
use crate::state::{Lang, ParsingState, ParsingStateDelta};
use crate::token::{GroupRule, StreamPosition, TokenEdge, TokenKind};

use super::child_state::ChildStateSpec;
use super::nodes_parser::{StopCause, StopSpec, TokenStopKind};
use super::{push_token_text, ConstructParser, ConstructParserResult, FromInvocation, ParseContext};

/// Condition: an environment's body found the terminator of a *different* environment.
///
/// Raised for `\begin{A}…\end{B}`: the terminator names `B`, but the body being parsed
/// belongs to `A`. The body closes at that point **without** consuming the terminator,
/// so an enclosing level can still claim it as its own.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.environments.terminator-mismatch",
    message = "missing terminator of environment ‘{expected}’: found the terminator of \
               ‘{found}’ instead"
)]
pub struct EnvironmentTerminatorMismatch {
    /// The environment being parsed, whose terminator was expected.
    pub expected: String,
    /// The environment named by the terminator that was found instead.
    pub found: String,
}

/// Condition: an environment's terminator command was not followed immediately by its
/// name group.
///
/// The name group is rigid — no comment, no paragraph break, and no whitespace inside
/// the name — so both `\end[y]` and `\end{ A }` raise this. The terminator command
/// alone is consumed and the body closes; whatever follows it is parsed as content of
/// the enclosing level.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.environments.malformed-terminator",
    message = "malformed terminator of environment ‘{environment}’: expected its name \
               group immediately after the command"
)]
pub struct MalformedEnvironmentTerminator {
    /// The environment being parsed.
    pub environment: String,
}

/// Condition: an environment's body ended without its terminator ever appearing.
///
/// The input ended inside the body, a group close delimiter appeared that nothing at
/// the body's level had opened, or the reading stopped at a token the reader could not
/// read; [`found`](MissingEnvironmentTerminator::found) says which.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.environments.missing-terminator")]
pub struct MissingEnvironmentTerminator {
    /// The environment being parsed.
    pub environment: String,
    /// What ended the body instead.
    pub found: MissingTerminatorFound,
}

/// What ended a body whose terminator never appeared ([`MissingEnvironmentTerminator`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToDiagnosticValue)]
#[non_exhaustive]
pub enum MissingTerminatorFound {
    /// The input ended inside the body.
    EndOfInput,
    /// A group close delimiter appeared that nothing at the body's level had opened.
    /// The body closes without consuming it, leaving it for an enclosing level to
    /// claim.
    StrayGroupClose,
    /// The body ended at a token the reader could not read and the driver tolerated.
    /// The input has *not* ended: the body closes where the reading stopped, and the
    /// enclosing content loop re-reads the failing token and applies its own token
    /// recovery to it.
    ///
    /// Only a raw body ([`VerbatimBodyParser`](super::VerbatimBodyParser)) reports
    /// this, and only when the embedder supplies its own token reader: the standard
    /// reader has nothing left to reject under the raw-reading state.
    UnreadableToken,
}

// Hand-written wording: the message varies by what ended the body (a match, which the
// message format string cannot express).
impl fmt::Display for MissingEnvironmentTerminator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.found {
            MissingTerminatorFound::EndOfInput => write!(
                f,
                "missing terminator of environment ‘{}’ before end of input",
                self.environment
            ),
            MissingTerminatorFound::StrayGroupClose => {
                write!(f, "missing terminator of environment ‘{}’", self.environment)
            }
            MissingTerminatorFound::UnreadableToken => write!(
                f,
                "missing terminator of environment ‘{}’ before a token that could not \
                 be read",
                self.environment
            ),
        }
    }
}

/// A rigid environment name group that was read successfully — `{align}` in
/// `\begin{align}`.
///
/// Returned by [`read_rigid_name_group`], which consumes the whole group. The name is
/// recorded twice, because the two forms can differ:
/// [`name_span`](NameGroup::name_span) is *where* the name lies — the coordinates that
/// anchor diagnostics and the parse that follows the group — and
/// [`name_text`](NameGroup::name_text) is *what* the name is — the characters the parser
/// read, which drive definition lookups, node data and diagnostic messages. The group
/// also records the stream position just past the close delimiter
/// ([`end`](NameGroup::end)) and the group rule its delimiters matched
/// ([`rule`](NameGroup::rule)).
///
/// The two name forms agree for a language that obeys span tiling
/// ([`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING)): there the text is
/// the span's [`content()`](SourceSpan::content). For a language that does not obey it,
/// the span only describes the stretch the name was read from and its content need not
/// be the name, so the parser records the characters as read
/// ([`with_name_as_read`](NameGroup::with_name_as_read)). Read the name through
/// `name_text`, never off the span.
pub struct NameGroup<L: Lang> {
    /// Where the name lies — see [`name_span`](NameGroup::name_span).
    name: SourceSpan<L::SourceOrigin>,
    /// See [`end`](NameGroup::end).
    end: StreamPosition<L>,
    /// See [`rule`](NameGroup::rule).
    rule: Arc<GroupRule<L>>,
    /// The name as the parser read it, when the `name` span cannot answer it — see
    /// [`name_text`](NameGroup::name_text). Set only through
    /// [`with_name_as_read`](NameGroup::with_name_as_read), so no caller can pair a
    /// span with text that disagrees with it.
    name_as_read: Option<Box<str>>,
}

impl<L: Lang> NameGroup<L> {
    /// Creates a name group whose name is exactly what the `name` span covers.
    ///
    /// That holds for a language that obeys span tiling
    /// ([`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING)), and for any
    /// name whose span was derived from a single token's own span. Otherwise record the
    /// characters as read with [`with_name_as_read`](NameGroup::with_name_as_read).
    pub fn new(
        name: SourceSpan<L::SourceOrigin>,
        end: StreamPosition<L>,
        rule: Arc<GroupRule<L>>,
    ) -> NameGroup<L> {
        NameGroup { name, end, rule, name_as_read: None }
    }

    /// Records the name **as read** — the characters the parser actually consumed — so
    /// that [`name_text`](NameGroup::name_text) answers those instead of the `name`
    /// span's content.
    ///
    /// A parser for a language with
    /// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false` must do
    /// this: there the span only describes the stretch the name was read from, so its
    /// content need not be the name.
    pub fn with_name_as_read(mut self, name: impl Into<Box<str>>) -> NameGroup<L> {
        self.name_as_read = Some(name.into());
        self
    }

    /// Where the name lies: the stretch between the delimiters, as the reader described
    /// it.
    ///
    /// Use this span to anchor diagnostics, to start the argument parse that follows the
    /// group, and as the node's invocation-name span. Its content is the name only for a
    /// language that obeys span tiling — read the name through
    /// [`name_text`](NameGroup::name_text), never off this span.
    pub fn name_span(&self) -> &SourceSpan<L::SourceOrigin> {
        &self.name
    }

    /// The name as read: the exact characters between the delimiters.
    ///
    /// For a language that obeys span tiling
    /// ([`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING)) this is the
    /// [`name_span`](NameGroup::name_span)'s content. For a language that does not, the
    /// span only describes the stretch the name was read from — its content need not be
    /// the name at all — so the parser records the characters as it reads them
    /// ([`with_name_as_read`](NameGroup::with_name_as_read)) and this method answers
    /// those.
    ///
    /// The name is what drives definition lookups, node data and diagnostic messages.
    pub fn name_text(&self) -> &str {
        match &self.name_as_read {
            Some(name) => name,
            None => self.name.content(),
        }
    }

    /// The stream position just past the group's close delimiter.
    pub fn end(&self) -> &StreamPosition<L> {
        &self.end
    }

    /// The group rule the name group's delimiters matched.
    ///
    /// The `Arc` is cloned from the matched group-open token, so the rule's
    /// `open`/`close` strings are the delimiter characters exactly as written: a read
    /// that deviates in any way reports "not a name group" rather than returning a group
    /// with different delimiters. A language that records how an environment was written
    /// stores this rule as the name group's spelling.
    pub fn rule(&self) -> &Arc<GroupRule<L>> {
        &self.rule
    }
}

// Manual impls: derives would demand `L: Clone`/`L: Debug` although only an `Arc`
// to rule data is stored.

impl<L: Lang> Clone for NameGroup<L> {
    fn clone(&self) -> Self {
        NameGroup {
            name: self.name.clone(),
            end: self.end.clone(),
            rule: Arc::clone(&self.rule),
            name_as_read: self.name_as_read.clone(),
        }
    }
}

impl<L: Lang> fmt::Debug for NameGroup<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NameGroup")
            .field("name", &self.name)
            .field("end", &self.end)
            .field("rule", &self.rule)
            .field("name_as_read", &self.name_as_read)
            .finish()
    }
}

/// How a consumed environment `\begin{name}` trigger was spelled in the source.
///
/// The parser composition driving the environment builds this from the command token
/// and the name group [`read_rigid_name_group`] matched, and passes it — together with
/// the terminator's [`EnvironmentTerminatorSyntaxData`] — to the language's invocation
/// syntax record, which the node stores as
/// [`CallableData::invocation_syntax`](crate::core::node::CallableData::invocation_syntax)
/// so the environment can be re-emitted as written.
///
/// The fields mirror those of the
/// [`Scanned`](EnvironmentTerminatorSyntaxData::Scanned) variant: source-qualified
/// spans, as the reader answered them, plus the matched name group. A site that records
/// one of these spans as node data converts it first — a span that is not in the node's
/// own source is recorded as text.
pub struct EnvironmentBeginSyntaxData<L: Lang> {
    /// The begin command's escape character as written.
    pub escape_char: char,
    /// The command word (the name, without the escape character).
    pub command_word: SourceSpan<L::SourceOrigin>,
    /// The command token's own syntactic post-space (`\begin {name}`'s
    /// tolerated inline whitespace).
    pub post_space: SourceSpan<L::SourceOrigin>,
    /// The matched rigid name group (name, end, and the matched rule).
    pub name_group: NameGroup<L>,
}

// Manual impls: derives would demand `L: Clone`/`L: Debug`.

impl<L: Lang> Clone for EnvironmentBeginSyntaxData<L> {
    fn clone(&self) -> Self {
        EnvironmentBeginSyntaxData {
            escape_char: self.escape_char,
            command_word: self.command_word.clone(),
            post_space: self.post_space.clone(),
            name_group: self.name_group.clone(),
        }
    }
}

impl<L: Lang> fmt::Debug for EnvironmentBeginSyntaxData<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnvironmentBeginSyntaxData")
            .field("escape_char", &self.escape_char)
            .field("command_word", &self.command_word)
            .field("post_space", &self.post_space)
            .field("name_group", &self.name_group)
            .finish()
    }
}

/// How a consumed environment terminator (`\end{name}`) was spelled in the source.
///
/// Reported on [`EnvironmentBody::terminator`] by the parser that consumed the
/// terminator — [`EnvironmentBodyParser`] or
/// [`VerbatimBodyParser`](super::VerbatimBodyParser). The composition driving the
/// environment passes it, together with the begin side's
/// [`EnvironmentBeginSyntaxData`], to the language's invocation syntax record.
#[non_exhaustive]
pub enum EnvironmentTerminatorSyntaxData<L: Lang> {
    /// The terminator was tokenized: the stop command followed by its rigid name group.
    /// Its full spelling is reported as source-qualified spans (a site that records one
    /// of them as node data converts it first).
    Scanned {
        /// The terminator command's escape character as written.
        escape_char: char,
        /// The command word (the name, without the escape character).
        command_word: SourceSpan<L::SourceOrigin>,
        /// The command token's own syntactic post-space (`\end {name}`'s
        /// tolerated inline whitespace).
        post_space: SourceSpan<L::SourceOrigin>,
        /// The matched rigid name group (name, end, and the matched rule).
        name_group: NameGroup<L>,
    },
    /// The terminator was consumed as one **literal** string the parser was given no
    /// finer description of
    /// ([`VerbatimBodyTerminator::Literal`](super::VerbatimBodyTerminator::Literal)):
    /// the matched span is the only fact there is to report.
    ///
    /// A raw body whose terminator *was* described piece by piece reports
    /// [`Scanned`](EnvironmentTerminatorSyntaxData::Scanned) instead, even though it too
    /// consumed the terminator as a single token.
    Literal {
        /// The consumed literal terminator's span.
        span: SourceSpan<L::SourceOrigin>,
    },
}

// Manual impls: derives would demand `L: Clone`/`L: Debug`.

impl<L: Lang> Clone for EnvironmentTerminatorSyntaxData<L> {
    fn clone(&self) -> Self {
        match self {
            EnvironmentTerminatorSyntaxData::Scanned {
                escape_char,
                command_word,
                post_space,
                name_group,
            } => EnvironmentTerminatorSyntaxData::Scanned {
                escape_char: *escape_char,
                command_word: command_word.clone(),
                post_space: post_space.clone(),
                name_group: name_group.clone(),
            },
            EnvironmentTerminatorSyntaxData::Literal { span } => {
                EnvironmentTerminatorSyntaxData::Literal { span: span.clone() }
            }
        }
    }
}

impl<L: Lang> fmt::Debug for EnvironmentTerminatorSyntaxData<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EnvironmentTerminatorSyntaxData::Scanned {
                escape_char,
                command_word,
                post_space,
                name_group,
            } => f
                .debug_struct("Scanned")
                .field("escape_char", escape_char)
                .field("command_word", command_word)
                .field("post_space", post_space)
                .field("name_group", name_group)
                .finish(),
            EnvironmentTerminatorSyntaxData::Literal { span } => {
                f.debug_struct("Literal").field("span", span).finish()
            }
        }
    }
}

/// Reads a rigid environment name group at the reader's position — `{align}` in
/// `\begin{align}`.
///
/// "Rigid" is the whole syntax: the group open of class `name_group_type` must be the
/// immediately next token (no whitespace before it — inline whitespace after the
/// introducing command is that command token's own post-space and was consumed with it;
/// comments and paragraph breaks are not tolerated), the interior must be characters
/// with no whitespace, and the matching close delimiter must follow.
///
/// On success the whole group is consumed and its facts are returned as a
/// [`NameGroup`]. On **any** deviation nothing is consumed — the reader is rewound to
/// where it stood — and `None` is returned; the caller applies its own recovery, since
/// a syntax this rigid leaves no finer distinction to report than "not a name group".
///
/// Use this when composing an environment-shaped construct of your own: a
/// `\begin`-shaped `make_invocation_parser` override reads the environment name with
/// this call before resolving the environment and running an
/// [`EnvironmentBodyParser`].
///
/// # Errors
///
/// Returns the parse error when the token reader fails and the driver's recovery is
/// strict. Under tolerant recovery a token error is not diagnosed here: the read
/// reports `None` and consumes nothing, and the enclosing content loop re-reads the
/// failing token and applies its own token recovery
/// ([`ParseContext::probe_token`]).
pub fn read_rigid_name_group<L: Lang>(
    cx: &mut ParseContext<'_, '_, L>,
    name_group_type: L::GroupTypeId,
) -> ConstructParserResult<L, Option<NameGroup<L>>> {
    let Some(open) = cx.probe_token(&Arc::clone(&cx.state))? else {
        return Ok(None);
    };
    // "Rigid": the open delimiter follows the trigger with no whitespace between —
    // its pre-space edge and its start edge coincide.
    let tight = cx.tokens.position_at(&open, TokenEdge::StartBeforePreSpace)
        == cx.tokens.position_at(&open, TokenEdge::Start);
    let rule = match cx.tokens.token_kind(&open) {
        TokenKind::GroupOpen { rule, .. }
            if rule.group_type == name_group_type && tight =>
        {
            Arc::clone(rule)
        }
        _ => return Ok(None),
    };
    cx.tokens.move_to(&open, TokenEdge::EndPastPostSpace);

    // The interior tokens are read under base + expecting_group_close (the memoized
    // derivation the group parser uses — the driver's descent delta included), so the
    // close delimiter is guaranteed recognizable regardless of the base's delimiter
    // table.
    let interior_state = cx.group_interior_state(&rule)?;
    let result = cx.with_parsing_state(interior_state, |cx| read_name_chars(cx, &rule));
    match result? {
        Some(name_group) => Ok(Some(name_group)),
        None => {
            // Nothing consumed: the reader goes back to the open delimiter, exactly
            // where this read started (a name group's open delimiter has no
            // pre-space — the match above requires it).
            cx.tokens.move_to(&open, TokenEdge::StartBeforePreSpace);
            Ok(None)
        }
    }
}

/// The interior loop of [`read_rigid_name_group`]: consecutive `Char` tokens — no
/// whitespace anywhere, rigid — up to the close delimiter of `rule`.
///
/// The name spans several tokens, so for a language with
/// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false` its
/// characters are accumulated as they are read and recorded on the group
/// ([`NameGroup::with_name_as_read`]): there the span between the two positions is only
/// what the reader describes for the stretch, and the name drives lookups, node data
/// and diagnostics.
fn read_name_chars<L: Lang>(
    cx: &mut ParseContext<'_, '_, L>,
    rule: &Arc<GroupRule<L>>,
) -> ConstructParserResult<L, Option<NameGroup<L>>> {
    let name_start = cx.tokens.position_here();
    let mut name_end = name_start.clone();
    let mut name_as_read = (!L::OBEYS_SPAN_TILING).then(String::new);
    let state = Arc::clone(&cx.state);
    loop {
        let Some(token) = cx.probe_token(&state)? else {
            return Ok(None);
        };
        if cx.tokens.position_at(&token, TokenEdge::StartBeforePreSpace)
            != cx.tokens.position_at(&token, TokenEdge::Start)
        {
            return Ok(None);
        }
        match cx.tokens.token_kind(&token) {
            TokenKind::Char(c) => {
                // The recipe all multi-token content follows: pre-space, spelling,
                // post-space, each as the reader answers it for this token. (The
                // rigid check above rejects a token whose pre-space edge and start
                // edge differ, so the pre-space is empty here — but the recipe does
                // not need to know that.)
                push_token_text(&mut name_as_read, cx, &token, c.encode_utf8(&mut [0u8; 4]));
                name_end = cx.tokens.position_at(&token, TokenEdge::EndPastPostSpace);
                cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
            }
            TokenKind::GroupClose { delim } if *delim == *rule.close => {
                cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
                let group = NameGroup::new(
                    cx.source_span_within(&name_start, &name_end)?,
                    cx.tokens.position_at(&token, TokenEdge::EndPastPostSpace),
                    Arc::clone(rule),
                );
                return Ok(Some(match name_as_read {
                    Some(name) => group.with_name_as_read(name),
                    None => group,
                }));
            }
            _ => return Ok(None),
        }
    }
}

/// A parsed environment body: the staged body node, where the environment ends, and how
/// it was terminated.
///
/// Produced by [`EnvironmentBodyParser`] and by
/// [`VerbatimBodyParser`](super::VerbatimBodyParser). The invocation parser driving the
/// environment turns it into the callable's body slot.
pub struct EnvironmentBody<L: Lang> {
    /// The staged body [`List`](crate::core::node::NodeKind::List) node: its span is the
    /// body's content interior and its children are the body's nodes. An empty body is
    /// an empty `List` node, not an absent one.
    pub body: BuildId,
    /// The stream position just past the environment's extent: past the consumed
    /// terminator on the clean path, past the stop command alone after a malformed
    /// terminator, and the body's end when the body closed with nothing consumed (name
    /// mismatch, unexpected group close, end of input). The driving invocation parser
    /// ends the callable's span here.
    pub end: StreamPosition<L>,
    /// Which of the body's nodes are the body slot's content, ready for the driving
    /// composition's [`ParsedSlot`](crate::core::node::ParsedSlot) record.
    ///
    /// [`EnvironmentBodyParser`] designates all of the body `List`'s children. A
    /// verbatim body designates its gobbled leading newline *out*
    /// ([`VerbatimBodyParser`](super::VerbatimBodyParser)): the parser that staged the
    /// body is the one that knows which nodes are content, exactly as for arguments.
    pub content: ContentNodes,
    /// How the consumed terminator was spelled
    /// ([`EnvironmentTerminatorSyntaxData`]), or `None` when the body closed without
    /// consuming one (name mismatch, malformed terminator, unexpected group close, end
    /// of input).
    ///
    /// The driving composition passes these facts, together with the begin side's
    /// [`EnvironmentBeginSyntaxData`], to the language's invocation syntax record when
    /// it builds the node's payload.
    pub terminator: Option<EnvironmentTerminatorSyntaxData<L>>,
    /// The parsing state the body's content run ended in
    /// ([`NodesOutcome::state`](super::NodesOutcome::state)): the state the run reached
    /// after applying the after-effects of its own nodes.
    ///
    /// This is the only place the definitions recorded in
    /// [`after_effects`](EnvironmentBody::after_effects) can be inspected
    /// (`state.scopes().retrieve_spec(…)`), since that record stores operations rather
    /// than a symbol table. It is not kept anywhere once the invocation is parsed.
    ///
    /// A body that runs no content loop — a verbatim body, whose raw text can generate
    /// no after-effects — reports the state the parser was entered with, unchanged. (Its
    /// raw content is read under a state derived from that one, which is recorded on the
    /// content node rather than here.)
    pub exit_state: Arc<ParsingState<L>>,
    /// The after-effects the body's nodes generated
    /// ([`NodesOutcome::after_effects`](super::NodesOutcome::after_effects)): one delta,
    /// the run's sibling after-effects merged in application order, with no provenance.
    /// `None` when the run applied none, and for a body that runs no content loop.
    ///
    /// The record is raw and unfiltered. A body parser only *reports* what the parsed
    /// nodes generated, exactly like [`NodesParser`](super::NodesParser); its own
    /// pass-through delta stays `None`, and the composition driving the environment
    /// decides what, if anything, escapes it. The LaTeX-like preset routes it through
    /// [`LatexlikeParseDriver::environment_after_effects`](crate::latexlike::LatexlikeParseDriver::environment_after_effects),
    /// the environment counterpart of
    /// [`GroupAfterEffectsFn`](super::GroupAfterEffectsFn).
    pub after_effects: Option<Box<ParsingStateDelta<L>>>,
}

// Manual impls: derives would demand `L: Clone`/`L: Debug`.

impl<L: Lang> Clone for EnvironmentBody<L> {
    fn clone(&self) -> Self {
        EnvironmentBody {
            body: self.body,
            end: self.end.clone(),
            content: self.content.clone(),
            terminator: self.terminator.clone(),
            exit_state: Arc::clone(&self.exit_state),
            after_effects: self.after_effects.clone(),
        }
    }
}

impl<L: Lang> fmt::Debug for EnvironmentBody<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnvironmentBody")
            .field("body", &self.body)
            .field("end", &self.end)
            .field("content", &self.content)
            .field("terminator", &self.terminator)
            .field("exit_state", &self.exit_state)
            .field("after_effects", &self.after_effects)
            .finish()
    }
}

/// Parses the body of an environment-shaped construct: the content up to its
/// terminator, and the terminator itself — the ` … \end{align}` part of
/// `\begin{align} … \end{align}`.
///
/// The core has no built-in notion of an "environment": that is preset vocabulary (see
/// [the language syntax guide](crate::guide::language_syntax#environments)). What the
/// core provides is this parser, which reads sibling content until a chosen terminator
/// command appears, checks the name group written after that command, and consumes the
/// terminator. The LaTeX-like preset builds `\begin{name} … \end{name}` out of it. For
/// a body read as raw text instead of parsed nodes, use
/// [`VerbatimBodyParser`](super::VerbatimBodyParser).
///
/// The invocation parser driving the environment constructs one with
/// [`new`](EnvironmentBodyParser::new), which takes the three facts about the
/// terminator: the stop command's name (`end`), the group class its name group is
/// written in (`{`…`}`), and — through
/// [`with_match_invocation_name`](EnvironmentBodyParser::with_match_invocation_name) —
/// whether that name must repeat the invocation's. None of this is declared spec-side:
/// the composition driving the parser also mints the
/// [`ParsedSlot`](crate::core::node::ParsedSlot) record for the body.
///
/// # Where the body ends
///
/// The content loop stops at the first command token named `stop_command_name` that
/// occurs at the body's *own* nesting level; a terminator inside a nested group or a
/// nested environment belongs to that construct and never ends this body.
///
/// The terminator itself is rigid: the stop command followed **immediately** by its name
/// group, with no comment, no paragraph break, and no whitespace inside the name. The
/// command token's own syntactic post-space (`\end {name}`) is the one tolerated gap.
/// The name in the group is compared for exact equality with the invocation name
/// (`align` for `\begin{align} … \end{align}`) unless name matching was turned off.
///
/// # What ends up in the tree
///
/// The body's nodes become the children of one staged
/// [`List`](crate::core::node::NodeKind::List) node, reported as
/// [`EnvironmentBody::body`], and all of them are designated as the body slot's content
/// ([`EnvironmentBody::content`]). The consumed terminator's characters appear in no
/// node: they lie between the `List` node's end and the end of the callable's span
/// ([`EnvironmentBody::end`]), and their spelling is reported separately as
/// [`EnvironmentBody::terminator`], from which they can be reconstructed.
///
/// The parser returns no pass-through state delta. It reports the content run's merged
/// after-effects and exit state on the produced [`EnvironmentBody`]
/// ([`after_effects`](EnvironmentBody::after_effects),
/// [`exit_state`](EnvironmentBody::exit_state)) instead, and the driving composition
/// decides what, if anything, escapes the environment.
///
/// # The state the body is read under
///
/// Both the body content *and* the terminator are read under
/// [`ParseContext::state`](ParseContext::state) as the caller left it: the driving
/// invocation parser stacks the environment's body delta on the invocation's base state
/// and reverts it structurally when the body ends, exactly as for arguments. The core
/// never interprets that delta — in the preset it is an ordinary field of the
/// environment's definition.
///
/// A body state that cannot tokenize the stop command runs the body to the end of the
/// input. This is a genuine pitfall: environments do not recover the way an unclosed
/// group does.
///
/// # Recovery
///
/// Each case below is reported through [`ParseContext::recover`], so a strict driver
/// aborts the parse and a tolerant one records the diagnostic and continues as
/// described:
///
/// - *Name mismatch* (`\begin{A}…\begin{B}…\end{A}`):
///   [`EnvironmentTerminatorMismatch`], then close the body **without consuming** the
///   terminator, so the enclosing environment's parser can find and consume its own
///   `\end{A}`. A terminator no level claims eventually reaches the root content loop
///   as an ordinary command and takes the unresolvable-command recovery.
/// - *Malformed terminator* (no rigid name group after the stop command):
///   [`MalformedEnvironmentTerminator`], then consume the command **alone** and close.
///   Leaving it unconsumed would cascade the same malformed token through every
///   enclosing level; what follows it is parsed as content of the enclosing level.
/// - *End of input*: [`MissingEnvironmentTerminator`] with
///   [`MissingTerminatorFound::EndOfInput`], anchored at the invocation trigger rather
///   than at the end of the input, then close.
/// - *A group close nobody at the body's level opened*:
///   [`MissingEnvironmentTerminator`] with [`MissingTerminatorFound::StrayGroupClose`],
///   then close without consuming it, leaving it for an enclosing level (or the root
///   content loop) to claim.
///
/// On all four paths [`EnvironmentBody::terminator`] is `None`, and
/// [`EnvironmentBody::end`] is the body's end — except after a malformed terminator,
/// where it is the position just past the consumed stop command.
pub struct EnvironmentBodyParser<'p, L: Lang> {
    /// The invocation trigger's span (`\begin{name}`'s command token), anchoring the
    /// missing-terminator diagnostic (the group parser's unclosed-at-open precedent).
    trigger_span: SourceSpan<L::SourceOrigin>,
    /// The invocation name the terminator must back-reference (`align` for
    /// `\begin{align} … \end{align}`), and the name diagnostics call the environment.
    invocation_name: &'p str,
    /// The terminator command's name (`end`), the body loop's stop condition.
    stop_command_name: &'p str,
    /// The group class of the terminator's name group.
    name_group_type: L::GroupTypeId,
    /// Whether the terminator's name must match `invocation_name` (default: `true`).
    match_invocation_name: bool,
    /// The span of the invocation name as written (`align` in `\begin{align}`), when
    /// the caller has one: it titles the body's traceback frame (`environment ‘align’`).
    /// Without it the frame falls back to the generic "environment body".
    /// (`invocation_name` itself is a borrowed `&str`, which the allocation-free frame
    /// cannot hold; a span can.)
    invocation_name_span: Option<SourceSpan<L::SourceOrigin>>,
}

impl<'p, L: Lang> EnvironmentBodyParser<'p, L> {
    /// Creates a body parser for the environment invoked as `invocation_name` (trigger
    /// token span `trigger_span`), terminated by the command `stop_command_name`
    /// followed by its rigid name group of class `name_group_type`.
    pub fn new(
        trigger_span: SourceSpan<L::SourceOrigin>,
        invocation_name: &'p str,
        stop_command_name: &'p str,
        name_group_type: L::GroupTypeId,
    ) -> EnvironmentBodyParser<'p, L> {
        EnvironmentBodyParser {
            trigger_span,
            invocation_name,
            stop_command_name,
            name_group_type,
            match_invocation_name: true,
            invocation_name_span: None,
        }
    }

    /// Sets whether the terminator's name must match the invocation name (default:
    /// `true`).
    ///
    /// With matching off, any rigid name group closes the body — for constructs whose
    /// terminator does not repeat the name written at the opening.
    pub fn with_match_invocation_name(mut self, match_invocation_name: bool) -> Self {
        self.match_invocation_name = match_invocation_name;
        self
    }

    /// Provides the span of the invocation name as written in the source, so the body's
    /// traceback frame can quote it (`environment ‘align’`).
    ///
    /// Drivers that read the name from a name group pass that group's
    /// [`name_span()`](NameGroup::name_span). Without it the frame is titled
    /// "environment body".
    pub fn with_invocation_name_span(mut self, name_span: SourceSpan<L::SourceOrigin>) -> Self {
        self.invocation_name_span = Some(name_span);
        self
    }

    /// The terminator flow, entered with the matched stop command left unconsumed at
    /// its span start: read the rigid name group that must follow immediately, check the
    /// name against the invocation's, and consume the terminator — or leave it
    /// unconsumed for an enclosing level (the recovery rules on the type).
    /// Returns the environment's end position, plus the consumed terminator's
    /// spelling facts on the clean path ([`EnvironmentTerminatorSyntaxData::Scanned`];
    /// `None` on every recovery path — nothing well-formed was consumed).
    // The return type spells the flow's two answers; an alias would name one method's
    // tuple, not a concept.
    #[allow(clippy::type_complexity)]
    fn finish_terminator(
        &self,
        cx: &mut ParseContext<'_, '_, L>,
    ) -> ConstructParserResult<L, (StreamPosition<L>, Option<EnvironmentTerminatorSyntaxData<L>>)>
    {
        // Re-read the stop token (its pre-space is already flushed as body content, so
        // it sits at its own span start). It was cleanly read under this same state
        // moments ago, so a mismatch here can only mean a misbehaving custom reader —
        // an extension contract violation, reported as an implementation error
        // ([§dd-dr:panic-policy]: outer-layer input never panics core code).
        let Some(end_token) = cx.probe_token(&Arc::clone(&cx.state))? else {
            return Err(cx.implementation_error(
                "the matched environment stop token disappeared on re-peek \
                 (the token reader re-read the same position differently)",
                cx.here(),
            ));
        };
        let token_escape_char = match cx.tokens.token_kind(&end_token) {
            TokenKind::Command { name, escape_char }
                if name == self.stop_command_name =>
            {
                escape_char
            }
            _ => {
                return Err(cx.implementation_error(
                    "the matched environment stop token changed on re-peek \
                     (the token reader re-read the same position differently)",
                    cx.tokens.source_span_of(&end_token),
                ));
            }
        };
        // The command token's own spelling, as the reader answers it: the whole
        // command (escape character included) and the syntactic post-space that follows
        // it. The command *word* is the command minus its escape character, which is
        // the command's first character by construction.
        let command = cx.tokens.source_span_between(&end_token, TokenEdge::Start, TokenEdge::End);
        let command_word = SourceSpan::new(
            command.source(),
            (command.start() + token_escape_char.len_utf8())..command.end(),
        );
        let token_post_space =
            cx.tokens.source_span_between(&end_token, TokenEdge::End, TokenEdge::EndPastPostSpace);
        // Consume the command whole (syntactic post-space included — `\end {name}`'s
        // tolerated inline whitespace); the name group must be the very next token.
        cx.tokens.move_to(&end_token, TokenEdge::EndPastPostSpace);
        let after_command = cx.tokens.position_here();

        match read_rigid_name_group(cx, self.name_group_type)? {
            Some(name_group) => {
                let name = name_group.name_text();
                if !self.match_invocation_name || name == self.invocation_name {
                    // The consumed terminator's spelling, straight off the
                    // command token (kind validated at the re-peek above) and the
                    // matched name group.
                    let end = name_group.end().clone();
                    let facts = Some(EnvironmentTerminatorSyntaxData::Scanned {
                        escape_char: token_escape_char,
                        command_word,
                        post_space: token_post_space,
                        name_group,
                    });
                    Ok((end, facts))
                } else {
                    // Mismatch: close without consuming — rewind to the terminator
                    // command's start and leave the whole terminator for an enclosing
                    // level.
                    let terminator_start =
                        cx.tokens.position_at(&end_token, TokenEdge::Start);
                    let span = cx.source_span_within(&terminator_start, name_group.end())?;
                    cx.recover(
                        EnvironmentTerminatorMismatch::new(self.invocation_name, name),
                        span,
                    )?;
                    cx.tokens.move_to(&end_token, TokenEdge::Start);
                    Ok((terminator_start, None))
                }
            }
            None => {
                // Malformed terminator: consume the command alone (the failed name
                // group read consumed nothing — the reader stands just past the
                // command) and close. A reader that drifted from that position broke
                // the read-consume contract — an implementation error, not recoverable.
                if cx.tokens.position_here() != after_command {
                    return Err(cx.implementation_error(
                        "the token reader moved during a failed terminator name-group \
                         read (a failed read must consume nothing)",
                        cx.tokens.source_span_of(&end_token),
                    ));
                }
                cx.recover(
                    MalformedEnvironmentTerminator::new(self.invocation_name),
                    cx.tokens.source_span_of(&end_token),
                )?;
                Ok((after_command, None))
            }
        }
    }
}

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

    fn parse(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
    ) -> ConstructParserResult<L, (EnvironmentBody<L>, Option<Box<ParsingStateDelta<L>>>)> {
        // The environment-body traceback frame ([§dd-dr:errors]), covering the body content *and*
        // the terminator flow — terminator diagnostics name the environment being
        // parsed. Anchored at the invocation trigger.
        let title = match &self.invocation_name_span {
            Some(name_span) => {
                FrameTitle::Quoted { label: "environment", name: name_span.clone() }
            }
            None => FrameTitle::Static("environment body"),
        };
        let frame = Frame { title, span: self.trigger_span.clone() };
        cx.with_frame(frame, |cx| self.parse_body(cx))
    }
}

impl<L: Lang> EnvironmentBodyParser<'_, L>
where
    L::InvocationSyntax: FromInvocation<L>,
{
    /// The body parse proper, run under the environment's traceback frame.
    // The return type is the `ConstructParser::parse` shape spelled out; an alias for
    // it would name one method's tuple, not a concept.
    #[allow(clippy::type_complexity)]
    fn parse_body(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
    ) -> ConstructParserResult<L, (EnvironmentBody<L>, Option<Box<ParsingStateDelta<L>>>)> {
        let body_start = cx.tokens.position_here();

        // The content loop, stopping at the terminator command — `consume = false`,
        // deliberately: whether the terminator is consumed hinges on the name group
        // *after* it, invisible at the stop point (the [§dd-dr:parsers-engine] manual post-stop lookahead).
        // Conditions are tested only at this nesting level, so a terminator inside a
        // nested group or environment never stops this body.
        let stop = StopSpec::at_token(
            TokenStopKind::Command { name: self.stop_command_name },
            false,
        );
        // The body runs under the caller-prepared cx.state (the spec's body delta is
        // the driving invocation parser's business); the content-loop parser comes
        // from the driver's factory (Phase 7.2 uniform routing).
        let body_state = Arc::clone(&cx.state);
        let (outcome, delta) = cx.parse_nodes(body_state, stop, ChildStateSpec::inherit())?;
        // The content-loop parser comes from the driver's factory (outer-layer code
        // for a custom driver), so its contract is validated, not debug-asserted
        // ([§dd-dr:panic-policy]).
        if delta.is_some() {
            return Err(cx.implementation_error(
                "the driver's content-loop parser returned a pass-through state delta \
                 (a nodes parser has no after-effect to report)",
                cx.here(),
            ));
        }
        // The interior run's after-effect facts, taken off the outcome before its
        // remaining fields are consumed below: the state the run reached and its merged
        // record, reported raw on the produced body ([`EnvironmentBody::after_effects`]).
        // This parser's own pass-through delta stays `None` — what escapes an
        // environment is the driving composition's call, not the body helper's.
        let exit_state = Arc::clone(&outcome.state);
        let after_effects = outcome.after_effects;

        // The body's content interior ends where the reader stands: the content loop
        // leaves every stop token unconsumed at its own start, with its pre-space
        // already flushed as body content, so this is exactly the end of the last
        // staged node (span tiling, where the language obeys it) and — unlike a node's
        // span end —
        // it is a stream position, which is what the environment's extent is measured
        // in.
        let body_end = cx.tokens.position_here();
        let body_span = cx.source_span_within(&body_start, &body_end)?;

        let (end, terminator) = match outcome.stop {
            StopCause::TokenCondition { .. } => self.finish_terminator(cx)?,
            StopCause::EndOfInput => {
                cx.recover(
                    MissingEnvironmentTerminator::new(
                        self.invocation_name,
                        MissingTerminatorFound::EndOfInput,
                    ),
                    self.trigger_span.clone(),
                )?;
                (body_end.clone(), None)
            }
            // A group close nobody at this level asked for: close the body without
            // consuming it (decision 8's unwinding — the stray close is left for an
            // enclosing level, or the root, to claim).
            StopCause::UnexpectedGroupClose { span, .. } => {
                cx.recover(
                    MissingEnvironmentTerminator::new(
                        self.invocation_name,
                        MissingTerminatorFound::StrayGroupClose,
                    ),
                    span,
                )?;
                (body_end.clone(), None)
            }
            StopCause::NodeCondition => {
                return Err(cx.implementation_error(
                    "the driver's content-loop parser reported a node-condition stop, \
                     but the environment body's stop spec sets no node condition",
                    cx.here(),
                ));
            }
        };

        let child_count = outcome.nodes.len() as u32;
        let body = cx
            .stage_node(
                NodeKind::list(),
                body_span.clone(),
                Arc::clone(&cx.state),
                outcome.nodes,
            )
            .map_err(|error| cx.staging_error(error, body_span))?;
        Ok((
            EnvironmentBody {
                body,
                end,
                content: ContentNodes::InChildrenOf(body, 0..child_count),
                terminator,
                exit_state,
                after_effects,
            },
            None,
        ))
    }
}

impl<L: Lang> fmt::Debug for EnvironmentBodyParser<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnvironmentBodyParser")
            .field("trigger_span", &self.trigger_span)
            .field("invocation_name", &self.invocation_name)
            .field("stop_command_name", &self.stop_command_name)
            .field("name_group_type", &self.name_group_type)
            .field("match_invocation_name", &self.match_invocation_name)
            .field("invocation_name_span", &self.invocation_name_span)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use crate::source::Span;

    use super::super::invocation_parser::parse_declared_arguments;
    use super::super::{
        GroupArgumentParser, Invocation, MarkerArgumentParser, NodesParser,
        OptionalGroupArgumentParser, StdInvocationParser, StopSpec,
    };
    use super::*;
    use crate::engine::{
        CommandResolution, ParseDriver, ParseResult, ParserSession, ResolvedCallable,
    };
    use crate::error::{DiagnosticInfo, ParseError, Recovery};
    use crate::scopes::{CallableQuery, CallableSyntax, Package, Scope, ScopeOp, ScopeStack};
    use crate::node::{
        CallableData, ChildRegion, ContentNodes, NodeRef, ParsedArguments, ParsedSlot,
        ParsedSlots, SlotRole,
    };
    use crate::source::{Source, SourcePos};
    use crate::spec::{ArgumentSpec, CallableSpec, StdCallableSpec};
    use crate::state::{
        FeaturePresence, LangFeatures, ParsingState, StateData, TokenRulesOverrides,
    };
    use crate::token::{
        CommandRule, CommandRules, CommentRule, CommentRules, ForbiddenCharsRules, GroupRules,
        ParagraphRules, SpecialsMatch, SpecialsRules, SpecialsScanError, StdStreamPosition,
        StdToken, StdTokenReader, TokenEdge, TokenKind, TokenListReader, TokenReader,
        TokenRules, TriggerChars, WhitespaceRules,
    };
    use alloc::boxed::Box;
    use alloc::string::String;
    use alloc::vec;
    use alloc::vec::Vec;

    const GT_BRACE: u32 = 0;
    const GT_OPTION: u32 = 1;
    const GT_RAW: u32 = 2;
    const CT_MACRO: u32 = 10;
    const CT_SPECIALS: u32 = 11;
    const CT_ENVIRONMENT: u32 = 12;

    // --- the test lang: `\`-commands, `{}` groups, `%` comments, `~` specials, and
    // --- `\begin{name}…\end{name}` environments through the composition below ----------

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

        // The tokenizer-layer hooks stay on `Lang` (7.2 placement doctrine).
        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(())
        }
    }

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

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

        fn resolve_command(
            &self,
            state: &ParsingState<EnvLang>,
            token: &StdToken<EnvLang>,
            tokens: &dyn TokenReader<'_, EnvLang>,
        ) -> Result<CommandResolution<EnvLang>, crate::error::ParseError> {
            let TokenKind::Command { name, escape_char } = tokens.token_kind(token) else {
                return Ok(CommandResolution::Unresolved { detail: None });
            };
            // `\begin` introduces every environment: the shared dispatcher spec's
            // factory returns the composition parser. `\end` deliberately resolves to
            // nothing — inside a body it is the stop condition (checked before the
            // dispatch arms), and an orphan at the root takes the
            // unresolvable-command recovery ([§dd-dr:parsers-engine], decision 8).
            if name == "begin" {
                return Ok(CommandResolution::Resolved(ResolvedCallable {
                    callable_type: CT_ENVIRONMENT,
                    spec: Arc::new(BeginSpec),
                }));
            }
            let query =
                CallableQuery::new(CT_MACRO, name, CallableSyntax::Command { escape_char });
            Ok(match state.scopes().retrieve_spec(&query, state) {
                Ok(resolved) => resolved
                    .map(|spec| ResolvedCallable { callable_type: CT_MACRO, spec })
                    .into(),
                Err(error) => {
                    CommandResolution::Unresolved { detail: Some(error.to_string()) }
                }
            })
        }
    }

    // --- EnvLang's own conditions: third-party-style derived conditions (the
    // --- extension surface demonstration, [§dd-dr:errors]) — plain data structs under the
    // --- language's "envlang." namespace, structurally identical to core conditions
    // --- (`no_constructor`: the tests build them with struct literals) ---------------

    /// `\begin` not followed immediately by its rigid name group.
    #[derive(Debug, Clone, DiagnosticInfo)]
    #[diagnostic(
        id = "envlang.begin.malformed-begin",
        message = "malformed ‘\\begin’: expected its name group immediately",
        no_constructor
    )]
    struct MalformedBegin;

    /// `\begin{name}` naming an environment no library defines.
    #[derive(Debug, Clone, DiagnosticInfo)]
    #[diagnostic(
        id = "envlang.begin.unknown-environment",
        message = "unknown environment ‘{name}’",
        no_constructor
    )]
    struct UnknownEnvironment {
        name: String,
    }

    /// A `\raw` verbatim block missing its `\endraw` terminator.
    #[derive(Debug, Clone, DiagnosticInfo)]
    #[diagnostic(
        id = "envlang.raw.missing-terminator",
        message = "missing ‘\\endraw’ before end of input",
        no_constructor
    )]
    struct MissingRawTerminator;

    // --- the environment-shaped invocation composition (the plan's "test-lang
    // --- EnvironmentSpec analog"): rigid `\begin{name}` scaffolding, environment lookup,
    // --- arguments (the shared 6.5 loop), the body through EnvironmentBodyParser,
    // --- ParsedSlots, empty recorded post-space --------------------------------------

    /// The `\begin` dispatcher: every environment enters through this shared spec.
    #[derive(Debug)]
    struct BeginSpec;

    impl crate::serialize::SerializableObject<EnvLang> for BeginSpec {}

    impl CallableSpec<EnvLang> for BeginSpec {
        /// The honest emptiness answer (slots session, decided direction 2): `\begin`
        /// declares nothing but reads an entire environment — bare use as a
        /// single-token expression argument must be diagnosed, not dispatched (the
        /// deliberate divergence from pylatexenc, which dispatches the environment as
        /// the argument).
        fn requires_content(&self) -> bool {
            true
        }

        fn make_invocation_parser<'a>(
            &'a self,
            invocation: Invocation<'a, EnvLang>,
        ) -> Result<Box<dyn ConstructParser<EnvLang, Output = BuildId> + 'a>, ParseError>
        {
            Ok(Box::new(EnvironmentInvocationParser { invocation }))
        }
    }

    struct EnvironmentInvocationParser<'a> {
        invocation: Invocation<'a, EnvLang>,
    }

    impl ConstructParser<EnvLang> for EnvironmentInvocationParser<'_> {
        type Output = BuildId;

        fn parse(
            &mut self,
            cx: &mut ParseContext<'_, '_, EnvLang>,
        ) -> ConstructParserResult<EnvLang, (BuildId, Option<Box<ParsingStateDelta<EnvLang>>>)>
        {
            let trigger = self.invocation.token;

            // Rigid scaffolding: the name group must be the immediately next token.
            let Some(name_group) = read_rigid_name_group(cx, GT_BRACE)? else {
                let trigger_span = cx.tokens.source_span_of(trigger);
                cx.recover(MalformedBegin, trigger_span.clone())?;
                // Chars fallback over the trigger alone (markup in a Chars node is the
                // accepted tolerant-recovery artifact); nothing past it is consumed.
                let id = cx.stage_node(
                    NodeKind::chars(trigger_span.span()),
                    trigger_span,
                    Arc::clone(&cx.state),
                    vec![],
                ).unwrap();
                return Ok((id, None));
            };
            let name = name_group.name_text();

            // Resolve the environment's spec by name. A provider failure is an
            // operational error, not a source condition — abort via the
            // implementation-error path.
            let query = CallableQuery::new(CT_ENVIRONMENT, name, CallableSyntax::Other);
            let resolved = cx
                .state
                .scopes()
                .retrieve_spec(&query, &cx.state)
                .map_err(|error| cx.implementation_error(error, name_group.name_span().clone()))?;
            let spec: Arc<dyn CallableSpec<EnvLang>> = match resolved {
                Some(spec) => spec,
                None => {
                    cx.recover(
                        UnknownEnvironment { name: name.into() },
                        name_group.name_span().clone(),
                    )?;
                    // Tolerant fallback: an argument-less body-only environment,
                    // so the body still parses to its terminator.
                    Arc::new(EnvSpec { arguments: vec![], body_delta: None })
                }
            };

            // Arguments: the 6.5 machinery, shared with StdInvocationParser. The
            // argument frames quote the *environment's* name, not `\begin`'s.
            let (mut children, arguments) =
                parse_declared_arguments(cx, &spec, name_group.name_span())?;

            // The body: parsed under the slot's state (the body delta stacked on the
            // invocation's base, session-mediated; structural revert) up to and
            // including the rigid `\end{name}` terminator. The delta is the env spec's
            // own field (the A.3 rehoming), read back through the documented
            // Any-supertrait downcast — the core never interprets it; the unknown-
            // environment fallback spec is EnvSpec too, so the downcast only misses
            // for a non-EnvSpec registration (which has no body delta to offer).
            let body_delta = (&*spec as &dyn core::any::Any)
                .downcast_ref::<EnvSpec>()
                .and_then(|env_spec| env_spec.body_delta.clone());
            let slot_state = match &body_delta {
                Some(delta) => cx.derive_state(delta)?,
                None => Arc::clone(&cx.state),
            };
            let trigger_span = cx.tokens.source_span_of(trigger);
            let trigger_start = cx.tokens.position_at(trigger, TokenEdge::Start);
            let mut body_parser =
                EnvironmentBodyParser::new(trigger_span, name, "end", GT_BRACE)
                    .with_invocation_name_span(name_group.name_span().clone());
            let (body, delta) =
                cx.parse_construct(&mut body_parser, Some(slot_state), None)?;
            debug_assert!(delta.is_none());

            let offset = children.len() as u32;
            children.push(body.body);
            // The slot record is pure node vocabulary: minted here, name carried on
            // the record itself (the A.2 reshape); content designation from the body
            // parser (7.7).
            let slots = ParsedSlots::from(vec![ParsedSlot::new(
                ChildRegion::new(offset..offset + 1, body.content.clone()),
                "body",
                SlotRole::Content,
                (),
            )]);

            let data = CallableData {
                callable_type: self.invocation.callable_type,
                // The environment's own name and spec, not the dispatcher's.
                name: name.into(),
                spec,
                arguments: ParsedArguments::from(arguments),
                slots,
                // Environment shapes record empty post-space ([§dd-dr:nodes] invariant 3 as
                // amended in 6.4): whitespace after `\begin` is unrecorded scaffolding
                // normalization, whitespace after `\end{…}` is sibling content.
                invocation_syntax: (),
            };
            let node_span = cx.source_span_within(&trigger_start, &body.end)?;
            let id = cx.stage_node(
                NodeKind::callable(data),
                node_span,
                Arc::clone(&cx.state),
                children,
            ).unwrap();
            Ok((id, None))
        }
    }

    // --- the verbatim takeover (the 6.6 obligation): a parser reading its body as raw
    // --- chars under a features-disabled state, staging an environment-shaped node
    // --- with a slot record — the decided verbatim recipe ([§dd-dr:tokens], Action-02 entry) ------

    /// `\raw … \endraw`: the body is raw source bytes — the parser never runs
    /// `NodesParser`, so no terminator-state doctrine is needed. It reads the
    /// body through the reader like every other parser (no raw-content peeking): under
    /// the verbatim state every byte is a `Char` token and the terminator one
    /// `GroupClose`.
    #[derive(Debug)]
    struct RawBlockSpec;

    impl crate::serialize::SerializableObject<EnvLang> for RawBlockSpec {}

    impl CallableSpec<EnvLang> for RawBlockSpec {
        /// The `\verb`-shaped honest emptiness answer: declares nothing, consumes a
        /// raw body — bare expression use must be diagnosed.
        fn requires_content(&self) -> bool {
            true
        }

        fn make_invocation_parser<'a>(
            &'a self,
            invocation: Invocation<'a, EnvLang>,
        ) -> Result<Box<dyn ConstructParser<EnvLang, Output = BuildId> + 'a>, ParseError>
        {
            Ok(Box::new(RawBlockParser { invocation }))
        }
    }

    struct RawBlockParser<'a> {
        invocation: Invocation<'a, EnvLang>,
    }

    impl ConstructParser<EnvLang> for RawBlockParser<'_> {
        type Output = BuildId;

        fn parse(
            &mut self,
            cx: &mut ParseContext<'_, '_, EnvLang>,
        ) -> ConstructParserResult<EnvLang, (BuildId, Option<Box<ParsingStateDelta<EnvLang>>>)>
        {
            const TERMINATOR: &str = "\\endraw";
            let trigger = self.invocation.token;
            // The `\verb` idiom: stand at the end of the trigger proper, so the
            // trigger's post-space bytes stay raw body content (they are not recorded
            // post-space).
            cx.tokens.move_to(trigger, TokenEdge::End);
            let body_start = cx.tokens.position_here();

            // The verbatim state: every feature gate off, and the expected group close
            // *replaced* by the raw terminator. The expected close is ungated by
            // the groups gate and overrides any close expectation inherited from an
            // enclosing group, so it is the single recognizer left active: the body
            // arrives as pure `Char` tokens — whitespace and would-be markup included —
            // and the terminator as one `GroupClose`.
            let raw_rule: Arc<GroupRule<EnvLang>> = Arc::new(GroupRule {
                group_type: GT_RAW,
                open: "\\raw".into(),
                close: TERMINATOR.into(),
            });
            let delta = ParsingStateDelta::new().rules(TokenRulesOverrides {
                whitespace: crate::state::WhitespaceOverrides::disable(),
                paragraphs: crate::state::ParagraphOverrides::disable(),
                groups: crate::state::GroupOverrides {
                    expecting_close: Some(Some(raw_rule)),
                    ..crate::state::GroupOverrides::disable()
                },
                commands: crate::state::CommandOverrides::disable(),
                comments: crate::state::CommentOverrides::disable(),
                specials: crate::state::SpecialsOverrides::disable(),
                ..TokenRulesOverrides::default()
            });
            let verbatim_state = cx.derive_state(&delta)?;
            let terminator = cx.with_parsing_state(verbatim_state, |cx| {
                let terminator = loop {
                    let token = cx.tokens.peek(&cx.state).expect("raw body reads as chars");
                    match cx.tokens.token_kind(&token) {
                        TokenKind::Char(_) => {
                            cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace)
                        }
                        TokenKind::GroupClose { .. }
                        | TokenKind::EndOfStream => break token,
                        other => unreachable!("verbatim state yields only chars, got {}", other),
                    }
                };
                // past `\endraw`; no-op at stream end
                cx.tokens.move_to(&terminator, TokenEdge::EndPastPostSpace);
                terminator
            });
            let terminator_start = cx.tokens.position_at(&terminator, TokenEdge::Start);
            let (body_end, end) = match cx.tokens.token_kind(&terminator) {
                TokenKind::GroupClose { .. } => (
                    terminator_start,
                    cx.tokens.position_at(&terminator, TokenEdge::EndPastPostSpace),
                ),
                _ => {
                    let trigger_span = cx.tokens.source_span_of(trigger);
                    cx.recover(MissingRawTerminator, trigger_span)?;
                    // This suite's stream positions are `Copy`.
                    (terminator_start, terminator_start)
                }
            };

            let body_span = cx.source_span_within(&body_start, &body_end)?;
            let mut body_nodes = Vec::new();
            if !body_span.is_empty() {
                body_nodes.push(cx.stage_node(
                    NodeKind::chars(body_span.span()),
                    body_span.clone(),
                    Arc::clone(&cx.state),
                    vec![],
                ).unwrap());
            }
            let body_children = body_nodes.len() as u32;
            let list = cx.stage_node(
                NodeKind::list(),
                body_span,
                Arc::clone(&cx.state),
                body_nodes,
            ).unwrap();
            // The slot record is minted by the parser — pure node vocabulary, the
            // name carried on the record itself ([§dd-dr:nodes] self-description).
            let slots = ParsedSlots::from(vec![ParsedSlot::new(
                ChildRegion::new(0..1, ContentNodes::InChildrenOf(list, 0..body_children)),
                "raw",
                SlotRole::Content,
                (),
            )]);
            let data = CallableData {
                callable_type: self.invocation.callable_type,
                name: self.invocation.name.into(),
                spec: Arc::clone(self.invocation.spec),
                arguments: ParsedArguments::empty(),
                slots,
                invocation_syntax: (),
            };
            let trigger_start = cx.tokens.position_at(trigger, TokenEdge::Start);
            let node_span = cx.source_span_within(&trigger_start, &end)?;
            let id = cx.stage_node(
                NodeKind::callable(data),
                node_span,
                Arc::clone(&cx.state),
                vec![list],
            ).unwrap();
            Ok((id, None))
        }
    }

    // --- states and spec builders ------------------------------------------------------

    fn rules() -> TokenRules<EnvLang> {
        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 brace_arg() -> Arc<ArgumentSpec<EnvLang>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(GroupArgumentParser::new(GT_BRACE))))
    }

    fn option_rule() -> Arc<GroupRule<EnvLang>> {
        Arc::new(GroupRule { group_type: GT_OPTION, open: "[".into(), close: "]".into() })
    }

    fn optional_arg() -> Arc<ArgumentSpec<EnvLang>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(OptionalGroupArgumentParser::new(
            option_rule(),
        ))))
    }

    fn marker_arg(marker: &str) -> Arc<ArgumentSpec<EnvLang>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(MarkerArgumentParser::new(marker))))
    }

    fn macro_spec(arguments: Vec<Arc<ArgumentSpec<EnvLang>>>) -> Arc<dyn CallableSpec<EnvLang>> {
        Arc::new(StdCallableSpec { arguments, ..Default::default() })
    }

    /// The test-lang environment spec (an `EnvironmentSpec` rehearsal): arguments
    /// declared spec-side like any callable; the body's state delta an **ordinary
    /// field** (the A.3 rehoming of pylatexenc's `make_body_parsing_state_delta`),
    /// read back by the composition that drives the parse — the core never sees it.
    #[derive(Debug)]
    struct EnvSpec {
        arguments: Vec<Arc<ArgumentSpec<EnvLang>>>,
        body_delta: Option<ParsingStateDelta<EnvLang>>,
    }

    impl crate::serialize::SerializableObject<EnvLang> for EnvSpec {}

    impl CallableSpec<EnvLang> for EnvSpec {
        fn arguments(&self) -> &[Arc<ArgumentSpec<EnvLang>>] {
            &self.arguments
        }
    }

    fn env_spec(
        arguments: Vec<Arc<ArgumentSpec<EnvLang>>>,
        body_delta: Option<ParsingStateDelta<EnvLang>>,
    ) -> Arc<dyn CallableSpec<EnvLang>> {
        Arc::new(EnvSpec { arguments, body_delta })
    }

    /// The suite's language definitions: the §G matrix — `\frac`, `\emph`, `\alpha`,
    /// `\section*[opt]{title}`, `\item[opt]`, the `\raw` takeover, and the environments
    /// `itemize` (plain), `tabular` (one mandatory argument), `nocomments` (slot delta
    /// disabling comment tokenization in the body), and the plain pair `A`/`B`.
    fn suite_state() -> Arc<ParsingState<EnvLang>> {
        let mut lib = Package::new("test-definitions");
        lib.insert(CT_MACRO, "frac", macro_spec(vec![brace_arg(), brace_arg()]));
        lib.insert(CT_MACRO, "emph", macro_spec(vec![brace_arg()]));
        lib.insert(CT_MACRO, "alpha", macro_spec(vec![]));
        lib.insert(
            CT_MACRO,
            "section",
            macro_spec(vec![marker_arg("*"), optional_arg(), brace_arg()]),
        );
        lib.insert(CT_MACRO, "item", macro_spec(vec![optional_arg()]));
        lib.insert(CT_MACRO, "raw", Arc::new(RawBlockSpec));

        lib.insert(CT_ENVIRONMENT, "itemize", env_spec(vec![], None));
        lib.insert(CT_ENVIRONMENT, "tabular", env_spec(vec![brace_arg()], None));
        lib.insert(
            CT_ENVIRONMENT,
            "nocomments",
            env_spec(
                vec![],
                Some(ParsingStateDelta::new().rules(TokenRulesOverrides {
                    comments: crate::state::CommentOverrides::disable(),
                    ..TokenRulesOverrides::default()
                })),
            ),
        );
        lib.insert(CT_ENVIRONMENT, "A", env_spec(vec![], None));
        lib.insert(CT_ENVIRONMENT, "B", env_spec(vec![], None));

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

    // --- harness (the established driving pattern) --------------------------------------

    struct Parsed {
        result: ParseResult<EnvLang>,
        pos: usize,
    }

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

    /// Drive a root `NodesParser` to end of input, stage the outcome under a root
    /// `List` spanning the parsed extent, freeze, and run the invariant checker.
    fn try_run<'s>(
        source: &'s Arc<Source>,
        tokens: &mut dyn TokenReader<'s, EnvLang>,
        state: &Arc<ParsingState<EnvLang>>,
        recovery: Recovery,
    ) -> Result<Parsed, ParseError> {
        let mut session = ParserSession::new();
        let driver = EnvDriver { recovery };
        let mut cx =
            ParseContext::new(tokens, Arc::clone(state), &mut session, &driver);
        let mut parser = NodesParser::new(StopSpec::none());
        let (outcome, delta) = parser.parse(&mut cx)?;
        assert_eq!(outcome.stop, StopCause::EndOfInput);
        assert!(delta.is_none());
        let pos = cx.here().start();
        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 = session.builder.add(
            NodeKind::list(),
            SourceSpan::new(source, root_span),
            Arc::clone(state),
            outcome.nodes, (), (),
        ).unwrap();
        let result = session.finish(root).unwrap();
        crate::node::check_tree_invariants(&result.tree);
        Ok(Parsed { result, pos })
    }

    /// [`try_run`] over a `StdTokenReader` — for content whose tokenization is
    /// state-dependent (optional-argument probing, slot deltas, the raw-content
    /// takeover): a pre-scanned token list cannot re-tokenize under momentary states
    /// (`TokenListReader`'s documented fidelity limit).
    fn parse_std(
        content: &str,
        state: &Arc<ParsingState<EnvLang>>,
        recovery: Recovery,
    ) -> Parsed {
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        try_run(&source, &mut reader, state, recovery).expect("parse")
    }

    /// Run against both readers (report R6) and assert they agree; for content whose
    /// tokenization is state-independent.
    fn parse_both(
        content: &str,
        state: &Arc<ParsingState<EnvLang>>,
        recovery: Recovery,
    ) -> Parsed {
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut std_reader = StdTokenReader::new(&source);
        let a = try_run(&source, &mut std_reader, state, recovery).expect("std reader");

        let mut scanned = Vec::new();
        let mut scanner = StdTokenReader::new(&source);
        loop {
            let token = TokenReader::next(&mut scanner, state).expect("clean scan");
            let reader: &dyn TokenReader<'_, EnvLang> = &scanner;
            let done = matches!(reader.token_kind(&token), TokenKind::EndOfStream);
            scanned.push(token);
            if done {
                break;
            }
        }
        let mut list_reader = TokenListReader::new(&source, scanned);
        let b = try_run(&source, &mut list_reader, state, recovery).expect("list reader");

        assert_eq!(shapes(&a.result), shapes(&b.result), "readers disagree on {:?}", content);
        assert_eq!(a.pos, b.pos, "positions disagree on {:?}", content);
        assert_eq!(
            a.result.diagnostics.len(),
            b.result.diagnostics.len(),
            "diagnostics disagree on {:?}",
            content
        );
        assert_eq!(
            a.result.tree.node_count(),
            b.result.tree.node_count(),
            "trees disagree on {:?}",
            content
        );
        a
    }

    /// One readable line per root child: kind, exact span, resolved content.
    fn shapes(result: &ParseResult<EnvLang>) -> 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 { .. } => {
                        format!(
                        "comment {} {:?}",
                        span,
                        node.comment().unwrap().content.resolve(node.source())
                    )
                    }
                    NodeKind::Group(_) => format!("group {}", span),
                    NodeKind::Callable(_) => {
                        format!("callable {} {:?}", span, node.name().unwrap())
                    }
                    NodeKind::List => format!("list {}", span),
                }
            })
            .collect()
    }

    fn root_child(parsed: &Parsed, i: usize) -> NodeRef<'_, EnvLang> {
        parsed.result.tree.root().child(i).expect("root child")
    }

    /// The environment's body nodes (slot 0's content), as (kind-ish string) lines.
    fn body_shapes(env: NodeRef<'_, EnvLang>) -> Vec<String> {
        env.slot_content_nodes(0)
            .expect("an environment has slot 0")
            .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 { .. } => {
                        format!(
                        "comment {} {:?}",
                        span,
                        node.comment().unwrap().content.resolve(node.source())
                    )
                    }
                    NodeKind::Group(_) => format!("group {}", span),
                    NodeKind::Callable(_) => {
                        format!("callable {} {:?}", span, node.name().unwrap())
                    }
                    NodeKind::List => format!("list {}", span),
                }
            })
            .collect()
    }

    fn diagnostics_mentioning(parsed: &Parsed, needle: &str) -> usize {
        parsed
            .result
            .diagnostics
            .iter()
            .filter(|d| d.message().contains(needle))
            .count()
    }

    // --- the environment shape ----------------------------------------------------------

    #[test]
    fn environment_round_trips_with_exact_spans() {
        let st = suite_state();
        //             0....5....1....1....2....2....3....3
        //                  0    5    0    5    0    5
        let content = "x \\begin{itemize} a b \\end{itemize} y";
        let parsed = parse_both(content, &st, Recovery::Strict);

        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..2 \"x \"", "callable 2..35 \"itemize\"", "chars 35..37 \" y\""],
        );
        let env = root_child(&parsed, 1);
        assert_eq!(env.callable_type(), Some(CT_ENVIRONMENT));
        // Environment shapes record empty post-space; the space after `\end{itemize}`
        // is sibling content ([§dd-dr:nodes] invariant 3 as amended).
        // Children = the body `List` alone; its span is the body's content interior,
        // whitespace on both ends included.
        assert_eq!(env.child_count(), 1);
        let body = env.slot_content_parent(0).expect("body list");
        assert!(body.is_list());
        assert_eq!(body.span().range(), 17..22);
        assert_eq!(body_shapes(env), ["chars 17..22 \" a b \""]);
        // The records: no arguments, one slot holding the body list — named on the
        // record itself (record-level slots, slots session).
        assert_eq!(env.arguments().unwrap().len(), 0);
        assert_eq!(env.slots().unwrap().len(), 1);
        assert!(env.slots().unwrap().get_named("body").is_some());
        assert!(parsed.result.diagnostics.is_empty());
        assert_eq!(parsed.pos, content.len());
    }

    #[test]
    fn empty_body_is_an_empty_list() {
        let st = suite_state();
        let content = "\\begin{itemize}\\end{itemize}";
        let parsed = parse_both(content, &st, Recovery::Strict);

        let env = root_child(&parsed, 0);
        assert_eq!(env.span().range(), 0..28);
        let body = env.slot_content_parent(0).unwrap();
        assert_eq!(body.span().range(), 15..15);
        assert_eq!(body.child_count(), 0);
        assert_eq!(env.body().unwrap().iter().count(), 0);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn inline_whitespace_in_scaffolding_is_tolerated_and_unrecorded() {
        let st = suite_state();
        //             0....5....1....1....2....2....3
        //                  0    5    0    5    0
        let content = "\\begin {itemize}x\\end {itemize}";
        let parsed = parse_both(content, &st, Recovery::Strict);

        let env = root_child(&parsed, 0);
        assert_eq!(env.span().range(), 0..31);
        assert_eq!(env.name(), Some("itemize"));
        // The commands' post-space is scaffolding normalization: not recorded.
        assert_eq!(body_shapes(env), ["chars 16..17 \"x\""]);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn scaffolding_is_the_reconstructible_complement() {
        let st = suite_state();
        let content = "\\begin{itemize} x \\end{itemize}";
        let parsed = parse_both(content, &st, Recovery::Strict);

        // Node span minus the children block = the `\begin{name}` prefix and the
        // `\end{name}` suffix (decision 6: rigid, reconstructed, not recorded).
        let env = root_child(&parsed, 0);
        let first = env.child(0).unwrap().span().start();
        let last = env.child(env.child_count() - 1).unwrap().span().end();
        assert_eq!(&content[env.span().start()..first], "\\begin{itemize}");
        assert_eq!(&content[last..env.span().end()], "\\end{itemize}");
    }

    #[test]
    fn paragraph_breaks_live_in_the_body() {
        let st = suite_state();
        let content = "\\begin{itemize}a\n\nb\\end{itemize}";
        let parsed = parse_both(content, &st, Recovery::Strict);

        let env = root_child(&parsed, 0);
        assert_eq!(
            body_shapes(env),
            ["chars 15..16 \"a\"", "chars 16..18 \"\\n\\n\"", "chars 18..19 \"b\""],
        );
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn environment_arguments_precede_the_body() {
        let st = suite_state();
        //             0....5....1....1....2....2....3....3
        //                  0    5    0    5    0    5
        let content = "\\begin{tabular}{cc} x \\end{tabular}";
        let parsed = parse_both(content, &st, Recovery::Strict);

        let env = root_child(&parsed, 0);
        assert_eq!(env.span().range(), 0..35);
        // Children: the argument region's group, then the body list.
        assert_eq!(env.child_count(), 2);
        assert!(env.child(0).unwrap().is_group());
        assert!(env.child(1).unwrap().is_list());
        // The argument record designates the group's children as content.
        let content_nodes: Vec<_> =
            env.argument_content_nodes(0).expect("provided").iter().collect();
        assert_eq!(content_nodes.len(), 1);
        assert_eq!(content_nodes[0].chars(), Some("cc"));
        // The slot record holds the body.
        assert_eq!(body_shapes(env), ["chars 19..22 \" x \""]);
        assert!(parsed.result.diagnostics.is_empty());
    }

    // --- nesting and unwinding ----------------------------------------------------------

    #[test]
    fn nested_environments_consume_their_own_terminators() {
        let st = suite_state();
        //             0....5....1....1....2....2....3....3....4
        //                  0    5    0    5    0    5    0
        let content = "\\begin{A} x \\begin{B} y \\end{B} z \\end{A}";
        let parsed = parse_both(content, &st, Recovery::Strict);

        assert_eq!(shapes(&parsed.result), ["callable 0..41 \"A\""]);
        let outer = root_child(&parsed, 0);
        assert_eq!(
            body_shapes(outer),
            ["chars 9..12 \" x \"", "callable 12..31 \"B\"", "chars 31..34 \" z \""],
        );
        let inner = outer.body().unwrap().iter().nth(1).unwrap();
        assert_eq!(body_shapes(inner), ["chars 21..24 \" y \""]);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn same_name_nesting_stays_level_locked() {
        let st = suite_state();
        let content = "\\begin{A}\\begin{A}x\\end{A}\\end{A}";
        let parsed = parse_both(content, &st, Recovery::Strict);

        let outer = root_child(&parsed, 0);
        assert_eq!(outer.span().range(), 0..33);
        let inner = outer.body().unwrap().iter().next().unwrap();
        assert_eq!(inner.span().range(), 9..26);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn mismatched_terminator_unwinds_without_consuming() {
        let st = suite_state();
        //             0....5....1....1....2....2....3
        //                  0    5    0    5    0
        let content = "\\begin{A}x\\begin{B}y\\end{A} z";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        // B's body stops at `\end`, reads the name, sees the mismatch: diagnostic +
        // close WITHOUT consuming — the unwinding lets A find and consume `\end{A}`.
        assert_eq!(shapes(&parsed.result), ["callable 0..27 \"A\"", "chars 27..29 \" z\""]);
        let a = root_child(&parsed, 0);
        assert_eq!(
            body_shapes(a),
            ["chars 9..10 \"x\"", "callable 10..20 \"B\""],
        );
        let b = a.body().unwrap().iter().nth(1).unwrap();
        // B's extent ends at its body's end, before the terminator it did not consume.
        assert_eq!(b.span().range(), 10..20);
        assert_eq!(body_shapes(b), ["chars 19..20 \"y\""]);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "‘B’"), 1);
    }

    #[test]
    fn mismatch_diagnostic_carries_the_nested_environment_frames() {
        // B's mismatch is diagnosed under B's body frame (innermost), B's `\begin`
        // invocation frame, A's body frame, and A's `\begin` invocation frame — the
        // pylatexenc-style "while parsing" traceback, from a single attachment point.
        let st = suite_state();
        let content = "\\begin{A}x\\begin{B}y\\end{A} z";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        let diagnostic = parsed
            .result
            .diagnostics
            .with_identifier(EnvironmentTerminatorMismatch::IDENTIFIER)
            .next()
            .unwrap();
        let condition =
            diagnostic.data().downcast_ref::<EnvironmentTerminatorMismatch>().unwrap();
        assert_eq!(condition.expected, "B");
        assert_eq!(condition.found, "A");
        let titles: Vec<&str> = diagnostic.frames().iter().map(|f| f.title()).collect();
        assert_eq!(
            titles,
            [
                "environment ‘B’",
                "callable ‘\\begin’",
                "environment ‘A’",
                "callable ‘\\begin’",
            ]
        );
    }

    #[test]
    fn orphan_terminator_takes_unresolvable_command_recovery() {
        let st = suite_state();
        let content = "x\\end{a}y";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        // The orphan `\end` reaches the root loop as an ordinary command: diagnostic +
        // chars fallback (not merged into neighboring runs); `{a}` is a plain group.
        assert_eq!(
            shapes(&parsed.result),
            [
                "chars 0..1 \"x\"",
                "chars 1..5 \"\\\\end\"",
                "group 5..8",
                "chars 8..9 \"y\"",
            ],
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "cannot resolve command"), 1);
    }

    #[test]
    fn terminator_inside_a_nested_group_does_not_stop_the_body() {
        let st = suite_state();
        //             0....5....1....1....2....2....3
        //                  0    5    0    5    0
        let content = "\\begin{A}{\\end{A}}\\end{A}";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        // Stop conditions are tested only at the body's own nesting level: inside the
        // brace group, `\end` is an ordinary (unresolvable) command — diagnosed chars
        // fallback + a plain `{A}` group — and the environment terminates at the outer
        // `\end{A}`.
        let env = root_child(&parsed, 0);
        assert_eq!(env.span().range(), 0..25);
        assert_eq!(body_shapes(env), ["group 9..18"]);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "cannot resolve command"), 1);
    }

    #[test]
    fn environment_in_a_group_and_group_in_a_body() {
        let st = suite_state();
        //             0....5....1....1....2....2....3
        //                  0    5    0    5    0
        let content = "{\\begin{A} {x} \\end{A}}";
        let parsed = parse_both(content, &st, Recovery::Strict);

        assert_eq!(shapes(&parsed.result), ["group 0..23"]);
        let env = root_child(&parsed, 0).child(0).unwrap();
        assert!(env.is_callable());
        assert_eq!(env.span().range(), 1..22);
        assert_eq!(
            body_shapes(env),
            ["chars 10..11 \" \"", "group 11..14", "chars 14..15 \" \""],
        );
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn stray_group_close_in_the_body_unwinds() {
        let st = suite_state();
        //             0....5....1....1....2
        //                  0    5    0
        let content = "{\\begin{A} x } y";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        // The body's loop reports the `}` as data; the environment closes without
        // consuming it (diagnostic), and the enclosing group then claims its close.
        assert_eq!(shapes(&parsed.result), ["group 0..14", "chars 14..16 \" y\""]);
        let env = root_child(&parsed, 0).child(0).unwrap();
        assert!(env.is_callable());
        assert_eq!(env.span().range(), 1..13);
        assert_eq!(body_shapes(env), ["chars 10..13 \" x \""]);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "missing terminator"), 1);
    }

    // --- terminator recovery -------------------------------------------------------------

    #[test]
    fn missing_terminator_at_end_of_input() {
        let st = suite_state();
        let content = "\\begin{itemize} x";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        let env = root_child(&parsed, 0);
        assert_eq!(env.span().range(), 0..17);
        assert_eq!(body_shapes(env), ["chars 15..17 \" x\""]);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "before end of input"), 1);
        assert_eq!(parsed.pos, content.len());
    }

    #[test]
    fn unterminated_environments_unwind_at_end_of_input() {
        let st = suite_state();
        let content = "\\begin{A}\\begin{B}x";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        // Both levels diagnose their own missing terminator (loop safety at EOF).
        let a = root_child(&parsed, 0);
        assert_eq!(a.span().range(), 0..19);
        let b = a.body().unwrap().iter().next().unwrap();
        assert_eq!(b.span().range(), 9..19);
        assert_eq!(parsed.result.diagnostics.len(), 2);
        assert_eq!(diagnostics_mentioning(&parsed, "before end of input"), 2);
    }

    #[test]
    fn malformed_terminator_consumes_the_command_alone() {
        let st = suite_state();
        //             0....5....1....1....2
        //                  0    5    0
        let content = "\\begin{A}x\\end[y]";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        // `\end` not followed by its name group: diagnosed, consumed, the environment
        // closes — and `[y]` re-parses as ordinary sibling content (no option rule is
        // in scope at the root: plain chars).
        assert_eq!(
            shapes(&parsed.result),
            ["callable 0..14 \"A\"", "chars 14..17 \"[y]\""],
        );
        let env = root_child(&parsed, 0);
        assert_eq!(body_shapes(env), ["chars 9..10 \"x\""]);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "malformed terminator"), 1);
    }

    #[test]
    fn malformed_terminator_at_end_of_input() {
        let st = suite_state();
        let content = "\\begin{A}x\\end";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        let env = root_child(&parsed, 0);
        assert_eq!(env.span().range(), 0..14);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "malformed terminator"), 1);
    }

    #[test]
    fn whitespace_in_the_terminator_name_is_malformed() {
        let st = suite_state();
        //             0....5....1....1....2....2
        //                  0    5    0
        let content = "\\begin{A}x\\end{ A }";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        // Rigid syntax: no whitespace inside the name group. The command is consumed,
        // the group re-parses as sibling content.
        assert_eq!(
            shapes(&parsed.result),
            ["callable 0..14 \"A\"", "group 14..19"],
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "malformed terminator"), 1);
    }

    #[test]
    fn strict_mode_aborts_on_terminator_problems() {
        let st = suite_state();
        for content in ["\\begin{A}x\\end{B}", "\\begin{A}x", "\\begin{A}x\\end[y]"] {
            let source: Arc<Source> = Arc::new(Source::new(content));
            let mut reader = StdTokenReader::new(&source);
            let result = try_run(&source, &mut reader, &st, Recovery::Strict);
            assert!(result.is_err(), "expected strict abort on {:?}", content);
        }
    }

    // --- the begin side -------------------------------------------------------------------

    #[test]
    fn malformed_begin_falls_back_to_chars() {
        let st = suite_state();
        let content = "\\begin x";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        // The fallback spans the trigger alone (post-space included — the token span
        // convention); nothing past it is consumed, and runs do not merge into it.
        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..7 \"\\\\begin \"", "chars 7..8 \"x\""],
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "malformed ‘\\begin’"), 1);
    }

    #[test]
    fn whitespace_in_the_begin_name_is_malformed() {
        let st = suite_state();
        let content = "\\begin{x y}z";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        assert_eq!(
            shapes(&parsed.result),
            ["chars 0..6 \"\\\\begin\"", "group 6..11", "chars 11..12 \"z\""],
        );
        assert_eq!(parsed.result.diagnostics.len(), 1);
    }

    #[test]
    fn unknown_environment_still_parses_its_body() {
        let st = suite_state();
        let content = "\\begin{nope} x \\end{nope}";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        let env = root_child(&parsed, 0);
        assert_eq!(env.name(), Some("nope"));
        assert_eq!(env.span().range(), 0..25);
        assert_eq!(body_shapes(env), ["chars 12..15 \" x \""]);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "unknown environment"), 1);
    }

    // --- slot state deltas ----------------------------------------------------------------

    #[test]
    fn slot_state_delta_scopes_the_body() {
        let st = suite_state();
        //             0....5....1....1....2....2....3....3....4....4
        //                  0    5    0    5    0    5    0    5
        let content = "\\begin{nocomments} a%b \\end{nocomments} %c";
        let parsed = parse_std(content, &st, Recovery::Strict);

        // Inside the body the slot's delta disables comment tokenization: `%b` is
        // chars. The terminator is still found under the slot state, and after the
        // structural revert `%c` is a comment again.
        let env = root_child(&parsed, 0);
        assert_eq!(body_shapes(env), ["chars 18..23 \" a%b \""]);
        assert!(root_child(&parsed, 2).is_comment());
        assert!(parsed.result.diagnostics.is_empty());
    }

    // --- the match_invocation_name switch --------------------------------------------------

    #[test]
    fn match_invocation_name_can_be_disabled() {
        // Driven directly (the composition above always back-references): with the
        // switch off, any rigid name group closes the body, without a diagnostic.
        let content = "x\\end{whatever} rest";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let st = suite_state();
        let mut reader = StdTokenReader::new(&source);
        let mut session = ParserSession::new();
        let driver = EnvDriver { recovery: Recovery::Strict };
        let mut cx = ParseContext::new(
            &mut reader,
            Arc::clone(&st),
            &mut session,
            &driver);
        let mut parser = EnvironmentBodyParser::new(
            SourceSpan::new(&source, 0..0),
            "A",
            "end",
            GT_BRACE,
        )
        .with_match_invocation_name(false);
        let (body, delta) = parser.parse(&mut cx).expect("parse");
        assert!(delta.is_none());
        // The environment ends where the reader stands: past the consumed terminator.
        assert_eq!(body.end, cx.tokens.position_here());
        assert_eq!(cx.here().start(), 15);

        let result = session.finish(body.body).unwrap();
        crate::node::check_tree_invariants(&result.tree);
        assert_eq!(result.tree.root().span().range(), 0..1);
        assert_eq!(result.tree.root().child(0).unwrap().chars(), Some("x"));
        assert!(result.diagnostics.is_empty());
    }

    // --- what the body reports about its interior's after-effects ------------------------
    // ([§dd-dr:environment-after-effects], the environment companion of
    // [§dd-dr:group-after-effects]): the body parser stays a blind helper — it *reports*
    // the interior content run's exit state and merged record on the produced
    // `EnvironmentBody` and returns no pass-through delta of its own, leaving what (if
    // anything) escapes the environment to the driving composition.

    /// The scope this section's `\gdef` defines into (pre-seeded, so the definition
    /// lands where the escape channel would carry it).
    const GLOBAL: &str = "global";

    /// A definition macro: the standard node, plus a scope-op delta as its
    /// after-effect (the `\newcommand` shape) — the delta-returning spec the suite's
    /// declarative language otherwise has none of.
    #[derive(Debug)]
    struct DefiningSpec {
        delta: ParsingStateDelta<EnvLang>,
    }

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

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

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

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

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

    /// `GLOBAL`-targeted definition of the zero-argument macro `name`.
    fn defining(name: &str) -> ParsingStateDelta<EnvLang> {
        ParsingStateDelta::new().scope_op(ScopeOp::Define {
            scope: GLOBAL.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<EnvLang>, name: &str) -> bool {
        let query =
            CallableQuery::new(CT_MACRO, name, CallableSyntax::Command { escape_char: '\\' });
        state.scopes().retrieve_spec(&query, state).unwrap().is_some()
    }

    /// A state defining `\gdef` — whose after-effect defines `\g` in the `GLOBAL`
    /// scope — over this suite's token rules, with that scope seeded.
    fn defining_state() -> Arc<ParsingState<EnvLang>> {
        let mut lib = Package::new("after-effect-definitions");
        lib.insert(CT_MACRO, "gdef", Arc::new(DefiningSpec { delta: defining("g") }));
        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(lib));
        scopes.push(Arc::new(Scope::<EnvLang>::new(GLOBAL)));
        Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }))
    }

    /// Drive an `EnvironmentBodyParser` for the environment `A` directly over
    /// `content`, and return the produced body together with the entry state.
    fn run_body(
        content: &str,
        state: &Arc<ParsingState<EnvLang>>,
    ) -> (EnvironmentBody<EnvLang>, ParseResult<EnvLang>) {
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let mut session = ParserSession::new();
        let driver = EnvDriver { recovery: Recovery::Strict };
        let mut cx =
            ParseContext::new(&mut reader, Arc::clone(state), &mut session, &driver);
        let mut parser =
            EnvironmentBodyParser::new(SourceSpan::new(&source, 0..0), "A", "end", GT_BRACE);
        let (body, delta) = parser.parse(&mut cx).expect("parse");
        // The pass-through delta stays `None`: an interior escape is *reported*, never
        // *returned* — routing it outward is the driving composition's decision.
        assert!(delta.is_none());
        let result = session.finish(body.body).unwrap();
        crate::node::check_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty());
        (body, result)
    }

    #[test]
    fn a_body_reports_the_interior_runs_merged_record_and_exit_state() {
        let st = defining_state();
        // `\gdef` inside the body leaves its definition to the body's own following
        // siblings — the interior content run applies it and records it.
        let (body, result) = run_body("\\gdef x\\end{A}", &st);
        assert_eq!(result.tree.root().child(0).unwrap().name(), Some("gdef"));

        // The reported record is the interior run's merged one, raw and unfiltered:
        // the single scope op `\gdef` generated, tagged with its target scope (the
        // structural `\gdef`-vs-`\def` split a routing hook keys on).
        let record = body.after_effects.expect("the interior applied one after-effect");
        let ops = <<EnvLang as Lang>::Features as LangFeatures>::Scopes::store_get(
            &record.scope_ops,
        )
        .expect("the lang declares the scopes feature present");
        assert!(
            matches!(
                &ops[..],
                [ScopeOp::Define { scope, callable_type, name, .. }]
                    if &**scope == GLOBAL && *callable_type == CT_MACRO && &**name == "g"
            ),
            "unexpected record ops: {ops:?}"
        );

        // The exit state is where the record's definitions are inspectable — the record
        // itself carries operations, not a symbol table. It is a *different* state from
        // the one the body was entered under, which the definition never reached.
        assert!(!Arc::ptr_eq(&body.exit_state, &st));
        assert!(defined(&body.exit_state, "g"));
        assert!(!defined(&st, "g"));
    }

    #[test]
    fn a_body_whose_interior_generates_nothing_reports_no_after_effects() {
        let st = defining_state();
        // No delta-returning construct inside: the run applied nothing, so there is
        // nothing to report and the state it reached is the very state it started from
        // (`Arc` identity — pass-through preserves it).
        let (body, _) = run_body("x\\end{A}", &st);
        assert!(body.after_effects.is_none());
        assert!(Arc::ptr_eq(&body.exit_state, &st));
    }

    // --- misbehaving custom readers are implementation errors ([§dd-dr:panic-policy]) -------

    /// How the flaky reader betrays the re-peek contract at the terminator.
    #[derive(Clone, Copy)]
    enum Betrayal {
        /// The second peek at the betrayal position returns a different token kind.
        KindChange,
        /// The second peek at the betrayal position returns a recoverable token error
        /// (under tolerant recovery the probe then reports the position unusable —
        /// the "stop token disappeared" arm).
        Vanish,
    }

    /// A delegating reader that violates peek idempotence at one position: from the
    /// second peek at `betray_at` on, it misreports the token.
    struct FlakyReader<'s> {
        inner: StdTokenReader<'s>,
        betray_at: usize,
        peeks_at_betrayal: u32,
        mode: Betrayal,
    }

    impl<'s> FlakyReader<'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, EnvLang> {
            &self.inner
        }

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

    impl<'s> TokenReader<'s, EnvLang> for FlakyReader<'s> {
        fn peek(
            &mut self,
            state: &Arc<ParsingState<EnvLang>>,
        ) -> crate::token::TokenResult<EnvLang, StdToken<EnvLang>> {
            if TokenReader::<EnvLang>::position_here(&self.inner).offset() == self.betray_at {
                self.peeks_at_betrayal += 1;
                if self.peeks_at_betrayal >= 2 {
                    let span = Span::new(self.betray_at, self.betray_at + 1);
                    let pre_space = Span::empty(self.betray_at);
                    return match self.mode {
                        Betrayal::KindChange => {
                            Ok(StdToken::char('x', span, pre_space))
                        }
                        Betrayal::Vanish => Err(crate::token::TokenError::new(
                            crate::token::TokenErrorKind::ForbiddenChar(
                                crate::token::ForbiddenChar::new('\\'),
                            ),
                            SourceSpan::new(self.inner.source(), span),
                            Some(crate::token::TokenRecovery {
                                token: StdToken::char('\\', span, pre_space),
                                // In-crate test infrastructure may build a position
                                // directly; a third-party reader would take one from
                                // the reader it delegates to.
                                resume: StdStreamPosition::at(span.end()),
                            }),
                        )),
                    };
                }
            }
            TokenReader::peek(&mut self.inner, state)
        }

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

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

    /// Parse `\begin{A}b\end{A}` with the reader betraying the terminator's re-peek
    /// (the `\end` sits at byte 10) — under **tolerant** recovery, deliberately: an
    /// implementation error bypasses the recover funnel and aborts even there.
    fn flaky_terminator_error(mode: Betrayal) -> ParseError {
        let content = "\\begin{A}b\\end{A}";
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = FlakyReader {
            inner: StdTokenReader::new(&source),
            betray_at: 10,
            peeks_at_betrayal: 0,
            mode,
        };
        try_run(&source, &mut reader, &suite_state(), Recovery::Tolerant)
            .expect_err("the reader contract violation must abort the parse")
    }

    #[test]
    fn a_reader_changing_the_stop_token_on_repeek_is_an_implementation_error() {
        let err = flaky_terminator_error(Betrayal::KindChange);
        assert_eq!(err.identifier(), crate::constructs::ImplementationError::IDENTIFIER);
    }

    #[test]
    fn a_reader_dropping_the_stop_token_on_repeek_is_an_implementation_error() {
        let err = flaky_terminator_error(Betrayal::Vanish);
        assert_eq!(err.identifier(), crate::constructs::ImplementationError::IDENTIFIER);
    }

    // --- the verbatim escape hatch ----------------------------------------------------------

    #[test]
    fn verbatim_body_via_the_takeover_hatch() {
        let st = suite_state();
        //             0....5....1....1....2....2....3
        //                  0    5    0    5    0
        let content = "\\raw {\\begin %~\\endraw z";
        let parsed = parse_std(content, &st, Recovery::Strict);

        // The takeover reads raw source bytes — markup, comment chars, specials and
        // all — into one Chars body node; the trigger's post-space stays raw content
        // (the `\verb` reposition idiom), and the slot record is parser-minted.
        assert_eq!(
            shapes(&parsed.result),
            ["callable 0..22 \"raw\"", "chars 22..24 \" z\""],
        );
        let raw = root_child(&parsed, 0);
        assert_eq!(raw.slots().unwrap().len(), 1);
        assert!(raw.slots().unwrap().get_named("raw").is_some());
        assert_eq!(body_shapes(raw), ["chars 4..15 \" {\\\\begin %~\""]);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn verbatim_body_inside_a_group_overrides_the_inherited_close() {
        // The Action-02 pitfall: inside a braces group the interior state expects `}`
        // (ungated by the groups gate), so a verbatim state that merely disabled the
        // feature gates would still read the body's `}` as a GroupClose. The recipe
        // *replaces* the expectation with the raw terminator instead: the `}` stays
        // body content, and the enclosing group still finds its own close afterwards.
        let st = suite_state();
        //             0....5....1....1....
        //                  0    5
        let content = "{a\\raw }b\\endraw c}";
        let parsed = parse_std(content, &st, Recovery::Strict);

        let group = root_child(&parsed, 0);
        assert!(group.is_group());
        assert_eq!(group.span().range(), 0..19);
        let raw = group.child(1).unwrap();
        assert_eq!(raw.span().range(), 2..16);
        assert_eq!(body_shapes(raw), ["chars 6..9 \" }b\""]);
        assert!(parsed.result.diagnostics.is_empty());
    }

    #[test]
    fn verbatim_body_missing_its_terminator() {
        let st = suite_state();
        let content = "\\raw abc";
        let parsed = parse_std(content, &st, Recovery::Tolerant);

        let raw = root_child(&parsed, 0);
        assert_eq!(raw.span().range(), 0..8);
        assert_eq!(body_shapes(raw), ["chars 4..8 \" abc\""]);
        assert_eq!(parsed.result.diagnostics.len(), 1);
        assert_eq!(diagnostics_mentioning(&parsed, "\\endraw"), 1);
    }

    // --- the requires_content() override (slots session): `\begin` bare in expression
    // --- position is diagnosed, not dispatched ----------------------------------------

    /// The documented divergence from pylatexenc (which dispatches the environment as
    /// the argument): `\emph\begin{A}…` diagnoses the bare `\begin` — `BeginSpec`
    /// declares nothing but overrides `requires_content()` — and stages it alone as
    /// `\emph`'s argument. The environment's pieces stay sibling content, its orphan
    /// `\end` taking the unresolvable-command recovery.
    #[test]
    fn bare_begin_in_expression_position_is_diagnosed() {
        let st = suite_state();
        //             0....5....1....1....2..
        //                  0    5    0
        let content = "\\emph\\begin{A}x\\end{A}";
        let parsed = parse_both(content, &st, Recovery::Tolerant);

        assert_eq!(
            shapes(&parsed.result),
            [
                "callable 0..11 \"emph\"",
                "group 11..14",
                "chars 14..15 \"x\"",
                "chars 15..19 \"\\\\end\"",
                "group 19..22",
            ],
        );
        let emph = root_child(&parsed, 0);
        let bare = emph.argument_content_nodes(0).unwrap().iter().next().unwrap();
        assert_eq!(bare.name(), Some("begin"));
        assert_eq!(bare.child_count(), 0);
        assert_eq!(parsed.result.diagnostics.len(), 2);
        assert_eq!(
            parsed.result.diagnostics.iter().next().unwrap().identifier(),
            crate::constructs::ExpressionCallableRequiresContent::IDENTIFIER,
        );
    }

    // --- the end-to-end §G suite ------------------------------------------------------------

    #[test]
    fn end_to_end_realistic_snippet() {
        let st = suite_state();
        let content = "Intro \\emph{te}~xt. % note\n\\begin{itemize} \\item[a] one\n\n\\item two \\frac{1}{2}\n\\end{itemize} tail \\section*{Top}!";
        let parsed = parse_std(content, &st, Recovery::Strict);

        assert_eq!(
            shapes(&parsed.result),
            [
                "chars 0..6 \"Intro \"",
                "callable 6..15 \"emph\"",
                "callable 15..16 \"~\"",
                "chars 16..20 \"xt. \"",
                "comment 20..27 \" note\"",
                "callable 27..92 \"itemize\"",
                "chars 92..98 \" tail \"",
                "callable 98..112 \"section\"",
                "chars 112..113 \"!\"",
            ],
        );

        // Post-space placement: `\emph` and `\section` have none (delimiters follow
        // directly); the specials `~` records none either.

        // The environment's body: whitespace, two \item invocations (one with its
        // option, one bare — the bare one's span includes its own syntactic
        // post-space), a paragraph break, and the \frac.
        let env = root_child(&parsed, 5);
        assert_eq!(env.callable_type(), Some(CT_ENVIRONMENT));
        assert_eq!(
            body_shapes(env),
            [
                "chars 42..43 \" \"",
                "callable 43..51 \"item\"",
                "chars 51..55 \" one\"",
                "chars 55..57 \"\\n\\n\"",
                "callable 57..63 \"item\"",
                "chars 63..67 \"two \"",
                "callable 67..78 \"frac\"",
                "chars 78..79 \"\\n\"",
            ],
        );
        let body: Vec<_> = env.body().unwrap().iter().collect();
        let item_with_option = body[1];
        assert!(item_with_option.arguments().unwrap().get(0).unwrap().is_provided());
        let bare_item = body[4];
        assert!(!bare_item.arguments().unwrap().get(0).unwrap().is_provided());
        let frac = body[6];
        let ones: Vec<_> = frac.argument_content_nodes(0).unwrap().iter().collect();
        assert_eq!(ones[0].chars(), Some("1"));

        // `\section*{Top}`: marker provided (a Chars content node), option absent,
        // title group provided.
        let section = root_child(&parsed, 7);
        let args = section.arguments().unwrap();
        assert!(args.get(0).unwrap().is_provided());
        assert!(!args.get(1).unwrap().is_provided());
        let title: Vec<_> = section.argument_content_nodes(2).unwrap().iter().collect();
        assert_eq!(title[0].chars(), Some("Top"));

        assert!(parsed.result.diagnostics.is_empty());
        assert_eq!(parsed.pos, content.len());
    }
    // --- the name group's text vs its coordinates (PLAN §1.5, the name-as-read rule) ---

    /// [`NameGroup::name_text`] answers the name **as read** where the parser recorded
    /// one, and the span's content otherwise. The two are separate facts once the
    /// language does not obey span tiling: there the span is only what the reader
    /// described for the stretch the name was read from.
    #[test]
    fn a_name_group_answers_the_name_as_read() {
        let source: Arc<Source> = Arc::new(Source::new("{itemize}"));
        let rule: Arc<GroupRule<EnvLang>> = Arc::new(GroupRule {
            group_type: GT_BRACE,
            open: String::from("{"),
            close: String::from("}"),
        });

        // No name as read: the span is the name (a tiled parse, or a name sliced out
        // of one token's own span).
        let spanned = NameGroup::new(
            SourceSpan::new(&source, 1..8),
            StdStreamPosition::at(9),
            Arc::clone(&rule),
        );
        assert_eq!(spanned.name_text(), "itemize");

        // A described span that covers something else entirely: the recorded
        // characters win, and the span stays what it is (the node's coordinates).
        let as_read = NameGroup::new(
            SourceSpan::new(&source, 0..1),
            StdStreamPosition::at(9),
            Arc::clone(&rule),
        )
        .with_name_as_read("itemize");
        assert_eq!(as_read.name_text(), "itemize");
        assert_eq!(as_read.name.content(), "{");
    }
}