techy 0.1.3

A fast, extensible LaTeX parser for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
//! Construct parsers: the `ConstructParser` contract and the standard parsers.
//!
//! [`ConstructParser`] is the single most important trait in the system: every construct —
//! the root parse ([`RootNodesParser`], the parser the entry point runs directly), the
//! main content loop ([`NodesParser`]), groups ([`GroupParser`]), callable invocations
//! ([`StdInvocationParser`], behind the
//! [`make_invocation_parser`](crate::core::specs::CallableSpec::make_invocation_parser) factory),
//! arguments (the standard [`ArgumentParser`](crate::core::constructs::ArgumentParser)
//! implementations), environment bodies ([`EnvironmentBodyParser`]) — is parsed by an
//! implementation of it, reading tokens and staging nodes through one [`ParseContext`].
//!
//! # Temporaries and stored behavior
//!
//! Construct parsers are **temporaries**: constructed with their per-use configuration
//! where they are needed, `parse(&mut self, …)` so working state is kept in fields, free
//! to borrow (`'s` content, token refs), dropped when the frame ends — never stored in
//! specs. **Stored** behavior objects — specs and
//! [`ArgumentParser`](crate::core::constructs::ArgumentParser)s — are `Arc`-shared,
//! `Send + Sync`, immutable, and receive every per-use input as arguments. Closures
//! (stop predicates) therefore belong to construct parsers only; specs stay data.
//!
//! # State threading (the "caller applies deltas" law, pinned to `cx`)
//!
//! [`ParseContext::state`] is the parser's **input** state — the caller sets it. A parser
//! that scopes a child state (group interior, argument extent, slot body) derives it
//! locally and scopes it through
//! [`parse_construct`](ParseContext::parse_construct) /
//! [`with_parsing_state`](ParseContext::with_parsing_state) (structural revert —
//! `Arc` clone is
//! cheap — plus the session's enclosing-state stack bookkeeping). The
//! `Option<Box<ParsingStateDelta>>` in the
//! return value is exclusively the *after-effect for the caller* (`\newcommand`);
//! it is boxed so the common `None` costs one pointer-sized slot per recursion
//! level, not the full delta struct.
//!
//! # Errors
//!
//! `Err` means **abort**: recovery happens at the detection site (the
//! [`recover`](ParseContext::recover) helper), and abnormal endings of sub-parses travel
//! as data ([`StopCause`]) — nobody continues past an `Err`.

mod argument_parsers;
mod attached_source;
mod chars_group_parser;
mod child_state;
#[cfg(test)]
mod content_reader_tests;
mod embellishments_parser;
mod environment_parser;
mod group_parser;
mod invocation_parser;
mod nodes_parser;
mod root_parser;
#[cfg(test)]
mod span_tiling_tests;
mod tack_on_parser;
mod terminated_parser;
mod verbatim_parser;

pub use argument_parsers::{
    peek_adjacent_argument, scan_argument_noise, stage_pre_space, ArgumentNoise,
    ExpectedExpressionArgument,
    ExpressionParser, GroupArgumentParser, MarkerArgumentParser, MissingMandatoryArgument,
    OptionalGroupArgumentParser,
};
pub use attached_source::{
    AttachedSourceOutcome, InvalidReferenceReason, InvalidSourceReferenceArgument,
    NoSourceResolver, UnresolvableSourceReference,
};
pub use chars_group_parser::CharsGroupArgumentParser;
pub use child_state::{ChildStateSpec, GroupChildState, InvocationChildState};
pub use embellishments_parser::EmbellishmentsArgumentParser;
pub use tack_on_parser::{RepeatedTackOnField, TackOnFieldsArgumentParser};
pub use environment_parser::{
    read_rigid_name_group, EnvironmentBeginSyntaxData, EnvironmentBody,
    EnvironmentBodyParser, EnvironmentTerminatorMismatch,
    EnvironmentTerminatorSyntaxData, MalformedEnvironmentTerminator,
    MissingEnvironmentTerminator, MissingTerminatorFound, NameGroup,
};
pub use group_parser::{
    GroupAfterEffectsFn, GroupParser, UnclosedGroup, UnclosedGroupFound,
};
pub use invocation_parser::{parse_declared_arguments, StdInvocationParser};
pub use nodes_parser::{
    CommandResolutionFailed, ExpressionCallableRequiresContent, NodesOutcome, NodesParser,
    StopCause, StopSpec, StrayGroupClose, TokenStopCondition, TokenStopKind,
    UnresolvableCommand, UnusableRecoveryToken, UnusableRecoveryTokenKind,
};
pub use root_parser::RootNodesParser;
pub use terminated_parser::{
    ExpectedArgumentOpener, MissingArgumentTerminator, TerminatedArgumentParser,
};
pub use verbatim_parser::{
    verbatim_state_delta, ExpectedVerbatimDelimiter, UnterminatedVerbatim,
    VerbatimArgumentParser, VerbatimBodyParser, VerbatimBodyTerminator,
};

use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use alloc::sync::Arc;
use core::fmt;

use crate::engine::{Frame, FrameTitle, ParseDriver, ParserSession, SessionDeriveError};
use crate::error::{Diagnostic, DiagnosticData, DiagnosticInfo, HookFailed, ParseError, Severity};
use crate::source::{SourceSpan, TextContent};
use crate::spec::{CallableSpec, FrameRole};
use crate::node::{
    BuildId, CallableData, ContentNodes, NodeBuildError, NodeKind, NodeTree, NodeTreeBuilder,
    ParsedArgument, ParsedArguments, ParsedSlots, StagedNodeView, StagedNodes,
};
use crate::state::{FeaturePresence, Lang, LangFeatures, ParsingState, ParsingStateDelta};
use crate::token::{GroupRule, StreamPosition, Token, TokenEdge, TokenReader};

/// The live frame covering a resolved invocation's parse (the dispatch push site): the spec's title hook with the invocation spelling — the
/// trigger token minus its syntactic post-space — anchored at the trigger. Built before
/// the `Invocation` moves into the spec's parser factory; allocation-free (`Arc` bumps
/// only).
pub(crate) fn invocation_frame<L: Lang>(
    cx: &ParseContext<'_, '_, L>,
    invocation: &Invocation<'_, L>,
) -> Frame<L> {
    let token = invocation.token;
    Frame {
        title: FrameTitle::Callable {
            spec: Arc::clone(invocation.spec),
            role: FrameRole::Invocation,
            name: cx.tokens.source_span_between(token, TokenEdge::Start, TokenEdge::End),
        },
        span: cx.tokens.source_span_of(token),
    }
}

/// Record a spelling fact the reader answered as node data on a node spanning
/// `node_span`: a node-relative [`Span`](crate::source::Span) when the fact lies in
/// the node's own source, the fact's text itself otherwise.
///
/// The one spelling of the node-data rule: a bare span means nothing without the
/// source it indexes, so a fact from another source is recorded as owned text instead
/// of as a span that would read against the wrong content. A fact can only come from
/// another source under a language with
/// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`, whose reader
/// may serve one parse from several sources: at a seam between two of them a single
/// token can even have edges in two sources, so one of its sub-spans may lie outside
/// the node's own.
///
/// The rule assumes nothing about the tokens: both arms read the very same
/// reader-answered span, and which arm applies is decided by the source the fact lies
/// in — the residency the all-trees law
/// ([`validate_tree`](crate::core::node::validate_tree)) checks.
pub(crate) fn node_text_content<O: crate::source::SourceOrigin>(
    fact: &SourceSpan<O>,
    node_span: &SourceSpan<O>,
) -> TextContent {
    match fact.same_source(node_span) {
        true => TextContent::Spanned(fact.span()),
        false => TextContent::Owned(fact.content().into()),
    }
}

/// Append the text of `token`'s pre-space to a run of owned content, as the reader
/// answers it for that token. Does nothing when `text` is `None` — the spelling of "no
/// owned text is being accumulated", which is the case for a language that obeys span
/// tiling ([`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING)).
pub(crate) fn push_pre_space_text<L: Lang>(
    text: &mut Option<String>,
    cx: &ParseContext<'_, '_, L>,
    token: &Token<L>,
) {
    let Some(text) = text else { return };
    text.push_str(
        cx.tokens
            .source_span_between(token, TokenEdge::StartBeforePreSpace, TokenEdge::Start)
            .content(),
    );
}

/// Append everything `token` contributes to a run of owned content: its pre-space, the
/// `spelling` the reader classified it as (the character of a
/// [`Char`](crate::core::token::TokenKind::Char) token, the delimiter of a group close read
/// as content), and its syntactic post-space — three answers about this one token,
/// asked of the reader that produced it.
///
/// This is the recipe multi-token content follows for a language with
/// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`, where the
/// tokens of one node need not form one contiguous stretch of one source, so no single
/// span describes their text. Does nothing when `text` is `None` (see
/// [`push_pre_space_text`]).
pub(crate) fn push_token_text<L: Lang>(
    text: &mut Option<String>,
    cx: &ParseContext<'_, '_, L>,
    token: &Token<L>,
    spelling: &str,
) {
    push_pre_space_text(text, cx, token);
    let Some(text) = text else { return };
    text.push_str(spelling);
    text.push_str(
        cx.tokens
            .source_span_between(token, TokenEdge::End, TokenEdge::EndPastPostSpace)
            .content(),
    );
}

/// The `Comment` node kind for a comment token, plus the node's span: the delimiter,
/// the text, and the syntactic post-space, each recorded as node data.
///
/// All four spans are reader answers about the token's edges — the delimiter is
/// `Start..ContentStart`, the content `ContentStart..End`, the post-space
/// `End..EndPastPostSpace`, and the node's span the token's own. The parser computes
/// none of them itself, and records the three sub-spans through the node-data rule
/// ([`node_text_content`]): a span of the node's own source where the answer lies in
/// it, the text itself otherwise — which is what a token whose edges fall in two
/// sources needs (a seam, reachable only under
/// [`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`).
pub(crate) fn comment_node_kind<L: Lang>(
    cx: &ParseContext<'_, '_, L>,
    token: &Token<L>,
) -> (NodeKind<L>, SourceSpan<L::SourceOrigin>) {
    let span = cx.tokens.source_span_of(token);
    let between = |a, b| cx.tokens.source_span_between(token, a, b);
    let kind = NodeKind::comment(
        node_text_content(&between(TokenEdge::Start, TokenEdge::ContentStart), &span),
        node_text_content(&between(TokenEdge::ContentStart, TokenEdge::End), &span),
        node_text_content(&between(TokenEdge::End, TokenEdge::EndPastPostSpace), &span),
    );
    (kind, span)
}

/// Everything a construct parser needs during one construct's parse, in one value:
/// the token reader, the input parsing state, the per-parse session, and the
/// language's driver.
///
/// A [`ConstructParser`] receives one by reference and does all of its work through
/// it: reading tokens, staging nodes, running sub-parsers, deriving and scoping
/// parsing states, pushing traceback frames, and reporting problems. Code that drives
/// construct parsers itself builds a context with [`new`](ParseContext::new).
///
/// **Spans come from the token reader** — the context holds no source handle. A
/// construct parser does not pair a byte range with a source itself: every
/// [`SourceSpan`] it stages or reports is obtained
/// from [`tokens`](ParseContext::tokens) — one token's span
/// ([`TokenReader::source_span_of`](crate::core::token::TokenReader::source_span_of),
/// [`source_span_between`](crate::core::token::TokenReader::source_span_between)), the span
/// between two stream positions
/// ([`source_span_within`](ParseContext::source_span_within)), or the empty span at
/// the current position ([`here`](ParseContext::here), the anchor for a condition
/// detected between tokens). Only the reader knows which source it is serving tokens
/// from, so only the reader can answer where a token is.
///
/// **Dispatching fallible public hooks yourself.** A third-party construct parser
/// that consults a fallible hook directly — say
/// [`ParseDriver::resolve_command`](crate::core::ParseDriver::resolve_command) or
/// [`CallableSpec::make_invocation_parser`](crate::core::specs::CallableSpec::make_invocation_parser)
/// — also owns the error's traceback: the hooks have no session access, so the
/// consultation site attaches the live traceback to a hook-returned abort error
/// through [`ParseContext::attach_hook_frames`]
/// (`.map_err(|error| cx.attach_hook_frames(error))`), exactly as the in-crate
/// dispatch sites do — an error already carrying frames keeps them.
pub struct ParseContext<'a, 's, L: Lang> {
    /// The token stream — and the answer to every "where?" question: what a token
    /// is worth as a span, and where the stream stands.
    pub tokens: &'a mut dyn TokenReader<'s, L>,
    /// The parser's **input** parsing state (the caller sets it; see the
    /// state-threading contract in [`core::constructs`](crate::core::constructs)).
    pub state: Arc<ParsingState<L>>,
    /// The per-parse [`ParserSession`]. What a construct parser reaches on it
    /// directly: the [`diagnostics`](ParserSession::diagnostics) sink, the
    /// language's session extension ([`ext`](ParserSession::ext)), and a rendered
    /// snapshot of the live frame stack
    /// ([`snapshot_frames`](ParserSession::snapshot_frames)). Everything else a
    /// parser needs from the session goes through this context's own methods,
    /// which are also the preferred spellings for the session-mediated derivations:
    /// staging via [`stage_node`](ParseContext::stage_node) /
    /// [`stage_invocation`](ParseContext::stage_invocation), descents via
    /// [`parse_construct`](ParseContext::parse_construct), state derivation via
    /// [`derive_state`](ParseContext::derive_state) /
    /// [`group_interior_state`](ParseContext::group_interior_state), problem
    /// reporting via [`recover`](ParseContext::recover) /
    /// [`implementation_error`](ParseContext::implementation_error), frames via
    /// [`with_frame`](ParseContext::with_frame) /
    /// [`attach_hook_frames`](ParseContext::attach_hook_frames). The session's node
    /// builder, memo storage, and frame stack are internal.
    pub session: &'a mut ParserSession<L>,
    /// The language's [`ParseDriver`]: recovery policy, parse-time hooks,
    /// the descent-delta channel, construct provision. **Concretely typed through
    /// `L`** — preset parsers reach preset helper methods (inherent methods on the
    /// driver type) with zero downcasts; generic code sees only the trait.
    pub driver: &'a L::Driver,
}

impl<'a, 's, L: Lang> ParseContext<'a, 's, L> {
    /// Creates a context from the four parse inputs: the token reader, the
    /// construct's input parsing state, the session, and the driver.
    ///
    /// Prefer this over a struct literal even though the fields are public. The
    /// context is where the library grows when parsing gains a new ambient concern
    /// (a depth limit, a cancellation signal), and construction through `new` keeps
    /// such an addition from breaking code that builds contexts.
    pub fn new(
        tokens: &'a mut dyn TokenReader<'s, L>,
        state: Arc<ParsingState<L>>,
        session: &'a mut ParserSession<L>,
        driver: &'a L::Driver,
    ) -> ParseContext<'a, 's, L> {
        ParseContext { tokens, state, session, driver }
    }

    /// The empty [`SourceSpan`] at the reader's current stream position — the
    /// diagnostics anchor for a condition detected **between** tokens (a missing
    /// argument, a contract violation with no token to blame).
    pub fn here(&self) -> SourceSpan<L::SourceOrigin> {
        SourceSpan::at(&self.tokens.source_position_at(&self.tokens.position_here()))
    }

    /// Returns the source span running from `begin` to `end` — the span of a
    /// construct covering several tokens.
    ///
    /// The two arguments are stream positions the reader returned
    /// ([`position_here`](crate::core::token::TokenReader::position_here),
    /// [`position_at`](crate::core::token::TokenReader::position_at)).
    ///
    /// The answer follows the language's [`Lang::OBEYS_SPAN_TILING`] declaration:
    ///
    /// - `true` (the default): the span is the range the two positions delimit
    ///   ([`TokenReader::source_span_within`](crate::core::token::TokenReader::source_span_within)).
    ///   `Err` reports an [`ImplementationError`] when they delimit no such range
    ///   (`end` before `begin`, or the two in different sources) — a contract violation
    ///   by the calling parser or by the reader; it aborts under any recovery policy,
    ///   and never panics.
    /// - `false`: the span is the one the reader *describes* for that stretch of stream
    ///   ([`TokenReader::source_span_describing`](crate::core::token::TokenReader::source_span_describing)),
    ///   and there is no error case — the two positions need not delimit one range of
    ///   one source, and an inverted pair is not an error either. The returned span is
    ///   a coordinate hint that becomes the node's span: callers must derive no content
    ///   and no structure from it.
    pub fn source_span_within(
        &self,
        begin: &StreamPosition<L>,
        end: &StreamPosition<L>,
    ) -> ConstructParserResult<L, SourceSpan<L::SourceOrigin>> {
        if !L::OBEYS_SPAN_TILING {
            return Ok(self.tokens.source_span_describing(begin, end));
        }
        match self.tokens.source_span_within(begin, end) {
            Some(span) => Ok(span),
            None => Err(self.implementation_error(
                format!(
                    "the positions {begin:?} and {end:?} do not delimit one range of \
                     one source (a span must run forward within a single source)"
                ),
                self.here(),
            )),
        }
    }

    /// Stages one parsed node and returns the [`BuildId`](crate::core::node::BuildId) that
    /// identifies it.
    ///
    /// This is the **single staging entry point** of parsing: every parsed node
    /// enters the tree through it, and construct parsers reach the tree builder no
    /// other way. Because of that, this is also where each node's language extension
    /// is created — [`Lang::make_node_ext`] runs here, with the
    /// [`StagedChildren`](crate::core::node::StagedChildren) view of `children` — so no
    /// node can escape extension minting and no parser has to cooperate for it to
    /// happen. The node is staged with annotation `()`: a parse produces the
    /// unannotated `NodeTree<L>`, and annotations belong to the code that consumes
    /// the tree afterwards.
    ///
    /// `children` are the node's structural children in order (for a `Callable`: one
    /// region per provided argument, then one per slot — see
    /// [`NodeTreeBuilder::add`](crate::core::node::NodeTreeBuilder::add)).
    ///
    /// # Errors
    ///
    /// Returns a [`NodeBuildError`](crate::core::node::NodeBuildError) in two cases, both
    /// of which abort the parse under any recovery policy — neither is a condition in
    /// the source being parsed:
    ///
    /// - a violation of the staging contract, which is an implementation bug in an
    ///   extension. Turn it into an abort error with
    ///   [`implementation_error`](ParseContext::implementation_error).
    /// - [`ExtMintFailed`](crate::core::node::NodeBuildError::ExtMintFailed), the failure
    ///   [`Lang::make_node_ext`] itself reported. This is an operational failure in
    ///   consumer-supplied code rather than a broken contract, so turn it into a
    ///   [`HookFailed`](crate::error::HookFailed) condition holding the mint's
    ///   `detail`, with the live traceback attached
    ///   ([`attach_hook_frames`](ParseContext::attach_hook_frames)).
    ///
    /// The in-crate staging callers match on the variant and do exactly that.
    pub fn stage_node(
        &mut self,
        kind: NodeKind<L>,
        span: SourceSpan<L::SourceOrigin>,
        state: Arc<ParsingState<L>>,
        children: Vec<BuildId>,
    ) -> Result<BuildId, NodeBuildError> {
        let ext = L::make_node_ext(
            &kind,
            &span,
            &state,
            self.session.builder.staged_children(&children),
        )?;
        self.session.builder.add(kind, span, state, children, ext, ())
    }

    /// The read-only view of the nodes staged so far, keyed by
    /// [`BuildId`](crate::core::node::BuildId) — what node-based stop predicates and span
    /// arithmetic over already-staged children consume. Read view only: staging goes
    /// through [`stage_node`](ParseContext::stage_node).
    pub fn staged_nodes(&self) -> StagedNodes<'_, L> {
        self.session.builder.staged_nodes()
    }

    /// Copies the content nodes a [`ContentNodes`] designation names into a small
    /// finished [`NodeTree`], so the reading helpers of
    /// [`extract`](crate::extract) apply while the enclosing parse is still running.
    ///
    /// This is the parse-time answer to "what does this argument or slot actually
    /// say?". The nodes a parse has staged are not in a tree yet — the tree is built
    /// once, at the end — so nothing that takes a
    /// [`NodeRef`](crate::core::node::NodeRef) can be pointed at them. This copies the
    /// designated nodes and their subtrees into a tree of their own, under a
    /// synthesized `List` root, and hands that tree back.
    ///
    /// `region_nodes` are the staged ids of the region the designation belongs to, in
    /// order — the slice of the callable's child list that the region's child offsets
    /// cover. `content` is the designation itself:
    /// [`InRegion`](ContentNodes::InRegion) offsets index `region_nodes`, and
    /// [`InChildrenOf`](ContentNodes::InChildrenOf) offsets index the named staged
    /// node's own children. Reading a *declared argument's* content is
    /// [`argument_content_as_tree`](ParseContext::argument_content_as_tree), which
    /// reads the region and the content designation off the argument record for you.
    ///
    /// # The tree that comes back
    ///
    /// The root is a `List` node holding one copy per designated content node, in
    /// order. Its ext is minted through
    /// [`Lang::make_node_ext`](crate::core::Lang::make_node_ext), as for every
    /// synthesized node; the copies keep the exts they were staged with, which is the
    /// rule for every copy in the library. Read the content with
    /// `tree.root().children()`.
    ///
    /// The root's span and parsing state describe where the content came from: the
    /// span covering the first through the last content node, and the first content
    /// node's state. Two cases have no such pair to compute, and both fall back:
    ///
    /// - **No content node at all** (`\m{}` designates none): the content parent's
    ///   span and state for an [`InChildrenOf`](ContentNodes::InChildrenOf)
    ///   designation — the empty content still sits inside the group — and otherwise
    ///   the empty span at the reader's position ([`here`](ParseContext::here)) with
    ///   this context's own [`state`](ParseContext::state).
    /// - **First and last node not laid out in order** — the two in different sources,
    ///   which a language declaring
    ///   [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false` allows,
    ///   or the last node starting before the first does or ending before the first
    ///   ends, so that no range from the first's start to the last's end would cover
    ///   both: the content parent's span if the designation has one, and otherwise the
    ///   first content node's own span. The state is the first content node's in either
    ///   case.
    ///
    /// In both fallbacks the root's span says *where* the content sits rather than what
    /// it covers, so it does not partition its children's spans the way a parsed `List`
    /// does. A consumer that assumes that partition — the byte accounting of a language
    /// declaring [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) — should
    /// read the children and not the root's own span.
    ///
    /// # Annotations: the way back
    ///
    /// The tree is annotated with `Option<BuildId>`: every copied node carries
    /// `Some(id)` naming the staged node it was copied from, and the synthesized root
    /// carries `None`. Node ids of the returned tree mean nothing outside it, so the
    /// annotation is what maps a result back onto the parse — for instance to anchor a
    /// diagnostic at the staged node a helper objected to. Read one with
    /// [`NodeRef::annotation`](crate::core::node::NodeRef::annotation).
    ///
    /// # Cost
    ///
    /// Every call copies: node data, spans, and states are cloned (`Arc`-shared where
    /// the storage is shared), and [`finish`](crate::core::node::NodeTreeBuilder::finish)
    /// takes one tree tag from a process-wide counter. That is cheap for one argument
    /// and not free per invocation of a very frequently used spec — for such a spec,
    /// read the content once and keep what you need, or use
    /// [`content_as_plain_chars`](ParseContext::content_as_plain_chars) when plain
    /// characters are all you are after.
    ///
    /// # Errors
    ///
    /// [`ContentOutOfBounds`](crate::core::node::NodeBuildError::ContentOutOfBounds)
    /// when the designation's range does not fit the nodes it indexes into — the
    /// region's own nodes, or the content parent's children — exactly as
    /// [`add`](crate::core::node::NodeTreeBuilder::add) reports it,
    /// [`ContentParentNotStaged`](crate::core::node::NodeBuildError::ContentParentNotStaged)
    /// for an [`InChildrenOf`](ContentNodes::InChildrenOf) parent that is not staged,
    /// [`ChildNotStaged`](crate::core::node::NodeBuildError::ChildNotStaged) for a
    /// designated id that is not, plus what the copy itself reports. All of these are
    /// contract violations by the calling parser — lift one with
    /// [`implementation_error`](ParseContext::implementation_error) — except
    /// [`ExtMintFailed`](crate::core::node::NodeBuildError::ExtMintFailed), the root
    /// ext mint's own reported failure, which is an operational failure to lift as a
    /// [`HookFailed`] condition, exactly as
    /// [`stage_node`](ParseContext::stage_node) documents.
    pub fn content_as_tree(
        &self,
        region_nodes: &[BuildId],
        content: &ContentNodes,
    ) -> Result<NodeTree<L, Option<BuildId>>, NodeBuildError> {
        let (nodes, parent) = self.resolve_content_nodes(region_nodes, content)?;
        let staged = self.staged_nodes();
        let mut builder: NodeTreeBuilder<L, Option<BuildId>> = NodeTreeBuilder::new();
        let mut children = Vec::with_capacity(nodes.len());
        for id in nodes {
            children.push(staged.copy_subtree_into(*id, &mut builder, &mut |view| {
                Some(view.id())
            })?);
        }
        let (span, state) = self.content_root_provenance(nodes, parent)?;
        let kind = NodeKind::list();
        let ext = L::make_node_ext(&kind, &span, &state, builder.staged_children(&children))?;
        let root = builder.add(kind, span, state, children, ext, None)?;
        builder.finish(root)
    }

    /// Copies a declared argument's content into a small finished [`NodeTree`] —
    /// [`content_as_tree`](ParseContext::content_as_tree) reached from the argument
    /// record, which is how an invocation parser reads what its own argument says.
    ///
    /// `argument` is the record the argument loop produced
    /// ([`parse_declared_arguments`]) and `children` the flat child list those records
    /// tile — the same pair that goes on to
    /// [`stage_invocation`](ParseContext::stage_invocation). The argument's region
    /// says which of `children` it covers and which of those are its content, and the
    /// designated nodes are copied as described on
    /// [`content_as_tree`](ParseContext::content_as_tree), whose page covers the shape
    /// of the returned tree, its annotations, and its cost.
    ///
    /// `Ok(None)` means the argument **was not provided** — an absent optional, or a
    /// mandatory one the argument parser already diagnosed as missing. A provided
    /// argument always answers `Ok(Some(tree))`, whose root may still have no children:
    /// `\m{}` is provided with empty content.
    ///
    /// # Errors
    ///
    /// [`RegionAlreadyResolved`](crate::core::node::NodeBuildError::RegionAlreadyResolved)
    /// for an argument record whose region is not in staging coordinates — records read
    /// back from a finished tree do not belong in a parse — and
    /// [`RegionOutOfBounds`](crate::core::node::NodeBuildError::RegionOutOfBounds)
    /// when the region's child offsets lie outside `children`, plus every error of
    /// [`content_as_tree`](ParseContext::content_as_tree).
    pub fn argument_content_as_tree(
        &self,
        argument: &ParsedArgument<L>,
        children: &[BuildId],
    ) -> Result<Option<NodeTree<L, Option<BuildId>>>, NodeBuildError> {
        let Some((region_nodes, content)) = self.argument_designation(argument, children)? else {
            return Ok(None);
        };
        self.content_as_tree(region_nodes, content).map(Some)
    }

    /// The characters of the content nodes a [`ContentNodes`] designation names,
    /// concatenated in order — the cheap direct read, for content that must be plain
    /// characters and nothing else.
    ///
    /// The text is read off the nodes' own data (each `Chars` node's payload), not off
    /// their spans: node data is what a reader answered for the node, so the result is
    /// the same under every language, including one declaring
    /// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`, whose
    /// content may come from more than one source. Characters are taken as written,
    /// with no trimming and no normalization. Empty content reads as the empty string.
    ///
    /// The parameters are those of
    /// [`content_as_tree`](ParseContext::content_as_tree); no tree is built and nothing
    /// is copied.
    ///
    /// **This is a stricter rule than
    /// [`extract::content_as_chars`](crate::extract::content_as_chars)**, which is the
    /// helper for reading text out of a finished tree. That one descends into groups
    /// and lists to collect the characters inside them and skips comments entirely; it
    /// objects only to a callable. This one accepts nothing but `Chars` nodes at the
    /// top level: anything other than characters among the content — a group, a
    /// callable, a comment, or a nested list — is
    /// [`NotPlainCharacters`](PlainCharsError::NotPlainCharacters). Use it where the
    /// content names something — a file reference, a key, a label — and a group or a
    /// comment in it means the document said something other than a name. Where the
    /// flattening rule is wanted instead, read the content with
    /// [`content_as_tree`](ParseContext::content_as_tree) and call
    /// `extract::content_as_chars` on `tree.root().children()`.
    ///
    /// # Errors
    ///
    /// [`NotPlainCharacters`](PlainCharsError::NotPlainCharacters), naming the
    /// offending staged node, for content holding anything other than characters — a
    /// condition in the parsed document, to diagnose through
    /// [`recover`](ParseContext::recover).
    /// [`MalformedRecord`](PlainCharsError::MalformedRecord)
    /// for a staged record that does not resolve, which is a contract violation by the
    /// calling parser and carries the same
    /// [`NodeBuildError`](crate::core::node::NodeBuildError) variants
    /// [`content_as_tree`](ParseContext::content_as_tree) reports.
    pub fn content_as_plain_chars(
        &self,
        region_nodes: &[BuildId],
        content: &ContentNodes,
    ) -> Result<String, PlainCharsError> {
        let (nodes, _) = self.resolve_content_nodes(region_nodes, content)?;
        let staged = self.staged_nodes();
        let mut text = String::new();
        for id in nodes {
            let view =
                staged.get(*id).ok_or(NodeBuildError::ChildNotStaged { child: *id })?;
            match view.kind() {
                NodeKind::Chars { content: chars, .. } => {
                    text.push_str(chars.resolve(view.span().source()))
                }
                _ => return Err(PlainCharsError::NotPlainCharacters { node: *id }),
            }
        }
        Ok(text)
    }

    /// The characters of a declared argument's content —
    /// [`content_as_plain_chars`](ParseContext::content_as_plain_chars) reached from
    /// the argument record, the way
    /// [`argument_content_as_tree`](ParseContext::argument_content_as_tree) reaches
    /// [`content_as_tree`](ParseContext::content_as_tree).
    ///
    /// `argument` and `children` are the argument loop's output pair, as there.
    /// `Ok(None)` means the argument was not provided; a provided argument with empty
    /// content answers `Ok(Some(String::new()))`.
    ///
    /// This is what the preset's `\input`-shaped spec
    /// ([`InputMacroSpec`](crate::latexlike::InputMacroSpec)) reads its source
    /// reference with, and the strict character rule stated on
    /// [`content_as_plain_chars`](ParseContext::content_as_plain_chars) is why
    /// `\input{{chap.tex}}` is diagnosed rather than resolved.
    ///
    /// # Errors
    ///
    /// Those of [`content_as_plain_chars`](ParseContext::content_as_plain_chars), plus
    /// — as [`MalformedRecord`](PlainCharsError::MalformedRecord) — the two record
    /// failures [`argument_content_as_tree`](ParseContext::argument_content_as_tree)
    /// reports: a region that is not in staging coordinates
    /// ([`RegionAlreadyResolved`](crate::core::node::NodeBuildError::RegionAlreadyResolved)),
    /// and region offsets outside `children`
    /// ([`RegionOutOfBounds`](crate::core::node::NodeBuildError::RegionOutOfBounds)).
    pub fn argument_content_as_plain_chars(
        &self,
        argument: &ParsedArgument<L>,
        children: &[BuildId],
    ) -> Result<Option<String>, PlainCharsError> {
        let Some((region_nodes, content)) = self.argument_designation(argument, children)? else {
            return Ok(None);
        };
        self.content_as_plain_chars(region_nodes, content).map(Some)
    }

    /// The shared first step of the two argument-side readers: the argument's region
    /// nodes and its content designation, or `None` for an argument that was not
    /// provided.
    fn argument_designation<'c>(
        &self,
        argument: &'c ParsedArgument<L>,
        children: &'c [BuildId],
    ) -> Result<Option<(&'c [BuildId], &'c ContentNodes)>, NodeBuildError> {
        let Some(region) = argument.region.as_ref() else {
            return Ok(None);
        };
        // At parse time a region is staged by construction: `finish` has not run.
        let Some((offsets, content)) = region.staged() else {
            return Err(NodeBuildError::RegionAlreadyResolved);
        };
        let region_nodes = children
            .get(offsets.start as usize..offsets.end as usize)
            .ok_or_else(|| NodeBuildError::RegionOutOfBounds {
                region: offsets.clone(),
                n_children: children.len() as u32,
            })?;
        Ok(Some((region_nodes, content)))
    }

    /// The shared second step of the content readers: the staged ids a designation
    /// names, plus the staged view of the content parent for an `InChildrenOf` one.
    fn resolve_content_nodes<'c>(
        &'c self,
        region_nodes: &'c [BuildId],
        content: &ContentNodes,
    ) -> Result<(&'c [BuildId], Option<StagedNodeView<'c, L>>), NodeBuildError> {
        match content {
            ContentNodes::InRegion(range) => {
                let nodes = region_nodes
                    .get(range.start as usize..range.end as usize)
                    .ok_or_else(|| NodeBuildError::ContentOutOfBounds {
                        content: range.clone(),
                        available: region_nodes.len() as u32,
                    })?;
                Ok((nodes, None))
            }
            ContentNodes::InChildrenOf(parent, range) => {
                let view = self
                    .staged_nodes()
                    .get(*parent)
                    .ok_or(NodeBuildError::ContentParentNotStaged { parent: *parent })?;
                let nodes = view
                    .children()
                    .get(range.start as usize..range.end as usize)
                    .ok_or_else(|| NodeBuildError::ContentOutOfBounds {
                        content: range.clone(),
                        available: view.children().len() as u32,
                    })?;
                Ok((nodes, Some(view)))
            }
        }
    }

    /// The span and parsing state of the `List` root
    /// [`content_as_tree`](ParseContext::content_as_tree) synthesizes — the rule its
    /// documentation states.
    // The pair is exactly what `add()` wants next; naming it would not read better.
    #[allow(clippy::type_complexity)]
    fn content_root_provenance(
        &self,
        nodes: &[BuildId],
        parent: Option<StagedNodeView<'_, L>>,
    ) -> Result<(SourceSpan<L::SourceOrigin>, Arc<ParsingState<L>>), NodeBuildError> {
        let staged = self.staged_nodes();
        match (nodes.first(), nodes.last()) {
            (Some(first), Some(last)) => {
                let first =
                    staged.get(*first).ok_or(NodeBuildError::ChildNotStaged { child: *first })?;
                let last =
                    staged.get(*last).ok_or(NodeBuildError::ChildNotStaged { child: *last })?;
                let (from, to) = (first.span(), last.span());
                let span = if from.same_source(to)
                    && from.start() <= to.start()
                    && from.end() <= to.end()
                {
                    SourceSpan::new(from.source(), from.start()..to.end())
                } else {
                    // No one forward range covers the content: the parent's span says
                    // where it sits, and without a parent the first node's own span is
                    // the nearest true statement.
                    match parent {
                        Some(parent) => parent.span().clone(),
                        None => from.clone(),
                    }
                };
                Ok((span, first.parsing_state().clone()))
            }
            _ => match parent {
                Some(parent) => Ok((parent.span().clone(), parent.parsing_state().clone())),
                None => Ok((self.here(), Arc::clone(&self.state))),
            },
        }
    }

    /// Stages the `Callable` node of a resolved invocation and returns its
    /// [`BuildId`](crate::core::node::BuildId).
    ///
    /// A shorthand over [`stage_node`](ParseContext::stage_node) for the common case
    /// where the node simply records what the invocation resolved to: it builds the
    /// [`CallableData`] by copying `callable_type`, `name` and `spec` out of the
    /// bundle, creates the invocation-syntax payload from it ([`FromInvocation`]),
    /// computes the node's span, and stages the node. This is what
    /// [`StdInvocationParser`] does, packaged for parsers that take over an
    /// invocation of the same macro shape.
    ///
    /// `arguments`/`slots` are **caller-tiled** records in staged child-list
    /// coordinates, and `children` the flat child list they tile — the natural
    /// output of the argument loop
    /// ([`parse_declared_arguments`]). The parse-side/restage-side symmetry with
    /// `restage_invocation` is by shared *vocabulary*, deliberately not shared
    /// arity: the restage side passes driver-tiled bundles because the region
    /// arithmetic is owned by the other party there.
    ///
    /// The node's span starts where the trigger starts; where it ends is
    /// decided by `end`, in three cases:
    ///
    /// - `Some(end)`: at that stream position — for takeovers whose consumed extent
    ///   outruns their last child (rest-of-line and heredoc shapes).
    /// - `None` with a last staged child whose span is in the trigger's source: at
    ///   that child's span end (the **standard rule**).
    /// - `None` otherwise (no child, or a child staged in another source): at the
    ///   reader's current stream position — which, for a childless invocation staged
    ///   in the ordinary flow, is just past the trigger's own post-space.
    ///
    /// For a language with
    /// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false` the last
    /// two cases are one: a staged child's span end says nothing about where the
    /// trigger's own source stands, so the node's span is always the one the reader
    /// describes for the stretch from the trigger's start to where the stream now
    /// stands — just past the last child in the ordinary flow.
    ///
    /// Deliberately **no `callable_type`/`name` overrides**: a composition that
    /// overrides both and whose span outruns its children (the environment shape)
    /// stays on [`stage_node`](ParseContext::stage_node) itself with
    /// an explicit [`CallableData`]. No ext/annotation parameters — staging
    /// mints the ext, and parse annotations are `()`.
    ///
    /// # Errors
    ///
    /// Returns an [`ImplementationError`] for an **invalid computed span**: under a
    /// language that obeys span tiling, a node end (from the standard rule or from
    /// `end`) that precedes the trigger's start or lies in a different source than
    /// the trigger. That is a contract violation by the calling parser; it aborts the
    /// parse under any recovery policy, and never panics. A language with
    /// `OBEYS_SPAN_TILING = false` claims nothing about the span and reports no such
    /// error.
    ///
    /// A failure of the underlying [`stage_node`](ParseContext::stage_node) is
    /// returned per that method's split: contract violations as
    /// [`ImplementationError`], the extension mint's own reported failure as
    /// [`HookFailed`](crate::error::HookFailed). Both abort under any recovery
    /// policy.
    pub fn stage_invocation(
        &mut self,
        invocation: &Invocation<'_, L>,
        arguments: ParsedArguments<L>,
        slots: ParsedSlots<L>,
        children: Vec<BuildId>,
        end: Option<&StreamPosition<L>>,
    ) -> ConstructParserResult<L, BuildId>
    where
        L::InvocationSyntax: FromInvocation<L>,
    {
        let token = invocation.token;
        let trigger = self.tokens.source_span_of(token);
        let trigger_start = self.tokens.position_at(token, TokenEdge::Start);
        let span = match end {
            // The explicit end: the takeover claims its consumed extent.
            Some(end) => self.invocation_span_within(&trigger, &trigger_start, end)?,
            // The standard rule needs a byte comparison between a child's span and
            // the trigger's, which presupposes span tiling. Where the language does
            // not declare it, no assumption is made about the children at all: the
            // only position this method holds that means "past the last child" is the
            // one the reader stands at (children are staged nodes — spans, not stream
            // positions), so the span is what the reader describes for the stretch
            // from the trigger's start to there.
            None if !L::OBEYS_SPAN_TILING => {
                let here = self.tokens.position_here();
                self.invocation_span_within(&trigger, &trigger_start, &here)?
            }
            None => {
                // The standard rule: the last staged child's span end, in the
                // trigger's own source. A last child no parser ever staged (an
                // implementation bug) falls through as if there were none — the
                // builder diagnoses the foreign id in `add`.
                let child_end = children
                    .last()
                    .and_then(|last| self.staged_nodes().get(*last))
                    .map(|child| child.span().clone())
                    .filter(|child| child.same_source(&trigger))
                    .map(|child| child.end());
                match child_end {
                    Some(child_end) => {
                        // A child ending before the trigger starts is a contract
                        // violation by outer code — the implementation-error abort,
                        // never a panic (`SourceSpan::new` would otherwise assert).
                        if child_end < trigger.start() {
                            return Err(self.invalid_invocation_span(&trigger));
                        }
                        SourceSpan::new(trigger.source(), trigger.start()..child_end)
                    }
                    // No usable child: the node ends where the reader stands.
                    None => {
                        let here = self.tokens.position_here();
                        self.invocation_span_within(&trigger, &trigger_start, &here)?
                    }
                }
            }
        };
        let data = CallableData {
            callable_type: invocation.callable_type,
            name: invocation.name.into(),
            spec: Arc::clone(invocation.spec),
            arguments,
            slots,
            invocation_syntax: L::InvocationSyntax::from_invocation(invocation, &*self.tokens),
        };
        self.stage_node(
            NodeKind::callable(data),
            span.clone(),
            Arc::clone(&self.state),
            children,
        )
        .map_err(|error| self.staging_error(error, span))
    }

    /// [`stage_invocation`](ParseContext::stage_invocation)'s span computation from
    /// two stream positions, with the invalid-span wording (and anchor) of that
    /// method.
    ///
    /// Dispatches on [`Lang::OBEYS_SPAN_TILING`] exactly like
    /// [`source_span_within`](ParseContext::source_span_within): the delimited range
    /// under `true`, the reader's described span (never an error) under `false`.
    fn invocation_span_within(
        &self,
        trigger: &SourceSpan<L::SourceOrigin>,
        begin: &StreamPosition<L>,
        end: &StreamPosition<L>,
    ) -> ConstructParserResult<L, SourceSpan<L::SourceOrigin>> {
        if !L::OBEYS_SPAN_TILING {
            return Ok(self.tokens.source_span_describing(begin, end));
        }
        match self.tokens.source_span_within(begin, end) {
            Some(span) => Ok(span),
            None => Err(self.invalid_invocation_span(trigger)),
        }
    }

    /// The invalid-computed-span abort of
    /// [`stage_invocation`](ParseContext::stage_invocation), anchored at the
    /// trigger — the construct whose staging failed, and the location a reader of
    /// the report can act on.
    fn invalid_invocation_span(
        &self,
        trigger: &SourceSpan<L::SourceOrigin>,
    ) -> ParseError<L::SourceOrigin> {
        self.implementation_error(
            "stage_invocation computed an invalid node span: the node's end must \
             not precede the trigger's start and must lie in the trigger's own \
             source — check the explicit end position or the staged children's \
             spans",
            trigger.clone(),
        )
    }

    /// Peeks at the token at the current position under `state`, mapping a tokenizer
    /// error per the recovery policy.
    ///
    /// This is the peek an argument parser probes a position with: strict mode aborts
    /// with the token error (mirroring the content loop); tolerant
    /// mode reports `None` **without diagnosing or consuming** — the caller treats the
    /// position as unusable (argument absent, terminator malformed) and the enclosing
    /// content loop re-reads the error and applies its own token recovery, avoiding a
    /// double report.
    ///
    /// A token error carrying **no** recovery is unrecoverable and aborts even under
    /// [`Recovery::Tolerant`](crate::error::Recovery::Tolerant) — mirroring the content loop, whose re-read would abort
    /// anyway; reporting `None` first would only add a spurious absent-position recovery
    /// (and its diagnostic) on the way down.
    ///
    /// `state` is passed explicitly (usually `&Arc::clone(&cx.state)`; peeking never
    /// consumes) so a parser can probe under a derived state — an optional-argument
    /// parser peeking with its minted group rule in force — without swapping
    /// [`state`](ParseContext::state).
    ///
    /// Shorthand for [`ParseDriver::probe_token`], where the policy is defined.
    pub fn probe_token(
        &mut self,
        state: &Arc<ParsingState<L>>,
    ) -> ConstructParserResult<L, Option<Token<L>>> {
        self.driver.probe_token(self.tokens, self.session, state)
    }

    /// Runs `parser` as one sub-parse of the construct being parsed, and returns its
    /// output and after-effect delta.
    ///
    /// This is the single entry point every descent (a construct parser running
    /// another [`ConstructParser`] over the same input) MUST go through — the
    /// counterpart of pylatexenc's `walker.parse_content(parser, …, parsing_state)`.
    ///
    /// The contract is **normative**: every descent — a parser running another
    /// parser for a construct *nested* inside its own — goes through this method,
    /// either called directly or through the thin wrappers
    /// [`parse_nodes`](ParseContext::parse_nodes) and
    /// [`parse_group`](ParseContext::parse_group), which delegate here. One shared
    /// entry point is what lets the engine attach its per-descent bookkeeping (the
    /// enclosing-state stack, the optional traceback frame, the
    /// [`DescentGuard`](crate::core::DescentGuard) depth check) uniformly, with
    /// no per-site cooperation. The contract's limit: plain Rust recursion that
    /// bypasses it — code calling another parser's
    /// [`parse`](ConstructParser::parse) method directly — cannot be detected by
    /// the library. The rule is documented, not enforceable.
    ///
    /// Two runs are deliberately **not** descents and call
    /// [`parse`](ConstructParser::parse) directly instead: the parse entry point
    /// running the root parser (see [`RootNodesParser`]), and a parser that
    /// delegates to an inner parser for the *same* construct — a wrapper adding an
    /// after-effect delta around [`StdInvocationParser`], say — which must not open
    /// a second nesting level or push a second frame for one construct.
    ///
    /// Before the sub-parse runs, the session's per-parse
    /// [`DescentGuard`](crate::core::DescentGuard) is asked whether the parse
    /// may go one level deeper: a warning answer is recorded as a
    /// [`DescentLimitApproaching`] diagnostic and the parse continues; a refusal
    /// aborts with a [`DescentLimitExceeded`] error under **any** recovery policy
    /// (past the limit there is no safe way to continue).
    ///
    /// `state` is the sub-parse's input state, scoped structurally for the duration
    /// of the run — swapped in, restored afterwards, with the session's
    /// enclosing-state stack maintained alongside (the
    /// [`with_parsing_state`](ParseContext::with_parsing_state) discipline):
    ///
    /// - `Some(state)`: the sub-parse runs under `state`.
    /// - `None`: the sub-parse runs under the **current** state — exactly as if
    ///   `Some(Arc::clone(&cx.state))` had been passed: the same swap/restore
    ///   scoping runs and the same enclosing-state stack entry is pushed. `None`
    ///   never means "skip the scoping".
    ///
    /// `frame`, when `Some`, is pushed on the session's live frame stack around the
    /// whole sub-parse (the [`with_frame`](ParseContext::with_frame) discipline):
    /// every condition recorded while `parser` runs carries the frame in its
    /// traceback snapshot. The frame is popped before this method returns, on the
    /// `Ok` and `Err` paths alike (errors are values, not unwinds).
    ///
    /// The returned [`ParsingStateDelta`] is the construct's after-effect for the
    /// caller, passed through **unapplied** — whether and where it applies is
    /// caller business (the "caller applies deltas" law).
    // The return type is the `ConstructParser::parse` shape spelled out; an alias for
    // it would add a second public name for one method's tuple.
    #[allow(clippy::type_complexity)]
    pub fn parse_construct<P>(
        &mut self,
        parser: &mut P,
        state: Option<Arc<ParsingState<L>>>,
        frame: Option<Frame<L>>,
    ) -> ConstructParserResult<L, (P::Output, Option<Box<ParsingStateDelta<L>>>)>
    where
        P: ConstructParser<L> + ?Sized,
    {
        // `None` = the current state; the scoping below runs identically either way.
        let state = match state {
            Some(state) => state,
            None => Arc::clone(&self.state),
        };
        let framed = frame.is_some();
        if let Some(frame) = frame {
            self.session.push_frame(frame);
        }
        // The descent guard: ask the session's per-parse guard whether one more
        // level may open. A refusal aborts under ANY recovery policy — past the
        // limit there is no safe way to continue — with the just-pushed frame in
        // the error's traceback, and popped again before returning.
        match self.session.enter_descent() {
            Ok(None) => {}
            Ok(Some(warning)) => {
                // The guard's early warning (the standard guard's one-time
                // half-budget notice under the unconfigured default): recorded
                // immediately, at the current position, with the live traceback.
                let span = self.here();
                let frames = self.session.snapshot_frames();
                self.session.diagnostics.push(Diagnostic::from_parts(
                    Severity::Warning,
                    Box::new(DescentLimitApproaching::new(warning.detail)),
                    span,
                    frames,
                ));
            }
            Err(refusal) => {
                let error = ParseError::new(
                    DescentLimitExceeded::new(refusal.detail),
                    self.here(),
                )
                .with_frames(self.session.snapshot_frames());
                if framed {
                    self.session.pop_frame();
                }
                return Err(error);
            }
        }
        let result = self.with_parsing_state(state, |cx| parser.parse(cx));
        // The guard exit runs on the `Ok` and `Err` result paths alike — errors
        // are values, not unwinds — and only for a granted entry (a refusal
        // returned above, before any descent opened).
        self.session.exit_descent();
        // The pop covers the `Err` path too — errors are values, not unwinds.
        if framed {
            self.session.pop_frame();
        }
        result
    }

    /// Runs `f` with [`state`](ParseContext::state) set to `state`, restoring the
    /// outer state afterwards.
    ///
    /// This is the state scoping that [`parse_construct`](ParseContext::parse_construct)
    /// performs, exposed for scopes that are not `ConstructParser`-shaped: the
    /// per-argument delta around `ArgumentParser::parse_argument`, or a takeover
    /// parser scoping a state it derived itself around arbitrary code.
    ///
    /// This is a **state-scoping utility, not a descent entry point**: code that
    /// runs another [`ConstructParser`] must go through
    /// [`parse_construct`](ParseContext::parse_construct) (which performs this
    /// scoping itself, plus its per-descent obligations), never through this
    /// method alone.
    ///
    /// Besides the structural swap/restore, this maintains the session's
    /// **enclosing-state stack** ([`ParsingStateStack`](crate::core::ParsingStateStack)):
    /// `state` is pushed for the duration of `f` and popped after — the same
    /// closure-scoped discipline as [`with_frame`](ParseContext::with_frame), at
    /// the same descent points. Prefer this over hand-rolled `cx.state` swaps: a
    /// manual swap leaves the stack (and therefore context-dependent event
    /// lowering, [`derive_state`](ParseContext::derive_state)) blind to the scope.
    pub fn with_parsing_state<R>(
        &mut self,
        state: Arc<ParsingState<L>>,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        self.session.push_state(Arc::clone(&state));
        let outer = core::mem::replace(&mut self.state, state);
        let result = f(self);
        self.state = outer;
        self.session.pop_state();
        result
    }

    /// Reports a problem detected in the source and applies the driver's recovery
    /// policy.
    ///
    /// This is **the recovery entry point**: every problem a construct parser finds
    /// in the source is reported through this one method, at the point of detection.
    /// It boxes the condition and passes it to [`ParseDriver::recover`], where the
    /// policy is defined — the default driver path applies
    /// [`refine_diagnostic`](ParseDriver::refine_diagnostic) exactly once (it needs
    /// this context's parsing state) and then records the condition as an
    /// error-severity diagnostic and returns `Ok(())` (tolerant — the caller continues
    /// with its local recovery) or returns it as a [`ParseError`] to bubble (strict).
    pub fn recover(
        &mut self,
        condition: impl DiagnosticInfo,
        span: SourceSpan<L::SourceOrigin>,
    ) -> Result<(), ParseError<L::SourceOrigin>> {
        self.recover_boxed(Box::new(condition), span)
    }

    /// Attaches the live traceback to an abort error returned by a hook, when the
    /// error has no frames of its own; an error that already has frames is returned
    /// unchanged.
    ///
    /// Extension hooks (driver hooks, spec factories, descent-state callbacks) have
    /// no access to the session, so the site that called the hook is the only place
    /// where a traceback snapshot can be taken.
    ///
    /// The in-crate dispatch sites use this on every fallible hook they consult; a
    /// construct parser that consults such a hook itself
    /// ([`ParseDriver::make_nodes_parser`](crate::core::ParseDriver::make_nodes_parser),
    /// [`CallableSpec::make_invocation_parser`](crate::core::specs::CallableSpec::make_invocation_parser),
    /// …) does the same at its own dispatch site:
    /// `.map_err(|error| cx.attach_hook_frames(error))`. Only the frames are
    /// touched: the error's condition and span are the hook's own.
    pub fn attach_hook_frames(
        &self,
        error: ParseError<L::SourceOrigin>,
    ) -> ParseError<L::SourceOrigin> {
        if error.frames().is_empty() {
            error.with_frames(self.session.snapshot_frames())
        } else {
            error
        }
    }

    /// The recovery entry point's boxed form, for payloads that are already boxed as
    /// `dyn DiagnosticData` (the token-error lift, where a `Custom` payload must not be
    /// double-boxed).
    pub(crate) fn recover_boxed(
        &mut self,
        data: Box<dyn DiagnosticData>,
        span: SourceSpan<L::SourceOrigin>,
    ) -> Result<(), ParseError<L::SourceOrigin>> {
        self.driver.recover(self.session, &self.state, data, span)
    }

    /// Derives a new parsing state by applying `delta` to the **current** state
    /// ([`state`](ParseContext::state)).
    ///
    /// This is the derivation point every construct parser goes through: it lowers
    /// **context-dependent events**, then runs the session-mediated derivation
    /// ([`ParserSession::derived_state`] with this context's driver), so every
    /// transition reaches
    /// [`ParseDriver::observe_transition`]. Deriving from another base goes through
    /// the session method directly
    /// (`cx.session.derived_state(cx.driver, &base, &delta)`) — with no event
    /// lowering: context-dependent events are positional, they mean something only
    /// at *this* context's position.
    ///
    /// # Event lowering
    ///
    /// When the delta carries [`events`](crate::core::ParsingStateDelta::events),
    /// each is offered to [`ParseDriver::resolve_state_event`] with the session's
    /// live enclosing-state stack (current state first —
    /// [`ParsingStateStack`](crate::core::ParsingStateStack)). Lowered events are
    /// **removed** and their patches merged; unlowered (context-free) events stay
    /// for [`Lang::finalize_transition`](crate::core::Lang::finalize_transition).
    /// This method runs the event loop; construct parsers never iterate events
    /// themselves, and the per-event *policy* is the driver's. Merge order:
    /// patches apply in event order,
    /// and the delta's own explicit overrides win over patch overrides (the delta
    /// author spoke).
    ///
    /// # Failures
    ///
    /// **Failing scope ops** are reported through the recovery entry point as
    /// [`ScopeOpFailed`] conditions at the current position: under
    /// [`Recovery::Strict`](crate::error::Recovery::Strict) the first failure aborts;
    /// under [`Recovery::Tolerant`](crate::error::Recovery::Tolerant) each failure is
    /// recorded and the parse continues under the error's
    /// [`recovered`](crate::core::DeriveError::recovered) state (the failing ops
    /// skipped, everything else applied), with the transition observed as usual.
    /// A **finalize refusal** ([`FinalizeError`](crate::core::FinalizeError) — a
    /// context-requiring event the driver did not lower) is an extension wiring
    /// bug, not a source condition: it aborts as an
    /// [`ImplementationError`] under any recovery policy. An `Err` from the
    /// lowering hook itself
    /// ([`ParseDriver::resolve_state_event`]'s abort channel) propagates
    /// unchanged, aborting under any recovery policy.
    pub fn derive_state(
        &mut self,
        delta: &ParsingStateDelta<L>,
    ) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
        let base = Arc::clone(&self.state);
        let effective;
        let delta = if delta.events.is_empty() {
            delta
        } else {
            effective = self.lower_state_events(delta)?;
            &effective
        };
        self.commit_derivation(&base, delta)
    }

    /// [`derive_state`](ParseContext::derive_state) with the **effective, as-applied
    /// delta recorded**: after the transition commits (cleanly or through the
    /// tolerant ops-skipped recovery), the delta actually handed to the derivation —
    /// context-dependent events already lowered into their override patches — is
    /// merged into `record` ([`ParsingStateDelta::merge_from`]: later field
    /// overrides win, scope ops and events concatenate in application order). This
    /// is where the merged after-effect record
    /// ([`NodesOutcome::after_effects`]) is captured.
    ///
    /// Recording the *effective* delta is essential: context-dependent events
    /// are positional (they mean something only at this context's position), so a
    /// record replayed elsewhere must carry their lowered patches, never the raw
    /// events. Context-free events that survive lowering are recorded as-is — by
    /// the [`Lang::Event`](crate::core::Lang::Event) contract they are consumed
    /// wherever the delta is applied, so they replay exactly. On the tolerant
    /// ops-skipped path the record keeps the delta **as applied** (the
    /// [`DeriveError::delta`](crate::core::DeriveError::delta) notion), failing
    /// ops included: a replay elsewhere re-attempts them and may re-diagnose.
    pub(crate) fn derive_state_recording(
        &mut self,
        delta: &ParsingStateDelta<L>,
        record: &mut Option<Box<ParsingStateDelta<L>>>,
    ) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
        let base = Arc::clone(&self.state);
        let effective;
        let applied = if delta.events.is_empty() {
            delta
        } else {
            effective = self.lower_state_events(delta)?;
            &effective
        };
        let new = self.commit_derivation(&base, applied)?;
        match record {
            Some(record) => record.merge_from(applied.clone()),
            None => *record = Some(Box::new(applied.clone())),
        }
        Ok(new)
    }

    /// The shared commit tail of the derivation seams: run the session-mediated
    /// derivation (so the transition reaches
    /// [`ParseDriver::observe_transition`]) and route derivation failures through
    /// [`recover_derive_failure`](ParseContext::recover_derive_failure). An
    /// observation abort ([`SessionDeriveError::Observe`] —
    /// [`ParseDriver::observe_transition`]'s `Err`) propagates unchanged under
    /// any recovery policy, with the live traceback attached here.
    fn commit_derivation(
        &mut self,
        base: &Arc<ParsingState<L>>,
        applied: &ParsingStateDelta<L>,
    ) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
        match self.session.derived_state(self.driver, base, applied) {
            Ok(new) => Ok(new),
            Err(SessionDeriveError::Derive(failure)) => {
                self.recover_derive_failure(base, failure)
            }
            Err(SessionDeriveError::Observe(error)) => Err(self.attach_hook_frames(error)),
        }
    }

    /// Derive via [`derive_state`](ParseContext::derive_state), then run `f` with
    /// [`state`](ParseContext::state) scoped to the derived state
    /// ([`with_parsing_state`](ParseContext::with_parsing_state)) — the
    /// delta-shaped state scope in one call, for takeover parsers.
    ///
    /// Like `with_parsing_state`, this is a state-scoping utility, **not** a
    /// descent entry point: running another [`ConstructParser`] under the derived
    /// state goes through [`parse_construct`](ParseContext::parse_construct)
    /// instead.
    pub fn with_derived_state<R>(
        &mut self,
        delta: &ParsingStateDelta<L>,
        f: impl FnOnce(&mut Self) -> R,
    ) -> ConstructParserResult<L, R> {
        let state = self.derive_state(delta)?;
        Ok(self.with_parsing_state(state, f))
    }

    /// The event loop of [`derive_state`](ParseContext::derive_state): offer each
    /// event to the driver with the live enclosing-state stack lent **current
    /// state first** (the context's current state is pushed for the lend when it
    /// is not already the innermost entry — sibling after-effects evolve
    /// `cx.state` between descents; an `Arc`-equal duplicate is harmless under
    /// the stack's scan semantics), and build the effective delta: patches merged
    /// in event order, the original delta's explicit overrides on top, lowered
    /// events removed. A hook `Err` aborts ([`ParseDriver::resolve_state_event`]'s
    /// contract), with the lent stack entry popped and the live traceback
    /// attached.
    fn lower_state_events(
        &mut self,
        delta: &ParsingStateDelta<L>,
    ) -> ConstructParserResult<L, ParsingStateDelta<L>> {
        let lent = match self.session.state_stack().innermost() {
            Some(innermost) => !Arc::ptr_eq(innermost, &self.state),
            None => true,
        };
        if lent {
            self.session.push_state(Arc::clone(&self.state));
        }
        let mut patches: Vec<ParsingStateDelta<L>> = Vec::new();
        let mut kept_events: Vec<L::Event> = Vec::new();
        let mut abort: Option<ParseError<L::SourceOrigin>> = None;
        for event in &delta.events {
            match self.driver.resolve_state_event(event, self.session.state_stack()) {
                Ok(Some(patch)) => patches.push(patch),
                Ok(None) => kept_events.push(event.clone()),
                Err(error) => {
                    // Break, don't return: the lent stack entry pops on the
                    // abort path too.
                    abort = Some(error);
                    break;
                }
            }
        }
        if lent {
            self.session.pop_state();
        }
        if let Some(error) = abort {
            return Err(self.attach_hook_frames(error));
        }

        // Merge: patches in event order (later wins), then the original delta's own
        // explicit overrides on top of all patches (the delta author spoke).
        let mut effective = ParsingStateDelta::new();
        for patch in patches {
            effective.rules.merge_from(patch.rules);
            // Matched store projections: with the scopes feature absent, neither
            // side's zero-sized scope-op store holds anything to concatenate.
            if let (Some(ops), Some(patch_ops)) = (
                <L::Features as LangFeatures>::Scopes::store_get_mut(&mut effective.scope_ops),
                <L::Features as LangFeatures>::Scopes::store_into_inner(patch.scope_ops),
            ) {
                ops.extend(patch_ops);
            }
            if patch.mode.is_some() {
                effective.mode = patch.mode;
            }
            if patch.ext.is_some() {
                effective.ext = patch.ext;
            }
            // Patch events are context-free by contract (resolve_state_event docs):
            // they pass through to finalize_transition un-lowered.
            effective.events.extend(patch.events);
        }
        effective.rules.merge_from(delta.rules.clone());
        if let (Some(ops), Some(delta_ops)) = (
            <L::Features as LangFeatures>::Scopes::store_get_mut(&mut effective.scope_ops),
            <L::Features as LangFeatures>::Scopes::store_get(&delta.scope_ops),
        ) {
            ops.extend(delta_ops.iter().cloned());
        }
        if delta.mode.is_some() {
            effective.mode = delta.mode;
        }
        if delta.ext.is_some() {
            effective.ext = delta.ext.clone();
        }
        effective.events.extend(kept_events);
        Ok(effective)
    }

    /// Derives the state a group's interior is parsed under, from the **current**
    /// state — [`ParserSession::group_interior_state`] with this context's driver
    /// supplied: the canonical expecting-close override merged with the driver's
    /// [`group_interior_delta`](ParseDriver::group_interior_delta), memoized per
    /// `(base, rule)`. Failing scope ops in the driver's descent delta recover exactly
    /// like [`derive_state`](ParseContext::derive_state)'s (the recovered interior
    /// still expects the entered rule's close — the descent invariant is an override,
    /// not an op).
    pub fn group_interior_state(
        &mut self,
        rule: &Arc<GroupRule<L>>,
    ) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
        let base = Arc::clone(&self.state);
        match self.session.group_interior_state(self.driver, &base, rule) {
            Ok(new) => Ok(new),
            Err(SessionDeriveError::Derive(failure)) => {
                self.recover_derive_failure(&base, failure)
            }
            Err(SessionDeriveError::Observe(error)) => Err(self.attach_hook_frames(error)),
        }
    }

    /// The shared recovery path of the two fallible derivation methods: report every
    /// failing op through the recovery entry point (strict: the first one aborts); a
    /// finalize refusal aborts as an [`ImplementationError`] under any policy (a
    /// context-requiring event reached the underlying derivation point un-lowered —
    /// the driver failed to lower it: extension wiring, not source input). Otherwise commit
    /// the ops-skipped transition — continue under the error's recovered state
    /// and observe it with the delta the derivation actually applied (which the
    /// error carries: for group interiors that is the *merged* descent delta this
    /// context never built).
    fn recover_derive_failure(
        &mut self,
        base: &Arc<ParsingState<L>>,
        failure: crate::state::DeriveError<L>,
    ) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
        let span = self.here();
        let crate::state::DeriveError {
            failures,
            finalize_error,
            recovered,
            delta,
        } = failure;
        for failed_op in &failures {
            self.recover(ScopeOpFailed::new(failed_op.to_string()), span.clone())?;
        }
        if let Some(finalize_error) = finalize_error {
            return Err(self.implementation_error(finalize_error, span));
        }
        // Tolerant continuation: commit the recovered transition — the session seam
        // observed nothing on the Err path (no transition had been committed). The
        // observation hook's own abort channel applies here like everywhere else.
        let recovered = Arc::new(recovered);
        self.driver
            .observe_transition(
                &mut self.session.ext,
                &mut self.session.diagnostics,
                base,
                &recovered,
                &delta,
            )
            .map_err(|error| self.attach_hook_frames(error))?;
        Ok(recovered)
    }

    /// **A thin wrapper over [`parse_construct`](ParseContext::parse_construct)**:
    /// builds the content-loop parser from the driver's
    /// [`make_nodes_parser`](ParseDriver::make_nodes_parser) factory and runs it
    /// through `parse_construct(parser, Some(state), None)`. Fusing the factory
    /// with the descent entry point is the point of this method: routing every
    /// content descent through it makes one driver override apply at every
    /// descent site.
    ///
    /// Parses one **nodes descent** (a content run: group interior, environment
    /// body, top-level drive) under `state`. State scoping and restoration follow
    /// [`parse_construct`](ParseContext::parse_construct).
    ///
    /// # Resuming a stopped run
    ///
    /// A run that stops before end of input — a token condition, an unexpected group
    /// close ([`StopCause`]) — can be **resumed**: handle the stop (diagnose, consume
    /// or skip the offending token), then call `parse_nodes` again. There is no resume
    /// method on [`NodesParser`]; resumption is *re-invocation* — each call builds a
    /// fresh parser from the factory with its own per-run `stop`/`child_states` — and
    /// the caller bridges the runs. The canonical bridge is the root parser
    /// ([`RootNodesParser`]), which diagnoses a stray group close, skips it, and
    /// re-enters. The bridge has three
    /// obligations:
    ///
    /// - **Resume under [`NodesOutcome::state`], never under this context's restored
    ///   `state`.** The descent restores [`state`](ParseContext::state) structurally on
    ///   return ([`parse_construct`](ParseContext::parse_construct)), and the run's sibling
    ///   after-effects (a `\newcommand`-style definition) are applied *internally*, not
    ///   returned as a pass-through delta — so after the call, the outcome's exported
    ///   live state is their only carrier. Re-entering with a clone of `cx.state`
    ///   silently rolls them back. A caller that re-anchors its ambient state first
    ///   (the root loop's `cx.state = outcome.state`) makes the two coincide.
    ///
    /// - **Stand the reader where the next run should start.** The stop contract is
    ///   defined ([`TokenStopCondition::consume`], [`StopCause`]'s per-variant docs): a
    ///   left stop token sits at its own start, pre-space already staged, and
    ///   re-peeks clean — but re-entering with the reader still on it and the same
    ///   stop condition stops again immediately, staging nothing: an infinite loop for
    ///   an unconditional resumer. Deal with the token first — consume it
    ///   ([`probe_token`](ParseContext::probe_token) +
    ///   [`move_to`](crate::core::token::TokenReader::move_to), the environment
    ///   terminator flow), skip it
    ///   ([`move_to_position`](crate::core::token::TokenReader::move_to_position) with the
    ///   stop cause's `after` position, the root loop), or exclude it from the next
    ///   run's stop spec.
    ///
    /// - **Concatenate the segments yourself.** Each run returns its own
    ///   [`NodesOutcome::nodes`]; the resuming caller extends one list across runs.
    ///   Bytes skipped *between* segments then belong to no node — either accept the
    ///   diagnosed byte-accounting break (the root loop's stray-close precedent) or
    ///   stage a span-backed chars fallback over them (the unresolvable-command
    ///   precedent, [`UnresolvableCommand`]) so the siblings keep tiling the parsed
    ///   extent. And a node stop condition counts each run's own siblings — its count
    ///   argument restarts at zero in a resumed segment. A bridge that *propagates*
    ///   the runs' state effects likewise merges each run's
    ///   [`NodesOutcome::after_effects`] into one record in run order (the
    ///   precedent of
    ///   [`parse_attached_source`](ParseContext::parse_attached_source)).
    ///
    /// Whether to resume at all is a per-construct policy question, not a default:
    /// the environment body deliberately **unwinds** on a terminator mismatch instead
    /// of resuming — a body that diagnosed `\end{A}` and kept going inside
    /// `\begin{A}…\begin{B}…\end{A}` would consume the enclosing environment's
    /// terminator (see [`EnvironmentBodyParser`]).
    // The output-plus-delta pair is the decided ConstructParser signature ([§dd-dr:parsers-engine]).
    #[allow(clippy::type_complexity)]
    pub fn parse_nodes<'p>(
        &mut self,
        state: Arc<ParsingState<L>>,
        stop: StopSpec<'p, L>,
        child_states: ChildStateSpec<'p, L>,
    ) -> ConstructParserResult<L, (NodesOutcome<L>, Option<Box<ParsingStateDelta<L>>>)>
    where
        'a: 'p,
        L::InvocationSyntax: FromInvocation<L>,
    {
        let driver = self.driver;
        // A factory Err aborts under any policy ("could not build the parser" —
        // the hook fallibility contract), with the live traceback attached here.
        let mut parser = driver
            .make_nodes_parser(stop, child_states)
            .map_err(|error| self.attach_hook_frames(error))?;
        self.parse_construct(&mut *parser, Some(state), None)
    }

    /// **A thin wrapper over [`parse_construct`](ParseContext::parse_construct)**:
    /// builds the group parser from the driver's
    /// [`make_group_parser`](ParseDriver::make_group_parser) factory and runs it
    /// through `parse_construct(parser, Some(base), frame)`. Fusing the factory
    /// with the descent entry point is the point of this method: routing every
    /// group descent through it makes one driver override apply at every group
    /// site.
    ///
    /// Parses one **group descent** (the consumed `GroupOpen` token and its resolved
    /// rule) with `base` as the group's input state. `frame`, when `Some`, is pushed
    /// around the whole descent
    /// ([`parse_construct`](ParseContext::parse_construct)'s frame semantics).
    ///
    /// The returned delta is the group's **after-effect for the caller** — `None` for the
    /// standard group, which drops its interior's state changes with the descent, and
    /// `Some` only where the language installed the leak hook
    /// ([`GroupAfterEffectsFn`], the `\gdef` shape). A caller with an after-effect channel
    /// of its own (the content loop) applies it; one without (the argument parsers) drops
    /// it.
    // Same decided pair as above.
    #[allow(clippy::type_complexity)]
    pub fn parse_group<'p>(
        &mut self,
        base: Arc<ParsingState<L>>,
        open: &Token<L>,
        rule: Arc<GroupRule<L>>,
        child_states: ChildStateSpec<'p, L>,
        frame: Option<Frame<L>>,
    ) -> ConstructParserResult<L, (BuildId, Option<Box<ParsingStateDelta<L>>>)>
    where
        'a: 'p,
        L::InvocationSyntax: FromInvocation<L>,
    {
        let driver = self.driver;
        // A factory Err aborts under any policy, as in `parse_nodes`.
        let mut parser = driver
            .make_group_parser(open, rule, child_states)
            .map_err(|error| self.attach_hook_frames(error))?;
        self.parse_construct(&mut *parser, Some(base), frame)
    }

    /// Run `f` with `frame` pushed on the session's live frame stack — the descent-point
    /// primitive of the parse traceback: every condition recorded through the
    /// recovery entry point while `f` runs carries the frame in its snapshot.
    ///
    /// Closure-scoped rather than an RAII guard, deliberately: a guard would hold
    /// `&mut self` against the parser body. The pop after `f` returns covers the `Err`
    /// path too — a bubbling [`ParseError`] leaves no stale frames behind.
    pub fn with_frame<R>(&mut self, frame: Frame<L>, f: impl FnOnce(&mut Self) -> R) -> R {
        self.session.push_frame(frame);
        let result = f(self);
        self.session.pop_frame();
        result
    }

    /// Builds the abort error for an extension-implementation contract violation
    /// detected at `span`: an [`ImplementationError`] with the live traceback
    /// attached.
    ///
    /// `detail` is typically a [`NodeBuildError`](crate::core::node::NodeBuildError) or a
    /// literal description of the contract that was violated.
    ///
    /// Deliberately **not** the recovery entry point: an implementation bug is not a source
    /// condition — it aborts even under [`Recovery::Tolerant`](crate::error::Recovery::Tolerant), and no
    /// [`ParseDriver::refine_diagnostic`] pass applies.
    pub fn implementation_error(
        &self,
        detail: impl fmt::Display,
        span: SourceSpan<L::SourceOrigin>,
    ) -> ParseError<L::SourceOrigin> {
        ParseError::new(ImplementationError::new(detail.to_string()), span)
            .with_frames(self.session.snapshot_frames())
    }

    /// Build the abort error for a failed staging call — the in-crate lift of a
    /// [`NodeBuildError`](crate::core::node::NodeBuildError) detected at `span`, applying
    /// the condition split stated on [`stage_node`](ParseContext::stage_node): the
    /// ext mint's own reported failure
    /// ([`ExtMintFailed`](crate::core::node::NodeBuildError::ExtMintFailed)) becomes a
    /// [`HookFailed`] condition carrying the mint's `detail` — an operational
    /// failure in consumer-supplied hook code, not a contract violation — and every
    /// other variant goes through
    /// [`implementation_error`](ParseContext::implementation_error). Both arms
    /// attach the live traceback and abort under any recovery policy.
    pub(crate) fn staging_error(
        &self,
        error: NodeBuildError,
        span: SourceSpan<L::SourceOrigin>,
    ) -> ParseError<L::SourceOrigin> {
        match error {
            NodeBuildError::ExtMintFailed { detail } => {
                ParseError::new(HookFailed::new(detail, None), span)
                    .with_frames(self.session.snapshot_frames())
            }
            other => self.implementation_error(other, span),
        }
    }
}

/// Why [`ParseContext::content_as_plain_chars`] and
/// [`ParseContext::argument_content_as_plain_chars`] could not answer.
///
/// The two variants are reported differently, and that is the whole point of the
/// split: [`NotPlainCharacters`](PlainCharsError::NotPlainCharacters) is something the
/// parsed document did, to diagnose through [`ParseContext::recover`], while
/// [`MalformedRecord`](PlainCharsError::MalformedRecord) is a contract violation by
/// the calling parser, to lift with [`ParseContext::implementation_error`] — it aborts
/// under any recovery policy.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PlainCharsError {
    /// The content holds a node that is anything other than characters: a group, a
    /// callable, a comment, or a nested list.
    ///
    /// Such a node carries no single text of its own, so there is nothing to read. The
    /// staged node is named so a diagnostic can be anchored at it (its span is
    /// [`StagedNodeView::span`](crate::core::node::StagedNodeView::span), through
    /// [`ParseContext::staged_nodes`]).
    NotPlainCharacters {
        /// The staged id of the offending node.
        node: BuildId,
    },
    /// A staged record did not resolve: the argument's region, its child offsets, the
    /// content designation, or a node it names.
    ///
    /// None of this depends on the parsed document — see the
    /// [`NodeBuildError`](crate::core::node::NodeBuildError) variants listed on
    /// [`ParseContext::content_as_tree`], which reports the same set.
    MalformedRecord(NodeBuildError),
}

impl From<NodeBuildError> for PlainCharsError {
    fn from(error: NodeBuildError) -> PlainCharsError {
        PlainCharsError::MalformedRecord(error)
    }
}

impl fmt::Display for PlainCharsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PlainCharsError::NotPlainCharacters { node } => {
                write!(f, "the content node {:?} is not plain characters", node)
            }
            PlainCharsError::MalformedRecord(error) => {
                write!(f, "the staged content record does not resolve: {}", error)
            }
        }
    }
}

impl core::error::Error for PlainCharsError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            PlainCharsError::NotPlainCharacters { .. } => None,
            PlainCharsError::MalformedRecord(error) => Some(error),
        }
    }
}

/// Condition: an implementation of an extension point — an argument or construct
/// parser, a [`Lang`] hook, a spec factory — violated a library contract.
///
/// An implementation bug to fix, not a source-input problem: it aborts the parse even
/// under [`Recovery::Tolerant`](crate::error::Recovery::Tolerant) (built through
/// [`ParseContext::implementation_error`], which ignores the recovery policy).
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.constructs.implementation-error",
    message = "implementation error (extension contract violation): {detail}"
)]
pub struct ImplementationError {
    /// Description of the violated contract.
    pub detail: String,
}

/// Condition: a scope op of an in-parse state delta failed.
///
/// The failure ([`ScopeOpError`](crate::core::specs::ScopeOpError)) is rendered into
/// `detail`, and the condition is reported through the recovery entry point by the
/// [`ParseContext`] derivation methods: strict parses abort on it; tolerant parses
/// record it and continue under the ops-skipped state
/// ([`DeriveError::recovered`](crate::core::DeriveError::recovered)).
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.specs.scope-op-failed",
    message = "scope op failed: {detail}"
)]
pub struct ScopeOpFailed {
    /// The rendered failure ([`ScopeOpError`](crate::core::specs::ScopeOpError)'s
    /// `Display`).
    pub detail: String,
}

/// Condition: the parse's [`DescentGuard`](crate::core::DescentGuard) refused to
/// open one more nesting level.
///
/// The input nests deeper than the configured (or built-in default) limit allows.
/// Raised by [`ParseContext::parse_construct`](ParseContext::parse_construct) and
/// **aborts under any recovery policy**: the limit exists so deeply nested input
/// cannot crash the process by stack exhaustion, and past it there is no safe way to
/// continue.
///
/// The `detail` names the limit that was hit and, when the parse ran on the
/// unconfigured built-in default, points at
/// [`Language::with_descent_guard_init`](crate::core::Language::with_descent_guard_init).
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.constructs.descent-limit-exceeded",
    message = "the input nests too deeply to parse: {detail}"
)]
pub struct DescentLimitExceeded {
    /// The guard's explanation: which limit was hit, and how to configure it.
    pub detail: String,
}

/// Condition (warning severity): the parse's
/// [`DescentGuard`](crate::core::DescentGuard) reported the nesting limit as getting
/// close.
///
/// For the standard guard ([`StdDescentGuard`](crate::core::StdDescentGuard)) that is
/// the first descent past half of the **unconfigured built-in default** stack budget,
/// reported once per parse. Recorded immediately by
/// [`ParseContext::parse_construct`](ParseContext::parse_construct); the parse
/// continues.
///
/// A configured limit never produces this warning — it exists as the early notice that
/// no limit was chosen explicitly and that the built-in default will soon refuse deeper
/// input; choose a limit with
/// [`Language::with_descent_guard_init`](crate::core::Language::with_descent_guard_init).
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.constructs.descent-limit-approaching",
    message = "the input's nesting approaches the parsing depth limit: {detail}"
)]
pub struct DescentLimitApproaching {
    /// The guard's explanation: how close the limit is, and how to configure it.
    pub detail: String,
}

impl<L: Lang> fmt::Debug for ParseContext<'_, '_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ParseContext")
            .field("at", &self.here())
            .field("state", &self.state)
            .field("session", &self.session)
            .finish()
    }
}

/// Result type of construct parsing. `Err` means abort — see the error contract
/// in [`core::constructs`](crate::core::constructs).
///
/// Parameter convention follows [`TokenResult`](crate::core::token::TokenResult) (lang first,
/// payload last). The underlying [`ParseError`] is generic over the source origin only
/// (mirroring [`Diagnostic`](crate::error::Diagnostic)); the alias derives it from `L`.
pub type ConstructParserResult<L, T> = Result<T, ParseError<<L as Lang>::SourceOrigin>>;

/// A parser for one construct: it reads tokens and stages nodes through a
/// [`ParseContext`], and returns what it staged.
///
/// This is the extension point for adding syntax to a language. Implement it to
/// parse a construct the standard parsers do not cover — a macro that takes over
/// its own invocation, a body shape of your own — and install it from the factory
/// that covers that construct:
/// [`CallableSpec::make_invocation_parser`](crate::core::specs::CallableSpec::make_invocation_parser)
/// for one callable, or the [`ParseDriver`] factories
/// ([`make_root_parser`](ParseDriver::make_root_parser),
/// [`make_nodes_parser`](ParseDriver::make_nodes_parser),
/// [`make_group_parser`](ParseDriver::make_group_parser),
/// [`make_invocation_parser`](ParseDriver::make_invocation_parser)) for every
/// construct of that shape in the language.
/// [Writing a construct parser](crate::guide::construct_parsers) works through a
/// complete example.
///
/// # What an implementation must do
///
/// Everything a parser needs is on the [`ParseContext`] it is given, and the
/// context's methods are the only supported route to each of these jobs:
///
/// - **Read tokens** through [`cx.tokens`](ParseContext::tokens), and ask that same
///   reader for every span it stages or reports — a parser never pairs a byte range
///   with a source itself.
/// - **Stage every node** through [`stage_node`](ParseContext::stage_node) (or the
///   invocation shorthand [`stage_invocation`](ParseContext::stage_invocation)).
///   There is no other route to the tree, which is what lets the engine mint each
///   node's language extension without the parser's cooperation.
/// - **Run any nested construct** through
///   [`parse_construct`](ParseContext::parse_construct) or its wrappers
///   [`parse_nodes`](ParseContext::parse_nodes) and
///   [`parse_group`](ParseContext::parse_group) — never by calling that parser's
///   [`parse`](ConstructParser::parse) directly, which would bypass the engine's
///   per-descent bookkeeping. Calling [`parse`](ConstructParser::parse) directly is
///   right in one case only: delegating to an inner parser for the **same**
///   construct, which must not open a second nesting level.
/// - **Report every problem it finds in the source** through
///   [`recover`](ParseContext::recover), at the point of detection, and continue
///   locally if it returns `Ok(())`. Report a violated library contract through
///   [`implementation_error`](ParseContext::implementation_error) instead.
///
/// An implementation is a **temporary**: it is constructed with its per-use
/// configuration where it is needed, keeps its working state in its own fields
/// ([`parse`](ConstructParser::parse) takes `&mut self`), may borrow freely, and is
/// dropped when the construct's parse ends. Never store one in a spec — specs are
/// shared across parses; see the two-tier ownership model in
/// [`core::constructs`](crate::core::constructs).
///
/// # What the engine guarantees
///
/// A parser reached through one of the factories above is run by
/// [`parse_construct`](ParseContext::parse_construct), which, around the single
/// [`parse`](ConstructParser::parse) call:
///
/// - sets [`cx.state`](ParseContext::state) to the construct's input state and
///   restores the caller's state afterwards, so a parser may derive and scope child
///   states freely without cleaning up;
/// - pushes the construct's traceback frame, if the caller supplied one, so every
///   condition recorded during the parse names the construct;
/// - checks the parse's nesting-depth limit before entering, so a parser that
///   recurses through the context cannot exhaust the stack.
///
/// The root parser is the one exception: the parse entry point calls its
/// [`parse`](ConstructParser::parse) directly, without a depth level or a frame
/// (see [`RootNodesParser`]).
pub trait ConstructParser<L: Lang> {
    /// What this parser produces on success — a staged [`BuildId`](crate::core::node::BuildId)
    /// for a parser that stages one node, a `Vec<BuildId>` for one that stages a run,
    /// a [`NodesOutcome`] for a content loop, and so on.
    type Output;

    /// Parses the construct at the context's current position, staging its nodes.
    ///
    /// Called once per run of the construct, by
    /// [`ParseContext::parse_construct`](ParseContext::parse_construct) (see the
    /// guarantees on the trait). On entry, `cx.state` is the construct's input
    /// parsing state and the reader stands at the construct's first unconsumed
    /// token: a parser dispatched on a trigger token — an invocation, a group —
    /// finds that token already consumed by the caller, post-space included.
    ///
    /// Returns the parser's [`Output`](ConstructParser::Output) together with an
    /// optional [`ParsingStateDelta`]: the construct's **after-effect for the
    /// caller** — a `\newcommand` whose definition must apply to the following
    /// siblings — and never the state the parser scoped internally. The parser does
    /// not apply it; the caller decides whether and where it applies. Return `None`
    /// when the construct has no effect beyond itself, which is the common case.
    ///
    /// # Errors
    ///
    /// An `Err` **aborts the whole parse**: nobody continues past it. Problems in
    /// the source are therefore not returned as errors — they are reported through
    /// [`recover`](ParseContext::recover) where they are detected, and it returns
    /// `Err` only when the driver's recovery policy says the parse must end (the
    /// default policy does so under
    /// [`Recovery::Strict`](crate::error::Recovery::Strict), and returns `Ok(())`
    /// under [`Recovery::Tolerant`](crate::error::Recovery::Tolerant)). Reserve a
    /// directly constructed `Err` for conditions no recovery can survive, such as a
    /// violated library contract
    /// ([`implementation_error`](ParseContext::implementation_error)).
    // The output-plus-delta pair is the decided signature (DESIGN_RATIONALE.md [§dd-dr:parsers-engine]);
    // splitting it into a named type would only rename the complexity. The delta is
    // boxed so the common `None` costs one pointer-sized return slot per recursion
    // level rather than the full delta struct.
    #[allow(clippy::type_complexity)]
    fn parse(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
    ) -> ConstructParserResult<L, (Self::Output, Option<Box<ParsingStateDelta<L>>>)>;
}

/// One resolved callable invocation, as passed to
/// [`CallableSpec::make_invocation_parser`].
///
/// The dispatch loop resolves the trigger token (through
/// [`ParseDriver::resolve_command`], or from the resolution a `Specials` token
/// already carries), builds this value, and moves it into the invocation parser the
/// spec's factory returns.
///
/// When the parser runs, the trigger token has already been **consumed whole** by the
/// dispatching arm (`move_to(token, TokenEdge::EndPastPostSpace)`, syntactic
/// post-space included) — see
/// [`StdInvocationParser`]'s documentation for the full contract.
///
/// The bundle is the **resolution result plus the token**: what the trigger *is*,
/// where it lies, and every other detail of it are reader questions — ask
/// `cx.tokens` (or, in [`FromInvocation::from_invocation`], the `tokens` parameter)
/// about [`token`](Invocation::token):
/// [`token_kind`](TokenReader::token_kind),
/// [`source_span_of`](TokenReader::source_span_of),
/// [`position_at`](TokenReader::position_at).
///
/// [`CallableSpec::make_invocation_parser`]: crate::core::specs::CallableSpec::make_invocation_parser
pub struct Invocation<'a, L: Lang> {
    /// The invocation form the trigger resolved to.
    pub callable_type: L::CallableTypeId,
    /// The trigger's invocation spelling, as written (the name the resolver matched).
    /// The *standard* parser stores an owned copy on the node; a takeover composition
    /// may store a name of its own (an environment node records the environment's
    /// name, not `begin`).
    pub name: &'a str,
    /// The behavior spec driving the parse.
    pub spec: &'a Arc<dyn CallableSpec<L>>,
    /// The token that triggered this invocation. Only a [`TokenReader`] can
    /// interpret it: pass it to `cx.tokens` to learn what the trigger is and where
    /// it is.
    pub token: &'a Token<L>,
}

impl<L: Lang> fmt::Debug for Invocation<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Invocation")
            .field("callable_type", &self.callable_type)
            .field("name", &self.name)
            .field("spec", &self.spec)
            .field("token", &self.token)
            .finish()
    }
}

/// Builds a language's invocation-syntax payload ([`Lang::InvocationSyntax`]) from
/// one resolved [`Invocation`]: the facts about how the invocation was spelled that
/// the staged node records.
///
/// Implement it on the payload type (which the core
/// [`InvocationSyntax`](crate::core::InvocationSyntax) trait already bounds) to let
/// the standard parsers stage that language's callables.
///
/// It is consulted by the **standard staging sites** —
/// [`ParseContext::stage_invocation`] (and through it
/// [`StdInvocationParser`] and the expression-position bare-callable staging) plus
/// the preset's specials sites — under a bound-where-used
/// (`where L::InvocationSyntax: FromInvocation<L>`): a standard parser's knowledge
/// about a custom payload is exactly "what the invocation bundle shows", and the
/// bound says so. The bundle carries the token that triggered the invocation, and
/// the reader arrives alongside, so the constructor can ask what was matched
/// (spelling, escape character) and where — the syntactic post-space, say.
///
/// Deliberately **separate from the required data bound**: a language whose
/// payload cannot be built from an `Invocation` alone stages its callables through
/// custom parsers (via [`stage_node`](ParseContext::stage_node)) and never
/// implements this trait — but driving the standard engine requires it (the
/// standard dispatch loop reaches [`StdInvocationParser`] through the defaulted
/// spec factory). techy implements it for `()` (records nothing), and the
/// latexlike preset for its payload enum, so `Lang`s with `InvocationSyntax = ()`
/// and latexlike-family languages satisfy the bound with no work of their own.
pub trait FromInvocation<L: Lang>: Sized {
    /// The payload recording `invocation`'s trigger spelling. Pure transcription:
    /// asks `tokens` what the token that triggered the invocation is
    /// ([`token_kind`](TokenReader::token_kind)) and where any spelling it records
    /// lies, since only the reader knows either. Performs no parsing and consumes
    /// nothing; the reader arrives as a shared borrow for the duration of the call,
    /// so the implementation cannot move the stream.
    fn from_invocation(
        invocation: &Invocation<'_, L>,
        tokens: &dyn TokenReader<'_, L>,
    ) -> Self;
}

/// The no-record payload: nothing to transcribe.
impl<L: Lang> FromInvocation<L> for () {
    fn from_invocation(_invocation: &Invocation<'_, L>, _tokens: &dyn TokenReader<'_, L>) {}
}

// `pub(crate)`: the span-tiling test language below is shared with the parser test
// modules that exercise it (only in test builds — the module is `cfg(test)`).
#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::source::{Source, Span};
    use crate::engine::StdParseDriver;
    use crate::error::Recovery;
    use crate::scopes::ScopeStack;
    use crate::state::{StateData, TrivialLang};
    use crate::token::{
        CommandRules, CommentRules, ForbiddenCharsRules, GroupRules, ParagraphRules,
        SpecialsRules, TokenListReader, TokenRules, WhitespaceRules,
    };
    use alloc::vec;

    /// The tiled counterpart of [`RelaxedStdLang`]: same associated types, the
    /// default `OBEYS_SPAN_TILING` (`true`).
    #[derive(Debug, Clone, Copy)]
    pub(crate) struct PlainLang;
    impl TrivialLang for PlainLang {}

    // `Features = AllLangFeatures` (via `TrivialLang`): the plain block literals
    // below only typecheck once the per-feature stores normalize to the blocks
    // themselves.
    pub(crate) fn min_rules<L: Lang<Features = crate::state::AllLangFeatures>>() -> TokenRules<L> {
        TokenRules {
            whitespace: WhitespaceRules { enabled: true, chars: " \t\n".into() },
            paragraphs: ParagraphRules { enabled: true },
            groups: GroupRules {
                enabled: true,
                rules: Vec::new(),
                temporary: Vec::new(),
                expecting_close: None,
            },
            commands: CommandRules { enabled: true, rules: Vec::new() },
            comments: CommentRules { enabled: true, rules: Vec::new() },
            specials: SpecialsRules { enabled: true },
            forbidden_chars: ForbiddenCharsRules { chars: "".into() },
        }
    }

    pub(crate) fn state<L>() -> Arc<ParsingState<L>>
    where
        L: Lang<Features = crate::state::AllLangFeatures, StateExt = ()>,
        L::ModeId: Default,
    {
        Arc::new(ParsingState::new(StateData {
            rules: min_rules(),
            scopes: ScopeStack::new(),
            mode: Default::default(),
            ext: (),
        }))
    }

    /// A test condition — recorded through the recovery entry point by
    /// [`RecoveringParser`].
    #[derive(Debug, Clone, PartialEq, Eq)]
    struct TestCondition;

    impl fmt::Display for TestCondition {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "test condition")
        }
    }

    impl crate::error::DiagnosticInfo for TestCondition {
        const IDENTIFIER: &'static str = "test.constructs.test-condition";
    }

    /// A probing construct parser: records the input state it ran under and the
    /// enclosing-state stack depth it saw; consumes nothing, stages nothing.
    #[derive(Default)]
    struct StackProbeParser {
        seen_state: Option<Arc<ParsingState<PlainLang>>>,
        seen_depth: Option<usize>,
    }

    impl ConstructParser<PlainLang> for StackProbeParser {
        type Output = ();

        fn parse(
            &mut self,
            cx: &mut ParseContext<'_, '_, PlainLang>,
        ) -> ConstructParserResult<PlainLang, ((), Option<Box<ParsingStateDelta<PlainLang>>>)>
        {
            self.seen_state = Some(Arc::clone(&cx.state));
            self.seen_depth = Some(cx.session.state_stack().len());
            Ok(((), None))
        }
    }

    /// A construct parser that reports one [`TestCondition`] through the recovery
    /// entry point (tolerant: records and continues; strict: aborts).
    struct RecoveringParser;

    impl ConstructParser<PlainLang> for RecoveringParser {
        type Output = ();

        fn parse(
            &mut self,
            cx: &mut ParseContext<'_, '_, PlainLang>,
        ) -> ConstructParserResult<PlainLang, ((), Option<Box<ParsingStateDelta<PlainLang>>>)>
        {
            cx.recover(TestCondition, cx.here())?;
            Ok(((), None))
        }
    }

    // --- the reader-answered spans (here / source_span_within) ----------------------

    /// A context over `content`, with a real [`StdTokenReader`] behind it.
    fn with_std_context<R>(
        content: &str,
        f: impl FnOnce(&mut ParseContext<'_, '_, PlainLang>, &Arc<Source>) -> R,
    ) -> R {
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = crate::token::StdTokenReader::new(&source);
        let mut session = ParserSession::new();
        let driver = StdParseDriver::new(Recovery::Strict, ());
        let mut cx = ParseContext::new(
            &mut reader,
            state(),
            &mut session,
            &driver);
        f(&mut cx, &source)
    }

    #[test]
    fn here_is_the_empty_span_at_the_reader_position() {
        with_std_context("abc", |cx, source| {
            let at = cx.here();
            assert_eq!(at.range(), 0..0);
            assert!(Arc::ptr_eq(at.source(), source));

            // It follows the reader.
            let token = cx.tokens.peek(&cx.state).unwrap();
            cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
            assert_eq!(cx.here().range(), 1..1);
        });
    }

    #[test]
    fn source_span_within_spans_two_positions_and_lifts_an_incoherent_pair() {
        with_std_context("abc", |cx, _source| {
            let begin = cx.tokens.position_here();
            let token = cx.tokens.peek(&cx.state).unwrap();
            let end = cx.tokens.position_at(&token, TokenEdge::EndPastPostSpace);
            assert_eq!(cx.source_span_within(&begin, &end).unwrap().range(), 0..1);

            // The reversed pair delimits nothing: an implementation error, not a
            // panic and not a source condition.
            let error = cx.source_span_within(&end, &begin).unwrap_err();
            let condition = error
                .data()
                .downcast_ref::<ImplementationError>()
                .expect("an ImplementationError condition");
            assert!(
                condition.detail.contains("do not delimit one range of one source"),
                "unexpected detail: {}",
                condition.detail
            );
        });
    }

    // --- the span-tiling declaration (Lang::OBEYS_SPAN_TILING) ----------------------

    /// A language that says nothing declares span tiling: the default is `true`, and
    /// this is checked at compile time so no parse can disagree.
    const _: () = assert!(PlainLang::OBEYS_SPAN_TILING);
    const _: () = assert!(<crate::latexlike::Latexlike as Lang>::OBEYS_SPAN_TILING);

    /// A language declaring that its parse trees are **not** span-tiled, tokenized by
    /// the standard reader. What it exercises here is the declaration itself and the
    /// [`ParseContext::source_span_within`] dispatch; how the parsers record content
    /// under the declaration is a separate concern, so the parse test below asserts
    /// structure only.
    #[derive(Debug, Clone, Copy)]
    pub(crate) struct RelaxedStdLang;

    impl Lang for RelaxedStdLang {
        const OBEYS_SPAN_TILING: bool = false;

        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = ();
        type StateExt = ();
        type Event = ();
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = ();
        type InvocationSyntax = ();
        type Driver = StdParseDriver<crate::engine::ScopesCommandResolver<RelaxedStdLang>>;

        fn make_node_ext(
            _kind: &NodeKind<Self>,
            _span: &SourceSpan<Self::SourceOrigin>,
            _state: &Arc<ParsingState<Self>>,
            _children: crate::node::StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    const _: () = assert!(!RelaxedStdLang::OBEYS_SPAN_TILING);

    /// The callable type id [`RelaxedStdLang`]'s driver resolves command tokens
    /// under — an arbitrary value every test defining macros for it shares.
    pub(crate) const RELAXED_MACRO: u32 = 10;

    /// [`RelaxedStdLang`]'s driver: command tokens resolve through the state's scope
    /// stack under [`RELAXED_MACRO`], so a test can define macros for the language the
    /// way it does for a tiled one.
    pub(crate) fn relaxed_driver(
        recovery: Recovery,
    ) -> StdParseDriver<crate::engine::ScopesCommandResolver<RelaxedStdLang>> {
        StdParseDriver::new(
            recovery,
            crate::engine::ScopesCommandResolver { command_type: RELAXED_MACRO },
        )
    }

    #[test]
    fn a_language_that_does_not_obey_span_tiling_parses_over_the_standard_reader() {
        // The declaration is a fact the parsers consult, never a bound: the standard
        // reader and the standard parsers serve such a language unchanged, and the
        // tree comes out with the structure the input has.
        let mut rules = min_rules::<RelaxedStdLang>();
        rules.groups.rules = vec![Arc::new(crate::token::GroupRule {
            group_type: 0,
            open: "{".into(),
            close: "}".into(),
        })];
        let seed = Arc::new(ParsingState::new(StateData {
            rules,
            scopes: ScopeStack::new(),
            mode: (),
            ext: (),
        }));
        let language = crate::engine::Language::new(relaxed_driver(Recovery::Strict), seed);
        let parsed = language.parse("a{b}c").expect("the parse runs");

        let root = parsed.tree.root();
        let kinds: Vec<_> = root
            .children()
            .iter()
            .map(|child| match child.kind() {
                NodeKind::Chars { .. } => "chars",
                NodeKind::Group(_) => "group",
                other => panic!("unexpected node kind: {other:?}"),
            })
            .collect();
        assert_eq!(kinds, ["chars", "group", "chars"]);
        // The all-trees law holds for such a tree, exactly as for a tiled one.
        crate::node::validate_tree(&parsed.tree).expect("the all-trees law holds");
    }

    #[test]
    fn source_span_within_describes_the_stretch_when_the_language_does_not_obey_tiling() {
        let source: Arc<Source> = Arc::new(Source::new("abc"));
        let mut reader = crate::token::StdTokenReader::new(&source);
        let mut session = ParserSession::new();
        let driver = relaxed_driver(Recovery::Strict);
        let cx = ParseContext::new(
            &mut reader,
            state::<RelaxedStdLang>(),
            &mut session,
            &driver);

        let begin = cx.tokens.position_here();
        let token = cx.tokens.peek(&cx.state).unwrap();
        let end = cx.tokens.position_at(&token, TokenEdge::EndPastPostSpace);

        // An ordered pair still spans exactly what it delimits …
        assert_eq!(cx.source_span_within(&begin, &end).unwrap().range(), 0..1);
        // … and the reversed pair is no longer an error: the reader's described span
        // is recorded, with no assumption made about it (here, the empty span at
        // `begin`, which is what `StdTokenReader` describes for an inverted pair).
        let described = cx
            .source_span_within(&end, &begin)
            .expect("no error under OBEYS_SPAN_TILING = false");
        assert_eq!(described.range(), 1..1);
    }

    // --- stage_invocation's three end cases -----------------------------------------

    /// A spec with no arguments and no behavior: `stage_invocation` reads only its
    /// identity off the bundle.
    #[derive(Debug)]
    struct TestSpec;

    impl crate::serialize::SerializableObject<PlainLang> for TestSpec {}
    impl CallableSpec<PlainLang> for TestSpec {}

    /// Stage a callable over the token of `content` at index `trigger` as the
    /// trigger, with the given children and end, and report the staged node's span
    /// range.
    fn stage_invocation_span(
        content: &str,
        trigger: usize,
        end: EndUnderTest,
        children: impl FnOnce(&mut ParseContext<'_, '_, PlainLang>) -> Vec<BuildId>,
    ) -> Result<core::ops::Range<usize>, ParseError> {
        with_std_context(content, |cx, _source| {
            let spec: Arc<dyn CallableSpec<PlainLang>> = Arc::new(TestSpec);
            for _ in 0..trigger {
                let skipped = cx.tokens.peek(&cx.state).unwrap();
                cx.tokens.move_to(&skipped, TokenEdge::EndPastPostSpace);
            }
            let token = cx.tokens.peek(&cx.state).unwrap();
            // The dispatch contract: the trigger is consumed before the parser runs.
            cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
            let children = children(cx);
            let invocation = Invocation {
                callable_type: 0u32,
                name: "t",
                spec: &spec,
                token: &token,
            };
            let end = match end {
                EndUnderTest::Standard => None,
                EndUnderTest::Here => Some(cx.tokens.position_here()),
                EndUnderTest::BeforeTheTrigger => {
                    Some(cx.tokens.position_at(&token, TokenEdge::StartBeforePreSpace))
                }
            };
            // A callable's children must be tiled by its regions: one content slot
            // covers whatever the fixture staged.
            let slots = match children.len() as u32 {
                0 => ParsedSlots::empty(),
                count => ParsedSlots::new(alloc::vec![crate::node::ParsedSlot::new(
                    crate::node::ChildRegion::new(
                        0..count,
                        crate::node::ContentNodes::InRegion(0..count),
                    ),
                    "content",
                    crate::node::SlotRole::Content,
                    (),
                )]),
            };
            let id = cx.stage_invocation(
                &invocation,
                ParsedArguments::empty(),
                slots,
                children,
                end.as_ref(),
            )?;
            Ok(cx.staged_nodes().get(id).unwrap().span().range())
        })
    }

    enum EndUnderTest {
        /// `None` — the standard rule.
        Standard,
        /// `Some` at the reader's current position.
        Here,
        /// `Some` before the trigger's own start (a contract violation).
        BeforeTheTrigger,
    }

    /// Stage one chars node over `range` as a child.
    fn chars_child(
        range: core::ops::Range<usize>,
    ) -> impl FnOnce(&mut ParseContext<'_, '_, PlainLang>) -> Vec<BuildId> {
        move |cx| {
            // The source the reader is serving, as the reader reports it.
            let here = cx.here();
            let span = SourceSpan::new(here.source(), range.clone());
            let id = cx
                .stage_node(
                    NodeKind::chars(span.span()),
                    span,
                    Arc::clone(&cx.state),
                    Vec::new(),
                )
                .unwrap();
            alloc::vec![id]
        }
    }

    /// Stage one chars node over `range` of a **second** source as a child — the
    /// standard rule's "last child in another source" branch.
    fn foreign_child(
        range: core::ops::Range<usize>,
    ) -> impl FnOnce(&mut ParseContext<'_, '_, PlainLang>) -> Vec<BuildId> {
        move |cx| {
            let other: Arc<Source> = Arc::new(Source::new("elsewhere"));
            let span = SourceSpan::new(&other, range.clone());
            let id = cx
                .stage_node(
                    NodeKind::chars(span.span()),
                    span,
                    Arc::clone(&cx.state),
                    Vec::new(),
                )
                .unwrap();
            alloc::vec![id]
        }
    }

    #[test]
    fn stage_invocation_ends_at_the_explicit_position() {
        // The reader stands past the trigger's post-space, and two more characters
        // are consumed before staging: the explicit end claims them.
        let range = stage_invocation_span("abcd", 0, EndUnderTest::Here, |cx| {
            for _ in 0..2 {
                let token = cx.tokens.peek(&cx.state).unwrap();
                cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
            }
            Vec::new()
        })
        .unwrap();
        assert_eq!(range, 0..3);
    }

    #[test]
    fn stage_invocation_ends_at_the_last_child_under_the_standard_rule() {
        let range = stage_invocation_span("abcd", 0, EndUnderTest::Standard, chars_child(1..3))
            .unwrap();
        assert_eq!(range, 0..3);
    }

    #[test]
    fn stage_invocation_ends_at_the_reader_for_a_childless_shape() {
        // No child: the node ends where the reader stands — just past the trigger.
        let range =
            stage_invocation_span("abcd", 0, EndUnderTest::Standard, |_cx| Vec::new()).unwrap();
        assert_eq!(range, 0..1);
    }

    #[test]
    fn stage_invocation_ignores_a_last_child_staged_in_another_source() {
        // The child's span cannot end this node — it is in another source — so the
        // node ends where the reader stands (just past the trigger), exactly as for
        // a childless shape.
        let range =
            stage_invocation_span("abcd", 0, EndUnderTest::Standard, foreign_child(3..9))
                .unwrap();
        assert_eq!(range, 0..1);
    }

    #[test]
    fn stage_invocation_reports_an_end_before_the_trigger_as_an_implementation_error() {
        // (a) an explicit end that precedes the trigger's start (the trigger's own
        // pre-space edge).
        let error =
            stage_invocation_span(" abcd", 0, EndUnderTest::BeforeTheTrigger, |_cx| Vec::new())
                .unwrap_err();
        assert_invalid_node_span(&error);

        // (b) the standard rule with a last child that ends before the trigger
        // starts (the trigger is the third character here, the child the first).
        let error =
            stage_invocation_span("abcd", 2, EndUnderTest::Standard, chars_child(0..1))
                .unwrap_err();
        assert_invalid_node_span(&error);
    }

    fn assert_invalid_node_span(error: &ParseError) {
        let condition = error
            .data()
            .downcast_ref::<ImplementationError>()
            .expect("an ImplementationError condition");
        assert!(
            condition.detail.contains("invalid node span"),
            "unexpected detail: {}",
            condition.detail
        );
    }

    // --- the descent entry point (parse_construct) --------------------------------

    #[test]
    fn parse_construct_state_none_matches_explicit_current_state_clone() {
        let source: Arc<Source> = Arc::new(Source::new("xy"));
        let st = state();
        let mut reader: TokenListReader<'_, PlainLang> = TokenListReader::new(&source, vec![]);
        let mut session = ParserSession::new();
        let driver = StdParseDriver::new(Recovery::Tolerant, ());
        let mut cx = ParseContext::new(
            &mut reader,
            Arc::clone(&st),
            &mut session,
            &driver);

        // `state: None`: the sub-parse runs under the current state, scoped (one
        // enclosing-state stack entry), and the outer state is restored after.
        let mut probe = StackProbeParser::default();
        cx.parse_construct(&mut probe, None, None).unwrap();
        assert!(Arc::ptr_eq(probe.seen_state.as_ref().unwrap(), &st));
        let depth_under_none = probe.seen_depth.unwrap();
        assert_eq!(depth_under_none, 1);
        assert!(Arc::ptr_eq(&cx.state, &st), "outer state restored");
        assert_eq!(cx.session.state_stack().len(), 0, "stack entry popped");

        // `Some(Arc::clone(&cx.state))`: observably identical — same input state,
        // same enclosing-state stack depth seen inside, same restore.
        let mut probe = StackProbeParser::default();
        let explicit = Arc::clone(&cx.state);
        cx.parse_construct(&mut probe, Some(explicit), None).unwrap();
        assert!(Arc::ptr_eq(probe.seen_state.as_ref().unwrap(), &st));
        assert_eq!(probe.seen_depth.unwrap(), depth_under_none);
        assert!(Arc::ptr_eq(&cx.state, &st), "outer state restored");
        assert_eq!(cx.session.state_stack().len(), 0, "stack entry popped");
    }

    #[test]
    fn parse_construct_frame_reaches_the_diagnostic_snapshot() {
        let source: Arc<Source> = Arc::new(Source::new("xy"));
        let st = state();
        let mut reader: TokenListReader<'_, PlainLang> = TokenListReader::new(&source, vec![]);
        let mut session = ParserSession::new();
        let driver = StdParseDriver::new(Recovery::Tolerant, ());
        let mut cx =
            ParseContext::new(&mut reader, st, &mut session, &driver);

        let frame = Frame {
            title: FrameTitle::Static("construct frame"),
            span: SourceSpan::new(&source, Span::new(0, 1)),
        };
        cx.parse_construct(&mut RecoveringParser, None, Some(frame)).unwrap();
        assert!(cx.session.snapshot_frames().is_empty(), "frame popped on return");

        let diagnostic = session.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.frames().len(), 1);
        assert_eq!(diagnostic.frames()[0].title(), "construct frame");
        assert_eq!(diagnostic.frames()[0].span().range(), 0..1);
    }

    #[test]
    fn parse_construct_pops_the_frame_on_the_err_path() {
        let source: Arc<Source> = Arc::new(Source::new("xy"));
        let st = state();
        let mut reader: TokenListReader<'_, PlainLang> = TokenListReader::new(&source, vec![]);
        let mut session = ParserSession::new();
        let driver = StdParseDriver::new(Recovery::Strict, ());
        let mut cx =
            ParseContext::new(&mut reader, st, &mut session, &driver);

        let frame = Frame {
            title: FrameTitle::Static("construct frame"),
            span: SourceSpan::new(&source, Span::new(0, 1)),
        };
        let err =
            cx.parse_construct(&mut RecoveringParser, None, Some(frame)).unwrap_err();
        assert!(
            cx.session.snapshot_frames().is_empty(),
            "frame popped on the Err path"
        );
        // The strict abort snapshotted the frame while it was live.
        assert_eq!(err.frames().len(), 1);
        assert_eq!(err.frames()[0].title(), "construct frame");
    }

    #[test]
    fn attach_hook_frames_adds_the_live_traceback_unless_present() {
        let source: Arc<Source> = Arc::new(Source::new("xy"));
        let st = state();
        let mut reader: TokenListReader<'_, PlainLang> = TokenListReader::new(&source, vec![]);
        let mut session = ParserSession::new();
        let driver = StdParseDriver::new(Recovery::Strict, ());
        let mut cx =
            ParseContext::new(&mut reader, st, &mut session, &driver);

        let frame = || Frame {
            title: FrameTitle::Static("hook frame"),
            span: SourceSpan::new(&source, Span::new(0, 1)),
        };
        let at = SourceSpan::new(&source, Span::new(1, 2));

        // A frameless hook error picks up the frames live at the dispatch site.
        let attached = cx.with_frame(frame(), |cx| {
            cx.attach_hook_frames(ParseError::new(TestCondition, at.clone()))
        });
        assert_eq!(attached.frames().len(), 1);
        assert_eq!(attached.frames()[0].title(), "hook frame");
        assert_eq!(attached.span().range(), 1..2, "condition and span are the hook's own");

        // An error already carrying frames passes through unchanged.
        let preexisting = ParseError::new(TestCondition, at.clone())
            .with_frames(vec![crate::error::TraceFrame::new("preexisting", at.clone())]);
        let kept = cx.with_frame(frame(), |cx| cx.attach_hook_frames(preexisting));
        assert_eq!(kept.frames().len(), 1);
        assert_eq!(kept.frames()[0].title(), "preexisting");
    }

    /// The `&dyn Fn` hot-path callbacks ([`TokenStopKind::Predicate`],
    /// [`StopSpec::node`], both [`ChildStateSpec`] `Compute` arms) materialize
    /// their `Result` on every consultation — per token or per descent — because
    /// the callee is opaque to the optimizer (unlike the statically dispatched
    /// `Lang`/driver hooks, where an infallible monomorphized body lets the
    /// optimizer remove the channel). This pins the measured cost: the `Result` wrapper adds
    /// zero bytes over the bare [`ParseError`] arm (the `Ok` payload fits the
    /// error type's niches) and the whole `Result` stays within one cache line
    /// ([`ConstructParserResult`] carries the identical [`ParseError`] arm), so
    /// the `Err` arm is deliberately **not** boxed — re-measure here before
    /// restructuring.
    #[test]
    fn hot_path_result_payloads_stay_within_one_cache_line() {
        use core::mem::size_of;
        type Origin = Option<String>;

        let parse_error = size_of::<ParseError<Origin>>();
        // `TokenStopKind::Predicate` / `StopSpec::node` (pre-sweep: `bool`, 1 B).
        let predicate = size_of::<Result<bool, ParseError<Origin>>>();
        // The two `Compute` arms (pre-sweep: `Arc<ParsingState<_>>`, 8 B).
        let compute =
            size_of::<Result<Arc<ParsingState<PlainLang>>, ParseError<Origin>>>();

        // The niche fit: wrapping either `Ok` payload in `Result` costs nothing
        // over the bare error arm.
        assert_eq!(
            predicate, parse_error,
            "Predicate/StopSpec::node Result outgrew the bare ParseError"
        );
        assert_eq!(
            compute, parse_error,
            "Compute-arm Result outgrew the bare ParseError"
        );
        assert!(parse_error <= 64, "ParseError outgrew one cache line: {parse_error} B");
    }
}