techy 0.1.1

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

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

use crate::constructs::{
    parse_declared_arguments, read_rigid_name_group, ConstructParser,
    ConstructParserResult, EnvironmentBeginSyntaxData, EnvironmentBody,
    EnvironmentBodyParser, Invocation, ParseContext, VerbatimBodyParser,
    VerbatimBodyTerminator,
};
use crate::error::{DiagnosticInfo, ParseError};
use crate::node::{
    BodySlotExt, BuildId, CallableData, ChildRegion, NodeKind, ParsedArguments,
    ParsedSlot, ParsedSlots, SlotRole,
};
use core::marker::PhantomData;

use crate::scopes::{CallableQuery, CallableSyntax, SpecProvenance};
use crate::source::{SourceSpan, TextContent};
use crate::spec::{ArgumentSpec, CallableSpec, FrameRole};
use crate::state::ParsingStateDelta;
use crate::token::{GroupRule, TokenEdge};

use super::driver::LatexlikeParseDriver;
use super::invocation_syntax::EnvironmentSyntax;
use super::lang::{
    LatexlikeCallableType, LatexlikeGroupType, LatexlikeInvocationSyntax, LatexlikeLang,
};
use super::spec::frame_title;
use super::Latexlike;

// --- conditions --------------------------------------------------------------------

/// Condition: the environment-opening command was not followed immediately by its
/// name group.
///
/// The name group is rigid, so `\begin [x]` and `\begin{ itemize }` both raise this.
/// Under tolerant recovery the command alone is staged as a
/// [`Chars`](crate::core::node::NodeKind::Chars) node — the whitespace the command
/// token itself consumed included, so that the siblings still partition the source
/// exactly — and nothing after it is consumed, leaving the rest to parse as ordinary
/// content.
///
/// The message quotes the command as it was written: the opening command's name is
/// whatever [`BeginSpec`] was registered under, `\begin` only by convention.
///
/// Like every condition, it can be constructed outside the crate, for instance to
/// manufacture a diagnostic in an embedding's own tests:
///
/// ```
/// use techy::latexlike::MalformedBegin;
///
/// let condition = MalformedBegin::new("\\begin");
/// assert_eq!(condition, MalformedBegin::new("\\begin"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "latexlike.environments.malformed-begin",
    message = "malformed ‘{command}’: expected the environment's name group \
               immediately after the command"
)]
pub struct MalformedBegin {
    /// The opening command as written: escape character included, the whitespace
    /// after it excluded (`\begin`).
    pub command: String,
}

/// Condition: `\begin{name}` named an environment that no provider in the scope stack
/// defines.
///
/// Under tolerant recovery the parse continues with a fallback definition that
/// declares no arguments, so the body is still parsed and still ends at its
/// `\end{name}` terminator.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "latexlike.environments.unknown-environment",
    message = "unknown environment ‘{name}’"
)]
pub struct UnknownEnvironment {
    /// The environment name as written in the `\begin` name group.
    pub name: String,
}

/// Condition: an environment terminator appeared with no environment open at its
/// level.
///
/// Inside a body the terminator is consumed by the body parser before any command
/// resolution happens, so a terminator that reaches its own definition ([`EndSpec`])
/// is always an orphan. Under tolerant recovery what was consumed — `\end{name}`
/// whole, or the command alone when no name group followed it — is staged as a
/// [`Chars`](crate::core::node::NodeKind::Chars) node.
///
/// The message quotes the terminator as it was written. It never spells the *opening*
/// command, which this site has no way to know: the pairing is recorded by
/// [`BeginSpec`], and only in the opening direction.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "latexlike.environments.orphan-end")]
pub struct OrphanEnd {
    /// The environment named by the terminator, when its name group parsed.
    pub name: Option<String>,
    /// The terminator as written: the whole consumed extent (`\end{align}`), or, when
    /// no name group followed, the command alone with the whitespace after it excluded
    /// (`\end`). A terminator spelled some other way than as a command is always
    /// quoted with its whole extent.
    pub terminator: String,
}

// Hand-written wording: the message names the environment only when the name group
// parsed (a match, which the message format string cannot express).
impl fmt::Display for OrphanEnd {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let terminator = &self.terminator;
        match &self.name {
            Some(name) => {
                write!(f, "orphan ‘{terminator}’: no environment ‘{name}’ is open here")
            }
            None => write!(f, "orphan ‘{terminator}’: no environment is open here"),
        }
    }
}

// --- the environment spec surface --------------------------------------------------

/// The invocation facts of one environment being parsed — what
/// [`EnvironmentBehavior`]'s hooks receive from the `\begin` composition. Grows by
/// field as behavior hooks demand (`#[non_exhaustive]`); built only by the
/// composition.
#[non_exhaustive]
pub struct EnvironmentInvocation<'p, LLL: LatexlikeLang = Latexlike> {
    /// The `\begin` trigger token's span — the anchor of body-level diagnostics
    /// (missing terminator).
    pub trigger_span: SourceSpan<LLL::SourceOrigin>,
    /// The environment's name as written inside the name group (`itemize`,
    /// `figure*`).
    pub name: &'p str,
    /// The name's span (the name group's interior).
    pub name_span: SourceSpan<LLL::SourceOrigin>,
    /// The begin trigger's escape character as written — the canonical escape a
    /// takeover body composes its terminator spelling from
    /// ([`VerbatimBehavior`]'s literal `\end{name}`).
    pub escape_char: char,
    /// The begin name group's open delimiter as written (off the matched rule).
    pub name_group_open: &'p str,
    /// The begin name group's close delimiter as written.
    pub name_group_close: &'p str,
    /// The terminator command's name (`end`), from the dispatching
    /// [`BeginSpec`](BeginSpec::end_command_name): the body's stop condition, and the
    /// command word a takeover body composes its terminator spelling from.
    pub end_command_name: &'p str,
}

// Manual impls: derives would demand `LLL: Clone`/`LLL: Debug` although only spans
// and borrowed strings are held.

impl<LLL: LatexlikeLang> Clone for EnvironmentInvocation<'_, LLL> {
    fn clone(&self) -> Self {
        EnvironmentInvocation {
            trigger_span: self.trigger_span.clone(),
            name: self.name,
            name_span: self.name_span.clone(),
            escape_char: self.escape_char,
            name_group_open: self.name_group_open,
            name_group_close: self.name_group_close,
            end_command_name: self.end_command_name,
        }
    }
}

impl<LLL: LatexlikeLang> fmt::Debug for EnvironmentInvocation<'_, LLL> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnvironmentInvocation")
            .field("trigger_span", &self.trigger_span)
            .field("name", &self.name)
            .field("name_span", &self.name_span)
            .field("escape_char", &self.escape_char)
            .field("name_group_open", &self.name_group_open)
            .field("name_group_close", &self.name_group_close)
            .field("end_command_name", &self.end_command_name)
            .finish()
    }
}

/// The behavior of one environment, behind [`EnvironmentSpec`] — the wrapper's inner
/// trait.
///
/// Third-party implementations override the defaulted methods; the composition
/// reaches them through the concrete wrapper's downcast.
///
/// This is the pylatexenc `EnvironmentSpec` analog (`make_body_parser`,
/// `make_body_parsing_state_delta`), with the declarative standard implementation
/// behind [`EnvironmentSpec::new`].
///
/// **Downcasting is part of the contract** (`Any` supertrait;
/// [`CallableSpec`]'s downcasting note applies): a consumer recovers a behavior's
/// concrete type from the stored `Arc<dyn EnvironmentBehavior<LLL>>` or
/// `&dyn EnvironmentBehavior<LLL>`.
pub trait EnvironmentBehavior<LLL: LatexlikeLang = Latexlike>:
    fmt::Debug + Send + Sync + Any
{
    /// The declarative argument structure of the environment, in invocation order —
    /// parsed right after `\begin{name}`, before the body. Default:
    /// no arguments.
    fn arguments(&self) -> &[Arc<ArgumentSpec<LLL>>] {
        &[]
    }

    /// The body's parsing-state delta (mode changes, tokenization tweaks), stacked on
    /// the invocation's base state for the body's whole extent — terminator included —
    /// and reverted structurally after (pylatexenc's `make_body_parsing_state_delta`).
    /// Default: none (`Ok(None)`).
    ///
    /// # Errors
    ///
    /// `Err` **aborts the parse** under any recovery policy — the composition
    /// derives the body state from the answer, and there is no recovery channel
    /// at this seam; the composition attaches the live traceback when the error
    /// carries no frames of its own. Carry
    /// [`HookFailed`](crate::error::HookFailed) for an operational failure in the
    /// behavior's own code,
    /// [`ImplementationError`](crate::core::constructs::ImplementationError) for a
    /// violated library contract, or a document condition for a diagnosis made
    /// deliberately (a behavior reading malformed argument data). An infallible
    /// implementation wraps its delta in `Ok(...)` and that is the only change.
    fn body_state_delta(
        &self,
        invocation: EnvironmentInvocation<'_, LLL>,
    ) -> Result<Option<ParsingStateDelta<LLL>>, ParseError<LLL::SourceOrigin>> {
        let _ = invocation;
        Ok(None)
    }

    /// The parser that reads the environment's body, entered right after the declared
    /// arguments under the body state. Default: the core [`EnvironmentBodyParser`] —
    /// content up to and including the rigid `\end{name}` terminator, staged as one
    /// body `List`. Override for takeover bodies ([`VerbatimBehavior`]'s raw read);
    /// the returned parser must produce an [`EnvironmentBody`] and no pass-through
    /// delta (its reported [terminator facts](EnvironmentBody::terminator) feed the
    /// invocation-syntax recording).
    ///
    /// The parser's reported [terminator facts](EnvironmentBody::terminator) must be
    /// a shape the language's environment-syntax record can store. The shipped
    /// [`StdEnvironmentSyntax`](super::StdEnvironmentSyntax) holds `\end{name}`-shaped
    /// end sides only, so a body parser reporting
    /// [`EnvironmentTerminatorSyntaxData::Literal`](crate::core::constructs::EnvironmentTerminatorSyntaxData::Literal)
    /// under it ends the parse with
    /// [`EnvironmentSyntaxError`](super::EnvironmentSyntaxError) — an
    /// [`ImplementationError`](crate::core::constructs::ImplementationError) abort
    /// under any recovery policy. Give
    /// [`VerbatimBodyParser`] a
    /// [`StopEnvironmentCommand`](crate::core::constructs::VerbatimBodyTerminator::StopEnvironmentCommand)
    /// terminator, as [`VerbatimBehavior`] does, and the facts come back `Scanned`.
    ///
    /// The produced body also **reports the interior's after-effect record and exit
    /// state** ([`EnvironmentBody::after_effects`], [`EnvironmentBody::exit_state`]),
    /// which the composition routes through
    /// [`LatexlikeParseDriver::environment_after_effects`] — the environment's escape
    /// channel. A takeover body parser that runs a content loop fills them honestly
    /// from its [`NodesOutcome`](crate::core::constructs::NodesOutcome); one that reports
    /// `None` and its entry state (a raw body — [`VerbatimBodyParser`]) lets nothing
    /// escape.
    fn make_body_parser<'p>(
        &'p self,
        invocation: EnvironmentInvocation<'p, LLL>,
    ) -> Box<dyn ConstructParser<LLL, Output = EnvironmentBody<LLL>> + 'p> {
        default_body_parser(invocation)
    }
}

/// The default body of [`EnvironmentBehavior::make_body_parser`], shared with the
/// composition's non-[`EnvironmentSpec`] fallback: the core [`EnvironmentBodyParser`]
/// over the preset's terminator shape, stopping on the invocation's own terminator
/// command.
fn default_body_parser<'p, LLL: LatexlikeLang>(
    invocation: EnvironmentInvocation<'p, LLL>,
) -> Box<dyn ConstructParser<LLL, Output = EnvironmentBody<LLL>> + 'p> {
    Box::new(
        EnvironmentBodyParser::new(
            invocation.trigger_span.clone(),
            invocation.name,
            invocation.end_command_name,
            LLL::GroupTypeId::content_group(),
        )
        .with_invocation_name_span(invocation.name_span),
    )
}

/// The declarative standard [`EnvironmentBehavior`] behind [`EnvironmentSpec::new`]:
/// arguments as plain data, body handling per the trait defaults.
struct StdEnvironmentBehavior<LLL: LatexlikeLang> {
    arguments: Vec<Arc<ArgumentSpec<LLL>>>,
}

impl<LLL: LatexlikeLang> EnvironmentBehavior<LLL> for StdEnvironmentBehavior<LLL> {
    fn arguments(&self) -> &[Arc<ArgumentSpec<LLL>>] {
        &self.arguments
    }
}

impl<LLL: LatexlikeLang> fmt::Debug for StdEnvironmentBehavior<LLL> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StdEnvironmentBehavior")
            .field("arguments", &self.arguments)
            .finish()
    }
}

/// The behavior of a verbatim environment: its **body is raw text**, read up to the
/// `\end{name}` terminator with nothing recognized inside it.
///
/// This is pylatexenc's `LatexVerbatimEnvironmentContentsParser` wired as an
/// [`EnvironmentBehavior`]. Declared arguments parse normally — tokenized, before the
/// raw region begins (`lstlisting`-style options).
///
/// The body is read by the core [`VerbatimBodyParser`], given a
/// [`StopEnvironmentCommand`](VerbatimBodyTerminator::StopEnvironmentCommand)
/// terminator built from the invocation's own spellings: the escape character it was
/// written with, its name group's delimiters, and the terminator command name the
/// dispatching [`BeginSpec`] carries — the same spellings the `\begin` composition
/// itself is built on. The single newline right after the begin syntax is staged but
/// designated out of the body content (the gobble rule — see
/// [`VerbatimBodyParser`]).
///
/// One behavior instance serves any environment name (the terminator back-reference
/// comes from the invocation), so `verbatim`, `verbatim*`, and listing-style
/// environments can share it:
///
/// ```
/// use std::sync::Arc;
/// use techy::core::{Language, ParsingState};
/// use techy::error::Recovery;
/// use techy::latexlike::{
///     CallableType, EnvironmentSpec, Latexlike, LatexlikeDriver, VerbatimBehavior,
/// };
/// use techy::core::specs::Package;
///
/// let mut package = Package::new("mydefs");
/// package.insert(
///     CallableType::Environment,
///     "verbatim",
///     EnvironmentSpec::from_behavior(Arc::new(VerbatimBehavior::default())),
/// );
/// let language: Language<Latexlike> = Language::new(
///     LatexlikeDriver::new(Recovery::Strict),
///     ParsingState::lang_initial_with_packages([package]).expect("seed state"),
/// );
///
/// let result = language
///     .parse("\\begin{verbatim}\na % b \\x{\n\\end{verbatim}")
///     .unwrap();
/// let env = result.tree.root().child(0).unwrap();
/// assert_eq!(env.environment_name(), Some("verbatim"));
/// let body: Vec<_> = env.body().unwrap().iter().collect();
/// assert_eq!(body.len(), 1);
/// assert_eq!(body[0].chars(), Some("a % b \\x{\n"));
/// ```
pub struct VerbatimBehavior<LLL: LatexlikeLang = Latexlike> {
    arguments: Vec<Arc<ArgumentSpec<LLL>>>,
}

impl<LLL: LatexlikeLang> VerbatimBehavior<LLL> {
    /// A verbatim-body environment with the given (ordinarily parsed) argument
    /// structure ahead of the raw body.
    pub fn new(arguments: Vec<Arc<ArgumentSpec<LLL>>>) -> VerbatimBehavior<LLL> {
        VerbatimBehavior { arguments }
    }
}

impl<LLL: LatexlikeLang> EnvironmentBehavior<LLL> for VerbatimBehavior<LLL> {
    fn arguments(&self) -> &[Arc<ArgumentSpec<LLL>>] {
        &self.arguments
    }

    fn make_body_parser<'p>(
        &'p self,
        invocation: EnvironmentInvocation<'p, LLL>,
    ) -> Box<dyn ConstructParser<LLL, Output = EnvironmentBody<LLL>> + 'p> {
        // The terminator's pieces, taken from the invocation's own spellings (the
        // begin trigger's escape char and the begin name group's delimiters): the
        // parser composes `\end{name}` from them to read the body up to, and reports
        // the very same pieces back as the standard end facts. The name group rule is
        // minted here rather than carried off the matched begin token — the delimiter
        // bytes and the group class are all that is recorded from it.
        Box::new(
            VerbatimBodyParser::new(
                invocation.trigger_span.clone(),
                invocation.name,
                VerbatimBodyTerminator::StopEnvironmentCommand {
                    escape_char: invocation.escape_char,
                    invocation_name: invocation.name,
                    stop_command_name: invocation.end_command_name,
                    name_group_rule: Arc::new(GroupRule {
                        group_type: LLL::GroupTypeId::content_group(),
                        open: invocation.name_group_open.into(),
                        close: invocation.name_group_close.into(),
                    }),
                },
                LLL::GroupTypeId::verbatim_group(),
            )
            .with_invocation_name_span(invocation.name_span),
        )
    }
}

impl<LLL: LatexlikeLang> Default for VerbatimBehavior<LLL> {
    fn default() -> Self {
        VerbatimBehavior { arguments: Vec::new() }
    }
}

impl<LLL: LatexlikeLang> fmt::Debug for VerbatimBehavior<LLL> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VerbatimBehavior").field("arguments", &self.arguments).finish()
    }
}

/// [`EnvironmentSpec::with_body_delta`]'s adapter: reports the given body state
/// delta — overriding whatever the wrapped behavior computes — and delegates
/// everything else.
struct BodyDeltaOverride<LLL: LatexlikeLang> {
    inner: Arc<dyn EnvironmentBehavior<LLL>>,
    delta: ParsingStateDelta<LLL>,
}

impl<LLL: LatexlikeLang> EnvironmentBehavior<LLL> for BodyDeltaOverride<LLL> {
    fn arguments(&self) -> &[Arc<ArgumentSpec<LLL>>] {
        self.inner.arguments()
    }

    /// Infallible: `Ok(...)` wrapping is this implementation's whole use of the
    /// `Result`.
    fn body_state_delta(
        &self,
        _invocation: EnvironmentInvocation<'_, LLL>,
    ) -> Result<Option<ParsingStateDelta<LLL>>, ParseError<LLL::SourceOrigin>> {
        Ok(Some(self.delta.clone()))
    }

    fn make_body_parser<'p>(
        &'p self,
        invocation: EnvironmentInvocation<'p, LLL>,
    ) -> Box<dyn ConstructParser<LLL, Output = EnvironmentBody<LLL>> + 'p> {
        self.inner.make_body_parser(invocation)
    }
}

impl<LLL: LatexlikeLang> fmt::Debug for BodyDeltaOverride<LLL> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BodyDeltaOverride")
            .field("inner", &self.inner)
            .field("delta", &self.delta)
            .finish()
    }
}

/// The preset's environment spec: the registration type for
/// [`CallableType::Environment`](super::CallableType::Environment) entries.
///
/// It is the concrete wrapper through which the `\begin` composition reaches the
/// environment's [`EnvironmentBehavior`] (`Any` downcasts hit concrete types only, so
/// the open set of behaviors is reached through this one concrete spec type).
///
/// The composition — not this spec — parses the invocation:
/// [`make_invocation_parser`](CallableSpec::make_invocation_parser) is never
/// consulted for environment entries (a deliberate, permanent boundary; registering an
/// `EnvironmentSpec` under another callable type gets the macro-shaped default
/// parse, which reads the arguments and no body). A generic non-`EnvironmentSpec`
/// [`CallableSpec`] under [`CallableType::Environment`](super::CallableType::Environment) is legitimate too: its
/// declared arguments parse and the body takes the default handling.
///
/// **Serialization.** The behavior (its arguments' parsers, its body handling) has no
/// serialized form, so an environment spec is serialized by *identity* — a reference
/// to the provider that defined it plus its key — which needs the [`SpecProvenance`]
/// stamp a shared package issues ([`with_provenance`](EnvironmentSpec::with_provenance);
/// [`Package::define_environment`](crate::core::specs::Package::define_environment) stamps
/// automatically in a shared package). An unstamped environment spec cannot be
/// serialized (the error names the type).
pub struct EnvironmentSpec<LLL: LatexlikeLang = Latexlike> {
    behavior: Arc<dyn EnvironmentBehavior<LLL>>,
    provenance: Option<SpecProvenance<LLL>>,
}

impl<LLL: LatexlikeLang> EnvironmentSpec<LLL> {
    /// A declarative environment with the given argument structure and the default
    /// body handling.
    pub fn new(arguments: Vec<Arc<ArgumentSpec<LLL>>>) -> EnvironmentSpec<LLL> {
        EnvironmentSpec::from_behavior(Arc::new(StdEnvironmentBehavior { arguments }))
    }

    /// An environment driven by a custom [`EnvironmentBehavior`] — the wrapper's
    /// registration entry for behavior-shaped customization (verbatim-like bodies).
    pub fn from_behavior(behavior: Arc<dyn EnvironmentBehavior<LLL>>) -> EnvironmentSpec<LLL> {
        EnvironmentSpec { behavior, provenance: None }
    }

    /// Set the body's parsing-state delta (`equation` entering
    /// [`Mode::Math`](super::Mode), a listing disabling comment tokenization),
    /// overriding whatever the current behavior computes.
    pub fn with_body_delta(self, delta: ParsingStateDelta<LLL>) -> EnvironmentSpec<LLL> {
        EnvironmentSpec {
            behavior: Arc::new(BodyDeltaOverride { inner: self.behavior, delta }),
            provenance: self.provenance,
        }
    }

    /// Record where this spec is defined — the [`SpecProvenance`] stamp a shared
    /// package issues ([`Package::provenance_for`](crate::core::specs::Package::provenance_for))
    /// — so that the spec can be serialized by identity. Replaces a previous stamp.
    pub fn with_provenance(mut self, provenance: SpecProvenance<LLL>) -> EnvironmentSpec<LLL> {
        self.provenance = Some(provenance);
        self
    }

    /// The behavior driving this environment's parse.
    pub fn behavior(&self) -> &dyn EnvironmentBehavior<LLL> {
        &*self.behavior
    }
}

// The `SerializableObject` impl (identity through the provenance stamp) lives in
// `super::serialize`, with the preset's other serialization impls.

impl<LLL: LatexlikeLang> CallableSpec<LLL> for EnvironmentSpec<LLL> {
    fn arguments(&self) -> &[Arc<ArgumentSpec<LLL>>] {
        self.behavior.arguments()
    }

    fn provenance(&self) -> Option<&SpecProvenance<LLL>> {
        self.provenance.as_ref()
    }

    fn stack_frame_title(&self, role: FrameRole, name: &str) -> String {
        frame_title("environment", role, name)
    }
}

impl<LLL: LatexlikeLang> Clone for EnvironmentSpec<LLL> {
    fn clone(&self) -> Self {
        EnvironmentSpec { behavior: Arc::clone(&self.behavior), provenance: self.provenance.clone() }
    }
}

impl<LLL: LatexlikeLang> fmt::Debug for EnvironmentSpec<LLL> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnvironmentSpec")
            .field("behavior", &self.behavior)
            .field("provenance", &self.provenance)
            .finish()
    }
}

// --- the `\begin` dispatcher and its composition ------------------------------------

/// The `\begin` dispatcher: every environment enters through this shared spec.
///
/// It is an ordinary [`Macro`](super::CallableType::Macro) entry of the
/// [`builtin_package`](super::builtin_package) (shadowable and unloadable like any
/// definition). Its parser is the preset's environment composition, which reads the
/// rigid `\begin{name}` syntax ([`read_rigid_name_group`](crate::core::constructs::read_rigid_name_group)),
/// resolves the environment's own definition, parses its declared arguments and its
/// body ([`EnvironmentBodyParser`](crate::core::constructs::EnvironmentBodyParser)), and
/// stages the environment node.
///
/// The spec carries the **terminator command's name** — the `end` of `\end{name}` —
/// rather than assuming it: the opening command's own name is whatever the definition
/// is registered under, and the closing one is this field, so a language spelling the
/// pair `\open`/`\shut` registers `BeginSpec::new("shut")` under `"open"` and needs no
/// code of its own. The name reaches the body parsers through
/// [`EnvironmentInvocation::end_command_name`].
///
/// **Serialization.** A `BeginSpec` has a self-contained serialized form (the
/// terminator command's name), so it is always serializable; when it carries a
/// [`SpecProvenance`] stamp ([`with_provenance`](BeginSpec::with_provenance) — the
/// [`builtin_package`](super::builtin_package) stamps its `\begin`) it is serialized
/// by identity instead, so that reading yields the very instance the reading side's
/// package holds.
pub struct BeginSpec<LLL: LatexlikeLang = Latexlike> {
    end_command_name: String,
    // `pub(super)`: the preset's wire layer reads the stamp directly — the
    // `CallableSpec` impl (and so its `provenance()`) carries a bound the
    // `SerializableObject` impl does not.
    pub(super) provenance: Option<SpecProvenance<LLL>>,
    lang: PhantomData<fn() -> LLL>,
}

impl<LLL: LatexlikeLang> BeginSpec<LLL> {
    /// The environment dispatcher spec whose bodies end at the command
    /// `end_command_name` (`"end"` for `\end{name}` — written without the escape
    /// character, which is the invocation's).
    ///
    /// The name must be the one the terminator command is *recognized* under: the
    /// body parsers match it against the command token's name, so a name no command
    /// token can carry leaves every body running to the end of its input (diagnosed
    /// as a missing terminator). Registering an [`EndSpec`] under the same name is
    /// what turns a stray terminator into an [`OrphanEnd`] diagnostic rather than an
    /// unknown command; nothing enforces the pairing.
    pub fn new(end_command_name: impl Into<String>) -> BeginSpec<LLL> {
        BeginSpec { end_command_name: end_command_name.into(), provenance: None, lang: PhantomData }
    }

    /// The terminator command's name, as given to [`new`](BeginSpec::new).
    pub fn end_command_name(&self) -> &str {
        &self.end_command_name
    }

    /// Record where this spec is defined — the [`SpecProvenance`] stamp a shared
    /// package issues — so that the spec is serialized by identity rather than in
    /// its self-contained form. Replaces a previous stamp.
    pub fn with_provenance(mut self, provenance: SpecProvenance<LLL>) -> BeginSpec<LLL> {
        self.provenance = Some(provenance);
        self
    }
}

// The `SerializableObject`/`DeserializableObject` impls live in `super::serialize`.

// The `SlotExt: BodySlotExt` clause is the body-marking contract: the composition
// mints the environment's body slot ext through the generic `BodySlotExt`
// mechanism, so `\begin` is registrable exactly for family members whose slot ext
// implements it (`()` and the preset's `BodyMarker` both do).
impl<LLL: LatexlikeLang> CallableSpec<LLL> for BeginSpec<LLL>
where
    crate::node::SlotExt<LLL>: BodySlotExt,
{
    fn provenance(&self) -> Option<&SpecProvenance<LLL>> {
        self.provenance.as_ref()
    }

    /// `\begin` declares nothing but reads an entire environment: bare use as a
    /// single-token expression argument is diagnosed, not dispatched — a deliberate,
    /// documented divergence from pylatexenc, which dispatches the environment as the
    /// argument.
    fn requires_content(&self) -> bool {
        true
    }

    /// Infallible: `Ok(...)` wrapping is this implementation's whole use of the
    /// `Result`.
    fn make_invocation_parser<'a>(
        &'a self,
        invocation: Invocation<'a, LLL>,
    ) -> Result<
        Box<dyn ConstructParser<LLL, Output = BuildId> + 'a>,
        crate::error::ParseError<LLL::SourceOrigin>,
    >
    {
        Ok(Box::new(EnvironmentInvocationParser {
            invocation,
            end_command_name: &self.end_command_name,
        }))
    }

    /// `\begin` itself is macro-shaped; the environment's own name titles the frames
    /// pushed once the composition has read it.
    fn stack_frame_title(&self, role: FrameRole, name: &str) -> String {
        frame_title("macro", role, name)
    }
}

// No `Default`/`Copy`: the terminator command name has no default worth assuming
// (that assumption is what this field exists to remove), and an owned name is not a
// `Copy` value. `Clone` stays — a spec is registration data.
impl<LLL: LatexlikeLang> Clone for BeginSpec<LLL> {
    fn clone(&self) -> Self {
        BeginSpec {
            end_command_name: self.end_command_name.clone(),
            provenance: self.provenance.clone(),
            lang: PhantomData,
        }
    }
}

impl<LLL: LatexlikeLang> fmt::Debug for BeginSpec<LLL> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BeginSpec")
            .field("end_command_name", &self.end_command_name)
            .field("provenance", &self.provenance)
            .finish()
    }
}

/// The orphan-`\end` spec: a resolved `\end` never belongs to an environment (the
/// body parser consumes well-formed terminators before command resolution), so its
/// parser diagnoses [`OrphanEnd`] and recovers. An ordinary
/// [`Macro`](super::CallableType::Macro) entry of the [`builtin_package`](super::builtin_package),
/// alongside [`BeginSpec`].
///
/// The spec carries no name of its own — it diagnoses whatever command it was
/// registered under, and that name should be the one the paired
/// [`BeginSpec`](BeginSpec::new) was given as its terminator.
///
/// **Serialization.** Stateless, so it is serialized in its (empty) self-contained
/// form and rebuilt as a fresh `EndSpec` — no provenance stamp (the type stays
/// `Copy`).
pub struct EndSpec<LLL: LatexlikeLang = Latexlike> {
    lang: PhantomData<fn() -> LLL>,
}

impl<LLL: LatexlikeLang> EndSpec<LLL> {
    /// The orphan-terminator diagnoser spec.
    pub fn new() -> EndSpec<LLL> {
        EndSpec { lang: PhantomData }
    }
}

// The `SerializableObject`/`DeserializableObject` impls live in `super::serialize`.

impl<LLL: LatexlikeLang> CallableSpec<LLL> for EndSpec<LLL> {
    /// Like `\begin`: declares nothing, reads material (its name group) — bare
    /// expression use is diagnosed.
    fn requires_content(&self) -> bool {
        true
    }

    /// Infallible: `Ok(...)` wrapping is this implementation's whole use of the
    /// `Result`.
    fn make_invocation_parser<'a>(
        &'a self,
        invocation: Invocation<'a, LLL>,
    ) -> Result<
        Box<dyn ConstructParser<LLL, Output = BuildId> + 'a>,
        crate::error::ParseError<LLL::SourceOrigin>,
    >
    {
        Ok(Box::new(OrphanEndParser { invocation }))
    }

    fn stack_frame_title(&self, role: FrameRole, name: &str) -> String {
        frame_title("macro", role, name)
    }
}

impl<LLL: LatexlikeLang> Default for EndSpec<LLL> {
    fn default() -> Self {
        EndSpec::new()
    }
}

impl<LLL: LatexlikeLang> Clone for EndSpec<LLL> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<LLL: LatexlikeLang> Copy for EndSpec<LLL> {}

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

/// The environment composition, a temporary construct parser built per invocation by
/// [`BeginSpec`]:
/// scaffolding, resolution, arguments, body, node assembly — assembled from the
/// public core building blocks (module docs). The composition owns **all
/// scanning**: it validates the trigger, reads the rigid name group
/// ([`read_rigid_name_group`]), parses arguments and body, and passes the
/// collected facts to the environment record's constructor
/// ([`EnvironmentSyntax::from_parsed`]) once, at staging time.
///
/// # Contract: std environments are command-initiated
///
/// This parser is dispatched for the `\begin` **command** ([`BeginSpec`] is a
/// macro-shaped entry), and its trigger must be a
/// [`Command`](crate::core::token::TokenKind::Command) token — a different trigger
/// shape (a specials-dispatched begin, say) is a documented-contract violation
/// and aborts as an implementation error. A custom trigger shape needs its own
/// composition *and* its own `Env` record type: this composition's begin facts
/// ([`EnvironmentBeginSyntaxData`]) are command-spelling facts by construction.
struct EnvironmentInvocationParser<'a, LLL: LatexlikeLang> {
    invocation: Invocation<'a, LLL>,
    /// The dispatching [`BeginSpec`]'s terminator command name, passed on to the
    /// body parsers through [`EnvironmentInvocation::end_command_name`].
    end_command_name: &'a str,
}

impl<LLL: LatexlikeLang> ConstructParser<LLL> for EnvironmentInvocationParser<'_, LLL>
where
    crate::node::SlotExt<LLL>: BodySlotExt,
{
    type Output = BuildId;

    fn parse(
        &mut self,
        cx: &mut ParseContext<'_, '_, LLL>,
    ) -> ConstructParserResult<LLL, (BuildId, Option<Box<ParsingStateDelta<LLL>>>)>
    {
        // The language's environment-side record ([`LatexlikeInvocationSyntax::Env`])
        // records the begin/end syntax; the composition owns all scanning plus
        // resolution, arguments, and node assembly.
        type Env<LLL> =
            <<LLL as crate::state::Lang>::InvocationSyntax as LatexlikeInvocationSyntax<
                LLL,
            >>::Env;
        let trigger = self.invocation.token;

        // The trigger contract first (see the type docs): std environments are
        // command-initiated, so a non-command trigger is a documented-contract
        // violation by whatever dispatched this composition — an implementation
        // error, not a source condition.
        let crate::token::TokenKind::Command { escape_char, .. } =
            cx.tokens.token_kind(trigger)
        else {
            return Err(cx.implementation_error(
                "the std environment composition requires a Command trigger \
                 (custom trigger shapes need their own composition and Env type)",
                cx.tokens.source_span_of(trigger),
            ));
        };
        // The trigger's own spelling, as the reader answers it: the command
        // itself (escape character included) and the syntactic post-space after it.
        let trigger_span = cx.tokens.source_span_of(trigger);
        let trigger_start = cx.tokens.position_at(trigger, TokenEdge::Start);
        let command =
            cx.tokens.source_span_between(trigger, TokenEdge::Start, TokenEdge::End);
        let post_space = cx.tokens.source_span_between(
            trigger,
            TokenEdge::End,
            TokenEdge::EndPastPostSpace,
        );

        // The begin-side scaffolding scan, composition-owned: the rigid name
        // group must be the immediately next token, of the language's content
        // class ([`read_rigid_name_group`]'s contract).
        let Some(name_group) =
            read_rigid_name_group(cx, LLL::GroupTypeId::content_group())?
        else {
            // The condition quotes the command as written — escape character
            // included, the trigger's own post-space excluded (`\begin` out of
            // `\begin [x]`) — since the opening command's name is this spec's
            // registration name, not a fixed spelling.
            cx.recover(
                MalformedBegin::new(String::from(command.content())),
                trigger_span.clone(),
            )?;
            // Chars fallback over the trigger alone (markup in a Chars node is the
            // accepted tolerant-recovery artifact); nothing past it is consumed.
            let id = cx
                .stage_node(
                    NodeKind::chars(trigger_span.span()),
                    trigger_span.clone(),
                    Arc::clone(&cx.state),
                    vec![],
                )
                .map_err(|error| cx.implementation_error(error, trigger_span))?;
            return Ok((id, None));
        };
        // The name as read, never the span's content: the span is only what the reader
        // described for the stretch when the language does not obey span tiling, and
        // the name drives the spec lookup, the node's `name` and the diagnostics.
        let name = name_group.name_text();

        // The begin side's spelling facts (escape char, command word, post-space,
        // matched name group) — recorded, no longer normalized away; handed to the
        // record's constructor at staging time.
        // The command *word* is the command minus its escape character, which is the
        // command's first character by construction.
        let begin_syntax = EnvironmentBeginSyntaxData {
            escape_char,
            command_word: SourceSpan::new(
                command.source(),
                (command.start() + escape_char.len_utf8())..command.end(),
            ),
            post_space,
            name_group: name_group.clone(),
        };

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

        // Declared arguments: the shared core loop; the argument frames quote the
        // *environment's* name, not `\begin`.
        let (mut children, arguments) =
            parse_declared_arguments(cx, &spec, name_group.name_span())?;

        // The environment's behavior, through the funnel downcast. A
        // non-`EnvironmentSpec` registration has no behavior to offer and gets the
        // default body handling.
        let behavior: Option<&dyn EnvironmentBehavior<LLL>> = (&*spec
            as &dyn core::any::Any)
            .downcast_ref::<EnvironmentSpec<LLL>>()
            .map(|environment_spec| environment_spec.behavior());
        // The invocation facts handed to the behavior hooks, spelling pieces
        // included (a takeover body composes its terminator from them). The rule
        // `Arc` clone pins the delimiter strings for the borrow; the escape char
        // transcribes from the already-validated command trigger; the terminator
        // command name comes from the dispatching spec.
        let name_group_rule = Arc::clone(name_group.rule());
        let env_invocation = EnvironmentInvocation {
            trigger_span: trigger_span.clone(),
            name,
            name_span: name_group.name_span().clone(),
            escape_char,
            name_group_open: &name_group_rule.open,
            name_group_close: &name_group_rule.close,
            end_command_name: self.end_command_name,
        };

        // The body: parsed under the behavior's state delta stacked on the
        // invocation's base (session-mediated, structurally reverted), by the
        // behavior's body parser — content up to and including the `\end{name}`
        // terminator in the default shape. A hook Err aborts under any policy
        // (body_state_delta's contract), with the live traceback attached here.
        let body_delta = match behavior {
            Some(b) => b
                .body_state_delta(env_invocation.clone())
                .map_err(|error| cx.attach_hook_frames(error))?,
            None => None,
        };
        let body_state = match &body_delta {
            Some(delta) => cx.derive_state(delta)?,
            None => Arc::clone(&cx.state),
        };
        // The invocation facts and the body's initial state outlive the body parse: the
        // after-effect routing below reports both to the driver, while the parser
        // consumes the facts and the parse consumes the state.
        let hook_invocation = env_invocation.clone();
        let mut body_parser = match behavior {
            Some(b) => b.make_body_parser(env_invocation),
            None => default_body_parser(env_invocation),
        };
        let (body, passthrough) =
            cx.parse_construct(&mut *body_parser, Some(Arc::clone(&body_state)), None)?;
        drop(body_parser);
        // A behavior-supplied body parser is outer-layer input; its documented
        // contract (no pass-through delta) is enforced as an implementation
        // error, never a panic ([§dd-dr:panic-policy]).
        if passthrough.is_some() {
            return Err(cx.implementation_error(
                "the environment body parser must return no pass-through state delta",
                trigger_span,
            ));
        }
        // The interior's after-effect facts, taken off the body before its remaining
        // fields are consumed below.
        let body_exit_state = body.exit_state;
        let body_after_effects = body.after_effects;
        // The body's merged after-effect record, routed through the driver's filter:
        // the answer is this environment invocation's own after-effect, which the
        // enclosing content loop applies and records — that is what lets an escape from
        // inside an environment compose outward exactly as a group's does. Called
        // unconditionally, an empty record included; an `Err` aborts under any recovery
        // policy, with the live traceback attached here (a driver hook has no session).
        let driver = cx.driver;
        let after_effects = driver
            .environment_after_effects(
                &hook_invocation,
                &spec,
                &body_state,
                &body_exit_state,
                body_after_effects,
            )
            .map_err(|error| cx.attach_hook_frames(error))?;

        // The payload, constructed once at staging time: the begin facts the
        // composition scanned plus the terminator facts the body parser (the
        // terminator consumer) reported back — the full command-plus-name-group
        // spelling for a tokenized terminator, and for a raw (verbatim) body too,
        // which consumed its terminator as one token but was given its pieces; a
        // body that closed without a terminator (mismatch, malformed, end of input)
        // leaves the end side empty.
        // The node's own extent, needed before the payload: the record converts each
        // source-qualified fact it was handed into node data against it.
        let node_span = cx.source_span_within(&trigger_start, &body.end)?;
        // An `Err` here means the body parser reported a terminator shape the record
        // cannot store — a definition wiring a body parser to a syntax record it does
        // not fit, so it aborts under any recovery policy like every other
        // extension-contract violation.
        let env_syntax = Env::<LLL>::from_parsed(begin_syntax, body.terminator, &node_span)
            .map_err(|error| cx.implementation_error(error, node_span.clone()))?;

        let offset = children.len() as u32;
        children.push(body.body);
        // The slot record is pure node vocabulary: minted here, name carried on the
        // record itself; the content designation is the body parser's
        // (`EnvironmentBody::content` — a verbatim body designates its gobbled
        // newline out, Phase 7.7). The ext is minted through `BodySlotExt` (not a
        // concrete marker type), so machinery generic over the language keeps working.
        let slots = ParsedSlots::from(vec![ParsedSlot::new(
            ChildRegion::new(offset..offset + 1, body.content),
            "body",
            SlotRole::Content,
            BodySlotExt::make_body(),
        )]);

        let data = CallableData {
            // The environment's own identity — not the `\begin` macro's.
            callable_type: LLL::CallableTypeId::environment_callable(),
            name: name.into(),
            spec,
            arguments: ParsedArguments::from(arguments),
            slots,
            // The recorded begin/end scaffolding facts — the environment arm of
            // the Lang-owned invocation-syntax payload (whitespace after the
            // begin/end commands is a recorded fact now, not a normalized-away
            // gap; whitespace after `\end{…}` stays sibling content).
            invocation_syntax: LLL::InvocationSyntax::environment_form(env_syntax),
        };
        let id = cx
            .stage_node(
                NodeKind::callable(data),
                node_span.clone(),
                Arc::clone(&cx.state),
                children,
            )
            .map_err(|error| cx.staging_error(error, node_span))?;
        Ok((id, after_effects))
    }
}

/// The orphan-`\end` recovery parser ([`EndSpec`]'s): read the name group when
/// present, diagnose [`OrphanEnd`], stage the consumed extent as a `Chars` node.
struct OrphanEndParser<'a, LLL: LatexlikeLang> {
    invocation: Invocation<'a, LLL>,
}

impl<LLL: LatexlikeLang> ConstructParser<LLL> for OrphanEndParser<'_, LLL> {
    type Output = BuildId;

    fn parse(
        &mut self,
        cx: &mut ParseContext<'_, '_, LLL>,
    ) -> ConstructParserResult<LLL, (BuildId, Option<Box<ParsingStateDelta<LLL>>>)>
    {
        let trigger = self.invocation.token;
        let trigger_start = cx.tokens.position_at(trigger, TokenEdge::Start);
        // The command word's end, for the quoted spelling of a terminator whose name
        // group never parsed: a command trigger's own post-space is consumed with it
        // and would read as a trailing blank inside the quotes. Any other trigger
        // shape (this spec is registrable under any syntax) quotes its whole extent.
        let command_end = match cx.tokens.token_kind(trigger) {
            crate::token::TokenKind::Command { .. } => TokenEdge::End,
            _ => TokenEdge::EndPastPostSpace,
        };
        let after_trigger = cx.tokens.position_at(trigger, TokenEdge::EndPastPostSpace);
        let name_group = read_rigid_name_group(cx, LLL::GroupTypeId::content_group())?;
        let (name, end) = match &name_group {
            // The name as read, never the span's content (see the begin side).
            Some(group) => (Some(String::from(group.name_text())), group.end().clone()),
            // Malformed name group: nothing past the trigger was consumed.
            None => (None, after_trigger),
        };
        let span = cx.source_span_within(&trigger_start, &end)?;
        // What was consumed, as text: the trigger up to `edge` — one reader answer
        // about one token, taken from its `Start` so the pre-space the content loop
        // already staged stays out — then the name group, its delimiters as written
        // (the rule cloned off the matched open token) around the name as read. The
        // span from `trigger_start` cannot answer this: for a language that does not
        // obey span tiling it is only what the reader describes for the stretch.
        let consumed = |cx: &ParseContext<'_, '_, LLL>, edge: TokenEdge| -> String {
            let mut text = String::from(
                cx.tokens.source_span_between(trigger, TokenEdge::Start, edge).content(),
            );
            if let Some(group) = &name_group {
                text.push_str(&group.rule().open);
                text.push_str(group.name_text());
                text.push_str(&group.rule().close);
            }
            text
        };
        // The condition quotes the terminator as written — its command name is this
        // spec's registration name, not a fixed spelling. Without a name group the
        // quote stops at the command word (`command_end`): the trigger's own
        // post-space is consumed with it and would read as a trailing blank inside
        // the quotes.
        let quoted_edge = match &name_group {
            Some(_) => TokenEdge::EndPastPostSpace,
            None => command_end,
        };
        let terminator = consumed(cx, quoted_edge);
        cx.recover(OrphanEnd::new(name, terminator), span.clone())?;
        // The node covers the trigger and, when one was read, the name group — several
        // tokens — so for a language with `OBEYS_SPAN_TILING = false` its content is
        // what was consumed (`consumed`, above), not the recorded span.
        let content = match LLL::OBEYS_SPAN_TILING {
            true => TextContent::Spanned(span.span()),
            false => TextContent::Owned(consumed(cx, TokenEdge::EndPastPostSpace).into()),
        };
        let id = cx
            .stage_node(
                NodeKind::chars(content),
                span.clone(),
                Arc::clone(&cx.state),
                vec![],
            )
            .map_err(|error| cx.staging_error(error, span))?;
        Ok((id, None))
    }
}

#[cfg(test)]
mod tests {
    use super::super::test_support::root_shapes;
    use super::super::{CallableType, GroupType, LatexlikeDriver, MacroSpec, Mode};
    use super::*;
    use crate::constructs::{
        ChildStateSpec, ExpressionParser, GroupAfterEffectsFn, GroupArgumentParser, GroupParser,
        OptionalGroupArgumentParser,
    };
    use crate::engine::{CommandResolution, Language, ParseDriver, ParseResult};
    use crate::error::{HookFailed, Recovery};
    use crate::latexlike::{check_latexlike_tree_invariants, source_recomposer};
    use crate::node::NodeRef;
    use crate::recompose::TreeRecomposer;
    use crate::scopes::{Package, Scope, ScopeOp, SpecsProvider};
    use super::super::test_support::RelaxedLatexlike;
    use crate::state::{
        CommentOverrides, FeaturePresence, Lang, LangFeatures, ParsingState,
        ParsingStateStack, TokenRulesOverrides,
    };
    use crate::token::{GroupRule, Token, TokenReader};
    use alloc::string::ToString;
    use core::sync::atomic::{AtomicUsize, Ordering};

    // --- the suite's definitions: the §G environment matrix over the real preset ------

    fn brace_arg() -> Arc<ArgumentSpec<Latexlike>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(GroupArgumentParser::new(GroupType::Content))))
    }

    fn optional_arg() -> Arc<ArgumentSpec<Latexlike>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(OptionalGroupArgumentParser::new(Arc::new(
            GroupRule { group_type: GroupType::Content, open: "[".into(), close: "]".into() },
        )))))
    }

    fn expr_arg() -> Arc<ArgumentSpec<Latexlike>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(ExpressionParser::new())))
    }

    fn env(arguments: Vec<Arc<ArgumentSpec<Latexlike>>>) -> Arc<EnvironmentSpec> {
        Arc::new(EnvironmentSpec::new(arguments))
    }

    #[test]
    fn dyn_environment_behavior_downcasts_to_its_concrete_type() {
        // The `Any` supertrait: the behavior a spec stores comes back type-erased
        // from the accessor a consumer actually uses — `EnvironmentSpec::behavior` —
        // and gives its concrete type back through dyn-to-`Any` upcasting.
        #[derive(Debug)]
        struct Custom {
            label: &'static str,
        }
        impl EnvironmentBehavior for Custom {}
        let spec: EnvironmentSpec =
            EnvironmentSpec::from_behavior(Arc::new(Custom { label: "custom" }));
        let any: &dyn Any = spec.behavior();
        let recovered = any.downcast_ref::<Custom>().expect("downcast to Custom");
        // The recovered reference answers the concrete value's own state.
        assert_eq!(recovered.label, "custom");
    }

    fn test_definitions() -> Package<Latexlike> {
        let mut package = Package::new("test-definitions");
        package.insert(CallableType::Environment, "itemize", env(vec![]));
        package.insert(CallableType::Environment, "tabular", env(vec![brace_arg()]));
        package.insert(CallableType::Environment, "figure", env(vec![optional_arg()]));
        // Starred names are ordinary separate entries.
        package.insert(CallableType::Environment, "figure*", env(vec![optional_arg()]));
        package.insert(
            CallableType::Environment,
            "nocomments",
            Arc::new(EnvironmentSpec::new(vec![]).with_body_delta(
                ParsingStateDelta::new().rules(TokenRulesOverrides {
                    comments: CommentOverrides::disable(),
                    ..TokenRulesOverrides::default()
                }),
            )),
        );
        package.insert(
            CallableType::Environment,
            "equation",
            Arc::new(
                EnvironmentSpec::new(vec![])
                    .with_body_delta(ParsingStateDelta::new().mode(Mode::Math)),
            ),
        );
        package.insert(CallableType::Environment, "A", env(vec![]));
        package.insert(CallableType::Environment, "B", env(vec![]));
        package.insert(
            CallableType::Macro,
            "frac",
            Arc::new(MacroSpec::new(vec![expr_arg(), expr_arg()])),
        );
        // Verbatim bodies (7.7): the plain environment, a starred sibling entry, and
        // a listing-style one with a tokenized option argument before the raw body.
        let verbatim = || {
            Arc::new(EnvironmentSpec::from_behavior(Arc::new(VerbatimBehavior::default())))
        };
        package.insert(CallableType::Environment, "verbatim", verbatim());
        package.insert(CallableType::Environment, "verbatim*", verbatim());
        package.insert(
            CallableType::Environment,
            "lstlisting",
            Arc::new(EnvironmentSpec::from_behavior(Arc::new(VerbatimBehavior::new(vec![
                optional_arg(),
            ])))),
        );
        package
    }

    fn language(recovery: Recovery) -> Language<Latexlike> {
        Language::new(
            LatexlikeDriver::new(recovery),
            ParsingState::lang_initial_with_packages([test_definitions()]).expect("seed state"),
        )
    }

    fn strict() -> Language<Latexlike> {
        language(Recovery::Strict)
    }

    fn tolerant() -> Language<Latexlike> {
        language(Recovery::Tolerant)
    }

    /// Strict parse expected clean: invariants checked, no diagnostics.
    fn parse_ok(input: &str) -> ParseResult<Latexlike> {
        let result = strict().parse(input).unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(
            result.diagnostics.is_empty(),
            "unexpected diagnostics: {:?}",
            result.diagnostics
        );
        result
    }

    /// Tolerant parse: invariants checked, diagnostics left to the caller.
    fn parse_tolerant(input: &str) -> ParseResult<Latexlike> {
        let result = tolerant().parse(input).unwrap();
        check_latexlike_tree_invariants(&result.tree);
        result
    }

    fn body_shapes(env: NodeRef<'_, Latexlike>) -> Vec<String> {
        env.body().expect("an environment node").iter().map(|node| node.summary()).collect()
    }

    fn messages(result: &ParseResult<Latexlike>) -> Vec<String> {
        result.diagnostics.iter().map(|d| d.message().to_string()).collect()
    }

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

    #[test]
    fn environment_round_trips_with_exact_spans() {
        //             0....5....1....1....2....2....3....3
        //                  0    5    0    5    0    5
        let content = "x \\begin{itemize} a b \\end{itemize} y";
        let result = parse_ok(content);

        assert_eq!(
            root_shapes(&result),
            ["chars(x )", "Environment(itemize)", "chars( y)"]
        );
        let env = result.tree.root().child(1).unwrap();
        assert_eq!(env.span().range(), 2..35);
        assert_eq!(env.callable_type(), Some(CallableType::Environment));
        assert_eq!(env.environment_name(), Some("itemize"));
        // Environment shapes record empty post-space; the space after `\end{itemize}`
        // is sibling content.
        assert_eq!(env.post_space(), Some(""));
        // Children = the body `List` alone; its span is the body's content interior.
        assert_eq!(env.child_count(), 1);
        let body = env.slot_content_parent(0).expect("body list");
        assert!(body.is_list());
        assert_eq!(body.span().range(), 17..22);
        assert_eq!(body_shapes(env), ["chars( a b )"]);
        assert_eq!(env.arguments().unwrap().len(), 0);
        assert_eq!(env.slots().unwrap().len(), 1);
        assert!(env.slots().unwrap().get_named("body").is_some());
    }

    /// The preset's body slot is minted with `SlotRole::Content` and the
    /// `BodySlotExt` body marker — `body()` finds it through the marker, not
    /// through a slot position.
    #[test]
    fn body_slot_carries_content_role_and_body_marker() {
        let result = parse_ok("\\begin{itemize} a \\end{itemize}");
        let env = result.tree.root().child(0).unwrap();
        let slot = env.slots().unwrap().get_named("body").expect("the body slot");
        assert_eq!(slot.role, SlotRole::Content);
        assert!(slot.ext.is_body());
        assert_eq!(body_shapes(env), ["chars( a )"]);
    }

    #[test]
    fn empty_body_is_an_empty_list() {
        let result = parse_ok("\\begin{itemize}\\end{itemize}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.span().range(), 0..28);
        let body = env.slot_content_parent(0).unwrap();
        assert_eq!(body.span().range(), 15..15);
        assert_eq!(env.body().unwrap().iter().count(), 0);
    }

    #[test]
    fn scaffolding_whitespace_is_tolerated_and_unrecorded() {
        let result = parse_ok("\\begin {itemize}x\\end {itemize}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.span().range(), 0..31);
        assert_eq!(env.environment_name(), Some("itemize"));
        assert_eq!(env.post_space(), Some(""));
        assert_eq!(body_shapes(env), ["chars(x)"]);
    }

    #[test]
    fn declared_arguments_parse_before_the_body() {
        let result = parse_ok("\\begin{tabular}{cc}x\\end{tabular}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.environment_name(), Some("tabular"));
        // Children: the argument group + the body list.
        assert_eq!(env.child_count(), 2);
        let arguments = env.arguments().unwrap();
        assert_eq!(arguments.len(), 1);
        assert!(arguments.get(0).unwrap().is_provided());
        assert_eq!(body_shapes(env), ["chars(x)"]);
    }

    #[test]
    fn optional_arguments_and_starred_names() {
        let with_opt = parse_ok("\\begin{figure}[t]x\\end{figure}");
        let env = with_opt.tree.root().child(0).unwrap();
        assert!(env.arguments().unwrap().get(0).unwrap().is_provided());

        let without_opt = parse_ok("\\begin{figure}x\\end{figure}");
        let env = without_opt.tree.root().child(0).unwrap();
        assert!(!env.arguments().unwrap().get(0).unwrap().is_provided());

        // `figure*` is its own entry: `*` reads as a plain name character.
        let starred = parse_ok("\\begin{figure*}[t]x\\end{figure*}");
        let env = starred.tree.root().child(0).unwrap();
        assert_eq!(env.environment_name(), Some("figure*"));
        assert!(env.arguments().unwrap().get(0).unwrap().is_provided());
    }

    #[test]
    fn nested_environments() {
        let result = parse_ok("\\begin{A}x\\begin{B}y\\end{B}z\\end{A}");
        let outer = result.tree.root().child(0).unwrap();
        assert_eq!(outer.environment_name(), Some("A"));
        assert_eq!(
            body_shapes(outer),
            ["chars(x)", "Environment(B)", "chars(z)"]
        );
        let inner = outer.body().unwrap().iter().nth(1).unwrap();
        assert_eq!(body_shapes(inner), ["chars(y)"]);
    }

    #[test]
    fn environments_and_math_compose() {
        // A math group inside a body, and an environment inside a math group.
        let math_in_body = parse_ok("\\begin{itemize}$x$\\end{itemize}");
        let env = math_in_body.tree.root().child(0).unwrap();
        assert_eq!(body_shapes(env), ["group(Math(Inline) $ $)"]);

        let env_in_math = parse_ok("$\\begin{itemize}x\\end{itemize}$");
        let math = env_in_math.tree.root().child(0).unwrap();
        assert!(math.is_math_group());
        assert_eq!(math.child(0).unwrap().summary(), "Environment(itemize)");
    }

    // --- body state deltas -------------------------------------------------------------

    #[test]
    fn body_delta_disables_comment_tokenization() {
        // `nocomments` turns comments off for its body: `%` stays a plain character.
        let result = parse_ok("\\begin{nocomments}a%b\\end{nocomments}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(body_shapes(env), ["chars(a%b)"]);

        // The same content in a plain environment parses a comment node.
        let plain = parse_ok("\\begin{itemize}a%b\n\\end{itemize}");
        let env = plain.tree.root().child(0).unwrap();
        assert_eq!(body_shapes(env), ["chars(a)", "comment(b)"]);
    }

    #[test]
    fn equation_body_parses_in_math_mode() {
        let result = parse_ok("y\\begin{equation}x\\end{equation}z");
        let env = result.tree.root().child(1).unwrap();
        let interior = env.body().unwrap().iter().next().unwrap();
        assert_eq!(interior.chars(), Some("x"));
        assert_eq!(interior.parsing_state().mode(), Mode::Math);
        // The environment node itself and the following content are text-mode
        // (structural reversion).
        assert_eq!(env.parsing_state().mode(), Mode::Text);
        let after = result.tree.root().child(2).unwrap();
        assert_eq!(after.parsing_state().mode(), Mode::Text);
    }

    #[test]
    fn environment_visibility_gates_by_mode() {
        // A math-only package defining `aligned`: resolvable inside `$…$`, unknown in
        // text mode.
        let with_math_envs = |recovery| {
            let mut math_envs = Package::new("mathenvs");
            math_envs.insert(CallableType::Environment, "aligned", env(vec![]));
            math_envs.set_visible_modes(Some(vec![Mode::Math]));
            Language::new(
                LatexlikeDriver::new(recovery),
                ParsingState::lang_initial_with_packages([math_envs]).expect("seed state"),
            )
        };

        let math = with_math_envs(Recovery::Strict)
            .parse("$\\begin{aligned}x\\end{aligned}$")
            .unwrap();
        check_latexlike_tree_invariants(&math.tree);
        assert!(math.diagnostics.is_empty());

        let text = with_math_envs(Recovery::Tolerant)
            .parse("\\begin{aligned}x\\end{aligned}")
            .unwrap();
        assert_eq!(messages(&text), ["unknown environment ‘aligned’"]);
    }

    // --- the `"_builtin"` seed: begin/end out of the box --------------------------------

    #[test]
    fn begin_and_end_dispatch_out_of_the_box() {
        // No extra packages: `\begin`/`\end` are `"_builtin"` entries; the environment
        // name is unknown, but the composition still parses the body to its
        // terminator under the tolerant fallback.
        let language = Language::new(
            LatexlikeDriver::new(Recovery::Tolerant),
            ParsingState::lang_initial().expect("seed state"),
        );
        let result = language.parse("\\begin{itemize}x\\end{itemize}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert_eq!(messages(&result), ["unknown environment ‘itemize’"]);
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.environment_name(), Some("itemize"));
        assert_eq!(body_shapes(env), ["chars(x)"]);
    }

    #[test]
    fn unloading_builtin_removes_the_dispatch_pair() {
        let seed = ParsingState::<Latexlike>::lang_initial().expect("seed state")
            .derived(&ParsingStateDelta::new().scope_op(ScopeOp::Unload {
                name: "_builtin".into(),
            }))
            .unwrap();
        let language = Language::new(LatexlikeDriver::new(Recovery::Tolerant), seed);
        let result = language.parse("\\begin{itemize}").unwrap();
        let all = messages(&result);
        assert_eq!(all.len(), 1);
        assert!(all[0].contains("cannot resolve command ‘\\begin’"), "{}", all[0]);
        // `\begin` recovered as chars, `{itemize}` an ordinary group.
        assert_eq!(root_shapes(&result), ["chars(\\begin)", "group(Content { })"]);
    }

    // --- the dispatch pair's names -----------------------------------------------------

    /// The `\open{name} … \shut{name}` language: the opening command is named by its
    /// registration and the terminator by [`BeginSpec::new`]'s argument, so a renamed
    /// pair is definitions, not code. The seed `_builtin` pair is unloaded — nothing
    /// in this language answers to `\begin`.
    fn renamed_pair_language(recovery: Recovery) -> Language<Latexlike> {
        let mut package = Package::new("renamed");
        package.insert(CallableType::Macro, "open", BeginSpec::<Latexlike>::new("shut"));
        package.insert(CallableType::Macro, "shut", EndSpec::<Latexlike>::new());
        package.insert(CallableType::Environment, "itemize", env(vec![]));
        package.insert(
            CallableType::Environment,
            "verbatim",
            Arc::new(EnvironmentSpec::from_behavior(Arc::new(
                VerbatimBehavior::default(),
            ))),
        );
        let seed = ParsingState::<Latexlike>::lang_initial_with_packages([package])
            .expect("seed state")
            .derived(&ParsingStateDelta::new().scope_op(ScopeOp::Unload {
                name: "_builtin".into(),
            }))
            .unwrap();
        Language::new(LatexlikeDriver::new(recovery), seed)
    }

    /// Strict parse expected clean, then reemitted: the recorded begin/end spellings
    /// must give the input back byte for byte.
    fn parse_and_reemit(language: &Language<Latexlike>, input: &str) -> ParseResult<Latexlike> {
        let result = language.parse(input).unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(
            result.diagnostics.is_empty(),
            "unexpected diagnostics: {:?}",
            result.diagnostics
        );
        let out = TreeRecomposer::new(&mut source_recomposer())
            .recompose(&result.tree, ())
            .unwrap();
        assert_eq!(out, input);
        result
    }

    #[test]
    fn a_renamed_dispatch_pair_parses_environments() {
        assert_eq!(BeginSpec::<Latexlike>::new("shut").end_command_name(), "shut");

        let language = renamed_pair_language(Recovery::Strict);
        let result = parse_and_reemit(&language, "\\open{itemize} a \\shut{itemize}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.callable_type(), Some(CallableType::Environment));
        assert_eq!(env.environment_name(), Some("itemize"));
        assert_eq!(body_shapes(env), ["chars( a )"]);

        // The pair is this package's alone: `\begin` resolves to nothing here.
        let tolerant = renamed_pair_language(Recovery::Tolerant);
        let result = tolerant.parse("\\begin{itemize}\\end{itemize}").unwrap();
        let all = messages(&result);
        assert!(all[0].contains("cannot resolve command ‘\\begin’"), "{all:?}");
    }

    #[test]
    fn a_renamed_dispatch_pair_terminates_verbatim_bodies() {
        // The raw body reads up to the literal terminator composed from the
        // invocation's own spellings — the renamed command word included — and
        // reports it back as standard end facts, so the reemission is exact here too.
        let language = renamed_pair_language(Recovery::Strict);
        let result =
            parse_and_reemit(&language, "\\open{verbatim}\na % b \\x{\n\\shut{verbatim}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.environment_name(), Some("verbatim"));
        let body: Vec<_> = env.body().unwrap().iter().collect();
        assert_eq!(body.len(), 1);
        assert_eq!(body[0].chars(), Some("a % b \\x{\n"));
    }

    #[test]
    fn the_environment_conditions_quote_the_source_spelling() {
        // Neither condition spells a canonical `\begin`/`\end`: the malformed opening
        // quotes the command it was written with, and the orphan terminator quotes
        // its own consumed extent.
        let language = renamed_pair_language(Recovery::Tolerant);

        let result = language.parse("\\open x").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert_eq!(
            messages(&result),
            ["malformed ‘\\open’: expected the environment's name group immediately \
              after the command"]
        );

        let result = language.parse("\\shut{itemize}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert_eq!(
            messages(&result),
            ["orphan ‘\\shut{itemize}’: no environment ‘itemize’ is open here"]
        );
    }

    // --- recovery matrix ---------------------------------------------------------------

    #[test]
    fn terminator_name_mismatch_unwinds() {
        let content = "\\begin{A}x\\begin{B}y\\end{A}";
        let result = parse_tolerant(content);
        let all = messages(&result);
        assert_eq!(all.len(), 1);
        assert!(
            all[0].contains("missing terminator of environment ‘B’")
                && all[0].contains("‘A’"),
            "{}",
            all[0]
        );
        // B closed without consuming `\end{A}`; A found and consumed its own
        // terminator.
        let outer = result.tree.root().child(0).unwrap();
        assert_eq!(outer.environment_name(), Some("A"));
        assert_eq!(outer.span().range(), 0..content.len());
        assert_eq!(body_shapes(outer), ["chars(x)", "Environment(B)"]);

        let err = strict().parse(content).unwrap_err();
        assert!(err.to_string().contains("missing terminator of environment ‘B’"), "{err}");
    }

    #[test]
    fn missing_terminator_at_end_of_input() {
        let result = parse_tolerant("\\begin{itemize}x");
        let all = messages(&result);
        assert_eq!(all.len(), 1);
        assert!(
            all[0].contains("missing terminator of environment ‘itemize’ before end of input"),
            "{}",
            all[0]
        );
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.span().range(), 0..16);
        assert_eq!(body_shapes(env), ["chars(x)"]);

        assert!(strict().parse("\\begin{itemize}x").is_err());
    }

    #[test]
    fn malformed_terminator_consumes_the_command_alone() {
        let result = parse_tolerant("\\begin{itemize}x\\end y");
        let all = messages(&result);
        assert_eq!(all.len(), 1);
        assert!(
            all[0].contains("malformed terminator of environment ‘itemize’"),
            "{}",
            all[0]
        );
        // The command (with its post-space) is consumed; `y` is sibling content
        // after the environment.
        assert_eq!(
            root_shapes(&result),
            ["Environment(itemize)", "chars(y)"]
        );
    }

    #[test]
    fn stray_group_close_in_the_body_unwinds_to_the_root() {
        // The root's tolerant stray-close recovery stages the consumed delimiter as
        // a chars node (7.9, superseding 7.4's byte-dropping quirk), so the partition
        // invariant holds across the unwind.
        let result = tolerant().parse("\\begin{itemize}a}b").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        let all = messages(&result);
        assert_eq!(all.len(), 2, "{all:?}");
        assert!(all[0].contains("missing terminator of environment ‘itemize’"), "{}", all[0]);
        assert!(all[1].contains("‘}’"), "{}", all[1]);
        assert_eq!(
            root_shapes(&result),
            ["Environment(itemize)", "chars(})", "chars(b)"]
        );
    }

    #[test]
    fn unknown_environments_still_parse_their_body() {
        let content = "\\begin{foo}x\\end{foo} y";
        let result = parse_tolerant(content);
        assert_eq!(messages(&result), ["unknown environment ‘foo’"]);
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.environment_name(), Some("foo"));
        assert_eq!(body_shapes(env), ["chars(x)"]);

        let err = strict().parse(content).unwrap_err();
        assert!(err.to_string().contains("unknown environment ‘foo’"), "{err}");
    }

    #[test]
    fn malformed_begin_recovers_as_chars() {
        let result = parse_tolerant("\\begin x");
        let all = messages(&result);
        assert_eq!(all.len(), 1);
        assert!(all[0].contains("malformed ‘\\begin’"), "{}", all[0]);
        // The chars fallback covers the consumed extent — the trigger *with* its
        // syntactic post-space, keeping the sibling partition exact.
        assert_eq!(root_shapes(&result), ["chars(\\begin )", "chars(x)"]);

        assert!(strict().parse("\\begin x").is_err());
    }

    #[test]
    fn orphan_end_at_the_root() {
        let result = parse_tolerant("a\\end{itemize}b");
        assert_eq!(
            messages(&result),
            ["orphan ‘\\end{itemize}’: no environment ‘itemize’ is open here"]
        );
        assert_eq!(
            root_shapes(&result),
            ["chars(a)", "chars(\\end{itemize})", "chars(b)"]
        );

        let err = strict().parse("a\\end{itemize}b").unwrap_err();
        assert!(err.to_string().contains("orphan ‘\\end{itemize}’"), "{err}");
    }

    #[test]
    fn orphan_end_without_a_name_group() {
        let result = parse_tolerant("\\end x");
        // The quoted spelling stops at the command word: the trigger's post-space is
        // consumed with it (and staged), but reads as a stray blank inside quotes.
        assert_eq!(messages(&result), ["orphan ‘\\end’: no environment is open here"]);
        assert_eq!(root_shapes(&result), ["chars(\\end )", "chars(x)"]);
    }

    #[test]
    fn orphan_end_inside_a_group() {
        let result = parse_tolerant("{\\end{itemize}}");
        assert_eq!(
            messages(&result),
            ["orphan ‘\\end{itemize}’: no environment ‘itemize’ is open here"]
        );
        let group = result.tree.root().child(0).unwrap();
        assert!(group.is_group());
        assert_eq!(group.child(0).unwrap().summary(), "chars(\\end{itemize})");
    }

    #[test]
    fn bare_begin_in_expression_position_is_diagnosed() {
        // The documented divergence from pylatexenc (slots session): `\begin` as a
        // bare expression argument is diagnosed, not dispatched as the argument.
        let result = parse_tolerant("\\frac\\begin{itemize} x");
        let all = messages(&result);
        assert!(
            all.iter().any(|m| m.contains("requires content")),
            "{all:?}"
        );
    }

    // --- traceback vocabulary ----------------------------------------------------------

    #[test]
    fn argument_frames_quote_the_environment() {
        // An unresolvable command inside `tabular`'s mandatory argument: the
        // diagnostic's traceback quotes the environment's name, not `\begin`.
        let result = parse_tolerant("\\begin{tabular}{a\\foo}x\\end{tabular}");
        let diagnostic = result.diagnostics.iter().next().unwrap();
        let titles: Vec<&str> =
            diagnostic.frames().iter().map(|frame| frame.title()).collect();
        assert!(
            titles.contains(&"argument #1 of environment ‘tabular’"),
            "{titles:?}"
        );
        assert!(titles.contains(&"macro ‘\\begin’"), "{titles:?}");
    }

    #[test]
    fn body_frames_quote_the_environment() {
        // A condition inside the body: the body's frame quotes the environment.
        let result = parse_tolerant("\\begin{itemize}\\foo\\end{itemize}");
        let diagnostic = result.diagnostics.iter().next().unwrap();
        let titles: Vec<&str> =
            diagnostic.frames().iter().map(|frame| frame.title()).collect();
        assert!(titles.contains(&"environment ‘itemize’"), "{titles:?}");
    }

    // --- the spec surface --------------------------------------------------------------

    fn probe_invocation() -> EnvironmentInvocation<'static> {
        let scratch: Arc<crate::source::Source> = Arc::new(crate::source::Source::new(""));
        EnvironmentInvocation {
            trigger_span: SourceSpan::new(&scratch, 0..0),
            name: "probe",
            name_span: SourceSpan::new(&scratch, 0..0),
            escape_char: '\\',
            name_group_open: "{",
            name_group_close: "}",
            end_command_name: "end",
        }
    }

    #[test]
    fn with_body_delta_overrides_any_behavior() {
        // On the declarative standard behavior… (the infallible impls answer
        // through the `Ok(...)` wrapping — their only use of the `Result`).
        let spec = EnvironmentSpec::<Latexlike>::new(vec![]);
        assert!(spec.behavior().body_state_delta(probe_invocation()).unwrap().is_none());
        let spec = spec.with_body_delta(ParsingStateDelta::new().mode(Mode::Math));
        let delta =
            spec.behavior().body_state_delta(probe_invocation()).unwrap().unwrap();
        assert_eq!(delta.mode, Some(Mode::Math));

        // …and wrapping a custom behavior.
        #[derive(Debug)]
        struct Custom;
        impl EnvironmentBehavior for Custom {
            fn body_state_delta(
                &self,
                _invocation: EnvironmentInvocation<'_>,
            ) -> Result<Option<ParsingStateDelta<Latexlike>>, ParseError> {
                Ok(Some(ParsingStateDelta::new().mode(Mode::Text)))
            }
        }
        let custom = EnvironmentSpec::from_behavior(Arc::new(Custom))
            .with_body_delta(ParsingStateDelta::new().mode(Mode::Math));
        let delta =
            custom.behavior().body_state_delta(probe_invocation()).unwrap().unwrap();
        assert_eq!(delta.mode, Some(Mode::Math));
    }

    #[test]
    fn a_failing_body_state_delta_aborts_under_any_policy() {
        // The hook-fallibility contract on `body_state_delta`: an Err ends the
        // parse even under tolerant recovery — the composition derives the body
        // state from the answer, so there is no recovery channel — and the
        // composition attaches the live traceback (the `\begin` invocation frame).
        #[derive(Debug)]
        struct Broken;
        impl EnvironmentBehavior for Broken {
            fn body_state_delta(
                &self,
                _invocation: EnvironmentInvocation<'_>,
            ) -> Result<Option<ParsingStateDelta<Latexlike>>, ParseError> {
                let scratch: Arc<crate::source::Source> =
                    Arc::new(crate::source::Source::new(""));
                Err(ParseError::new(
                    crate::error::HookFailed::new("body-delta table unavailable", None),
                    SourceSpan::new(&scratch, 0..0),
                ))
            }
        }

        let mut package = Package::new("broken");
        package.insert(
            CallableType::Environment,
            "bad",
            EnvironmentSpec::from_behavior(Arc::new(Broken)),
        );
        let language = Language::new(
            LatexlikeDriver::new(Recovery::Tolerant),
            ParsingState::lang_initial_with_packages([package]).expect("seed state"),
        );
        let error = language.parse("\\begin{bad}x\\end{bad}").unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        assert_eq!(
            error.message(),
            "extension hook reported a failure: body-delta table unavailable"
        );
        // The `\begin` dispatch frame is live at the consultation site — the only
        // frame, as `bad` declares no arguments.
        assert_eq!(error.frames().len(), 1);
        assert_eq!(error.frames()[0].title(), "macro ‘\\begin’");
    }

    #[test]
    fn a_literal_terminator_the_record_cannot_store_aborts_under_any_policy() {
        // `StdEnvironmentSyntax` holds `\end{name}`-shaped end sides only. A body
        // parser reporting a bare literal terminator leaves it nothing to record, so
        // `from_parsed` fails and the composition aborts — recording a spelling that
        // source recomposition would emit wrongly is not an option.
        #[derive(Debug)]
        struct LiteralTerminated;
        impl EnvironmentBehavior for LiteralTerminated {
            fn make_body_parser<'p>(
                &'p self,
                invocation: EnvironmentInvocation<'p>,
            ) -> Box<dyn ConstructParser<Latexlike, Output = EnvironmentBody<Latexlike>> + 'p>
            {
                Box::new(VerbatimBodyParser::new(
                    invocation.trigger_span.clone(),
                    invocation.name,
                    VerbatimBodyTerminator::Literal {
                        terminator: String::from("\\end{lit}"),
                    },
                    GroupType::Verbatim,
                ))
            }
        }

        let mut package = Package::new("literal-terminator");
        package.insert(
            CallableType::Environment,
            "lit",
            EnvironmentSpec::from_behavior(Arc::new(LiteralTerminated)),
        );
        for recovery in [Recovery::Strict, Recovery::Tolerant] {
            let language = Language::new(
                LatexlikeDriver::new(recovery),
                ParsingState::lang_initial_with_packages([package.clone()])
                    .expect("seed state"),
            );
            let error = language.parse("\\begin{lit}x\\end{lit}").unwrap_err();
            assert_eq!(error.identifier(), "core.constructs.implementation-error");
            assert!(
                error.message().contains("environment ‘lit’"),
                "the message should name the environment: {}",
                error.message()
            );
            assert!(error.message().contains("literal terminator"), "{}", error.message());
        }
    }

    #[test]
    fn environment_spec_exposes_arguments_through_the_callable_trait() {
        let spec = EnvironmentSpec::new(vec![brace_arg()]);
        let dyn_spec: &dyn CallableSpec<Latexlike> = &spec;
        assert_eq!(dyn_spec.arguments().len(), 1);
        assert_eq!(
            dyn_spec.stack_frame_title(FrameRole::Invocation, "align"),
            "environment ‘align’"
        );
        assert_eq!(
            dyn_spec.stack_frame_title(FrameRole::Argument { index: 0 }, "align"),
            "argument #1 of environment ‘align’"
        );
    }

    #[test]
    fn a_generic_callable_spec_under_environment_gets_default_body_handling() {
        // A non-`EnvironmentSpec` registration under the Environment type: declared
        // arguments parse, the body takes the default handling.
        let mut package = Package::new("generic");
        package.insert(
            CallableType::Environment,
            "gen",
            Arc::new(crate::spec::StdCallableSpec { arguments: vec![brace_arg()], ..Default::default() }),
        );
        let language = Language::new(
            LatexlikeDriver::new(Recovery::Strict),
            ParsingState::lang_initial_with_packages([package]).expect("seed state"),
        );
        let result = language.parse("\\begin{gen}{a}x\\end{gen}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty());
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.environment_name(), Some("gen"));
        assert_eq!(env.arguments().unwrap().len(), 1);
        assert_eq!(body_shapes(env), ["chars(x)"]);
    }

    // --- verbatim bodies (7.7): `VerbatimBehavior` through the composition ------------

    #[test]
    fn verbatim_body_is_raw_text_with_the_newline_gobbled() {
        // pylatexenc test_latexnodes_parsers_verbatim test_simple, through the full
        // composition: escapes, `\begin`, comments, specials — all raw.
        let content = "\\begin{verbatim}\nHello world.\\\n\\macro, \\begin! % no comment; ~.\\( x\n\\end{verbatim}\n";
        let result = parse_ok(content);
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.environment_name(), Some("verbatim"));

        let evpos = content.find("\\end{verbatim}").unwrap();
        assert_eq!(env.span().range(), 0..evpos + "\\end{verbatim}".len());

        // Body content: everything between the gobbled newline and the terminator.
        let body: Vec<_> = env.body().unwrap().iter().collect();
        assert_eq!(body.len(), 1);
        assert_eq!(body[0].chars(), Some(&content[17..evpos]));
        // The raw chars node records the features-disabled verbatim state.
        assert!(!body[0].parsing_state().rules().commands_enabled());
        assert!(!body[0].parsing_state().rules().comments_enabled());

        // The gobbled newline is kept as the body list's first child — every byte
        // stays in the tree — but designated out of the content.
        let list = env.slot_content_parent(0).unwrap();
        assert_eq!(list.child_count(), 2);
        assert_eq!(list.child(0).unwrap().chars(), Some("\n"));

        // The newline after `\end{verbatim}` is ordinary sibling content.
        assert_eq!(result.tree.root().child(1).unwrap().chars(), Some("\n"));
    }

    #[test]
    fn verbatim_at_stream_end_and_without_a_leading_newline() {
        // pylatexenc test_simple_nofinaleol; no leading newline means no gobble.
        let result = parse_ok("\\begin{verbatim}abc %x\\end{verbatim}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.span().range(), 0..36);
        assert_eq!(body_shapes(env), ["chars(abc %x)"]);
        let list = env.slot_content_parent(0).unwrap();
        assert_eq!(list.child_count(), 1);
    }

    #[test]
    fn empty_and_newline_only_verbatim_bodies() {
        let result = parse_ok("\\begin{verbatim}\\end{verbatim}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(body_shapes(env), Vec::<String>::new());
        assert_eq!(env.slot_content_parent(0).unwrap().child_count(), 0);

        // A body that is just the gobbled newline: the node exists, the content is
        // empty.
        let result = parse_ok("\\begin{verbatim}\n\\end{verbatim}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(body_shapes(env), Vec::<String>::new());
        assert_eq!(env.slot_content_parent(0).unwrap().child_count(), 1);
    }

    #[test]
    fn verbatim_terminator_matching_is_literal() {
        // `\end {verbatim}` (with a space) is not the terminator — the raw scan
        // matches the literal string, pylatexenc's string-search parity — so the body
        // runs to end of input and recovers.
        let result = parse_tolerant("\\begin{verbatim}a\\end {verbatim}");
        assert_eq!(
            messages(&result),
            ["missing terminator of environment ‘verbatim’ before end of input"]
        );
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(body_shapes(env), ["chars(a\\end {verbatim})"]);
    }

    #[test]
    fn verbatim_does_not_nest() {
        // An inner `\begin{verbatim}` is raw text; the first terminator ends the body.
        let result = parse_ok("\\begin{verbatim}a\\begin{verbatim}b\\end{verbatim} c");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(body_shapes(env), ["chars(a\\begin{verbatim}b)"]);
        assert_eq!(result.tree.root().child(1).unwrap().chars(), Some(" c"));
    }

    #[test]
    fn starred_verbatim_terminates_on_its_own_name() {
        // `verbatim*` is an ordinary separate entry; the terminator back-references
        // the invocation's name, `*` included.
        let result = parse_ok("\\begin{verbatim*}a b\\end{verbatim*}");
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.environment_name(), Some("verbatim*"));
        assert_eq!(body_shapes(env), ["chars(a b)"]);
    }

    #[test]
    fn lstlisting_style_arguments_parse_before_the_raw_body() {
        // The option group parses tokenized, the raw body follows; the gobbled
        // newline lives inside the body list, so the callable's children block stays
        // span-contiguous (option group, then list — invariant 3).
        let content = "\\begin{lstlisting}[language=Python]\nif a<b: pass\n\\end{lstlisting}";
        let result = parse_ok(content);
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.child_count(), 2);
        assert!(env.arguments().unwrap().get(0).unwrap().is_provided());
        let option: Vec<_> = env.argument_content_nodes(0).unwrap().iter().collect();
        assert_eq!(option.len(), 1);
        assert_eq!(option[0].chars(), Some("language=Python"));
        assert_eq!(body_shapes(env), ["chars(if a<b: pass\n)"]);
    }

    #[test]
    fn unterminated_verbatim_environment_recovers() {
        let err = strict().parse("\\begin{verbatim}\nabc").unwrap_err();
        assert!(
            err.to_string().contains("missing terminator of environment ‘verbatim’"),
            "{err}"
        );

        let result = parse_tolerant("\\begin{verbatim}\nabc");
        assert_eq!(
            messages(&result),
            ["missing terminator of environment ‘verbatim’ before end of input"]
        );
        let env = result.tree.root().child(0).unwrap();
        assert_eq!(env.span().range(), 0..20);
        assert_eq!(body_shapes(env), ["chars(abc)"]);
    }
    // --- a latexlike-family language that does not obey span tiling (PLAN §1.5 R7) ----

    /// A `Language` over [`RelaxedLatexlike`] with `itemize` defined.
    fn relaxed_language() -> Language<RelaxedLatexlike> {
        let mut package: Package<RelaxedLatexlike> = Package::new("relaxed-envs");
        package
            .define_environment("itemize", core::iter::empty::<&str>())
            .expect("no argument codes");
        Language::new(
            LatexlikeDriver::new(Recovery::Tolerant),
            ParsingState::lang_initial_with_packages([Arc::new(package)]).expect("seed state"),
        )
    }

    /// The environment's name is read from a rigid name group — several `Char` tokens
    /// — and drives the spec lookup, the node's `name` and the diagnostics. For a
    /// language with `OBEYS_SPAN_TILING = false` it therefore comes from the characters
    /// as read, not from the name group's span; a wrong name would show up here as an
    /// unresolved environment.
    #[test]
    fn an_environment_name_is_read_exactly_where_the_language_does_not_obey_span_tiling() {
        // Over the standard reader the described span happens to be the exact range,
        // so what this pins is the accumulation path: the name the lookup and the node
        // see is the one `read_name_chars` collected character by character. A reader
        // whose described span says something else is the scripted reader's business.
        let input = r"\begin{itemize}x\end{itemize}";

        let mut package: Package<Latexlike> = Package::new("envs");
        package.define_environment("itemize", core::iter::empty::<&str>()).unwrap();
        let tiled = Language::new(
            LatexlikeDriver::new(Recovery::Tolerant),
            ParsingState::lang_initial_with_packages([Arc::new(package)]).expect("seed state"),
        )
        .parse(input)
        .expect("the parse runs");
        let relaxed = relaxed_language().parse(input).expect("the parse runs");

        assert!(tiled.diagnostics.is_empty(), "{:?}", tiled.diagnostics);
        assert!(
            relaxed.diagnostics.is_empty(),
            "the lookup found the environment: {:?}",
            relaxed.diagnostics
        );

        let tiled_env = tiled.tree.root().child(0).expect("the environment");
        let relaxed_env = relaxed.tree.root().child(0).expect("the environment");
        assert_eq!(tiled_env.name(), Some("itemize"));
        assert_eq!(relaxed_env.name(), Some("itemize"));
        assert_eq!(tiled_env.span().range(), relaxed_env.span().range());
        assert_eq!(
            tiled_env.children().len(),
            relaxed_env.children().len(),
            "the two environments differ in shape"
        );
        crate::node::validate_tree(&relaxed.tree).expect("the all-trees law holds");
        crate::latexlike::check_latexlike_tree_invariants(&relaxed.tree);
    }

    /// The orphan-`\end` recovery node covers the trigger and its name group — several
    /// tokens — so for a language with `OBEYS_SPAN_TILING = false` its content is the
    /// text of what was consumed, not the recorded span (which is only what the reader
    /// describes for the stretch). The diagnostic quotes the same text.
    #[test]
    fn the_orphan_end_recovery_owns_its_text_where_the_language_does_not_obey_span_tiling() {
        let relaxed = relaxed_language();

        for (input, recovered, quoted) in [
            ("a\\end{itemize}b", "\\end{itemize}", "\\end{itemize}"),
            // Without a name group the quote stops at the command word.
            ("\\end x", "\\end ", "\\end"),
        ] {
            // The tiled parse of the same input, for comparison.
            let tiled = parse_tolerant(input);
            let index = usize::from(input.starts_with('a'));
            let tiled_node = tiled.tree.root().child(index).expect("the recovery node");
            assert_eq!(tiled_node.chars(), Some(recovered));
            assert!(
                matches!(
                    tiled_node.kind(),
                    NodeKind::Chars { content: TextContent::Spanned(_), .. }
                ),
                "a tiled parse records the recovered extent as a span"
            );

            let result = relaxed.parse(input).expect("tolerant recovery");
            crate::latexlike::check_latexlike_tree_invariants(&result.tree);
            // The condition quotes the terminator as written — assembled the same way,
            // so the diagnostic names what was actually read.
            let rendered: Vec<String> =
                result.diagnostics.iter().map(|d| d.message().to_string()).collect();
            assert_eq!(rendered.len(), 1, "{rendered:?}");
            assert!(
                rendered[0].contains(&alloc::format!("orphan ‘{quoted}’")),
                "the diagnostic quotes the terminator as read: {rendered:?}"
            );
            let node = result.tree.root().child(index).expect("the recovery node");
            assert_eq!(node.chars(), Some(recovered), "the recovered text differs from {input:?}");
            assert!(
                matches!(node.kind(), NodeKind::Chars { content: TextContent::Owned(_), .. }),
                "a relaxed parse records the recovered extent as text, got {:?}",
                node.kind()
            );
            crate::node::validate_tree(&result.tree).expect("the all-trees law holds");
        }
    }

    // --- the environment after-effect leak channel (the `\gdef` shape) ------------------
    //
    // [§dd-dr:environment-after-effects], the environment companion of
    // [§dd-dr:group-after-effects]: the `\begin` composition routes the body's reported
    // interior record through `LatexlikeParseDriver::environment_after_effects` and
    // returns the survivor as the invocation's own after-effect, which the enclosing
    // content loop applies and records. An environment therefore leaks exactly what its
    // driver's hook keeps — and, level by level, composes the escape outward.

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

    /// A member of the latexlike family whose driver installs the after-effect leak
    /// hooks: the preset's vocabularies, seed, specs and parsers are unchanged — only
    /// the driver differs, which is what makes the hooks the site under test (the
    /// `Driver: LatexlikeParseDriver<Self>` bound is what a custom driver opts into).
    #[derive(Debug, Clone, Copy)]
    struct GdefLatexlike;

    impl Lang for GdefLatexlike {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = GroupType;
        type CallableTypeId = CallableType;
        type ModeId = Mode;
        type StateExt = ();
        type Event = crate::latexlike::Event;
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = crate::latexlike::LatexlikeNodeExts;
        type InvocationSyntax =
            crate::latexlike::InvocationSyntaxData<crate::latexlike::StdEnvironmentSyntax<Self>>;
        type Driver = GdefDriver;

        /// The preset's own seed, for this language's vocabularies.
        fn initial_state_data(
        ) -> Result<crate::state::StateData<Self>, crate::state::FinalizeError> {
            let mut scopes = crate::scopes::ScopeStack::new();
            scopes.push(crate::latexlike::builtin_package());
            Ok(crate::state::StateData {
                rules: crate::latexlike::default_token_rules(),
                scopes,
                mode: Mode::Text,
                ext: (),
            })
        }

        fn scan_specials(
            state: &ParsingState<Self>,
            content: &str,
            pos: usize,
        ) -> Result<Option<crate::token::SpecialsMatch<Self>>, crate::token::SpecialsScanError>
        {
            state.scopes().scan_specials(state, content, pos)
        }

        fn specials_trigger_chars(
            data: &crate::state::StateData<Self>,
        ) -> crate::token::TriggerChars {
            data.scopes.specials_trigger_chars()
        }

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

    impl LatexlikeLang for GdefLatexlike {}

    /// The leak filter, shared verbatim by the group-level and the environment-level
    /// hook: keep the ops the language tagged as global, drop the rest. A merged record
    /// carries no provenance, so a `\gdef`-vs-`\def` split *is* this structural filter
    /// over the scope each op targets (both hook types' documentation).
    fn keep_global_defines(
        record: Option<Box<ParsingStateDelta<GdefLatexlike>>>,
    ) -> Option<Box<ParsingStateDelta<GdefLatexlike>>> {
        let record = record?;
        let ops = <<GdefLatexlike as Lang>::Features as LangFeatures>::Scopes::store_get(
            &record.scope_ops,
        )
        .expect("the lang declares the scopes feature present");
        let kept: Vec<ScopeOp<GdefLatexlike>> = ops
            .iter()
            .filter(|op| matches!(op, ScopeOp::Define { scope, .. } if &**scope == GLOBAL))
            .cloned()
            .collect();
        if kept.is_empty() {
            return None;
        }
        let mut escaping = ParsingStateDelta::new();
        for op in kept {
            escaping = escaping.scope_op(op);
        }
        Some(Box::new(escaping))
    }

    /// The group-level hook as the driver stores it: a closure (it captures the call
    /// counter), handed to [`GroupParser::new_with_after_effects`] as a borrowed
    /// `dyn Fn`.
    #[allow(clippy::type_complexity)]
    type GroupHook = Box<
        dyn Fn(
                &Arc<GroupRule<GdefLatexlike>>,
                &Arc<ParsingState<GdefLatexlike>>,
                &Arc<ParsingState<GdefLatexlike>>,
                Option<Box<ParsingStateDelta<GdefLatexlike>>>,
            ) -> Result<Option<Box<ParsingStateDelta<GdefLatexlike>>>, ParseError>
            + Send
            + Sync,
    >;

    /// What [`GdefDriver`]'s environment hook answers.
    #[derive(Debug, Clone, Copy)]
    enum EnvironmentPolicy {
        /// Keep the globally-targeted defines — the `\gdef` policy.
        Leak,
        /// Fail: the hook-fallibility contract's abort channel.
        Fail,
    }

    /// [`GdefLatexlike`]'s driver: the preset's behavior throughout — every
    /// [`ParseDriver`] hook is the wrapped [`LatexlikeDriver`]'s own answer — plus the
    /// two after-effect leak hooks, the group-level one installed on every group descent
    /// and the environment-level one from [`LatexlikeParseDriver`]. Both run the same
    /// filter, which is what makes the two constructs' escapes comparable.
    struct GdefDriver {
        inner: LatexlikeDriver<GdefLatexlike>,
        /// `None` = the stock behavior (nothing escapes a group).
        group_hook: Option<GroupHook>,
        /// What the environment hook does.
        environment_policy: EnvironmentPolicy,
        /// Environment hook calls, so the tests can pin one call per level.
        environment_calls: AtomicUsize,
        /// Of those, the ones handed an empty record.
        empty_records: AtomicUsize,
        /// Group hook calls (shared with the closure that counts them).
        group_calls: Arc<AtomicUsize>,
    }

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

    impl GdefDriver {
        fn new(group_hook: bool, environment_policy: EnvironmentPolicy) -> GdefDriver {
            let group_calls = Arc::new(AtomicUsize::new(0));
            // The closure captures the counter — the reason the hook is a boxed
            // `dyn Fn` and not a bare `fn` pointer.
            let counter = Arc::clone(&group_calls);
            let hook: GroupHook = Box::new(move |_rule, initial, exit, record| {
                counter.fetch_add(1, Ordering::Relaxed);
                if record.is_none() {
                    assert!(Arc::ptr_eq(initial, exit));
                }
                Ok(keep_global_defines(record))
            });
            GdefDriver {
                inner: LatexlikeDriver::new(Recovery::Tolerant),
                group_hook: group_hook.then_some(hook),
                environment_policy,
                environment_calls: AtomicUsize::new(0),
                empty_records: AtomicUsize::new(0),
                group_calls,
            }
        }

        /// Both hooks installed, both keeping the globally-targeted defines.
        fn leaking() -> GdefDriver {
            GdefDriver::new(true, EnvironmentPolicy::Leak)
        }

        /// The environment hook fails; no group hook (the failure is the subject).
        fn failing() -> GdefDriver {
            GdefDriver::new(false, EnvironmentPolicy::Fail)
        }

        fn environment_calls(&self) -> usize {
            self.environment_calls.load(Ordering::Relaxed)
        }

        fn empty_records(&self) -> usize {
            self.empty_records.load(Ordering::Relaxed)
        }

        fn group_calls(&self) -> usize {
            self.group_calls.load(Ordering::Relaxed)
        }
    }

    impl ParseDriver<GdefLatexlike> for GdefDriver {
        fn recovery(&self) -> Recovery {
            self.inner.recovery()
        }

        fn source_resolver(&self) -> Option<&dyn crate::source::SourceResolver<Option<String>>> {
            self.inner.source_resolver()
        }

        fn observe_parse_start(
            &self,
            source: &Arc<crate::source::Source<Option<String>>>,
            seed: &Arc<ParsingState<GdefLatexlike>>,
            diagnostics: &mut crate::error::Diagnostics<Option<String>>,
        ) {
            self.inner.observe_parse_start(source, seed, diagnostics);
        }

        fn resolve_command(
            &self,
            state: &ParsingState<GdefLatexlike>,
            token: &Token<GdefLatexlike>,
            tokens: &dyn TokenReader<'_, GdefLatexlike>,
        ) -> Result<CommandResolution<GdefLatexlike>, ParseError> {
            self.inner.resolve_command(state, token, tokens)
        }

        fn make_paragraph_break_node(
            &self,
            state: &ParsingState<GdefLatexlike>,
            break_span: &SourceSpan<Option<String>>,
        ) -> NodeKind<GdefLatexlike> {
            self.inner.make_paragraph_break_node(state, break_span)
        }

        fn group_interior_delta(
            &self,
            base: &ParsingState<GdefLatexlike>,
            rule: &Arc<GroupRule<GdefLatexlike>>,
        ) -> Option<ParsingStateDelta<GdefLatexlike>> {
            self.inner.group_interior_delta(base, rule)
        }

        fn resolve_state_event(
            &self,
            event: &crate::latexlike::Event,
            stack: &ParsingStateStack<GdefLatexlike>,
        ) -> Result<Option<ParsingStateDelta<GdefLatexlike>>, ParseError> {
            self.inner.resolve_state_event(event, stack)
        }

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

    /// The one-line opt-in the trait's defaults are designed for — here with the one
    /// hook overridden.
    impl LatexlikeParseDriver<GdefLatexlike> for GdefDriver {
        fn environment_after_effects(
            &self,
            invocation: &EnvironmentInvocation<'_, GdefLatexlike>,
            spec: &Arc<dyn CallableSpec<GdefLatexlike>>,
            initial: &Arc<ParsingState<GdefLatexlike>>,
            exit: &Arc<ParsingState<GdefLatexlike>>,
            record: Option<Box<ParsingStateDelta<GdefLatexlike>>>,
        ) -> Result<Option<Box<ParsingStateDelta<GdefLatexlike>>>, ParseError> {
            self.environment_calls.fetch_add(1, Ordering::Relaxed);
            // Arguments 1 and 2: the invocation facts and the resolved spec — jointly
            // what a policy keys on, in place of the group hook's matched `GroupRule`.
            assert!(matches!(invocation.name, "center" | "outer"), "{}", invocation.name);
            assert_eq!(invocation.end_command_name, "end");
            assert!(spec.arguments().is_empty());
            // Arguments 3 and 4: the body's two states. An interior that generated
            // nothing never left the state it started in; one that did is inspectable
            // only here (the record carries operations, not a symbol table).
            match &record {
                None => {
                    self.empty_records.fetch_add(1, Ordering::Relaxed);
                    assert!(Arc::ptr_eq(initial, exit));
                }
                Some(_) => assert!(!Arc::ptr_eq(initial, exit)),
            }
            match self.environment_policy {
                EnvironmentPolicy::Leak => Ok(keep_global_defines(record)),
                EnvironmentPolicy::Fail => Err(ParseError::new(
                    HookFailed::new("the leak policy table is unavailable", None),
                    invocation.name_span.clone(),
                )),
            }
        }
    }

    /// `scope`-targeted definition of the zero-argument macro `name` — the language
    /// tagging its own op, which is all a hook has to discriminate on.
    fn defining<LLL: LatexlikeLang>(scope: &str, name: &str) -> ParsingStateDelta<LLL> {
        ParsingStateDelta::new().scope_op(ScopeOp::Define {
            scope: scope.into(),
            callable_type: LLL::CallableTypeId::macro_callable(),
            name: name.into(),
            spec: Arc::new(MacroSpec::<LLL>::default()),
        })
    }

    /// The suite's definitions, for any family member: `\gdef` and `\def` — zero-argument
    /// macros whose after-effects define `\g` and `\d` in the globally-named and in a
    /// local scope respectively — and the plain environments `center` and `outer`.
    fn gdef_package<LLL: LatexlikeLang>() -> Package<LLL> {
        let mut package = Package::new("gdef-definitions");
        let macro_type = LLL::CallableTypeId::macro_callable();
        let environment_type = LLL::CallableTypeId::environment_callable();
        package.insert(
            macro_type,
            "gdef",
            MacroSpec::<LLL>::new(vec![]).with_after_effect(defining(GLOBAL, "g")),
        );
        package.insert(
            macro_type,
            "def",
            MacroSpec::<LLL>::new(vec![]).with_after_effect(defining(LOCAL, "d")),
        );
        package.insert(environment_type, "center", Arc::new(EnvironmentSpec::<LLL>::new(vec![])));
        package.insert(environment_type, "outer", Arc::new(EnvironmentSpec::<LLL>::new(vec![])));
        package
    }

    /// The suite's seed: the family member's own seed plus the definitions above and the
    /// document-level scope `\gdef` defines into.
    fn gdef_seed<LLL: LatexlikeLang>() -> ParsingState<LLL> {
        let definitions: Arc<dyn SpecsProvider<LLL>> = Arc::new(gdef_package::<LLL>());
        let global: Arc<dyn SpecsProvider<LLL>> = Arc::new(Scope::<LLL>::new(GLOBAL));
        ParsingState::lang_initial_with_packages([definitions, global]).expect("seed state")
    }

    /// A [`GdefLatexlike`] language under `driver`.
    fn gdef_language(driver: GdefDriver) -> Language<GdefLatexlike> {
        Language::new(driver, gdef_seed::<GdefLatexlike>())
    }

    /// Parse `input`, check the tree, and report `(root child summaries, diagnostics)`.
    fn gdef_parse(
        language: &Language<GdefLatexlike>,
        input: &str,
    ) -> (Vec<String>, Vec<String>) {
        let result = language.parse(input).expect("the parse runs");
        check_latexlike_tree_invariants(&result.tree);
        let shapes = result.tree.root().children().iter().map(|n| n.summary()).collect();
        let messages = result.diagnostics.iter().map(|d| d.message().to_string()).collect();
        (shapes, messages)
    }

    #[test]
    fn an_environment_leaks_the_after_effects_its_hook_keeps_exactly_as_a_group_does() {
        // The acceptance pair: the same `\gdef` inside a group and inside an
        // environment, under a driver whose two hooks run the same filter. Both leak,
        // so the following `\g` resolves in both — an environment's escape channel is
        // the group's, one construct level up.
        for input in ["{\\gdef}\\g", "\\begin{center}\\gdef\\end{center}\\g"] {
            let language = gdef_language(GdefDriver::leaking());
            let (shapes, messages) = gdef_parse(&language, input);
            assert!(messages.is_empty(), "{input:?}: {messages:?}");
            // The construct, then `\g` as a resolved callable (an unresolved command
            // would be a `chars` recovery node plus a diagnostic).
            assert_eq!(shapes.len(), 2, "{input:?}: {shapes:?}");
            assert_eq!(shapes[1], "Macro(g)", "{input:?}: {shapes:?}");
            // One hook call at the one construct level, whichever construct it was.
            assert_eq!(
                language.driver().group_calls() + language.driver().environment_calls(),
                1,
                "{input:?}",
            );
        }
    }

    #[test]
    fn a_locally_targeted_definition_escapes_neither_a_group_nor_an_environment() {
        // The other half of the structural split: `\def` tags its op with a local
        // scope, the filter drops it, and the construct's boundary is where the
        // definition dies — in a group and in an environment alike.
        for input in ["{\\def}\\d", "\\begin{center}\\def\\end{center}\\d"] {
            let language = gdef_language(GdefDriver::leaking());
            let (shapes, messages) = gdef_parse(&language, input);
            assert_eq!(messages.len(), 1, "{input:?}: {messages:?}");
            assert!(messages[0].contains("cannot resolve command ‘\\d’"), "{messages:?}");
            assert_eq!(shapes[1], "chars(\\d)", "{input:?}: {shapes:?}");
        }
    }

    #[test]
    fn the_stock_driver_lets_nothing_escape_an_environment() {
        // The `Ok(None)` trait default, on the canned assembly whose
        // `LatexlikeParseDriver` impl is the empty one: `\gdef` inside an environment
        // is scoped to it exactly as it is inside a group, and `\g` after either
        // construct is unresolvable.
        let language = Language::new(
            LatexlikeDriver::<Latexlike>::new(Recovery::Tolerant),
            gdef_seed::<Latexlike>(),
        );
        for input in ["\\begin{center}\\gdef\\end{center}\\g", "{\\gdef}\\g"] {
            let result = language.parse(input).expect("the parse runs");
            check_latexlike_tree_invariants(&result.tree);
            assert_eq!(messages(&result).len(), 1, "{input:?}: {:?}", messages(&result));
            assert_eq!(root_shapes(&result)[1], "chars(\\g)", "{input:?}");
        }
    }

    #[test]
    fn an_escape_composes_outward_through_nested_environments_and_groups() {
        // One hook per level, so the survivor of the inner filter is the raw record the
        // next level out is offered: the enclosing content loop applies the returned
        // delta *and* merges it into its own record, which is what the enclosing
        // construct's hook then sees.
        let language = gdef_language(GdefDriver::leaking());
        let (shapes, messages) = gdef_parse(
            &language,
            "\\begin{outer}\\begin{center}\\gdef\\end{center}\\end{outer}\\g",
        );
        assert!(messages.is_empty(), "{messages:?}");
        assert_eq!(shapes[1], "Macro(g)", "{shapes:?}");
        assert_eq!(language.driver().environment_calls(), 2);

        // The two constructs interleave just as freely: a group inside an environment.
        let language = gdef_language(GdefDriver::leaking());
        let (shapes, messages) =
            gdef_parse(&language, "\\begin{center}{\\gdef}\\end{center}\\g");
        assert!(messages.is_empty(), "{messages:?}");
        assert_eq!(shapes[1], "Macro(g)", "{shapes:?}");
        assert_eq!(language.driver().group_calls(), 1);
        assert_eq!(language.driver().environment_calls(), 1);

        // …and an environment inside a group.
        let language = gdef_language(GdefDriver::leaking());
        let (shapes, messages) =
            gdef_parse(&language, "{\\begin{center}\\gdef\\end{center}}\\g");
        assert!(messages.is_empty(), "{messages:?}");
        assert_eq!(shapes[1], "Macro(g)", "{shapes:?}");
        assert_eq!(language.driver().group_calls(), 1);
        assert_eq!(language.driver().environment_calls(), 1);
    }

    #[test]
    fn the_environment_hook_is_called_unconditionally() {
        // Like the group hook: an empty record is a fact worth being told, and a policy
        // keying on the invocation alone must still run. An empty-bodied environment
        // reaches the hook with `record = None`.
        let language = gdef_language(GdefDriver::leaking());
        let (shapes, messages) = gdef_parse(&language, "\\begin{center}\\end{center}\\g");
        assert_eq!(messages.len(), 1, "{messages:?}");
        assert_eq!(shapes[1], "chars(\\g)", "{shapes:?}");
        assert_eq!(language.driver().environment_calls(), 1);
        assert_eq!(language.driver().empty_records(), 1);

        // A body that parses nodes but generates no after-effect reaches it the same
        // way, still with an empty record.
        let language = gdef_language(GdefDriver::leaking());
        let (_, messages) = gdef_parse(&language, "\\begin{center}x\\end{center}");
        assert!(messages.is_empty(), "{messages:?}");
        assert_eq!(language.driver().environment_calls(), 1);
        assert_eq!(language.driver().empty_records(), 1);
    }

    #[test]
    fn a_failing_environment_after_effects_hook_aborts_under_any_policy() {
        // The hook-fallibility contract, on the environment's escape channel: an Err
        // ends the parse even under tolerant recovery — it is an error, not a
        // diagnostic — and the composition attaches the live traceback (a driver hook
        // has no session access), so the `\begin` dispatch names the context.
        let language = gdef_language(GdefDriver::failing());
        let error = language.parse("\\begin{center}x\\end{center}").unwrap_err();
        assert_eq!(error.identifier(), "core.hooks.hook-failed");
        assert_eq!(
            error.message(),
            "extension hook reported a failure: the leak policy table is unavailable"
        );
        // The error is anchored where the hook put it — the environment's name.
        assert_eq!(error.span().range(), 7..13);
        // The `\begin` dispatch frame is live at the routing site — the only frame, as
        // `center` declares no arguments and the body parser's own frame is long popped.
        assert_eq!(error.frames().len(), 1);
        assert_eq!(error.frames()[0].title(), "macro ‘\\begin’");
        assert_eq!(language.driver().environment_calls(), 1);
    }
}