techy 0.1.4

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

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

use crate::error::DiagnosticInfo;
use crate::node::{ArgumentExt, ContentNodes, GroupData, NodeKind};
use crate::engine::{Frame, FrameTitle};
use crate::source::{SourceSpan, TextContent};
use crate::spec::{ArgumentParser, ArgumentSpec, ParsedArgumentNodes};
use crate::state::{
    CommandOverrides, CommentOverrides, FeaturePresence, ForbiddenCharsOverrides,
    GroupOverrides, Lang, LangFeatures, LangHasGroups, ParagraphOverrides, ParsingState,
    ParsingStateDelta, SpecialsOverrides, TokenRulesOverrides,
};
use crate::token::{GroupRule, StreamPosition, TokenEdge, TokenKind};

use super::argument_parsers::stage_pre_space;
use super::environment_parser::{
    EnvironmentBody, EnvironmentTerminatorSyntaxData, MissingEnvironmentTerminator,
    MissingTerminatorFound, NameGroup,
};
use super::{node_text_content, push_pre_space_text, push_token_text, ConstructParser, ConstructParserResult, ParseContext};

/// Condition: a delimited verbatim region ended before its closing delimiter appeared.
///
/// Raised at the end of the input, and when a token the reader could not read was
/// tolerated. Tolerant recovery keeps the content read so far and records an **empty**
/// close on the group node — the [`GroupData::close`] convention for a delimiter that
/// was never found.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.verbatim.unterminated-verbatim",
    message = "missing closing delimiter ‘{close}’ of the verbatim content"
)]
pub struct UnterminatedVerbatim {
    /// The closing delimiter that never appeared.
    pub close: String,
}

/// Condition: no opening delimiter could be read where a delimited verbatim argument
/// was mandatory.
///
/// Raised at the end of the input, and — when the parser prescribes a fixed pair — when
/// a different character stands at that position. Recovery reports the argument absent,
/// consuming nothing.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.verbatim.expected-verbatim-delimiter")]
pub struct ExpectedVerbatimDelimiter {
    /// The expected opening delimiter, when the parser prescribes one (`None` = any
    /// character would have done, but none was there).
    pub expected: Option<char>,
}

// Hand-written wording: the expected delimiter is quoted only when the parser
// prescribes one (a match, which the message format string cannot express).
impl fmt::Display for ExpectedVerbatimDelimiter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.expected {
            Some(open) => {
                write!(f, "expected opening delimiter ‘{open}’ for verbatim content")
            }
            None => write!(f, "expected a verbatim opening delimiter"),
        }
    }
}

/// The parsing state change that switches tokenization to raw reading, with
/// `terminator` as the string that ends the raw region.
///
/// Every tokenization feature the language has is turned off
/// ([`TokenRulesOverrides::disable_all`](crate::core::token::TokenRulesOverrides::disable_all))
/// and [`expecting_group_close`](crate::core::token::TokenRules::expecting_group_close)
/// is **replaced** by `terminator`. Under the derived state the content arrives as plain
/// [`Char`](TokenKind::Char) tokens and the terminator — `terminator`'s `close` string,
/// which must be non-empty to ever match — as a single
/// [`GroupClose`](TokenKind::GroupClose) token.
///
/// Turning the features off clears the forbidden-character set along with everything
/// else, so a character the language outlaws elsewhere reads as ordinary raw content
/// inside a verbatim region.
///
/// This is the building block for custom raw-content parsers: derive a state from it
/// with [`ParseContext::derive_state`] and read under that state. [`VerbatimArgumentParser`]
/// and [`VerbatimBodyParser`] do exactly that, and
/// [the construct parsers guide](crate::guide::construct_parsers#a-complete-takeover-parser)
/// works through a parser of one's own.
///
/// Requires a language with the groups feature ([`LangHasGroups`]): the terminator is
/// installed as the expected group close, which is groups data.
pub fn verbatim_state_delta<L: LangHasGroups>(
    terminator: Arc<GroupRule<L>>,
) -> ParsingStateDelta<L> {
    // The groups literal spreads from the *disabled* block, not from its default: a
    // whole-block field literal replaces everything `disable_all()` set up for that
    // block (the struct-update note on [`TokenRulesOverrides`]).
    ParsingStateDelta::new().rules(TokenRulesOverrides {
        groups: GroupOverrides {
            expecting_close: Some(Some(terminator)),
            ..GroupOverrides::disable()
        },
        ..TokenRulesOverrides::disable_all()
    })
}

/// Why the shared raw-content loop stopped. The two terminator-less endings are told
/// apart because they are diagnosed differently: only one of them is the end of the
/// input.
#[derive(Debug, Clone)]
enum RawContentStop<L: Lang> {
    /// The terminator was found and consumed, over this span.
    Terminator(SourceSpan<L::SourceOrigin>),
    /// The input ended before the terminator appeared.
    EndOfInput,
    /// A token the reader could not read was tolerated where the content was being
    /// read. The input has not ended.
    UnreadableToken,
}

/// The result of the shared raw-content loop: where the content ended, and what stopped
/// it — the consumed terminator's span among the answers.
struct RawContentEnd<L: Lang> {
    /// End of the raw content (= the terminator's start when one was found).
    content_end: StreamPosition<L>,
    /// The raw content's text as the reader answered it, token by token: `Some`
    /// exactly when the language does not obey span tiling
    /// ([`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`),
    /// where the tokens it was read from need not form one contiguous stretch of one
    /// source and a span could not describe their text. Covers exactly the stretch from
    /// where the loop started to [`content_end`](RawContentEnd::content_end).
    content_text: Option<String>,
    /// What stopped the loop; read the consumed terminator's span off it with
    /// [`terminator`](RawContentEnd::terminator).
    stop: RawContentStop<L>,
    /// Just past the consumed terminator — equal to `content_end` when the region
    /// ended without one.
    end: StreamPosition<L>,
}

impl<L: Lang> RawContentEnd<L> {
    /// The consumed terminator's span, or `None` when the region ended without one
    /// (end of input, or a tolerated unreadable token — [`stop`](RawContentEnd::stop)
    /// says which).
    fn terminator(&self) -> Option<&SourceSpan<L::SourceOrigin>> {
        match &self.stop {
            RawContentStop::Terminator(span) => Some(span),
            RawContentStop::EndOfInput | RawContentStop::UnreadableToken => None,
        }
    }
}

/// The raw content as node data on a `Chars` node spanning `content_span` — or `None`
/// when there is no content to stage (techy stages no empty chars node).
///
/// The text the loop accumulated where it accumulated one (a language with
/// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`), the exact
/// span slice otherwise — and *emptiness is decided the same way*: for such a language
/// the span is only what the reader described for the stretch the content was read
/// from, so whether there is content is the accumulated text's answer, not the span's.
fn raw_content_text<L: Lang, O>(
    raw_end: &RawContentEnd<L>,
    content_span: &SourceSpan<O>,
) -> Option<TextContent>
where
    O: crate::source::SourceOrigin,
{
    match &raw_end.content_text {
        Some(text) if text.is_empty() => None,
        Some(text) => Some(TextContent::Owned(text.as_str().into())),
        None if content_span.is_empty() => None,
        None => Some(TextContent::Spanned(content_span.span())),
    }
}

/// Read raw content under `state` (a [`verbatim_state_delta`]-derived state) until the
/// expected-close terminator, end of input, or a tolerated unreadable token, calling
/// `on_char` for every consumed content char (the delimited form's depth counter; it
/// returns `true` to treat a would-be terminator [`GroupClose`] as ordinary content —
/// see [`VerbatimArgumentParser`]'s pairing rule). The terminator, when found, is
/// consumed. Diagnosing the terminator-less endings is the caller's business.
///
/// For a language with
/// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false` the loop also
/// accumulates the content's text from what the reader says about each token it
/// consumes — the pre-space, the spelling (a character, or a delimiter read as
/// content), and the syntactic post-space — plus the pre-space of the token that ends
/// the content, which lies before `content_end` and is content too.
fn read_raw_content<L: Lang>(
    cx: &mut ParseContext<'_, '_, L>,
    state: &Arc<ParsingState<L>>,
    mut consume_close_as_content: impl FnMut(TokenKind<'_, L>) -> bool,
    mut on_char: impl FnMut(char),
) -> ConstructParserResult<L, RawContentEnd<L>> {
    let mut text: Option<String> = (!L::OBEYS_SPAN_TILING).then(String::new);
    loop {
        let Some(token) = cx.probe_token(state)? else {
            // A tolerated unreadable token: the standard reader has nothing left to
            // reject under the recipe state (the forbidden set is cleared with the
            // other features), but a custom reader may still fail. The verbatim
            // region ends here; the enclosing content loop re-reads the error and
            // applies its own token recovery (the probe protocol,
            // DESIGN_RATIONALE.md [§dd-dr:errors]).
            let here = cx.tokens.position_here();
            return Ok(RawContentEnd {
                content_end: here.clone(),
                content_text: text,
                stop: RawContentStop::UnreadableToken,
                end: here,
            });
        };
        let kind = cx.tokens.token_kind(&token);
        match kind {
            TokenKind::Char(c) => {
                on_char(c);
                push_token_text(&mut text, cx, &token, c.encode_utf8(&mut [0u8; 4]));
                cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
            }
            TokenKind::GroupClose { delim } => {
                cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
                if consume_close_as_content(kind) {
                    // A nested close read as ordinary content (the pairing rule):
                    // its bytes are part of the raw content.
                    push_token_text(&mut text, cx, &token, delim);
                    continue;
                }
                // The content ends at the terminator's `Start` edge, so whatever the
                // reader reports as the terminator's pre-space is content.
                push_pre_space_text(&mut text, cx, &token);
                return Ok(RawContentEnd {
                    content_end: cx.tokens.position_at(&token, TokenEdge::Start),
                    content_text: text,
                    stop: RawContentStop::Terminator(cx.tokens.source_span_of(&token)),
                    end: cx.tokens.position_at(&token, TokenEdge::EndPastPostSpace),
                });
            }
            TokenKind::EndOfStream => {
                // Same rule as for the terminator: the end-of-stream token's
                // pre-space (the input's trailing whitespace) is content.
                push_pre_space_text(&mut text, cx, &token);
                let end = cx.tokens.position_at(&token, TokenEdge::Start);
                return Ok(RawContentEnd {
                    content_end: end.clone(),
                    content_text: text,
                    stop: RawContentStop::EndOfInput,
                    end,
                });
            }
            other => {
                // The verbatim state disables every other recognizer; only a
                // misbehaving custom reader can produce these kinds here.
                return Err(cx.implementation_error(
                    format_args!(
                        "token reader produced a {} token under a verbatim state",
                        other
                    ),
                    cx.tokens.source_span_of(&token),
                ));
            }
        }
    }
}

/// The default auto-matched delimiter pairs of [`VerbatimArgumentParser`]:
/// `{`→`}`, `[`→`]`, `<`→`>`, `(`→`)`; any other opening character closes with
/// itself.
fn default_auto_delimiters() -> Vec<(char, char)> {
    vec![('{', '}'), ('[', ']'), ('<', '>'), ('(', ')')]
}

/// Parses a raw-text argument delimited by a pair of characters, `\verb|…|`-style (the
/// `v` argument code of the LaTeX-like preset).
///
/// The opening delimiter is the first character after optional whitespace, read raw
/// under a state where only whitespace scanning is left active. Comments are *not*
/// skipped — `%` is a perfectly good `\verb` delimiter — and the skipped whitespace is
/// staged like any other argument's surrounding noise. Any character the language can
/// tokenize will do, including one it declares forbidden in the surrounding state: the
/// delimiter is read raw, like the content it opens.
///
/// By default the closing delimiter is matched automatically: the paired closer for
/// `{ [ < (` — that table is replaceable with
/// [`with_auto_delimiters`](VerbatimArgumentParser::with_auto_delimiters) — and the same
/// character for anything else.
/// [`with_delimiters`](VerbatimArgumentParser::with_delimiters) prescribes a fixed pair
/// instead (the `v<c1><c2>` argument code).
///
/// When the two delimiters differ, nested occurrences of the opening character deepen a
/// depth counter and matching closers close it, so `\verb{a{b}c}` reads `a{b}c` whole.
/// With identical delimiters the first closer ends the region.
///
/// The content is read as raw text under the state derived through
/// [`verbatim_state_delta`], and staged as a
/// [`Group`](crate::core::node::NodeKind::Group) node of the configured class whose
/// single `Chars` child (omitted when the content is empty) holds the raw text and
/// records the verbatim state; the argument's content is the group's children.
///
/// Requires a language with the groups feature ([`LangHasGroups`]): the parser installs
/// its closing delimiter as an expected group close and stages a group node.
///
/// # Recovery
///
/// Both problems are reported through [`ParseContext::recover`], so a strict driver
/// aborts the parse and a tolerant one records the diagnostic and continues as
/// described:
///
/// - No opening delimiter where the argument starts — the input has ended, or a fixed
///   pair was prescribed and a different character stands there:
///   [`ExpectedVerbatimDelimiter`], and the argument is reported absent with nothing
///   consumed.
/// - The input ends, or a token the reader could not read is tolerated, before the
///   closing delimiter: [`UnterminatedVerbatim`], and the group records an empty
///   close.
pub struct VerbatimArgumentParser<L: Lang> {
    group_type: L::GroupTypeId,
    delimiters: Option<(char, char)>,
    auto_delimiters: Vec<(char, char)>,
}

impl<L: LangHasGroups> VerbatimArgumentParser<L> {
    /// Creates an auto-delimited verbatim argument parser staging groups of class
    /// `group_type` (`\verb|…|`, `\verb+…+`, …; the bare `v` argument code).
    pub fn new(group_type: L::GroupTypeId) -> VerbatimArgumentParser<L> {
        VerbatimArgumentParser {
            group_type,
            delimiters: None,
            auto_delimiters: default_auto_delimiters(),
        }
    }

    /// Prescribes a fixed delimiter pair (the `v<c1><c2>` argument code): the argument
    /// is provided only when `open` itself comes next.
    pub fn with_delimiters(mut self, open: char, close: char) -> Self {
        self.delimiters = Some((open, close));
        self
    }

    /// Replaces the table of automatically matched delimiter pairs (default: `{}`,
    /// `[]`, `<>`, `()`).
    ///
    /// An opening character that is not in the table closes with itself. Ignored when
    /// [`with_delimiters`](VerbatimArgumentParser::with_delimiters) prescribed a pair.
    pub fn with_auto_delimiters(
        mut self,
        pairs: impl IntoIterator<Item = (char, char)>,
    ) -> Self {
        self.auto_delimiters = pairs.into_iter().collect();
        self
    }

    /// The delta of the delimiter-discovery peek: the one raw character after optional
    /// whitespace — whitespace scanning stays as the base state has it, every other
    /// recognizer is off, an inherited close expectation is **cleared** (a `}` must be
    /// readable as a delimiter char even inside a braces group), and the
    /// forbidden-character set is cleared as well.
    ///
    /// Clearing the forbidden set matters twice over. The delimiter is read raw, like
    /// the content it opens (the same rule [`verbatim_state_delta`] applies to the
    /// content), so a character the language outlaws elsewhere is a perfectly good
    /// delimiter. And a probe must never make a token erroneous that the enclosing
    /// state accepts: the probe protocol leaves diagnosing a failed token to the
    /// enclosing content loop, which re-reads it under *its* state, so a character
    /// only the probe rejects would be reported by nobody. In the LaTeX-like preset
    /// `$` is forbidden inside math mode while also closing the math group, and the
    /// probe clears the close expectation — without clearing the forbidden set too,
    /// the probe would reject the `$` of `$\verb$a$$` and no diagnostic would ever be
    /// raised for it.
    fn delimiter_probe_delta(&self) -> ParsingStateDelta<L> {
        // Only the groups store is known transparent under `L: LangHasGroups`; the
        // other blocks are built through their store projections — a feature the
        // language does not have needs no disabling (nothing exists to recognize).
        ParsingStateDelta::new().rules(TokenRulesOverrides {
            paragraphs: <L::Features as LangFeatures>::Paragraphs::store_with(
                ParagraphOverrides::disable,
            ),
            groups: GroupOverrides {
                expecting_close: Some(None),
                ..GroupOverrides::disable()
            },
            commands: <L::Features as LangFeatures>::Commands::store_with(
                CommandOverrides::disable,
            ),
            comments: <L::Features as LangFeatures>::Comments::store_with(
                CommentOverrides::disable,
            ),
            specials: <L::Features as LangFeatures>::Specials::store_with(
                SpecialsOverrides::disable,
            ),
            forbidden_chars: <L::Features as LangFeatures>::ForbiddenChars::store_with(
                ForbiddenCharsOverrides::disable,
            ),
            ..TokenRulesOverrides::default()
        })
    }
}

impl<L: LangHasGroups> ArgumentParser<L> for VerbatimArgumentParser<L>
where
    ArgumentExt<L>: Default,
{
    fn parse_argument(
        &self,
        cx: &mut ParseContext<'_, '_, L>,
        _spec: &ArgumentSpec<L>,
    ) -> ConstructParserResult<L, Option<ParsedArgumentNodes<L>>> {
        // Read the opening delimiter: one raw char after optional whitespace. Each
        // "argument absent" exit below consumes nothing: the probe never moves the
        // stream, so the reader is left exactly where this parse started.
        let probe_state = cx.derive_state(&self.delimiter_probe_delta())?;
        let Some(token) = cx.probe_token(&probe_state)? else {
            return Ok(None);
        };
        let open = match cx.tokens.token_kind(&token) {
            TokenKind::Char(c) => c,
            // Under the probe state only `Char` and `EndOfStream` exist; treat
            // anything else like end of input (a misbehaving reader is caught by the
            // content loop's implementation-error arm, not the recovery path).
            _ => {
                let span = cx.tokens.source_span_of(&token);
                cx.recover(
                    ExpectedVerbatimDelimiter::new(self.delimiters.map(|(open, _)| open)),
                    span,
                )?;
                return Ok(None);
            }
        };
        let close = match self.delimiters {
            Some((expected_open, close)) => {
                if open != expected_open {
                    let span = cx.tokens.source_span_of(&token);
                    cx.recover(ExpectedVerbatimDelimiter::new(expected_open), span)?;
                    return Ok(None);
                }
                close
            }
            None => self
                .auto_delimiters
                .iter()
                .find(|(auto_open, _)| *auto_open == open)
                .map(|(_, auto_close)| *auto_close)
                .unwrap_or(open),
        };

        // Committed: the whitespace becomes region noise, the delimiter is consumed.
        let mut nodes = Vec::new();
        stage_pre_space(cx, &mut nodes, &token)?;
        cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
        let open_span = cx.tokens.source_span_of(&token);
        let open_start = cx.tokens.position_at(&token, TokenEdge::Start);
        let content_start = cx.tokens.position_here();

        // The raw-content read under the recipe state, with the pairing depth counter:
        // nested opens (paired delimiters only) deepen, matched closes surface.
        let close_rule = Arc::new(GroupRule {
            group_type: self.group_type,
            open: String::from(open),
            close: String::from(close),
        });
        let content_state = cx.derive_state(&verbatim_state_delta(Arc::clone(&close_rule)))?;
        let paired = open != close;
        // Shared by the two `read_raw_content` callbacks (each captures it by `&`).
        let depth = core::cell::Cell::new(1usize);
        let raw_end = read_raw_content(
            cx,
            &content_state,
            |_close_kind| {
                depth.set(depth.get() - 1);
                depth.get() > 0
            },
            |c| {
                if paired && c == open {
                    depth.set(depth.get() + 1);
                }
            },
        )?;
        if raw_end.terminator().is_none() {
            cx.recover(UnterminatedVerbatim::new(String::from(close)), open_span.clone())?;
        }

        // The decided group + chars shape (module docs): the chars node under the
        // verbatim state, the group under the surrounding state.
        let mut children = Vec::new();
        let content_span = cx.source_span_within(&content_start, &raw_end.content_end)?;
        if let Some(content) = raw_content_text(&raw_end, &content_span) {
            let id = cx
                .stage_node(
                    NodeKind::chars(content),
                    content_span.clone(),
                    Arc::clone(&content_state),
                    vec![],
                )
                .map_err(|error| cx.staging_error(error, content_span))?;
            children.push(id);
        }
        let child_count = children.len() as u32;
        let group_span = cx.source_span_within(&open_start, &raw_end.end)?;
        // The recorded delimiters are node data: a span only where the reader's answer
        // lies in the node's own source, the text itself otherwise.
        let data = GroupData {
            group_type: Some(self.group_type),
            open: node_text_content(&open_span, &group_span),
            close: raw_end
                .terminator()
                .map(|span| node_text_content(span, &group_span))
                .unwrap_or_else(TextContent::empty),
        };
        let group = cx
            .stage_node(
                NodeKind::group(data),
                group_span.clone(),
                Arc::clone(&cx.state),
                children,
            )
            .map_err(|error| cx.staging_error(error, group_span))?;
        nodes.push(group);
        Ok(Some(ParsedArgumentNodes::new(
            nodes,
            ContentNodes::InChildrenOf(group, 0..child_count),
            Default::default(),
        )))
    }

    /// The delimited region is mandatory: absent is a diagnosed recovery, not a valid
    /// match.
    fn can_match_empty(&self) -> bool {
        false
    }
}

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

/// What ends a verbatim body: a literal string, or a stop command repeating the
/// invocation's name, such as `\end{verbatim}`.
///
/// Both shapes are **read** the same way: [`VerbatimBodyParser`] composes one raw
/// terminator string out of the variant's fields and installs it as the body state's
/// expected group close ([`verbatim_state_delta`]), so the whole terminator arrives as a
/// single token. A raw body never tokenizes its terminator, whatever shape it was given
/// in, and the composed string is matched character for character — `\end {verbatim}`,
/// with a space in it, does not end the body.
///
/// The shapes differ only in what the parser reports for the consumed terminator
/// ([`EnvironmentBody::terminator`]): a literal one has no structure to report beyond
/// its span ([`Literal`](EnvironmentTerminatorSyntaxData::Literal)), whereas a stop
/// command was composed from known pieces and reports them as
/// [`Scanned`](EnvironmentTerminatorSyntaxData::Scanned) facts — the same shape
/// [`EnvironmentBodyParser`](super::EnvironmentBodyParser) reports after tokenizing a
/// terminator, so a consumer that records how the source was written needs no separate
/// case for raw bodies.
pub enum VerbatimBodyTerminator<'p, L : Lang> {
    /// The terminator given as one raw string, with no further structure to it.
    Literal {
        /// The terminator, as literal raw text (e.g. `|END_VERBATIM_HERE|`)
        terminator : String
    },
    /// The terminator given as an environment-terminating command that repeats the
    /// invocation's name — `\end{verbatim}`, spelled out piece by piece.
    StopEnvironmentCommand {
        /// The escape character the terminator command is written with (`\` for
        /// `\end{verbatim}`) — the canonical spelling the composing caller uses,
        /// ordinarily the one its own opening command was written with.
        escape_char: char,
        /// The invocation name the terminator must back-reference (`lstlisting` for
        /// `\begin{lstlisting} … \end{lstlisting}`), and the name diagnostics call
        /// the environment.
        invocation_name: &'p str,
        /// The terminator command's name (`end`), the body loop's stop condition.
        stop_command_name: &'p str,
        /// The group rule the terminator's name must be enclosed in: for `\end{xyz}`,
        /// the `{`/`}` rule.
        name_group_rule: Arc<GroupRule<L>>,
    }
}

impl<L: Lang> VerbatimBodyTerminator<'_, L> {
    /// The raw terminator string the body is read up to: the literal as given, or
    /// the stop command's spelling composed piece by piece — escape character,
    /// command name, name group open delimiter, invocation name, name group close
    /// delimiter (`\end{verbatim}`). No whitespace is tolerated anywhere inside it:
    /// the composed string is matched byte for byte, so `\end {verbatim}` does not
    /// end the body.
    fn text(&self) -> String {
        match self {
            VerbatimBodyTerminator::Literal { terminator } => terminator.clone(),
            VerbatimBodyTerminator::StopEnvironmentCommand {
                escape_char,
                invocation_name,
                stop_command_name,
                name_group_rule,
            } => {
                let mut text = String::new();
                text.push(*escape_char);
                text.push_str(stop_command_name);
                text.push_str(&name_group_rule.open);
                text.push_str(invocation_name);
                text.push_str(&name_group_rule.close);
                text
            }
        }
    }

    /// The spelling reported for a consumed terminator occupying `span` and
    /// ending at the stream position `end` — the arm matching this terminator's own
    /// shape (the type docs). The stop-command arm's spans are the pieces
    /// [`text`](Self::text) composed the matched string from, laid out from `span`'s
    /// start in that same order; the post-space span is empty, the composed spelling
    /// having no gap to record.
    fn syntax_data(
        &self,
        span: SourceSpan<L::SourceOrigin>,
        end: StreamPosition<L>,
    ) -> EnvironmentTerminatorSyntaxData<L> {
        match self {
            VerbatimBodyTerminator::Literal { .. } => {
                EnvironmentTerminatorSyntaxData::Literal { span }
            }
            VerbatimBodyTerminator::StopEnvironmentCommand {
                escape_char,
                invocation_name,
                stop_command_name,
                name_group_rule,
            } => {
                // The matched string is the composed one byte for byte, so each
                // piece's extent follows from its length, in the source the whole
                // match was found in.
                let piece = |start: usize, len: usize| {
                    SourceSpan::new(span.source(), start..start + len)
                };
                let command_word_start = span.start() + escape_char.len_utf8();
                let command_word_end = command_word_start + stop_command_name.len();
                let name_start = command_word_end + name_group_rule.open.len();
                EnvironmentTerminatorSyntaxData::Scanned {
                    escape_char: *escape_char,
                    command_word: piece(command_word_start, stop_command_name.len()),
                    post_space: piece(command_word_end, 0),
                    // The pieces are sliced from the matched terminator's own
                    // single-token span, so the name span's content *is* the name
                    // under either span-tiling declaration: no name-as-read needed.
                    name_group: NameGroup::new(
                        piece(name_start, invocation_name.len()),
                        end,
                        Arc::clone(name_group_rule),
                    ),
                }
            }
        }
    }
}

// Manual impl: a derive would demand `L: Debug` although only an `Arc` to rule data
// is stored.
impl<L: Lang> fmt::Debug for VerbatimBodyTerminator<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VerbatimBodyTerminator::Literal { terminator } => {
                f.debug_struct("Literal").field("terminator", terminator).finish()
            }
            VerbatimBodyTerminator::StopEnvironmentCommand {
                escape_char,
                invocation_name,
                stop_command_name,
                name_group_rule,
            } => f
                .debug_struct("StopEnvironmentCommand")
                .field("escape_char", escape_char)
                .field("invocation_name", invocation_name)
                .field("stop_command_name", stop_command_name)
                .field("name_group_rule", name_group_rule)
                .finish(),
        }
    }
}

/// Parses the body of an environment-shaped construct as **raw text**: everything up to
/// `terminator`, with no commands, groups or comments recognized inside it.
///
/// The body is read, the terminator consumed, and the standard body `List` staged with
/// the content as one raw `Chars` node. It produces the same [`EnvironmentBody`] as
/// [`EnvironmentBodyParser`](super::EnvironmentBodyParser), so a definition that supplies
/// its own body parser can use either. "Environment" is the LaTeX-like preset's
/// vocabulary; this parser reads the region between an opening the caller has already
/// read and the terminator it is configured with.
///
/// [`new`](VerbatimBodyParser::new) takes what a definition has to configure: the name
/// diagnostics call the construct, what ends the body ([`VerbatimBodyTerminator`] — a
/// literal string, or a stop command repeating that name), and the group class of the
/// rule minted to carry the terminator (that class is recorded nowhere — the body stages
/// a `List`, not a group). In the LaTeX-like preset none of this is written by hand: an
/// environment registered with the shipped verbatim behavior sets it up (see
/// [the definitions guide](crate::guide::specs#the-spec-types)).
///
/// **Newline gobbling** (on by default): a newline standing at the very start of the
/// body — the one right after `\begin{verbatim}` — is staged as a leading whitespace
/// `Chars` node but designated *out* of the content ([`EnvironmentBody::content`]), so
/// the tree keeps every character while extracted content starts at the first real
/// verbatim line. Turn it off with
/// [`with_gobble_leading_newline`](VerbatimBodyParser::with_gobble_leading_newline).
///
/// The consumed terminator's spelling is reported on [`EnvironmentBody::terminator`] in
/// the variant matching the terminator's own shape:
/// [`Literal`](EnvironmentTerminatorSyntaxData::Literal) for a literal string,
/// [`Scanned`](EnvironmentTerminatorSyntaxData::Scanned) for a stop command.
///
/// Requires a language with the groups feature ([`LangHasGroups`]): the terminator is
/// carried by a minted group rule installed as the expected group close.
///
/// # Recovery
///
/// When the input ends before the terminator appears — or a token the reader could not
/// read is tolerated there — [`MissingEnvironmentTerminator`] is reported through
/// [`ParseContext::recover`], anchored at the invocation trigger like the tokenizing body
/// parser's. Its [`found`](MissingEnvironmentTerminator::found) tells the two apart:
/// [`MissingTerminatorFound::EndOfInput`] for the ended input,
/// [`MissingTerminatorFound::UnreadableToken`] for the tolerated token error. A strict
/// driver aborts the parse; a tolerant one records the diagnostic, keeps the content
/// read so far, closes the body where the reading stopped, and leaves
/// [`EnvironmentBody::terminator`] `None`.
pub struct VerbatimBodyParser<'p, L: Lang> {
    /// The invocation trigger's span (`\begin{verbatim}`'s command token), anchoring
    /// the missing-terminator diagnostic.
    trigger_span: SourceSpan<L::SourceOrigin>,
    /// The invocation name diagnostics call the environment.
    invocation_name: &'p str,
    /// The terminator specification.
    terminator: VerbatimBodyTerminator<'p, L>,
    /// The class of the minted expected-close rule (a language's verbatim group
    /// class); recorded nowhere — the body stages a `List`, not a group.
    group_type: L::GroupTypeId,
    /// Whether to gobble a single leading newline (default: `true`).
    gobble_leading_newline: bool,
    /// The span of the invocation name as written, for the body's traceback frame
    /// (mirrors [`EnvironmentBodyParser`](super::EnvironmentBodyParser)).
    invocation_name_span: Option<SourceSpan<L::SourceOrigin>>,
}

impl<'p, L: LangHasGroups> VerbatimBodyParser<'p, L> {
    /// Creates a verbatim body parser for the construct invoked as `invocation_name`
    /// (trigger token span `trigger_span`), ended by `terminator`
    /// ([`VerbatimBodyTerminator`]), minting its expected-close rule under
    /// `group_type`.
    pub fn new(
        trigger_span: SourceSpan<L::SourceOrigin>,
        invocation_name: &'p str,
        terminator: VerbatimBodyTerminator<'p, L>,
        group_type: L::GroupTypeId,
    ) -> VerbatimBodyParser<'p, L> {
        VerbatimBodyParser {
            trigger_span,
            invocation_name,
            terminator,
            group_type,
            gobble_leading_newline: true,
            invocation_name_span: None,
        }
    }

    /// Sets whether a single newline at the body's very start is designated out of the
    /// content (default: `true`).
    ///
    /// That newline ends the `\begin{verbatim}` line: it belongs to the construct's
    /// opening syntax rather than to the verbatim text. Either way it is staged, and
    /// stays in the tree.
    pub fn with_gobble_leading_newline(mut self, gobble: bool) -> Self {
        self.gobble_leading_newline = gobble;
        self
    }

    /// Provides the span of the invocation name as written, so the body's traceback
    /// frame can quote it (`environment ‘verbatim’`). Without it the frame is titled
    /// "environment body".
    pub fn with_invocation_name_span(mut self, name_span: SourceSpan<L::SourceOrigin>) -> Self {
        self.invocation_name_span = Some(name_span);
        self
    }
}

impl<L: LangHasGroups> ConstructParser<L> for VerbatimBodyParser<'_, L> {
    type Output = EnvironmentBody<L>;

    fn parse(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
    ) -> ConstructParserResult<L, (EnvironmentBody<L>, Option<Box<ParsingStateDelta<L>>>)> {
        // The same environment-body traceback frame as the tokenized parser.
        let title = match &self.invocation_name_span {
            Some(name_span) => {
                FrameTitle::Quoted { label: "environment", name: name_span.clone() }
            }
            None => FrameTitle::Static("environment body"),
        };
        let frame = Frame { title, span: self.trigger_span.clone() };
        cx.with_frame(frame, |cx| self.parse_body(cx))
    }
}

impl<L: LangHasGroups> VerbatimBodyParser<'_, L> {
    /// The body parse proper, run under the environment's traceback frame.
    // The return type is the `ConstructParser::parse` shape spelled out; an alias for
    // it would name one method's tuple, not a concept.
    #[allow(clippy::type_complexity)]
    fn parse_body(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
    ) -> ConstructParserResult<L, (EnvironmentBody<L>, Option<Box<ParsingStateDelta<L>>>)> {
        let body_start = cx.tokens.position_here();
        // Whatever shape the terminator was given in, the body reads up to one raw
        // string ([`VerbatimBodyTerminator::text`]).
        let close_rule = Arc::new(GroupRule {
            group_type: self.group_type,
            // The rule exists solely as the expected-close carrier; the construct's
            // opener is the `\begin{name}` scaffolding the composition already read.
            open: String::new(),
            close: self.terminator.text(),
        });
        let verbatim_state = cx.derive_state(&verbatim_state_delta(close_rule))?;

        let mut children = Vec::new();

        // The gobble peek: a newline as the body's very first raw char.
        let mut content_designation_start = 0u32;
        if self.gobble_leading_newline {
            if let Some(token) = cx.probe_token(&verbatim_state)? {
                if matches!(cx.tokens.token_kind(&token), TokenKind::Char('\n')) {
                    cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
                    let span = cx.tokens.source_span_of(&token);
                    let id = cx
                        .stage_node(
                            NodeKind::chars(span.span()),
                            span.clone(),
                            Arc::clone(&verbatim_state),
                            vec![],
                        )
                        .map_err(|error| cx.staging_error(error, span))?;
                    children.push(id);
                    content_designation_start = 1;
                }
            }
        }

        let content_start = cx.tokens.position_here();
        let raw_end = read_raw_content(cx, &verbatim_state, |_| false, |_| ())?;
        let missing_terminator = match &raw_end.stop {
            RawContentStop::Terminator(_) => None,
            RawContentStop::EndOfInput => Some(MissingTerminatorFound::EndOfInput),
            RawContentStop::UnreadableToken => Some(MissingTerminatorFound::UnreadableToken),
        };
        if let Some(found) = missing_terminator {
            cx.recover(
                MissingEnvironmentTerminator::new(self.invocation_name, found),
                self.trigger_span.clone(),
            )?;
        }

        let content_span = cx.source_span_within(&content_start, &raw_end.content_end)?;
        if let Some(content) = raw_content_text(&raw_end, &content_span) {
            let id = cx
                .stage_node(
                    NodeKind::chars(content),
                    content_span.clone(),
                    Arc::clone(&verbatim_state),
                    vec![],
                )
                .map_err(|error| cx.staging_error(error, content_span))?;
            children.push(id);
        }

        let child_count = children.len() as u32;
        let body_span = cx.source_span_within(&body_start, &raw_end.content_end)?;
        let body = cx
            .stage_node(
                NodeKind::list(),
                body_span.clone(),
                Arc::clone(&cx.state),
                children,
            )
            .map_err(|error| cx.staging_error(error, body_span))?;
        let end = raw_end.end.clone();
        Ok((
            EnvironmentBody {
                body,
                end: end.clone(),
                content: ContentNodes::InChildrenOf(body, content_designation_start..child_count),
                // The facts of the matched terminator, in the arm matching the shape
                // it was given in: a bare span for a literal, the standard
                // command-plus-name-group spelling for a stop command (no tokenized
                // scan exists either way — the pieces are the ones the terminator
                // string was composed from).
                terminator: raw_end
                    .terminator()
                    .map(|span| self.terminator.syntax_data(span.clone(), end.clone())),
                // A raw body runs no content loop: no sibling construct parsed inside
                // it, so nothing evolved the state it was read under and nothing can
                // escape it. The honest facts are the entry state and an empty record.
                exit_state: Arc::clone(&cx.state),
                after_effects: None,
            },
            None,
        ))
    }
}

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

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

    use super::super::{ChildStateSpec, NodesParser, StopCause, StopSpec};
    use super::*;
    use crate::engine::{
        CommandResolution, ParseDriver, ParseResult, ParserSession, ResolvedCallable,
    };
    use crate::error::{ParseError, Recovery};
    use crate::node::{check_tree_invariants, BuildId, NodeRef};
    use crate::scopes::{CallableQuery, CallableSyntax, Package, ScopeStack};
    use crate::constructs::tests::{relaxed_driver, RelaxedStdLang, RELAXED_MACRO};
    use crate::source::{Source, SourcePos};
    use crate::spec::{CallableSpec, StdCallableSpec};
    use crate::state::StateData;
    use crate::token::{
        CommandRule, CommandRules, CommentRule, CommentRules, ForbiddenCharsRules, GroupRules,
        ParagraphRules, SpecialsRules, StdStreamPosition, StdToken, StdTokenReader, TokenEdge,
        TokenError, TokenErrorKind, TokenKind, TokenReader, TokenRecovery, TokenResult,
        TokenRules, WhitespaceRules,
    };
    use alloc::format;
    use alloc::string::ToString;
    use alloc::vec;

    const GT_BRACE: u32 = 0;
    const GT_VERB: u32 = 1;
    const CT_MACRO: u32 = 10;

    /// Test lang resolving `Command` tokens against the state's providers under the
    /// `CT_MACRO` form (the compact 6.4/6.5 suite pattern).
    #[derive(Debug, Clone, Copy)]
    struct VerbLang;
    impl Lang for VerbLang {
        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 = VerbDriver;
        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 VerbDriver {
        recovery: Recovery,
    }

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

        fn resolve_command(
            &self,
            state: &ParsingState<VerbLang>,
            token: &StdToken<VerbLang>,
            tokens: &dyn TokenReader<'_, VerbLang>,
        ) -> Result<CommandResolution<VerbLang>, crate::error::ParseError> {
            let TokenKind::Command { name, escape_char } = tokens.token_kind(token) else {
                return Ok(CommandResolution::Unresolved { detail: None });
            };
            let query =
                CallableQuery::new(CT_MACRO, name, CallableSyntax::Command { escape_char });
            Ok(match state.scopes().retrieve_spec(&query, state) {
                Ok(resolved) => resolved
                    .map(|spec| ResolvedCallable { callable_type: CT_MACRO, spec })
                    .into(),
                Err(error) => {
                    CommandResolution::Unresolved { detail: Some(error.to_string()) }
                }
            })
        }
    }

    fn rules<L: Lang<GroupTypeId = u32, Features = crate::state::AllLangFeatures>>(
    ) -> TokenRules<L> {
        TokenRules {
            whitespace: WhitespaceRules { enabled: true, chars: " \t\n".into() },
            paragraphs: ParagraphRules { enabled: true },
            groups: GroupRules {
                enabled: true,
                rules: vec![Arc::new(GroupRule {
                    group_type: GT_BRACE,
                    open: "{".into(),
                    close: "}".into(),
                })],
                temporary: Vec::new(),
                expecting_close: None,
            },
            commands: CommandRules {
                enabled: true,
                rules: vec![Arc::new(CommandRule {
                    escape_char: '\\',
                    name_chars: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".into(),
                })],
            },
            comments: CommentRules {
                enabled: true,
                rules: vec![Arc::new(CommentRule { start: "%".into() })],
            },
            specials: SpecialsRules { enabled: true },
            forbidden_chars: ForbiddenCharsRules { chars: "".into() },
        }
    }

    fn plain_state() -> Arc<ParsingState<VerbLang>> {
        Arc::new(ParsingState::new(StateData {
            rules: rules(),
            scopes: ScopeStack::new(),
            mode: (),
            ext: (),
        }))
    }

    /// A state whose provider defines each named macro with the given argument specs.
    fn state_with(
        macros: &[(&str, Vec<Arc<ArgumentSpec<VerbLang>>>)],
    ) -> Arc<ParsingState<VerbLang>> {
        let mut package = Package::new("test-macros");
        for (name, arguments) in macros {
            let spec: Arc<dyn CallableSpec<VerbLang>> =
                Arc::new(StdCallableSpec { arguments: arguments.clone(), ..Default::default() });
            package.insert(CT_MACRO, *name, spec);
        }
        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(package));
        Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }))
    }

    fn verb_arg() -> Arc<ArgumentSpec<VerbLang>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(VerbatimArgumentParser::new(GT_VERB))))
    }

    fn verb_arg_with(parser: VerbatimArgumentParser<VerbLang>) -> Arc<ArgumentSpec<VerbLang>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(parser)))
    }

    fn brace_arg() -> Arc<ArgumentSpec<VerbLang>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(super::super::GroupArgumentParser::new(
            GT_BRACE,
        ))))
    }

    // --- harness: full content drive over `StdTokenReader` (verbatim re-tokenizes
    // --- under derived states, so only the scanning reader applies — [§dd-dr:tokens]) -----------

    fn try_parse(
        content: &str,
        state: &Arc<ParsingState<VerbLang>>,
        recovery: Recovery,
    ) -> Result<ParseResult<VerbLang>, ParseError> {
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let mut session = ParserSession::new();
        let driver = VerbDriver { recovery };
        let mut cx = ParseContext::new(
            &mut reader,
            Arc::clone(state),
            &mut session,
            &driver);
        let mut parser = NodesParser::new(StopSpec::none())
            .with_child_states(ChildStateSpec::inherit());
        let (outcome, delta) = parser.parse(&mut cx)?;
        assert_eq!(outcome.stop, StopCause::EndOfInput);
        assert!(delta.is_none());
        let root_span = {
            let staged = session.builder.staged_nodes();
            match (outcome.nodes.first(), outcome.nodes.last()) {
                (Some(&first), Some(&last)) => Span::new(
                    staged.get(first).unwrap().span().start(),
                    staged.get(last).unwrap().span().end(),
                ),
                _ => Span::empty(0),
            }
        };
        let root = session
            .builder
            .add(
                NodeKind::list(),
                SourceSpan::new(&source, root_span),
                Arc::clone(state),
                outcome.nodes, (), (),
            )
            .unwrap();
        let result = session.finish(root).unwrap();
        check_tree_invariants(&result.tree);
        Ok(result)
    }

    fn parse(
        content: &str,
        state: &Arc<ParsingState<VerbLang>>,
        recovery: Recovery,
    ) -> ParseResult<VerbLang> {
        try_parse(content, state, recovery).expect("parse")
    }

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

    /// The verbatim group node of `\verb`-style argument 0 plus its raw text.
    fn verb_group(node: NodeRef<'_, VerbLang>) -> NodeRef<'_, VerbLang> {
        let region: Vec<_> = node.argument_nodes(0).expect("provided argument").iter().collect();
        *region.last().expect("the group node ends the region")
    }

    fn verbatim_text<'t>(node: NodeRef<'t, VerbLang>) -> Option<&'t str> {
        let content: Vec<_> = node.argument_content_nodes(0)?.iter().collect();
        match content.as_slice() {
            [] => Some(""),
            [chars] => chars.chars(),
            _ => panic!("verbatim content is at most one chars node"),
        }
    }

    /// Pin of the recorded verbatim state: every tokenization feature off (the
    /// pylatexenc `vps.enable_*` assertions).
    fn assert_verbatim_state(node: NodeRef<'_, VerbLang>) {
        let rules = node.parsing_state().rules();
        assert!(!rules.whitespace_enabled());
        assert!(!rules.paragraphs_enabled());
        assert!(!rules.groups_enabled());
        assert!(!rules.commands_enabled());
        assert!(!rules.comments_enabled());
        assert!(!rules.specials_enabled());
        assert!(rules.expecting_group_close().is_some());
    }

    // --- the delimited form (`\verb`) — pylatexenc test_latexnodes_parsers_verbatim
    // --- TestLatexDelimitedVerbatimParser, adapted to invocation position ------------

    #[test]
    fn simple_delimiters() {
        let st = state_with(&[("verb", vec![verb_arg()])]);
        let result = parse(r"\verb|verbatim| x", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());

        let verb = root_child(&result, 0);
        assert_eq!(verb.name(), Some("verb"));
        assert_eq!(verb.span().range(), 0..15);
        let group = verb_group(verb);
        assert_eq!(group.span().range(), 5..15);
        assert_eq!(group.group_type(), Some(GT_VERB));
        assert_eq!(group.group_delimiters(), Some(("|", "|")));
        assert_eq!(verbatim_text(verb), Some("verbatim"));
        let chars = group.child(0).unwrap();
        assert_eq!(chars.span().range(), 6..14);
        assert_verbatim_state(chars);
        // The group wrapper records the surrounding (fully enabled) state.
        assert!(group.parsing_state().rules().commands_enabled());
        assert_eq!(root_child(&result, 1).chars(), Some(" x"));
    }

    #[test]
    fn raw_content_ignores_every_recognizer() {
        // pylatexenc's test_special_contents: escapes, comments, a paragraph break,
        // specials — all raw chars between `<` and the auto-matched `>`.
        let text = "<\\$%*~+\n\n%\\)\nverbatim>";
        let st = state_with(&[("verb", vec![verb_arg()])]);
        let result = parse(&format!("\\verb{text}"), &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());

        let verb = root_child(&result, 0);
        let group = verb_group(verb);
        assert_eq!(group.group_delimiters(), Some(("<", ">")));
        assert_eq!(verbatim_text(verb), Some(&text[1..text.len() - 1]));
    }

    #[test]
    fn a_language_forbidden_char_is_ordinary_raw_content() {
        // Ruled 2026-08-10: `disable_all()` clears the forbidden set (a gateless
        // feature's off is its inactive data), so a character outlawed outside the
        // region reads as raw verbatim content instead of ending the region early
        // with a diagnostic.
        let st = {
            let spec: Arc<dyn CallableSpec<VerbLang>> =
                Arc::new(StdCallableSpec { arguments: vec![verb_arg()], ..Default::default() });
            let mut package = Package::new("test-macros");
            package.insert(CT_MACRO, "verb", spec);
            let mut scopes = ScopeStack::new();
            scopes.push(Arc::new(package));
            let mut rules = rules::<VerbLang>();
            rules.forbidden_chars.chars = "$".into();
            Arc::new(ParsingState::new(StateData { rules, scopes, mode: (), ext: () }))
        };
        let result = parse(r"\verb|a$b| x", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());

        let verb = root_child(&result, 0);
        assert_eq!(verbatim_text(verb), Some("a$b"));
    }

    #[test]
    fn a_language_forbidden_char_can_be_the_delimiter() {
        // The delimiter probe clears the forbidden set too (the raw-reading rule
        // applies to the delimiter as much as to the content it opens), so a character
        // the language outlaws elsewhere opens and closes the region like any other.
        let st = {
            let spec: Arc<dyn CallableSpec<VerbLang>> =
                Arc::new(StdCallableSpec { arguments: vec![verb_arg()], ..Default::default() });
            let mut package = Package::new("test-macros");
            package.insert(CT_MACRO, "verb", spec);
            let mut scopes = ScopeStack::new();
            scopes.push(Arc::new(package));
            let mut rules = rules::<VerbLang>();
            rules.forbidden_chars.chars = "$".into();
            Arc::new(ParsingState::new(StateData { rules, scopes, mode: (), ext: () }))
        };
        let result = parse(r"\verb$a$ x", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());

        let verb = root_child(&result, 0);
        let group = verb_group(verb);
        assert_eq!(group.group_delimiters(), Some(("$", "$")));
        assert_eq!(group.span().range(), 5..8);
        assert_eq!(verbatim_text(verb), Some("a"));
        // The region ends at the closing delimiter: what follows is enclosing content.
        assert_eq!(root_child(&result, 1).chars(), Some(" x"));
    }

    #[test]
    fn whitespace_before_the_delimiter_is_region_noise() {
        // In invocation position the trigger's own post-space swallows `\verb |x|`'s
        // gap, so exercise pre-delimiter whitespace behind a first argument.
        let st = state_with(&[("lst", vec![brace_arg(), verb_arg()])]);
        let result = parse(r"\lst{a} |xy|", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());

        let lst = root_child(&result, 0);
        let region: Vec<_> = lst.argument_nodes(1).unwrap().iter().collect();
        assert_eq!(region.len(), 2);
        assert_eq!(region[0].chars(), Some(" "));
        assert_eq!(region[1].group_delimiters(), Some(("|", "|")));
        let content: Vec<_> = lst.argument_content_nodes(1).unwrap().iter().collect();
        assert_eq!(content.len(), 1);
        assert_eq!(content[0].chars(), Some("xy"));
    }

    #[test]
    fn a_paragraph_break_may_precede_the_delimiter() {
        // pylatexenc `skip_space_chars` parity: the pre-delimiter skip has no
        // paragraph rule — `\n\n` is plain noise ahead of the region.
        let st = state_with(&[("lst", vec![brace_arg(), verb_arg()])]);
        let result = parse("\\lst{a}\n\n|xy|", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());
        let lst = root_child(&result, 0);
        let region: Vec<_> = lst.argument_nodes(1).unwrap().iter().collect();
        assert_eq!(region[0].chars(), Some("\n\n"));
        assert_eq!(verbatim_text_at(lst, 1), Some("xy"));
    }

    fn verbatim_text_at(node: NodeRef<'_, VerbLang>, i: usize) -> Option<&str> {
        let content: Vec<_> = node.argument_content_nodes(i)?.iter().collect();
        content.first().and_then(|chars| chars.chars())
    }

    #[test]
    fn auto_matched_pairs_and_the_depth_counter() {
        let st = state_with(&[("verb", vec![verb_arg()])]);

        // `{` auto-matches `}` (pylatexenc test_curlybrace_delimiters)...
        let result = parse(r"\verb{verbatim}", &st, Recovery::Strict);
        let verb = root_child(&result, 0);
        assert_eq!(verb_group(verb).group_delimiters(), Some(("{", "}")));
        assert_eq!(verbatim_text(verb), Some("verbatim"));

        // ...and nested pairs balance through the depth counter.
        let result = parse(r"\verb{a{b{c}}d}e", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());
        let verb = root_child(&result, 0);
        assert_eq!(verbatim_text(verb), Some("a{b{c}}d"));
        assert_eq!(root_child(&result, 1).chars(), Some("e"));

        // Identical delimiters have no nesting: the first closer ends the region.
        let result = parse(r"\verb|a|b", &st, Recovery::Strict);
        assert_eq!(verbatim_text(root_child(&result, 0)), Some("a"));
    }

    #[test]
    fn verbatim_inside_an_enclosing_group() {
        // The probe delta *clears* the inherited close expectation, and the content
        // delta *replaces* it: `}` works both as delimiter and as raw content inside
        // a braces group; the group still finds its own close after the region.
        let st = state_with(&[("verb", vec![verb_arg()])]);

        let result = parse(r"{\verb|}|}", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());
        let group = root_child(&result, 0);
        assert_eq!(group.group_delimiters(), Some(("{", "}")));
        let verb = group.child(0).unwrap();
        assert_eq!(verbatim_text(verb), Some("}"));

        let result = parse(r"{\verb}x}}", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());
        let verb = root_child(&result, 0).child(0).unwrap();
        assert_eq!(verb_group(verb).group_delimiters(), Some(("}", "}")));
        assert_eq!(verbatim_text(verb), Some("x"));
    }

    #[test]
    fn empty_content_stages_no_chars_node() {
        let st = state_with(&[("verb", vec![verb_arg()])]);
        let result = parse(r"\verb||", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());
        let verb = root_child(&result, 0);
        let group = verb_group(verb);
        assert_eq!(group.child_count(), 0);
        assert_eq!(verbatim_text(verb), Some(""));
    }

    #[test]
    fn fixed_delimiters() {
        // pylatexenc test_simple_delimiters_required_delims: `{`…`>` prescribed.
        let st = state_with(&[(
            "verb",
            vec![verb_arg_with(VerbatimArgumentParser::new(GT_VERB).with_delimiters('{', '>'))],
        )]);
        let result = parse(r"\verb{verbatim>", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());
        let verb = root_child(&result, 0);
        assert_eq!(verb_group(verb).group_delimiters(), Some(("{", ">")));
        assert_eq!(verbatim_text(verb), Some("verbatim"));
    }

    #[test]
    fn custom_auto_delimiter_table() {
        // pylatexenc test_simple_delimiters_auto_delims: '`' auto-matches '\''.
        let st = state_with(&[(
            "verb",
            vec![verb_arg_with(
                VerbatimArgumentParser::new(GT_VERB)
                    .with_auto_delimiters([('{', '}'), ('<', '>'), ('`', '\'')]),
            )],
        )]);
        let result = parse(r"\verb`verbatim'", &st, Recovery::Strict);
        assert!(result.diagnostics.is_empty());
        let verb = root_child(&result, 0);
        assert_eq!(verb_group(verb).group_delimiters(), Some(("`", "'")));
        assert_eq!(verbatim_text(verb), Some("verbatim"));
    }

    #[test]
    fn wrong_fixed_delimiter_reports_the_argument_absent() {
        let st = state_with(&[(
            "verb",
            vec![verb_arg_with(VerbatimArgumentParser::new(GT_VERB).with_delimiters('{', '}'))],
        )]);

        let err = try_parse(r"\verb|x|", &st, Recovery::Strict).unwrap_err();
        assert!(err.to_string().contains("expected opening delimiter ‘{’"), "{err}");

        let result = parse(r"\verb|x|", &st, Recovery::Tolerant);
        assert_eq!(result.diagnostics.len(), 1);
        let verb = root_child(&result, 0);
        assert!(!verb.arguments().unwrap().get(0).unwrap().is_provided());
        // Nothing consumed: `|x|` re-parses as sibling content.
        assert_eq!(root_child(&result, 1).chars(), Some("|x|"));
    }

    #[test]
    fn missing_delimiter_at_end_of_input() {
        let st = state_with(&[("verb", vec![verb_arg()])]);

        let err = try_parse(r"\verb", &st, Recovery::Strict).unwrap_err();
        assert!(err.to_string().contains("expected a verbatim opening delimiter"), "{err}");

        let result = parse(r"\verb", &st, Recovery::Tolerant);
        assert_eq!(result.diagnostics.len(), 1);
        assert!(!root_child(&result, 0).arguments().unwrap().get(0).unwrap().is_provided());
    }

    #[test]
    fn unterminated_verbatim_recovers_with_an_empty_close() {
        let st = state_with(&[("verb", vec![verb_arg()])]);

        let err = try_parse(r"\verb|abc", &st, Recovery::Strict).unwrap_err();
        assert!(err.to_string().contains("missing closing delimiter ‘|’"), "{err}");

        let result = parse(r"\verb|abc", &st, Recovery::Tolerant);
        assert_eq!(result.diagnostics.len(), 1);
        let verb = root_child(&result, 0);
        let group = verb_group(verb);
        assert_eq!(group.group_delimiters(), Some(("|", "")));
        assert_eq!(group.span().range(), 5..9);
        assert_eq!(verbatim_text(verb), Some("abc"));
    }

    // --- the environment-contents form (`VerbatimBodyParser`), driven directly at the
    // --- body position — pylatexenc TestLatexVerbatimEnvironmentContentsParser -------

    struct BodyRun {
        result: ParseResult<VerbLang>,
        /// Where the environment ends, as the body parser reported it.
        end: crate::token::StdStreamPosition,
        /// The same place as a byte offset, for the numeric assertions.
        end_offset: usize,
        content: ContentNodes,
        body_id: BuildId,
        terminator: Option<EnvironmentTerminatorSyntaxData<VerbLang>>,
        /// The state the body was read under, for the after-effects assertions below.
        entry_state: Arc<ParsingState<VerbLang>>,
        /// What the body reported as its interior's exit state.
        exit_state: Arc<ParsingState<VerbLang>>,
        /// What the body reported as its interior's merged after-effect record.
        after_effects: Option<Box<ParsingStateDelta<VerbLang>>>,
    }

    /// `\end{verbatim}` spelled out as one literal string.
    fn literal_terminator() -> VerbatimBodyTerminator<'static, VerbLang> {
        VerbatimBodyTerminator::Literal { terminator: "\\end{verbatim}".into() }
    }

    /// The same `\end{verbatim}` given piecewise, as the preset's environment
    /// composition gives it: `\` + `end` + the `{…}` name group around `verbatim`.
    fn command_terminator() -> VerbatimBodyTerminator<'static, VerbLang> {
        VerbatimBodyTerminator::StopEnvironmentCommand {
            escape_char: '\\',
            invocation_name: "verbatim",
            stop_command_name: "end",
            name_group_rule: Arc::new(GroupRule {
                group_type: GT_BRACE,
                open: "{".into(),
                close: "}".into(),
            }),
        }
    }

    fn run_body(
        content: &str,
        recovery: Recovery,
        gobble: bool,
    ) -> Result<BodyRun, ParseError> {
        run_body_with(content, recovery, gobble, literal_terminator())
    }

    fn run_body_with(
        content: &str,
        recovery: Recovery,
        gobble: bool,
        terminator: VerbatimBodyTerminator<'_, VerbLang>,
    ) -> Result<BodyRun, ParseError> {
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        run_body_over(&source, &mut reader, recovery, gobble, terminator)
    }

    /// [`run_body_with`] over a caller-supplied reader — the seam the unreadable-token
    /// test needs, the standard reader having nothing left to reject under the raw
    /// reading state.
    fn run_body_over<'s>(
        source: &'s Arc<Source>,
        reader: &mut dyn TokenReader<'s, VerbLang>,
        recovery: Recovery,
        gobble: bool,
        terminator: VerbatimBodyTerminator<'_, VerbLang>,
    ) -> Result<BodyRun, ParseError> {
        let state = plain_state();
        let mut session = ParserSession::new();
        let driver = VerbDriver { recovery };
        let mut cx = ParseContext::new(
            reader,
            Arc::clone(&state),
            &mut session,
            &driver);
        let mut parser =
            VerbatimBodyParser::new(
                SourceSpan::new(source, 0..0),
                "verbatim",
                terminator,
                GT_VERB,
            )
            .with_gobble_leading_newline(gobble);
        let (body, delta) = parser.parse(&mut cx)?;
        assert!(delta.is_none());
        let end_offset = cx.tokens.source_position_at(&body.end).pos();
        let span = {
            let staged = session.builder.staged_nodes();
            staged.get(body.body).unwrap().span().range()
        };
        let root = session
            .builder
            .add(
                NodeKind::list(),
                SourceSpan::new(source, span),
                Arc::clone(&state),
                vec![body.body], (), (),
            )
            .unwrap();
        let result = session.finish(root).unwrap();
        check_tree_invariants(&result.tree);
        Ok(BodyRun {
            result,
            end: body.end,
            end_offset,
            content: body.content,
            body_id: body.body,
            terminator: body.terminator,
            entry_state: state,
            exit_state: body.exit_state,
            after_effects: body.after_effects,
        })
    }

    #[test]
    fn environment_contents_gobble_and_terminator() {
        // pylatexenc test_simple: the fragment right after `\begin{verbatim}`.
        let text = "\nHello world.\\\n\\macro, \\begin! This: % is not a comment; ~. all\n\\end{verbatim}\n";
        let evpos = text.find("\\end{verbatim}").unwrap();
        let run = run_body(text, Recovery::Strict, true).unwrap();
        assert!(run.result.diagnostics.is_empty());

        // The body list keeps every byte: the gobbled newline node, then the content.
        let list = run.result.tree.root().child(0).unwrap();
        assert_eq!(list.span().range(), 0..evpos);
        assert_eq!(list.child_count(), 2);
        assert_eq!(list.child(0).unwrap().chars(), Some("\n"));
        assert_eq!(list.child(1).unwrap().chars(), Some(&text[1..evpos]));
        assert_verbatim_state(list.child(1).unwrap());

        // The designation excludes the gobbled newline; `end` lies past the
        // terminator (the trailing "\n" stays enclosing content).
        assert_eq!(run.content, ContentNodes::InChildrenOf(run.body_id, 1..2));
        assert_eq!(run.end_offset, evpos + "\\end{verbatim}".len());
    }

    #[test]
    fn environment_contents_at_stream_end() {
        // pylatexenc test_simple_nofinaleol: EOF immediately after the terminator.
        let text = "\nHello.\n\\end{verbatim}";
        let evpos = text.find("\\end{verbatim}").unwrap();
        let run = run_body(text, Recovery::Strict, true).unwrap();
        assert!(run.result.diagnostics.is_empty());
        let list = run.result.tree.root().child(0).unwrap();
        assert_eq!(list.child(1).unwrap().chars(), Some(&text[1..evpos]));
        assert_eq!(run.end_offset, text.len());
    }

    #[test]
    fn environment_contents_without_a_leading_newline_gobble_nothing() {
        let text = "xyz\n\\end{verbatim}";
        let run = run_body(text, Recovery::Strict, true).unwrap();
        let list = run.result.tree.root().child(0).unwrap();
        assert_eq!(list.child_count(), 1);
        assert_eq!(list.child(0).unwrap().chars(), Some("xyz\n"));
        assert_eq!(run.content, ContentNodes::InChildrenOf(run.body_id, 0..1));
    }

    #[test]
    fn environment_contents_gobble_disabled() {
        let text = "\nxyz\\end{verbatim}";
        let run = run_body(text, Recovery::Strict, false).unwrap();
        let list = run.result.tree.root().child(0).unwrap();
        assert_eq!(list.child_count(), 1);
        assert_eq!(list.child(0).unwrap().chars(), Some("\nxyz"));
        assert_eq!(run.content, ContentNodes::InChildrenOf(run.body_id, 0..1));
    }

    #[test]
    fn environment_contents_missing_terminator() {
        let text = "\nno end in sight";
        let err = run_body(text, Recovery::Strict, true).err().expect("strict abort");
        assert!(err.to_string().contains("missing terminator of environment ‘verbatim’"), "{err}");

        let run = run_body(text, Recovery::Tolerant, true).unwrap();
        assert_eq!(run.result.diagnostics.len(), 1);
        let list = run.result.tree.root().child(0).unwrap();
        assert_eq!(list.child(1).unwrap().chars(), Some(&text[1..]));
        assert_eq!(run.end_offset, text.len());
        // Nothing was consumed, so no terminator facts are reported.
        assert!(run.terminator.is_none());
    }

    /// A token source that cannot read the character at one offset: peeking there
    /// reports a recoverable error, whose recovery the tolerant policy takes by
    /// skipping that one character.
    ///
    /// The standard reader has nothing left to reject under the raw-reading state (the
    /// forbidden set is cleared with every other feature), so only a reader of the
    /// embedder's own reaches the body's unreadable-token ending.
    struct UnreadableAtReader<'s> {
        inner: StdTokenReader<'s>,
        /// The offset that cannot be read.
        at: usize,
    }

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

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

    impl<'s> TokenReader<'s, VerbLang> for UnreadableAtReader<'s> {
        fn peek(
            &mut self,
            state: &Arc<ParsingState<VerbLang>>,
        ) -> TokenResult<VerbLang, StdToken<VerbLang>> {
            let here = self.inner().position_here();
            if here.offset() != self.at {
                return self.inner_mut().peek(state);
            }
            let span = Span::new(self.at, self.at + 1);
            Err(TokenError::new(
                TokenErrorKind::ForbiddenChar(crate::token::ForbiddenChar::new('?')),
                SourceSpan::new(self.inner.source(), span),
                Some(TokenRecovery {
                    token: StdToken::char('?', span, Span::empty(self.at)),
                    resume: StdStreamPosition::at(self.at + 1),
                }),
            ))
        }

        fn move_to(&mut self, tok: &StdToken<VerbLang>, edge: TokenEdge) {
            self.inner_mut().move_to(tok, edge);
        }

        fn move_to_position(&mut self, at: &StdStreamPosition) {
            self.inner_mut().move_to_position(at);
        }

        fn token_kind<'t>(&self, tok: &'t StdToken<VerbLang>) -> TokenKind<'t, VerbLang>
        where
            's: 't,
        {
            self.inner().token_kind(tok)
        }

        fn source_span_between(
            &self,
            tok: &StdToken<VerbLang>,
            a: TokenEdge,
            b: TokenEdge,
        ) -> SourceSpan {
            self.inner().source_span_between(tok, a, b)
        }

        fn position_here(&self) -> StdStreamPosition {
            self.inner().position_here()
        }

        fn position_at(&self, tok: &StdToken<VerbLang>, edge: TokenEdge) -> StdStreamPosition {
            self.inner().position_at(tok, edge)
        }

        fn source_position_at(&self, at: &StdStreamPosition) -> SourcePos {
            self.inner().source_position_at(at)
        }

        fn source_span_within(
            &self,
            begin: &StdStreamPosition,
            end: &StdStreamPosition,
        ) -> Option<SourceSpan> {
            self.inner().source_span_within(begin, end)
        }

        fn source_span_describing(
            &self,
            begin: &StdStreamPosition,
            end: &StdStreamPosition,
        ) -> SourceSpan {
            self.inner().source_span_describing(begin, end)
        }
    }

    #[test]
    fn a_tolerated_unreadable_token_ends_the_body_and_is_not_end_of_input() {
        // The body ends where the reading stopped, and the diagnostic says so: the
        // input has more to give, so `EndOfInput` would be the wrong answer.
        let text = "\nabc?def\\end{verbatim}";
        let unreadable = text.find('?').unwrap();
        let source: Arc<Source> = Arc::new(Source::new(text));
        let mut reader =
            UnreadableAtReader { inner: StdTokenReader::new(&source), at: unreadable };
        let run = run_body_over(
            &source,
            &mut reader,
            Recovery::Tolerant,
            true,
            literal_terminator(),
        )
        .expect("the tolerant policy keeps going");

        assert_eq!(run.result.diagnostics.len(), 1);
        let diagnostic = run.result.diagnostics.iter().next().unwrap();
        assert_eq!(
            diagnostic.identifier(),
            <MissingEnvironmentTerminator as crate::error::DiagnosticInfo>::IDENTIFIER
        );
        let condition = diagnostic
            .data()
            .downcast_ref::<MissingEnvironmentTerminator>()
            .expect("the missing-terminator condition");
        assert_eq!(condition.found, MissingTerminatorFound::UnreadableToken);
        assert_eq!(
            diagnostic.message(),
            "missing terminator of environment ‘verbatim’ before a token that could \
             not be read"
        );

        // The content is what was read up to the unreadable character, and the body
        // ends there — not at the input's end, which lies well beyond.
        let list = run.result.tree.root().child(0).unwrap();
        assert_eq!(list.child(1).unwrap().chars(), Some(&text[1..unreadable]));
        assert_eq!(run.end_offset, unreadable);
        assert!(run.end_offset < text.len());
        assert!(run.terminator.is_none());
    }

    #[test]
    fn a_raw_body_reports_no_after_effects_and_its_entry_state() {
        // The escape channel's honest emptiness answer
        // ([§dd-dr:environment-after-effects]): a raw body runs no content loop, so no
        // sibling construct evolved the state it was read under and nothing can escape
        // it — the reported facts are the entry state (`Arc` identity) and an empty
        // record, whatever the routing hook above would be willing to let through.
        let run = run_body("\nabc\n\\end{verbatim}", Recovery::Strict, true).unwrap();
        assert!(run.result.diagnostics.is_empty());
        assert!(run.after_effects.is_none());
        assert!(Arc::ptr_eq(&run.exit_state, &run.entry_state));

        // The same on the recovery path, where no terminator was ever found.
        let run = run_body("\nno end in sight", Recovery::Tolerant, true).unwrap();
        assert!(run.after_effects.is_none());
        assert!(Arc::ptr_eq(&run.exit_state, &run.entry_state));
    }

    // --- the terminator's two shapes: same bytes read, different facts reported -----

    #[test]
    fn a_literal_terminator_reports_its_span_alone() {
        let text = "\nxyz\n\\end{verbatim}";
        let evpos = text.find("\\end{verbatim}").unwrap();
        let run = run_body_with(text, Recovery::Strict, true, literal_terminator()).unwrap();
        assert!(run.result.diagnostics.is_empty());
        match run.terminator.expect("a consumed terminator") {
            EnvironmentTerminatorSyntaxData::Literal { span } => {
                assert_eq!(span.range(), evpos..text.len());
            }
            other => panic!("expected literal terminator facts, got {other:?}"),
        }
    }

    #[test]
    fn a_stop_command_terminator_reads_the_same_bytes() {
        // The composed `\end{verbatim}` is matched exactly as the literal one is:
        // same content read, same end position.
        let text = "\nHello.\n\\end{verbatim}\n";
        let evpos = text.find("\\end{verbatim}").unwrap();
        let run = run_body_with(text, Recovery::Strict, true, command_terminator()).unwrap();
        assert!(run.result.diagnostics.is_empty());
        let list = run.result.tree.root().child(0).unwrap();
        assert_eq!(list.child(1).unwrap().chars(), Some(&text[1..evpos]));
        assert_eq!(run.end_offset, evpos + "\\end{verbatim}".len());
    }

    #[test]
    fn a_stop_command_terminator_reports_scanned_facts() {
        //                       0....5....1....1....2
        //                            0    5    0
        let text = "\nxyz\n\\end{verbatim}";
        let evpos = text.find("\\end{verbatim}").unwrap();
        let run = run_body_with(text, Recovery::Strict, true, command_terminator()).unwrap();
        assert!(run.result.diagnostics.is_empty());
        match run.terminator.expect("a consumed terminator") {
            EnvironmentTerminatorSyntaxData::Scanned {
                escape_char,
                command_word,
                post_space,
                name_group,
            } => {
                // The pieces the terminator string was composed from, laid back out
                // over the matched span: `\` `end` `{` `verbatim` `}`, no gap.
                assert_eq!(escape_char, '\\');
                assert_eq!(&text[command_word.range()], "end");
                assert_eq!(post_space.range(), command_word.end()..command_word.end());
                assert_eq!(name_group.name_text(), "verbatim");
                assert_eq!(*name_group.end(), run.end);
                assert_eq!(name_group.rule().group_type, GT_BRACE);
                assert_eq!((&*name_group.rule().open, &*name_group.rule().close), ("{", "}"));
                // The whole terminator is exactly the span the pieces tile.
                assert_eq!(
                    command_word.start() - escape_char.len_utf8(),
                    evpos
                );
            }
            other => panic!("expected scanned terminator facts, got {other:?}"),
        }
    }

    #[test]
    fn a_stop_command_terminator_tolerates_no_whitespace() {
        // The composed string is matched byte for byte: `\end {verbatim}` is not it.
        let text = "\nxyz\n\\end {verbatim}";
        let run = run_body_with(text, Recovery::Tolerant, true, command_terminator()).unwrap();
        assert_eq!(run.result.diagnostics.len(), 1);
        assert!(run.terminator.is_none());
        let list = run.result.tree.root().child(0).unwrap();
        assert_eq!(list.child(1).unwrap().chars(), Some(&text[1..]));
    }

    #[test]
    fn the_recipe_delta_is_reusable() {
        // `verbatim_state_delta` = the pinned recipe as data: derived states read raw
        // chars and the terminator as one GroupClose, whatever the base rules.
        let state = plain_state();
        let rule = Arc::new(GroupRule::<VerbLang> {
            group_type: GT_VERB,
            open: String::new(),
            close: "@@end".into(),
        });
        let derived = state.derived(&verbatim_state_delta(Arc::clone(&rule))).unwrap();
        assert!(!derived.rules().commands_enabled());
        assert_eq!(
            derived.rules().expecting_group_close().map(|r| r.close.as_str()),
            Some("@@end")
        );
    }
    // --- a language that does not obey span tiling (PLAN §1.5 R4) ---------------------

    // The shared relaxed language resolves commands under the same callable type id
    // this suite uses, so its macros can be defined the usual way.
    const _: () = assert!(CT_MACRO == RELAXED_MACRO);

    /// Raw verbatim content is multi-token content: for a language with
    /// `OBEYS_SPAN_TILING = false` it is recorded as the text the reader answered,
    /// token by token, and reads back exactly as the tiled parse's span slice does.
    #[test]
    fn verbatim_content_is_owned_where_the_language_does_not_obey_span_tiling() {
        // The tiled parse of the same input, for comparison.
        let tiled = parse(
            "\\verb|a b|",
            &state_with(&[("verb", vec![verb_arg()])]),
            Recovery::Strict,
        );
        let tiled_content = verb_content(root_child(&tiled, 0));
        assert_eq!(tiled_content.chars(), Some("a b"));
        assert!(matches!(
            tiled_content.kind(),
            NodeKind::Chars { content: TextContent::Spanned(_), .. }
        ));

        let spec: Arc<dyn CallableSpec<RelaxedStdLang>> =
            Arc::new(StdCallableSpec::new([ArgumentSpec::new_unnamed(Arc::new(
                VerbatimArgumentParser::new(GT_VERB),
            ))]));
        let mut package = Package::new("test-macros");
        package.insert(CT_MACRO, "verb", spec);
        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(package));
        let seed = Arc::new(ParsingState::new(StateData {
            rules: rules::<RelaxedStdLang>(),
            scopes,
            mode: (),
            ext: (),
        }));
        let language = crate::engine::Language::new(relaxed_driver(Recovery::Strict), seed);
        let relaxed = language.parse("\\verb|a b|").expect("the parse runs");

        let content = verb_content(relaxed.tree.root().child(0).expect("the callable"));
        assert_eq!(content.chars(), Some("a b"));
        assert!(
            matches!(content.kind(), NodeKind::Chars { content: TextContent::Owned(_), .. }),
            "the content of a relaxed verbatim parse is owned text"
        );
        // The group's delimiters are single-token facts: the node-data rule keeps them
        // as spans of the node's own source here (one source, so they lie in it).
        let group = content.parent().expect("the verbatim group");
        let data = group.group().expect("a group node");
        assert_eq!(data.open.resolve(group.source()), "|");
        crate::node::validate_tree(&relaxed.tree).expect("the all-trees law holds");
    }

    /// The same, for the two content arms the per-token recipe has to get right: a
    /// nested close read as content by the pairing rule, and characters that reach the
    /// terminator's own pre-space position. Both must read back as the tiled parse's
    /// span slice.
    #[test]
    fn relaxed_verbatim_content_covers_the_nested_close_and_trailing_arms() {
        let spec: Arc<dyn CallableSpec<RelaxedStdLang>> =
            Arc::new(StdCallableSpec::new([ArgumentSpec::new_unnamed(Arc::new(
                VerbatimArgumentParser::new(GT_VERB),
            ))]));
        let mut package = Package::new("test-macros");
        package.insert(CT_MACRO, "verb", spec);
        let mut scopes = ScopeStack::new();
        scopes.push(Arc::new(package));
        let seed = Arc::new(ParsingState::new(StateData {
            rules: rules::<RelaxedStdLang>(),
            scopes,
            mode: (),
            ext: (),
        }));
        let language = crate::engine::Language::new(relaxed_driver(Recovery::Strict), seed);

        for (input, expected) in [
            // Paired delimiters: the inner `}` is ordinary content (the pairing rule),
            // so the loop's group-close arm contributes its spelling to the text.
            (r"\verb{a{b}c}", "a{b}c"),
            // Characters up to the closing delimiter, whitespace included — the
            // verbatim state reads them as plain `Char` tokens.
            (r"\verb|ab  |", "ab  "),
        ] {
            let tiled = parse(
                input,
                &state_with(&[("verb", vec![verb_arg()])]),
                Recovery::Strict,
            );
            assert_eq!(verb_content(root_child(&tiled, 0)).chars(), Some(expected));

            let relaxed = language.parse(input).expect("the parse runs");
            let content = verb_content(relaxed.tree.root().child(0).expect("the callable"));
            assert_eq!(content.chars(), Some(expected), "relaxed content of {input:?}");
            assert!(
                matches!(content.kind(), NodeKind::Chars { content: TextContent::Owned(_), .. }),
                "the content of a relaxed verbatim parse is owned text"
            );
            crate::node::validate_tree(&relaxed.tree).expect("the all-trees law holds");
        }
    }

    /// The raw-content `Chars` child of a `\verb`-style callable's verbatim group.
    fn verb_content<L: Lang>(node: NodeRef<'_, L>) -> NodeRef<'_, L> {
        let region: Vec<_> = node.argument_nodes(0).expect("provided argument").iter().collect();
        let group = *region.last().expect("the group node ends the region");
        group.child(0).expect("the raw content")
    }
}