techy 0.1.1

A fast, extensible LaTeX parser for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
//! Engine orchestration: [`ParserSession`], the root object of one parse, and the
//! [`ParseDriver`] behavior object.
//!
//! A session holds everything one parse **accumulates** — the staging
//! [`NodeTreeBuilder`], the [`Diagnostics`] sink, the derivation memos, the live frame
//! stack — and [`finish`](ParserSession::finish) freezes it into a [`ParseResult`].
//! Sessions are transient: one parse each, no reuse. Parse *behavior*, the
//! [`Recovery`] policy included, belongs to the language's [`ParseDriver`] instead.
//!
//! The [`Language<L>`] bundle is the long-lived counterpart: the initial state and the
//! driver instance, with the [`parse()`](Language::parse) shorthand and the
//! configurable [`parse_setup()`](Language::parse_setup) → [`ParseSetup::parse`] entry
//! running reader → root parser → `finish()`.
//!
//! `ParseResult` deliberately has no `'env` lifetime and no `Language` reference:
//! nodes are self-contained, so results outlive the bundle that produced them.

mod descent_guard;
mod driver;
mod language;
mod state_memo;

use core::fmt;

use crate::error::{
    Diagnostic, DiagnosticData, Diagnostics, ParseError, Recovery, Severity, TraceFrame,
};
use crate::node::{BuildId, NodeBuildError, NodeTree, NodeTreeBuilder};
use crate::source::SourceSpan;
use crate::spec::{CallableSpec, FrameRole};
use crate::state::{
    DeriveError, FeaturePresence, Lang, LangFeatures, ParsingState, ParsingStateDelta,
    ParsingStateStack,
};
use crate::token::GroupRule;

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

use state_memo::{
    GroupInteriorEntry, GroupInteriorKey, GroupInteriorMemo, GroupInteriorProbe, StateMemo,
    StateMemoKey, StateMemoProbe,
};

pub use descent_guard::{
    DescentGuard, DescentRefusal, DescentWarning, StdDescentGuard, StdDescentGuardInit,
};
pub use driver::{
    resolve_command_in_scopes, CommandResolution, CommandResolver, ParseDriver,
    ResolvedCallable, ScopesCommandResolver, StdParseDriver,
};
pub use language::{Language, ParseSetup};

/// One construct that a parse currently has open: an entry of the session's parse
/// frame stack.
///
/// The stack is what lets a reported problem say which group, argument, or
/// environment the parser was inside. Frames are pushed and popped at every descent
/// by
/// [`ParseContext::with_frame`](crate::core::constructs::ParseContext::with_frame), and
/// [`ParserSession::snapshot_frames`] copies the live stack into
/// [`TraceFrame`]s — which are not generic over the language type `L` — whenever a
/// condition is recorded.
///
/// Building a frame allocates nothing (only `Arc` reference counts change), because a
/// push happens once per construct in every parse; the title is rendered only when a
/// snapshot is taken, that is, only when a problem is being reported.
pub struct Frame<L: Lang> {
    /// How the frame's traceback title is produced at snapshot time.
    pub title: FrameTitle<L>,
    /// Where in the source the parse descended (the traceback's location line).
    pub span: SourceSpan<L::SourceOrigin>,
}

/// How a [`Frame`]'s title is produced when the stack is snapshotted.
///
/// The variants name mechanisms rather than kinds of construct: the engine has no
/// vocabulary for macros or environments, so a callable's title is produced by its
/// own spec, through
/// [`stack_frame_title`](CallableSpec::stack_frame_title), at the moment a snapshot
/// is taken.
pub enum FrameTitle<L: Lang> {
    /// A fixed title.
    Static(&'static str),
    /// `label ‘<slice>’`, quoting a source slice (a group's open delimiter, an
    /// environment's name).
    Quoted {
        /// The label preceding the quoted slice.
        label: &'static str,
        /// The span whose content is quoted.
        name: SourceSpan<L::SourceOrigin>,
    },
    /// A callable's frame, titled by the spec's
    /// [`stack_frame_title`](CallableSpec::stack_frame_title) hook.
    Callable {
        /// The invocation's behavior spec.
        spec: Arc<dyn CallableSpec<L>>,
        /// Which part of the callable's parse the frame covers.
        role: FrameRole,
        /// The span of the invocation spelling, quoted into the title.
        name: SourceSpan<L::SourceOrigin>,
    },
}

impl<L: Lang> Frame<L> {
    /// Render the live frame into a snapshot [`TraceFrame`] — run only when a
    /// condition is recorded: titles
    /// allocate here, never on push.
    fn render(&self) -> TraceFrame<L::SourceOrigin> {
        let title = match &self.title {
            FrameTitle::Static(title) => String::from(*title),
            FrameTitle::Quoted { label, name } => {
                format!("{} ‘{}’", label, name.content())
            }
            FrameTitle::Callable { spec, role, name } => {
                spec.stack_frame_title(*role, name.content())
            }
        };
        TraceFrame::new(title, self.span.clone())
    }
}

// Manual Debug impls: derives would demand `L: Debug` although only associated types
// (already bounded) and `Arc`s are stored.

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

impl<L: Lang> fmt::Debug for FrameTitle<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FrameTitle::Static(title) => f.debug_tuple("Static").field(title).finish(),
            FrameTitle::Quoted { label, name } => f
                .debug_struct("Quoted")
                .field("label", label)
                .field("name", name)
                .finish(),
            FrameTitle::Callable { spec, role, name } => f
                .debug_struct("Callable")
                .field("spec", spec)
                .field("role", role)
                .field("name", name)
                .finish(),
        }
    }
}

/// Why a state derivation made through the session failed
/// ([`ParserSession::derived_state`], [`ParserSession::group_interior_state`]).
///
/// Either the derivation itself failed, or the driver's transition observation hook
/// asked for the parse to end. The two arms stay separate because a caller can do
/// different things with them: a derivation failure comes with a structured
/// [`DeriveError`] naming the operations that failed and offering a recovered state
/// to continue under, while an observation abort is already the [`ParseError`] that
/// ends the parse (see [`ParseDriver::observe_transition`]).
#[allow(clippy::large_enum_variant)] // large `Derive` arm by design — see `DeriveError`
#[non_exhaustive]
pub enum SessionDeriveError<L: Lang> {
    /// The derivation failed ([`ParsingState::derived`]'s error): failing scope
    /// ops and/or a finalize refusal, with the recovered state for tolerant
    /// continuation.
    Derive(DeriveError<L>),
    /// [`ParseDriver::observe_transition`] answered its abort channel; the
    /// transition was not committed.
    Observe(ParseError<L::SourceOrigin>),
}

impl<L: Lang> fmt::Display for SessionDeriveError<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SessionDeriveError::Derive(error) => fmt::Display::fmt(error, f),
            SessionDeriveError::Observe(error) => fmt::Display::fmt(error, f),
        }
    }
}

// Manual Debug: a derive would demand `L: Debug` although only bounded associated
// data is stored (the `DeriveError` pattern).
impl<L: Lang> fmt::Debug for SessionDeriveError<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SessionDeriveError::Derive(error) => f.debug_tuple("Derive").field(error).finish(),
            SessionDeriveError::Observe(error) => {
                f.debug_tuple("Observe").field(error).finish()
            }
        }
    }
}

impl<L: Lang> core::error::Error for SessionDeriveError<L> {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            SessionDeriveError::Derive(error) => Some(error),
            SessionDeriveError::Observe(error) => Some(error),
        }
    }
}

/// Everything one parse accumulates: the nodes being staged, the diagnostics, and the
/// bookkeeping the engine needs while the parse runs.
///
/// A session is created for one parse and consumed by
/// [`finish`](ParserSession::finish), which freezes it into a [`ParseResult`]. It is
/// the only mutable part of a parse — trees, states, and specs are all immutable —
/// and construct parsers reach it as
/// [`ParseContext::session`](crate::core::constructs::ParseContext::session).
///
/// [`diagnostics`](ParserSession::diagnostics) and [`ext`](ParserSession::ext) are
/// public fields, so a parser can record a diagnostic or update the language's own
/// per-parse data directly. The node builder is deliberately private: nodes are
/// staged only through
/// [`ParseContext::stage_node`](crate::core::constructs::ParseContext::stage_node), which
/// creates the node extension as it goes, so no parser can stage a node with its
/// extension left unpopulated. Read staged nodes back with
/// [`ParseContext::staged_nodes`](crate::core::constructs::ParseContext::staged_nodes).
///
/// Most programs never touch a session: [`Language::parse`] creates and finishes one.
/// Construct it directly when driving construct parsers yourself, over a
/// [`ParseContext`](crate::core::constructs::ParseContext) you built.
pub struct ParserSession<L: Lang> {
    /// The staging node builder (crate-internal; see the type docs).
    pub(crate) builder: NodeTreeBuilder<L>,
    /// The diagnostics accumulated so far.
    pub diagnostics: Diagnostics<L::SourceOrigin>,
    /// The parse-global mutable language extension ([`Lang::SessionExt`],
    /// `Default`-initialized): the preset-owned mutable object of a parse — transition
    /// observation counters ([`ParseDriver::observe_transition`]), parse-global caches.
    pub ext: L::SessionExt,
    /// The derivation memo:
    /// overrides-only derivations (token rules and/or mode) deduplicated by
    /// [`derived_state`](ParserSession::derived_state), keyed on base-state `Arc`
    /// identity plus the delta's overrides — rule payloads by `Arc` identity, the mode
    /// override by value (see [`state_memo`]). Entries hold their key `Arc`s alive, so
    /// pointer keys cannot be reused (no ABA hazard); retention is bounded by the
    /// session — one transient parse.
    state_memo: StateMemo<L>,
    /// The group-interior derivation memo: one entry per `(base, rule)`
    /// descent — the canonical expecting-close derivation *merged with the driver's*
    /// [`group_interior_delta`](ParseDriver::group_interior_delta), which runs on memo
    /// miss only. Deliberately separate from [`state_memo`](ParserSession::state_memo):
    /// sharing it would let a hand-built expecting-close delta collide with a
    /// driver-augmented descent under one key (see [`state_memo`] module docs).
    group_interior_memo: GroupInteriorMemo<L>,
    /// The live parse-frame stack, outermost first:
    /// maintained exclusively by
    /// [`ParseContext::with_frame`](crate::core::constructs::ParseContext::with_frame)
    /// (closure-scoped push/pop) and snapshotted — innermost first — into every
    /// condition the recover funnel records. Private: the push/pop balance is an
    /// invariant.
    frames: Vec<Frame<L>>,
    /// The live **enclosing-state stack** ([`ParsingStateStack`]): the states the
    /// parse descended through, pushed/popped at the same descent points as the
    /// frame stack — maintained exclusively by
    /// [`ParseContext::with_parsing_state`](crate::core::constructs::ParseContext::with_parsing_state)
    /// (closure-scoped push/pop) and lent by reference to the driver's
    /// event-lowering hook ([`ParseDriver::resolve_state_event`]) inside
    /// [`ParseContext::derive_state`](crate::core::constructs::ParseContext::derive_state).
    /// The engine retains exactly these states implicitly anyway (leaving a scope
    /// structurally restores the outer `Arc`) — the stack only materializes them,
    /// and it is dropped with the session: no ancestry data survives into parsed
    /// material. Private: the push/pop balance is an invariant.
    state_stack: ParsingStateStack<L>,
    /// The per-parse [`StdDescentGuard`] instance, consulted by
    /// [`ParseContext::parse_construct`](crate::core::constructs::ParseContext::parse_construct)
    /// before every descent. [`ParseSetup::parse`] installs it eagerly at
    /// parse entry (through
    /// [`install_descent_guard`](ParserSession::install_descent_guard)); a
    /// hand-built session that never installs one gets a
    /// default-configured guard lazily at the first descent.
    descent_guard: Option<StdDescentGuard>,
}

impl<L: Lang> ParserSession<L> {
    /// Creates an empty session for one parse.
    ///
    /// A session holds no configuration — the recovery policy and every other
    /// parse-time decision belong to the language's [`ParseDriver`] — so there is
    /// nothing to pass here.
    pub fn new() -> ParserSession<L> {
        ParserSession {
            builder: NodeTreeBuilder::new(),
            diagnostics: Diagnostics::new(),
            ext: Default::default(),
            state_memo: StateMemo::new(),
            group_interior_memo: GroupInteriorMemo::new(),
            frames: Vec::new(),
            state_stack: ParsingStateStack::new(),
            descent_guard: None,
        }
    }

    /// Installs the guard that caps how deeply this parse may nest.
    ///
    /// [`ParseSetup::parse`] does this for you. Call it yourself when driving
    /// construct parsers over a [`ParseContext`](crate::core::constructs::ParseContext) you
    /// built: create the guard with [`DescentGuard::init`] on the thread that will
    /// parse, and install it before parsing starts.
    ///
    /// Without an installed guard, the first descent creates one from the default
    /// configuration. That still caps the nesting, but a stack-measuring guard then
    /// takes its reference measurement at that first descent instead of at the true
    /// start of the parse.
    pub fn install_descent_guard(&mut self, guard: StdDescentGuard) {
        self.descent_guard = Some(guard);
    }

    /// Ask the parse's guard whether one more descent may start —
    /// [`parse_construct`](crate::core::constructs::ParseContext::parse_construct)'s
    /// pre-descent hook, creating the default-configured guard lazily when none
    /// was installed.
    pub(crate) fn enter_descent(
        &mut self,
    ) -> Result<Option<DescentWarning>, DescentRefusal> {
        self.descent_guard
            .get_or_insert_with(|| StdDescentGuard::init(&Default::default()))
            .try_enter()
    }

    /// The matching end of a granted [`enter_descent`](ParserSession::enter_descent):
    /// the sub-parse returned and the parse is one level shallower again.
    pub(crate) fn exit_descent(&mut self) {
        if let Some(guard) = &mut self.descent_guard {
            guard.exit();
        }
    }

    /// Push onto the live enclosing-state stack — called only by
    /// [`ParseContext::with_parsing_state`](crate::core::constructs::ParseContext::with_parsing_state)
    /// (and the event-lowering lend in
    /// [`derive_state`](crate::core::constructs::ParseContext::derive_state)), whose
    /// closure scoping guarantees the matching pop.
    pub(crate) fn push_state(&mut self, state: Arc<ParsingState<L>>) {
        self.state_stack.push(state);
    }

    /// Pop the innermost enclosing-state entry (`with_parsing_state`'s epilogue).
    pub(crate) fn pop_state(&mut self) {
        let popped = self.state_stack.pop();
        debug_assert!(popped.is_some(), "with_parsing_state pops exactly what it pushed");
    }

    /// The live enclosing-state stack (innermost-first; see [`ParsingStateStack`]).
    pub(crate) fn state_stack(&self) -> &ParsingStateStack<L> {
        &self.state_stack
    }

    /// Push a live traceback frame — called only by
    /// [`ParseContext::with_frame`](crate::core::constructs::ParseContext::with_frame), whose
    /// closure scoping guarantees the matching [`pop_frame`](ParserSession::pop_frame).
    pub(crate) fn push_frame(&mut self, frame: Frame<L>) {
        self.frames.push(frame);
    }

    /// Pop the innermost live traceback frame (`with_frame`'s epilogue).
    pub(crate) fn pop_frame(&mut self) {
        let popped = self.frames.pop();
        debug_assert!(popped.is_some(), "with_frame pops exactly what it pushed");
    }

    /// Copies the constructs currently open into [`TraceFrame`]s, innermost first.
    ///
    /// The frame titles are rendered here, which is why the copy is made only when a
    /// condition is being recorded. Call it when building a [`ParseError`] of your
    /// own, to attach the parse traceback with
    /// [`ParseError::with_frames`](crate::error::ParseError::with_frames).
    ///
    /// The live stack itself changes only through
    /// [`ParseContext::with_frame`](crate::core::constructs::ParseContext::with_frame).
    pub fn snapshot_frames(&self) -> Vec<TraceFrame<L::SourceOrigin>> {
        self.frames.iter().rev().map(Frame::render).collect()
    }

    /// Derives a new parsing state from `base` and `delta`, reporting the transition
    /// to the driver.
    ///
    /// This is how states are derived *during* a parse. The result is exactly what
    /// [`ParsingState::derived`] would produce — the session layer may deduplicate the
    /// work and report the transition, never change its outcome — but going through
    /// the session is what lets [`ParseDriver::observe_transition`] see every
    /// transition, with the session's [`ext`](ParserSession::ext) to accumulate into.
    /// Code outside a parse (initial states, tests, tree transformations) calls
    /// `derived()` directly.
    ///
    /// Construct parsers normally call [`ParseContext::derive_state`] rather than this
    /// method: it supplies the driver and, first, turns context-dependent events into
    /// ordinary patches. This method performs no such event lowering.
    ///
    /// [`ParseContext::derive_state`]: crate::core::constructs::ParseContext::derive_state
    ///
    /// # Memoization
    ///
    /// A delta carrying only token-rule overrides and/or a mode override — no
    /// extension replacement, no events, no scope operations — is memoized for the
    /// rest of the session. The key is the base state's `Arc` identity plus the
    /// overrides, with rule payloads taken by `Arc` identity and the per-block gates
    /// and the mode by value.
    ///
    /// Identity keying is exact here, because `derived()` is a pure function of the
    /// base data, the delta, and the events ([`Lang::finalize_transition`]'s purity
    /// contract). It can only miss — on `Arc`s that are value-equal but distinct —
    /// never hit falsely; the mode key, being a `Copy + Eq` value, cannot even miss.
    /// Deltas carrying an extension, events, or scope operations always derive afresh:
    /// those payloads have no identity to key on.
    ///
    /// [`ParseDriver::observe_transition`] runs on **every** call, memoized ones
    /// included. [`Lang::finalize_transition`] runs once per distinct derivation.
    ///
    /// # Errors
    ///
    /// [`Derive`](SessionDeriveError::Derive) means the derivation itself failed —
    /// scope operations can fail, so this method is fallible exactly as
    /// [`ParsingState::derived`] beneath it is. A delta of overrides alone cannot fail
    /// this way, which is also why the memo never needs to cache a failure.
    ///
    /// [`Observe`](SessionDeriveError::Observe) means
    /// [`observe_transition`](ParseDriver::observe_transition) asked for the parse to
    /// end.
    ///
    /// On either error no transition is committed and nothing is memoized. On the
    /// `Derive` arm [`observe_transition`](ParseDriver::observe_transition) has **not**
    /// run, so a caller that tolerates the failure and continues under
    /// [`DeriveError::recovered`](crate::core::DeriveError) is responsible for
    /// reporting that transition itself — which the
    /// [`ParseContext`](crate::core::constructs::ParseContext) convenience method does on
    /// its recovery path.
    #[allow(clippy::result_large_err)] // large `Err` by design — see `DeriveError`
    pub fn derived_state(
        &mut self,
        driver: &L::Driver,
        base: &Arc<ParsingState<L>>,
        delta: &ParsingStateDelta<L>,
    ) -> Result<Arc<ParsingState<L>>, SessionDeriveError<L>> {
        // The scope-op list is read through its store projection: absent scopes
        // (`None`) hold no ops, so such a delta is memoizable like any other
        // overrides-only delta.
        let memoizable = delta.ext.is_none()
            && delta.events.is_empty()
            && <L::Features as LangFeatures>::Scopes::store_get(&delta.scope_ops)
                .is_none_or(|ops| ops.is_empty());
        if memoizable {
            if let Some(hit) = self.state_memo.get(&StateMemoProbe {
                base,
                mode: delta.mode,
                rules: &delta.rules,
            }) {
                let new = Arc::clone(hit);
                driver
                    .observe_transition(&mut self.ext, &mut self.diagnostics, base, &new, delta)
                    .map_err(SessionDeriveError::Observe)?;
                return Ok(new);
            }
        }
        let new =
            Arc::new(base.derived(delta).map_err(SessionDeriveError::Derive)?);
        driver
            .observe_transition(&mut self.ext, &mut self.diagnostics, base, &new, delta)
            .map_err(SessionDeriveError::Observe)?;
        // The memo insert runs last, after the observation: on any Err nothing is
        // committed — no memo entry, no observed transition to a state nobody got.
        if memoizable {
            self.state_memo.insert(
                StateMemoKey {
                    base: Arc::clone(base),
                    mode: delta.mode,
                    rules: delta.rules.clone(),
                },
                Arc::clone(&new),
            );
        }
        Ok(new)
    }

    /// Derives the state a group's interior is parsed under, when the group entered
    /// matched `rule`.
    ///
    /// That state is always `base` with `expecting_group_close` set to `rule` — the
    /// invariant that keeps the group's close delimiter recognizable — merged with
    /// whatever [`group_interior_delta`](ParseDriver::group_interior_delta) returns,
    /// which is how a group class changes the conditions its content is parsed under
    /// (a math group setting the parsing mode).
    ///
    /// The invariant wins over the hook: whatever the driver's delta says, the
    /// interior's `expecting_group_close` is the rule that was entered.
    ///
    /// # Memoization
    ///
    /// Sibling groups under one state repeat the identical derivation, which is the
    /// largest state-copying cost in deeply nested documents, so the result is
    /// memoized per `(base, rule)` (both by `Arc` identity). This memo is separate
    /// from the one [`derived_state`](ParserSession::derived_state) uses: sharing one
    /// map would let a hand-built expecting-close delta and a driver-augmented descent
    /// collide under the same key while deriving different states.
    ///
    /// The driver hook therefore runs on a memo **miss** only, which is sound because
    /// it is contractually a pure function of `(base, rule)`. A memoized hit reuses
    /// its previous answer, and the entry stores the *merged* delta so that
    /// [`observe_transition`](ParseDriver::observe_transition) — which runs on every
    /// call, hits included — always sees the true delta. Since the key is
    /// `(base, rule)` rather than the shape of the delta, the descent stays
    /// deduplicated even when the driver's delta carries events or an extension.
    ///
    /// # Errors
    ///
    /// [`Derive`](SessionDeriveError::Derive) means the derivation failed: a driver's
    /// descent delta may carry scope operations, and those can fail.
    /// [`Observe`](SessionDeriveError::Observe) means
    /// [`observe_transition`](ParseDriver::observe_transition) asked for the parse to
    /// end.
    ///
    /// On either error nothing is memoized, and on the `Derive` arm no transition was
    /// reported — as in [`derived_state`](ParserSession::derived_state). The
    /// derivation error's [`recovered`](crate::core::DeriveError::recovered) state
    /// still has the interior invariant applied, because the forced
    /// `expecting_group_close` is an override rather than an operation, so a caller
    /// that tolerates the failure can safely parse the interior under it.
    ///
    /// Failures are deliberately not cached: every failing descent reports again,
    /// rather than a misbehaving driver being diagnosed once and then silently
    /// tolerated.
    #[allow(clippy::result_large_err)] // large `Err` by design — see `DeriveError`
    pub fn group_interior_state(
        &mut self,
        driver: &L::Driver,
        base: &Arc<ParsingState<L>>,
        rule: &Arc<GroupRule<L>>,
    ) -> Result<Arc<ParsingState<L>>, SessionDeriveError<L>> {
        if let Some(entry) = self.group_interior_memo.get(&GroupInteriorProbe { base, rule })
        {
            let new = Arc::clone(&entry.state);
            let delta = Arc::clone(&entry.delta);
            driver
                .observe_transition(&mut self.ext, &mut self.diagnostics, base, &new, &delta)
                .map_err(SessionDeriveError::Observe)?;
            return Ok(new);
        }
        let mut delta = driver.group_interior_delta(base, rule).unwrap_or_default();
        // The descent invariant, forced last: the interior always expects exactly the
        // entered rule's close — a driver delta cannot displace it. The write goes
        // through the store projection (this method is total engine machinery under
        // an unbounded `L`); it is reachable only through the guarded GroupOpen
        // dispatch, so for a groups-present language the projection is always `Some`
        // and the behavior is unchanged.
        if let Some(groups) =
            <L::Features as LangFeatures>::Groups::store_get_mut(&mut delta.rules.groups)
        {
            groups.expecting_close = Some(Some(Arc::clone(rule)));
        }
        let delta = Arc::new(delta);
        let new =
            Arc::new(base.derived(&delta).map_err(SessionDeriveError::Derive)?);
        driver
            .observe_transition(&mut self.ext, &mut self.diagnostics, base, &new, &delta)
            .map_err(SessionDeriveError::Observe)?;
        // The memo insert runs last, after the observation (see `derived_state`).
        self.group_interior_memo.insert(
            GroupInteriorKey { base: Arc::clone(base), rule: Arc::clone(rule) },
            GroupInteriorEntry { state: Arc::clone(&new), delta: Arc::clone(&delta) },
        );
        Ok(new)
    }

    /// Records a detected problem, or turns it into the error that ends the parse.
    ///
    /// `recovery` is the policy for **this** condition: the driver's blanket answer,
    /// or a per-condition decision by a custom driver policy. Under
    /// [`Recovery::Tolerant`] the condition is recorded as an error-severity
    /// [`Diagnostic`] at `span` and `Ok(())` is returned, so the caller continues with
    /// the local recovery documented for that condition. Under [`Recovery::Strict`]
    /// the condition is returned as a [`ParseError`] to propagate, and nothing
    /// continues past it. Either way it receives a snapshot of the frames currently
    /// open — the parse traceback.
    ///
    /// Construct parsers call
    /// [`ParseContext::recover`](crate::core::constructs::ParseContext::recover) instead.
    /// That entry point boxes the condition and passes it to [`ParseDriver::recover`],
    /// which applies [`refine_diagnostic`](ParseDriver::refine_diagnostic) — needing
    /// the context's state — and its recovery policy before reaching this method.
    ///
    /// # Errors
    ///
    /// Returns the condition as a [`ParseError`] exactly when `recovery` is
    /// [`Recovery::Strict`].
    pub fn recover(
        &mut self,
        recovery: Recovery,
        data: Box<dyn DiagnosticData>,
        span: SourceSpan<L::SourceOrigin>,
    ) -> Result<(), ParseError<L::SourceOrigin>> {
        let frames = self.snapshot_frames();
        match recovery {
            Recovery::Tolerant => {
                self.diagnostics
                    .push(Diagnostic::from_parts(Severity::Error, data, span, frames));
                Ok(())
            }
            Recovery::Strict => Err(ParseError::from_parts(data, span, frames)),
        }
    }

    /// Freezes the session into a [`ParseResult`], with `root` as the tree's root
    /// node.
    ///
    /// Everything reachable from `root` is flattened into the final [`NodeTree`],
    /// resolving the staged argument and slot regions on the way. The diagnostics
    /// come along — a tolerant parse succeeds with a non-empty set — as does the
    /// session extension ([`ext`](ParserSession::ext)), holding whatever
    /// [`ParseDriver::observe_transition`] accumulated.
    ///
    /// # Errors
    ///
    /// Returns [`NodeBuildError`] when the staging contract was violated. That is an
    /// implementation bug in an extension, not a problem with the document.
    pub fn finish(self, root: BuildId) -> Result<ParseResult<L>, NodeBuildError> {
        Ok(ParseResult {
            tree: self.builder.finish(root)?,
            diagnostics: self.diagnostics,
            session_ext: self.ext,
        })
    }
}

impl<L: Lang> Default for ParserSession<L> {
    fn default() -> Self {
        ParserSession::new()
    }
}

impl<L: Lang> fmt::Debug for ParserSession<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ParserSession")
            .field("builder", &self.builder)
            .field("diagnostics", &self.diagnostics)
            .field("ext", &self.ext)
            .field("state_memo", &self.state_memo.len())
            .field("group_interior_memo", &self.group_interior_memo.len())
            .field("frames", &self.frames.len())
            .field("state_stack", &self.state_stack.len())
            .field("descent_guard_installed", &self.descent_guard.is_some())
            .finish()
    }
}

/// What a completed parse produced: the finished node tree, the diagnostics, and
/// whatever the language accumulated along the way.
///
/// Returned by [`Language::parse`] and [`ParseSetup::parse`]. It owns everything it
/// holds and borrows nothing from the [`Language`] that produced it, so a result
/// outlives its language. A parse that aborted returns a
/// [`ParseError`](crate::error::ParseError) instead, and no `ParseResult` at all.
///
/// The fields are public: read [`tree`](ParseResult::tree) for the document,
/// [`diagnostics`](ParseResult::diagnostics) for what was reported, and take either
/// of them by value when only one is needed.
pub struct ParseResult<L: Lang> {
    /// The parsed document, as an immutable node tree.
    pub tree: NodeTree<L>,
    /// Everything reported during the parse.
    ///
    /// A tolerant parse succeeds with a non-empty set of diagnostics, so check
    /// [`has_errors`](crate::error::Diagnostics::has_errors) before treating the tree
    /// as clean.
    pub diagnostics: Diagnostics<L::SourceOrigin>,
    /// The language's own per-parse data at the end of the parse
    /// ([`Lang::SessionExt`]), or `()` for a language that declares none.
    ///
    /// [`ParseDriver::observe_transition`] accumulates into this value while the parse
    /// runs — how many times the parse entered math mode, for instance — and this
    /// field is where the accumulated value comes out. Anything that hook chose to
    /// *report* rather than accumulate is in
    /// [`diagnostics`](ParseResult::diagnostics) instead.
    ///
    /// Only a completed parse yields this value; a parse that aborted drops it with
    /// its session.
    pub session_ext: L::SessionExt,
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constructs::{ConstructParser, ConstructParserResult, ParseContext};
    use crate::scopes::ScopeStack;
    use crate::node::NodeKind;
    use crate::source::{Source, Span};
    use crate::state::{
        CommentOverrides, GroupOverrides, Lang, ParsingState, ParsingStateDelta, TrivialLang,
        StateData, TokenRulesOverrides,
    };
    use crate::token::{
        CommandRules, CommentRules, ForbiddenCharsRules, GroupRule, GroupRules,
        CommandRule, ParagraphRules, SpecialsRules, StdToken, StdTokenReader, TokenKind,
        TokenListReader, TokenReader, TokenRules, WhitespaceRules,
    };
    use alloc::string::String;
    use alloc::sync::Arc;
    use alloc::vec;
    use alloc::vec::Vec;

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

    /// A third-party-style condition — the extension surface demonstration: a
    /// plain data struct, a `Display` for the wording, and a `DiagnosticInfo` impl,
    /// structurally identical to the library's own conditions.
    #[derive(Debug, Clone, PartialEq, Eq)]
    struct TestUnresolvable {
        name: String,
    }

    impl fmt::Display for TestUnresolvable {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "unresolvable command ‘{}’", self.name)
        }
    }

    impl crate::error::DiagnosticInfo for TestUnresolvable {
        const IDENTIFIER: &'static str = "test.engine.unresolvable-command";
    }

    // `Features = AllLangFeatures` (all test languages here declare it): the plain
    // block literals below only typecheck once the per-feature stores normalize to
    // the blocks themselves.
    fn min_rules<L: Lang<GroupTypeId = u32, Features = crate::state::AllLangFeatures>>(
    ) -> TokenRules<L> {
        TokenRules {
            whitespace: WhitespaceRules { enabled: true, chars: " \t\n".into() },
            paragraphs: ParagraphRules { enabled: true },
            groups: GroupRules {
                enabled: true,
                rules: Vec::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() },
        }
    }

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

    fn span(source: &Arc<Source>, range: core::ops::Range<usize>) -> crate::source::SourceSpan {
        crate::source::SourceSpan::new(source, range)
    }

    #[test]
    fn recover_is_tolerant_or_strict() {
        use crate::error::DiagnosticInfo;

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

        let mut session: ParserSession<PlainLang> = ParserSession::new();
        let condition = TestUnresolvable { name: "foo".into() };
        assert!(session
            .recover(
                Recovery::Tolerant,
                alloc::boxed::Box::new(condition.clone()),
                span(&source, 0..3),
            )
            .is_ok());
        assert_eq!(session.diagnostics.len(), 1);
        assert!(session.diagnostics.has_errors());
        let diagnostic = session.diagnostics.iter().next().unwrap();
        // The message is rendered from the payload's Display, on demand.
        assert_eq!(diagnostic.message(), "unresolvable command ‘foo’");
        assert_eq!(diagnostic.identifier(), TestUnresolvable::IDENTIFIER);

        let mut session: ParserSession<PlainLang> = ParserSession::new();
        let err = session
            .recover(
                Recovery::Strict,
                alloc::boxed::Box::new(condition.clone()),
                span(&source, 0..3),
            )
            .unwrap_err();
        // No PartialEq on the carriers ([§dd-dr:errors]): compare identifier and downcast fields.
        assert_eq!(err.identifier(), TestUnresolvable::IDENTIFIER);
        assert_eq!(err.data().downcast_ref::<TestUnresolvable>(), Some(&condition));
        assert_eq!(err.span().start(), 0);
        assert!(session.diagnostics.is_empty()); // strict mode records nothing
        // Display renders the condition's message; render() adds position info.
        assert_eq!(alloc::format!("{}", err), "unresolvable command ‘foo’");
        assert!(err.render().contains("line 1"));
    }

    #[test]
    fn parse_error_is_a_core_error() {
        fn assert_error<E: core::error::Error>() {}
        assert_error::<ParseError>();
    }

    /// A toy construct parser: reads one `Char` token via the context, stages a
    /// `Chars` node, returns no delta. Exercises the whole path — `ParseContext` over
    /// a `TokenListReader`, staging through the session's builder, `finish` into a
    /// `ParseResult`.
    struct OneCharParser;

    impl ConstructParser<PlainLang> for OneCharParser {
        type Output = crate::node::BuildId;

        fn parse(
            &mut self,
            cx: &mut ParseContext<'_, '_, PlainLang>,
        ) -> ConstructParserResult<
            PlainLang,
            (Self::Output, Option<Box<ParsingStateDelta<PlainLang>>>),
        > {
            let token = cx.tokens.next(&cx.state).expect("test token stream is error-free");
            let TokenKind::Char(_) = cx.tokens.token_kind(&token) else {
                panic!("test feeds a Char token")
            };
            let span = cx.tokens.source_span_of(&token);
            let id = cx.stage_node(
                NodeKind::chars(span.span()),
                span,
                cx.state.clone(),
                vec![],
            ).unwrap();
            Ok((id, None))
        }
    }

    #[test]
    fn construct_parser_plumbing_end_to_end() {
        let source: Arc<Source> = Arc::new(Source::new("q"));
        let st = state();
        let tokens: Vec<StdToken<PlainLang>> =
            vec![StdToken::char('q', Span::new(0, 1), Span::empty(0))];
        let mut reader = TokenListReader::new(&source, tokens);
        let mut session = ParserSession::new();
        let driver = StdParseDriver::new(Recovery::Tolerant, ());

        let mut cx =
            ParseContext::new(&mut reader, st.clone(), &mut session, &driver);
        let mut parser = OneCharParser;
        let (id, delta) = parser.parse(&mut cx).unwrap();
        assert!(delta.is_none());
        assert_eq!(cx.here().start(), 1);

        let result = session.finish(id).unwrap();
        assert!(result.diagnostics.is_empty());
        assert_eq!(result.tree.root().chars(), Some("q"));
    }

    #[test]
    fn context_recover_forwards_to_the_session() {
        let source: Arc<Source> = Arc::new(Source::new("x"));
        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 condition = TestUnresolvable { name: "boom".into() };
        assert!(cx.recover(condition, span(&source, 0..1)).is_ok());
        assert_eq!(session.diagnostics.len(), 1);
    }

    // --- the live frame stack ([§dd-dr:errors]) ----------------------------------------------------

    #[test]
    fn with_frame_pushes_pops_and_snapshots_into_diagnostics() {
        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("test frame"), span: span(&source, 0..1) };
        let inner_depth = cx.with_frame(frame, |cx| {
            // A condition recorded inside the frame carries it in its snapshot.
            cx.recover(TestUnresolvable { name: "x".into() }, span(&source, 1..2))
                .unwrap();
            cx.session.frames.len()
        });
        assert_eq!(inner_depth, 1);
        assert!(session.frames.is_empty(), "with_frame pops after the closure returns");

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

    #[test]
    fn with_frame_pops_on_the_err_path_and_strict_errors_carry_frames() {
        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);

        // The closure body aborts (strict recover); with_frame still pops — the pop
        // after the closure returns covers the Err path by construction.
        let outer =
            Frame { title: FrameTitle::Static("outer frame"), span: span(&source, 0..1) };
        let inner =
            Frame { title: FrameTitle::Static("inner frame"), span: span(&source, 1..2) };
        let result: Result<(), ParseError> = cx.with_frame(outer, |cx| {
            cx.with_frame(inner, |cx| {
                cx.recover(TestUnresolvable { name: "x".into() }, span(&source, 1..2))
            })
        });
        let err = result.unwrap_err();
        assert!(session.frames.is_empty(), "both frames popped on the Err path");

        // The strict ParseError snapshotted the stack, innermost first.
        let titles: Vec<&str> = err.frames().iter().map(|f| f.title()).collect();
        assert_eq!(titles, ["inner frame", "outer frame"]);
        assert!(err.render().contains("Inside:"));
    }

    #[test]
    fn snapshot_renders_quoted_and_callable_frame_titles() {
        use crate::spec::{FrameRole, StdCallableSpec};

        let source: Arc<Source> = Arc::new(Source::new(r"{\frac ab}"));
        let mut session: ParserSession<PlainLang> = ParserSession::new();
        let spec: Arc<dyn crate::spec::CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec::default());

        session.push_frame(Frame {
            title: FrameTitle::Quoted { label: "group", name: span(&source, 0..1) },
            span: span(&source, 0..1),
        });
        session.push_frame(Frame {
            title: FrameTitle::Callable {
                spec: Arc::clone(&spec),
                role: FrameRole::Invocation,
                name: span(&source, 1..6),
            },
            span: span(&source, 1..6),
        });
        session.push_frame(Frame {
            title: FrameTitle::Callable {
                spec,
                role: FrameRole::Argument { index: 1 },
                name: span(&source, 1..6),
            },
            span: span(&source, 8..8),
        });

        // Innermost first; titles rendered only here (the cold path), through the
        // spec's defaulted stack_frame_title hook for callables.
        let frames = session.snapshot_frames();
        let titles: Vec<&str> = frames.iter().map(|f| f.title()).collect();
        assert_eq!(
            titles,
            ["argument #2 of ‘\\frac’", "callable ‘\\frac’", "group ‘{’"]
        );
    }

    // --- the default driver's hook defaults ---------------------------------------------

    /// The command token of `source`, and the reader that produced it — what a
    /// resolver hook receives, since it reads the token through that reader. The scan
    /// runs under rules recognizing `\name` commands; resolution then consults
    /// whatever state the test built.
    fn command_token<'s>(
        source: &'s Arc<Source>,
    ) -> (StdToken<PlainLang>, StdTokenReader<'s>) {
        let mut rules: TokenRules<PlainLang> = min_rules();
        rules.commands.rules = vec![Arc::new(CommandRule {
            escape_char: '\\',
            name_chars: "abcdefghijklmnopqrstuvwxyz".into(),
        })];
        let scan_state = Arc::new(ParsingState::new(StateData {
            rules,
            scopes: ScopeStack::new(),
            mode: (),
            ext: (),
        }));
        let mut reader = StdTokenReader::new(source);
        let token = TokenReader::<'_, PlainLang>::next(&mut reader, &scan_state).unwrap();
        (token, reader)
    }

    #[test]
    fn default_resolve_command_reports_unimplemented_resolution() {
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new(r"\foo"));
        let (token, reader) = command_token(&source);
        let driver: StdParseDriver = StdParseDriver::new(Recovery::Strict, ());
        let resolved: CommandResolution<PlainLang> =
            driver.resolve_command(&st, &token, &reader).unwrap();
        match resolved {
            CommandResolution::Unresolved { detail } => {
                assert!(detail.unwrap().contains("command resolution is not implemented"));
            }
            CommandResolution::Resolved(_) => panic!("the default must not resolve"),
            CommandResolution::Failed { .. } => {
                panic!("the default must not fail operationally")
            }
        }
    }

    #[test]
    fn scopes_command_resolver_resolves_through_the_scope_stack() {
        use crate::scopes::Package;
        use crate::spec::StdCallableSpec;

        // A state whose scope stack defines `foo` under callable type 0.
        let mut package: Package<PlainLang> = Package::new("defs");
        package.insert(0u32, "foo", StdCallableSpec::default());
        let st = ParsingState::<PlainLang>::lang_initial_with_packages([package])
            .expect("seed state");

        let source: Arc<Source> = Arc::new(Source::new(r"\foo"));
        let (token, reader) = command_token(&source);
        // Through the strategy value carried by StdParseDriver…
        let driver: StdParseDriver<ScopesCommandResolver<PlainLang>> = StdParseDriver::new(
            Recovery::Strict,
            ScopesCommandResolver::<PlainLang> { command_type: 0u32 },
        );
        assert!(matches!(
            driver.resolve_command(&st, &token, &reader).unwrap(),
            CommandResolution::Resolved(_)
        ));
        // …and a clean miss carries the searched-providers detail.
        let other: Arc<Source> = Arc::new(Source::new(r"\bar"));
        let (miss, miss_reader) = command_token(&other);
        match driver.resolve_command(&st, &miss, &miss_reader).unwrap() {
            CommandResolution::Unresolved { detail } => {
                assert!(detail.unwrap().contains("defs"));
            }
            other => panic!("expected a clean miss, got {:?}", other),
        }
    }

    #[test]
    fn std_driver_source_resolver_defaults_none_and_is_configurable() {
        use crate::source::{MapResolver, SourceResolver};

        let bare: StdParseDriver = StdParseDriver::new(Recovery::Strict, ());
        assert!(ParseDriver::<PlainLang>::source_resolver(&bare).is_none());

        // By value: the builder shares internally.
        let by_value: StdParseDriver =
            StdParseDriver::new(Recovery::Strict, ()).with_source_resolver(MapResolver::new());
        assert!(ParseDriver::<PlainLang>::source_resolver(&by_value).is_some());

        // Pre-shared Arcs pass through without double-wrap (pointer identity holds).
        let premade: Arc<dyn SourceResolver> = Arc::new(MapResolver::new());
        let witness = Arc::clone(&premade);
        let shared: StdParseDriver =
            StdParseDriver::new(Recovery::Strict, ()).with_source_resolver(premade);
        assert!(Arc::ptr_eq(shared.source_resolver.as_ref().unwrap(), &witness));
    }

    #[test]
    fn default_paragraph_break_node_is_spanned_whitespace_chars() {
        let st = state();
        let source: Arc<crate::source::Source> =
            Arc::new(crate::source::Source::new("x  \n\nz"));
        let break_span = crate::source::SourceSpan::new(&source, 3..5);
        let driver: StdParseDriver = StdParseDriver::new(Recovery::Strict, ());
        let kind: NodeKind<PlainLang> =
            driver.make_paragraph_break_node(&st, &break_span);
        match kind {
            NodeKind::Chars { content, .. } => {
                // Span-backed over the full break span (newlines included), per the
                // whitespace-as-chars invariant ([§dd-dr:nodes]).
                assert!(!content.is_owned());
                assert_eq!(content.resolve(&source), "\n\n");
            }
            other => panic!("expected a Chars kind, got {:?}", other),
        }
    }

    // --- the session-mediated derivation seam (6.3, DESIGN_RATIONALE.md [§dd-dr:parsers-engine]) ----------

    #[derive(Debug, Default)]
    struct Observed {
        transitions: usize,
    }

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

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

    /// ObserverLang's driver: counts every transition observation (the hook is on the driver, not on `Lang`).
    #[derive(Debug, Clone, Copy, Default)]
    struct ObserverDriver;
    impl ParseDriver<ObserverLang> for ObserverDriver {
        fn observe_transition(
            &self,
            ext: &mut Observed,
            _diagnostics: &mut Diagnostics,
            _prev: &ParsingState<ObserverLang>,
            _new: &ParsingState<ObserverLang>,
            _delta: &ParsingStateDelta<ObserverLang>,
        ) -> Result<(), ParseError> {
            ext.transitions += 1;
            Ok(())
        }
    }

    #[test]
    fn derived_state_is_data_equivalent_observed_and_memoizes_rules_only_deltas() {
        let base: Arc<ParsingState<ObserverLang>> = state();
        let delta = ParsingStateDelta::new().rules(TokenRulesOverrides {
            comments: CommentOverrides::disable(),
            ..TokenRulesOverrides::default()
        });
        let mut session: ParserSession<ObserverLang> = ParserSession::new();

        let via_session = session.derived_state(&ObserverDriver, &base, &delta).unwrap();
        // Data-equivalent to the pure transition…
        assert_eq!(via_session.rules(), base.derived(&delta).unwrap().rules());
        // …with the transition event observed.
        assert_eq!(session.ext.transitions, 1);

        // Rules-only deltas are memoized: the identical derivation returns the shared
        // state, and the transition is still observed (hits included).
        let again = session.derived_state(&ObserverDriver, &base, &delta).unwrap();
        assert!(Arc::ptr_eq(&via_session, &again));
        assert_eq!(session.ext.transitions, 2);

        // A different base misses (keys carry the base's identity).
        let other_base = Arc::new(base.derived(&ParsingStateDelta::new()).unwrap());
        let elsewhere = session.derived_state(&ObserverDriver, &other_base, &delta).unwrap();
        assert!(!Arc::ptr_eq(&via_session, &elsewhere));
    }

    #[test]
    fn derived_state_keys_payloads_by_arc_identity() {
        let base: Arc<ParsingState<ObserverLang>> = state();
        let rule: Arc<GroupRule<ObserverLang>> =
            Arc::new(GroupRule { group_type: 5, open: "[".into(), close: "]".into() });
        let mut session: ParserSession<ObserverLang> = ParserSession::new();

        // The optional-argument shape: a groups override whose Vec is rebuilt per call
        // but whose *elements* are the same Arcs — hits (elementwise identity keying).
        let delta_a = ParsingStateDelta::new().rules(TokenRulesOverrides {
            groups: GroupOverrides {
                rules: Some(vec![Arc::clone(&rule)]),
                ..GroupOverrides::default()
            },
            ..TokenRulesOverrides::default()
        });
        let delta_b = ParsingStateDelta::new().rules(TokenRulesOverrides {
            groups: GroupOverrides {
                rules: Some(vec![Arc::clone(&rule)]),
                ..GroupOverrides::default()
            },
            ..TokenRulesOverrides::default()
        });
        let first = session.derived_state(&ObserverDriver, &base, &delta_a).unwrap();
        let second = session.derived_state(&ObserverDriver, &base, &delta_b).unwrap();
        assert!(Arc::ptr_eq(&first, &second));

        // A value-equal but Arc-distinct payload misses: identity keying is
        // conservative, never falsely shared.
        let equal_rule: Arc<GroupRule<ObserverLang>> =
            Arc::new(GroupRule { group_type: 5, open: "[".into(), close: "]".into() });
        let delta_c = ParsingStateDelta::new().rules(TokenRulesOverrides {
            groups: GroupOverrides {
                rules: Some(vec![equal_rule]),
                ..GroupOverrides::default()
            },
            ..TokenRulesOverrides::default()
        });
        let third = session.derived_state(&ObserverDriver, &base, &delta_c).unwrap();
        assert!(!Arc::ptr_eq(&first, &third));
    }

    #[test]
    fn derived_state_memoizes_mode_overrides_by_value() {
        let base: Arc<ParsingState<ObserverLang>> = state();
        let mut session: ParserSession<ObserverLang> = ParserSession::new();

        // A mode override is memo-key material by *value* (modes are `Copy + Eq`
        // vocabulary, unlike the identity-keyed rule payloads): two independently
        // built deltas hit one entry, with the hits observed.
        let math = session.derived_state(&ObserverDriver, &base, &ParsingStateDelta::new().mode(TestMode::Math)).unwrap();
        assert_eq!(math.mode(), TestMode::Math);
        let again = session.derived_state(&ObserverDriver, &base, &ParsingStateDelta::new().mode(TestMode::Math)).unwrap();
        assert!(Arc::ptr_eq(&math, &again));
        assert_eq!(session.ext.transitions, 2);

        // Distinct modes are distinct keys — no false sharing on the same base (and a
        // mode-less delta, `mode: None`, is a third key still).
        let text = session.derived_state(&ObserverDriver, &base, &ParsingStateDelta::new().mode(TestMode::Text)).unwrap();
        assert!(!Arc::ptr_eq(&math, &text));
        assert_eq!(text.mode(), TestMode::Text);

        // Mode and rules overrides combine into one keyed derivation.
        let overrides = || TokenRulesOverrides {
            comments: CommentOverrides::disable(),
            ..TokenRulesOverrides::default()
        };
        let combo = session.derived_state(
            &ObserverDriver,
            &base,
            &ParsingStateDelta::new().mode(TestMode::Math).rules(overrides()),
        ).unwrap();
        assert_eq!(combo.mode(), TestMode::Math);
        assert!(!combo.rules().comments_enabled());
        assert!(!Arc::ptr_eq(&math, &combo)); // differs from the mode-only entry
        let combo_again = session.derived_state(
            &ObserverDriver,
            &base,
            &ParsingStateDelta::new().mode(TestMode::Math).rules(overrides()),
        ).unwrap();
        assert!(Arc::ptr_eq(&combo, &combo_again));

        // Carrying an ext replacement still disables the memo, mode or not (same for
        // events and library pushes: those payloads have no identity to key on).
        let with_ext = ParsingStateDelta::new().mode(TestMode::Math).ext(());
        let fresh_a = session.derived_state(&ObserverDriver, &base, &with_ext).unwrap();
        let fresh_b = session.derived_state(&ObserverDriver, &base, &with_ext).unwrap();
        assert!(!Arc::ptr_eq(&fresh_a, &fresh_b));
    }

    #[test]
    fn derived_state_never_memoizes_ext_or_event_deltas() {
        let base: Arc<ParsingState<ObserverLang>> = state();
        let mut session: ParserSession<ObserverLang> = ParserSession::new();

        // An event payload has no identity to key on — always a fresh derivation.
        let with_event = ParsingStateDelta::new().event(());
        let first = session.derived_state(&ObserverDriver, &base, &with_event).unwrap();
        let second = session.derived_state(&ObserverDriver, &base, &with_event).unwrap();
        assert!(!Arc::ptr_eq(&first, &second));

        // Same for an ext replacement.
        let with_ext = ParsingStateDelta::new().ext(());
        let third = session.derived_state(&ObserverDriver, &base, &with_ext).unwrap();
        let fourth = session.derived_state(&ObserverDriver, &base, &with_ext).unwrap();
        assert!(!Arc::ptr_eq(&third, &fourth));

        // All four transitions were observed.
        assert_eq!(session.ext.transitions, 4);
    }

    #[test]
    fn group_interior_state_memoizes_by_pointer_identity_and_observes_hits() {
        let base: Arc<ParsingState<ObserverLang>> = state();
        let rule: Arc<GroupRule<ObserverLang>> =
            Arc::new(GroupRule { group_type: 0, open: "{".into(), close: "}".into() });
        let mut session: ParserSession<ObserverLang> = ParserSession::new();

        let first = session.group_interior_state(&ObserverDriver, &base, &rule).unwrap();
        assert!(first
            .rules()
            .expecting_group_close()
            .is_some_and(|expected| Arc::ptr_eq(expected, &rule)));

        // Memo hit: the same interior Arc, and the transition event still observed.
        let second = session.group_interior_state(&ObserverDriver, &base, &rule).unwrap();
        assert!(Arc::ptr_eq(&first, &second));
        assert_eq!(session.ext.transitions, 2);

        // Keys are pointer identities: an equal-but-distinct rule Arc is a fresh
        // derivation, and so is a distinct base.
        let equal_rule: Arc<GroupRule<ObserverLang>> =
            Arc::new(GroupRule { group_type: 0, open: "{".into(), close: "}".into() });
        let third = session.group_interior_state(&ObserverDriver, &base, &equal_rule).unwrap();
        assert!(!Arc::ptr_eq(&first, &third));
        let other_base = Arc::new(base.derived(&ParsingStateDelta::new()).unwrap());
        let fourth = session.group_interior_state(&ObserverDriver, &other_base, &rule).unwrap();
        assert!(!Arc::ptr_eq(&first, &fourth));
        assert_eq!(session.ext.transitions, 4);
    }

    // --- the driver seam (7.2): descent deltas, custom policy, typed helper access -----

    /// A lang whose driver enters Math mode for group class 7 — the D2 math plug at
    /// the engine seam — while counting hook runs (the counter never influences the
    /// returned delta, so the purity contract holds).
    #[derive(Debug, Clone, Copy)]
    struct DescentLang;
    impl Lang for DescentLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = TestMode;
        type StateExt = ();
        type Event = ();
        type SessionExt = Observed;
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = ();
        type InvocationSyntax = ();
        type Driver = DescentDriver;
        fn make_node_ext(
            _kind: &crate::node::NodeKind<Self>,
            _span: &crate::source::SourceSpan<Self::SourceOrigin>,
            _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
            _children: crate::node::StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    #[derive(Debug, Default)]
    struct DescentDriver {
        hook_runs: core::sync::atomic::AtomicUsize,
    }

    impl ParseDriver<DescentLang> for DescentDriver {
        fn observe_transition(
            &self,
            ext: &mut Observed,
            _diagnostics: &mut Diagnostics,
            _prev: &ParsingState<DescentLang>,
            _new: &ParsingState<DescentLang>,
            _delta: &ParsingStateDelta<DescentLang>,
        ) -> Result<(), ParseError> {
            ext.transitions += 1;
            Ok(())
        }

        fn group_interior_delta(
            &self,
            _base: &ParsingState<DescentLang>,
            rule: &Arc<GroupRule<DescentLang>>,
        ) -> Option<ParsingStateDelta<DescentLang>> {
            self.hook_runs.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
            (rule.group_type == 7).then(|| {
                // The delta also tries to clear the expected close — the descent
                // invariant must win over it.
                ParsingStateDelta::new().mode(TestMode::Math).rules(TokenRulesOverrides {
                    groups: GroupOverrides {
                        expecting_close: Some(None),
                        ..GroupOverrides::default()
                    },
                    ..TokenRulesOverrides::default()
                })
            })
        }
    }

    #[test]
    fn group_interior_state_merges_the_driver_delta_on_miss_only() {
        use core::sync::atomic::Ordering;

        let base: Arc<ParsingState<DescentLang>> = state();
        let math_rule: Arc<GroupRule<DescentLang>> =
            Arc::new(GroupRule { group_type: 7, open: "$".into(), close: "$".into() });
        let brace: Arc<GroupRule<DescentLang>> =
            Arc::new(GroupRule { group_type: 0, open: "{".into(), close: "}".into() });
        let mut session: ParserSession<DescentLang> = ParserSession::new();
        let driver = DescentDriver::default();

        // A math-class descent: the driver's delta enters Math mode, and the descent
        // invariant wins over the delta's expecting-close sabotage.
        let interior = session.group_interior_state(&driver, &base, &math_rule).unwrap();
        assert_eq!(interior.mode(), TestMode::Math);
        assert!(interior
            .rules()
            .expecting_group_close()
            .is_some_and(|expected| Arc::ptr_eq(expected, &math_rule)));
        assert_eq!(driver.hook_runs.load(Ordering::Relaxed), 1);

        // Memo hit: the same interior Arc, the hook NOT re-run (miss-only contract),
        // the transition observed on the hit too.
        let again = session.group_interior_state(&driver, &base, &math_rule).unwrap();
        assert!(Arc::ptr_eq(&interior, &again));
        assert_eq!(driver.hook_runs.load(Ordering::Relaxed), 1);
        assert_eq!(session.ext.transitions, 2);

        // A class the hook declines keeps the canonical descent (and its own entry).
        let plain = session.group_interior_state(&driver, &base, &brace).unwrap();
        assert_eq!(plain.mode(), TestMode::Text);
        assert_eq!(driver.hook_runs.load(Ordering::Relaxed), 2);

        // No cross-contamination with the general memo: a hand-built expecting-close
        // delta through derived_state yields the *undecorated* interior — the two
        // maps key different operations.
        let hand_built = ParsingStateDelta::new().rules(TokenRulesOverrides {
            groups: GroupOverrides {
                expecting_close: Some(Some(Arc::clone(&math_rule))),
                ..GroupOverrides::default()
            },
            ..TokenRulesOverrides::default()
        });
        let undriven = session.derived_state(&driver, &base, &hand_built).unwrap();
        assert_eq!(undriven.mode(), TestMode::Text);
        assert!(!Arc::ptr_eq(&undriven, &interior));
    }

    #[test]
    fn custom_driver_recover_policy_replaces_strict_tolerant() {
        // The policy space beyond the enum: a driver whose recover suppresses every
        // condition — nothing recorded, nothing aborted.
        #[derive(Debug, Clone, Copy)]
        struct QuietLang;
        impl Lang for QuietLang {
            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 = QuietDriver;
            fn make_node_ext(
                _kind: &crate::node::NodeKind<Self>,
                _span: &crate::source::SourceSpan<Self::SourceOrigin>,
                _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
                _children: crate::node::StagedChildren<'_, Self>,
            ) -> Result<(), crate::node::NodeBuildError> {
                Ok(())
            }
        }

        #[derive(Debug, Clone, Copy)]
        struct QuietDriver;
        impl ParseDriver<QuietLang> for QuietDriver {
            fn recover(
                &self,
                _session: &mut ParserSession<QuietLang>,
                _state: &ParsingState<QuietLang>,
                _data: Box<dyn DiagnosticData>,
                _span: SourceSpan<Option<String>>,
            ) -> Result<(), ParseError> {
                Ok(())
            }
        }

        let source: Arc<Source> = Arc::new(Source::new("x"));
        let st: Arc<ParsingState<QuietLang>> = state();
        let mut reader: TokenListReader<'_, QuietLang> = TokenListReader::new(&source, vec![]);
        let mut session = ParserSession::new();
        let driver = QuietDriver;
        let mut cx = ParseContext::new(&mut reader, st, &mut session, &driver);

        // The funnel consults the driver: the condition vanishes — no diagnostic, no
        // abort — under a policy neither Strict nor Tolerant could express.
        assert!(cx.recover(TestUnresolvable { name: "gone".into() }, span(&source, 0..1)).is_ok());
        assert!(session.diagnostics.is_empty());
    }

    #[test]
    fn preset_helper_methods_are_reachable_through_the_typed_driver_field() {
        // The zero-downcast access pattern: `ParseContext.driver` is `&L::Driver`,
        // concretely typed, so inherent methods (the preset-helper surface — a future
        // `LatexlikeDriver::load_package`) are directly callable inside parsers.
        #[derive(Debug, Clone, Copy)]
        struct HelperLang;
        impl Lang for HelperLang {
            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 = HelperDriver;
            fn make_node_ext(
                _kind: &crate::node::NodeKind<Self>,
                _span: &crate::source::SourceSpan<Self::SourceOrigin>,
                _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
                _children: crate::node::StagedChildren<'_, Self>,
            ) -> Result<(), crate::node::NodeBuildError> {
                Ok(())
            }
        }

        #[derive(Debug, Clone, Copy)]
        struct HelperDriver {
            answer: u32,
        }
        impl ParseDriver<HelperLang> for HelperDriver {}
        impl HelperDriver {
            /// An inherent helper — not on the `ParseDriver` trait.
            fn preset_helper(&self) -> u32 {
                self.answer
            }
        }

        let source: Arc<Source> = Arc::new(Source::new(""));
        let st: Arc<ParsingState<HelperLang>> = state();
        let mut reader: TokenListReader<'_, HelperLang> = TokenListReader::new(&source, vec![]);
        let mut session = ParserSession::new();
        let driver = HelperDriver { answer: 42 };
        let cx = ParseContext::new(&mut reader, st, &mut session, &driver);
        assert_eq!(cx.driver.preset_helper(), 42);
    }

    #[test]
    fn session_ext_is_default_initialized() {
        let session: ParserSession<ObserverLang> = ParserSession::new();
        assert_eq!(session.ext.transitions, 0);
    }

    // --- scope-op fallibility at the session seam (7.3) --------------------------------

    #[test]
    fn scope_op_deltas_derive_fresh_and_failures_are_neither_cached_nor_observed() {
        use crate::scopes::{Package, ScopeOp};

        let base: Arc<ParsingState<ObserverLang>> = state();
        let mut session: ParserSession<ObserverLang> = ParserSession::new();

        // A delta carrying scope ops is never memoized: two identical derivations are
        // distinct states (the ops-carrying gate, extending the ext/events rule)…
        let push = || {
            ParsingStateDelta::new()
                .push_provider(Arc::new(Package::<ObserverLang>::new("p")))
        };
        let first = session.derived_state(&ObserverDriver, &base, &push()).unwrap();
        let second = session.derived_state(&ObserverDriver, &base, &push()).unwrap();
        assert!(!Arc::ptr_eq(&first, &second));
        assert_eq!(session.ext.transitions, 2);

        // …and a failing delta returns the mechanical DeriveError with nothing
        // committed: no memo entry, no observation.
        let failing = ParsingStateDelta::new().scope_op(ScopeOp::Unload { name: "absent".into() });
        let SessionDeriveError::Derive(error) =
            session.derived_state(&ObserverDriver, &base, &failing).unwrap_err()
        else {
            panic!("expected the derivation-failure arm");
        };
        assert_eq!(error.failures.len(), 1);
        assert_eq!(session.ext.transitions, 2);
        let SessionDeriveError::Derive(error) =
            session.derived_state(&ObserverDriver, &base, &failing).unwrap_err()
        else {
            panic!("expected the derivation-failure arm");
        };
        assert_eq!(error.failures.len(), 1); // fails identically — nothing was cached
        assert_eq!(session.ext.transitions, 2);
    }

    /// A driver whose descent delta carries a *failing* scope op for group class 9 —
    /// the group-interior failure path.
    #[derive(Debug, Clone, Copy, Default)]
    struct FailingDescentDriver;

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

    impl ParseDriver<FailingDescentLang> for FailingDescentDriver {
        fn observe_transition(
            &self,
            ext: &mut Observed,
            _diagnostics: &mut Diagnostics,
            _prev: &ParsingState<FailingDescentLang>,
            _new: &ParsingState<FailingDescentLang>,
            _delta: &ParsingStateDelta<FailingDescentLang>,
        ) -> Result<(), ParseError> {
            ext.transitions += 1;
            Ok(())
        }

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

    #[test]
    fn group_interior_failures_repeat_uncached_and_the_recovered_state_expects_the_close() {
        let base: Arc<ParsingState<FailingDescentLang>> = state();
        let bad: Arc<GroupRule<FailingDescentLang>> =
            Arc::new(GroupRule { group_type: 9, open: "$".into(), close: "$".into() });
        let good: Arc<GroupRule<FailingDescentLang>> =
            Arc::new(GroupRule { group_type: 0, open: "{".into(), close: "}".into() });
        let mut session: ParserSession<FailingDescentLang> = ParserSession::new();

        let SessionDeriveError::Derive(error) =
            session.group_interior_state(&FailingDescentDriver, &base, &bad).unwrap_err()
        else {
            panic!("expected the derivation-failure arm");
        };
        // The recovered interior still satisfies the descent invariant (the forced
        // expecting-close is an override, not an op) — safe to parse under.
        assert!(error
            .recovered
            .rules()
            .expecting_group_close()
            .is_some_and(|expected| Arc::ptr_eq(expected, &bad)));
        // The carried delta is the *merged* descent delta (op + forced close).
        assert_eq!(error.delta.scope_ops.len(), 1);
        assert!(error.delta.rules.groups.expecting_close.is_some());
        assert_eq!(session.ext.transitions, 0);

        // Failures are not cached: the identical descent fails afresh…
        assert!(session.group_interior_state(&FailingDescentDriver, &base, &bad).is_err());
        assert_eq!(session.ext.transitions, 0);

        // …while an unaffected class memoizes as usual.
        let ok_a = session.group_interior_state(&FailingDescentDriver, &base, &good).unwrap();
        let ok_b = session.group_interior_state(&FailingDescentDriver, &base, &good).unwrap();
        assert!(Arc::ptr_eq(&ok_a, &ok_b));
        assert_eq!(session.ext.transitions, 2);
    }

    // --- the enclosing-state stack + context-dependent event lowering (E4) -------------

    /// A lang with both event classes: `NeedsContext` is context-dependent (the
    /// driver lowers it; finalize refuses it loudly), `Plain` is context-free
    /// (finalize counts it into the state ext).
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum CtxEvent {
        NeedsContext,
        Plain,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    struct CtxSeen {
        plain_events: usize,
    }

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

        fn finalize_transition(
            new: &mut StateData<CtxLang>,
            _prev: &ParsingState<CtxLang>,
            events: &[CtxEvent],
        ) -> Result<(), crate::state::FinalizeError> {
            for event in events {
                match event {
                    // The two-class contract's loud arm: a context-requiring event
                    // reaching the bare choke point is refused, never dropped.
                    CtxEvent::NeedsContext => {
                        return Err(crate::state::FinalizeError::new(
                            "the NeedsContext event requires the enclosing-state \
                             stack — derive through a parse context",
                        ));
                    }
                    CtxEvent::Plain => new.ext.plain_events += 1,
                }
            }
            Ok(())
        }
        fn make_node_ext(
            _kind: &crate::node::NodeKind<Self>,
            _span: &crate::source::SourceSpan<Self::SourceOrigin>,
            _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
            _children: crate::node::StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    /// Lowers `NeedsContext` into a forbidden-chars patch encoding the lent
    /// stack's depth (proving the hook saw the live stack); `lower: false`
    /// simulates a mis-wired driver that fails to lower; `fail_events: true`
    /// simulates a lowering hook whose own code fails operationally (the
    /// hook-fallibility abort channel).
    #[derive(Debug, Clone, Copy)]
    struct CtxDriver {
        lower: bool,
        fail_events: bool,
    }
    impl ParseDriver<CtxLang> for CtxDriver {
        fn recovery(&self) -> Recovery {
            Recovery::Tolerant
        }
        fn resolve_state_event(
            &self,
            event: &CtxEvent,
            stack: &crate::state::ParsingStateStack<CtxLang>,
        ) -> Result<Option<ParsingStateDelta<CtxLang>>, ParseError> {
            if self.fail_events {
                let source: Arc<Source> = Arc::new(Source::new(""));
                return Err(ParseError::new(
                    crate::error::HookFailed::new("event backend is down", None),
                    crate::source::SourceSpan::new(&source, 0..0),
                ));
            }
            if !self.lower || *event != CtxEvent::NeedsContext {
                return Ok(None);
            }
            // A context-derived patch: depth many 'd's (any stack-derived fact
            // observable from the derived state works).
            let depth_marker: String = "d".repeat(stack.len());
            Ok(Some(ParsingStateDelta::new().rules(
                crate::state::TokenRulesOverrides {
                    forbidden_chars: crate::state::ForbiddenCharsOverrides {
                        chars: Some(depth_marker.into()),
                    },
                    ..Default::default()
                },
            )))
        }
    }

    fn ctx_context<'a, 's>(
        reader: &'a mut crate::token::TokenListReader<'s, CtxLang>,
        state: Arc<ParsingState<CtxLang>>,
        session: &'a mut ParserSession<CtxLang>,
        driver: &'a CtxDriver,
    ) -> ParseContext<'a, 's, CtxLang> {
        ParseContext::new(reader, state, session, driver)
    }

    #[test]
    fn with_parsing_state_maintains_the_session_stack() {
        let source: Arc<Source> = Arc::new(Source::new(""));
        let outer: Arc<ParsingState<CtxLang>> =
            Arc::new(ParsingState::lang_initial().expect("seed state"));
        let inner = Arc::new(outer.derived(&ParsingStateDelta::new()).unwrap());
        let mut reader = crate::token::TokenListReader::new(&source, alloc::vec![]);
        let mut session = ParserSession::new();
        let driver = CtxDriver { lower: true, fail_events: false };
        let mut cx =
            ctx_context(&mut reader, Arc::clone(&outer), &mut session, &driver);

        assert_eq!(cx.session.state_stack().len(), 0);
        cx.with_parsing_state(Arc::clone(&outer), |cx| {
            assert_eq!(cx.session.state_stack().len(), 1);
            cx.with_parsing_state(Arc::clone(&inner), |cx| {
                assert_eq!(cx.session.state_stack().len(), 2);
                // Innermost-first, current state first.
                let innermost = cx.session.state_stack().iter().next().unwrap();
                assert!(Arc::ptr_eq(innermost, &inner));
            });
            assert_eq!(cx.session.state_stack().len(), 1);
            // The scoped state was restored along with the stack.
            assert!(Arc::ptr_eq(&cx.state, &outer));
        });
        assert_eq!(session.state_stack().len(), 0, "zero residue after the scope");
    }

    #[test]
    fn derive_state_lowers_context_dependent_events_through_the_stack() {
        let source: Arc<Source> = Arc::new(Source::new(""));
        let base: Arc<ParsingState<CtxLang>> =
            Arc::new(ParsingState::lang_initial().expect("seed state"));
        let mut reader = crate::token::TokenListReader::new(&source, alloc::vec![]);
        let mut session = ParserSession::new();
        let driver = CtxDriver { lower: true, fail_events: false };
        let mut cx =
            ctx_context(&mut reader, Arc::clone(&base), &mut session, &driver);

        let delta = ParsingStateDelta::new().event(CtxEvent::NeedsContext);
        // Outside any scope: the lend pushes the current state (depth 1).
        let derived = cx.derive_state(&delta).unwrap();
        assert_eq!(derived.rules().forbidden_chars(), "d");
        // The event was removed before finalize (no refusal, no Plain count).
        assert_eq!(derived.ext().plain_events, 0);

        // Inside a scope whose innermost entry IS the current state: no
        // duplicate push — the hook sees exactly the scoped depth.
        let scoped = cx.with_parsing_state(Arc::clone(&base), |cx| {
            cx.with_parsing_state(Arc::clone(&base), |cx| cx.derive_state(&delta))
        });
        assert_eq!(scoped.unwrap().rules().forbidden_chars(), "dd");

        // A current state that evolved past the innermost entry is lent on top.
        let evolved = Arc::new(base.derived(&ParsingStateDelta::new()).unwrap());
        let lent = cx.with_parsing_state(Arc::clone(&base), |cx| {
            cx.state = Arc::clone(&evolved); // a sibling after-effect
            cx.derive_state(&delta)
        });
        assert_eq!(lent.unwrap().rules().forbidden_chars(), "dd");
        assert_eq!(session.state_stack().len(), 0);
    }

    #[test]
    fn a_failing_resolve_state_event_aborts_and_pops_the_lent_stack_entry() {
        // The hook-fallibility contract: resolve_state_event's Err aborts even
        // under this driver's Tolerant recovery (there is no recovery channel at
        // the lowering seam), the hook's condition rides the abort, and the
        // enclosing-state stack entry lent for the loop is popped on the abort
        // path too (zero residue).
        let source: Arc<Source> = Arc::new(Source::new(""));
        let base: Arc<ParsingState<CtxLang>> =
            Arc::new(ParsingState::lang_initial().expect("seed state"));
        let mut reader = crate::token::TokenListReader::new(&source, alloc::vec![]);
        let mut session = ParserSession::new();
        let driver = CtxDriver { lower: true, fail_events: true };
        let mut cx =
            ctx_context(&mut reader, Arc::clone(&base), &mut session, &driver);

        let delta = ParsingStateDelta::new().event(CtxEvent::NeedsContext);
        let error = cx.derive_state(&delta).unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        assert_eq!(
            error.message(),
            "extension hook reported a failure: event backend is down"
        );
        assert_eq!(session.state_stack().len(), 0, "zero residue after the abort");
    }

    #[test]
    fn derive_state_keeps_context_free_events_for_finalize_and_the_author_wins() {
        let source: Arc<Source> = Arc::new(Source::new(""));
        let base: Arc<ParsingState<CtxLang>> =
            Arc::new(ParsingState::lang_initial().expect("seed state"));
        let mut reader = crate::token::TokenListReader::new(&source, alloc::vec![]);
        let mut session = ParserSession::new();
        let driver = CtxDriver { lower: true, fail_events: false };
        let mut cx =
            ctx_context(&mut reader, Arc::clone(&base), &mut session, &driver);

        // A context-free event passes through to finalize untouched…
        let plain = cx.derive_state(&ParsingStateDelta::new().event(CtxEvent::Plain)).unwrap();
        assert_eq!(plain.ext().plain_events, 1);

        // …mixed deltas lower only the context-dependent one…
        let mixed = cx
            .derive_state(
                &ParsingStateDelta::new()
                    .event(CtxEvent::Plain)
                    .event(CtxEvent::NeedsContext),
            )
            .unwrap();
        assert_eq!(mixed.ext().plain_events, 1);
        assert_eq!(mixed.rules().forbidden_chars(), "d");

        // …and the delta's own explicit override wins over the event's patch
        // (the delta author spoke).
        let authored = cx
            .derive_state(
                &ParsingStateDelta::new().event(CtxEvent::NeedsContext).rules(
                    crate::state::TokenRulesOverrides {
                        forbidden_chars: crate::state::ForbiddenCharsOverrides {
                            chars: Some("A".into()),
                        },
                        ..Default::default()
                    },
                ),
            )
            .unwrap();
        assert_eq!(authored.rules().forbidden_chars(), "A");
    }

    #[test]
    fn context_dependent_event_in_bare_derived_errors_loudly() {
        // Out of any parse, the two-class contract's loud arm: finalize refuses,
        // derived() folds the refusal into the DeriveError.
        let base: Arc<ParsingState<CtxLang>> =
            Arc::new(ParsingState::lang_initial().expect("seed state"));
        let error = base
            .derived(&ParsingStateDelta::new().event(CtxEvent::NeedsContext))
            .unwrap_err();
        assert!(error.failures.is_empty());
        let finalize_error = error.finalize_error.as_ref().unwrap();
        assert!(finalize_error.message().contains("NeedsContext"));
        assert!(error.to_string().contains("cannot build the parsing state"));
    }

    #[test]
    fn unlowered_context_event_in_parse_aborts_as_implementation_error() {
        // A driver that fails to lower a context-requiring event is extension
        // wiring gone wrong: derive_state aborts under ANY recovery policy
        // (CtxDriver reports Tolerant).
        let source: Arc<Source> = Arc::new(Source::new(""));
        let base: Arc<ParsingState<CtxLang>> =
            Arc::new(ParsingState::lang_initial().expect("seed state"));
        let mut reader = crate::token::TokenListReader::new(&source, alloc::vec![]);
        let mut session = ParserSession::new();
        let driver = CtxDriver { lower: false, fail_events: false };
        let mut cx =
            ctx_context(&mut reader, Arc::clone(&base), &mut session, &driver);

        let error = cx
            .derive_state(&ParsingStateDelta::new().event(CtxEvent::NeedsContext))
            .unwrap_err();
        use crate::error::DiagnosticInfo as _;
        assert_eq!(
            error.identifier(),
            crate::constructs::ImplementationError::IDENTIFIER
        );
        assert!(error.to_string().contains("NeedsContext"));
        assert!(session.diagnostics.is_empty(), "not a tolerant diagnostic");
    }
}