Skip to main content

rustyfi_syntax/
cst_v1.rs

1//! The SATySFi **0.1.0** (`dev-0-1-0`) surface grammar — a *fork* of
2//! [`crate::cst`], not a version-gate of it (gating one shared `cst.rs` would
3//! mean hand-writing `Parse` for nearly every node, destroying the derive
4//! idiom and risking 0.0.6 on every 0.1 edit). [`crate::cst`] stays frozen:
5//! this module imports only its token-`Atom`-generic, non-recursive helpers
6//! ([`crate::cst::Header`], [`crate::cst::ParseFileError`]) and re-declares
7//! everything else — including its own `*ErasedV1` eraser leaves and its own
8//! copy of `render_parse_error` — so that touching `cst_v1.rs` never touches
9//! `cst.rs`.
10//!
11//! **Scope.** SATySFi 0.1's grammar adds a whole ML-style module system
12//! (`bind`/`modexpr`/`sigexpr`/`decl`) on top of an expr/pattern/type layer
13//! that is structurally close to 0.0.6's, plus five surface deltas:
14//! `,`-separated lists/records (not `;`), `EXACT_EQ` for both definitional
15//! and record `=` (reusing [`DefEqTok`] — no new `=` leaf), mandatory
16//! `match … with … end`, per-binding staging instead of a whole-file
17//! `@stage:` header, and no `when`/`while`/`before` at all. This module
18//! builds:
19//!
20//! * [`FileV1`] — `header* expr EOI` or `header* module Name
21//!   option(sig_annot) = struct bind* end EOI`.
22//! * [`Bind`] — every arm of upstream `bind`: `val`/`val inline`/`val
23//!   block`, `val math` (math-split — see
24//!   [`Bind::ValueMath`]), `val rec … and …`/`val mutable`/`type … and …`,
25//!   `module … = modexpr`/`signature … = sigexpr`/`include
26//!   modexpr`.
27//! * [`ast::ModExpr`]/[`ast::SigExpr`]/[`ast::Decl`] — the full
28//!   module/signature grammar: functor literals/
29//!   application, module paths/aliases, `:>` coercion, `sig … end` with
30//!   every `decl` form, `with type` refinement, `include`.
31//! * A copy of [`crate::cst::ast`]'s expr/pattern/type layer with the 0.1
32//!   deltas applied (see each type's doc comment for the exact delta),
33//!   including the full `let rec … and … in`/`let mutable … in` expression
34//!   forms, a widened `TypeExpr` grammar (products, prefix application),
35//!   `inline […]`/`block […]`/`math […]` command types
36//!   (`parser_v1.mly:730-735`) and `LONG_LOWER` qualified type paths
37//!   (`:720-728,742-743`; `TypeApp::AppliedLong`/`TypeAtom::LongName`).
38//!
39//! **Grammar shipped with placeholder semantics only.** Every
40//! module/signature construct beyond the struct-literal
41//! `ModExpr::Struct` body PARSES and round-trips, but lowers to a precise
42//! `LowerError` (`v1/lower.rs`) rather than real semantics — see that
43//! module's doc comment for the placeholder set and the seal rule.
44//!
45//! **Deliberately NOT built**: macro binds/decls
46//! and row quantifiers (`rowquant`). Staging DOES parse — the
47//! operand prefixes `&e`/`~e` ([`ast::StagePrefix`],
48//! `parser_v1.mly:870-873`) and the per-binding qualifier of `val ~x`/`val
49//! persistent ~x` ([`BindStageV1`], `:417-421` and the decl form
50//! `:600-603`), with `persistent` a 0.1-only keyword token.
51//!
52//! **The `#[recurse]` SCC story (five roots).** Five
53//! singleton, directly self-referential roots — the same shape
54//! [`crate::cst::ast`] uses, for the same reason (see its module doc comment
55//! for the measured compile-time blowup a naive transcription hits):
56//!
57//! * [`ast::Expr`] (its variants' own `Box<Expr>` children);
58//! * [`ast::PatBot`] (`CtorApplied`'s `Box<PatBot>` argument);
59//! * [`ast::TypeExpr`] (`Fun`'s right-recursive `Box<TypeExpr>` codomain);
60//! * [`ast::ModExpr`] (`Functor.body`'s `Box<ModExpr>` self-loop);
61//! * [`ast::SigExpr`] (`Functor.dom`/`Functor.cod`'s `Box<SigExpr>`
62//!   self-loop — encoded left-recursion-safe, `with` is
63//!   bot+suffix, never `With { base: Box<SigExpr> }`; see [`ast::SigExpr`]'s
64//!   own doc comment).
65//!
66//! Every other recursion edge is routed through the erasers declared below
67//! ([`ExprErasedV1`], [`PatErasedV1`], [`PatBotErasedV1`], [`TyErasedV1`],
68//! [`MathErasedV1`], [`ModExprErasedV1`], [`SigExprErasedV1`],
69//! [`TypeBindsErasedV1`]), keeping each SCC a singleton and the wrapped
70//! grammar's recursion reborrowing one stream type (syan pins it, not us).
71//! [`ast::Decl`] is a satellite, not a root: it has no `Box<Self>` anywhere
72//! and no type inside the `#[recurse]` module ever names it — it is reached
73//! only through the hand-written [`StructDeclV1`] connector (an opaque leaf
74//! to the SCC analysis, mirroring [`StructBindV1`]), so `SigExpr ↔ Decl`
75//! never forms a rootless static sub-cycle.
76
77use crate::leaf::*;
78use newer_type::implement;
79use syan::parse::{Parse, Unparse};
80
81/// `@require:` / `@import:` header element — byte-identical between 0.0.6
82/// and `dev-0-1-0` (this port's own confirmation), so 0.1 simply reuses
83/// [`crate::cst`]'s definition rather than re-declaring an identical enum.
84/// 0.1 has no `@stage:` header at all (the shared lexer's `V0_1` path
85/// rejects it outright — see `lexer.rs`'s `lex_header`), so
86/// [`crate::cst::Header`]'s absence of a `Stage` variant costs nothing here.
87pub use crate::cst::Header;
88
89/// A 0.1 header element — the UNION of BOTH packaging generations' header
90/// forms (Axis B). `Legacy` is `dev-0-1-0`'s `@require:`/`@import:`
91/// (byte-identical to 0.0.6's, reusing [`Header`]); the three `Use*`
92/// forms are `saphe-split`'s `headerelem` (`parser.mly:371-380 @ b836d512`).
93/// Which family is *legal* is a `LoadMode` question the loader answers
94/// (`rustyfi_loader`), not a grammar question — this ONE `V0_1` grammar
95/// accepts both so the mode error can be raised at load time with a better
96/// message than a lex error would give.
97///
98/// Variant order is parse priority (syan ordered-alternatives, most-specific
99/// first): `UsePackage` (the `package` keyword disambiguates) precedes the
100/// `of`-suffixed `UseOf`, which precedes bare `Use` (longest-match: `use M of
101/// …` must claim its `of` before a bare `use M` matches), which precedes the
102/// token-disjoint `Legacy` (`@`-headers lex to distinct tokens).
103#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
104pub enum HeaderV1 {
105    /// `USE PACKAGE optional_open mod_chain` — depend on an installed package
106    /// by its consumer-chosen alias (`used_as`). Header attributes
107    /// (`#[test-only]` etc., upstream `list(attribute)`) are DEFERRED.
108    UsePackage {
109        use_kw: KwUse,
110        package_kw: KwPackage,
111        open_kw: Option<KwOpen>,
112        path: ast::ModChainV1,
113    },
114    /// `USE optional_open mod_chain OF STRING` — load a local file by
115    /// backtick-quoted relative path (the `@import:` analog).
116    UseOf {
117        use_kw: KwUse,
118        open_kw: Option<KwOpen>,
119        path: ast::ModChainV1,
120        of_kw: KwOf,
121        relpath: LiteralTok,
122    },
123    /// `USE optional_open mod_chain` — sibling module inside the same package
124    /// (closed resolution; only legal inside envelope source trees, enforced
125    /// by the loader).
126    Use {
127        use_kw: KwUse,
128        open_kw: Option<KwOpen>,
129        path: ast::ModChainV1,
130    },
131    /// `@require:`/`@import:` — Legacy packaging, unchanged shape.
132    Legacy(Header),
133}
134
135impl HeaderV1 {
136    /// A short human-readable name for this header, for loader diagnostics
137    /// (e.g. `use package Stdlib`, `@require: foo`).
138    pub fn display_name(&self) -> String {
139        match self {
140            Self::UsePackage { path, .. } => format!("use package {}", path.render()),
141            Self::UseOf { path, relpath, .. } => {
142                format!("use {} of `{}`", path.render(), relpath.body)
143            }
144            Self::Use { path, .. } => format!("use {}", path.render()),
145            Self::Legacy(Header::Require(t)) => format!("@require: {}", t.content),
146            Self::Legacy(Header::Import(t)) => format!("@import: {}", t.content),
147            Self::Legacy(Header::Stage(_)) => "@stage:".to_string(),
148        }
149    }
150}
151
152impl ast::ModChainV1 {
153    /// The dotted path as source text, e.g. `Stdlib.Logo` or `Local`.
154    pub fn render(&self) -> String {
155        match self {
156            Self::Long(t) => {
157                let mut parts = t.mods.clone();
158                parts.push(t.name.clone());
159                parts.join(".")
160            }
161            Self::Single(t) => t.name.clone(),
162        }
163    }
164
165    /// The HEAD component — the module/envelope identifier the loader keys
166    /// dependency resolution off (upstream's `used_as` map is keyed by it;
167    /// the tail is submodule access, a typecheck-time concern). For `A.B.C`
168    /// that is `A`; for a bare `A` it is `A`.
169    pub fn head_name(&self) -> String {
170        match self {
171            Self::Long(t) => t.mods.first().cloned().unwrap_or_else(|| t.name.clone()),
172            Self::Single(t) => t.name.clone(),
173        }
174    }
175}
176
177/// A binding-position NAME: `LOWER | ( binop )` — upstream 0.1's
178/// `bound_identifier` (`parser_v1.mly:358-363`) is the same nonterminal
179/// 0.0.6's `var` folds ([`crate::cst::BindName`]'s doc comment), and the
180/// leaf-level parse (`VarTok` | `OpNameTok`) is identical in both
181/// generations, so 0.1 reuses the type rather than re-declaring it —
182/// another token-generic, non-recursive import like [`Header`] above.
183pub use crate::cst::BindName;
184
185/// A whole 0.1 `.saty`/`.satyh` file (`main`, upstream `parser_v1.mly:364-
186/// 368`): a header list followed by either a library (`main_lib`) or a
187/// document expression. Unlike 0.0.6's [`crate::cst::File`] (a flat prelude
188/// of top-level `let`s with an optional trailing `in body`), 0.1 has no flat
189/// top-level binding sequence at all: a document body is *just* an
190/// [`ast::Expr`] (every `let` chains its own `in`), and a library is exactly
191/// one `module … = struct … end`.
192#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
193pub enum FileV1 {
194    /// `header* expr EOI` (`parser_v1.mly:367`).
195    Document {
196        headers: Vec<HeaderV1>,
197        body: ast::Expr,
198        eoi: EoiTok,
199    },
200    /// `header* MODULE UPPER option(sig_annot) EXACT_EQ STRUCT bind* END
201    /// EOI` (`parser_v1.mly:372-375`, `main_lib`; `sig_annot = COERCE
202    /// sigexpr`, `:555-557`). Note 0.1's annotation sigil is
203    /// `:>` (COERCE), never 0.0.6's `: sig … end`.
204    Library {
205        headers: Vec<HeaderV1>,
206        module_kw: KwModule,
207        name: CtorTok,
208        sig_annot: Option<SigAnnotV1>,
209        eq: DefEqTok,
210        struct_kw: KwStruct,
211        binds: Vec<Bind>,
212        end_kw: KwEnd,
213        eoi: EoiTok,
214    },
215}
216
217/// `COERCE sigexpr` — a signature annotation `:> S` (`sig_annot`,
218/// `parser_v1.mly:555-557`). 0.1's annotation sigil is `:>` (COERCE,
219/// `lexer_v1.mll:280`), NOT 0.0.6's `: sig … end` ([`crate::cst::SigAnnot`],
220/// `cst.rs:295-303`) — `module M : S = …` is a 0.1 parse error (pinned in
221/// tests). The signature body goes through [`SigExprErasedV1`]: `SigAnnotV1`
222/// lives outside the `#[recurse]` module, so this is a cross-boundary edge
223/// into the `SigExpr` root (see the module doc comment's SCC story).
224#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
225pub struct SigAnnotV1 {
226    pub coerce: CoerceTok,
227    pub sig_: SigExprErasedV1,
228}
229
230/// One parameter of a [`Bind`] (`param_unit`, `parser_v1.mly:635-646`): an
231/// optional `?(l = x, …)` labeled-optional binder bundle, then either a
232/// plain `patbot` or a `( pat : τ )` ascribed pattern
233/// ([`ast::ParamBody::Ascribed`]). Defined INSIDE [`mod@ast`]
234/// and re-exported here so that [`ast::Expr::Fun`]/[`ast::Expr::LetIn`]/
235/// [`ast::RecClauseV1`] can reference it without a boundary-crossing
236/// Parse-trait cycle (the `TypeBindsErasedV1` E0275 hazard).
237pub use ast::{AscribedInnerV1, OptParamEntryV1, OptParamsV1, Param, ParamBody};
238
239/// Every arm of `bind` (`parser_v1.mly:415-440`) — upstream's own
240/// nonterminal name (helper types like [`StructBindV1`]/
241/// [`TypeBindSingleV1`] keep a `V1` suffix). Every value arm's `=` is
242/// `EXACT_EQ` ([`DefEqTok`]) and body is an [`ast::Expr`]. `name` is a
243/// [`crate::cst::BindName`] wherever upstream's `bound_identifier` reaches it
244/// (`Value`, and the rec clauses inside [`ast::RecClauseV1`]); `ValueMutable`
245/// and `ValueInline`/`ValueBlock`'s `ctx` stay plain [`VarTok`]s — upstream's
246/// `MUTABLE LOWER …`/ctx-variable productions are a plain `LOWER`, not
247/// `bound_identifier` (see [`crate::cst::BindName`]'s doc comment for the
248/// ordered-choice-safety argument).
249#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
250pub enum Bind {
251    /// `VAL PERSISTENT? EXACT_TILDE? bind_value_nonrec`
252    /// (`parser_v1.mly:416-421,442,459-465`): `val <stage>? <name> <param>*
253    /// = <expr>`, where `<stage>` is `~` (stage 0) or `persistent ~` (the
254    /// persistent stage) and its absence means stage 1, the document stage.
255    ///
256    /// The prefix is an `Option<BindStageV1>` tried before `name`; on an
257    /// unstaged `val x = …` it fails at the first token, collapses to `None`
258    /// and steals nothing, so every existing fixture parses unchanged. It
259    /// also keeps this arm ordered-choice-safe against the keyword-headed
260    /// `Value*` arms below: `val ~rec …` still fails here (at `name`, which
261    /// cannot match the `rec` keyword) and falls through, exactly as `val
262    /// rec …` does.
263    Value {
264        kw: KwVal,
265        stage: Option<BindStageV1>,
266        name: BindName,
267        params: Vec<Param>,
268        eq: DefEqTok,
269        body: ast::Expr,
270    },
271    /// `VAL INLINE bind_inline` (`parser_v1.mly:422-431` dispatch → `448` →
272    /// `466-491`): `val inline <ctx> \cmd <param>* = <expr>` (the
273    /// heavyweight, ctx-explicit form — the only one `stdja-mini` uses;
274    /// `ctx` stays `Option` so the lightweight, ctx-synthesized form parses
275    /// too, for free).
276    ValueInline {
277        kw: KwVal,
278        /// See [`Bind::Value::stage`] — upstream's qualifier sits before the
279        /// whole `bind_value`, and `bind_value` is what `inline`/`block`/
280        /// `math`/`rec`/`mutable` select between (`parser_v1.mly:417-421` →
281        /// `:581-593`), so every arm below carries the same prefix.
282        stage: Option<BindStageV1>,
283        inline_kw: KwInline,
284        ctx: Option<VarTok>,
285        cmd: AnyHorzCmdTok,
286        params: Vec<Param>,
287        eq: DefEqTok,
288        body: ast::Expr,
289    },
290    /// `VAL BLOCK bind_block` (`parser_v1.mly:450` → `493-518`): `val block
291    /// <ctx> +cmd <param>* = <expr>`.
292    ValueBlock {
293        kw: KwVal,
294        /// See [`Bind::ValueInline::stage`].
295        stage: Option<BindStageV1>,
296        block_kw: KwBlock,
297        ctx: Option<VarTok>,
298        cmd: AnyVertCmdTok,
299        params: Vec<Param>,
300        eq: DefEqTok,
301        body: ast::Expr,
302    },
303    /// `VAL MATH bind_math` (`parser_v1.mly:452-453` dispatch → `520-531`):
304    /// `val math <ctx> \cmd <param>* [with <sub> <sup>] = <expr>`.
305    /// Unlike `ValueInline`/`ValueBlock`, `ctx` is MANDATORY — upstream
306    /// has no lightweight ctx-less form (contrast `bind_inline`'s two
307    /// productions, :466-491). Placed after
308    /// `ValueBlock`, ordered-choice-safe for the same reason as `Value`
309    /// above: `math`/`with` both lex as keyword tokens under V0_1, so no
310    /// arm can steal another's input.
311    ValueMath {
312        kw: KwVal,
313        /// See [`Bind::ValueInline::stage`].
314        stage: Option<BindStageV1>,
315        math_kw: KwMath,
316        ctx: VarTok,
317        /// `\cmd` — math commands share the `\` sigil with inline commands
318        /// (there is no separate math-command token; see `elaborate.rs`'s
319        /// `command_scheme` doc comment, which notes the same sharing on
320        /// the eval side).
321        cmd: AnyHorzCmdTok,
322        params: Vec<Param>,
323        scripts: Option<ScriptsParamV1>,
324        eq: DefEqTok,
325        body: ast::Expr,
326    },
327    /// `VAL REC bind_value_nonrec (AND bind_value_nonrec)*`
328    /// (`parser_v1.mly:444-445,455-465`): `val rec f p* = e (and g p* = e)*`.
329    /// With `rec`/`mutable`/`inline`/`block` all lexed as keyword tokens
330    /// under V0_1, no arm can steal another's input —
331    /// `Value.name: BindName` cannot match a keyword token — so declared
332    /// order is a documentation/perf choice; `Value` stays first because it
333    /// is the overwhelmingly common arm.
334    ValueRec {
335        kw: KwVal,
336        /// See [`Bind::ValueInline::stage`]. One qualifier covers the whole
337        /// `and`-chain, matching upstream's single `UTBindValue(stage,
338        /// UTRec(binds))`.
339        stage: Option<BindStageV1>,
340        rec_kw: KwRec,
341        first: ast::RecClauseV1,
342        ands: Vec<ast::AndClauseV1>,
343    },
344    /// `VAL MUTABLE LOWER REVERSED_ARROW expr` (`parser_v1.mly:446-447`):
345    /// `val mutable x <- e`. The name is a plain `LOWER` upstream (not
346    /// `bound_identifier`), hence `VarTok`, matching the cst target
347    /// (`cst::TopBinding::LetMutable.name`, `cst.rs:237`).
348    ValueMutable {
349        kw: KwVal,
350        /// See [`Bind::ValueInline::stage`].
351        stage: Option<BindStageV1>,
352        mutable_kw: KwMutable,
353        name: VarTok,
354        arrow: OverwriteEqTok,
355        value: ast::Expr,
356    },
357    /// `TYPE bind_type_single (AND bind_type_single)*`
358    /// (`parser_v1.mly:432-433,535-544`): `type t 'a* = body (and u 'a* =
359    /// body)*` — variant and synonym forms, mutually recursive across the
360    /// `and` chain.
361    Type {
362        kw: KwType,
363        first: TypeBindSingleV1,
364        ands: Vec<TypeAndV1>,
365    },
366    /// `MODULE UPPER option(sig_annot) EXACT_EQ modexpr` — upstream
367    /// `bind`'s MODULE arm (`parser_v1.mly:434-435`), with the FULL
368    /// `modexpr` body and the optional `:>` annotation. The
369    /// body goes
370    /// through [`ModExprErasedV1`]: `Bind` is outside the `#[recurse]`
371    /// module, and `Bind → ModExpr → StructBindV1 → Bind` is the runtime
372    /// cycle both connectors erase (one break per direction).
373    Module {
374        module_kw: KwModule,
375        name: CtorTok,
376        sig_annot: Option<SigAnnotV1>,
377        eq: DefEqTok,
378        body: ModExprErasedV1,
379    },
380    /// `SIGNATURE UPPER EXACT_EQ sigexpr` (`parser_v1.mly:436-437`).
381    Signature {
382        kw: KwSignature,
383        name: CtorTok,
384        eq: DefEqTok,
385        sig_: SigExprErasedV1,
386    },
387    /// `INCLUDE modexpr` (`:438-439`) — a bind-include includes a MODULE
388    /// (contrast [`ast::Decl::Include`], which includes a signature).
389    Include { kw: KwInclude, body: ModExprErasedV1 },
390}
391
392/// The stage qualifier of a `val` bind or `val` decl: `~` alone is stage 0,
393/// `persistent ~` is the persistent stage (`parser_v1.mly:417-421` for binds,
394/// `:600-603` for decls). No prefix at all is stage 1 — the document stage,
395/// where an ordinary `val` lives — which is why the field holding this is an
396/// `Option`.
397///
398/// This is 0.1's replacement for 0.0.6's whole-file `@stage:` header: the
399/// same three stages, chosen per binding instead of per file.
400#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
401pub struct BindStageV1 {
402    pub persistent: Option<KwPersistent>,
403    pub tilde: ExactTildeTok,
404}
405
406/// `scripts_param` (`parser_v1.mly:532-534`): `WITH sub=LOWER sup=LOWER` —
407/// `val math`'s optional `with sub sup` suffix, binding the two
408/// script-callback parameters directly rather than synthesizing the
409/// hidden `%math-attach-scripts` wrapper.
410#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
411pub struct ScriptsParamV1 {
412    pub with_kw: KwWith,
413    pub sub: VarTok,
414    pub sup: VarTok,
415}
416
417/// One `bind_type_single` (`parser_v1.mly:539-544`). **0.1 delta from
418/// [`crate::cst::TypeDecl`]:** the type parameters come AFTER the name
419/// (`type t 'a = …`, `tyident LOWER; tyvars list(TYPEVAR)`), where 0.0.6
420/// writes them before (`type 'a t = …`, `cst.rs:401-408`) — the lowering
421/// reorders the fields. No `constraint` suffix exists in 0.1's production.
422#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
423pub struct TypeBindSingleV1 {
424    pub name: VarTok,
425    pub tyvars: Vec<TypeVarTok>,
426    pub eq: DefEqTok,
427    pub body: TypeBodyV1,
428}
429
430/// An `and bind_type_single` continuation (`bind_type`'s
431/// `separated_nonempty_list(AND, …)`, `parser_v1.mly:535-537`).
432#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
433pub struct TypeAndV1 {
434    pub and_kw: KwAnd,
435    pub bind: TypeBindSingleV1,
436}
437
438/// One whole `bind_type` chain — `bind_type_single (AND bind_type_single)*`
439/// (`parser_v1.mly:535-537`) — grouped into a single struct so the sig
440/// layer ([`ast::SigExpr::WithType`], [`ast::Decl::Type`]) can reference the
441/// chain through ONE eraser ([`TypeBindsErasedV1`]). [`Bind::Type`] keeps
442/// its flattened `first`/`ands` fields unchanged (avoiding call-site
443/// churn); the two spellings are the same grammar.
444#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
445pub struct TypeBindsV1 {
446    pub first: TypeBindSingleV1,
447    pub ands: Vec<TypeAndV1>,
448}
449
450/// The right-hand side of one type bind: a variant's constructor list
451/// (`EXACT_EQ BAR? variants`, `parser_v1.mly:540-541,545-553`) or a
452/// transparent synonym (`EXACT_EQ typ`, `:542-543`). Variant-first is
453/// unambiguous for the same reason as [`crate::cst::TypeDeclBody`]
454/// (`cst.rs:410-418`): a variant list is `BarTok`/`CtorTok`-headed and no
455/// [`ast::TypeExpr`] can start with either.
456#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
457pub enum TypeBodyV1 {
458    Variant {
459        leading_bar: Option<BarTok>,
460        first: VariantDefV1,
461        rest: Vec<BarVariantDefV1>,
462    },
463    Synonym(ast::TypeExpr),
464}
465
466/// One `UPPER [OF typ]` variant (`parser_v1.mly:549-553`).
467#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
468pub struct VariantDefV1 {
469    pub ctor: CtorTok,
470    pub of_ty: Option<OfTypeV1>,
471}
472
473/// The `of typ` payload suffix.
474#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
475pub struct OfTypeV1 {
476    pub of_kw: KwOf,
477    pub ty: ast::TypeExpr,
478}
479
480/// A `| UPPER [OF typ]` continuation (`variants`' `separated_nonempty_
481/// list(BAR, variant)`, `parser_v1.mly:545-548`).
482#[derive(Parse, Unparse, Debug, Clone, PartialEq)]
483pub struct BarVariantDefV1 {
484    pub bar: BarTok,
485    pub def: VariantDefV1,
486}
487
488/// One declaration inside a `module … = struct … end` body.
489/// [`Bind`]'s own alternatives are exactly what a struct
490/// body may contain (`bind*`), so this simply re-parses a [`Bind`] — but
491/// *not* by naming `Bind` as a field type directly: [`Bind`] lives
492/// **outside** the `#[recurse]` module (below), so `Bind -> ModExpr ->
493/// Vec<StructBindV1> -> Bind` would be a self-recursive cycle through a
494/// plain `#[derive(Parse)]`, which (without the `#[recurse]` engine to back
495/// it) is an `E0275` hazard (an unbounded recursive trait-bound
496/// obligation) — exactly [`crate::cst::StructDecl`]'s own rationale
497/// (`cst.rs:262-269`). Hand-writing `Parse`/`Unparse` here — the same trick
498/// as the `erased_leaf_v1!` macro below — sidesteps that: the impl has no
499/// recursive where-bound for the compiler to try to satisfy, it just calls
500/// `Bind::parse` through the stream-erasing adapter at runtime.
501#[derive(Debug, Clone, PartialEq)]
502pub struct StructBindV1(pub Box<Bind>);
503
504impl Parse<crate::token::Atom> for StructBindV1 {
505    type Error = syan::error::ParseError<crate::span::Span>;
506
507    fn parse_stream<S: syan::parse::ParseStream<Atom = crate::token::Atom>>(
508        stream: &mut S,
509    ) -> Result<Self, Self::Error> {
510        let value = <Bind as Parse<_>>::parse_stream(stream)?;
511        Ok(StructBindV1(Box::new(value)))
512    }
513}
514
515impl Unparse<crate::token::Atom> for StructBindV1 {
516    fn unparse<S: syan::parse::unparse::Emitter<crate::token::Atom>>(
517        &self,
518        sink: &mut S,
519    ) -> Result<(), S::Error> {
520        self.0.unparse(sink)
521    }
522}
523
524/// One declaration inside a `sig … end` body (`list(decl)`,
525/// `parser_v1.mly:591`) — [`StructBindV1`]'s twin, hand-written `Parse`/
526/// `Unparse` for the same `E0275` reason. [`ast::Decl`] lives INSIDE the
527/// `#[recurse]` module and `SigExpr → SigBotV1 → StructDeclV1 → Decl →
528/// SigExpr` is a runtime cycle; naming `ast::Decl` as a plain derived field
529/// of [`ast::SigBotV1`] would re-enter the module's own SCC analysis. As an
530/// opaque leaf it closes that cycle at RUNTIME while keeping both SCCs
531/// singletons. NOTE: named after [`crate::cst::StructDecl`] (the mechanism),
532/// even though it carries a sig-`decl`, not a struct binding.
533#[derive(Debug, Clone, PartialEq)]
534pub struct StructDeclV1(pub Box<ast::Decl>);
535
536impl Parse<crate::token::Atom> for StructDeclV1 {
537    type Error = syan::error::ParseError<crate::span::Span>;
538
539    fn parse_stream<S: syan::parse::ParseStream<Atom = crate::token::Atom>>(
540        stream: &mut S,
541    ) -> Result<Self, Self::Error> {
542        let value = <ast::Decl as Parse<_>>::parse_stream(stream)?;
543        Ok(StructDeclV1(Box::new(value)))
544    }
545}
546
547impl Unparse<crate::token::Atom> for StructDeclV1 {
548    fn unparse<S: syan::parse::unparse::Emitter<crate::token::Atom>>(
549        &self,
550        sink: &mut S,
551    ) -> Result<(), S::Error> {
552        self.0.unparse(sink)
553    }
554}
555
556/// Recursion-edge eraser types for the expr/pattern/type layer —
557/// the `cst_v1` analogue of [`crate::cst`]'s `erased_leaf!` macro (see its
558/// doc comment for the measured compile-time blowup that makes this
559/// mandatory). Suffixed `V1` throughout so these never collide with
560/// [`crate::cst`]'s own erasers, even though the two live in sibling
561/// modules and could not actually name-clash. Defined *outside* the
562/// `#[recurse]` module so the macro treats them as opaque leaves.
563macro_rules! erased_leaf_v1 {
564    ($($(#[$doc:meta])* $name:ident => $target:ty;)*) => {
565        $(
566            $(#[$doc])*
567            #[implement(newer_type_std::ops::Deref)]
568            #[derive(Debug, Clone, PartialEq)]
569            pub struct $name(pub Box<$target>);
570
571            impl Parse<crate::token::Atom> for $name {
572                type Error = syan::error::ParseError<crate::span::Span>;
573
574                fn parse_stream<S: syan::parse::ParseStream<Atom = crate::token::Atom>>(
575                    stream: &mut S,
576                ) -> Result<Self, Self::Error> {
577                    // No erasure any more — see `cst.rs`'s `erased_leaf!`.
578                    let value = <$target as Parse<_>>::parse_stream(stream)?;
579                    Ok($name(Box::new(value)))
580                }
581            }
582
583            impl Unparse<crate::token::Atom> for $name {
584                fn unparse<S: syan::parse::unparse::Emitter<crate::token::Atom>>(
585                    &self,
586                    sink: &mut S,
587                ) -> Result<(), S::Error> {
588                    self.0.unparse(sink)
589                }
590            }
591        )*
592    };
593}
594
595erased_leaf_v1! {
596    /// An [`ast::Expr`] behind a stream-erasing parse (see above).
597    ExprErasedV1 => ast::Expr;
598    /// An [`ast::Pattern`] behind a stream-erasing parse (see above).
599    PatErasedV1 => ast::Pattern;
600    /// An [`ast::PatBot`] behind a stream-erasing parse (see above). Kept
601    /// separate from [`PatErasedV1`] for the same reason
602    /// [`crate::cst`]'s `PatErased`/`PatBotErased` split exists: a
603    /// constructor pattern's argument is a `patbot`, not a full `patas`.
604    PatBotErasedV1 => ast::PatBot;
605    /// An [`ast::TypeExpr`] behind a stream-erasing parse (see above).
606    TyErasedV1 => ast::TypeExpr;
607    /// An [`ast::MathElemCst`] behind a stream-erasing parse (see above).
608    MathErasedV1 => ast::MathElemCst;
609    /// An [`ast::ModExpr`] behind a stream-erasing parse. Carries the
610    /// OUTSIDE→INSIDE edge `Bind::Module.body → ModExpr` — the one edge of
611    /// the `Bind → ModExpr → StructBindV1 → Bind` runtime cycle not already
612    /// erased by the connector (the erasers are for the INSIDE types, not
613    /// for `Bind`).
614    ModExprErasedV1 => ast::ModExpr;
615    /// An [`ast::SigExpr`] behind a stream-erasing parse. Used by
616    /// [`SigAnnotV1`] and [`Bind::Signature`] (outside → the SigExpr root).
617    SigExprErasedV1 => ast::SigExpr;
618    /// A [`TypeBindsV1`] behind a stream-erasing parse. Unlike every other
619    /// eraser this one targets an OUTSIDE type: `SigExpr::WithType` /
620    /// `Decl::Type` (inside) must reach `bind_type`, whose
621    /// `TypeBindSingleV1` re-enters the module through plain-derived
622    /// `ast::TypeExpr` fields — an inside→outside-plain-derive→inside-root
623    /// chain with no precedent in `cst.rs`'s discipline. Erasing at the
624    /// boundary keeps the re-entry cheap (one stream type, monomorphized
625    /// once), exactly like every other cross-boundary edge.
626    TypeBindsErasedV1 => TypeBindsV1;
627}
628
629/// The recursive expression/pattern/type/text grammar for SATySFi 0.1.
630/// A copy of [`crate::cst::ast`] with the deltas documented on each
631/// type; see the module doc comment for the SCC/root story.
632#[syan::parse::recurse]
633pub mod ast {
634    use crate::leaf::*;
635    use syan::parse::{Parse, Unparse};
636
637    /// One `param_unit` (`parser_v1.mly:635-646`): an optional `?(l = x, …)`
638    /// labeled-optional binder bundle, then a [`ParamBody`] (a plain
639    /// `patbot`, or a `( pat : τ )` ascribed pattern). Held inside `mod ast`
640    /// (re-exported at [`super::Param`]) so the roots that carry param lists
641    /// (`Expr::Fun`/`Expr::LetIn`/`RecClauseV1`) reference it without a
642    /// boundary Parse-trait cycle. A bare `patbot` param parses `Param {
643    /// opts: None, body: ParamBody::Pat(_) }` directly — the `?`-headed
644    /// `opts` `Option` is tried first, failing on a non-`?` head with no
645    /// token stolen, so an all-plain param list parses unchanged.
646    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
647    pub struct Param {
648        pub opts: Option<OptParamsV1>,
649        pub body: ParamBody,
650    }
651
652    /// A `param_unit`'s trailing shape (`parser_v1.mly:635-646`): either a
653    /// plain `patbot`, or a `( pattern : typ )` ascribed pattern
654    /// (`parser_v1.mly:641-645`).
655    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
656    pub enum ParamBody {
657        /// Tried FIRST: `( x : int )` fails `patbot`'s own paren body at the
658        /// `:` (a `patbot` paren group expects only more patterns/`,`/`)`)
659        /// and backtracks to `Ascribed` cleanly (ordered choice, no token
660        /// stolen).
661        Pat(PatBot),
662        /// `( pattern : typ )` — a FULL `pattern` (not `patbot`) ascribed
663        /// with a full `typ`, both via erasers (same cycle-avoidance
664        /// discipline as every other satellite in this module).
665        Ascribed {
666            paren: ParenGroup<()>,
667            #[group(self.paren)]
668            inner: AscribedInnerV1,
669        },
670    }
671
672    /// An ascribed param's group content: `pattern : typ` (`parser_v1.mly`'s
673    /// `param_unit`, `:641-645`).
674    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
675    pub struct AscribedInnerV1 {
676        pub pat: super::PatErasedV1,
677        pub colon: ColonTok,
678        pub ty: super::TyErasedV1,
679    }
680
681    /// A `?(l = x, …)` labeled-optional parameter bundle (`parser_v1.mly`'s
682    /// optional-`param_unit` head). The `?` reuses [`OptionalTypeTok`]
683    /// (SATySFi 0.1 dropped the fused `?:` sigil); the `(…)` is a paren
684    /// group of `,`-separated `label = binder` entries (non-empty enforced
685    /// at lowering).
686    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
687    pub struct OptParamsV1 {
688        pub q: OptionalTypeTok,
689        pub paren: ParenGroup<()>,
690        #[group(self.paren)]
691        pub entries: Vec<OptParamEntryV1>,
692    }
693
694    /// One `label = binder` entry of an [`OptParamsV1`] bundle (the last `,`
695    /// is optional; `=` is upstream's `EXACT_EQ`, reusing [`DefEqTok`]).
696    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
697    pub struct OptParamEntryV1 {
698        pub label: VarTok,
699        pub eq: DefEqTok,
700        pub var: VarTok,
701        pub comma: Option<CommaTok>,
702    }
703
704    /// `nxlet`-analogue: a let/if/match/lambda-headed expression, falling
705    /// through to the flattened operator chain ([`Expr::Ops`], [`OpChain`]) at the
706    /// bottom. Variant order is parse priority (ordered-choice
707    /// backtracking): every `let`-headed form is tried before the fallback
708    /// [`Expr::Overwrite`]/[`Expr::Ops`] (which may also start with a bare
709    /// variable), and `Ops` — having no distinguishing leading keyword —
710    /// must stay last.
711    ///
712    /// **0.1 deltas from [`crate::cst::ast::Expr`]:** `Match` gains a
713    /// mandatory trailing `end` (`parser_v1.mly:792`); `let-rec` becomes
714    /// `let rec … in …` (a plain `let` followed by the new [`KwRec`]
715    /// keyword) with full `and`-chained mutual recursion (see
716    /// [`Expr::LetRecIn`]); a new `LetMutableIn` form covers `let mutable x
717    /// <- init in body`; a new `LetPatternIn` form covers
718    /// `let pat = value in body` for any non-bare-variable pattern
719    /// (`parser_v1.mly:796`, `pattern_non_var`); `open` requires a leading
720    /// `let` (`parser_v1.mly:798`, `LET OPEN UPPER IN`) where 0.0.6 allows a
721    /// bare `open Name in body`; and `WhileDo`, the `Guard`/`when` match-arm
722    /// suffix, and `OpChain`'s `before` postfix are dropped entirely —
723    /// SATySFi 0.1's grammar has no `WHEN`/`WHILE`/`BEFORE` tokens at all
724    /// (confirmed by grep of `parser_v1.mly`). `Overwrite` (`name <- value`)
725    /// is kept unchanged (`parser_v1.mly:810-812`, `REVERSED_ARROW`) — it is
726    /// unrelated to the removed `before` postfix.
727    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
728    pub enum Expr {
729        /// `let rec clause (and clause)* in body` (`parser_v1.mly:794-795`
730        /// dispatching to `bind_value_rec`, `:455-458`) — full mutual
731        /// recursion.
732        LetRecIn {
733            let_kw: KwLet,
734            rec_kw: KwRec,
735            first: RecClauseV1,
736            ands: Vec<AndClauseV1>,
737            in_kw: KwIn,
738            body: Box<Expr>,
739        },
740        /// `let mutable x <- init in body` (`parser_v1.mly:794-795`
741        /// dispatching to `bind_value`'s MUTABLE arm, `:446-447`). Same
742        /// shape as [`crate::cst::ast::Expr::LetMutableIn`] minus the fused
743        /// keyword: 0.1 spells it `let mutable` (two tokens), 0.0.6
744        /// `let-mutable` (one). Disambiguated one token after `let` by the
745        /// V0_1-gated `mutable` keyword, so declared order relative to the
746        /// other `let`-headed arms is correctness-irrelevant.
747        LetMutableIn {
748            let_kw: KwLet,
749            mutable_kw: KwMutable,
750            name: VarTok,
751            arrow: OverwriteEqTok,
752            init: Box<Expr>,
753            in_kw: KwIn,
754            body: Box<Expr>,
755        },
756        /// `let name param* = value in body` (only a plain variable target
757        /// is supported here — a general pattern falls through to
758        /// [`Expr::LetPatternIn`]). `name` is a [`super::BindName`] —
759        /// upstream's expression-level `let` reaches the
760        /// same `bind_value_nonrec` (`:794-795` → `:459-465`) `val`/`val
761        /// rec` do, so `let (+++) a b = … in` is valid 0.1 here too.
762        LetIn {
763            kw: KwLet,
764            name: super::BindName,
765            params: Vec<Param>,
766            eq: DefEqTok,
767            value: Box<Expr>,
768            in_kw: KwIn,
769            body: Box<Expr>,
770        },
771        /// `let pat = value in body` (`parser_v1.mly:796`,
772        /// `pattern_non_var`) — any pattern shape, tried only after the
773        /// bare-variable form [`Expr::LetIn`] fails to match.
774        LetPatternIn {
775            kw: KwLet,
776            pat: super::PatErasedV1,
777            eq: DefEqTok,
778            value: Box<Expr>,
779            in_kw: KwIn,
780            body: Box<Expr>,
781        },
782        /// `let open Name in body` (`parser_v1.mly:798`; unlike 0.0.6's
783        /// bare `open Name in body`, 0.1 requires the leading `let`).
784        OpenIn {
785            let_kw: KwLet,
786            open_kw: KwOpen,
787            name: CtorTok,
788            in_kw: KwIn,
789            body: Box<Expr>,
790        },
791        /// `if cond then a else b` (`else` is never optional, so there is
792        /// no dangling-else ambiguity).
793        If {
794            kw: KwIf,
795            cond: Box<Expr>,
796            then_kw: KwThen,
797            then_branch: Box<Expr>,
798            else_kw: KwElse,
799            else_branch: Box<Expr>,
800        },
801        /// `fun x y -> body`. Each parameter is a full `patbot` (through
802        /// `Param`), not a bare variable: upstream `parser_v1.mly:849-863`'s
803        /// `fun` genuinely binds a `patbot` per parameter (`ELambda(patbot,
804        /// e)` in `types.cppo.ml`), so `fun _ -> …` (wildcard) and `fun (a,
805        /// b) -> …` (tuple-destructuring) are legal upstream syntax (gaps
806        /// 2+3 of the V0_1-only language-completeness sweep). Reaching
807        /// `PatBot` from here is the same cross-root DAG edge
808        /// [`RecClauseV1::params`] already makes (both `Expr` and `PatBot`
809        /// are roots inside this `#[recurse]` module — see the module doc
810        /// comment), so no new SCC edge.
811        Fun {
812            kw: KwFun,
813            params: Vec<Param>,
814            arrow: ArrowTok,
815            body: Box<Expr>,
816        },
817        /// `match scrutinee with [|] pat -> body (| pat -> body)* end`
818        /// (`parser_v1.mly:792`). Mandatorily closed with `end`
819        /// (`tokR=END`); no `when` guards (0.1 has no `WHEN` token).
820        Match {
821            kw: KwMatch,
822            scrutinee: Box<Expr>,
823            with_kw: KwWith,
824            leading_bar: Option<BarTok>,
825            first: MatchArm,
826            rest: Vec<BarArm>,
827            end_kw: KwEnd,
828        },
829        /// `name <- value` (`expr_overwrite`, `parser_v1.mly:810-812`,
830        /// `REVERSED_ARROW`). Starts with a bare [`VarTok`], which is also
831        /// how [`Expr::Ops`] can start — must stay before `Ops` so
832        /// backtracking tries the `<-` shape first.
833        Overwrite {
834            name: VarTok,
835            arrow: OverwriteEqTok,
836            value: super::ExprErasedV1,
837        },
838        /// The flattened binary-operator chain — see
839        /// [`crate::cst::ast::Expr`]'s module doc comment on precedence
840        /// flattening (unchanged approach here). Must stay last (no leading
841        /// keyword).
842        Ops(OpChain),
843    }
844
845    /// One `name param* = value` clause of a `val rec`/`let rec` group —
846    /// upstream `bind_value_nonrec` (`parser_v1.mly:459-465`) as reached
847    /// from `bind_value_rec` (`:455-458`). **0.1 deltas from
848    /// [`crate::cst::ast::RecBinding`]:** no `: ty` ascription and no
849    /// multi-clause `| patbot* = value` sugar exist in 0.1 at all
850    /// (`bind_value_nonrec` has neither a `COLON ty` nor a `BAR`
851    /// alternative — 0.0.6's `recdecargpart` machinery has no 0.1
852    /// counterpart), so there are no `ascription`/`leading_bar`/`extra`
853    /// fields to mirror. `params` is upstream's `list(param_unit)` (see
854    /// [`super::Param`]'s doc comment), reaching `PatBot` through the same
855    /// cross-root DAG edge `cst::ast::RecBinding.params` makes
856    /// (`cst.rs:753-762`); `value` goes through [`super::ExprErasedV1`] (not
857    /// `Box<Expr>`) so this struct never joins `Expr`'s SCC — byte-for-byte
858    /// `cst.rs`'s own `RecBinding.value: ExprErased` discipline.
859    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
860    pub struct RecClauseV1 {
861        pub name: super::BindName,
862        pub params: Vec<Param>,
863        pub eq: DefEqTok,
864        pub value: super::ExprErasedV1,
865    }
866
867    /// An `and name param* = value` continuation of a `val rec`/`let rec`
868    /// group (`bind_value_rec`'s `separated_nonempty_list(AND, …)`,
869    /// `parser_v1.mly:455-458`). `and` lexes as `Token::LetAnd` → [`KwAnd`]
870    /// in both generations (`lexer.rs:141`), so no new token is needed.
871    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
872    pub struct AndClauseV1 {
873        pub and_kw: KwAnd,
874        pub clause: RecClauseV1,
875    }
876
877    /// One `pat -> body` match arm (`parser_v1.mly:959`). Unlike
878    /// [`crate::cst::ast::MatchArm`], has no `when` guard — 0.1's grammar
879    /// has none.
880    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
881    pub struct MatchArm {
882        pub pat: super::PatErasedV1,
883        pub arrow: ArrowTok,
884        pub body: super::ExprErasedV1,
885    }
886
887    /// A `| pat -> body` continuation of a match's arm list.
888    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
889    pub struct BarArm {
890        pub bar: BarTok,
891        pub arm: MatchArm,
892    }
893
894    /// A flattened binary-operator chain: `head (op rhs)*`, left-folded
895    /// (with correct per-operator precedence/associativity) during
896    /// elaboration — see [`crate::cst::ast::OpChain`]'s doc comment.
897    /// **Delta:** no `before` postfix field — 0.1 has no `BEFORE` token at
898    /// all (confirmed by grep of `parser_v1.mly`), so
899    /// [`crate::cst::ast::OpChain::before`] simply has no 0.1 counterpart.
900    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
901    pub struct OpChain {
902        pub head: AppExpr,
903        pub tail: Vec<OpRhs>,
904    }
905
906    /// One `op rhs` continuation of an [`OpChain`].
907    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
908    pub struct OpRhs {
909        pub op: BinOpTok,
910        pub rhs: AppExpr,
911    }
912
913    /// `nxun`/`nxapp`/`nxunsub`-analogue flattened: an optional leading
914    /// unary minus, an optional leading `!`/`!!`/... deref, an atomic head
915    /// with any `#label` field accesses, and an application-chain tail —
916    /// structurally identical to [`crate::cst::ast::AppExpr`] (`expr_app`,
917    /// `parser_v1.mly:849-863`, no 0.1 delta).
918    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
919    pub struct AppExpr {
920        pub minus: Option<ExactMinusTok>,
921        pub stage: Option<StagePrefix>,
922        pub excl: Option<UnopExclamTok>,
923        pub head: Atomic,
924        pub head_accesses: Vec<AccessSeg>,
925        pub args: Vec<AppArg>,
926    }
927
928    /// A staging prefix on a 0.1 operand: `&e` builds code for the next
929    /// stage, `~e` splices the result of a previous-stage computation
930    /// (`expr_un`, `parser_v1.mly:870-873`, `UTNext`/`UTPrev` — the same two
931    /// productions 0.0.6 has, unchanged).
932    ///
933    /// A fork of [`crate::cst::ast::StagePrefix`], not a re-export: it lives
934    /// inside 0.0.6's `#[recurse]` module, and this module's whole discipline
935    /// is that touching `cst_v1.rs` never touches `cst.rs` (module doc
936    /// comment). The two are token-identical, so `rustyfi-lang`'s
937    /// `v1::lower` maps one to the other by moving tokens.
938    ///
939    /// Upstream puts these on `expr_un`, one level BELOW `expr_app`, so
940    /// `&f x` is `(&f) x` and never `&(f x)`. This grammar flattens
941    /// `expr_un`/`expr_app` into one node, so the prefix is an optional field
942    /// on the *head* ([`AppExpr`]) and on each *argument* ([`AppArg`])
943    /// independently — which reproduces exactly that reading.
944    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
945    pub enum StagePrefix {
946        /// `&e` — quote: the value is `e`'s code, to run one stage later.
947        Next(ExactAmpTok),
948        /// `~e` — splice: run `e` now and drop its code in here.
949        Prev(ExactTildeTok),
950    }
951
952    /// One `#label` field-access segment (`expr_bot ACCESS`,
953    /// `parser_v1.mly:878`).
954    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
955    pub struct AccessSeg {
956        pub hash: AccessTok,
957        pub label: VarTok,
958    }
959
960    /// One application-chain argument. **0.1 delta:** the 0.0.6 `?:`/`?*`
961    /// (`Optional`/`Omission`) forms are gone — SATySFi 0.1 dropped the fused
962    /// `?:` sigil (`?:`/`?*` now lex as `?` + `:`/`*`, a downstream parse
963    /// error), replaced by the labeled `?(l = e, …)` bundle
964    /// ([`AppArg::Bundled`]).
965    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
966    pub enum AppArg {
967        /// `?(l = e, …) atom` — a labeled-optional bundle paired with the
968        /// positional argument it precedes (pairing them rejects a dangling
969        /// trailing bundle at parse time). `?(`-headed, token-disjoint from
970        /// the `Atom`/`Ctor` arms.
971        Bundled {
972            opts: OptArgsV1,
973            excl: Option<UnopExclamTok>,
974            atom: Atomic,
975            accesses: Vec<AccessSeg>,
976        },
977        /// `?(l = e, …) Ctor` — as [`AppArg::Bundled`] but the positional
978        /// argument is a bare constructor.
979        BundledCtor { opts: OptArgsV1, ctor: CtorTok },
980        Atom {
981            stage: Option<StagePrefix>,
982            excl: Option<UnopExclamTok>,
983            atom: Atomic,
984            accesses: Vec<AccessSeg>,
985        },
986        Ctor(CtorTok),
987    }
988
989    /// A `?(l = e, …)` labeled-optional application bundle: the `?` sigil
990    /// (reusing [`OptionalTypeTok`]), then a paren group of `,`-separated
991    /// `label = expr` entries (non-empty enforced at lowering).
992    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
993    pub struct OptArgsV1 {
994        pub q: OptionalTypeTok,
995        pub paren: ParenGroup<()>,
996        #[group(self.paren)]
997        pub entries: Vec<OptArgEntryV1>,
998    }
999
1000    /// One `label = expr` entry of an [`OptArgsV1`] bundle — a FULL
1001    /// expression (`?(bias = 1 + n)`), routed through [`super::ExprErasedV1`]
1002    /// so this satellite never joins `Expr`'s SCC.
1003    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1004    pub struct OptArgEntryV1 {
1005        pub label: VarTok,
1006        pub eq: DefEqTok,
1007        pub value: super::ExprErasedV1,
1008        pub comma: Option<CommaTok>,
1009    }
1010
1011    /// `expr_bot`-analogue: an atomic expression. **Delta:** [`Atomic::List`]
1012    /// and [`Atomic::Record`] are now `,`-separated
1013    /// (`optterm_list(COMMA, …)`, `parser_v1.mly:935,942`) rather than
1014    /// 0.0.6's `;`-separated forms — see [`ListItem`]/[`RecordField`].
1015    /// Parenthesized/tuple bodies were already `,`-separated in 0.0.6 and
1016    /// are unchanged (`parser_v1.mly:914`).
1017    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1018    pub enum Atomic {
1019        Length(LengthTok),
1020        Float(FloatTok),
1021        Int(IntTok),
1022        Literal(LiteralTok),
1023        True(KwTrue),
1024        False(KwFalse),
1025        /// A bare constructor, e.g. `None`, or the head of `Some 1`.
1026        Ctor(CtorTok),
1027        Var(VarTok),
1028        /// `Mod.x` — a module-qualified variable.
1029        VarWithMod(VarWithModTok),
1030        /// `command \cmd` (upstream `parser_v1.mly:906`, `L_PAREN COMMAND
1031        /// backslash_cmd R_PAREN` — the parens arrive via [`Atomic::Paren`]
1032        /// here, exactly like [`crate::cst::ast::Atomic::Command`], which
1033        /// this reproduces verbatim; the `plus_cmd` alternative at :908 is
1034        /// deferred with the same rationale as the 0.0.6 comment). Needed by
1035        /// the transliterated `v01-mini.satyh`'s `(command \math)`.
1036        Command { kw: CommandTok, name: AnyHorzCmdTok },
1037        /// `()`
1038        Unit { paren: UnitParen },
1039        /// `( expr )` or `( expr, expr, … )` (the latter elaborates to a
1040        /// tuple).
1041        Paren {
1042            paren: ParenGroup<()>,
1043            #[group(self.paren)]
1044            inner: Box<ParenBody>,
1045        },
1046        /// `(| label = expr, … |)` or `(| base with label = expr, … |)`
1047        /// (`,`-separated — see [`RecordBody`]).
1048        Record {
1049            rec: RecordGroup<()>,
1050            #[group(self.rec)]
1051            body: RecordBody,
1052        },
1053        /// `[ expr, … ]` (`,`-separated — see [`ListItem`]).
1054        List {
1055            list: ListGroup<()>,
1056            #[group(self.list)]
1057            items: Vec<ListItem>,
1058        },
1059        /// `{ inline text }`
1060        InlineText {
1061            igrp: InlineGroup<()>,
1062            #[group(self.igrp)]
1063            elems: Vec<InlineElem>,
1064        },
1065        /// `'< block text >`
1066        BlockText {
1067            bgrp: BlockGroup<()>,
1068            #[group(self.bgrp)]
1069            elems: Vec<BlockElem>,
1070        },
1071        /// `${ math }`. Parses the same math grammar as 0.0.6; the
1072        /// `math-text`/`math-boxes` value split is a lowering/typing
1073        /// concern, not a cst_v1 shape change.
1074        MathText {
1075            mgrp: MathGroup<()>,
1076            #[group(self.mgrp)]
1077            elems: Vec<super::MathErasedV1>,
1078        },
1079    }
1080
1081    /// `(| … |)`'s content: either a plain field list, or a *record
1082    /// update* `base with l = e, …` (`parser_v1.mly:942-957`). `Update` is
1083    /// tried first (backtracks cleanly to `Fields`, same rationale as
1084    /// [`crate::cst::ast::RecordBody`]).
1085    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1086    pub enum RecordBody {
1087        Update {
1088            base: super::ExprErasedV1,
1089            with_kw: KwWith,
1090            fields: Vec<RecordField>,
1091        },
1092        Fields(Vec<RecordField>),
1093    }
1094
1095    /// The parenthesized-expression group's content: one expression, plus
1096    /// any `, expr` continuations (present only for a tuple) — unchanged
1097    /// from 0.0.6 (already `,`-separated, `parser_v1.mly:914`).
1098    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1099    pub struct ParenBody {
1100        pub first: super::ExprErasedV1,
1101        pub rest: Vec<CommaExpr>,
1102    }
1103
1104    /// A `, expr` continuation inside a parenthesized tuple.
1105    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1106    pub struct CommaExpr {
1107        pub comma: CommaTok,
1108        pub value: super::ExprErasedV1,
1109    }
1110
1111    /// One record field `label = expr,` (the last `,` is optional; `=` is
1112    /// upstream's `EXACT_EQ`, reusing [`DefEqTok`]). **Delta from
1113    /// [`crate::cst::ast::RecordField`]:** `,` separator, not `;`.
1114    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1115    pub struct RecordField {
1116        pub name: VarTok,
1117        pub eq: DefEqTok,
1118        pub value: super::ExprErasedV1,
1119        pub comma: Option<CommaTok>,
1120    }
1121
1122    /// One list element `expr,` (the last `,` is optional). **Delta from
1123    /// [`crate::cst::ast::ListItem`]:** `,` separator, not `;`.
1124    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1125    pub struct ListItem {
1126        pub value: super::ExprErasedV1,
1127        pub comma: Option<CommaTok>,
1128    }
1129
1130    /// One inline-text element — identical shape to
1131    /// [`crate::cst::ast::InlineElem`] (no 0.1 delta; text-mode content is
1132    /// untouched by the comma/`end` deltas).
1133    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1134    pub enum InlineElem {
1135        Char(CharTok),
1136        /// A backtick literal written inside inline text (`` `…` ``). Its own
1137        /// arm, not a `Char` run, so the elaborator can dispatch it through the
1138        /// context's code-text command — see `Token::CodeText`.
1139        CodeText(CodeTextTok),
1140        Space(SpaceTok),
1141        Break(BreakTok),
1142        /// `#var;` — embeds a program variable's value as inline content.
1143        Embed { var: VarInHorzTok, semi: EndActiveTok },
1144        /// `${ math }` — embeds math content as inline text.
1145        EmbedMath {
1146            mgrp: MathGroup<()>,
1147            #[group(self.mgrp)]
1148            elems: Vec<super::MathErasedV1>,
1149        },
1150        /// `\cmd …` (`name` also accepts the module-qualified `\Mod.cmd`
1151        /// form).
1152        Cmd { name: AnyHorzCmdTok, tail: CmdTail },
1153        /// An itemize bullet (`*`+) marker.
1154        ItemBullet(ItemTok),
1155        /// A `|` separator marker.
1156        Sep(SepTok),
1157    }
1158
1159    /// One block-text element — identical shape to
1160    /// [`crate::cst::ast::BlockElem`] (no 0.1 delta).
1161    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1162    pub enum BlockElem {
1163        /// `#var;` — embeds a program variable's value as block content.
1164        Embed { var: VarInVertTok, semi: EndActiveTok },
1165        /// `+cmd …` (`name` also accepts the module-qualified `+Mod.cmd`
1166        /// form).
1167        Cmd { name: AnyVertCmdTok, tail: CmdTail },
1168    }
1169
1170    /// A command's arguments — identical shape to
1171    /// [`crate::cst::ast::CmdTail`] — **0.1 delta:** an optional LEADING
1172    /// `?(l = e, …)` bundle. A command
1173    /// applied with an optional on its FIRST argument (`\cmd ?(l = e){arg}`,
1174    /// `+sec ?(label = t){title}<body>` — the ONLY shape the capstone census
1175    /// finds) can't ride inside `args` (an `expr_app` application chain whose
1176    /// *head* must be a bare `Atomic`, never a `?`-headed bundle — the head
1177    /// slot has no place for a leading bundle), so it is peeled off here as
1178    /// `lead_opts` and re-attached to the first argument at lowering
1179    /// (`v1::lower::lower_cmd_tail`). A bundle on a LATER argument
1180    /// (`\cmd{a} ?(l = e){b}`) still rides inside `args` as an ordinary
1181    /// [`AppArg::Bundled`]. `?(`-headed, token-disjoint from every
1182    /// `args` head shape, so a bundle-less tail parses `lead_opts: None`.
1183    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1184    pub enum CmdTail {
1185        /// `;` — no arguments.
1186        Semi(EndActiveTok),
1187        /// The argument chain, optionally prefixed by a leading `?(l = e, …)`
1188        /// bundle on the first argument.
1189        Args {
1190            lead_opts: Option<OptArgsV1>,
1191            args: super::ExprErasedV1,
1192            semi: Option<EndActiveTok>,
1193        },
1194    }
1195
1196    /// `patas`-analogue: a pattern, plus an optional `as name` binding —
1197    /// identical shape to [`crate::cst::ast::Pattern`] (no 0.1 delta).
1198    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1199    pub struct Pattern {
1200        pub head: PatCons,
1201        pub as_clause: Option<AsClause>,
1202    }
1203
1204    /// The `as name` suffix of a pattern.
1205    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1206    pub struct AsClause {
1207        pub as_kw: KwAs,
1208        pub name: VarTok,
1209    }
1210
1211    /// `pattr`-analogue: a `patbot`, followed by any number of `:: patbot`
1212    /// segments — identical shape to [`crate::cst::ast::PatCons`] (see its
1213    /// doc comment for why this is a flattened `Vec` rather than right
1214    /// recursion; no 0.1 delta).
1215    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1216    pub struct PatCons {
1217        pub head: PatBot,
1218        pub tail: Vec<ConsSeg>,
1219    }
1220
1221    /// One `:: patbot` continuation of a cons pattern.
1222    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1223    pub struct ConsSeg {
1224        pub cons: ConsTok,
1225        pub tail: PatBot,
1226    }
1227
1228    /// `patbot`, plus the constructor-pattern forms `pattr` adds —
1229    /// identical shape to [`crate::cst::ast::PatBot`], except
1230    /// [`PatBot::List`] is now `,`-separated (`parser_v1.mly:990-1015`,
1231    /// comma-sep list/tuple patterns).
1232    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1233    pub enum PatBot {
1234        /// `Ctor patbot` — a constructor applied to one argument pattern.
1235        /// This field is `PatBot`'s own self-loop (the root SCC).
1236        CtorApplied { ctor: CtorTok, arg: Box<PatBot> },
1237        /// A bare (nullary) constructor pattern.
1238        Ctor(CtorTok),
1239        Int(IntTok),
1240        True(KwTrue),
1241        False(KwFalse),
1242        Str(LiteralTok),
1243        Wild(WildcardTok),
1244        Var(VarTok),
1245        /// `()`
1246        Unit { paren: UnitParen },
1247        /// `( pat )` or `( pat, pat, … )` (the latter elaborates to a tuple
1248        /// pattern; already `,`-separated in 0.0.6, unchanged).
1249        Paren {
1250            paren: ParenGroup<()>,
1251            #[group(self.paren)]
1252            inner: Box<PatternParenBody>,
1253        },
1254        /// `[ pat, … ]` (also matches `[]`). **Delta:** `,` separator, not
1255        /// `;`.
1256        List {
1257            plist: ListGroup<()>,
1258            #[group(self.plist)]
1259            items: Vec<PatListItem>,
1260        },
1261    }
1262
1263    /// The parenthesized-pattern group's content: one pattern, plus any
1264    /// `, pat` continuations (present only for a tuple pattern).
1265    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1266    pub struct PatternParenBody {
1267        pub first: super::PatErasedV1,
1268        pub rest: Vec<CommaPattern>,
1269    }
1270
1271    /// A `, pat` continuation inside a parenthesized tuple pattern.
1272    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1273    pub struct CommaPattern {
1274        pub comma: CommaTok,
1275        pub value: super::PatErasedV1,
1276    }
1277
1278    /// One list-pattern element `pat,` (the last `,` is optional). **Delta
1279    /// from [`crate::cst::ast::PatListItem`]:** `,` separator, not `;`.
1280    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1281    pub struct PatListItem {
1282        pub value: super::PatErasedV1,
1283        pub comma: Option<CommaTok>,
1284    }
1285
1286    /// A type-expression grammar (`typ`/`typ_prod`/`typ_app`/`typ_bot`,
1287    /// `parser_v1.mly:685-752`, simplified — same scope as
1288    /// [`crate::cst::ast::TypeExpr`]). Spells products (`length * length`,
1289    /// [`TypeProd`]) and prefix type application (`list int`, [`TypeApp`]) —
1290    /// without them a `type` bind could declare almost nothing — plus the
1291    /// `?(…)` labeled-optional domain prefix
1292    /// ([`TypeExpr::OptRowFun`]), where a
1293    /// row-variable TAIL (`?(… | ?'r) ->`) parses but is rejected at
1294    /// lowering (it needs signature-level row quantification, not yet
1295    /// implemented). Self-recursive only through `Fun`'s/`OptRowFun`'s
1296    /// codomain (right recursion); parenthesized nesting goes through
1297    /// [`super::TyErasedV1`].
1298    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1299    pub enum TypeExpr {
1300        /// `?(l : ty, … [| ?'r]) dom -> cod` (`typ` `:688-693`, `typ_opt_dom`
1301        /// `:753-758`). `?`-headed — neither
1302        /// `Fun`/`Atom` (headed by `TypeProd`) can start with
1303        /// `OptionalTypeTok`, so declared order relative to them is
1304        /// safety-neutral; declared first to mirror the upstream `typ`
1305        /// production order. Lowered (`v1/lower.rs`) to
1306        /// `cst::ast::TypeExpr::OptRowFun`, thence (`typecheck.rs`) to
1307        /// `MonoType::Func(Row::Cons(l1, ty1, … Row::Empty), dom, cod)` — a
1308        /// CLOSED row, matching what `Ast::LambdaOpt` infers,
1309        /// so an explicit `?(l:τ)->` signature unifies against an actual
1310        /// `?(l=x)`-taking function.
1311        OptRowFun {
1312            opt_dom: TypeOptDomV1,
1313            dom: TypeProd,
1314            arrow: ArrowTok,
1315            cod: Box<TypeExpr>,
1316        },
1317        /// `dom -> cod` (right-associative). This field is `TypeExpr`'s own
1318        /// self-loop (the root SCC). `dom` widened from [`TypeAtom`] to
1319        /// [`TypeProd`] so e.g. `'a option -> 'b option` and
1320        /// `'a * 'b -> 'c` both parse at their expected precedence.
1321        Fun {
1322            dom: TypeProd,
1323            arrow: ArrowTok,
1324            cod: Box<TypeExpr>,
1325        },
1326        /// The non-arrow fallthrough — widened from [`TypeAtom`] to
1327        /// [`TypeProd`]: a product/application with no
1328        /// enclosing arrow is still just "the whole type expression minus
1329        /// `->`".
1330        Atom(TypeProd),
1331    }
1332
1333    /// `?(l : ty, … [| ?'r])` — the (possibly row-tailed) labeled-optional
1334    /// domain prefix of a [`TypeExpr::OptRowFun`] (`typ_opt_dom`,
1335    /// `parser_v1.mly:753-758`).
1336    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1337    pub struct TypeOptDomV1 {
1338        pub q: OptionalTypeTok,
1339        pub paren: ParenGroup<()>,
1340        #[group(self.paren)]
1341        pub inner: TypeOptDomInnerV1,
1342    }
1343
1344    /// A [`TypeOptDomV1`]'s group content: one or more `label : typ` entries
1345    /// (nonempty enforced at lowering), then an optional `| ?'r` row-variable
1346    /// tail (`typ_opt_dom` `:756-757`) — parsed, but rejected with a
1347    /// `LowerError` (needs signature-level row quantification, not
1348    /// implemented; contrast [`TypeRecordInnerV1`]'s own
1349    /// `row_tail`, which IS fully supported, since a bare
1350    /// record-typed value has no `quant`-list obligation to satisfy).
1351    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1352    pub struct TypeOptDomInnerV1 {
1353        pub entries: Vec<TypeOptEntryV1>,
1354        pub row_tail: Option<RowTailV1>,
1355    }
1356
1357    /// One `label : typ,` entry of a [`TypeOptDomV1`] (last `,` optional;
1358    /// `typ_opt_dom_entry`, `parser_v1.mly:759-762` — COLON, unlike the
1359    /// value-level `?(l = e)` bundle's `=`).
1360    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1361    pub struct TypeOptEntryV1 {
1362        pub label: VarTok,
1363        pub colon: ColonTok,
1364        pub ty: super::TyErasedV1,
1365        pub comma: Option<CommaTok>,
1366    }
1367
1368    /// `| ?'r` — a row-variable tail (shared by [`TypeOptDomInnerV1`] and
1369    /// [`TypeRecordInnerV1`]; `parser_v1.mly:748-749`/`:756-757`).
1370    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1371    pub struct RowTailV1 {
1372        pub bar: BarTok,
1373        pub var: RowVarTok,
1374    }
1375
1376    /// `typ_prod` (`parser_v1.mly:696-709`): one or more `*`-separated
1377    /// [`TypeApp`]s, flattened to head+`Vec` exactly like
1378    /// [`crate::cst::ast::TypeProd`] (`cst.rs:1284-1295`) — the same
1379    /// deferred-fold technique as `OpChain`/`PatCons`, keeping `TypeExpr` a
1380    /// singleton SCC.
1381    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1382    pub struct TypeProd {
1383        pub first: TypeApp,
1384        pub rest: Vec<StarType>,
1385    }
1386
1387    /// A `* ty` continuation of a [`TypeProd`].
1388    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1389    pub struct StarType {
1390        pub star: ExactTimesTok,
1391        pub ty: TypeApp,
1392    }
1393
1394    /// `typ_app` (`parser_v1.mly:711-739`). **0.1 delta from
1395    /// [`crate::cst::ast::TypeApp`] (`cst.rs:1297-1312`):** application is
1396    /// PREFIX and n-ary (`list int`, `pair int bool`), not 0.0.6's postfix
1397    /// single-argument (`int list`) — the prefix→postfix bridge (with an
1398    /// arity-1 guard: arity ≥ 2 is a `LowerError`, not a parse error) lives
1399    /// in `v1/lower.rs`. `Applied`/`AppliedLong` (needing at least one
1400    /// argument atom) are tried before `Atom` — a bare name has no argument
1401    /// atom to consume and falls through cleanly (a following
1402    /// keyword/`=`/`and`/`->`/`*` never parses as a [`TypeAtom`]).
1403    ///
1404    /// Four further arms are keyword- or token-headed and so
1405    /// disjoint from `Applied`/`Atom`'s `VarTok`-headed shapes (ordering them
1406    /// BEFORE those is cosmetic, not load-bearing):
1407    ///
1408    /// - [`TypeApp::InlineCmdTy`]/[`TypeApp::BlockCmdTy`]/
1409    ///   [`TypeApp::MathCmdTy`]: `inline [τ, …]`/
1410    ///   `block [τ, …]`/`math [τ, …]` command types (`parser.mly:730-735`,
1411    ///   `typ_cmd_arg` `:763-774`; `math […]`: `parser.mly:830-831`),
1412    ///   `KwInline`/`KwBlock`/`KwMath`-headed (all three are V0_1 keywords
1413    ///   already — `val inline`/`val block` binds; `math` since the
1414    ///   math-split). One deliberate superset of upstream remains: each
1415    ///   bracketed slot is a full [`super::TyErasedV1`] (`TypeExpr`), not upstream's
1416    ///   narrower `typ_prod`. The `?(label: τ, …)` optional-labeled-slot
1417    ///   prefix is modeled — see [`TypeCmdArgItemV1::opts`];
1418    ///   `MathCmdTy` reuses `TypeCmdArgItemV1` as-is, so
1419    ///   `math [?(l : τ) …]` sig rows come for free.
1420    /// - [`AppliedLong`](TypeApp::AppliedLong): `M.t τ…` — the `LONG_LOWER`
1421    ///   qualified-head twin of `Applied` (`parser.mly:720-728`,
1422    ///   `LONG_LOWER` `lexer.mll:318`), `VarWithModTok`-headed (lexed by the
1423    ///   program-mode capital-head scan, `lexer.rs:753-777`). Needed to NAME
1424    ///   an abstract type from outside its sealing module — without
1425    ///   it, an opaque `M.t` could never appear in another module's
1426    ///   signature at all.
1427    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1428    pub enum TypeApp {
1429        /// `inline [τ, …]` — see the enum doc comment.
1430        //
1431        // NOTE the group fields are `ilist`/`blist`/`mlist`, not three `list`s:
1432        // syan names a group substruct after (group-field name, ENUM name) with
1433        // no variant component, so same-named groups in one enum collide
1434        // (E0428 + E0119).
1435        InlineCmdTy {
1436            kw: KwInline,
1437            ilist: ListGroup<()>,
1438            #[group(self.ilist)]
1439            args: Vec<TypeCmdArgItemV1>,
1440        },
1441        /// `block [τ, …]` — see the enum doc comment.
1442        BlockCmdTy {
1443            kw: KwBlock,
1444            blist: ListGroup<()>,
1445            #[group(self.blist)]
1446            args: Vec<TypeCmdArgItemV1>,
1447        },
1448        /// `math [τ, …]` (upstream
1449        /// `parser.mly:830-831` `MATH L_SQUARE optterm_list(COMMA,
1450        /// typ_cmd_arg) R_SQUARE → MMathCommandType(mncmdargtys)` — same
1451        /// `typ_cmd_arg` as inline/block). `KwMath`-headed, so this arm is
1452        /// disjoint from `Applied`/`Atom` and ambiguity-free: a bare `math`
1453        /// can never lex as a `VarTok` under V0_1 at all.
1454        MathCmdTy {
1455            kw: KwMath,
1456            mlist: ListGroup<()>,
1457            #[group(self.mlist)]
1458            args: Vec<TypeCmdArgItemV1>,
1459        },
1460        /// `M.t τ…` — see the enum doc comment. Mirrors
1461        /// `Applied`'s n-ary shape (`v1/lower.rs`'s prefix→postfix bridge
1462        /// rejects arity ≥ 2 identically for both).
1463        AppliedLong {
1464            ctor: VarWithModTok,
1465            first: TypeAtom,
1466            rest: Vec<TypeAtom>,
1467        },
1468        Applied {
1469            ctor: VarTok,
1470            first: TypeAtom,
1471            rest: Vec<TypeAtom>,
1472        },
1473        Atom(TypeAtom),
1474    }
1475
1476    /// One `[…]`-bracketed command-type argument slot: an optional
1477    /// `?(l : τ, …)` labeled-optional bundle PREFIX (upstream
1478    /// `typ_cmd_arg : option(typ_opt_dom) typ_prod`,
1479    /// `parser.mly:753-773`), then the mandatory `τ,` (`,`-separated, last
1480    /// `,` optional — the [`ListItem`] pattern). A full [`super::TyErasedV1`] per
1481    /// slot (permissive superset of upstream's narrower `typ_prod`). `opts`
1482    /// is `Option`-tried first: a non-`?`-headed slot fails the `?` head with
1483    /// no token stolen, so a plain slot parses `opts: None`.
1484    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1485    pub struct TypeCmdArgItemV1 {
1486        pub opts: Option<TypeCmdOptDomV1>,
1487        pub ty: super::TyErasedV1,
1488        pub comma: Option<CommaTok>,
1489    }
1490
1491    /// `?(l : τ, …)` — a CLOSED command-type optional bundle (upstream
1492    /// `typ_opt_dom`, `parser.mly:755-761`,
1493    /// minus the `| ?'r` row-variable tail: command optional-argument types
1494    /// are closed maps, never rows — upstream itself silently DISCARDS a
1495    /// written row variable here, `parser.mly:859-869`'s literal `TODO
1496    /// (error)` — so this port doesn't model one either; a stray `?'r` inside
1497    /// a command-type bracket is a parse error, faithfully matching
1498    /// upstream's "never actually usable" treatment of it). Mirrors
1499    /// [`crate::cst::ast::CstTypeOptDom`]-shaped satellites elsewhere in this file.
1500    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1501    pub struct TypeCmdOptDomV1 {
1502        pub q: OptionalTypeTok,
1503        pub paren: ParenGroup<()>,
1504        #[group(self.paren)]
1505        pub entries: Vec<TypeCmdOptEntryV1>,
1506    }
1507
1508    /// One `label : τ,` entry of a [`TypeCmdOptDomV1`] bundle (the last `,`
1509    /// is optional).
1510    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1511    pub struct TypeCmdOptEntryV1 {
1512        pub label: VarTok,
1513        pub colon: ColonTok,
1514        pub ty: super::TyErasedV1,
1515        pub comma: Option<CommaTok>,
1516    }
1517
1518    /// An atomic type expression. `parser_v1.mly:740-752`'s record forms are
1519    /// fully modeled: both the closed form and the open (row-var-tailed) form
1520    /// share [`TypeAtom::Record`], distinguished by
1521    /// [`TypeRecordInnerV1::row_tail`].
1522    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1523    pub enum TypeAtom {
1524        /// `( ty )`
1525        Paren {
1526            paren: ParenGroup<()>,
1527            #[group(self.paren)]
1528            inner: super::TyErasedV1,
1529        },
1530        /// `(| l1 : ty1, l2 : ty2, … |)` (closed) or `(| l1 : ty1, … | ?'r |)`
1531        /// (open — a row-variable tail)
1532        /// (`typ_bot`'s two `L_RECORD` arms, `parser_v1.mly:746-749`;
1533        /// `typ_record_elem` `:775-777` — COLON fields, unlike record
1534        /// EXPRESSIONS' `l = e`). Lowered (`v1/lower.rs`): the closed form to
1535        /// the existing `cst::ast::TypeAtom::Record` (`cst.rs:1344`) and
1536        /// thence to a closed `MonoType::Record` row (`typecheck.rs:512`);
1537        /// the open form to the additive `cst::ast::TypeAtom::RecordOpen`
1538        /// and thence to an OPEN `MonoType::Record(Row::Var(…))` — a fresh
1539        /// row variable, using the existing generic `Row`/`RowVarRef`/
1540        /// `unify_row` machinery (no new type machinery needed).
1541        Record {
1542            rec: RecordGroup<()>,
1543            #[group(self.rec)]
1544            inner: TypeRecordInnerV1,
1545        },
1546        /// A type variable, e.g. `'a`.
1547        Var(TypeVarTok),
1548        /// `M.t` — a qualified type name (upstream
1549        /// `LONG_LOWER`, `parser.mly:742-743`). `VarWithModTok`-headed,
1550        /// token-disjoint from `Var`/`Name`/`Paren` (`TypeVarTok`/`VarTok`/
1551        /// `LParenTok`) — see [`TypeApp::AppliedLong`]'s doc comment.
1552        LongName(VarWithModTok),
1553        /// A (possibly qualified) type name, e.g. `int`, `string`.
1554        Name(VarTok),
1555    }
1556
1557    /// A [`TypeAtom::Record`]'s group content: the field list, plus an
1558    /// optional `| ?'r` row-variable tail (present ⇒ an OPEN record type;
1559    /// absent ⇒ closed).
1560    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1561    pub struct TypeRecordInnerV1 {
1562        pub fields: Vec<TypeRecordFieldV1>,
1563        pub row_tail: Option<RowTailV1>,
1564    }
1565
1566    /// One `l : ty,` field (last `,` optional — the [`ListItem`] pattern).
1567    /// **Deltas from [`crate::cst::ast::TypeRecordField`] (`cst.rs:1363`):**
1568    /// `,` separator, not `;` (same delta as [`RecordField`]); field type is
1569    /// a full [`super::TyErasedV1`] (upstream `typ_record_elem :776` takes a
1570    /// full `typ`) — erased, not a direct `TypeExpr`, for the same
1571    /// cycle-avoidance reason `cst.rs:1355-1362` documents.
1572    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1573    pub struct TypeRecordFieldV1 {
1574        pub name: VarTok,
1575        pub colon: ColonTok,
1576        pub ty: super::TyErasedV1,
1577        pub comma: Option<CommaTok>,
1578    }
1579
1580    /// `mathtop`-analogue: one math element — identical shape to
1581    /// [`crate::cst::ast::MathElemCst`] (no 0.1 delta; see its doc comment
1582    /// for why this needs no direct self-loop of its own).
1583    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1584    pub struct MathElemCst {
1585        pub base: MathBot,
1586        pub scripts: Vec<MathScript>,
1587    }
1588
1589    /// `mathbot` — identical shape to [`crate::cst::ast::MathBot`] (no 0.1
1590    /// delta; `name` accepts a module-qualified `\Mod.cmd` math command
1591    /// too, `AnyMathCmdTok::Mod` — the lexer already emits
1592    /// `Token::MathCmdWithMod` for one, `lexer.rs`'s `\\` arm in `Mode::
1593    /// Math`, since `${\Math.paren{…}}`-shaped
1594    /// qualified references need it to parse at all).
1595    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1596    pub enum MathBot {
1597        /// `\cmd matharg*`, sigil-only or module-qualified (`\Mod.cmd
1598        /// matharg*`).
1599        Cmd { name: AnyMathCmdTok, args: Vec<MathArg> },
1600        Chars(MathCharTok),
1601        /// `#var` (math mode never trails this with `;`).
1602        Embed(VarInMathTok),
1603        /// A `|` separator marker (flat; elaborator regroups).
1604        Sep(SepTok),
1605        /// `{ … }` — re-enters the math grammar.
1606        Group {
1607            mgrp: MathGroup<()>,
1608            #[group(self.mgrp)]
1609            elems: Vec<super::MathErasedV1>,
1610        },
1611    }
1612
1613    /// One postfix script combo of a [`MathElemCst`] — identical shape to
1614    /// [`crate::cst::ast::MathScript`] (no 0.1 delta).
1615    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1616    pub enum MathScript {
1617        /// `^ group`
1618        Super { hat: SuperscriptTok, group: MathGroupArg },
1619        /// `_ group`
1620        Sub { under: SubscriptTok, group: MathGroupArg },
1621        /// A run of `'` marks — sugar for a superscript of primes
1622        /// characters.
1623        Primes(PrimesTok),
1624    }
1625
1626    /// `mathgroup`-analogue: a script's operand is either a bracketed math
1627    /// group or a bare `mathbot`.
1628    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1629    pub enum MathGroupArg {
1630        Group {
1631            mgrp: MathGroup<()>,
1632            #[group(self.mgrp)]
1633            elems: Vec<super::MathErasedV1>,
1634        },
1635        Bot(Box<MathBot>),
1636    }
1637
1638    /// `matharg`-analogue: one command argument in math mode — identical
1639    /// shape to [`crate::cst::ast::MathArg`] (no 0.1 delta; the escape
1640    /// bodies reuse the now-comma-separated [`ParenBody`]/[`ListItem`]/
1641    /// [`RecordBody`] defined above).
1642    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1643    pub enum MathArg {
1644        /// `{ math }`.
1645        Math {
1646            mgrp: MathGroup<()>,
1647            #[group(self.mgrp)]
1648            elems: Vec<super::MathErasedV1>,
1649        },
1650        /// `!{ inline text }`.
1651        Inline {
1652            igrp: InlineGroup<()>,
1653            #[group(self.igrp)]
1654            elems: Vec<InlineElem>,
1655        },
1656        /// `!<block text>`.
1657        Block {
1658            bgrp: BlockGroup<()>,
1659            #[group(self.bgrp)]
1660            elems: Vec<BlockElem>,
1661        },
1662        /// `!(e)` / `!(e, e, …)`.
1663        ParenEscape {
1664            paren: ParenGroup<()>,
1665            #[group(self.paren)]
1666            inner: Box<ParenBody>,
1667        },
1668        /// `![e, …]`.
1669        ListEscape {
1670            list: ListGroup<()>,
1671            #[group(self.list)]
1672            items: Vec<ListItem>,
1673        },
1674        /// `!(|l = e, …|)`.
1675        RecordEscape {
1676            rec: RecordGroup<()>,
1677            #[group(self.rec)]
1678            body: RecordBody,
1679        },
1680    }
1681
1682    // ---- the module/signature layer --------------------------------------
1683
1684    /// `mod_chain`: `UPPER | LONG_UPPER` (`parser_v1.mly:404-414`). `M.N.P`
1685    /// arrives as ONE [`LongUpperTok`] (the V0_1 lexer branch), so a chain is
1686    /// always exactly one token — which is what makes [`ModExpr::App`]'s two-
1687    /// chain juxtaposition (`F X`, `F.G X.Y`) unambiguous at the token level.
1688    /// Token-disjoint arms; order is cosmetic.
1689    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1690    pub enum ModChainV1 {
1691        Long(LongUpperTok),
1692        Single(CtorTok),
1693    }
1694
1695    /// `modexpr` (`parser_v1.mly:380-403`). SELF-LOOP ROOT: `Functor.body:
1696    /// Box<ModExpr>` (`:381-382`). Variant order is parse priority:
1697    /// `Functor` (`fun`-headed) and `Struct` (`struct`-headed) are
1698    /// keyword-disjoint from everything; `Coerce` (`UPPER :>`) must precede
1699    /// `App`/`Var` so the `:>` suffix is claimed before a bare chain matches;
1700    /// `App` (two chains, `modexpr_app` `:388-394`) precedes `Var` (one
1701    /// chain, `modexpr_bot` `:398-400`) for longest-match. Struct bodies go
1702    /// through [`super::StructBindV1`] (the struct-body connector, erased), so
1703    /// `ModExpr` never statically references [`super::Bind`] — see the
1704    /// module doc comment's SCC story.
1705    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1706    pub enum ModExpr {
1707        /// `FUN ( UPPER : sigexpr ) ARROW modexpr` (`parser_v1.mly:381-382`).
1708        Functor {
1709            fun_kw: KwFun,
1710            lp: LParenTok,
1711            param: CtorTok,
1712            colon: ColonTok,
1713            dom: Box<SigExpr>,
1714            rp: RParenTok,
1715            arrow: ArrowTok,
1716            body: Box<ModExpr>,
1717        },
1718        /// `UPPER COERCE sigexpr` (`:383-384`) — coercion applies to a BARE
1719        /// module name only, upstream-faithfully (`A.B :> S` is a parse
1720        /// error there too).
1721        Coerce {
1722            name: CtorTok,
1723            coerce: CoerceTok,
1724            sig_: Box<SigExpr>,
1725        },
1726        /// `mod_chain mod_chain` — functor application (`:389-394`).
1727        App { func: ModChainV1, arg: ModChainV1 },
1728        /// `mod_chain` — a (possibly long) module path (`:399-400`).
1729        Var(ModChainV1),
1730        /// `STRUCT list(bind) END` (`:401-402`) — the only form `v1/lower.rs`
1731        /// gives real semantics to; reuses the struct-body connector.
1732        Struct {
1733            struct_kw: KwStruct,
1734            binds: Vec<super::StructBindV1>,
1735            end_kw: KwEnd,
1736        },
1737    }
1738
1739    /// `sigexpr` (`parser_v1.mly:558-573`). SELF-LOOP ROOT: `Functor.dom`/
1740    /// `Functor.cod: Box<SigExpr>` (`:570-571`).
1741    ///
1742    /// **Left-recursion note (load-bearing).** The naive sketch would write
1743    /// `With { base: Box<SigExpr>, … }` — as a syan2 ordered-choice
1744    /// production that is LEFT RECURSION (`SigExpr` would begin by parsing
1745    /// `SigExpr`; syan2 gives no diagnostic, it just recurses/fails at parse
1746    /// time — a known consumer hazard). Upstream is *not* left-recursive:
1747    /// the `with` base is `sigexpr_bot` (`:559,564`) and `with` cannot chain
1748    /// (the result of a `with` is never itself a valid `with` base). So the
1749    /// faithful encoding is bot + one optional-shaped suffix arm, tried
1750    /// before the bare-bot fallthrough: `S with type t = int with type u =
1751    /// bool` is a parse error here exactly as upstream (pinned in tests).
1752    /// NO arm of this enum may ever begin with `Box<SigExpr>`/`SigExpr` as
1753    /// its first field — reviewer checklist item.
1754    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1755    pub enum SigExpr {
1756        /// `( UPPER : sigexpr ) ARROW sigexpr` (`:570-571`) — the functor
1757        /// signature. `(`-headed; no [`SigBotV1`] starts with `(`, so this
1758        /// is token-disjoint from the other arms.
1759        Functor {
1760            lp: LParenTok,
1761            param: CtorTok,
1762            colon: ColonTok,
1763            dom: Box<SigExpr>,
1764            rp: RParenTok,
1765            arrow: ArrowTok,
1766            cod: Box<SigExpr>,
1767        },
1768        /// `sigexpr_bot WITH TYPE bind_type` (`:559-563`) /
1769        /// `sigexpr_bot WITH mod_chain TYPE bind_type` (`:564-569`). The
1770        /// `Option<ModChainV1>` is greedy-then-backtrack: on `with type` the
1771        /// chain fails (`type` is a keyword token, not `UPPER`/`LONG_UPPER`)
1772        /// and collapses to `None`. `binds` goes through
1773        /// [`super::TypeBindsErasedV1`].
1774        WithType {
1775            base: SigBotV1,
1776            with_kw: KwWith,
1777            path: Option<ModChainV1>,
1778            type_kw: KwType,
1779            binds: super::TypeBindsErasedV1,
1780        },
1781        /// A bare `sigexpr_bot` (`:572-573`). Must come after [`SigExpr::WithType`]
1782        /// (maximal munch of the `with` suffix).
1783        Bot(SigBotV1),
1784    }
1785
1786    /// `sigexpr_bot` (`parser_v1.mly:575-595`) — a satellite (no self-loop;
1787    /// no edge back to `SigExpr`). Sig bodies go through
1788    /// [`super::StructDeclV1`] (opaque hand-written connector), so
1789    /// `SigBotV1` never statically references [`Decl`].
1790    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1791    pub enum SigBotV1 {
1792        /// `LONG_UPPER` — a signature path `M.N.S` (`:581-590`).
1793        Path(LongUpperTok),
1794        /// `UPPER` — a signature name (`:576-580`).
1795        Var(CtorTok),
1796        /// `SIG list(decl) END` (`:591-595`). `sig` is a version-independent
1797        /// keyword (`lexer.rs`).
1798        Sig {
1799            sig_kw: KwSig,
1800            decls: Vec<super::StructDeclV1>,
1801            end_kw: KwEnd,
1802        },
1803    }
1804
1805    /// `decl` (`parser_v1.mly:597-621`) — one item of a `sig … end` body.
1806    /// NOT a root: no arm contains `Decl`; reached only through
1807    /// [`super::StructDeclV1`], so `SigExpr ↔ Decl` never forms a rootless
1808    /// static sub-cycle (the shape `cst.rs`'s `AppArgErased` doc warns the
1809    /// engine rejects). Its recursion-bearing edges are plain DAG edges INTO
1810    /// roots: `ty: TypeExpr` (the same satellite→root shape as
1811    /// `RecClauseV1.params: Vec<PatBot>`) and `sig_: Box<SigExpr>`.
1812    ///
1813    /// Deferred arms (parse errors): macro decls `val \m : macro-type`
1814    /// (`:608-611`), row quantifiers (`rowquant`, `:631-633` — no
1815    /// `ROWVAR` token for this position yet).
1816    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1817    pub enum Decl {
1818        /// `VAL PERSISTENT? EXACT_TILDE? bound_identifier quant COLON typ`
1819        /// (`:598-603`; `quant`'s tyvar list `:623-630` — `val map 'a 'b :
1820        /// ('a -> 'b) -> …`). The stage prefix is the decl-side twin of
1821        /// [`super::Bind::Value`]'s own `stage` field, with the same
1822        /// ordered-choice argument (see that arm's doc comment).
1823        Val {
1824            kw: KwVal,
1825            stage: Option<super::BindStageV1>,
1826            name: super::BindName,
1827            quant: Vec<TypeVarTok>,
1828            colon: ColonTok,
1829            ty: TypeExpr,
1830        },
1831        /// `VAL BACKSLASH_CMD quant COLON typ` (`:604-605`). Plain
1832        /// [`HorzCmdTok`] — upstream uses the bare token, and program mode
1833        /// already lexes `\cmd`. Naming mirrors
1834        /// [`crate::cst::SigItem::ValHorzCmd`].
1835        ValHorzCmd {
1836            kw: KwVal,
1837            cmd: HorzCmdTok,
1838            quant: Vec<TypeVarTok>,
1839            colon: ColonTok,
1840            ty: TypeExpr,
1841        },
1842        /// `VAL PLUS_CMD quant COLON typ` (`:606-607`).
1843        ValVertCmd {
1844            kw: KwVal,
1845            cmd: VertCmdTok,
1846            quant: Vec<TypeVarTok>,
1847            colon: ColonTok,
1848            ty: TypeExpr,
1849        },
1850        /// `TYPE LOWER CONS kind` — an OPAQUE type (`:612-613`). Tried
1851        /// before the transparent [`Decl::Type`]: the two share the `type
1852        /// name` prefix and are told apart by `::` vs `=`/tyvars
1853        /// (backtracking is two tokens deep, cheap).
1854        TypeOpaque {
1855            kw: KwType,
1856            name: VarTok,
1857            cons: ConsTok,
1858            kind: KindV1,
1859        },
1860        /// `TYPE bind_type` — transparent type(s) (`:614-615`), sharing the
1861        /// grouped chain with [`SigExpr::WithType`].
1862        Type {
1863            kw: KwType,
1864            binds: super::TypeBindsErasedV1,
1865        },
1866        /// `MODULE UPPER COLON sigexpr` (`:616-617`) — note `:` here (a
1867        /// decl constrains), vs `:>` on binds (a bind seals).
1868        Module {
1869            kw: KwModule,
1870            name: CtorTok,
1871            colon: ColonTok,
1872            sig_: Box<SigExpr>,
1873        },
1874        /// `SIGNATURE UPPER EXACT_EQ sigexpr` (`:618-619`).
1875        Signature {
1876            kw: KwSignature,
1877            name: CtorTok,
1878            eq: DefEqTok,
1879            sig_: Box<SigExpr>,
1880        },
1881        /// `INCLUDE sigexpr` (`:620-621`) — a decl-include includes a
1882        /// SIGNATURE (contrast [`super::Bind::Include`], which includes a
1883        /// MODULE).
1884        Include { kw: KwInclude, sig_: Box<SigExpr> },
1885    }
1886
1887    // Ordered-choice safety of `Decl`: all arms are keyword-headed
1888    // (`val`/`type`/`module`/`signature`/`include`); within `val`, the
1889    // second token (`BindName`'s `Var`-or-`LParen` vs `HorzCmdTok` vs
1890    // `VertCmdTok`) is disjoint; within `type`, `TypeOpaque`-before-`Type`
1891    // as documented.
1892
1893    /// `kind` (`parser_v1.mly:672-677`): `kind_base (ARROW kind_base)*`
1894    /// flattened head+`Vec` — the same deferred-fold shape as
1895    /// [`TypeProd`]/[`PatCons`], keeping the type acyclic. `kind_base` is a
1896    /// bare LOWER (`:678-681`, `MKindName`), so the whole kind grammar is
1897    /// token-only. (`kind_row`, `:682-683`, arrives with row quantifiers,
1898    /// not yet implemented.)
1899    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1900    pub struct KindV1 {
1901        pub first: VarTok,
1902        pub rest: Vec<KindArrowV1>,
1903    }
1904
1905    /// An `-> kind_base` continuation of a [`KindV1`].
1906    #[derive(Parse, Unparse, Debug, Clone, PartialEq)]
1907    pub struct KindArrowV1 {
1908        pub arrow: ArrowTok,
1909        pub base: VarTok,
1910    }
1911
1912    // (`Quant` needs no struct: upstream `quant = list(tyquant)
1913    // list(rowquant)` (`:623-625`), and with rowquants deferred it is
1914    // exactly `Vec<TypeVarTok>` — inlined into `Decl::Val*` above.)
1915}
1916
1917/// Lex ([`crate::lexer::lex_with_version`] under [`crate::version::RustyfiVersion::V0_1`])
1918/// and parse a whole 0.1 `.saty`/`.satyh` source file. Mirrors
1919/// [`crate::cst::parse_file`]'s two-step shape exactly, sharing its
1920/// [`crate::cst::ParseFileError`] (no new error type).
1921pub fn parse_file_v1(src: &str) -> Result<FileV1, crate::cst::ParseFileError> {
1922    let atoms = crate::lexer::lex_with_version(src, crate::version::RustyfiVersion::V0_1)
1923        .map_err(crate::cst::ParseFileError::from_lex)?;
1924    let mut stream = crate::stream::AtomStream::new(atoms);
1925    match <FileV1 as Parse<_>>::parse(&mut stream) {
1926        Ok(file) => Ok(file),
1927        // The one shared reducer, not the private copy this used to keep: a
1928        // 0.1 library is ONE top-level `module` binding, so it is the
1929        // generation that most needs the high-water mark. See
1930        // [`crate::parse_error`].
1931        Err(e) => Err(crate::parse_error::locate(src, &stream, &e)),
1932    }
1933}