rustyfi-syntax 0.1.4

Lexer, token stream, and syan2-based surface grammar for SATySFi
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
//! The SATySFi **0.1.0** (`dev-0-1-0`) surface grammar — a *fork* of
//! [`crate::cst`], not a version-gate of it (gating one shared `cst.rs` would
//! mean hand-writing `Parse` for nearly every node, destroying the derive
//! idiom and risking 0.0.6 on every 0.1 edit). [`crate::cst`] stays frozen:
//! this module imports only its token-`Atom`-generic, non-recursive helpers
//! ([`crate::cst::Header`], [`crate::cst::ParseFileError`]) and re-declares
//! everything else — including its own `*ErasedV1` eraser leaves and its own
//! copy of `render_parse_error` — so that touching `cst_v1.rs` never touches
//! `cst.rs`.
//!
//! **Scope.** SATySFi 0.1's grammar adds a whole ML-style module system
//! (`bind`/`modexpr`/`sigexpr`/`decl`) on top of an expr/pattern/type layer
//! that is structurally close to 0.0.6's, plus five surface deltas:
//! `,`-separated lists/records (not `;`), `EXACT_EQ` for both definitional
//! and record `=` (reusing [`DefEqTok`] — no new `=` leaf), mandatory
//! `match … with … end`, per-binding staging instead of a whole-file
//! `@stage:` header, and no `when`/`while`/`before` at all. This module
//! builds:
//!
//! * [`FileV1`] — `header* expr EOI` or `header* module Name
//!   option(sig_annot) = struct bind* end EOI`.
//! * [`Bind`] — every arm of upstream `bind`: `val`/`val inline`/`val
//!   block`, `val math` (math-split — see
//!   [`Bind::ValueMath`]), `val rec … and …`/`val mutable`/`type … and …`,
//!   `module … = modexpr`/`signature … = sigexpr`/`include
//!   modexpr`.
//! * [`ast::ModExpr`]/[`ast::SigExpr`]/[`ast::Decl`] — the full
//!   module/signature grammar: functor literals/
//!   application, module paths/aliases, `:>` coercion, `sig … end` with
//!   every `decl` form, `with type` refinement, `include`.
//! * A copy of [`crate::cst::ast`]'s expr/pattern/type layer with the 0.1
//!   deltas applied (see each type's doc comment for the exact delta),
//!   including the full `let rec … and … in`/`let mutable … in` expression
//!   forms, a widened `TypeExpr` grammar (products, prefix application),
//!   `inline […]`/`block […]`/`math […]` command types
//!   (`parser_v1.mly:730-735`) and `LONG_LOWER` qualified type paths
//!   (`:720-728,742-743`; `TypeApp::AppliedLong`/`TypeAtom::LongName`).
//!
//! **Grammar shipped with placeholder semantics only.** Every
//! module/signature construct beyond the struct-literal
//! `ModExpr::Struct` body PARSES and round-trips, but lowers to a precise
//! `LowerError` (`v1/lower.rs`) rather than real semantics — see that
//! module's doc comment for the placeholder set and the seal rule.
//!
//! **Deliberately NOT built**: macro binds/decls
//! and row quantifiers (`rowquant`). Staging DOES parse — the
//! operand prefixes `&e`/`~e` ([`ast::StagePrefix`],
//! `parser_v1.mly:870-873`) and the per-binding qualifier of `val ~x`/`val
//! persistent ~x` ([`BindStageV1`], `:417-421` and the decl form
//! `:600-603`), with `persistent` a 0.1-only keyword token.
//!
//! **The `#[recurse]` SCC story (five roots).** Five
//! singleton, directly self-referential roots — the same shape
//! [`crate::cst::ast`] uses, for the same reason (see its module doc comment
//! for the measured compile-time blowup a naive transcription hits):
//!
//! * [`ast::Expr`] (its variants' own `Box<Expr>` children);
//! * [`ast::PatBot`] (`CtorApplied`'s `Box<PatBot>` argument);
//! * [`ast::TypeExpr`] (`Fun`'s right-recursive `Box<TypeExpr>` codomain);
//! * [`ast::ModExpr`] (`Functor.body`'s `Box<ModExpr>` self-loop);
//! * [`ast::SigExpr`] (`Functor.dom`/`Functor.cod`'s `Box<SigExpr>`
//!   self-loop — encoded left-recursion-safe, `with` is
//!   bot+suffix, never `With { base: Box<SigExpr> }`; see [`ast::SigExpr`]'s
//!   own doc comment).
//!
//! Every other recursion edge is routed through the erasers declared below
//! ([`ExprErasedV1`], [`PatErasedV1`], [`PatBotErasedV1`], [`TyErasedV1`],
//! [`MathErasedV1`], [`ModExprErasedV1`], [`SigExprErasedV1`],
//! [`TypeBindsErasedV1`]), keeping each SCC a singleton and the wrapped
//! grammar's recursion reborrowing one stream type (syan pins it, not us).
//! [`ast::Decl`] is a satellite, not a root: it has no `Box<Self>` anywhere
//! and no type inside the `#[recurse]` module ever names it — it is reached
//! only through the hand-written [`StructDeclV1`] connector (an opaque leaf
//! to the SCC analysis, mirroring [`StructBindV1`]), so `SigExpr ↔ Decl`
//! never forms a rootless static sub-cycle.

use crate::leaf::*;
use newer_type::implement;
use syan::parse::{Parse, Unparse};

/// `@require:` / `@import:` header element — byte-identical between 0.0.6
/// and `dev-0-1-0` (this port's own confirmation), so 0.1 simply reuses
/// [`crate::cst`]'s definition rather than re-declaring an identical enum.
/// 0.1 has no `@stage:` header at all (the shared lexer's `V0_1` path
/// rejects it outright — see `lexer.rs`'s `lex_header`), so
/// [`crate::cst::Header`]'s absence of a `Stage` variant costs nothing here.
pub use crate::cst::Header;

/// A 0.1 header element — the UNION of BOTH packaging generations' header
/// forms (Axis B). `Legacy` is `dev-0-1-0`'s `@require:`/`@import:`
/// (byte-identical to 0.0.6's, reusing [`Header`]); the three `Use*`
/// forms are `saphe-split`'s `headerelem` (`parser.mly:371-380 @ b836d512`).
/// Which family is *legal* is a `LoadMode` question the loader answers
/// (`rustyfi_loader`), not a grammar question — this ONE `V0_1` grammar
/// accepts both so the mode error can be raised at load time with a better
/// message than a lex error would give.
///
/// Variant order is parse priority (syan ordered-alternatives, most-specific
/// first): `UsePackage` (the `package` keyword disambiguates) precedes the
/// `of`-suffixed `UseOf`, which precedes bare `Use` (longest-match: `use M of
/// …` must claim its `of` before a bare `use M` matches), which precedes the
/// token-disjoint `Legacy` (`@`-headers lex to distinct tokens).
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub enum HeaderV1 {
    /// `USE PACKAGE optional_open mod_chain` — depend on an installed package
    /// by its consumer-chosen alias (`used_as`). Header attributes
    /// (`#[test-only]` etc., upstream `list(attribute)`) are DEFERRED.
    UsePackage {
        use_kw: KwUse,
        package_kw: KwPackage,
        open_kw: Option<KwOpen>,
        path: ast::ModChainV1,
    },
    /// `USE optional_open mod_chain OF STRING` — load a local file by
    /// backtick-quoted relative path (the `@import:` analog).
    UseOf {
        use_kw: KwUse,
        open_kw: Option<KwOpen>,
        path: ast::ModChainV1,
        of_kw: KwOf,
        relpath: LiteralTok,
    },
    /// `USE optional_open mod_chain` — sibling module inside the same package
    /// (closed resolution; only legal inside envelope source trees, enforced
    /// by the loader).
    Use {
        use_kw: KwUse,
        open_kw: Option<KwOpen>,
        path: ast::ModChainV1,
    },
    /// `@require:`/`@import:` — Legacy packaging, unchanged shape.
    Legacy(Header),
}

impl HeaderV1 {
    /// A short human-readable name for this header, for loader diagnostics
    /// (e.g. `use package Stdlib`, `@require: foo`).
    pub fn display_name(&self) -> String {
        match self {
            Self::UsePackage { path, .. } => format!("use package {}", path.render()),
            Self::UseOf { path, relpath, .. } => {
                format!("use {} of `{}`", path.render(), relpath.body)
            }
            Self::Use { path, .. } => format!("use {}", path.render()),
            Self::Legacy(Header::Require(t)) => format!("@require: {}", t.content),
            Self::Legacy(Header::Import(t)) => format!("@import: {}", t.content),
            Self::Legacy(Header::Stage(_)) => "@stage:".to_string(),
        }
    }
}

impl ast::ModChainV1 {
    /// The dotted path as source text, e.g. `Stdlib.Logo` or `Local`.
    pub fn render(&self) -> String {
        match self {
            Self::Long(t) => {
                let mut parts = t.mods.clone();
                parts.push(t.name.clone());
                parts.join(".")
            }
            Self::Single(t) => t.name.clone(),
        }
    }

    /// The HEAD component — the module/envelope identifier the loader keys
    /// dependency resolution off (upstream's `used_as` map is keyed by it;
    /// the tail is submodule access, a typecheck-time concern). For `A.B.C`
    /// that is `A`; for a bare `A` it is `A`.
    pub fn head_name(&self) -> String {
        match self {
            Self::Long(t) => t.mods.first().cloned().unwrap_or_else(|| t.name.clone()),
            Self::Single(t) => t.name.clone(),
        }
    }
}

/// A binding-position NAME: `LOWER | ( binop )` — upstream 0.1's
/// `bound_identifier` (`parser_v1.mly:358-363`) is the same nonterminal
/// 0.0.6's `var` folds ([`crate::cst::BindName`]'s doc comment), and the
/// leaf-level parse (`VarTok` | `OpNameTok`) is identical in both
/// generations, so 0.1 reuses the type rather than re-declaring it —
/// another token-generic, non-recursive import like [`Header`] above.
pub use crate::cst::BindName;

/// A whole 0.1 `.saty`/`.satyh` file (`main`, upstream `parser_v1.mly:364-
/// 368`): a header list followed by either a library (`main_lib`) or a
/// document expression. Unlike 0.0.6's [`crate::cst::File`] (a flat prelude
/// of top-level `let`s with an optional trailing `in body`), 0.1 has no flat
/// top-level binding sequence at all: a document body is *just* an
/// [`ast::Expr`] (every `let` chains its own `in`), and a library is exactly
/// one `module … = struct … end`.
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub enum FileV1 {
    /// `header* expr EOI` (`parser_v1.mly:367`).
    Document {
        headers: Vec<HeaderV1>,
        body: ast::Expr,
        eoi: EoiTok,
    },
    /// `header* MODULE UPPER option(sig_annot) EXACT_EQ STRUCT bind* END
    /// EOI` (`parser_v1.mly:372-375`, `main_lib`; `sig_annot = COERCE
    /// sigexpr`, `:555-557`). Note 0.1's annotation sigil is
    /// `:>` (COERCE), never 0.0.6's `: sig … end`.
    Library {
        headers: Vec<HeaderV1>,
        module_kw: KwModule,
        name: CtorTok,
        sig_annot: Option<SigAnnotV1>,
        eq: DefEqTok,
        struct_kw: KwStruct,
        binds: Vec<Bind>,
        end_kw: KwEnd,
        eoi: EoiTok,
    },
}

/// `COERCE sigexpr` — a signature annotation `:> S` (`sig_annot`,
/// `parser_v1.mly:555-557`). 0.1's annotation sigil is `:>` (COERCE,
/// `lexer_v1.mll:280`), NOT 0.0.6's `: sig … end` ([`crate::cst::SigAnnot`],
/// `cst.rs:295-303`) — `module M : S = …` is a 0.1 parse error (pinned in
/// tests). The signature body goes through [`SigExprErasedV1`]: `SigAnnotV1`
/// lives outside the `#[recurse]` module, so this is a cross-boundary edge
/// into the `SigExpr` root (see the module doc comment's SCC story).
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub struct SigAnnotV1 {
    pub coerce: CoerceTok,
    pub sig_: SigExprErasedV1,
}

/// One parameter of a [`Bind`] (`param_unit`, `parser_v1.mly:635-646`): an
/// optional `?(l = x, …)` labeled-optional binder bundle, then either a
/// plain `patbot` or a `( pat : τ )` ascribed pattern
/// ([`ast::ParamBody::Ascribed`]). Defined INSIDE [`mod@ast`]
/// and re-exported here so that [`ast::Expr::Fun`]/[`ast::Expr::LetIn`]/
/// [`ast::RecClauseV1`] can reference it without a boundary-crossing
/// Parse-trait cycle (the `TypeBindsErasedV1` E0275 hazard).
pub use ast::{AscribedInnerV1, OptParamEntryV1, OptParamsV1, Param, ParamBody};

/// Every arm of `bind` (`parser_v1.mly:415-440`) — upstream's own
/// nonterminal name (helper types like [`StructBindV1`]/
/// [`TypeBindSingleV1`] keep a `V1` suffix). Every value arm's `=` is
/// `EXACT_EQ` ([`DefEqTok`]) and body is an [`ast::Expr`]. `name` is a
/// [`crate::cst::BindName`] wherever upstream's `bound_identifier` reaches it
/// (`Value`, and the rec clauses inside [`ast::RecClauseV1`]); `ValueMutable`
/// and `ValueInline`/`ValueBlock`'s `ctx` stay plain [`VarTok`]s — upstream's
/// `MUTABLE LOWER …`/ctx-variable productions are a plain `LOWER`, not
/// `bound_identifier` (see [`crate::cst::BindName`]'s doc comment for the
/// ordered-choice-safety argument).
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub enum Bind {
    /// `VAL PERSISTENT? EXACT_TILDE? bind_value_nonrec`
    /// (`parser_v1.mly:416-421,442,459-465`): `val <stage>? <name> <param>*
    /// = <expr>`, where `<stage>` is `~` (stage 0) or `persistent ~` (the
    /// persistent stage) and its absence means stage 1, the document stage.
    ///
    /// The prefix is an `Option<BindStageV1>` tried before `name`; on an
    /// unstaged `val x = …` it fails at the first token, collapses to `None`
    /// and steals nothing, so every existing fixture parses unchanged. It
    /// also keeps this arm ordered-choice-safe against the keyword-headed
    /// `Value*` arms below: `val ~rec …` still fails here (at `name`, which
    /// cannot match the `rec` keyword) and falls through, exactly as `val
    /// rec …` does.
    Value {
        kw: KwVal,
        stage: Option<BindStageV1>,
        name: BindName,
        params: Vec<Param>,
        eq: DefEqTok,
        body: ast::Expr,
    },
    /// `VAL INLINE bind_inline` (`parser_v1.mly:422-431` dispatch → `448` →
    /// `466-491`): `val inline <ctx> \cmd <param>* = <expr>` (the
    /// heavyweight, ctx-explicit form — the only one `stdja-mini` uses;
    /// `ctx` stays `Option` so the lightweight, ctx-synthesized form parses
    /// too, for free).
    ValueInline {
        kw: KwVal,
        /// See [`Bind::Value::stage`] — upstream's qualifier sits before the
        /// whole `bind_value`, and `bind_value` is what `inline`/`block`/
        /// `math`/`rec`/`mutable` select between (`parser_v1.mly:417-421` →
        /// `:581-593`), so every arm below carries the same prefix.
        stage: Option<BindStageV1>,
        inline_kw: KwInline,
        ctx: Option<VarTok>,
        cmd: AnyHorzCmdTok,
        params: Vec<Param>,
        eq: DefEqTok,
        body: ast::Expr,
    },
    /// `VAL BLOCK bind_block` (`parser_v1.mly:450` → `493-518`): `val block
    /// <ctx> +cmd <param>* = <expr>`.
    ValueBlock {
        kw: KwVal,
        /// See [`Bind::ValueInline::stage`].
        stage: Option<BindStageV1>,
        block_kw: KwBlock,
        ctx: Option<VarTok>,
        cmd: AnyVertCmdTok,
        params: Vec<Param>,
        eq: DefEqTok,
        body: ast::Expr,
    },
    /// `VAL MATH bind_math` (`parser_v1.mly:452-453` dispatch → `520-531`):
    /// `val math <ctx> \cmd <param>* [with <sub> <sup>] = <expr>`.
    /// Unlike `ValueInline`/`ValueBlock`, `ctx` is MANDATORY — upstream
    /// has no lightweight ctx-less form (contrast `bind_inline`'s two
    /// productions, :466-491). Placed after
    /// `ValueBlock`, ordered-choice-safe for the same reason as `Value`
    /// above: `math`/`with` both lex as keyword tokens under V0_1, so no
    /// arm can steal another's input.
    ValueMath {
        kw: KwVal,
        /// See [`Bind::ValueInline::stage`].
        stage: Option<BindStageV1>,
        math_kw: KwMath,
        ctx: VarTok,
        /// `\cmd` — math commands share the `\` sigil with inline commands
        /// (there is no separate math-command token; see `elaborate.rs`'s
        /// `command_scheme` doc comment, which notes the same sharing on
        /// the eval side).
        cmd: AnyHorzCmdTok,
        params: Vec<Param>,
        scripts: Option<ScriptsParamV1>,
        eq: DefEqTok,
        body: ast::Expr,
    },
    /// `VAL REC bind_value_nonrec (AND bind_value_nonrec)*`
    /// (`parser_v1.mly:444-445,455-465`): `val rec f p* = e (and g p* = e)*`.
    /// With `rec`/`mutable`/`inline`/`block` all lexed as keyword tokens
    /// under V0_1, no arm can steal another's input —
    /// `Value.name: BindName` cannot match a keyword token — so declared
    /// order is a documentation/perf choice; `Value` stays first because it
    /// is the overwhelmingly common arm.
    ValueRec {
        kw: KwVal,
        /// See [`Bind::ValueInline::stage`]. One qualifier covers the whole
        /// `and`-chain, matching upstream's single `UTBindValue(stage,
        /// UTRec(binds))`.
        stage: Option<BindStageV1>,
        rec_kw: KwRec,
        first: ast::RecClauseV1,
        ands: Vec<ast::AndClauseV1>,
    },
    /// `VAL MUTABLE LOWER REVERSED_ARROW expr` (`parser_v1.mly:446-447`):
    /// `val mutable x <- e`. The name is a plain `LOWER` upstream (not
    /// `bound_identifier`), hence `VarTok`, matching the cst target
    /// (`cst::TopBinding::LetMutable.name`, `cst.rs:237`).
    ValueMutable {
        kw: KwVal,
        /// See [`Bind::ValueInline::stage`].
        stage: Option<BindStageV1>,
        mutable_kw: KwMutable,
        name: VarTok,
        arrow: OverwriteEqTok,
        value: ast::Expr,
    },
    /// `TYPE bind_type_single (AND bind_type_single)*`
    /// (`parser_v1.mly:432-433,535-544`): `type t 'a* = body (and u 'a* =
    /// body)*` — variant and synonym forms, mutually recursive across the
    /// `and` chain.
    Type {
        kw: KwType,
        first: TypeBindSingleV1,
        ands: Vec<TypeAndV1>,
    },
    /// `MODULE UPPER option(sig_annot) EXACT_EQ modexpr` — upstream
    /// `bind`'s MODULE arm (`parser_v1.mly:434-435`), with the FULL
    /// `modexpr` body and the optional `:>` annotation. The
    /// body goes
    /// through [`ModExprErasedV1`]: `Bind` is outside the `#[recurse]`
    /// module, and `Bind → ModExpr → StructBindV1 → Bind` is the runtime
    /// cycle both connectors erase (one break per direction).
    Module {
        module_kw: KwModule,
        name: CtorTok,
        sig_annot: Option<SigAnnotV1>,
        eq: DefEqTok,
        body: ModExprErasedV1,
    },
    /// `SIGNATURE UPPER EXACT_EQ sigexpr` (`parser_v1.mly:436-437`).
    Signature {
        kw: KwSignature,
        name: CtorTok,
        eq: DefEqTok,
        sig_: SigExprErasedV1,
    },
    /// `INCLUDE modexpr` (`:438-439`) — a bind-include includes a MODULE
    /// (contrast [`ast::Decl::Include`], which includes a signature).
    Include { kw: KwInclude, body: ModExprErasedV1 },
}

/// The stage qualifier of a `val` bind or `val` decl: `~` alone is stage 0,
/// `persistent ~` is the persistent stage (`parser_v1.mly:417-421` for binds,
/// `:600-603` for decls). No prefix at all is stage 1 — the document stage,
/// where an ordinary `val` lives — which is why the field holding this is an
/// `Option`.
///
/// This is 0.1's replacement for 0.0.6's whole-file `@stage:` header: the
/// same three stages, chosen per binding instead of per file.
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub struct BindStageV1 {
    pub persistent: Option<KwPersistent>,
    pub tilde: ExactTildeTok,
}

/// `scripts_param` (`parser_v1.mly:532-534`): `WITH sub=LOWER sup=LOWER` —
/// `val math`'s optional `with sub sup` suffix, binding the two
/// script-callback parameters directly rather than synthesizing the
/// hidden `%math-attach-scripts` wrapper.
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub struct ScriptsParamV1 {
    pub with_kw: KwWith,
    pub sub: VarTok,
    pub sup: VarTok,
}

/// One `bind_type_single` (`parser_v1.mly:539-544`). **0.1 delta from
/// [`crate::cst::TypeDecl`]:** the type parameters come AFTER the name
/// (`type t 'a = …`, `tyident LOWER; tyvars list(TYPEVAR)`), where 0.0.6
/// writes them before (`type 'a t = …`, `cst.rs:401-408`) — the lowering
/// reorders the fields. No `constraint` suffix exists in 0.1's production.
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub struct TypeBindSingleV1 {
    pub name: VarTok,
    pub tyvars: Vec<TypeVarTok>,
    pub eq: DefEqTok,
    pub body: TypeBodyV1,
}

/// An `and bind_type_single` continuation (`bind_type`'s
/// `separated_nonempty_list(AND, …)`, `parser_v1.mly:535-537`).
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub struct TypeAndV1 {
    pub and_kw: KwAnd,
    pub bind: TypeBindSingleV1,
}

/// One whole `bind_type` chain — `bind_type_single (AND bind_type_single)*`
/// (`parser_v1.mly:535-537`) — grouped into a single struct so the sig
/// layer ([`ast::SigExpr::WithType`], [`ast::Decl::Type`]) can reference the
/// chain through ONE eraser ([`TypeBindsErasedV1`]). [`Bind::Type`] keeps
/// its flattened `first`/`ands` fields unchanged (avoiding call-site
/// churn); the two spellings are the same grammar.
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub struct TypeBindsV1 {
    pub first: TypeBindSingleV1,
    pub ands: Vec<TypeAndV1>,
}

/// The right-hand side of one type bind: a variant's constructor list
/// (`EXACT_EQ BAR? variants`, `parser_v1.mly:540-541,545-553`) or a
/// transparent synonym (`EXACT_EQ typ`, `:542-543`). Variant-first is
/// unambiguous for the same reason as [`crate::cst::TypeDeclBody`]
/// (`cst.rs:410-418`): a variant list is `BarTok`/`CtorTok`-headed and no
/// [`ast::TypeExpr`] can start with either.
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub enum TypeBodyV1 {
    Variant {
        leading_bar: Option<BarTok>,
        first: VariantDefV1,
        rest: Vec<BarVariantDefV1>,
    },
    Synonym(ast::TypeExpr),
}

/// One `UPPER [OF typ]` variant (`parser_v1.mly:549-553`).
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub struct VariantDefV1 {
    pub ctor: CtorTok,
    pub of_ty: Option<OfTypeV1>,
}

/// The `of typ` payload suffix.
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub struct OfTypeV1 {
    pub of_kw: KwOf,
    pub ty: ast::TypeExpr,
}

/// A `| UPPER [OF typ]` continuation (`variants`' `separated_nonempty_
/// list(BAR, variant)`, `parser_v1.mly:545-548`).
#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
pub struct BarVariantDefV1 {
    pub bar: BarTok,
    pub def: VariantDefV1,
}

/// One declaration inside a `module … = struct … end` body.
/// [`Bind`]'s own alternatives are exactly what a struct
/// body may contain (`bind*`), so this simply re-parses a [`Bind`] — but
/// *not* by naming `Bind` as a field type directly: [`Bind`] lives
/// **outside** the `#[recurse]` module (below), so `Bind -> ModExpr ->
/// Vec<StructBindV1> -> Bind` would be a self-recursive cycle through a
/// plain `#[derive(Parse)]`, which (without the `#[recurse]` engine to back
/// it) is an `E0275` hazard (an unbounded recursive trait-bound
/// obligation) — exactly [`crate::cst::StructDecl`]'s own rationale
/// (`cst.rs:262-269`). Hand-writing `Parse`/`Unparse` here — the same trick
/// as the `erased_leaf_v1!` macro below — sidesteps that: the impl has no
/// recursive where-bound for the compiler to try to satisfy, it just calls
/// `Bind::parse` through the stream-erasing adapter at runtime.
#[derive(Debug, Clone, PartialEq)]
pub struct StructBindV1(pub Box<Bind>);

impl Parse<crate::token::Atom> for StructBindV1 {
    type Error = syan::error::ParseError<crate::span::Span>;

    fn parse_stream<S: syan::parse::ParseStream<Atom = crate::token::Atom>>(
        stream: &mut S,
    ) -> Result<Self, Self::Error> {
        let value = <Bind as Parse<_>>::parse_stream(stream)?;
        Ok(StructBindV1(Box::new(value)))
    }
}

impl Unparse<crate::token::Atom> for StructBindV1 {
    fn unparse<S: syan::parse::unparse::Emitter<crate::token::Atom>>(
        &self,
        sink: &mut S,
    ) -> Result<(), S::Error> {
        self.0.unparse(sink)
    }
}

/// One declaration inside a `sig … end` body (`list(decl)`,
/// `parser_v1.mly:591`) — [`StructBindV1`]'s twin, hand-written `Parse`/
/// `Unparse` for the same `E0275` reason. [`ast::Decl`] lives INSIDE the
/// `#[recurse]` module and `SigExpr → SigBotV1 → StructDeclV1 → Decl →
/// SigExpr` is a runtime cycle; naming `ast::Decl` as a plain derived field
/// of [`ast::SigBotV1`] would re-enter the module's own SCC analysis. As an
/// opaque leaf it closes that cycle at RUNTIME while keeping both SCCs
/// singletons. NOTE: named after [`crate::cst::StructDecl`] (the mechanism),
/// even though it carries a sig-`decl`, not a struct binding.
#[derive(Debug, Clone, PartialEq)]
pub struct StructDeclV1(pub Box<ast::Decl>);

impl Parse<crate::token::Atom> for StructDeclV1 {
    type Error = syan::error::ParseError<crate::span::Span>;

    fn parse_stream<S: syan::parse::ParseStream<Atom = crate::token::Atom>>(
        stream: &mut S,
    ) -> Result<Self, Self::Error> {
        let value = <ast::Decl as Parse<_>>::parse_stream(stream)?;
        Ok(StructDeclV1(Box::new(value)))
    }
}

impl Unparse<crate::token::Atom> for StructDeclV1 {
    fn unparse<S: syan::parse::unparse::Emitter<crate::token::Atom>>(
        &self,
        sink: &mut S,
    ) -> Result<(), S::Error> {
        self.0.unparse(sink)
    }
}

/// Recursion-edge eraser types for the expr/pattern/type layer —
/// the `cst_v1` analogue of [`crate::cst`]'s `erased_leaf!` macro (see its
/// doc comment for the measured compile-time blowup that makes this
/// mandatory). Suffixed `V1` throughout so these never collide with
/// [`crate::cst`]'s own erasers, even though the two live in sibling
/// modules and could not actually name-clash. Defined *outside* the
/// `#[recurse]` module so the macro treats them as opaque leaves.
macro_rules! erased_leaf_v1 {
    ($($(#[$doc:meta])* $name:ident => $target:ty;)*) => {
        $(
            $(#[$doc])*
            #[implement(newer_type_std::ops::Deref)]
            #[derive(Debug, Clone, PartialEq)]
            pub struct $name(pub Box<$target>);

            impl Parse<crate::token::Atom> for $name {
                type Error = syan::error::ParseError<crate::span::Span>;

                fn parse_stream<S: syan::parse::ParseStream<Atom = crate::token::Atom>>(
                    stream: &mut S,
                ) -> Result<Self, Self::Error> {
                    // No erasure any more — see `cst.rs`'s `erased_leaf!`.
                    let value = <$target as Parse<_>>::parse_stream(stream)?;
                    Ok($name(Box::new(value)))
                }
            }

            impl Unparse<crate::token::Atom> for $name {
                fn unparse<S: syan::parse::unparse::Emitter<crate::token::Atom>>(
                    &self,
                    sink: &mut S,
                ) -> Result<(), S::Error> {
                    self.0.unparse(sink)
                }
            }
        )*
    };
}

erased_leaf_v1! {
    /// An [`ast::Expr`] behind a stream-erasing parse (see above).
    ExprErasedV1 => ast::Expr;
    /// An [`ast::Pattern`] behind a stream-erasing parse (see above).
    PatErasedV1 => ast::Pattern;
    /// An [`ast::PatBot`] behind a stream-erasing parse (see above). Kept
    /// separate from [`PatErasedV1`] for the same reason
    /// [`crate::cst`]'s `PatErased`/`PatBotErased` split exists: a
    /// constructor pattern's argument is a `patbot`, not a full `patas`.
    PatBotErasedV1 => ast::PatBot;
    /// An [`ast::TypeExpr`] behind a stream-erasing parse (see above).
    TyErasedV1 => ast::TypeExpr;
    /// An [`ast::MathElemCst`] behind a stream-erasing parse (see above).
    MathErasedV1 => ast::MathElemCst;
    /// An [`ast::ModExpr`] behind a stream-erasing parse. Carries the
    /// OUTSIDE→INSIDE edge `Bind::Module.body → ModExpr` — the one edge of
    /// the `Bind → ModExpr → StructBindV1 → Bind` runtime cycle not already
    /// erased by the connector (the erasers are for the INSIDE types, not
    /// for `Bind`).
    ModExprErasedV1 => ast::ModExpr;
    /// An [`ast::SigExpr`] behind a stream-erasing parse. Used by
    /// [`SigAnnotV1`] and [`Bind::Signature`] (outside → the SigExpr root).
    SigExprErasedV1 => ast::SigExpr;
    /// A [`TypeBindsV1`] behind a stream-erasing parse. Unlike every other
    /// eraser this one targets an OUTSIDE type: `SigExpr::WithType` /
    /// `Decl::Type` (inside) must reach `bind_type`, whose
    /// `TypeBindSingleV1` re-enters the module through plain-derived
    /// `ast::TypeExpr` fields — an inside→outside-plain-derive→inside-root
    /// chain with no precedent in `cst.rs`'s discipline. Erasing at the
    /// boundary keeps the re-entry cheap (one stream type, monomorphized
    /// once), exactly like every other cross-boundary edge.
    TypeBindsErasedV1 => TypeBindsV1;
}

impl ast::Pattern {
    /// Whether this pattern is a lone variable — the 0.1 twin of
    /// [`crate::cst::ast::Pattern::is_bare_var`], over this module's
    /// identically-shaped pattern types.
    pub fn is_bare_var(&self) -> bool {
        self.as_clause.is_none()
            && self.head.tail.is_empty()
            && matches!(self.head.head, ast::PatBot::Var(_))
    }
}

/// An [`ast::Pattern`] that is **not** a bare variable — upstream 0.1's own
/// `pattern_non_var` (`parser_v1.mly:796`), and the 0.1 twin of
/// [`crate::cst::PatNonVarErased`], whose doc comment carries the whole
/// story.
///
/// 0.1 blows up the same way and slightly harder: over a chain of
/// `let vN = N in` ending in a broken `let`, 5,755 serves at 3, 46,971 at 6,
/// 376,699 at 9, 3,014,523 at 12, 24,117,115 at 15 — the same ×2.000 per
/// `let`, off a larger constant. [`Expr::LetIn`] subsumes every
/// bare-variable target here too (its `params` is greedy but no
/// [`Param`](ast::Param) begins with `=`), so refusing one costs nothing and
/// makes the two `let` alternatives disjoint.
#[implement(newer_type_std::ops::Deref)]
#[derive(Debug, Clone, PartialEq)]
pub struct PatNonVarErasedV1(pub Box<ast::Pattern>);

impl Parse<crate::token::Atom> for PatNonVarErasedV1 {
    type Error = syan::error::ParseError<crate::span::Span>;

    fn parse_stream<S: syan::parse::ParseStream<Atom = crate::token::Atom>>(
        stream: &mut S,
    ) -> Result<Self, Self::Error> {
        let value = <ast::Pattern as Parse<_>>::parse_stream(stream)?;
        if value.is_bare_var() {
            // See `cst::PatNonVarErased` — same guard, same reasoning.
            let ast::PatBot::Var(v) = &value.head.head else {
                unreachable!("a bare-variable pattern has a variable head")
            };
            return Err(syan::error::ParseError::expected(
                v.span,
                "a destructuring pattern (a plain `let x = …` is not one)",
            ));
        }
        Ok(PatNonVarErasedV1(Box::new(value)))
    }
}

impl Unparse<crate::token::Atom> for PatNonVarErasedV1 {
    fn unparse<S: syan::parse::unparse::Emitter<crate::token::Atom>>(
        &self,
        sink: &mut S,
    ) -> Result<(), S::Error> {
        self.0.unparse(sink)
    }
}

/// The recursive expression/pattern/type/text grammar for SATySFi 0.1.
/// A copy of [`crate::cst::ast`] with the deltas documented on each
/// type; see the module doc comment for the SCC/root story.
#[syan::parse::recurse]
pub mod ast {
    use crate::leaf::*;
    use syan::parse::{Parse, Unparse};

    /// One `param_unit` (`parser_v1.mly:635-646`): an optional `?(l = x, …)`
    /// labeled-optional binder bundle, then a [`ParamBody`] (a plain
    /// `patbot`, or a `( pat : τ )` ascribed pattern). Held inside `mod ast`
    /// (re-exported at [`super::Param`]) so the roots that carry param lists
    /// (`Expr::Fun`/`Expr::LetIn`/`RecClauseV1`) reference it without a
    /// boundary Parse-trait cycle. A bare `patbot` param parses `Param {
    /// opts: None, body: ParamBody::Pat(_) }` directly — the `?`-headed
    /// `opts` `Option` is tried first, failing on a non-`?` head with no
    /// token stolen, so an all-plain param list parses unchanged.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct Param {
        pub opts: Option<OptParamsV1>,
        pub body: ParamBody,
    }

    /// A `param_unit`'s trailing shape (`parser_v1.mly:635-646`): either a
    /// plain `patbot`, or a `( pattern : typ )` ascribed pattern
    /// (`parser_v1.mly:641-645`).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum ParamBody {
        /// Tried FIRST: `( x : int )` fails `patbot`'s own paren body at the
        /// `:` (a `patbot` paren group expects only more patterns/`,`/`)`)
        /// and backtracks to `Ascribed` cleanly (ordered choice, no token
        /// stolen).
        Pat(PatBot),
        /// `( pattern : typ )` — a FULL `pattern` (not `patbot`) ascribed
        /// with a full `typ`, both via erasers (same cycle-avoidance
        /// discipline as every other satellite in this module).
        Ascribed {
            paren: ParenGroup<()>,
            #[group(self.paren)]
            inner: AscribedInnerV1,
        },
    }

    /// An ascribed param's group content: `pattern : typ` (`parser_v1.mly`'s
    /// `param_unit`, `:641-645`).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct AscribedInnerV1 {
        pub pat: super::PatErasedV1,
        pub colon: ColonTok,
        pub ty: super::TyErasedV1,
    }

    /// A `?(l = x, …)` labeled-optional parameter bundle (`parser_v1.mly`'s
    /// optional-`param_unit` head). The `?` reuses [`OptionalTypeTok`]
    /// (SATySFi 0.1 dropped the fused `?:` sigil); the `(…)` is a paren
    /// group of `,`-separated `label = binder` entries (non-empty enforced
    /// at lowering).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct OptParamsV1 {
        pub q: OptionalTypeTok,
        pub paren: ParenGroup<()>,
        #[group(self.paren)]
        pub entries: Vec<OptParamEntryV1>,
    }

    /// One `label = binder` entry of an [`OptParamsV1`] bundle (the last `,`
    /// is optional; `=` is upstream's `EXACT_EQ`, reusing [`DefEqTok`]).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct OptParamEntryV1 {
        pub label: VarTok,
        pub eq: DefEqTok,
        pub var: VarTok,
        pub comma: Option<CommaTok>,
    }

    /// `nxlet`-analogue: a let/if/match/lambda-headed expression, falling
    /// through to the flattened operator chain ([`Expr::Ops`], [`OpChain`]) at the
    /// bottom. Variant order is parse priority (ordered-choice
    /// backtracking): every `let`-headed form is tried before the fallback
    /// [`Expr::Overwrite`]/[`Expr::Ops`] (which may also start with a bare
    /// variable), and `Ops` — having no distinguishing leading keyword —
    /// must stay last.
    ///
    /// **0.1 deltas from [`crate::cst::ast::Expr`]:** `Match` gains a
    /// mandatory trailing `end` (`parser_v1.mly:792`); `let-rec` becomes
    /// `let rec … in …` (a plain `let` followed by the new [`KwRec`]
    /// keyword) with full `and`-chained mutual recursion (see
    /// [`Expr::LetRecIn`]); a new `LetMutableIn` form covers `let mutable x
    /// <- init in body`; a new `LetPatternIn` form covers
    /// `let pat = value in body` for any non-bare-variable pattern
    /// (`parser_v1.mly:796`, `pattern_non_var`); `open` requires a leading
    /// `let` (`parser_v1.mly:798`, `LET OPEN UPPER IN`) where 0.0.6 allows a
    /// bare `open Name in body`; and `WhileDo`, the `Guard`/`when` match-arm
    /// suffix, and `OpChain`'s `before` postfix are dropped entirely —
    /// SATySFi 0.1's grammar has no `WHEN`/`WHILE`/`BEFORE` tokens at all
    /// (confirmed by grep of `parser_v1.mly`). `Overwrite` (`name <- value`)
    /// is kept unchanged (`parser_v1.mly:810-812`, `REVERSED_ARROW`) — it is
    /// unrelated to the removed `before` postfix.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum Expr {
        /// `let rec clause (and clause)* in body` (`parser_v1.mly:794-795`
        /// dispatching to `bind_value_rec`, `:455-458`) — full mutual
        /// recursion.
        LetRecIn {
            let_kw: KwLet,
            rec_kw: KwRec,
            first: RecClauseV1,
            ands: Vec<AndClauseV1>,
            in_kw: KwIn,
            body: Box<Expr>,
        },
        /// `let mutable x <- init in body` (`parser_v1.mly:794-795`
        /// dispatching to `bind_value`'s MUTABLE arm, `:446-447`). Same
        /// shape as [`crate::cst::ast::Expr::LetMutableIn`] minus the fused
        /// keyword: 0.1 spells it `let mutable` (two tokens), 0.0.6
        /// `let-mutable` (one). Disambiguated one token after `let` by the
        /// V0_1-gated `mutable` keyword, so declared order relative to the
        /// other `let`-headed arms is correctness-irrelevant.
        LetMutableIn {
            let_kw: KwLet,
            mutable_kw: KwMutable,
            name: VarTok,
            arrow: OverwriteEqTok,
            init: Box<Expr>,
            in_kw: KwIn,
            body: Box<Expr>,
        },
        /// `let name param* = value in body` (only a plain variable target
        /// is supported here — a general pattern falls through to
        /// [`Expr::LetPatternIn`]). `name` is a [`super::BindName`] —
        /// upstream's expression-level `let` reaches the
        /// same `bind_value_nonrec` (`:794-795` → `:459-465`) `val`/`val
        /// rec` do, so `let (+++) a b = … in` is valid 0.1 here too.
        LetIn {
            kw: KwLet,
            name: super::BindName,
            params: Vec<Param>,
            eq: DefEqTok,
            value: Box<Expr>,
            in_kw: KwIn,
            body: Box<Expr>,
        },
        /// `let pat = value in body` (`parser_v1.mly:796`,
        /// `pattern_non_var`) — any pattern shape EXCEPT a bare variable,
        /// which [`Expr::LetIn`] already covers. The exclusion is upstream's
        /// (the nonterminal is literally named `pattern_non_var`) and is
        /// carried by the field's type, [`super::PatNonVarErasedV1`], rather
        /// than by variant order: leaving the two alternatives overlapping
        /// made a failure inside `body` cost ×2 per enclosing `let`.
        LetPatternIn {
            kw: KwLet,
            pat: super::PatNonVarErasedV1,
            eq: DefEqTok,
            value: Box<Expr>,
            in_kw: KwIn,
            body: Box<Expr>,
        },
        /// `let open Name in body` (`parser_v1.mly:798`; unlike 0.0.6's
        /// bare `open Name in body`, 0.1 requires the leading `let`).
        OpenIn {
            let_kw: KwLet,
            open_kw: KwOpen,
            name: CtorTok,
            in_kw: KwIn,
            body: Box<Expr>,
        },
        /// `if cond then a else b` (`else` is never optional, so there is
        /// no dangling-else ambiguity).
        If {
            kw: KwIf,
            cond: Box<Expr>,
            then_kw: KwThen,
            then_branch: Box<Expr>,
            else_kw: KwElse,
            else_branch: Box<Expr>,
        },
        /// `fun x y -> body`. Each parameter is a full `patbot` (through
        /// `Param`), not a bare variable: upstream `parser_v1.mly:849-863`'s
        /// `fun` genuinely binds a `patbot` per parameter (`ELambda(patbot,
        /// e)` in `types.cppo.ml`), so `fun _ -> …` (wildcard) and `fun (a,
        /// b) -> …` (tuple-destructuring) are legal upstream syntax (gaps
        /// 2+3 of the V0_1-only language-completeness sweep). Reaching
        /// `PatBot` from here is the same cross-root DAG edge
        /// [`RecClauseV1::params`] already makes (both `Expr` and `PatBot`
        /// are roots inside this `#[recurse]` module — see the module doc
        /// comment), so no new SCC edge.
        Fun {
            kw: KwFun,
            params: Vec<Param>,
            arrow: ArrowTok,
            body: Box<Expr>,
        },
        /// `match scrutinee with [|] pat -> body (| pat -> body)* end`
        /// (`parser_v1.mly:792`). Mandatorily closed with `end`
        /// (`tokR=END`); no `when` guards (0.1 has no `WHEN` token).
        Match {
            kw: KwMatch,
            scrutinee: Box<Expr>,
            with_kw: KwWith,
            leading_bar: Option<BarTok>,
            first: MatchArm,
            rest: Vec<BarArm>,
            end_kw: KwEnd,
        },
        /// `name <- value` (`expr_overwrite`, `parser_v1.mly:810-812`,
        /// `REVERSED_ARROW`). Starts with a bare [`VarTok`], which is also
        /// how [`Expr::Ops`] can start — must stay before `Ops` so
        /// backtracking tries the `<-` shape first.
        Overwrite {
            name: VarTok,
            arrow: OverwriteEqTok,
            value: super::ExprErasedV1,
        },
        /// The flattened binary-operator chain — see
        /// [`crate::cst::ast::Expr`]'s module doc comment on precedence
        /// flattening (unchanged approach here). Must stay last (no leading
        /// keyword).
        Ops(OpChain),
    }

    /// One `name param* = value` clause of a `val rec`/`let rec` group —
    /// upstream `bind_value_nonrec` (`parser_v1.mly:459-465`) as reached
    /// from `bind_value_rec` (`:455-458`). **0.1 deltas from
    /// [`crate::cst::ast::RecBinding`]:** no `: ty` ascription and no
    /// multi-clause `| patbot* = value` sugar exist in 0.1 at all
    /// (`bind_value_nonrec` has neither a `COLON ty` nor a `BAR`
    /// alternative — 0.0.6's `recdecargpart` machinery has no 0.1
    /// counterpart), so there are no `ascription`/`leading_bar`/`extra`
    /// fields to mirror. `params` is upstream's `list(param_unit)` (see
    /// [`super::Param`]'s doc comment), reaching `PatBot` through the same
    /// cross-root DAG edge `cst::ast::RecBinding.params` makes
    /// (`cst.rs:753-762`); `value` goes through [`super::ExprErasedV1`] (not
    /// `Box<Expr>`) so this struct never joins `Expr`'s SCC — byte-for-byte
    /// `cst.rs`'s own `RecBinding.value: ExprErased` discipline.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct RecClauseV1 {
        pub name: super::BindName,
        pub params: Vec<Param>,
        pub eq: DefEqTok,
        pub value: super::ExprErasedV1,
    }

    /// An `and name param* = value` continuation of a `val rec`/`let rec`
    /// group (`bind_value_rec`'s `separated_nonempty_list(AND, …)`,
    /// `parser_v1.mly:455-458`). `and` lexes as `Token::LetAnd` → [`KwAnd`]
    /// in both generations (`lexer.rs:141`), so no new token is needed.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct AndClauseV1 {
        pub and_kw: KwAnd,
        pub clause: RecClauseV1,
    }

    /// One `pat -> body` match arm (`parser_v1.mly:959`). Unlike
    /// [`crate::cst::ast::MatchArm`], has no `when` guard — 0.1's grammar
    /// has none.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct MatchArm {
        pub pat: super::PatErasedV1,
        pub arrow: ArrowTok,
        pub body: super::ExprErasedV1,
    }

    /// A `| pat -> body` continuation of a match's arm list.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct BarArm {
        pub bar: BarTok,
        pub arm: MatchArm,
    }

    /// A flattened binary-operator chain: `head (op rhs)*`, left-folded
    /// (with correct per-operator precedence/associativity) during
    /// elaboration — see [`crate::cst::ast::OpChain`]'s doc comment.
    /// **Delta:** no `before` postfix field — 0.1 has no `BEFORE` token at
    /// all (confirmed by grep of `parser_v1.mly`), so
    /// [`crate::cst::ast::OpChain::before`] simply has no 0.1 counterpart.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct OpChain {
        pub head: AppExpr,
        pub tail: Vec<OpRhs>,
    }

    /// One `op rhs` continuation of an [`OpChain`].
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct OpRhs {
        pub op: BinOpTok,
        pub rhs: AppExpr,
    }

    /// `nxun`/`nxapp`/`nxunsub`-analogue flattened: an optional leading
    /// unary minus, an optional leading `!`/`!!`/... deref, an atomic head
    /// with any `#label` field accesses, and an application-chain tail —
    /// structurally identical to [`crate::cst::ast::AppExpr`] (`expr_app`,
    /// `parser_v1.mly:849-863`, no 0.1 delta).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct AppExpr {
        pub minus: Option<ExactMinusTok>,
        pub stage: Option<StagePrefix>,
        pub excl: Option<UnopExclamTok>,
        pub head: Atomic,
        pub head_accesses: Vec<AccessSeg>,
        pub args: Vec<AppArg>,
    }

    /// A staging prefix on a 0.1 operand: `&e` builds code for the next
    /// stage, `~e` splices the result of a previous-stage computation
    /// (`expr_un`, `parser_v1.mly:870-873`, `UTNext`/`UTPrev` — the same two
    /// productions 0.0.6 has, unchanged).
    ///
    /// A fork of [`crate::cst::ast::StagePrefix`], not a re-export: it lives
    /// inside 0.0.6's `#[recurse]` module, and this module's whole discipline
    /// is that touching `cst_v1.rs` never touches `cst.rs` (module doc
    /// comment). The two are token-identical, so `rustyfi-lang`'s
    /// `v1::lower` maps one to the other by moving tokens.
    ///
    /// Upstream puts these on `expr_un`, one level BELOW `expr_app`, so
    /// `&f x` is `(&f) x` and never `&(f x)`. This grammar flattens
    /// `expr_un`/`expr_app` into one node, so the prefix is an optional field
    /// on the *head* ([`AppExpr`]) and on each *argument* ([`AppArg`])
    /// independently — which reproduces exactly that reading.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum StagePrefix {
        /// `&e` — quote: the value is `e`'s code, to run one stage later.
        Next(ExactAmpTok),
        /// `~e` — splice: run `e` now and drop its code in here.
        Prev(ExactTildeTok),
    }

    /// One `#label` field-access segment (`expr_bot ACCESS`,
    /// `parser_v1.mly:878`).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct AccessSeg {
        pub hash: AccessTok,
        pub label: VarTok,
    }

    /// One application-chain argument. **0.1 delta:** the 0.0.6 `?:`/`?*`
    /// (`Optional`/`Omission`) forms are gone — SATySFi 0.1 dropped the fused
    /// `?:` sigil (`?:`/`?*` now lex as `?` + `:`/`*`, a downstream parse
    /// error), replaced by the labeled `?(l = e, …)` bundle
    /// ([`AppArg::Bundled`]).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum AppArg {
        /// `?(l = e, …) atom` — a labeled-optional bundle paired with the
        /// positional argument it precedes (pairing them rejects a dangling
        /// trailing bundle at parse time). `?(`-headed, token-disjoint from
        /// the `Atom`/`Ctor` arms.
        Bundled {
            opts: OptArgsV1,
            excl: Option<UnopExclamTok>,
            atom: Atomic,
            accesses: Vec<AccessSeg>,
        },
        /// `?(l = e, …) Ctor` — as [`AppArg::Bundled`] but the positional
        /// argument is a bare constructor.
        BundledCtor { opts: OptArgsV1, ctor: CtorTok },
        Atom {
            stage: Option<StagePrefix>,
            excl: Option<UnopExclamTok>,
            atom: Atomic,
            accesses: Vec<AccessSeg>,
        },
        Ctor(CtorTok),
    }

    /// A `?(l = e, …)` labeled-optional application bundle: the `?` sigil
    /// (reusing [`OptionalTypeTok`]), then a paren group of `,`-separated
    /// `label = expr` entries (non-empty enforced at lowering).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct OptArgsV1 {
        pub q: OptionalTypeTok,
        pub paren: ParenGroup<()>,
        #[group(self.paren)]
        pub entries: Vec<OptArgEntryV1>,
    }

    /// One `label = expr` entry of an [`OptArgsV1`] bundle — a FULL
    /// expression (`?(bias = 1 + n)`), routed through [`super::ExprErasedV1`]
    /// so this satellite never joins `Expr`'s SCC.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct OptArgEntryV1 {
        pub label: VarTok,
        pub eq: DefEqTok,
        pub value: super::ExprErasedV1,
        pub comma: Option<CommaTok>,
    }

    /// `expr_bot`-analogue: an atomic expression. **Delta:** [`Atomic::List`]
    /// and [`Atomic::Record`] are now `,`-separated
    /// (`optterm_list(COMMA, …)`, `parser_v1.mly:935,942`) rather than
    /// 0.0.6's `;`-separated forms — see [`ListItem`]/[`RecordField`].
    /// Parenthesized/tuple bodies were already `,`-separated in 0.0.6 and
    /// are unchanged (`parser_v1.mly:914`).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum Atomic {
        Length(LengthTok),
        Float(FloatTok),
        Int(IntTok),
        Literal(LiteralTok),
        True(KwTrue),
        False(KwFalse),
        /// A bare constructor, e.g. `None`, or the head of `Some 1`.
        Ctor(CtorTok),
        Var(VarTok),
        /// `Mod.x` — a module-qualified variable.
        VarWithMod(VarWithModTok),
        /// `command \cmd` (upstream `parser_v1.mly:906`, `L_PAREN COMMAND
        /// backslash_cmd R_PAREN` — the parens arrive via [`Atomic::Paren`]
        /// here, exactly like [`crate::cst::ast::Atomic::Command`], which
        /// this reproduces verbatim; the `plus_cmd` alternative at :908 is
        /// deferred with the same rationale as the 0.0.6 comment). Needed by
        /// the transliterated `v01-mini.satyh`'s `(command \math)`.
        Command { kw: CommandTok, name: AnyHorzCmdTok },
        /// `()`
        Unit { paren: UnitParen },
        /// `( expr )` or `( expr, expr, … )` (the latter elaborates to a
        /// tuple).
        Paren {
            paren: ParenGroup<()>,
            #[group(self.paren)]
            inner: Box<ParenBody>,
        },
        /// `(| label = expr, … |)` or `(| base with label = expr, … |)`
        /// (`,`-separated — see [`RecordBody`]).
        Record {
            rec: RecordGroup<()>,
            #[group(self.rec)]
            body: RecordBody,
        },
        /// `[ expr, … ]` (`,`-separated — see [`ListItem`]).
        List {
            list: ListGroup<()>,
            #[group(self.list)]
            items: Vec<ListItem>,
        },
        /// `{ inline text }`
        InlineText {
            igrp: InlineGroup<()>,
            #[group(self.igrp)]
            elems: Vec<InlineElem>,
        },
        /// `'< block text >`
        BlockText {
            bgrp: BlockGroup<()>,
            #[group(self.bgrp)]
            elems: Vec<BlockElem>,
        },
        /// `${ math }`. Parses the same math grammar as 0.0.6; the
        /// `math-text`/`math-boxes` value split is a lowering/typing
        /// concern, not a cst_v1 shape change.
        MathText {
            mgrp: MathGroup<()>,
            #[group(self.mgrp)]
            elems: Vec<super::MathErasedV1>,
        },
    }

    /// `(| … |)`'s content: either a plain field list, or a *record
    /// update* `base with l = e, …` (`parser_v1.mly:942-957`). `Update` is
    /// tried first (backtracks cleanly to `Fields`, same rationale as
    /// [`crate::cst::ast::RecordBody`]).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum RecordBody {
        Update {
            base: super::ExprErasedV1,
            with_kw: KwWith,
            fields: Vec<RecordField>,
        },
        Fields(Vec<RecordField>),
    }

    /// The parenthesized-expression group's content: one expression, plus
    /// any `, expr` continuations (present only for a tuple) — unchanged
    /// from 0.0.6 (already `,`-separated, `parser_v1.mly:914`).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct ParenBody {
        pub first: super::ExprErasedV1,
        pub rest: Vec<CommaExpr>,
    }

    /// A `, expr` continuation inside a parenthesized tuple.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct CommaExpr {
        pub comma: CommaTok,
        pub value: super::ExprErasedV1,
    }

    /// One record field `label = expr,` (the last `,` is optional; `=` is
    /// upstream's `EXACT_EQ`, reusing [`DefEqTok`]). **Delta from
    /// [`crate::cst::ast::RecordField`]:** `,` separator, not `;`.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct RecordField {
        pub name: VarTok,
        pub eq: DefEqTok,
        pub value: super::ExprErasedV1,
        pub comma: Option<CommaTok>,
    }

    /// One list element `expr,` (the last `,` is optional). **Delta from
    /// [`crate::cst::ast::ListItem`]:** `,` separator, not `;`.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct ListItem {
        pub value: super::ExprErasedV1,
        pub comma: Option<CommaTok>,
    }

    /// One inline-text element — identical shape to
    /// [`crate::cst::ast::InlineElem`] (no 0.1 delta; text-mode content is
    /// untouched by the comma/`end` deltas).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum InlineElem {
        Char(CharTok),
        /// A backtick literal written inside inline text (`` `…` ``). Its own
        /// arm, not a `Char` run, so the elaborator can dispatch it through the
        /// context's code-text command — see `Token::CodeText`.
        CodeText(CodeTextTok),
        Space(SpaceTok),
        Break(BreakTok),
        /// `#var;` — embeds a program variable's value as inline content.
        Embed { var: VarInHorzTok, semi: EndActiveTok },
        /// `${ math }` — embeds math content as inline text.
        EmbedMath {
            mgrp: MathGroup<()>,
            #[group(self.mgrp)]
            elems: Vec<super::MathErasedV1>,
        },
        /// `\cmd …` (`name` also accepts the module-qualified `\Mod.cmd`
        /// form).
        Cmd { name: AnyHorzCmdTok, tail: CmdTail },
        /// An itemize bullet (`*`+) marker.
        ItemBullet(ItemTok),
        /// A `|` separator marker.
        Sep(SepTok),
    }

    /// One block-text element — identical shape to
    /// [`crate::cst::ast::BlockElem`] (no 0.1 delta).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum BlockElem {
        /// `#var;` — embeds a program variable's value as block content.
        Embed { var: VarInVertTok, semi: EndActiveTok },
        /// `+cmd …` (`name` also accepts the module-qualified `+Mod.cmd`
        /// form).
        Cmd { name: AnyVertCmdTok, tail: CmdTail },
    }

    /// A command's arguments — identical shape to
    /// [`crate::cst::ast::CmdTail`] — **0.1 delta:** an optional LEADING
    /// `?(l = e, …)` bundle. A command
    /// applied with an optional on its FIRST argument (`\cmd ?(l = e){arg}`,
    /// `+sec ?(label = t){title}<body>` — the ONLY shape the capstone census
    /// finds) can't ride inside `args` (an `expr_app` application chain whose
    /// *head* must be a bare `Atomic`, never a `?`-headed bundle — the head
    /// slot has no place for a leading bundle), so it is peeled off here as
    /// `lead_opts` and re-attached to the first argument at lowering
    /// (`v1::lower::lower_cmd_tail`). A bundle on a LATER argument
    /// (`\cmd{a} ?(l = e){b}`) still rides inside `args` as an ordinary
    /// [`AppArg::Bundled`]. `?(`-headed, token-disjoint from every
    /// `args` head shape, so a bundle-less tail parses `lead_opts: None`.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum CmdTail {
        /// `;` — no arguments.
        Semi(EndActiveTok),
        /// The argument chain, optionally prefixed by a leading `?(l = e, …)`
        /// bundle on the first argument.
        Args {
            lead_opts: Option<OptArgsV1>,
            args: super::ExprErasedV1,
            semi: Option<EndActiveTok>,
        },
    }

    /// `patas`-analogue: a pattern, plus an optional `as name` binding —
    /// identical shape to [`crate::cst::ast::Pattern`] (no 0.1 delta).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct Pattern {
        pub head: PatCons,
        pub as_clause: Option<AsClause>,
    }

    /// The `as name` suffix of a pattern.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct AsClause {
        pub as_kw: KwAs,
        pub name: VarTok,
    }

    /// `pattr`-analogue: a `patbot`, followed by any number of `:: patbot`
    /// segments — identical shape to [`crate::cst::ast::PatCons`] (see its
    /// doc comment for why this is a flattened `Vec` rather than right
    /// recursion; no 0.1 delta).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct PatCons {
        pub head: PatBot,
        pub tail: Vec<ConsSeg>,
    }

    /// One `:: patbot` continuation of a cons pattern.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct ConsSeg {
        pub cons: ConsTok,
        pub tail: PatBot,
    }

    /// `patbot`, plus the constructor-pattern forms `pattr` adds —
    /// identical shape to [`crate::cst::ast::PatBot`], except
    /// [`PatBot::List`] is now `,`-separated (`parser_v1.mly:990-1015`,
    /// comma-sep list/tuple patterns).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum PatBot {
        /// `Ctor patbot` — a constructor applied to one argument pattern.
        /// This field is `PatBot`'s own self-loop (the root SCC).
        CtorApplied { ctor: CtorTok, arg: Box<PatBot> },
        /// A bare (nullary) constructor pattern.
        Ctor(CtorTok),
        Int(IntTok),
        True(KwTrue),
        False(KwFalse),
        Str(LiteralTok),
        Wild(WildcardTok),
        Var(VarTok),
        /// `()`
        Unit { paren: UnitParen },
        /// `( pat )` or `( pat, pat, … )` (the latter elaborates to a tuple
        /// pattern; already `,`-separated in 0.0.6, unchanged).
        Paren {
            paren: ParenGroup<()>,
            #[group(self.paren)]
            inner: Box<PatternParenBody>,
        },
        /// `[ pat, … ]` (also matches `[]`). **Delta:** `,` separator, not
        /// `;`.
        List {
            plist: ListGroup<()>,
            #[group(self.plist)]
            items: Vec<PatListItem>,
        },
    }

    /// The parenthesized-pattern group's content: one pattern, plus any
    /// `, pat` continuations (present only for a tuple pattern).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct PatternParenBody {
        pub first: super::PatErasedV1,
        pub rest: Vec<CommaPattern>,
    }

    /// A `, pat` continuation inside a parenthesized tuple pattern.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct CommaPattern {
        pub comma: CommaTok,
        pub value: super::PatErasedV1,
    }

    /// One list-pattern element `pat,` (the last `,` is optional). **Delta
    /// from [`crate::cst::ast::PatListItem`]:** `,` separator, not `;`.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct PatListItem {
        pub value: super::PatErasedV1,
        pub comma: Option<CommaTok>,
    }

    /// A type-expression grammar (`typ`/`typ_prod`/`typ_app`/`typ_bot`,
    /// `parser_v1.mly:685-752`, simplified — same scope as
    /// [`crate::cst::ast::TypeExpr`]). Spells products (`length * length`,
    /// [`TypeProd`]) and prefix type application (`list int`, [`TypeApp`]) —
    /// without them a `type` bind could declare almost nothing — plus the
    /// `?(…)` labeled-optional domain prefix
    /// ([`TypeExpr::OptRowFun`]), where a
    /// row-variable TAIL (`?(… | ?'r) ->`) parses but is rejected at
    /// lowering (it needs signature-level row quantification, not yet
    /// implemented). Self-recursive only through `Fun`'s/`OptRowFun`'s
    /// codomain (right recursion); parenthesized nesting goes through
    /// [`super::TyErasedV1`].
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum TypeExpr {
        /// `?(l : ty, … [| ?'r]) dom -> cod` (`typ` `:688-693`, `typ_opt_dom`
        /// `:753-758`). `?`-headed — neither
        /// `Fun`/`Atom` (headed by `TypeProd`) can start with
        /// `OptionalTypeTok`, so declared order relative to them is
        /// safety-neutral; declared first to mirror the upstream `typ`
        /// production order. Lowered (`v1/lower.rs`) to
        /// `cst::ast::TypeExpr::OptRowFun`, thence (`typecheck.rs`) to
        /// `MonoType::Func(Row::Cons(l1, ty1, … Row::Empty), dom, cod)` — a
        /// CLOSED row, matching what `Ast::LambdaOpt` infers,
        /// so an explicit `?(l:τ)->` signature unifies against an actual
        /// `?(l=x)`-taking function.
        OptRowFun {
            opt_dom: TypeOptDomV1,
            dom: TypeProd,
            arrow: ArrowTok,
            cod: Box<TypeExpr>,
        },
        /// `dom -> cod` (right-associative). This field is `TypeExpr`'s own
        /// self-loop (the root SCC). `dom` widened from [`TypeAtom`] to
        /// [`TypeProd`] so e.g. `'a option -> 'b option` and
        /// `'a * 'b -> 'c` both parse at their expected precedence.
        Fun {
            dom: TypeProd,
            arrow: ArrowTok,
            cod: Box<TypeExpr>,
        },
        /// The non-arrow fallthrough — widened from [`TypeAtom`] to
        /// [`TypeProd`]: a product/application with no
        /// enclosing arrow is still just "the whole type expression minus
        /// `->`".
        Atom(TypeProd),
    }

    /// `?(l : ty, … [| ?'r])` — the (possibly row-tailed) labeled-optional
    /// domain prefix of a [`TypeExpr::OptRowFun`] (`typ_opt_dom`,
    /// `parser_v1.mly:753-758`).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct TypeOptDomV1 {
        pub q: OptionalTypeTok,
        pub paren: ParenGroup<()>,
        #[group(self.paren)]
        pub inner: TypeOptDomInnerV1,
    }

    /// A [`TypeOptDomV1`]'s group content: one or more `label : typ` entries
    /// (nonempty enforced at lowering), then an optional `| ?'r` row-variable
    /// tail (`typ_opt_dom` `:756-757`) — parsed, but rejected with a
    /// `LowerError` (needs signature-level row quantification, not
    /// implemented; contrast [`TypeRecordInnerV1`]'s own
    /// `row_tail`, which IS fully supported, since a bare
    /// record-typed value has no `quant`-list obligation to satisfy).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct TypeOptDomInnerV1 {
        pub entries: Vec<TypeOptEntryV1>,
        pub row_tail: Option<RowTailV1>,
    }

    /// One `label : typ,` entry of a [`TypeOptDomV1`] (last `,` optional;
    /// `typ_opt_dom_entry`, `parser_v1.mly:759-762` — COLON, unlike the
    /// value-level `?(l = e)` bundle's `=`).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct TypeOptEntryV1 {
        pub label: VarTok,
        pub colon: ColonTok,
        pub ty: super::TyErasedV1,
        pub comma: Option<CommaTok>,
    }

    /// `| ?'r` — a row-variable tail (shared by [`TypeOptDomInnerV1`] and
    /// [`TypeRecordInnerV1`]; `parser_v1.mly:748-749`/`:756-757`).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct RowTailV1 {
        pub bar: BarTok,
        pub var: RowVarTok,
    }

    /// `typ_prod` (`parser_v1.mly:696-709`): one or more `*`-separated
    /// [`TypeApp`]s, flattened to head+`Vec` exactly like
    /// [`crate::cst::ast::TypeProd`] (`cst.rs:1284-1295`) — the same
    /// deferred-fold technique as `OpChain`/`PatCons`, keeping `TypeExpr` a
    /// singleton SCC.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct TypeProd {
        pub first: TypeApp,
        pub rest: Vec<StarType>,
    }

    /// A `* ty` continuation of a [`TypeProd`].
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct StarType {
        pub star: ExactTimesTok,
        pub ty: TypeApp,
    }

    /// `typ_app` (`parser_v1.mly:711-739`). **0.1 delta from
    /// [`crate::cst::ast::TypeApp`] (`cst.rs:1297-1312`):** application is
    /// PREFIX and n-ary (`list int`, `pair int bool`), not 0.0.6's postfix
    /// single-argument (`int list`) — the prefix→postfix bridge (with an
    /// arity-1 guard: arity ≥ 2 is a `LowerError`, not a parse error) lives
    /// in `v1/lower.rs`. `Applied`/`AppliedLong` (needing at least one
    /// argument atom) are tried before `Atom` — a bare name has no argument
    /// atom to consume and falls through cleanly (a following
    /// keyword/`=`/`and`/`->`/`*` never parses as a [`TypeAtom`]).
    ///
    /// Four further arms are keyword- or token-headed and so
    /// disjoint from `Applied`/`Atom`'s `VarTok`-headed shapes (ordering them
    /// BEFORE those is cosmetic, not load-bearing):
    ///
    /// - [`TypeApp::InlineCmdTy`]/[`TypeApp::BlockCmdTy`]/
    ///   [`TypeApp::MathCmdTy`]: `inline [τ, …]`/
    ///   `block [τ, …]`/`math [τ, …]` command types (`parser.mly:730-735`,
    ///   `typ_cmd_arg` `:763-774`; `math […]`: `parser.mly:830-831`),
    ///   `KwInline`/`KwBlock`/`KwMath`-headed (all three are V0_1 keywords
    ///   already — `val inline`/`val block` binds; `math` since the
    ///   math-split). One deliberate superset of upstream remains: each
    ///   bracketed slot is a full [`super::TyErasedV1`] (`TypeExpr`), not upstream's
    ///   narrower `typ_prod`. The `?(label: τ, …)` optional-labeled-slot
    ///   prefix is modeled — see [`TypeCmdArgItemV1::opts`];
    ///   `MathCmdTy` reuses `TypeCmdArgItemV1` as-is, so
    ///   `math [?(l : τ) …]` sig rows come for free.
    /// - [`AppliedLong`](TypeApp::AppliedLong): `M.t τ…` — the `LONG_LOWER`
    ///   qualified-head twin of `Applied` (`parser.mly:720-728`,
    ///   `LONG_LOWER` `lexer.mll:318`), `VarWithModTok`-headed (lexed by the
    ///   program-mode capital-head scan, `lexer.rs:753-777`). Needed to NAME
    ///   an abstract type from outside its sealing module — without
    ///   it, an opaque `M.t` could never appear in another module's
    ///   signature at all.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum TypeApp {
        /// `inline [τ, …]` — see the enum doc comment.
        //
        // NOTE the group fields are `ilist`/`blist`/`mlist`, not three `list`s:
        // syan names a group substruct after (group-field name, ENUM name) with
        // no variant component, so same-named groups in one enum collide
        // (E0428 + E0119).
        InlineCmdTy {
            kw: KwInline,
            ilist: ListGroup<()>,
            #[group(self.ilist)]
            args: Vec<TypeCmdArgItemV1>,
        },
        /// `block [τ, …]` — see the enum doc comment.
        BlockCmdTy {
            kw: KwBlock,
            blist: ListGroup<()>,
            #[group(self.blist)]
            args: Vec<TypeCmdArgItemV1>,
        },
        /// `math [τ, …]` (upstream
        /// `parser.mly:830-831` `MATH L_SQUARE optterm_list(COMMA,
        /// typ_cmd_arg) R_SQUARE → MMathCommandType(mncmdargtys)` — same
        /// `typ_cmd_arg` as inline/block). `KwMath`-headed, so this arm is
        /// disjoint from `Applied`/`Atom` and ambiguity-free: a bare `math`
        /// can never lex as a `VarTok` under V0_1 at all.
        MathCmdTy {
            kw: KwMath,
            mlist: ListGroup<()>,
            #[group(self.mlist)]
            args: Vec<TypeCmdArgItemV1>,
        },
        /// `M.t τ…` — see the enum doc comment. Mirrors
        /// `Applied`'s n-ary shape (`v1/lower.rs`'s prefix→postfix bridge
        /// rejects arity ≥ 2 identically for both).
        AppliedLong {
            ctor: VarWithModTok,
            first: TypeAtom,
            rest: Vec<TypeAtom>,
        },
        Applied {
            ctor: VarTok,
            first: TypeAtom,
            rest: Vec<TypeAtom>,
        },
        Atom(TypeAtom),
    }

    /// One `[…]`-bracketed command-type argument slot: an optional
    /// `?(l : τ, …)` labeled-optional bundle PREFIX (upstream
    /// `typ_cmd_arg : option(typ_opt_dom) typ_prod`,
    /// `parser.mly:753-773`), then the mandatory `τ,` (`,`-separated, last
    /// `,` optional — the [`ListItem`] pattern). A full [`super::TyErasedV1`] per
    /// slot (permissive superset of upstream's narrower `typ_prod`). `opts`
    /// is `Option`-tried first: a non-`?`-headed slot fails the `?` head with
    /// no token stolen, so a plain slot parses `opts: None`.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct TypeCmdArgItemV1 {
        pub opts: Option<TypeCmdOptDomV1>,
        pub ty: super::TyErasedV1,
        pub comma: Option<CommaTok>,
    }

    /// `?(l : τ, …)` — a CLOSED command-type optional bundle (upstream
    /// `typ_opt_dom`, `parser.mly:755-761`,
    /// minus the `| ?'r` row-variable tail: command optional-argument types
    /// are closed maps, never rows — upstream itself silently DISCARDS a
    /// written row variable here, `parser.mly:859-869`'s literal `TODO
    /// (error)` — so this port doesn't model one either; a stray `?'r` inside
    /// a command-type bracket is a parse error, faithfully matching
    /// upstream's "never actually usable" treatment of it). Mirrors
    /// [`crate::cst::ast::CstTypeOptDom`]-shaped satellites elsewhere in this file.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct TypeCmdOptDomV1 {
        pub q: OptionalTypeTok,
        pub paren: ParenGroup<()>,
        #[group(self.paren)]
        pub entries: Vec<TypeCmdOptEntryV1>,
    }

    /// One `label : τ,` entry of a [`TypeCmdOptDomV1`] bundle (the last `,`
    /// is optional).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct TypeCmdOptEntryV1 {
        pub label: VarTok,
        pub colon: ColonTok,
        pub ty: super::TyErasedV1,
        pub comma: Option<CommaTok>,
    }

    /// An atomic type expression. `parser_v1.mly:740-752`'s record forms are
    /// fully modeled: both the closed form and the open (row-var-tailed) form
    /// share [`TypeAtom::Record`], distinguished by
    /// [`TypeRecordInnerV1::row_tail`].
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum TypeAtom {
        /// `( ty )`
        Paren {
            paren: ParenGroup<()>,
            #[group(self.paren)]
            inner: super::TyErasedV1,
        },
        /// `(| l1 : ty1, l2 : ty2, … |)` (closed) or `(| l1 : ty1, … | ?'r |)`
        /// (open — a row-variable tail)
        /// (`typ_bot`'s two `L_RECORD` arms, `parser_v1.mly:746-749`;
        /// `typ_record_elem` `:775-777` — COLON fields, unlike record
        /// EXPRESSIONS' `l = e`). Lowered (`v1/lower.rs`): the closed form to
        /// the existing `cst::ast::TypeAtom::Record` (`cst.rs:1344`) and
        /// thence to a closed `MonoType::Record` row (`typecheck.rs:512`);
        /// the open form to the additive `cst::ast::TypeAtom::RecordOpen`
        /// and thence to an OPEN `MonoType::Record(Row::Var(…))` — a fresh
        /// row variable, using the existing generic `Row`/`RowVarRef`/
        /// `unify_row` machinery (no new type machinery needed).
        Record {
            rec: RecordGroup<()>,
            #[group(self.rec)]
            inner: TypeRecordInnerV1,
        },
        /// A type variable, e.g. `'a`.
        Var(TypeVarTok),
        /// `M.t` — a qualified type name (upstream
        /// `LONG_LOWER`, `parser.mly:742-743`). `VarWithModTok`-headed,
        /// token-disjoint from `Var`/`Name`/`Paren` (`TypeVarTok`/`VarTok`/
        /// `LParenTok`) — see [`TypeApp::AppliedLong`]'s doc comment.
        LongName(VarWithModTok),
        /// A (possibly qualified) type name, e.g. `int`, `string`.
        Name(VarTok),
    }

    /// A [`TypeAtom::Record`]'s group content: the field list, plus an
    /// optional `| ?'r` row-variable tail (present ⇒ an OPEN record type;
    /// absent ⇒ closed).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct TypeRecordInnerV1 {
        pub fields: Vec<TypeRecordFieldV1>,
        pub row_tail: Option<RowTailV1>,
    }

    /// One `l : ty,` field (last `,` optional — the [`ListItem`] pattern).
    /// **Deltas from [`crate::cst::ast::TypeRecordField`] (`cst.rs:1363`):**
    /// `,` separator, not `;` (same delta as [`RecordField`]); field type is
    /// a full [`super::TyErasedV1`] (upstream `typ_record_elem :776` takes a
    /// full `typ`) — erased, not a direct `TypeExpr`, for the same
    /// cycle-avoidance reason `cst.rs:1355-1362` documents.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct TypeRecordFieldV1 {
        pub name: VarTok,
        pub colon: ColonTok,
        pub ty: super::TyErasedV1,
        pub comma: Option<CommaTok>,
    }

    /// `mathtop`-analogue: one math element — identical shape to
    /// [`crate::cst::ast::MathElemCst`] (no 0.1 delta; see its doc comment
    /// for why this needs no direct self-loop of its own).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct MathElemCst {
        pub base: MathBot,
        pub scripts: Vec<MathScript>,
    }

    /// `mathbot` — identical shape to [`crate::cst::ast::MathBot`] (no 0.1
    /// delta; `name` accepts a module-qualified `\Mod.cmd` math command
    /// too, `AnyMathCmdTok::Mod` — the lexer already emits
    /// `Token::MathCmdWithMod` for one, `lexer.rs`'s `\\` arm in `Mode::
    /// Math`, since `${\Math.paren{…}}`-shaped
    /// qualified references need it to parse at all).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum MathBot {
        /// `\cmd matharg*`, sigil-only or module-qualified (`\Mod.cmd
        /// matharg*`).
        Cmd { name: AnyMathCmdTok, args: Vec<MathArg> },
        Chars(MathCharTok),
        /// `#var` (math mode never trails this with `;`).
        Embed(VarInMathTok),
        /// A `|` separator marker (flat; elaborator regroups).
        Sep(SepTok),
        /// `{ … }` — re-enters the math grammar.
        Group {
            mgrp: MathGroup<()>,
            #[group(self.mgrp)]
            elems: Vec<super::MathErasedV1>,
        },
    }

    /// One postfix script combo of a [`MathElemCst`] — identical shape to
    /// [`crate::cst::ast::MathScript`] (no 0.1 delta).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum MathScript {
        /// `^ group`
        Super { hat: SuperscriptTok, group: MathGroupArg },
        /// `_ group`
        Sub { under: SubscriptTok, group: MathGroupArg },
        /// A run of `'` marks — sugar for a superscript of primes
        /// characters.
        Primes(PrimesTok),
    }

    /// `mathgroup`-analogue: a script's operand is either a bracketed math
    /// group or a bare `mathbot`.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum MathGroupArg {
        Group {
            mgrp: MathGroup<()>,
            #[group(self.mgrp)]
            elems: Vec<super::MathErasedV1>,
        },
        Bot(Box<MathBot>),
    }

    /// `matharg`-analogue: one command argument in math mode — identical
    /// shape to [`crate::cst::ast::MathArg`] (no 0.1 delta; the escape
    /// bodies reuse the now-comma-separated [`ParenBody`]/[`ListItem`]/
    /// [`RecordBody`] defined above).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum MathArg {
        /// `{ math }`.
        Math {
            mgrp: MathGroup<()>,
            #[group(self.mgrp)]
            elems: Vec<super::MathErasedV1>,
        },
        /// `!{ inline text }`.
        Inline {
            igrp: InlineGroup<()>,
            #[group(self.igrp)]
            elems: Vec<InlineElem>,
        },
        /// `!<block text>`.
        Block {
            bgrp: BlockGroup<()>,
            #[group(self.bgrp)]
            elems: Vec<BlockElem>,
        },
        /// `!(e)` / `!(e, e, …)`.
        ParenEscape {
            paren: ParenGroup<()>,
            #[group(self.paren)]
            inner: Box<ParenBody>,
        },
        /// `![e, …]`.
        ListEscape {
            list: ListGroup<()>,
            #[group(self.list)]
            items: Vec<ListItem>,
        },
        /// `!(|l = e, …|)`.
        RecordEscape {
            rec: RecordGroup<()>,
            #[group(self.rec)]
            body: RecordBody,
        },
    }

    // ---- the module/signature layer --------------------------------------

    /// `mod_chain`: `UPPER | LONG_UPPER` (`parser_v1.mly:404-414`). `M.N.P`
    /// arrives as ONE [`LongUpperTok`] (the V0_1 lexer branch), so a chain is
    /// always exactly one token — which is what makes [`ModExpr::App`]'s two-
    /// chain juxtaposition (`F X`, `F.G X.Y`) unambiguous at the token level.
    /// Token-disjoint arms; order is cosmetic.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum ModChainV1 {
        Long(LongUpperTok),
        Single(CtorTok),
    }

    /// `modexpr` (`parser_v1.mly:380-403`). SELF-LOOP ROOT: `Functor.body:
    /// Box<ModExpr>` (`:381-382`). Variant order is parse priority:
    /// `Functor` (`fun`-headed) and `Struct` (`struct`-headed) are
    /// keyword-disjoint from everything; `Coerce` (`UPPER :>`) must precede
    /// `App`/`Var` so the `:>` suffix is claimed before a bare chain matches;
    /// `App` (two chains, `modexpr_app` `:388-394`) precedes `Var` (one
    /// chain, `modexpr_bot` `:398-400`) for longest-match. Struct bodies go
    /// through [`super::StructBindV1`] (the struct-body connector, erased), so
    /// `ModExpr` never statically references [`super::Bind`] — see the
    /// module doc comment's SCC story.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum ModExpr {
        /// `FUN ( UPPER : sigexpr ) ARROW modexpr` (`parser_v1.mly:381-382`).
        Functor {
            fun_kw: KwFun,
            lp: LParenTok,
            param: CtorTok,
            colon: ColonTok,
            dom: Box<SigExpr>,
            rp: RParenTok,
            arrow: ArrowTok,
            body: Box<ModExpr>,
        },
        /// `UPPER COERCE sigexpr` (`:383-384`) — coercion applies to a BARE
        /// module name only, upstream-faithfully (`A.B :> S` is a parse
        /// error there too).
        Coerce {
            name: CtorTok,
            coerce: CoerceTok,
            sig_: Box<SigExpr>,
        },
        /// `mod_chain mod_chain` — functor application (`:389-394`).
        App { func: ModChainV1, arg: ModChainV1 },
        /// `mod_chain` — a (possibly long) module path (`:399-400`).
        Var(ModChainV1),
        /// `STRUCT list(bind) END` (`:401-402`) — the only form `v1/lower.rs`
        /// gives real semantics to; reuses the struct-body connector.
        Struct {
            struct_kw: KwStruct,
            binds: Vec<super::StructBindV1>,
            end_kw: KwEnd,
        },
    }

    /// `sigexpr` (`parser_v1.mly:558-573`). SELF-LOOP ROOT: `Functor.dom`/
    /// `Functor.cod: Box<SigExpr>` (`:570-571`).
    ///
    /// **Left-recursion note (load-bearing).** The naive sketch would write
    /// `With { base: Box<SigExpr>, … }` — as a syan2 ordered-choice
    /// production that is LEFT RECURSION (`SigExpr` would begin by parsing
    /// `SigExpr`; syan2 gives no diagnostic, it just recurses/fails at parse
    /// time — a known consumer hazard). Upstream is *not* left-recursive:
    /// the `with` base is `sigexpr_bot` (`:559,564`) and `with` cannot chain
    /// (the result of a `with` is never itself a valid `with` base). So the
    /// faithful encoding is bot + one optional-shaped suffix arm, tried
    /// before the bare-bot fallthrough: `S with type t = int with type u =
    /// bool` is a parse error here exactly as upstream (pinned in tests).
    /// NO arm of this enum may ever begin with `Box<SigExpr>`/`SigExpr` as
    /// its first field — reviewer checklist item.
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum SigExpr {
        /// `( UPPER : sigexpr ) ARROW sigexpr` (`:570-571`) — the functor
        /// signature. `(`-headed; no [`SigBotV1`] starts with `(`, so this
        /// is token-disjoint from the other arms.
        Functor {
            lp: LParenTok,
            param: CtorTok,
            colon: ColonTok,
            dom: Box<SigExpr>,
            rp: RParenTok,
            arrow: ArrowTok,
            cod: Box<SigExpr>,
        },
        /// `sigexpr_bot WITH TYPE bind_type` (`:559-563`) /
        /// `sigexpr_bot WITH mod_chain TYPE bind_type` (`:564-569`). The
        /// `Option<ModChainV1>` is greedy-then-backtrack: on `with type` the
        /// chain fails (`type` is a keyword token, not `UPPER`/`LONG_UPPER`)
        /// and collapses to `None`. `binds` goes through
        /// [`super::TypeBindsErasedV1`].
        WithType {
            base: SigBotV1,
            with_kw: KwWith,
            path: Option<ModChainV1>,
            type_kw: KwType,
            binds: super::TypeBindsErasedV1,
        },
        /// A bare `sigexpr_bot` (`:572-573`). Must come after [`SigExpr::WithType`]
        /// (maximal munch of the `with` suffix).
        Bot(SigBotV1),
    }

    /// `sigexpr_bot` (`parser_v1.mly:575-595`) — a satellite (no self-loop;
    /// no edge back to `SigExpr`). Sig bodies go through
    /// [`super::StructDeclV1`] (opaque hand-written connector), so
    /// `SigBotV1` never statically references [`Decl`].
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum SigBotV1 {
        /// `LONG_UPPER` — a signature path `M.N.S` (`:581-590`).
        Path(LongUpperTok),
        /// `UPPER` — a signature name (`:576-580`).
        Var(CtorTok),
        /// `SIG list(decl) END` (`:591-595`). `sig` is a version-independent
        /// keyword (`lexer.rs`).
        Sig {
            sig_kw: KwSig,
            decls: Vec<super::StructDeclV1>,
            end_kw: KwEnd,
        },
    }

    /// `decl` (`parser_v1.mly:597-621`) — one item of a `sig … end` body.
    /// NOT a root: no arm contains `Decl`; reached only through
    /// [`super::StructDeclV1`], so `SigExpr ↔ Decl` never forms a rootless
    /// static sub-cycle (the shape `cst.rs`'s `AppArgErased` doc warns the
    /// engine rejects). Its recursion-bearing edges are plain DAG edges INTO
    /// roots: `ty: TypeExpr` (the same satellite→root shape as
    /// `RecClauseV1.params: Vec<PatBot>`) and `sig_: Box<SigExpr>`.
    ///
    /// Deferred arms (parse errors): macro decls `val \m : macro-type`
    /// (`:608-611`), row quantifiers (`rowquant`, `:631-633` — no
    /// `ROWVAR` token for this position yet).
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub enum Decl {
        /// `VAL PERSISTENT? EXACT_TILDE? bound_identifier quant COLON typ`
        /// (`:598-603`; `quant`'s tyvar list `:623-630` — `val map 'a 'b :
        /// ('a -> 'b) -> …`). The stage prefix is the decl-side twin of
        /// [`super::Bind::Value`]'s own `stage` field, with the same
        /// ordered-choice argument (see that arm's doc comment).
        Val {
            kw: KwVal,
            stage: Option<super::BindStageV1>,
            name: super::BindName,
            quant: Vec<TypeVarTok>,
            colon: ColonTok,
            ty: TypeExpr,
        },
        /// `VAL BACKSLASH_CMD quant COLON typ` (`:604-605`). Plain
        /// [`HorzCmdTok`] — upstream uses the bare token, and program mode
        /// already lexes `\cmd`. Naming mirrors
        /// [`crate::cst::SigItem::ValHorzCmd`].
        ValHorzCmd {
            kw: KwVal,
            cmd: HorzCmdTok,
            quant: Vec<TypeVarTok>,
            colon: ColonTok,
            ty: TypeExpr,
        },
        /// `VAL PLUS_CMD quant COLON typ` (`:606-607`).
        ValVertCmd {
            kw: KwVal,
            cmd: VertCmdTok,
            quant: Vec<TypeVarTok>,
            colon: ColonTok,
            ty: TypeExpr,
        },
        /// `TYPE LOWER CONS kind` — an OPAQUE type (`:612-613`). Tried
        /// before the transparent [`Decl::Type`]: the two share the `type
        /// name` prefix and are told apart by `::` vs `=`/tyvars
        /// (backtracking is two tokens deep, cheap).
        TypeOpaque {
            kw: KwType,
            name: VarTok,
            cons: ConsTok,
            kind: KindV1,
        },
        /// `TYPE bind_type` — transparent type(s) (`:614-615`), sharing the
        /// grouped chain with [`SigExpr::WithType`].
        Type {
            kw: KwType,
            binds: super::TypeBindsErasedV1,
        },
        /// `MODULE UPPER COLON sigexpr` (`:616-617`) — note `:` here (a
        /// decl constrains), vs `:>` on binds (a bind seals).
        Module {
            kw: KwModule,
            name: CtorTok,
            colon: ColonTok,
            sig_: Box<SigExpr>,
        },
        /// `SIGNATURE UPPER EXACT_EQ sigexpr` (`:618-619`).
        Signature {
            kw: KwSignature,
            name: CtorTok,
            eq: DefEqTok,
            sig_: Box<SigExpr>,
        },
        /// `INCLUDE sigexpr` (`:620-621`) — a decl-include includes a
        /// SIGNATURE (contrast [`super::Bind::Include`], which includes a
        /// MODULE).
        Include { kw: KwInclude, sig_: Box<SigExpr> },
    }

    // Ordered-choice safety of `Decl`: all arms are keyword-headed
    // (`val`/`type`/`module`/`signature`/`include`); within `val`, the
    // second token (`BindName`'s `Var`-or-`LParen` vs `HorzCmdTok` vs
    // `VertCmdTok`) is disjoint; within `type`, `TypeOpaque`-before-`Type`
    // as documented.

    /// `kind` (`parser_v1.mly:672-677`): `kind_base (ARROW kind_base)*`
    /// flattened head+`Vec` — the same deferred-fold shape as
    /// [`TypeProd`]/[`PatCons`], keeping the type acyclic. `kind_base` is a
    /// bare LOWER (`:678-681`, `MKindName`), so the whole kind grammar is
    /// token-only. (`kind_row`, `:682-683`, arrives with row quantifiers,
    /// not yet implemented.)
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct KindV1 {
        pub first: VarTok,
        pub rest: Vec<KindArrowV1>,
    }

    /// An `-> kind_base` continuation of a [`KindV1`].
    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
    pub struct KindArrowV1 {
        pub arrow: ArrowTok,
        pub base: VarTok,
    }

    // (`Quant` needs no struct: upstream `quant = list(tyquant)
    // list(rowquant)` (`:623-625`), and with rowquants deferred it is
    // exactly `Vec<TypeVarTok>` — inlined into `Decl::Val*` above.)
}

/// Lex ([`crate::lexer::lex_with_version`] under [`crate::version::RustyfiVersion::V0_1`])
/// and parse a whole 0.1 `.saty`/`.satyh` source file. Mirrors
/// [`crate::cst::parse_file`]'s two-step shape exactly, sharing its
/// [`crate::cst::ParseFileError`] (no new error type).
pub fn parse_file_v1(src: &str) -> Result<FileV1, crate::cst::ParseFileError> {
    let atoms = crate::lexer::lex_with_version(src, crate::version::RustyfiVersion::V0_1)
        .map_err(crate::cst::ParseFileError::from_lex)?;
    let mut stream = crate::stream::AtomStream::new(atoms);
    match <FileV1 as Parse<_>>::parse(&mut stream) {
        Ok(file) => Ok(file),
        // The one shared reducer, not the private copy this used to keep: a
        // 0.1 library is ONE top-level `module` binding, so it is the
        // generation that most needs the high-water mark. See
        // [`crate::parse_error`].
        Err(e) => Err(crate::parse_error::locate(src, &stream, &e)),
    }
}