Skip to main content

elly_core/
parse.rs

1//! Parsing: Muon tree → Elly chunk, resolving names as it goes.
2//!
3//! A program is a single chain (`<expr>`). Chains are split on the first `&`-prefixed
4//! item into an application spine and a trailing abstraction. Comments are dropped.
5//!
6//! The parser emits straight into a [`Builder`](crate::code::Builder): each
7//! method pushes the nodes below its own and returns that node unpushed (see
8//! [`code`](crate::code)). It resolves every name as it reaches it, against
9//! a [`Scope`] that mirrors the environment the evaluator will build, so no
10//! tree is built and no pass runs after the parse. A module is read in two
11//! walks over its chains: the declarations first, which give every member its
12//! index, then the bodies (see `docs/done/2026-10-11_elly-ctx-chunks.md`).
13//!
14//! Patterns are emitted as [`Pat`]s matched directly by the evaluator.
15//! `&p0 &p1 …` runs collect into one multi-parameter lambda, and application
16//! spines and spread calls flatten into one `App` node.
17
18use alloc::vec::Vec;
19
20use muon::{Chain, Group, Item, Seq};
21use num_bigint::BigInt;
22
23use crate::builtins::Builtin;
24use crate::code::{
25    len32, Builder, ChunkId, HomeLeaf, Member, ModId, Node, NodeId, Pat, PatId, Run, Text,
26};
27use crate::module::{ImportSpec, ModuleName};
28use crate::resolve::{Barrier, Ref, Scope};
29use crate::source::{report, ChunkSpan, DocSource, Pos};
30use crate::sym::Sym;
31use crate::Ctx;
32
33/// Copy a source string slice into an owned text leaf.
34fn text(s: &str) -> Text {
35    Text::from(s)
36}
37
38// TODO: use thiserror?
39/// A failure at the syntax or parse stage.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum Error {
42    /// The syntax layer (Muon) rejected the input.
43    Syntax(muon::ParseError),
44    /// The input is a valid Muon tree but not a valid Elly program (this
45    /// subset), with the span of the source the error is about.
46    Parse(ParseError, muon::Span),
47}
48
49impl Error {
50    /// The span of the source the error is about; a syntax error is at an
51    /// offset, so its span is empty.
52    pub fn span(&self) -> muon::Span {
53        match self {
54            Error::Syntax(e) => muon::Span {
55                offset: e.offset as Pos,
56                length: 0,
57            },
58            Error::Parse(_, span) => *span,
59        }
60    }
61
62    /// Reports the error in the document `name`, whose text is `text`, as
63    /// `name:line:column: message` and the line, the span underlined (see
64    /// [`source::report`](crate::source::report)).
65    pub fn report(&self, name: &str, text: &str) -> alloc::string::String {
66        let message = match self {
67            Error::Syntax(e) => alloc::format!("syntax error: {:?}", e.kind),
68            Error::Parse(e, _) => alloc::format!("parse error: {e:?}"),
69        };
70        report(name, text, self.span(), &message)
71    }
72}
73
74// TODO: use thiserror?
75/// A parse failure: the input is a valid Muon tree but not a well-formed Elly
76/// program in this subset.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum ParseError {
79    /// The top-level sequence held more than one chain; top-level sequencing
80    /// is deferred (a program is a single expression).
81    MultipleExpressions,
82    /// A chain reduced to nothing (e.g. only comments).
83    EmptyChain,
84    /// A `&` binder with no body — `&x` alone is ill-formed (yet).
85    AbsWithoutBody,
86    /// A `&` prefix on something that is not a well-formed binder header (see
87    /// `BadPattern` for the pattern content itself).
88    BadBinder,
89    /// A binder appeared where an atomic expression was expected. Not reachable
90    /// via the split logic, kept so parsing never panics.
91    UnexpectedBinder,
92    /// A `.` sigil on something that is not a single name/number segment (e.g.
93    /// `.(…)`, `.&x`). `.foo` / `.0` are symbols; the record sugar `.(…)` and
94    /// other prefixed items are deferred / ill-formed.
95    BadSymbol,
96    /// A bare `.` used as an atom (`f . g`, a lone `.`). At the Muon layer this
97    /// is a `<punct>`; Elly reserves it for a future `.` / `|>` application
98    /// combinator, which is deferred.
99    CombinatorDeferred,
100    /// `_` used as a reference. `_` is the discard pattern (a binder that binds
101    /// nothing), never a name that can be read back.
102    DiscardReference,
103    /// A `&`-binder tried to introduce a name starting with `__`. Such names are
104    /// reserved for builtins / special forms and may be referenced but not bound.
105    ReservedName,
106    /// A `<sym>` that begins like a number but is not a valid integer literal
107    /// (`1a`, `0xZZ`, `1__2`, `0x`). Since a `<name>` may not start with a digit,
108    /// a digit-leading sym must be a well-formed `<int>` or it is an error.
109    MalformedNumber,
110    /// A stray `:` / `=` (or other) `<punct>` item at atom position. Muon parses
111    /// this punctuation, but outside a `let` binding (`=`) or a map entry (`:`)
112    /// it has no atomic reading. (A `#{…}` map literal and a `#[…]` list value are
113    /// their own atoms; the bare `{…}` / `[…]` forms are rejected, not deferred.)
114    PunctAtAtom,
115    /// A map entry (`<braces>` chain) whose key is missing or malformed: no `:`
116    /// after the key, or a key item that is not a bare atom, a `.`-symbol, a `(…)`
117    /// computed key, or a `#[…]` / `#{…}` literal key (`{ : 1 }`, `{ foo }`).
118    MalformedMapKey,
119    /// A `let` not followed by a binder group — `let 1 e`. An *empty* group is not
120    /// an error: `let () e` binds nothing and is `e` (see `Parser::let_block`).
121    LetMissingBinders,
122    /// A `let (…)` with nothing after the binder group; the body is required.
123    LetMissingBody,
124    /// A `recur` not followed by a binder group — `recur 1 e`. As with `let`, an
125    /// empty group is not an error: `recur () e` is `e`.
126    RecurMissingBinders,
127    /// A `recur (…)` with nothing after the binder group; the body is required.
128    RecurMissingBody,
129    /// A `recur` binding whose name is already in scope. The group's bindings are
130    /// simultaneous, so inside it the name would mean the group's own binding and
131    /// never the outer one — the opposite of what the identical `let` line means.
132    /// Detected by resolution (`resolve.rs`); carries the offending name.
133    RecurShadowsOuter(Text),
134    /// A binding inside a `let (…)` group is not `<pattern> "=" <expr>`: missing
135    /// or repeated top-level `=`, an empty pattern, or an empty value.
136    MalformedBinding,
137    /// A keyword (`let`, `with`) used as a reference or a binder. Keywords are
138    /// syntax, not names: they may be neither read nor bound.
139    ReservedKeyword,
140    /// A malformed pattern: an empty pattern, a comma-grouped `(a, b)` used as a
141    /// single pattern, a misplaced `...rest`, or any item with no pattern reading.
142    BadPattern,
143    /// A comparand after `=` / `<` / `>` that is not a single **atom** (a name or
144    /// a literal). A pattern is a closed grammar — `= f x`, `< (f x)`, `= [a]`
145    /// have no reading; write `= x`, `= 5`, or `.foo`.
146    ComparandNotAtom,
147    /// A bare **matching literal** used as an entire `&`-header or `let` binding
148    /// LHS: a number (`&42`), a symbol (`&.foo`), or a string (`&"foo"`).
149    /// Parenthesize it — `&(42)`, `&(.foo)`, `&("foo")`, `let ((42) = v)` — so the
150    /// "match this literal" intent is explicit (a bare literal reads as a value, or
151    /// as an intended binder). A literal *nested* in `[…]` / `{…}` / `(…)` / an
152    /// or-pattern needs no parens.
153    BareLiteralHeader,
154    /// A `<str>` literal with an **unpaired UTF-16 surrogate** escape (`"\uD83D"`,
155    /// a high or low `\uXXXX` not completing a pair). Muon accepts it lexically,
156    /// but UTF-8 cannot represent it, so Elly's decode rejects it at parse.
157    LoneSurrogate,
158    /// A bare top-level `|` in a `let` binding's LHS: `let ((x=.a) | (x=.b) = v)`.
159    /// Wrap the or-pattern — `let (((x=.a) | (x=.b)) = v) e` — so it does not
160    /// visually compete with the binding's own `=`.
161    LetOrUnparenthesized,
162    /// An `as <Type>` whose `<Type>` is not one of the closed kinds
163    /// `Int Sym List Map Fun`.
164    UnknownType,
165    /// An or-pattern `(p | q)` whose arms bind different sets of names.
166    OrBindersMismatch,
167    /// A `|>` pipe combinator with a missing operand — `|> f`, `x |>`, or
168    /// `x |> |> f`. Both sides of `|>` must be non-empty.
169    MalformedPipe,
170    /// A name reference that resolves to no enclosing `&`-binding — a free
171    /// variable. Detected by resolution (`resolve.rs`) while parsing, so it is
172    /// a *static* error: the program is rejected before it runs, rather
173    /// than raising `.unbound_name` at eval. Carries the offending name (spans
174    /// are still a TODO). `__`-names never reach here — they are resolved to
175    /// [`Node::Builtin`] at parse.
176    UnboundName(Text),
177    /// A module binding whose left-hand side is not a single bare
178    /// name: a destructuring pattern, a literal, a discard, or a digit-leading
179    /// token. Module top-level keys are plain names in v0. A `__…` or keyword LHS
180    /// reports [`ParseError::ReservedName`] / [`ParseError::ReservedKeyword`] instead.
181    BadModuleItemName,
182    /// A module defines the same item name twice, or an `import`'s local name is
183    /// also an item name. A name means one thing inside a module, so both are
184    /// rejected here. The `Foo = import "spec"` form is the one place a name is
185    /// both an import and an item: it is a single declaration, and it makes them
186    /// the same thing.
187    DuplicateModuleItem,
188    /// An `import` that is neither `import "<spec>" as <Name>` nor
189    /// `<Name> = import "<spec>"`: a missing `as`, a spec that is not a string
190    /// literal, or trailing items. The spec is a literal in a fixed position —
191    /// which is what makes a module's imports a static, auditable list — so there
192    /// is nothing to compute here.
193    MalformedImport,
194    /// An `import` somewhere other than a module's top level — today, inside a
195    /// `recur` group. An import is a frame slot the const
196    /// stage fills before the module exists, so it can only be written in a
197    /// module's own source. Written anywhere else, `import` is an ordinary keyword
198    /// and reports [`ParseError::ReservedKeyword`].
199    MisplacedImport,
200    /// A `const` declaration that is neither `const <name>`, `const (<name> …)`
201    /// nor `<name> = const`: a declaration that is not a bare name, a group whose
202    /// chains are not bare names, or a **payload** — `const x = 1`, `x = const 1`.
203    /// The payload forms are reserved for const-time expressions and rejected
204    /// until those exist (see `docs/done/2026-08-13_elly-modules-iotas.md`).
205    MalformedConst,
206    /// A `const` somewhere other than a module's top level — today, inside a
207    /// `recur` group. A group is built while a program runs
208    /// and has no instance of its own to mint against, so an iota can only be
209    /// declared in a module's source. Written anywhere else, `const` is an
210    /// ordinary keyword and reports [`ParseError::ReservedKeyword`].
211    MisplacedConst,
212    /// A binder — a pattern binder, a `let` binding, a `recur` binding — taking a
213    /// name the enclosing module declares as an **import**. A declaration's name
214    /// means one thing over the whole module, so it may not be shadowed from
215    /// inside (see `docs/done/2026-08-13_elly-modules-iotas.md`). Carries the name.
216    ShadowsImport(Text),
217    /// A binder taking a name the enclosing module declares as a `const`
218    /// [iota](ParseError::ShadowsImport). Carries the name.
219    ShadowsIota(Text),
220    /// A `local` declaration that is neither `local <name> = <expr>` nor the
221    /// group `local (<name> = <expr> …)`: a left-hand side that is not a bare
222    /// name, a group chain that is not a binding, or a missing body. The
223    /// head-with-arguments form `local f x = <expr>` lands here too — it is a
224    /// template moditem, left open (see `docs/done/2026-08-13_elly-modules-local.md`).
225    MalformedLocal,
226    /// A `local` somewhere other than a module's top level — today, inside a
227    /// `recur` group, where every binding is private
228    /// already, so the keyword would say nothing. Written anywhere else, `local`
229    /// is an ordinary keyword and reports [`ParseError::ReservedKeyword`].
230    MisplacedLocal,
231    /// A binder taking a name the enclosing module declares as a
232    /// [`local`](ParseError::ShadowsImport). Carries the name.
233    ShadowsLocal(Text),
234    /// A binder taking a name the enclosing module — or an enclosing
235    /// `recur` group — declares as an **item**. Carries the
236    /// name. This is the direction opposite to
237    /// [`RecurShadowsOuter`](ParseError::RecurShadowsOuter), which stops a group
238    /// binding from shadowing a name already in scope; together they make a
239    /// declared name unshadowable from either side.
240    ShadowsItem(Text),
241    /// A `__` name the language does not define, in either position it can be
242    /// written: a module top-level left-hand side (`__mian = …`) or a reference
243    /// in an expression (`__mian`). The `__` namespace belongs to the language —
244    /// a source may write the builtins and the **reserved moditems** it defines
245    /// and nothing else — so a misspelling fails here, naming the namespace,
246    /// rather than becoming an item nobody reads or a name nothing binds.
247    /// Carries the name as written.
248    UnknownReserved(Text),
249    /// A module declaring the same reserved moditem twice (two `__main`s). A
250    /// reserved moditem is a single slot, not a table, so there is no second one
251    /// to hold. Carries the name.
252    DuplicateReserved(Text),
253    /// A reserved moditem somewhere other than a module's top level — today,
254    /// inside a `recur` group. A group is an item table,
255    /// not a module source, and nothing would ever read the slot. Written
256    /// anywhere else, `__main` is an ordinary `__` name and reports
257    /// [`UnknownReserved`](ParseError::UnknownReserved).
258    MisplacedReserved,
259    /// A [home-module leaf](crate::HomeLeaf) — `Self`, `#Self(…)`, `x.Self`, or
260    /// the `Self <pat>` pattern — outside a module body. Each reads the module
261    /// its body is written in, and there is none: the term is not a module's, or
262    /// it is a `recur` group in a program that is not a
263    /// module. One test covers both, since a group is not a module either.
264    /// Carries the name — `Self`, the one word every form is spelled with.
265    OutsideModule(Text),
266    /// An `as <Proto>` pattern whose reference is a `__` name that is not a
267    /// **prototype**: a builtin that is no module at all (`as __eq`), or `__Err`,
268    /// which is a namespace of operations that no value answers `__proto` with —
269    /// so the check could never hold. Rejected here rather than compiled into a
270    /// pattern that always refutes. Carries the name.
271    NotAPrototype(Text),
272    /// A [`&`](muon::Item::Prefixed)-headed **run** (`&x.0`, `&(a, b).0`) — a
273    /// binder glued to a following atom with no whitespace. A binder is one
274    /// prefixed atom, so the glued tail has no reading; write it spaced
275    /// (`&x .0`) to apply, or restructure. See `docs/done/2026-09-09_elly-parse-runs.md` §C.
276    BinderRunGlued,
277    /// An `<int>`-then-`.<digits>` run — the float-like run `3.14` (Muon groups
278    /// the two atoms, see `docs/done/2026-09-08_muon-runs.md`). Float literals do
279    /// not exist yet; this holds the notation open for them (a real float is a
280    /// later `Num` extension) while giving a clear error now instead of the
281    /// runtime `.not_applicable` a spaced `3 .14` projection raises.
282    FloatLiteralUnsupported,
283    /// A [`#`](muon::Item::Prefixed)-prefixed form other than the three that
284    /// read: `#[…]` (a list), `#{…}` (a map), and `#Self(…)` / `#Self …`
285    /// (construction). The `#` sigil marks a **literal notation**, and the
286    /// remaining shapes — `#<sym>`, `#<str>`, `#(…)`, `#.name` — are reserved
287    /// for future literal kinds with no reading yet. A bare `#Self` lands here
288    /// as well: construction is a form, not a value, so it may only head a
289    /// spine (see `Parser::app_spine`). See `docs/todo/elly-syntax-v1.md` §2.
290    ReservedLiteralForm,
291    /// A bare `[…]` where a list literal or list pattern is written. After the
292    /// reshuffle (phase 3), the list literal uses the `#`-prefixed spelling
293    /// exclusively: write `#[…]`. See `docs/todo/elly-syntax-v1.md` § 3–5.
294    BareListLiteral,
295    /// A bare `{…}` carrying a `:`-clause where a map literal or map pattern is
296    /// written. After the reshuffle, the map literal uses the `#`-prefixed
297    /// spelling exclusively: write `#{…}`. A `:`-clause has no reading in a block
298    /// (nothing legal in a block starts `<key> :`), so a brace group with one is
299    /// this error in every position; a brace group *without* a `:`-clause is a
300    /// block (step 6), and the empty `{}` is the unit value.
301    /// See `docs/todo/elly-syntax-v1.md` § 3–5.
302    BareMapLiteral,
303    /// A block `{…}` whose final clause is a binding (`{ …, x = v }`). A block's
304    /// value is its last clause's value and its bindings do not escape, so a
305    /// trailing binding would bind a name nothing can read and leave no value to
306    /// return — as a `let` with no body does. End the block with an expression.
307    /// See `docs/todo/elly-syntax-v1.md` § 5 (review) and step 6.
308    BlockTrailingBinding,
309    /// A `case` with no `{…}` arm block — `case x` or `case` alone, or a trailing
310    /// item that is not a brace group. The block is where the clauses live, so a
311    /// `case` without one has nothing to match against and no reading.
312    CaseMissingArms,
313    /// A `case` subject that is more than one item — `case f x { … }`. The subject
314    /// is exactly one item so the arm block's `{…}` is unambiguous; group a
315    /// compound subject (`case (f x) { … }`) or pipe it in (`f x |> case { … }`).
316    CaseSubjectExtra,
317    /// A `case` arm whose chain is not headed by `&` — a clause that is not a
318    /// binder. Every arm is `& <pattern> … <body>`; a bare expression is not one.
319    ArmNotBinder,
320    /// A `case` arm with a pattern (and any guards) but no body after them —
321    /// `& x` or `& x when (c)` alone. An arm's body is required.
322    ArmMissingBody,
323    /// A `when` guard with no `(…)` condition group — `when` at the end of a
324    /// header, or `when` followed by something other than a parenthesized group.
325    WhenMissingCond,
326}
327
328/// A parse error unwinding, with the span of the source it is about, or
329/// `NONE` until a caller that knows what it was parsing gives one: an error
330/// is placed at the innermost item, chain or declaration that places it.
331#[derive(Debug)]
332struct Failure(ParseError, ChunkSpan);
333
334/// A parser result.
335type Parsed<T> = Result<T, Failure>;
336
337impl From<ParseError> for Failure {
338    fn from(error: ParseError) -> Self {
339        Failure(error, ChunkSpan::NONE)
340    }
341}
342
343impl Failure {
344    /// The failure, placed at `span()` if it has no span yet.
345    fn or_at(self, span: impl FnOnce() -> ChunkSpan) -> Self {
346        match self.1.get() {
347            Some(_) => self,
348            None => Failure(self.0, span()),
349        }
350    }
351
352    /// The error a compile entry point reports, its span in the document
353    /// `src`. An error nothing placed is at the document's start.
354    fn into_error(self, src: Source<'_>) -> Error {
355        let span = self.1.in_doc(src.base).unwrap_or_default();
356        Error::Parse(self.0, span)
357    }
358}
359
360// ===========================================================================
361// entry points
362// ===========================================================================
363
364/// How an expression source resolves its free names.
365pub(crate) enum Root<'p> {
366    /// A free name is [`ParseError::UnboundName`].
367    Closed,
368    /// A free name is bound into the root frame, as if given: an open term.
369    Open,
370    /// The root frame holds `prelude`, and any other free name is unbound.
371    Prelude(&'p [Text]),
372    /// The scope of module `ModId` of a chunk, as its `__main` sees it: its
373    /// imports and frame, then its members. A free name is unbound.
374    Module(ChunkId, ModId),
375}
376
377/// What an expression source holds.
378#[derive(Clone, Copy)]
379pub(crate) enum Body<'p> {
380    /// One expression: a second chain is [`ParseError::MultipleExpressions`],
381    /// which catches a chain split by the one-chain newline rule.
382    Expr,
383    /// The clauses of a block, without its braces: `x = 2, x.add x` is
384    /// `{ x = 2, x.add x }`. The block is the body of a lambda binding
385    /// `binders`, in order — `{ … }` in `&(a, b) { … }` — so the environment
386    /// it is evaluated in binds their values, the last one innermost.
387    Block { binders: &'p [Text] },
388}
389
390impl Ctx {
391    /// Parse expression source `src` into a new chunk named `__eval_N`: a top
392    /// module with only a body.
393    pub(crate) fn compile_expr(
394        &self,
395        src: &str,
396        root: Root<'_>,
397        body: Body<'_>,
398    ) -> Result<ChunkId, Error> {
399        let seq = muon::parse(src).map_err(Error::Syntax)?;
400        let mut scope = match root {
401            Root::Closed => Scope::new(self, Vec::new(), 0, false, Vec::new()),
402            Root::Open => Scope::new(self, Vec::new(), 0, true, Vec::new()),
403            Root::Prelude(prelude) => {
404                let names = prelude.iter().map(|n| self.intern(n)).collect();
405                Scope::new(self, names, 0, false, Vec::new())
406            }
407            Root::Module(chunk, module) => {
408                let code = self.chunk(chunk);
409                let m = code.module(module);
410                let names = |members: &[Member]| members.iter().map(|m| m.name).collect();
411                let (items, rest) = code.members(m).split_at(m.items as usize);
412                let (locals, iotas) = rest.split_at(m.locals as usize);
413                let members = Barrier::Module {
414                    items: names(items),
415                    locals: names(locals),
416                    iotas: names(iotas),
417                };
418                let frame = code.frame_names(m).to_vec();
419                Scope::new(
420                    self,
421                    frame,
422                    m.imports.len as usize,
423                    false,
424                    alloc::vec![members],
425                )
426            }
427        };
428        let mut b = Builder::new();
429        let src = Source {
430            text: src,
431            base: b.add_doc(None, src),
432        };
433        if let Body::Block { binders } = body {
434            for name in binders {
435                let bound = scope.bind(self.intern(name));
436                bound.map_err(|e| Failure(e, ChunkSpan::NONE).into_error(src))?;
437            }
438        }
439        let mut p = Parser::new(self, scope, b, src);
440        let top = p.b.enter_module();
441        let (body, span) = match body {
442            Body::Expr => p.program(&seq),
443            Body::Block { .. } => p.block_program(&seq),
444        }
445        .map_err(|f| f.into_error(src))?;
446        let body = p.b.push(body, span);
447        let mark = p.b.member_scratch.len();
448        p.b.leave_module(top, None, mark, 0, 0, &[], Vec::new(), body);
449        Ok(self.add_built(p.b, None, "__eval_"))
450    }
451
452    /// Compile module source `src` against a frame of ordered names into a
453    /// new chunk named `name`, or `__module_N` if it has none.
454    ///
455    /// References to frame names resolve to de Bruijn locals. Lookup order:
456    /// enclosing binders $\to$ imports $\to$ module members (iotas $\to$ items
457    /// $\to$ locals) $\to$ frame $\to$ builtin aliases. Module imports occupy
458    /// the leading frame slots.
459    /// `doc` is where the source came from, `None` for an anonymous source.
460    pub(crate) fn compile_source(
461        &self,
462        src: &str,
463        frame: &[Text],
464        name: Option<ModuleName>,
465        doc: Option<DocSource>,
466    ) -> Result<ChunkId, Error> {
467        let seq = muon::parse(src).map_err(Error::Syntax)?;
468        let b = self.emit_module(&seq, src, doc, frame, name.clone())?;
469        Ok(self.add_built(b, name, "__module_"))
470    }
471
472    fn emit_module(
473        &self,
474        seq: &Seq<'_>,
475        src: &str,
476        doc: Option<DocSource>,
477        frame: &[Text],
478        name: Option<ModuleName>,
479    ) -> Result<Builder, Error> {
480        let mut b = Builder::new();
481        let source = Source {
482            text: src,
483            base: b.add_doc(doc, src),
484        };
485        let chains = chain_slices(seq);
486        let decls = declarations(&chains, self, source).map_err(|f| f.into_error(source))?;
487        let items = sorted(&decls.items);
488        let locals = sorted(&decls.locals);
489        let iotas = sorted(&decls.iotas);
490        // The imports are the leading frame slots, searched before the
491        // members; the host's frame names follow them.
492        let mut slots: Vec<Sym> = decls.imports.iter().map(|(n, _)| *n).collect();
493        slots.extend(frame.iter().map(|n| self.intern(n)));
494        let members = Barrier::Module {
495            items: items.clone(),
496            locals: locals.clone(),
497            iotas: iotas.clone(),
498        };
499        let scope = Scope::new(
500            self,
501            slots.clone(),
502            decls.imports.len(),
503            false,
504            alloc::vec![members],
505        );
506        let mut p = Parser::new(self, scope, b, source);
507        let top = p.b.enter_module();
508        let (mark, body) = p
509            .members(&decls, &items, &locals, &iotas)
510            .map_err(|f| f.into_error(source))?;
511        let specs = decls.imports.into_iter().map(|(_, spec)| spec).collect();
512        let (n_items, n_locals) = (len32(items.len()), len32(locals.len()));
513        p.b.leave_module(top, name, mark, n_items, n_locals, &slots, specs, body);
514        Ok(p.b)
515    }
516}
517
518/// The text a chunk's document was parsed from, and its first position in
519/// the chunk: what turns the Muon tree's items into chunk spans.
520#[derive(Clone, Copy)]
521struct Source<'s> {
522    text: &'s str,
523    base: Pos,
524}
525
526impl Source<'_> {
527    /// The span of `item`, which was parsed from this source.
528    fn item(self, item: &Item<'_>) -> ChunkSpan {
529        let span = item.span(self.text);
530        ChunkSpan::new(self.base + span.offset, span.length)
531    }
532
533    /// The span from the first of `items` to the last, which were parsed from
534    /// this source in order.
535    fn items(self, items: &[&Item<'_>]) -> ChunkSpan {
536        match items {
537            [] => ChunkSpan::NONE,
538            [item] => self.item(item),
539            [first, .., last] => self.item(first).join(self.item(last)),
540        }
541    }
542
543    /// The span of a bracket group, its brackets included.
544    fn group(self, group: &Group<'_>) -> ChunkSpan {
545        ChunkSpan::new(self.base + group.span.offset, group.span.length)
546    }
547}
548
549/// `names`, sorted by `Sym`: the order of a member index space.
550fn sorted(names: &[Sym]) -> Vec<Sym> {
551    let mut names = names.to_vec();
552    names.sort();
553    names
554}
555
556// ===========================================================================
557// module declarations
558// ===========================================================================
559
560/// One body a module source declares, read in the declaration walk and
561/// emitted in the second.
562enum Decl<'b, 'a> {
563    /// `name = <body>`.
564    Item(Sym, Vec<&'b Item<'a>>),
565    /// `Name = import "…"` or `name = const`: an item that forwards the
566    /// import or the iota of the same name.
567    Forward(Sym),
568    /// `local name = <body>`.
569    Local(Sym, Vec<&'b Item<'a>>),
570    /// `__main = <body>`, the reserved moditem.
571    Main(Vec<&'b Item<'a>>),
572}
573
574/// A module source's left-hand sides, read before any body.
575struct Decls<'b, 'a> {
576    /// What each body is, in source order, with its declaration's span.
577    bodies: Vec<(Decl<'b, 'a>, ChunkSpan)>,
578    /// The span of every member's declaration, sorted by name (see
579    /// [`span`](Self::span)).
580    spans: Vec<(Sym, ChunkSpan)>,
581    /// The item names, in source order.
582    items: Vec<Sym>,
583    /// The `local` names, in source order.
584    locals: Vec<Sym>,
585    /// The names declared by `const`, in source order — the module's iotas.
586    iotas: Vec<Sym>,
587    /// The `import` declarations, in source order, which is frame-slot order.
588    imports: Vec<(Sym, ImportSpec)>,
589    has_main: bool,
590}
591
592impl Decls<'_, '_> {
593    /// The span of member `name`'s declaration: `name = body`, or the name of
594    /// an iota a group declares. An item and an iota of one name are one
595    /// declaration, `name = const`.
596    fn span(&self, name: Sym) -> ChunkSpan {
597        match self.spans.binary_search_by(|(n, _)| n.cmp(&name)) {
598            Ok(i) => self.spans[i].1,
599            Err(_) => ChunkSpan::NONE,
600        }
601    }
602}
603
604/// Read a module source's (or a `recur` group's) declarations: the items,
605/// locals, iotas, imports and `__main`, with their bodies unparsed, rejecting
606/// a name declared twice.
607///
608/// Items are single bare names in v0. An import is both a frame slot and, in
609/// its re-exporting form `Foo = import "spec"`, an item.
610fn declarations<'b, 'a>(
611    chains: &[Vec<&'b Item<'a>>],
612    ctx: &Ctx,
613    src: Source<'_>,
614) -> Parsed<Decls<'b, 'a>> {
615    let mut d = Decls {
616        bodies: Vec::new(),
617        spans: Vec::new(),
618        items: Vec::new(),
619        locals: Vec::new(),
620        iotas: Vec::new(),
621        imports: Vec::new(),
622        has_main: false,
623    };
624    let mut re = Reexports::default();
625    for ci in chains {
626        declaration(ci, ctx, src, &mut d, &mut re).map_err(|f| f.or_at(|| src.items(ci)))?;
627    }
628    // A name declared twice in two kinds is placed at its later declaration
629    // that has a span: a private import records none.
630    let dup = |name: &Sym| {
631        let span = d.spans.iter().rev().find(|(n, _)| n == name);
632        Err(Failure(
633            ParseError::DuplicateModuleItem,
634            span.map_or(ChunkSpan::NONE, |(_, span)| *span),
635        ))
636    };
637    for (name, _) in &d.imports {
638        if d.iotas.contains(name) || !re.imports.contains(name) && d.items.contains(name) {
639            return dup(name);
640        }
641    }
642    for iota in &d.iotas {
643        if !re.iotas.contains(iota) && d.items.contains(iota) {
644            return dup(iota);
645        }
646    }
647    for name in &d.locals {
648        let taken = d.items.contains(name)
649            || d.iotas.contains(name)
650            || d.imports.iter().any(|(n, _)| n == name);
651        if taken {
652            return dup(name);
653        }
654    }
655    // Stable, so that of an item and an iota of one name the first stays.
656    d.spans.sort_by_key(|(name, _)| *name);
657    Ok(d)
658}
659
660/// The imports and iotas a module's items re-export, by name.
661#[derive(Default)]
662struct Reexports {
663    imports: Vec<Sym>,
664    iotas: Vec<Sym>,
665}
666
667/// Read one declaration, the chain `ci`, into `d`.
668fn declaration<'b, 'a>(
669    ci: &[&'b Item<'a>],
670    ctx: &Ctx,
671    src: Source<'_>,
672    d: &mut Decls<'b, 'a>,
673    re: &mut Reexports,
674) -> Parsed<()> {
675    let span = src.items(ci);
676    let split = ci.iter().position(|it| matches!(it, Item::Punct("=")));
677    if split.is_none() && head_keyword(ci[0]) == Some("import") {
678        let (name, spec) = parse_private_import(ci, ctx, src)?;
679        push_import(&mut d.imports, name, spec)?;
680        return Ok(());
681    }
682    if split.is_none() && head_keyword(ci[0]) == Some("const") {
683        for (name, span) in parse_const_decl(ci, ctx, src)? {
684            push_name(&mut d.iotas, name)?;
685            d.spans.push((name, span));
686        }
687        return Ok(());
688    }
689    if split.is_none() && head_keyword(ci[0]) == Some("local") {
690        for (name, body, span) in parse_local_group(ci, ctx, src)? {
691            push_name(&mut d.locals, name)?;
692            d.spans.push((name, span));
693            d.bodies.push((Decl::Local(name, body), span));
694        }
695        return Ok(());
696    }
697    let eq = split.ok_or(ParseError::MalformedBinding)?;
698    if ci[eq + 1..].iter().any(|it| matches!(it, Item::Punct("="))) {
699        return Err(ParseError::MalformedBinding.into());
700    }
701    let (head, tail) = (&ci[..eq], &ci[eq + 1..]);
702    if head.is_empty() || tail.is_empty() {
703        return Err(ParseError::MalformedBinding.into());
704    }
705    if head.len() > 1 && head_keyword(head[0]) == Some("const") {
706        return Err(ParseError::MalformedConst.into());
707    }
708    if head.len() > 1 && head_keyword(head[0]) == Some("local") {
709        let name = plain_name(&head[1..], ParseError::MalformedLocal, ctx, src)?;
710        push_name(&mut d.locals, name)?;
711        d.spans.push((name, span));
712        d.bodies.push((Decl::Local(name, tail.to_vec()), span));
713        return Ok(());
714    }
715    if let [Item::Sym(s)] = head {
716        if let Some(reserved) = reserved_moditem(s) {
717            if d.has_main {
718                let error = ParseError::DuplicateReserved(text(reserved));
719                return Err(Failure(error, src.items(head)));
720            }
721            d.has_main = true;
722            d.bodies.push((Decl::Main(tail.to_vec()), span));
723            return Ok(());
724        }
725        if s.starts_with("__") {
726            let error = ParseError::UnknownReserved(text(s));
727            return Err(Failure(error, src.items(head)));
728        }
729    }
730    let name = plain_name(head, ParseError::BadModuleItemName, ctx, src)?;
731    if d.items.contains(&name) {
732        return Err(ParseError::DuplicateModuleItem.into());
733    }
734    if head_keyword(tail[0]) == Some("import") {
735        let spec = parse_import_spec(tail)?;
736        push_import(&mut d.imports, name, spec)?;
737        re.imports.push(name);
738        d.items.push(name);
739        d.spans.push((name, span));
740        d.bodies.push((Decl::Forward(name), span));
741        return Ok(());
742    }
743    if head_keyword(tail[0]) == Some("const") {
744        if tail.len() != 1 {
745            return Err(ParseError::MalformedConst.into());
746        }
747        push_name(&mut d.iotas, name)?;
748        re.iotas.push(name);
749        d.items.push(name);
750        d.spans.push((name, span));
751        d.bodies.push((Decl::Forward(name), span));
752        return Ok(());
753    }
754    d.items.push(name);
755    d.spans.push((name, span));
756    d.bodies.push((Decl::Item(name, tail.to_vec()), span));
757    Ok(())
758}
759
760/// The reserved moditems the language defines, as the names a module top-level
761/// left-hand side may spell in the `__` namespace. One so far; `__test` and
762/// `__doc` are anticipated, and each will be another slot on a module with a
763/// clause here (see `docs/done/2026-08-14_elly-run.md`).
764///
765/// Answers with the `'static` spelling so the caller reports the *defined* name
766/// rather than echoing the source, and `None` for a name that is not one — which
767/// the caller turns into [`ParseError::UnknownReserved`] rather than an item.
768fn reserved_moditem(name: &str) -> Option<&'static str> {
769    match name {
770        "__main" => Some("__main"),
771        _ => None,
772    }
773}
774
775/// Record one import, rejecting a name a previous import already took.
776fn push_import(imports: &mut Vec<(Sym, ImportSpec)>, name: Sym, spec: ImportSpec) -> Parsed<()> {
777    if imports.iter().any(|(n, _)| *n == name) {
778        return Err(ParseError::DuplicateModuleItem.into());
779    }
780    imports.push((name, spec));
781    Ok(())
782}
783
784/// Record one iota or local, rejecting a name a previous one already took.
785fn push_name(names: &mut Vec<Sym>, name: Sym) -> Parsed<()> {
786    if names.contains(&name) {
787        return Err(ParseError::DuplicateModuleItem.into());
788    }
789    names.push(name);
790    Ok(())
791}
792
793/// Parse `import "<spec>" as <Name>` — the private form, whose whole chain is the
794/// declaration — to its name and spec. The keyword may be a bare sym or a glued
795/// run head (§D); in the run case only the spec glues into the run (`import"spec"`)
796/// while `as <Name>` stays in the chain after it, so the two are concatenated back
797/// into the one item stream the spaced form already is.
798fn parse_private_import<'a>(
799    ci: &[&Item<'a>],
800    ctx: &Ctx,
801    src: Source<'_>,
802) -> Parsed<(Sym, ImportSpec)> {
803    let rest: Vec<&Item<'a>> = match ci[0] {
804        Item::Run(members) => members[1..]
805            .iter()
806            .map(|it| it as &Item<'a>)
807            .chain(ci[1..].iter().copied())
808            .collect(),
809        _ => ci[1..].to_vec(),
810    };
811    match rest.as_slice() {
812        [Item::Str(spec), Item::Sym("as"), rest @ ..] if !rest.is_empty() => {
813            let name = plain_name(rest, ParseError::BadModuleItemName, ctx, src)?;
814            Ok((name, decode_str(spec)?))
815        }
816        _ => Err(ParseError::MalformedImport.into()),
817    }
818}
819
820/// Parse a private `const` declaration — `const <name>`, or the group form
821/// `const (<name> …)` — to the names it declares.
822///
823/// The group is an ordinary `<parens>` wrapping a `<seq>`, so its names may be
824/// newline- or comma-separated and it may carry comments, exactly as a `let`
825/// group may. An **empty group declares nothing**, the same degenerate reading
826/// `let ()` and `recur ()` take.
827fn parse_const_decl<'a>(
828    ci: &[&Item<'a>],
829    ctx: &Ctx,
830    src: Source<'_>,
831) -> Parsed<Vec<(Sym, ChunkSpan)>> {
832    // The keyword may be a bare sym or a glued run head (§D); the declared names
833    // are read from what follows it (the run's members in the run case).
834    let rest: Vec<&Item<'a>> = match ci[0] {
835        Item::Run(members) => members[1..].iter().map(|it| it as &Item<'a>).collect(),
836        _ => ci[1..].to_vec(),
837    };
838    match rest.as_slice() {
839        [Item::Parens(Group { seq, .. }), ..] => {
840            let mut names = Vec::new();
841            for c in chain_slices(seq) {
842                let name = plain_name(&c, ParseError::MalformedConst, ctx, src)?;
843                names.push((name, src.items(&c)));
844            }
845            Ok(names)
846        }
847        rest if !rest.is_empty() => {
848            let name = plain_name(rest, ParseError::MalformedConst, ctx, src)?;
849            Ok(alloc::vec![(name, src.items(rest))])
850        }
851        _ => Err(ParseError::MalformedConst.into()),
852    }
853}
854
855/// Parse group form `local (<name> = <expr> …)` to its names and unparsed bodies.
856///
857/// The group is an ordinary `<parens>` wrapping a `<seq>`. An empty group
858/// declares nothing. The single form `local x = <expr>` is handled separately.
859#[allow(clippy::type_complexity)]
860fn parse_local_group<'b, 'a>(
861    ci: &[&'b Item<'a>],
862    ctx: &Ctx,
863    src: Source<'_>,
864) -> Parsed<Vec<(Sym, Vec<&'b Item<'a>>, ChunkSpan)>> {
865    let group = match ci[0] {
866        Item::Run(members) => members.get(1),
867        _ => ci.get(1).copied(),
868    };
869    let Some(Item::Parens(Group { seq, .. })) = group else {
870        return Err(ParseError::MalformedLocal.into());
871    };
872    let mut bindings = Vec::new();
873    for c in chain_slices(seq) {
874        let malformed = || Failure(ParseError::MalformedLocal, src.items(&c));
875        let eq = c
876            .iter()
877            .position(|it| matches!(it, Item::Punct("=")))
878            .ok_or_else(malformed)?;
879        let (head, tail) = (&c[..eq], &c[eq + 1..]);
880        if head.is_empty() || tail.is_empty() {
881            return Err(malformed());
882        }
883        if tail.iter().any(|it| matches!(it, Item::Punct("="))) {
884            return Err(malformed());
885        }
886        bindings.push((
887            plain_name(head, ParseError::MalformedLocal, ctx, src)?,
888            tail.to_vec(),
889            src.items(&c),
890        ));
891    }
892    Ok(bindings)
893}
894
895/// Parse the `import "<spec>"` RHS of a re-exporting import to its spec.
896/// Handles both spaced and glued spellings.
897fn parse_import_spec(tail: &[&Item<'_>]) -> Parsed<ImportSpec> {
898    let spec = match tail {
899        [_import, Item::Str(spec)] => spec,
900        [Item::Run(members)] => match members.as_slice() {
901            [_import, Item::Str(spec)] => spec,
902            _ => return Err(ParseError::MalformedImport.into()),
903        },
904        _ => return Err(ParseError::MalformedImport.into()),
905    };
906    decode_str(spec)
907}
908
909/// Parse a single plain name for a binding position.
910/// Must be exactly one `<sym>` that is not a keyword, `__` name, discard, or number.
911fn plain_name(items: &[&Item<'_>], bad: ParseError, ctx: &Ctx, src: Source<'_>) -> Parsed<Sym> {
912    plain_name_at(items, bad, ctx).map_err(|f| f.or_at(|| src.items(items)))
913}
914
915/// [`plain_name`], unplaced.
916fn plain_name_at(items: &[&Item<'_>], bad: ParseError, ctx: &Ctx) -> Parsed<Sym> {
917    match items {
918        [Item::Sym(s)] if is_keyword(s) => Err(ParseError::ReservedKeyword.into()),
919        [Item::Sym(s)] if s.starts_with("__") => Err(ParseError::ReservedName.into()),
920        [Item::Sym(s)] if reads_as_number(s) || *s == "_" => Err(bad.into()),
921        [Item::Sym(s)] => Ok(ctx.intern(s)),
922        _ => Err(bad.into()),
923    }
924}
925
926/// Check if a `<sym>` reads as a number (valid integer or digit-leading).
927fn reads_as_number(s: &str) -> bool {
928    parse_int(s).is_some() || s.as_bytes()[0].is_ascii_digit()
929}
930
931// ===========================================================================
932// the parser
933// ===========================================================================
934
935/// Where an expression lands, which decides what an `&` there becomes.
936///
937/// A slot passes through the forms that are their inner expression — a
938/// one-chain `( … )`, `{ e }`, `let () e`, `recur () e`, a pipe's right-hand
939/// side — and every other form parses its parts in slots of their own.
940#[derive(Debug, Clone, Copy, PartialEq, Eq)]
941enum Slot {
942    /// Anywhere else: an `&` captures a fresh frame.
943    Value,
944    /// Applied where it is made — a callee, a builtin's thunk argument: an
945    /// `&` shares the enclosing environment ([`Plan::Chain`](crate::code::Plan)).
946    Applied,
947    /// A list argument a builtin applies elementwise: its elements are
948    /// [`Applied`](Slot::Applied).
949    AppliedElems,
950    /// Directly the body of a lambda whose head is still open: an `&` extends
951    /// the head, so `&a &b body` is one lambda of two parameters.
952    Body,
953}
954
955/// A node and its span.
956type Spanned = (Node, ChunkSpan);
957
958/// A parsed expression, its descendants pushed.
959enum Built {
960    /// Its own node, unpushed, and its span.
961    Node(Node, ChunkSpan),
962    /// An application spine still open on the scratch stack, so a trailing
963    /// argument or a pipe operand can extend it.
964    Spine(Spine),
965}
966
967/// An application spine on the builder's scratch stack: the callee at
968/// `mark`, then the arguments so far.
969struct Spine {
970    mark: usize,
971    /// The callee, if it is a builtin: it decides its arguments' slots.
972    callee: Option<Builtin>,
973    /// The span of the application so far.
974    span: ChunkSpan,
975}
976
977/// A lambda whose head is being parsed: its parameters are
978/// `pat_scratch[pats..]`.
979struct Head {
980    pats: usize,
981    /// For a [`Chain`](crate::code::Plan::Chain) lambda, the enclosing
982    /// activation's mark to unbind its parameters to; `None` for one that
983    /// opened an activation of its own.
984    chain: Option<usize>,
985}
986
987/// A name or literal as written, before it is resolved.
988enum SymRef {
989    Home,
990    Int(BigInt),
991    Builtin(Builtin),
992    Name(Sym),
993}
994
995/// The most parameters one lambda takes: a closure counts its applied
996/// arguments in a `u8`.
997const MAX_HEAD: usize = u8::MAX as usize;
998
999/// Emits one chunk from the Muon tree, resolving as it goes.
1000struct Parser<'c, 's> {
1001    ctx: &'c Ctx,
1002    b: Builder,
1003    scope: Scope<'c>,
1004    /// The lambdas whose heads are open, innermost last.
1005    heads: Vec<Head>,
1006    /// The source being parsed, which gives the spans.
1007    src: Source<'s>,
1008}
1009
1010impl<'c, 's> Parser<'c, 's> {
1011    /// A parser emitting into `b`, which has recorded `src` as a document.
1012    fn new(ctx: &'c Ctx, scope: Scope<'c>, b: Builder, src: Source<'s>) -> Self {
1013        Parser {
1014            ctx,
1015            b,
1016            scope,
1017            heads: Vec::new(),
1018            src,
1019        }
1020    }
1021
1022    /// A program: a single top-level chain, or none — the empty program is
1023    /// `()`, as the empty block is.
1024    fn program(&mut self, seq: &Seq<'_>) -> Parsed<Spanned> {
1025        match chain_slices(seq).as_slice() {
1026            [] => Ok(self.close(Built::Node(Node::Unit, ChunkSpan::NONE))),
1027            [items] => {
1028                let built = self.expr(items, Slot::Value)?;
1029                Ok(self.close(built))
1030            }
1031            [_, second, ..] => Err(Failure(
1032                ParseError::MultipleExpressions,
1033                self.src.items(second),
1034            )),
1035        }
1036    }
1037
1038    /// A source of block clauses, as [`block`](Self::block) reads the inside
1039    /// of a `{…}`.
1040    fn block_program(&mut self, seq: &Seq<'_>) -> Parsed<Spanned> {
1041        if braces_contain_colon(seq) {
1042            return Err(ParseError::BareMapLiteral.into());
1043        }
1044        let clauses = chain_slices(seq);
1045        let span = match (clauses.first(), clauses.last()) {
1046            (Some(first), Some(last)) => self.src.items(first).join(self.src.items(last)),
1047            _ => ChunkSpan::NONE,
1048        };
1049        let built = self.build_block(clauses, Slot::Value, span)?;
1050        Ok(self.close(built))
1051    }
1052
1053    /// Emits the bodies `decls` declares into the member slots of the module
1054    /// being emitted, whose sorted names are `items`, `locals` and `iotas`.
1055    /// Returns the members' scratch mark and the `__main` body, or `NONE`.
1056    ///
1057    /// The bodies are emitted in source order, so errors come in source
1058    /// order, and their members land in sorted order.
1059    fn members(
1060        &mut self,
1061        decls: &Decls<'_, '_>,
1062        items: &[Sym],
1063        locals: &[Sym],
1064        iotas: &[Sym],
1065    ) -> Parsed<(usize, NodeId)> {
1066        let mark = self.b.member_scratch.len();
1067        for &name in items.iter().chain(locals).chain(iotas) {
1068            let member = Member {
1069                name,
1070                node: NodeId::NONE,
1071            };
1072            self.b.member_scratch.push((member, decls.span(name)));
1073        }
1074        let slot = |name: Sym, names: &[Sym]| {
1075            names
1076                .binary_search(&name)
1077                .expect("a declared name has a slot")
1078        };
1079        let mut main = NodeId::NONE;
1080        for (decl, span) in &decls.bodies {
1081            let (index, node) = match decl {
1082                Decl::Item(name, body) => (slot(*name, items), self.body(body)?),
1083                Decl::Forward(name) => {
1084                    let node = self.name_ref(*name).map_err(|f| f.or_at(|| *span))?;
1085                    (slot(*name, items), self.b.push(node, *span))
1086                }
1087                Decl::Local(name, body) => (items.len() + slot(*name, locals), self.body(body)?),
1088                Decl::Main(body) => {
1089                    main = self.body(body)?;
1090                    continue;
1091                }
1092            };
1093            self.b.member_scratch[mark + index].0.node = node;
1094        }
1095        Ok((mark, main))
1096    }
1097
1098    /// A member's body, pushed.
1099    fn body(&mut self, items: &[&Item<'_>]) -> Parsed<NodeId> {
1100        let built = self.expr(items, Slot::Value)?;
1101        Ok(self.child(built))
1102    }
1103
1104    // -----------------------------------------------------------------------
1105    // spines
1106    // -----------------------------------------------------------------------
1107
1108    /// The node of `built` and its span, closing an open spine.
1109    fn close(&mut self, built: Built) -> Spanned {
1110        match built {
1111            Built::Node(node, span) => (node, span),
1112            Built::Spine(spine) => self.close_spine(spine),
1113        }
1114    }
1115
1116    /// `built`, pushed.
1117    fn child(&mut self, built: Built) -> NodeId {
1118        let (node, span) = self.close(built);
1119        self.b.push(node, span)
1120    }
1121
1122    /// An application of the spine's run, or its one element.
1123    fn close_spine(&mut self, spine: Spine) -> Spanned {
1124        let len = self.b.scratch.len() - spine.mark;
1125        if len == 1 {
1126            return self.b.scratch.pop().expect("a spine has a callee");
1127        }
1128        let app = Node::App {
1129            len: len32(len),
1130            args: self.b.push_run(Run::App, spine.mark),
1131        };
1132        (app, spine.span)
1133    }
1134
1135    /// A spine with `callee` and no arguments yet.
1136    fn start(&mut self, callee: Spanned) -> Spine {
1137        let mark = self.b.scratch.len();
1138        self.b.scratch.push(callee);
1139        Spine {
1140            mark,
1141            callee: builtin_of(callee.0),
1142            span: callee.1,
1143        }
1144    }
1145
1146    /// A spine that `built` heads, to apply to one more argument: an open
1147    /// spine extends, and so does a closed application, whose run is copied
1148    /// (`(f x) &y b` is `f` applied to `x` and the lambda).
1149    fn open(&mut self, built: Built) -> Spine {
1150        match built {
1151            Built::Spine(spine) => spine,
1152            Built::Node(Node::App { len, args }, span) => {
1153                let mark = self.b.scratch.len();
1154                for i in 0..len {
1155                    let node = self.b.node(args.nth(i));
1156                    self.b.scratch.push(node);
1157                }
1158                Spine {
1159                    mark,
1160                    callee: builtin_of(self.b.scratch[mark].0),
1161                    span,
1162                }
1163            }
1164            Built::Node(node, span) => self.start((node, span)),
1165        }
1166    }
1167
1168    /// The slot of `spine`'s next argument.
1169    fn arg_slot(&self, spine: &Spine) -> Slot {
1170        let i = self.b.scratch.len() - spine.mark - 1;
1171        match spine.callee {
1172            Some(op) if op.applies_arg(i) => Slot::Applied,
1173            Some(op) if op.applies_elements_of(i) => Slot::AppliedElems,
1174            _ => Slot::Value,
1175        }
1176    }
1177
1178    /// The slot of the next element of a spine being built: the callee of a
1179    /// spine of several elements is applied where it is made.
1180    fn next_slot(&self, spine: &Option<Spine>) -> Slot {
1181        match spine {
1182            None => Slot::Applied,
1183            Some(spine) => self.arg_slot(spine),
1184        }
1185    }
1186
1187    /// Applies `spine` to one more argument. A builtin module applied to the
1188    /// symbol of one of its members folds to the member's own leaf
1189    /// (`__Int .add` is `__Int.add`), so a written member costs no lookup.
1190    fn extend(&mut self, spine: &mut Spine, arg: Spanned) {
1191        spine.span = spine.span.join(arg.1);
1192        if self.b.scratch.len() - spine.mark == 1 {
1193            if let (Some(ns), Node::Symbol(m)) = (spine.callee, arg.0) {
1194                if let Some(op) = ns.member(m) {
1195                    self.b.scratch[spine.mark] = (Node::Builtin(op), spine.span);
1196                    spine.callee = Some(op);
1197                    return;
1198                }
1199            }
1200        }
1201        self.b.scratch.push(arg);
1202    }
1203
1204    /// Adds `arg` to the spine being built, starting it if it is the first.
1205    fn push_arg(&mut self, spine: &mut Option<Spine>, arg: Spanned) {
1206        match spine {
1207            None => *spine = Some(self.start(arg)),
1208            Some(spine) => self.extend(spine, arg),
1209        }
1210    }
1211
1212    // -----------------------------------------------------------------------
1213    // expressions
1214    // -----------------------------------------------------------------------
1215
1216    /// A comment-free slice of items. An error in it that nothing below
1217    /// placed is placed at the slice, as is each of the methods below that
1218    /// parse an item or a chain.
1219    fn expr(&mut self, items: &[&Item<'_>], slot: Slot) -> Parsed<Built> {
1220        let src = self.src;
1221        self.pipeline(items, slot)
1222            .map_err(|f| f.or_at(|| src.items(items)))
1223    }
1224
1225    /// [`expr`](Self::expr), unplaced.
1226    fn pipeline(&mut self, items: &[&Item<'_>], slot: Slot) -> Parsed<Built> {
1227        if items.is_empty() {
1228            return Err(ParseError::EmptyChain.into());
1229        }
1230        // `|>` is the loosest operator: split on the last one to form a
1231        // left-associative pipe chain over segments. The right side is parsed
1232        // first, so the left knows the slot it lands in.
1233        match items.iter().rposition(|it| matches!(it, Item::Punct("|>"))) {
1234            None => self.segment(items, slot),
1235            Some(k) => {
1236                let (left, right) = (&items[..k], &items[k + 1..]);
1237                if left.is_empty() || right.is_empty() {
1238                    let pipe = self.src.item(items[k]);
1239                    return Err(Failure(ParseError::MalformedPipe, pipe));
1240                }
1241                let r = self.segment(right, Slot::Applied)?;
1242                let mut spine = self.open(r);
1243                let slot = self.arg_slot(&spine);
1244                let l = self.expr(left, slot)?;
1245                let l = self.close(l);
1246                self.extend(&mut spine, l);
1247                Ok(Built::Spine(spine))
1248            }
1249        }
1250    }
1251
1252    /// One pipe segment (a `|>`-free slice).
1253    ///
1254    /// This is an application spine whose trailing argument may be a `&`/`let`/`recur`
1255    /// binder form. Split points have lowest precedence within the segment.
1256    fn segment(&mut self, items: &[&Item<'_>], slot: Slot) -> Parsed<Built> {
1257        match items.iter().position(|it| is_split_point(it)) {
1258            None => self.app_spine(items, slot),
1259            Some(0) => match head_keyword(items[0]) {
1260                Some("let") | Some("recur") => self.let_or_recur(items[0], items, slot),
1261                Some("case") => self.case(items, slot),
1262                _ => self.binder(items, slot),
1263            },
1264            Some(k) => {
1265                let f = self.segment(&items[..k], Slot::Applied)?;
1266                let mut spine = self.open(f);
1267                let slot = self.arg_slot(&spine);
1268                let arg = self.segment(&items[k..], slot)?;
1269                let arg = self.close(arg);
1270                self.extend(&mut spine, arg);
1271                Ok(Built::Spine(spine))
1272            }
1273        }
1274    }
1275
1276    /// An application spine, folding left. `(…)` items are spread into
1277    /// multiple arguments. A spine of one element is that element, in the
1278    /// slot the spine is in.
1279    fn app_spine(&mut self, items: &[&Item<'_>], slot: Slot) -> Parsed<Built> {
1280        if let [item] = items {
1281            match item {
1282                Item::Parens(group) => return self.group(group, slot),
1283                Item::Run(_) => {}
1284                _ => return self.aexpr(item, slot),
1285            }
1286        }
1287        let mut spine: Option<Spine> = None;
1288        for (i, it) in items.iter().enumerate() {
1289            match *it {
1290                Item::Run(members) if i == 0 => {
1291                    let src = self.src;
1292                    check_run_head(members).map_err(|f| f.or_at(|| src.item(it)))?;
1293                    let members = if is_self_head(members) {
1294                        let new = self.home(HomeLeaf::New)?;
1295                        let span = self.src.item(&members[0]);
1296                        self.push_arg(&mut spine, (new, span));
1297                        &members[1..]
1298                    } else {
1299                        &members[..]
1300                    };
1301                    for m in members {
1302                        self.expand_arg(m, &mut spine)?;
1303                    }
1304                }
1305                Item::Prefixed { sigil: '#', item }
1306                    if i == 0 && matches!(item.as_ref(), Item::Sym("Self")) =>
1307                {
1308                    let new = self.home(HomeLeaf::New)?;
1309                    let span = self.src.item(it);
1310                    self.push_arg(&mut spine, (new, span));
1311                }
1312                _ => self.expand_arg(it, &mut spine)?,
1313            }
1314        }
1315        let spine = spine.expect("a spine has at least one item");
1316        let len = self.b.scratch.len() - spine.mark;
1317        if len == 1 {
1318            if let Node::Home {
1319                leaf: HomeLeaf::New,
1320                ..
1321            } = self.b.scratch[spine.mark].0
1322            {
1323                let span = self.b.scratch[spine.mark].1;
1324                return Err(Failure(ParseError::ReservedLiteralForm, span));
1325            }
1326            let (node, span) = self.close_spine(spine);
1327            return Ok(Built::Node(node, span));
1328        }
1329        Ok(Built::Spine(spine))
1330    }
1331
1332    /// Expand one chain item into arguments of the spine being built. `(…)`
1333    /// groups spread; `.Self` reads the payload of everything before it;
1334    /// other items are single atoms.
1335    fn expand_arg(&mut self, item: &Item<'_>, spine: &mut Option<Spine>) -> Parsed<()> {
1336        match item {
1337            Item::Parens(group) => {
1338                let chains = chain_slices(&group.seq);
1339                if chains.is_empty() {
1340                    let span = self.src.group(group);
1341                    self.push_arg(spine, (Node::Unit, span));
1342                }
1343                for chain in &chains {
1344                    let slot = self.next_slot(spine);
1345                    let arg = self.expr(chain, slot)?;
1346                    let arg = self.close(arg);
1347                    self.push_arg(spine, arg);
1348                }
1349                // The application covers the group's brackets too.
1350                if let Some(spine) = spine {
1351                    spine.span = spine.span.join(self.src.group(group));
1352                }
1353                Ok(())
1354            }
1355            Item::Prefixed { sigil: '.', item }
1356                if matches!(item.as_ref(), Item::Sym("Self")) && spine.is_some() =>
1357            {
1358                let acc = self.close_spine(spine.take().expect("checked"));
1359                let value = self.home(HomeLeaf::Value)?;
1360                let value_span = self.src.item(item);
1361                let span = acc.1.join(value_span);
1362                let mark = self.b.scratch.len();
1363                self.b.scratch.push((value, value_span));
1364                self.b.scratch.push(acc);
1365                let read = Node::App {
1366                    len: 2,
1367                    args: self.b.push_run(Run::App, mark),
1368                };
1369                *spine = Some(self.start((read, span)));
1370                Ok(())
1371            }
1372            _ => {
1373                let slot = self.next_slot(spine);
1374                let arg = self.aexpr(item, slot)?;
1375                let arg = self.close(arg);
1376                self.push_arg(spine, arg);
1377                Ok(())
1378            }
1379        }
1380    }
1381
1382    /// A `(…)` group as an atom: `()` is unit, `(e)` is `e`, and `(a, b, …)`
1383    /// a spread spine.
1384    fn group(&mut self, group: &Group<'_>, slot: Slot) -> Parsed<Built> {
1385        let chains = chain_slices(&group.seq);
1386        match chains.as_slice() {
1387            [] => Ok(Built::Node(Node::Unit, self.src.group(group))),
1388            [chain] => self.expr(chain, slot),
1389            chains => {
1390                let mut spine = None;
1391                for chain in chains {
1392                    let slot = self.next_slot(&spine);
1393                    let arg = self.expr(chain, slot)?;
1394                    let arg = self.close(arg);
1395                    self.push_arg(&mut spine, arg);
1396                }
1397                let mut spine = spine.expect("a group of several chains");
1398                spine.span = self.src.group(group);
1399                Ok(Built::Spine(spine))
1400            }
1401        }
1402    }
1403
1404    /// A single item as an atomic expression.
1405    fn aexpr(&mut self, item: &Item<'_>, slot: Slot) -> Parsed<Built> {
1406        let src = self.src;
1407        self.atom_expr(item, slot)
1408            .map_err(|f| f.or_at(|| src.item(item)))
1409    }
1410
1411    /// [`aexpr`](Self::aexpr), unplaced.
1412    fn atom_expr(&mut self, item: &Item<'_>, slot: Slot) -> Parsed<Built> {
1413        let node = match item {
1414            Item::Sym(s) => self.sym(s)?,
1415            Item::Prefixed { sigil: '.', item } => self.dot_symbol(item)?,
1416            Item::Brackets(_) => return Err(ParseError::BareListLiteral.into()),
1417            Item::Parens(group) => return self.group(group, slot),
1418            Item::Str(s) => self.b.str(decode_str(s)?),
1419            Item::Braces(group) => return self.block(group, slot),
1420            Item::Punct(".") => return Err(ParseError::CombinatorDeferred.into()),
1421            Item::Punct(_) => return Err(ParseError::PunctAtAtom.into()),
1422            Item::Comm(_) => return Err(ParseError::EmptyChain.into()),
1423            Item::Prefixed { sigil: '#', item } => match item.as_ref() {
1424                Item::Brackets(Group { seq, .. }) => self.list(seq, slot)?,
1425                Item::Braces(Group { seq, .. }) => self.map(seq)?,
1426                _ => return Err(ParseError::ReservedLiteralForm.into()),
1427            },
1428            Item::Prefixed { .. } => return Err(ParseError::UnexpectedBinder.into()),
1429            Item::Run(members) => {
1430                check_run_head(members)?;
1431                let items: Vec<&Item<'_>> = members.iter().collect();
1432                return self.expr(&items, slot);
1433            }
1434        };
1435        Ok(Built::Node(node, self.src.item(item)))
1436    }
1437
1438    /// A `<sym>`: an integer literal or a resolved name.
1439    fn sym(&mut self, s: &str) -> Parsed<Node> {
1440        let r = classify(s, self.ctx)?;
1441        self.resolve_sym(r)
1442    }
1443
1444    fn resolve_sym(&mut self, r: SymRef) -> Parsed<Node> {
1445        match r {
1446            SymRef::Home => self.home(HomeLeaf::Module),
1447            SymRef::Int(n) => Ok(self.b.int(n)),
1448            SymRef::Builtin(op) => Ok(Node::Builtin(op)),
1449            SymRef::Name(name) => self.name_ref(name),
1450        }
1451    }
1452
1453    /// A reference to `name`, resolved.
1454    fn name_ref(&mut self, name: Sym) -> Parsed<Node> {
1455        Ok(match self.scope.reference(name)? {
1456            Ref::Local(index) => Node::Local { name, index },
1457            Ref::Item { index, depth } => Node::ModItem { index, depth, name },
1458            Ref::Builtin(op) => Node::Builtin(op),
1459        })
1460    }
1461
1462    /// A home-module leaf, resolved to the nearest module.
1463    fn home(&mut self, leaf: HomeLeaf) -> Parsed<Node> {
1464        let depth = self
1465            .scope
1466            .home_depth()
1467            .ok_or_else(|| ParseError::OutsideModule(text(leaf.name())))?;
1468        Ok(Node::Home { leaf, depth })
1469    }
1470
1471    /// A `.`-prefixed item as a symbol.
1472    fn dot_symbol(&mut self, item: &Item<'_>) -> Parsed<Node> {
1473        match item {
1474            Item::Sym(s) => Ok(Node::Symbol(self.ctx.intern(s))),
1475            _ => Err(ParseError::BadSymbol.into()),
1476        }
1477    }
1478
1479    /// A `#[…]` list into a runtime list literal of *any* arity: `#[]` (the
1480    /// empty list, not unit), `#[e]` (a genuine 1-list, not collapsed),
1481    /// `#[e0, e1, …]`. Each non-comment chain is one element expression.
1482    fn list(&mut self, seq: &Seq<'_>, slot: Slot) -> Parsed<Node> {
1483        let elem_slot = match slot {
1484            Slot::AppliedElems => Slot::Applied,
1485            _ => Slot::Value,
1486        };
1487        let chains = chain_slices(seq);
1488        let mark = self.b.scratch.len();
1489        for chain in &chains {
1490            let elem = self.expr(chain, elem_slot)?;
1491            let elem = self.close(elem);
1492            self.b.scratch.push(elem);
1493        }
1494        Ok(Node::List {
1495            len: len32(chains.len()),
1496            elems: self.b.push_run(Run::List, mark),
1497        })
1498    }
1499
1500    /// A `#{…}` map literal: each non-comment chain of the `<seq>` is one
1501    /// entry (see [`entry`](Self::entry)). Entry order is source order —
1502    /// evaluation re-sorts by the value order. The run holds the keys, then
1503    /// the values.
1504    fn map(&mut self, seq: &Seq<'_>) -> Parsed<Node> {
1505        let chains = chain_slices(seq);
1506        let n = chains.len();
1507        let mark = self.b.scratch.len();
1508        self.b
1509            .scratch
1510            .resize(mark + 2 * n, (Node::Unit, ChunkSpan::NONE));
1511        for (i, chain) in chains.iter().enumerate() {
1512            let src = self.src;
1513            let (key, value) = self
1514                .entry(chain)
1515                .map_err(|f| f.or_at(|| src.items(chain)))?;
1516            self.b.scratch[mark + i] = key;
1517            self.b.scratch[mark + n + i] = value;
1518        }
1519        Ok(Node::Map {
1520            len: len32(n),
1521            entries: self.b.push_run(Run::Map, mark),
1522        })
1523    }
1524
1525    /// One map entry `<key> ":" <value>`. The `:` is a single `<punct>` item at
1526    /// position 1; the key is the single head item ([`map_key`](Self::map_key))
1527    /// and the value is the rest of the chain parsed as an `<expr>`. An *empty*
1528    /// value tail is sugar for the unit value `()` (so `#{ .foo: }` is
1529    /// `#{ .foo: () }`).
1530    fn entry(&mut self, items: &[&Item<'_>]) -> Parsed<(Spanned, Spanned)> {
1531        if items.len() < 2 || !matches!(items[1], Item::Punct(":")) {
1532            return Err(ParseError::MalformedMapKey.into());
1533        }
1534        let src = self.src;
1535        let key = self
1536            .map_key(items[0])
1537            .map_err(|f| f.or_at(|| src.item(items[0])))?;
1538        let value_items = &items[2..];
1539        let value = if value_items.is_empty() {
1540            // The unit an empty value stands for is written as the `:`.
1541            (Node::Unit, self.src.item(items[1]))
1542        } else {
1543            let value = self.expr(value_items, Slot::Value)?;
1544            self.close(value)
1545        };
1546        Ok((key, value))
1547    }
1548
1549    /// A map-entry key item. A bare *non-digit* atom key is the **symbol** of
1550    /// the same spelling — `one` == `.one`. A **digit-leading** bare key (`0`,
1551    /// `5`) is rejected to avoid the number/symbol confusion: write `.0` for
1552    /// the symbol or `(0)` for the integer. Wrap a key as a `(…)` **computed**
1553    /// key to evaluate it: `(one)` is the *value* of variable `one`; an *empty*
1554    /// `()` is the unit key. The remaining forms are a `.`-prefixed symbol, a
1555    /// string, a path (`Mod.k`), and a `#[…]` / `#{…}` literal key. A bare
1556    /// `[…]` / `{…}` key is refused with its `#`-spelling nudge.
1557    fn map_key(&mut self, item: &Item<'_>) -> Parsed<Spanned> {
1558        match item {
1559            Item::Sym(s) if s.as_bytes()[0].is_ascii_digit() => {
1560                Err(ParseError::MalformedMapKey.into())
1561            }
1562            Item::Sym(s) => Ok((Node::Symbol(self.ctx.intern(s)), self.src.item(item))),
1563            // A bare `{…}` in key position is a block expression at the atom
1564            // layer, which has no reading as a key.
1565            Item::Braces(_) => Err(ParseError::BareMapLiteral.into()),
1566            Item::Prefixed { sigil: '.', .. }
1567            | Item::Prefixed { sigil: '#', .. }
1568            | Item::Brackets(_)
1569            | Item::Parens(_)
1570            | Item::Str(_) => {
1571                let key = self.aexpr(item, Slot::Value)?;
1572                Ok(self.close(key))
1573            }
1574            // A **path** key (`#{ Mod.k: v }`) denotes a concrete value by
1575            // reference, so it is a lookup key alongside the `.sym` /
1576            // bare-sym forms (§E).
1577            Item::Run(members) => {
1578                let head =
1579                    check_path(members, self.ctx).map_err(|_| ParseError::MalformedMapKey)?;
1580                self.path(head, members)
1581            }
1582            _ => Err(ParseError::MalformedMapKey.into()),
1583        }
1584    }
1585
1586    /// A `{…}` brace group as a **block expression** (syntax v1 step 6): a
1587    /// sequence of clauses whose value is the last clause's (see
1588    /// [`build_block`](Self::build_block)). A `:`-clause (a stale bare-map
1589    /// entry) has no reading in a block and is refused with the `#{…}` nudge.
1590    fn block(&mut self, group: &Group<'_>, slot: Slot) -> Parsed<Built> {
1591        if braces_contain_colon(&group.seq) {
1592            return Err(ParseError::BareMapLiteral.into());
1593        }
1594        let span = self.src.group(group);
1595        self.build_block(chain_slices(&group.seq), slot, span)
1596    }
1597
1598    /// A block from its (already joined, comment-free) clause chains — shared
1599    /// by the `{…}` block and by `let (…) e` (its group's binding chains plus
1600    /// its body as the final clause).
1601    ///
1602    /// - The empty block `{}` is the unit value `()`, and `{ e }` is `e` — the
1603    ///   degenerate-case identities.
1604    /// - Each **non-final** clause is a binding (`<pat> = <expr>`, a top-level
1605    ///   `=`, bound over the rest; its value resolves before its pattern binds)
1606    ///   or a bare expression, evaluated for its effect.
1607    /// - The **final** clause is the block's value and must be an expression; a
1608    ///   trailing binding is [`BlockTrailingBinding`](ParseError::BlockTrailingBinding).
1609    ///
1610    /// A block is a scope: its bindings are unbound when it ends. Its span is
1611    /// `span`, the whole form.
1612    fn build_block(
1613        &mut self,
1614        clauses: Vec<Vec<&Item<'_>>>,
1615        slot: Slot,
1616        span: ChunkSpan,
1617    ) -> Parsed<Built> {
1618        let Some((last, leading)) = clauses.split_last() else {
1619            return Ok(Built::Node(Node::Unit, span));
1620        };
1621        if clause_is_binding(last) {
1622            let span = self.src.items(last);
1623            return Err(Failure(ParseError::BlockTrailingBinding, span));
1624        }
1625        if leading.is_empty() {
1626            return self.expr(last, slot);
1627        }
1628        let (mark, pat_mark) = (self.b.scratch.len(), self.b.pat_scratch.len());
1629        let locals = self.scope.mark();
1630        for ci in leading {
1631            let (pat, value) = if clause_is_binding(ci) {
1632                let src = self.src;
1633                let (head, tail) = split_binding(ci).map_err(|f| f.or_at(|| src.items(ci)))?;
1634                let value = self.expr(tail, Slot::Value)?;
1635                let value = self.close(value);
1636                ((self.pattern(head)?, self.src.items(head)), value)
1637            } else {
1638                let value = self.expr(ci, Slot::Value)?;
1639                ((Pat::None, ChunkSpan::NONE), self.close(value))
1640            };
1641            self.b.pat_scratch.push(pat);
1642            self.b.scratch.push(value);
1643        }
1644        let value = self.expr(last, Slot::Value)?;
1645        let value = self.close(value);
1646        self.b.pat_scratch.push((Pat::None, ChunkSpan::NONE));
1647        self.b.scratch.push(value);
1648        self.scope.truncate(locals);
1649        let block = Node::Block {
1650            len: len32(clauses.len()),
1651            binds: self.b.push_pat_run(Run::Block, pat_mark),
1652            exprs: self.b.push_run(Run::Block, mark),
1653        };
1654        Ok(Built::Node(block, span))
1655    }
1656
1657    /// A leading `let`/`recur` form, reading the binder group from a glued
1658    /// run or a bare symbol.
1659    fn let_or_recur(&mut self, head: &Item<'_>, items: &[&Item<'_>], slot: Slot) -> Parsed<Built> {
1660        let is_recur = head_keyword(head) == Some("recur");
1661        // Placed at the keyword and what follows it.
1662        let at = self.src.items(&items[..items.len().min(2)]);
1663        let missing = || {
1664            let error = if is_recur {
1665                ParseError::RecurMissingBinders
1666            } else {
1667                ParseError::LetMissingBinders
1668            };
1669            Failure(error, at)
1670        };
1671        let (group_item, body_items): (&Item<'_>, &[&Item<'_>]) = match head {
1672            Item::Run(members) if members.len() == 2 => (&members[1], &items[1..]),
1673            Item::Run(_) => return Err(missing()),
1674            _ => (*items.get(1).ok_or_else(missing)?, &items[2..]),
1675        };
1676        let group = match group_item {
1677            Item::Parens(Group { seq, .. }) => seq,
1678            _ => return Err(missing()),
1679        };
1680        let span = self.src.items(items);
1681        if is_recur {
1682            self.recur(group, body_items, slot, span)
1683        } else {
1684            self.let_block(group, body_items, slot, span)
1685        }
1686    }
1687
1688    /// `let (b0, b1, …) body`: a block of the group's bindings and the body.
1689    /// An empty group binds nothing (`let () e` is `e`).
1690    fn let_block(
1691        &mut self,
1692        group: &Seq<'_>,
1693        body_items: &[&Item<'_>],
1694        slot: Slot,
1695        span: ChunkSpan,
1696    ) -> Parsed<Built> {
1697        if body_items.is_empty() {
1698            return Err(ParseError::LetMissingBody.into());
1699        }
1700        let mut clauses = chain_slices(group);
1701        for ci in &clauses {
1702            if !clause_is_binding(ci) {
1703                return Err(Failure(ParseError::MalformedBinding, self.src.items(ci)));
1704            }
1705        }
1706        clauses.push(body_items.to_vec());
1707        self.build_block(clauses, slot, span)
1708    }
1709
1710    /// `recur (b0, b1, …) body`: simultaneous bindings, a nested module whose
1711    /// items they are and whose body is `body`. Its names are read before any
1712    /// of its bodies, as a module's are, and sorted to give each its index.
1713    /// An empty group is `body`.
1714    fn recur(
1715        &mut self,
1716        group: &Seq<'_>,
1717        body_items: &[&Item<'_>],
1718        slot: Slot,
1719        span: ChunkSpan,
1720    ) -> Parsed<Built> {
1721        if body_items.is_empty() {
1722            return Err(ParseError::RecurMissingBody.into());
1723        }
1724        let chains = chain_slices(group);
1725        let decls = declarations(&chains, self.ctx, self.src)?;
1726        if !decls.imports.is_empty() {
1727            return Err(ParseError::MisplacedImport.into());
1728        }
1729        if let Some(&iota) = decls.iotas.first() {
1730            return Err(Failure(ParseError::MisplacedConst, decls.span(iota)));
1731        }
1732        if let Some(&local) = decls.locals.first() {
1733            return Err(Failure(ParseError::MisplacedLocal, decls.span(local)));
1734        }
1735        if let Some((_, span)) = decls
1736            .bodies
1737            .iter()
1738            .find(|(d, _)| matches!(d, Decl::Main(_)))
1739        {
1740            return Err(Failure(ParseError::MisplacedReserved, *span));
1741        }
1742        if decls.items.is_empty() {
1743            return self.segment(body_items, slot);
1744        }
1745        let items = sorted(&decls.items);
1746        self.scope.push_group(items.clone()).map_err(|e| {
1747            let at = match &e {
1748                ParseError::RecurShadowsOuter(name) => decls.span(self.ctx.intern(name)),
1749                _ => span,
1750            };
1751            Failure(e, at)
1752        })?;
1753        let id = self.b.enter_module();
1754        let (mark, _) = self.members(&decls, &items, &[], &[])?;
1755        let body = self.segment(body_items, Slot::Value)?;
1756        let body = self.child(body);
1757        self.scope.pop_group();
1758        let n = len32(items.len());
1759        self.b
1760            .leave_module(id, None, mark, n, 0, &[], Vec::new(), body);
1761        Ok(Built::Node(Node::Recur(id), span))
1762    }
1763
1764    /// `case <subject>? { arms }`. The subject resolves first and is placed
1765    /// after the arm bodies. A subjectless case is `&__arg (case __arg { … })`.
1766    fn case(&mut self, items: &[&Item<'_>], slot: Slot) -> Parsed<Built> {
1767        let span = self.src.items(items);
1768        let missing = || Failure(ParseError::CaseMissingArms, span);
1769        let mut rest: Vec<&Item<'_>> = Vec::new();
1770        if let Item::Run(members) = items[0] {
1771            rest.extend(members[1..].iter());
1772        }
1773        rest.extend_from_slice(&items[1..]);
1774        let (last, subject_items) = rest.split_last().ok_or_else(missing)?;
1775        let arms = match last {
1776            Item::Braces(Group { seq, .. }) => chain_slices(seq),
1777            _ => return Err(missing()),
1778        };
1779        if arms.is_empty() {
1780            return Err(missing());
1781        }
1782        match subject_items {
1783            [] => {
1784                let arg = self.ctx.intern("__arg");
1785                // The parameter and the subject it binds are the case's own.
1786                let depth = self.begin_abs(slot);
1787                self.param(span, |p| {
1788                    p.scope.bind(arg)?;
1789                    Ok(Pat::Bind(arg))
1790                })?;
1791                let subject = self.name_ref(arg)?;
1792                let body = self.case_node((subject, span), &arms)?;
1793                self.end_abs(depth, Built::Node(body, span), span)
1794            }
1795            [subject] => {
1796                let subject = self.aexpr(subject, Slot::Value)?;
1797                let subject = self.close(subject);
1798                Ok(Built::Node(self.case_node(subject, &arms)?, span))
1799            }
1800            _ => Err(Failure(
1801                ParseError::CaseSubjectExtra,
1802                self.src.items(subject_items),
1803            )),
1804        }
1805    }
1806
1807    /// The arms of a case over `subject`, each `& <pattern> (when (<cond>))* <body>`.
1808    fn case_node(&mut self, subject: Spanned, arms: &[Vec<&Item<'_>>]) -> Parsed<Node> {
1809        let (mark, pat_mark) = (self.b.scratch.len(), self.b.pat_scratch.len());
1810        for items in arms {
1811            let inner = match items.first() {
1812                Some(Item::Prefixed { sigil: '&', item }) => item.as_ref(),
1813                _ => return Err(Failure(ParseError::ArmNotBinder, self.src.items(items))),
1814            };
1815            if is_bare_literal_header(inner) {
1816                let span = self.src.item(inner);
1817                return Err(Failure(ParseError::BareLiteralHeader, span));
1818            }
1819            let locals = self.scope.mark();
1820            let base = (self.pattern(&[inner])?, self.src.item(inner));
1821            let (pat, rest) = self.guarded(base, &items[1..])?;
1822            if rest.is_empty() {
1823                return Err(Failure(ParseError::ArmMissingBody, self.src.items(items)));
1824            }
1825            let body = self.expr(rest, Slot::Value)?;
1826            let body = self.close(body);
1827            self.scope.truncate(locals);
1828            self.b.pat_scratch.push(pat);
1829            self.b.scratch.push(body);
1830        }
1831        self.b.scratch.push(subject);
1832        Ok(Node::Case {
1833            len: len32(arms.len()),
1834            conds: self.b.push_pat_run(Run::Case, pat_mark),
1835            exprs: self.b.push_run(Run::Case, mark),
1836        })
1837    }
1838
1839    // -----------------------------------------------------------------------
1840    // abstractions
1841    // -----------------------------------------------------------------------
1842
1843    /// `&<pattern> body` — the one binding form every abstraction is built
1844    /// from. A run of `&p0 &p1 …`, or a curried binder group `&(a, b)`,
1845    /// collects into one lambda: the body is parsed in [`Slot::Body`], where
1846    /// an `&` extends the open head. A head that would exceed
1847    /// [`MAX_HEAD`] parameters starts a fresh nested lambda instead.
1848    fn binder(&mut self, items: &[&Item<'_>], slot: Slot) -> Parsed<Built> {
1849        if items.len() == 1 {
1850            return Err(ParseError::AbsWithoutBody.into());
1851        }
1852        let inner = match items[0] {
1853            Item::Prefixed { sigil: '&', item } => item.as_ref(),
1854            _ => return Err(ParseError::UnexpectedBinder.into()),
1855        };
1856        let span = self.src.items(items);
1857        let depth = self.begin_abs(slot);
1858        let rest = if matches!(items.get(1), Some(it) if is_when_kw(it))
1859            && !matches!(inner, Item::Parens(_))
1860        {
1861            if is_bare_literal_header(inner) {
1862                let span = self.src.item(inner);
1863                return Err(Failure(ParseError::BareLiteralHeader, span));
1864            }
1865            let mut rest: &[&Item<'_>] = &[];
1866            let base_span = self.src.item(inner);
1867            self.param_spanned(|p| {
1868                let base = (p.pattern(&[inner])?, base_span);
1869                let (pat, after) = p.guarded(base, &items[1..])?;
1870                rest = after;
1871                Ok(pat)
1872            })?;
1873            if rest.is_empty() {
1874                return Err(ParseError::AbsWithoutBody.into());
1875            }
1876            rest
1877        } else {
1878            match inner {
1879                // A `(…)` inner is a binder group whose commas curry
1880                // (`&(a, b)` is two parameters); `&()` is the nullary marker,
1881                // one parameter that matches unit.
1882                Item::Parens(group) => {
1883                    let params = chain_slices(&group.seq);
1884                    if params.is_empty() {
1885                        self.param(self.src.group(group), |_| Ok(Pat::Unit))?;
1886                    }
1887                    for chain in &params {
1888                        self.param(self.src.items(chain), |p| p.pattern(chain))?;
1889                    }
1890                }
1891                // A bare matching literal (number `&42`, symbol `&.foo`,
1892                // string `&"s"`) as the whole header must be parenthesized:
1893                // `&(42)`, `&(.foo)`, `&("s")` (see `BareLiteralHeader`).
1894                it if is_bare_literal_header(it) => {
1895                    let span = self.src.item(it);
1896                    return Err(Failure(ParseError::BareLiteralHeader, span));
1897                }
1898                other => self.param(self.src.item(other), |p| p.pattern(&[other]))?,
1899            }
1900            &items[1..]
1901        };
1902        let body = self.segment(rest, Slot::Body)?;
1903        self.end_abs(depth, body, span)
1904    }
1905
1906    /// Starts an abstraction in `slot`: opens a lambda, or in
1907    /// [`Slot::Body`] extends the open one. Returns the depth of the open
1908    /// heads to close back to in [`end_abs`](Self::end_abs).
1909    fn begin_abs(&mut self, slot: Slot) -> usize {
1910        let depth = self.heads.len();
1911        if slot != Slot::Body {
1912            self.open_head(slot == Slot::Applied);
1913        }
1914        depth
1915    }
1916
1917    /// Opens a lambda: a [`Chain`](crate::code::Plan::Chain) one binds in
1918    /// the enclosing activation, any other opens an activation of its own.
1919    fn open_head(&mut self, chain: bool) {
1920        let pats = self.b.pat_scratch.len();
1921        let chain = if chain {
1922            Some(self.scope.mark())
1923        } else {
1924            self.scope.push_level();
1925            None
1926        };
1927        self.heads.push(Head { pats, chain });
1928    }
1929
1930    /// Adds the parameter `parse` emits, and binds, to the innermost open
1931    /// head, opening a nested lambda first if the head is full. The
1932    /// parameter's span is `span`.
1933    fn param(
1934        &mut self,
1935        span: ChunkSpan,
1936        parse: impl FnOnce(&mut Self) -> Parsed<Pat>,
1937    ) -> Parsed<()> {
1938        self.param_spanned(|p| Ok((parse(p)?, span)))
1939    }
1940
1941    /// [`param`](Self::param) for a parameter whose span `parse` gives.
1942    fn param_spanned(
1943        &mut self,
1944        parse: impl FnOnce(&mut Self) -> Parsed<(Pat, ChunkSpan)>,
1945    ) -> Parsed<()> {
1946        let head = self.heads.last().expect("a parameter has a head");
1947        if self.b.pat_scratch.len() - head.pats == MAX_HEAD {
1948            self.open_head(false);
1949        }
1950        let pat = parse(self)?;
1951        self.b.pat_scratch.push(pat);
1952        Ok(())
1953    }
1954
1955    /// Closes the heads opened since `depth` around `body`, innermost first;
1956    /// each lambda's span is `span`, the whole abstraction. An abstraction
1957    /// that only extended an open head returns its body.
1958    fn end_abs(&mut self, depth: usize, body: Built, span: ChunkSpan) -> Parsed<Built> {
1959        let mut body = self.close(body);
1960        while self.heads.len() > depth {
1961            let head = self.heads.pop().expect("an open head");
1962            let plan = match head.chain {
1963                Some(mark) => {
1964                    self.scope.truncate(mark);
1965                    None
1966                }
1967                None => Some(self.scope.pop_level()),
1968            };
1969            body = (self.b.lambda(head.pats, body, plan.as_deref(), span), span);
1970        }
1971        Ok(Built::Node(body.0, body.1))
1972    }
1973
1974    /// Folds `when (<cond>)` guards onto `base`, returning the guarded pattern
1975    /// and the items after the guards. Each condition resolves after the
1976    /// pattern it guards binds, and a pattern guard's pattern after its
1977    /// condition.
1978    fn guarded<'i, 'a>(
1979        &mut self,
1980        mut pat: (Pat, ChunkSpan),
1981        mut items: &'i [&'i Item<'a>],
1982    ) -> Parsed<((Pat, ChunkSpan), &'i [&'i Item<'a>])> {
1983        while !items.is_empty() && is_when_kw(items[0]) {
1984            // Placed at the `when` and what follows it.
1985            let missing = Failure(
1986                ParseError::WhenMissingCond,
1987                self.src.items(&items[..items.len().min(2)]),
1988            );
1989            let (group, next): (&Seq<'a>, &[&Item<'a>]) = match items[0] {
1990                Item::Run(members) if members.len() == 2 => match &members[1] {
1991                    Item::Parens(Group { seq, .. }) => (seq, &items[1..]),
1992                    _ => return Err(missing),
1993                },
1994                Item::Run(_) => return Err(missing),
1995                _ => match items.get(1) {
1996                    Some(Item::Parens(Group { seq, .. })) => (seq, &items[2..]),
1997                    _ => return Err(missing),
1998                },
1999            };
2000            let Some(chain) = single_chain(group).filter(|chain| !chain.is_empty()) else {
2001                return Err(missing);
2002            };
2003            let inner = self.b.push_pat(pat.0, pat.1);
2004            let (gpat, cond) = if clause_is_binding(&chain) {
2005                let src = self.src;
2006                let (head, tail) =
2007                    split_binding(&chain).map_err(|f| f.or_at(|| src.items(&chain)))?;
2008                let cond = self.expr(tail, Slot::Value)?;
2009                let cond = self.child(cond);
2010                let gpat = self.pattern(head)?;
2011                (self.b.push_pat(gpat, self.src.items(head)), cond)
2012            } else {
2013                let cond = self.expr(&chain, Slot::Value)?;
2014                (PatId::NONE, self.child(cond))
2015            };
2016            let guard = self.src.items(&items[..items.len() - next.len()]);
2017            pat = (Pat::When { inner, gpat, cond }, pat.1.join(guard));
2018            items = next;
2019        }
2020        Ok((pat, items))
2021    }
2022
2023    // -----------------------------------------------------------------------
2024    // patterns
2025    // -----------------------------------------------------------------------
2026
2027    /// A pattern from a chain of items, binding its names. Splits on `|`
2028    /// (or-pattern), then `=` (equality / at-pattern), otherwise defers to
2029    /// `as` / atom levels.
2030    fn pattern(&mut self, items: &[&Item<'_>]) -> Parsed<Pat> {
2031        let src = self.src;
2032        self.or_pattern(items)
2033            .map_err(|f| f.or_at(|| src.items(items)))
2034    }
2035
2036    /// [`pattern`](Self::pattern), unplaced.
2037    fn or_pattern(&mut self, items: &[&Item<'_>]) -> Parsed<Pat> {
2038        if items.is_empty() {
2039            return Err(ParseError::BadPattern.into());
2040        }
2041        if let Some(idx) = items.iter().position(|it| matches!(it, Item::Punct("|"))) {
2042            let mark = self.scope.mark();
2043            let left = self.pattern(&items[..idx])?;
2044            let left_names: Vec<Sym> = self.scope.bound_since(mark).to_vec();
2045            self.scope.truncate(mark);
2046            let right = self.pattern(&items[idx + 1..])?;
2047            if self.scope.bound_since(mark) != left_names.as_slice() {
2048                return Err(ParseError::OrBindersMismatch.into());
2049            }
2050            let left = self.b.push_pat(left, self.src.items(&items[..idx]));
2051            let right = self.b.push_pat(right, self.src.items(&items[idx + 1..]));
2052            return Ok(Pat::Or(left, right));
2053        }
2054        match items[0] {
2055            Item::Punct("<") => return Ok(Pat::Less(self.comparand(&items[1..])?)),
2056            Item::Punct(">") => return Ok(Pat::Greater(self.comparand(&items[1..])?)),
2057            _ => {}
2058        }
2059        if let Some(idx) = items.iter().position(|it| matches!(it, Item::Punct("="))) {
2060            if idx == 0 {
2061                return Ok(Pat::Equal(self.comparand(&items[1..])?));
2062            }
2063            let name = plain_name(&items[..idx], ParseError::BadPattern, self.ctx, self.src)?;
2064            self.scope.bind(name)?;
2065            let inner = self.pattern(&items[idx + 1..])?;
2066            let span = self.src.items(&items[idx + 1..]);
2067            return Ok(Pat::At(name, self.b.push_pat(inner, span)));
2068        }
2069        self.narrowed(items)
2070    }
2071
2072    /// The RHS of an `=` / `<` / `>` comparand: exactly one atom, pushed.
2073    /// A pattern is a closed grammar; comparands never recurse into `expr`.
2074    fn comparand(&mut self, items: &[&Item<'_>]) -> Parsed<NodeId> {
2075        let node = match items {
2076            [it] => match it {
2077                Item::Sym(s) => self.sym(s)?,
2078                Item::Prefixed { sigil: '.', item } => self.dot_symbol(item)?,
2079                Item::Str(s) => self.b.str(decode_str(s)?),
2080                Item::Run(members) => {
2081                    let head = check_path(members, self.ctx)?;
2082                    self.path(head, members)?.0
2083                }
2084                _ => return Err(Failure(ParseError::ComparandNotAtom, self.src.items(items))),
2085            },
2086            _ => return Err(Failure(ParseError::ComparandNotAtom, self.src.items(items))),
2087        };
2088        Ok(self.b.push(node, self.src.items(items)))
2089    }
2090
2091    /// The narrowing level: `Self <pat>`, `(as <Proto>) <pat>`, `<pat> as <Proto>`, or a bare atom.
2092    /// A prototype resolves before the pattern it narrows binds.
2093    fn narrowed(&mut self, items: &[&Item<'_>]) -> Parsed<Pat> {
2094        if let Item::Sym("Self") = items[0] {
2095            if items.len() < 2 {
2096                return Err(ParseError::BadPattern.into());
2097            }
2098            let depth = self
2099                .scope
2100                .home_depth()
2101                .ok_or_else(|| ParseError::OutsideModule(text("Self")))?;
2102            let inner = self.pattern(&items[1..])?;
2103            return Ok(Pat::Unwrap {
2104                depth,
2105                inner: self.b.push_pat(inner, self.src.items(&items[1..])),
2106            });
2107        }
2108        if let Item::Parens(Group { seq, .. }) = items[0] {
2109            if let Some(chain) = single_chain(seq) {
2110                if !chain.is_empty() && matches!(chain[0], Item::Sym("as")) {
2111                    let proto = self.proto(&chain[1..])?;
2112                    let inner = self.pattern(&items[1..])?;
2113                    return Ok(self.typed(proto, (inner, self.src.items(&items[1..]))));
2114                }
2115            }
2116        }
2117        if let Some(idx) = items.iter().position(|it| matches!(it, Item::Sym("as"))) {
2118            let proto = self.proto(&items[idx + 1..])?;
2119            let inner = self.atom(&items[..idx])?;
2120            return Ok(self.typed(proto, (inner, self.src.items(&items[..idx]))));
2121        }
2122        self.atom(items)
2123    }
2124
2125    /// The prototype of `as <Proto>`: exactly one name or path, a module
2126    /// reference. A reference to a builtin prototype folds to its kind.
2127    fn proto(&mut self, items: &[&Item<'_>]) -> Parsed<Proto> {
2128        let src = self.src;
2129        self.proto_ref(items)
2130            .map_err(|f| f.or_at(|| src.items(items)))
2131    }
2132
2133    /// [`proto`](Self::proto), unplaced.
2134    fn proto_ref(&mut self, items: &[&Item<'_>]) -> Parsed<Proto> {
2135        let node = match items {
2136            [Item::Sym(s)] => match classify(s, self.ctx)? {
2137                SymRef::Int(_) => return Err(ParseError::UnknownType.into()),
2138                r => self.resolve_sym(r)?,
2139            },
2140            [Item::Run(members)] => {
2141                let head = check_path(members, self.ctx)?;
2142                self.path(head, members)?.0
2143            }
2144            _ => return Err(ParseError::UnknownType.into()),
2145        };
2146        match node {
2147            Node::Builtin(op) => match op.proto_kind() {
2148                Some(kind) => Ok(Proto::Kind(kind)),
2149                None => Err(ParseError::NotAPrototype(text(op.name())).into()),
2150            },
2151            node => Ok(Proto::Ref(self.b.push(node, self.src.items(items)))),
2152        }
2153    }
2154
2155    /// `inner as proto`.
2156    fn typed(&mut self, proto: Proto, inner: (Pat, ChunkSpan)) -> Pat {
2157        let inner = self.b.push_pat(inner.0, inner.1);
2158        match proto {
2159            Proto::Kind(kind) => Pat::TypeKind(kind, inner),
2160            Proto::Ref(node) => Pat::TypeRef(node, inner),
2161        }
2162    }
2163
2164    /// A path: a run of a name followed by `.`-prefixed segments, checked by
2165    /// [`check_path`] to have head `head`. Folds left into the head applied
2166    /// to symbol literals, each a binary application, and a builtin module's
2167    /// member to its leaf.
2168    fn path(&mut self, head: SymRef, members: &[Item<'_>]) -> Parsed<Spanned> {
2169        let mut acc = (self.resolve_sym(head)?, self.src.item(&members[0]));
2170        for m in &members[1..] {
2171            let Item::Prefixed { sigil: '.', item } = m else {
2172                unreachable!("checked by check_path")
2173            };
2174            let symbol = self.dot_symbol(item)?;
2175            let Node::Symbol(name) = symbol else {
2176                unreachable!("a dotted segment is a symbol")
2177            };
2178            let span = self.src.item(m);
2179            if let Some(op) = builtin_of(acc.0).and_then(|ns| ns.member(name)) {
2180                acc = (Node::Builtin(op), acc.1.join(span));
2181                continue;
2182            }
2183            let mark = self.b.scratch.len();
2184            let joined = acc.1.join(span);
2185            self.b.scratch.push(acc);
2186            self.b.scratch.push((symbol, span));
2187            let app = Node::App {
2188                len: 2,
2189                args: self.b.push_run(Run::App, mark),
2190            };
2191            acc = (app, joined);
2192        }
2193        Ok(acc)
2194    }
2195
2196    /// An atomic pattern: a single item or a `(…)` grouping of one pattern.
2197    fn atom(&mut self, items: &[&Item<'_>]) -> Parsed<Pat> {
2198        match items {
2199            [it] => self.atom_item(it),
2200            _ => Err(ParseError::BadPattern.into()),
2201        }
2202    }
2203
2204    /// A single atomic-pattern item.
2205    fn atom_item(&mut self, item: &Item<'_>) -> Parsed<Pat> {
2206        let src = self.src;
2207        self.atom_pattern(item)
2208            .map_err(|f| f.or_at(|| src.item(item)))
2209    }
2210
2211    /// [`atom_item`](Self::atom_item), unplaced.
2212    fn atom_pattern(&mut self, item: &Item<'_>) -> Parsed<Pat> {
2213        match item {
2214            Item::Sym("_") => Ok(Pat::Discard),
2215            Item::Sym(s) if is_keyword(s) => Err(ParseError::ReservedKeyword.into()),
2216            Item::Sym(s) if s.starts_with("__") => Err(ParseError::ReservedName.into()),
2217            Item::Sym(s) => match parse_int(s) {
2218                Some(n) => {
2219                    let node = self.b.int(n);
2220                    Ok(Pat::Equal(self.b.push(node, self.src.item(item))))
2221                }
2222                None if s.as_bytes()[0].is_ascii_digit() => Err(ParseError::MalformedNumber.into()),
2223                None => {
2224                    let name = self.ctx.intern(s);
2225                    self.scope.bind(name)?;
2226                    Ok(Pat::Bind(name))
2227                }
2228            },
2229            Item::Prefixed {
2230                sigil: '.',
2231                item: inner,
2232            } => {
2233                let node = self.dot_symbol(inner)?;
2234                Ok(Pat::Equal(self.b.push(node, self.src.item(item))))
2235            }
2236            Item::Str(s) => {
2237                let node = self.b.str(decode_str(s)?);
2238                Ok(Pat::Equal(self.b.push(node, self.src.item(item))))
2239            }
2240            Item::Brackets(_) => Err(ParseError::BareListLiteral.into()),
2241            Item::Parens(Group { seq, .. }) => match single_chain(seq) {
2242                Some(chain) if !chain.is_empty() => self.pattern(&chain),
2243                _ => Err(ParseError::BadPattern.into()),
2244            },
2245            Item::Braces(_) => Err(ParseError::BareMapLiteral.into()),
2246            Item::Prefixed { sigil: '#', item } => match item.as_ref() {
2247                Item::Brackets(Group { seq, .. }) => self.list_pattern(seq),
2248                Item::Braces(Group { seq, .. }) => self.map_pattern(seq),
2249                _ => Err(ParseError::ReservedLiteralForm.into()),
2250            },
2251            _ => Err(ParseError::BadPattern.into()),
2252        }
2253    }
2254
2255    /// A trailing rest (`...name` or `...`) written at `span`, binding its name.
2256    fn rest(&mut self, rest: Option<&str>, span: ChunkSpan) -> Parsed<PatId> {
2257        let pat = match rest {
2258            Some(name) => {
2259                let name = self.ctx.intern(name);
2260                self.scope.bind(name)?;
2261                Pat::Bind(name)
2262            }
2263            None => Pat::Discard,
2264        };
2265        Ok(self.b.push_pat(pat, span))
2266    }
2267
2268    /// A `#[…]` list pattern with an optional trailing rest, which binds
2269    /// before the elements.
2270    fn list_pattern(&mut self, seq: &Seq<'_>) -> Parsed<Pat> {
2271        let chains = chain_slices(seq);
2272        let (elems, rest) = split_rest(&chains)?;
2273        let rest = match rest {
2274            Some(rest) => self.rest(rest, self.rest_span(&chains))?,
2275            None => PatId::NONE,
2276        };
2277        let mark = self.b.pat_scratch.len();
2278        for chain in elems {
2279            let pat = self.pattern(chain)?;
2280            self.b.pat_scratch.push((pat, self.src.items(chain)));
2281        }
2282        Ok(Pat::List {
2283            len: len32(elems.len()),
2284            elems: self.b.push_pat_run(Run::PatList, mark),
2285            rest,
2286        })
2287    }
2288
2289    /// A `#{ k0: p0, … }` map pattern. A key is a lookup — a bare symbol, a
2290    /// path, or a pattern that is an equality — or else a pattern that
2291    /// captures the key. The lookup keys resolve first, then their values
2292    /// bind, then each captured key and its value, then the rest: the order
2293    /// the matcher binds in.
2294    fn map_pattern(&mut self, seq: &Seq<'_>) -> Parsed<Pat> {
2295        let chains = chain_slices(seq);
2296        let (entries, rest) = split_rest(&chains)?;
2297        let mut keys = Vec::with_capacity(entries.len());
2298        for chain in entries {
2299            let malformed = || Failure(ParseError::MalformedMapKey, self.src.items(chain));
2300            let colon = chain
2301                .iter()
2302                .position(|it| matches!(it, Item::Punct(":")))
2303                .ok_or_else(malformed)?;
2304            if colon == 0 || colon + 1 == chain.len() {
2305                return Err(malformed());
2306            }
2307            let key = match &chain[..colon] {
2308                [Item::Sym(s)] if s.as_bytes()[0].is_ascii_digit() => return Err(malformed()),
2309                [Item::Sym(_)] | [Item::Run(_)] => true,
2310                key => is_lookup(key),
2311            };
2312            keys.push((colon, key));
2313        }
2314        let n = entries.len();
2315        let mark = self.b.pat_scratch.len();
2316        self.b
2317            .pat_scratch
2318            .resize(mark + 2 * n, (Pat::None, ChunkSpan::NONE));
2319        for (i, (chain, &(colon, lookup))) in entries.iter().zip(&keys).enumerate() {
2320            if lookup {
2321                let node = match &chain[..colon] {
2322                    [Item::Sym(s)] => Node::Symbol(self.ctx.intern(s)),
2323                    [Item::Run(members)] => {
2324                        let head = check_path(members, self.ctx)?;
2325                        self.path(head, members)?.0
2326                    }
2327                    key => self.lookup_expr(key)?,
2328                };
2329                let span = self.src.items(&chain[..colon]);
2330                self.b.pat_scratch[mark + i] = (Pat::Lookup(self.b.push(node, span)), span);
2331            }
2332        }
2333        for (i, (chain, &(colon, lookup))) in entries.iter().zip(&keys).enumerate() {
2334            if lookup {
2335                let value = self.pattern(&chain[colon + 1..])?;
2336                let span = self.src.items(&chain[colon + 1..]);
2337                self.b.pat_scratch[mark + n + i] = (value, span);
2338            }
2339        }
2340        for (i, (chain, &(colon, lookup))) in entries.iter().zip(&keys).enumerate() {
2341            if !lookup {
2342                let key = self.pattern(&chain[..colon])?;
2343                self.b.pat_scratch[mark + i] = (key, self.src.items(&chain[..colon]));
2344                let value = self.pattern(&chain[colon + 1..])?;
2345                let span = self.src.items(&chain[colon + 1..]);
2346                self.b.pat_scratch[mark + n + i] = (value, span);
2347            }
2348        }
2349        let rest = match rest {
2350            Some(rest) => self.rest(rest, self.rest_span(&chains))?,
2351            None => PatId::NONE,
2352        };
2353        Ok(Pat::Map {
2354            len: len32(n),
2355            entries: self.b.push_pat_run(Run::PatMap, mark),
2356            rest,
2357        })
2358    }
2359
2360    /// The span of a list or map pattern's rest, its last chain.
2361    fn rest_span(&self, chains: &[Vec<&Item<'_>>]) -> ChunkSpan {
2362        chains
2363            .last()
2364            .map_or(ChunkSpan::NONE, |chain| self.src.items(chain))
2365    }
2366
2367    /// The expression of a lookup key, one [`is_lookup`] accepts.
2368    fn lookup_expr(&mut self, items: &[&Item<'_>]) -> Parsed<Node> {
2369        if let Some(Item::Punct("=")) = items.first() {
2370            let node = self.comparand(&items[1..])?;
2371            return Ok(self.b.node(node).0);
2372        }
2373        match items {
2374            [Item::Parens(Group { seq, .. })] => {
2375                let chain = single_chain(seq).expect("checked by is_lookup");
2376                self.lookup_expr(&chain)
2377            }
2378            [Item::Sym(s)] => Ok(self.b.int(parse_int(s).expect("checked by is_lookup"))),
2379            [Item::Prefixed { sigil: '.', item }] => self.dot_symbol(item),
2380            [Item::Str(s)] => Ok(self.b.str(decode_str(s)?)),
2381            _ => unreachable!("checked by is_lookup"),
2382        }
2383    }
2384}
2385
2386/// A prototype in `as <Proto>`.
2387enum Proto {
2388    /// A builtin prototype, compiled to a discriminant test.
2389    Kind(crate::builtins::TyKind),
2390    /// Any other, evaluated at match time and required to be a module.
2391    Ref(NodeId),
2392}
2393
2394/// The builtin `node` is, if it is one.
2395fn builtin_of(node: Node) -> Option<Builtin> {
2396    match node {
2397        Node::Builtin(op) => Some(op),
2398        _ => None,
2399    }
2400}
2401
2402/// Classify a `<sym>` as a home leaf, an integer literal, a builtin or a
2403/// name, rejecting what reads as none of them.
2404fn classify(s: &str, ctx: &Ctx) -> Parsed<SymRef> {
2405    if s == "Self" {
2406        return Ok(SymRef::Home);
2407    }
2408    if is_keyword(s) {
2409        return Err(ParseError::ReservedKeyword.into());
2410    }
2411    if s == "_" {
2412        Err(ParseError::DiscardReference.into())
2413    } else if let Some(n) = parse_int(s) {
2414        Ok(SymRef::Int(n))
2415    } else if s.as_bytes()[0].is_ascii_digit() {
2416        Err(ParseError::MalformedNumber.into())
2417    } else if s.starts_with("__") {
2418        match Builtin::from_name(s) {
2419            Some(op) => Ok(SymRef::Builtin(op)),
2420            None => Err(ParseError::UnknownReserved(text(s)).into()),
2421        }
2422    } else {
2423        Ok(SymRef::Name(ctx.intern(s)))
2424    }
2425}
2426
2427/// Check a path — a run starting with an identifier followed by
2428/// `.`-prefixed segments — and classify its head.
2429fn check_path(members: &[Item<'_>], ctx: &Ctx) -> Parsed<SymRef> {
2430    if members.len() < 2 {
2431        return Err(ParseError::ComparandNotAtom.into());
2432    }
2433    let head = match &members[0] {
2434        Item::Sym(s) => classify(s, ctx)?,
2435        _ => return Err(ParseError::ComparandNotAtom.into()),
2436    };
2437    for m in &members[1..] {
2438        if !matches!(m, Item::Prefixed { sigil: '.', .. }) {
2439            return Err(ParseError::ComparandNotAtom.into());
2440        }
2441    }
2442    for m in &members[1..] {
2443        if let Item::Prefixed { item, .. } = m {
2444            if !matches!(item.as_ref(), Item::Sym(_)) {
2445                return Err(ParseError::BadSymbol.into());
2446            }
2447        }
2448    }
2449    Ok(head)
2450}
2451
2452/// Whether a map pattern's key chain is an equality pattern, and so a lookup
2453/// key: the shape [`Parser::pattern`] reads as [`Pat::Equal`].
2454fn is_lookup(items: &[&Item<'_>]) -> bool {
2455    if items.is_empty() || items.iter().any(|it| matches!(it, Item::Punct("|"))) {
2456        return false;
2457    }
2458    if matches!(items[0], Item::Punct("<") | Item::Punct(">")) {
2459        return false;
2460    }
2461    if let Some(idx) = items.iter().position(|it| matches!(it, Item::Punct("="))) {
2462        return idx == 0;
2463    }
2464    if matches!(items[0], Item::Sym("Self")) || items.iter().any(|it| matches!(it, Item::Sym("as")))
2465    {
2466        return false;
2467    }
2468    match items {
2469        [Item::Sym(s)] => !is_keyword(s) && !s.starts_with("__") && parse_int(s).is_some(),
2470        [Item::Prefixed { sigil: '.', .. }] | [Item::Str(_)] => true,
2471        [Item::Parens(Group { seq, .. })] => match single_chain(seq) {
2472            Some(chain) => is_lookup(&chain) && !starts_with_as(&chain),
2473            None => false,
2474        },
2475        _ => false,
2476    }
2477}
2478
2479/// Whether a chain is the `as <Proto>` of a `(as <Proto>) <pat>` pattern.
2480fn starts_with_as(chain: &[&Item<'_>]) -> bool {
2481    matches!(chain.first(), Some(Item::Sym("as")))
2482}
2483
2484/// Split a list or map pattern's chains into its entries and its trailing
2485/// rest, if any: `Some(Some(name))` for `...name`, `Some(None)` for `...`.
2486/// A rest anywhere but last is [`ParseError::BadPattern`].
2487#[allow(clippy::type_complexity)]
2488fn split_rest<'c, 'b, 'a>(
2489    chains: &'c [Vec<&'b Item<'a>>],
2490) -> Parsed<(&'c [Vec<&'b Item<'a>>], Option<Option<&'a str>>)> {
2491    let n = chains.len();
2492    for (i, chain) in chains.iter().enumerate() {
2493        if as_rest(chain).is_some() && i != n - 1 {
2494            return Err(ParseError::BadPattern.into());
2495        }
2496    }
2497    match chains.split_last() {
2498        Some((last, entries)) => match as_rest(last) {
2499            Some(rest) => Ok((entries, Some(rest))),
2500            None => Ok((chains, None)),
2501        },
2502        None => Ok((chains, None)),
2503    }
2504}
2505
2506/// Recognize a trailing-rest element chain (`...rest` or `...`).
2507fn as_rest<'a>(chain: &[&Item<'a>]) -> Option<Option<&'a str>> {
2508    let [Item::Prefixed {
2509        sigil: '.',
2510        item: a,
2511    }] = chain
2512    else {
2513        return None;
2514    };
2515    let Item::Prefixed {
2516        sigil: '.',
2517        item: b,
2518    } = a.as_ref()
2519    else {
2520        return None;
2521    };
2522    match b.as_ref() {
2523        Item::Prefixed {
2524            sigil: '.',
2525            item: c,
2526        } => match c.as_ref() {
2527            Item::Sym(name) => Some(Some(name)),
2528            _ => None,
2529        },
2530        Item::Punct(".") => Some(None),
2531        _ => None,
2532    }
2533}
2534
2535/// Split a binding chain `<pattern> "=" <expr>` on its one top-level `=`.
2536/// Head and tail must be non-empty.
2537#[allow(clippy::type_complexity)]
2538fn split_binding<'i, 'a>(
2539    items: &'i [&'i Item<'a>],
2540) -> Parsed<(&'i [&'i Item<'a>], &'i [&'i Item<'a>])> {
2541    let mut eq = None;
2542    for (i, it) in items.iter().enumerate() {
2543        if matches!(it, Item::Punct("=")) {
2544            if eq.is_some() {
2545                return Err(ParseError::MalformedBinding.into());
2546            }
2547            eq = Some(i);
2548        }
2549    }
2550    let eq = eq.ok_or(ParseError::MalformedBinding)?;
2551    let (head, tail) = (&items[..eq], &items[eq + 1..]);
2552    if head.is_empty() || tail.is_empty() {
2553        return Err(ParseError::MalformedBinding.into());
2554    }
2555    if head.iter().any(|it| matches!(it, Item::Punct("|"))) {
2556        return Err(ParseError::LetOrUnparenthesized.into());
2557    }
2558    if let [it] = head {
2559        if is_bare_literal_header(it) {
2560            return Err(ParseError::BareLiteralHeader.into());
2561        }
2562    }
2563    Ok((head, tail))
2564}
2565
2566/// Reject `&`-headed runs and float-like runs (`3.14`).
2567fn check_run_head(members: &[Item<'_>]) -> Parsed<()> {
2568    if matches!(&members[0], Item::Prefixed { sigil: '&', .. }) {
2569        return Err(ParseError::BinderRunGlued.into());
2570    }
2571    if let (
2572        Item::Sym(head),
2573        Some(Item::Prefixed {
2574            sigil: '.',
2575            item: seg,
2576        }),
2577    ) = (&members[0], members.get(1))
2578    {
2579        if parse_int(head).is_some() && is_dot_number(seg) {
2580            return Err(ParseError::FloatLiteralUnsupported.into());
2581        }
2582    }
2583    Ok(())
2584}
2585
2586/// Check if a `.`-prefixed segment is a number (float tail).
2587fn is_dot_number(item: &Item<'_>) -> bool {
2588    match item {
2589        Item::Sym(s) => parse_int(s).is_some(),
2590        _ => false,
2591    }
2592}
2593
2594/// Check if a run is the glued `#Self(…)` construction.
2595fn is_self_head(members: &[Item<'_>]) -> bool {
2596    matches!(
2597        members.first(),
2598        Some(Item::Prefixed { sigil: '#', item })
2599            if matches!(item.as_ref(), Item::Sym("Self"))
2600    )
2601}
2602
2603/// Decode a Muon `<str>` literal into owned UTF-8 `Text`, combining surrogate pairs.
2604/// Unpaired surrogates cause [`ParseError::LoneSurrogate`].
2605fn decode_str(raw: &str) -> Parsed<Text> {
2606    let b = raw.as_bytes();
2607    let mut out = alloc::string::String::with_capacity(raw.len());
2608    let mut i = 0;
2609    let mut chunk = 0;
2610    while i < b.len() {
2611        if b[i] != b'\\' {
2612            i += 1;
2613            continue;
2614        }
2615        out.push_str(&raw[chunk..i]);
2616        match b[i + 1] {
2617            b'"' => out.push('"'),
2618            b'\\' => out.push('\\'),
2619            b'/' => out.push('/'),
2620            b'n' => out.push('\n'),
2621            b't' => out.push('\t'),
2622            b'r' => out.push('\r'),
2623            b'b' => out.push('\u{8}'),
2624            b'f' => out.push('\u{c}'),
2625            b'u' => {
2626                let hi = hex4(&b[i + 2..i + 6]);
2627                i += 6;
2628                if (0xD800..=0xDBFF).contains(&hi) {
2629                    let lo = match (b.get(i), b.get(i + 1)) {
2630                        (Some(b'\\'), Some(b'u')) => hex4(&b[i + 2..i + 6]),
2631                        _ => return Err(ParseError::LoneSurrogate.into()),
2632                    };
2633                    if !(0xDC00..=0xDFFF).contains(&lo) {
2634                        return Err(ParseError::LoneSurrogate.into());
2635                    }
2636                    let c = 0x1_0000 + ((hi - 0xD800) << 10) + (lo - 0xDC00);
2637                    out.push(char::from_u32(c).expect("combined surrogate pair"));
2638                    i += 6;
2639                } else if (0xDC00..=0xDFFF).contains(&hi) {
2640                    return Err(ParseError::LoneSurrogate.into());
2641                } else {
2642                    out.push(char::from_u32(hi).expect("non-surrogate BMP scalar"));
2643                }
2644                chunk = i;
2645                continue;
2646            }
2647            _ => unreachable!("Muon validated the <str> escape grammar"),
2648        }
2649        i += 2;
2650        chunk = i;
2651    }
2652    out.push_str(&raw[chunk..]);
2653    Ok(Text::from(out.as_str()))
2654}
2655
2656/// Read four ASCII hex digits as a `u32`.
2657fn hex4(b: &[u8]) -> u32 {
2658    b.iter()
2659        .fold(0, |v, &c| v * 16 + (c as char).to_digit(16).unwrap())
2660}
2661
2662/// Parse an integer literal (decimal, hex, or binary) with `_` separators.
2663pub(crate) fn parse_int(s: &str) -> Option<BigInt> {
2664    let (neg, body) = match s.as_bytes().first()? {
2665        b'-' => (true, &s[1..]),
2666        b'+' => (false, &s[1..]),
2667        _ => (false, s),
2668    };
2669    let (radix, digits) =
2670        if let Some(h) = body.strip_prefix("0x").or_else(|| body.strip_prefix("0X")) {
2671            (16u32, h)
2672        } else if let Some(b) = body.strip_prefix("0b").or_else(|| body.strip_prefix("0B")) {
2673            (2, b)
2674        } else {
2675            (10, body)
2676        };
2677    let mut cleaned = alloc::string::String::new();
2678    let mut after_sep = true;
2679    for &c in digits.as_bytes() {
2680        if c == b'_' {
2681            if after_sep {
2682                return None;
2683            }
2684            after_sep = true;
2685        } else {
2686            cleaned.push(c as char);
2687            after_sep = false;
2688        }
2689    }
2690    if after_sep || cleaned.is_empty() {
2691        return None;
2692    }
2693    let mag = BigInt::parse_bytes(cleaned.as_bytes(), radix)?;
2694    Some(if neg { -mag } else { mag })
2695}
2696
2697/// Whether a block clause is a **binding** — it carries a top-level `=` punct.
2698/// A nested `=` lives inside a `(…)`/`[…]`/`{…}` item, never as a top-level
2699/// `Item::Punct`, so this is exactly the `<binding>` vs `<chain>` split the
2700/// `let` group makes (and [`split_binding`] then splits at the first `=`).
2701fn clause_is_binding(items: &[&Item<'_>]) -> bool {
2702    items.iter().any(|it| matches!(it, Item::Punct("=")))
2703}
2704
2705/// Whether `item` is a bare **matching literal** — a number, a `.`-symbol, or a
2706/// string — used where a whole `&`-header or `let` LHS is expected. These are
2707/// equality patterns, not binders, so a bare one reads as a stray value or an
2708/// intended binding; Elly requires the wrap (`&(42)`, `&(.foo)`, `&("s")`; see
2709/// `BareLiteralHeader`). Nested in `[…]`/`{…}`/`(…)`/an or-pattern they are fine.
2710fn is_bare_literal_header(item: &Item<'_>) -> bool {
2711    match item {
2712        Item::Sym(s) => parse_int(s).is_some(),
2713        Item::Prefixed { sigil: '.', .. } => true,
2714        Item::Str(_) => true,
2715        _ => false,
2716    }
2717}
2718
2719/// Check if an item is the `when` guard keyword.
2720fn is_when_kw(item: &Item) -> bool {
2721    head_keyword(item) == Some("when")
2722}
2723
2724/// Returns non-comment chains of a `<seq>` with [chain-joining](join_chains) applied.
2725fn chain_slices<'a, 'b>(seq: &'b Seq<'a>) -> Vec<Vec<&'b Item<'a>>> {
2726    let chains = seq
2727        .0
2728        .iter()
2729        .filter(|c| !is_comment_only(c))
2730        .map(|c| {
2731            c.0.iter()
2732                .filter(|it| !matches!(it, Item::Comm(_)))
2733                .collect()
2734        })
2735        .collect();
2736    join_chains(chains)
2737}
2738
2739/// Returns true if a `<braces>` seq contains a chain whose second non-comment item is `:`.
2740/// Used by [`Parser::block`] to reject bare-map spellings.
2741fn braces_contain_colon(seq: &Seq<'_>) -> bool {
2742    for chain in seq.0.iter().filter(|c| !is_comment_only(c)) {
2743        let items: Vec<&Item<'_>> = chain
2744            .0
2745            .iter()
2746            .filter(|it| !matches!(it, Item::Comm(_)))
2747            .collect();
2748        if items.len() >= 2 && matches!(items[1], Item::Punct(":")) {
2749            return true;
2750        }
2751    }
2752    false
2753}
2754
2755/// Joins adjacent chains if they form a single continued expression.
2756/// A chain joins if the predecessor ends with a continuation (e.g., `&`, `=`, `|>`, `when`)
2757/// or if the current chain starts with one (e.g., `|>`, `elif`, `else`, `catch`).
2758fn join_chains<'a, 'b>(chains: Vec<Vec<&'b Item<'a>>>) -> Vec<Vec<&'b Item<'a>>> {
2759    let mut out: Vec<Vec<&'b Item<'a>>> = Vec::with_capacity(chains.len());
2760    for chain in chains {
2761        let join = matches!(out.last(), Some(prev) if trailing_join(prev) || leading_join(&chain));
2762        if join {
2763            out.last_mut().unwrap().extend(chain);
2764        } else {
2765            out.push(chain);
2766        }
2767    }
2768    out
2769}
2770
2771/// Whether a chain ends with a trailing continuation.
2772fn trailing_join(chain: &[&Item]) -> bool {
2773    match chain.last() {
2774        Some(Item::Prefixed { sigil: '&', .. }) => true,
2775        Some(Item::Punct("=")) | Some(Item::Punct("|>")) => true,
2776        _ => {
2777            let n = chain.len();
2778            n >= 2
2779                && matches!(chain[n - 2], Item::Sym("when"))
2780                && matches!(chain[n - 1], Item::Parens(_))
2781        }
2782    }
2783}
2784
2785/// Whether a chain opens with a leading continuation.
2786fn leading_join(chain: &[&Item]) -> bool {
2787    match chain.first() {
2788        Some(Item::Punct("|>")) => true,
2789        Some(first) => matches!(head_keyword(first), Some("elif" | "else" | "catch")),
2790        None => false,
2791    }
2792}
2793
2794/// Returns the single non-comment chain of a `<seq>`, if it contains exactly one.
2795fn single_chain<'a, 'b>(seq: &'b Seq<'a>) -> Option<Vec<&'b Item<'a>>> {
2796    let mut chains = chain_slices(seq).into_iter();
2797    let first = chains.next()?;
2798    if chains.next().is_some() {
2799        return None;
2800    }
2801    Some(first)
2802}
2803
2804/// Whether a chain holds only comments.
2805fn is_comment_only(chain: &Chain) -> bool {
2806    chain.0.iter().all(|it| matches!(it, Item::Comm(_)))
2807}
2808
2809/// Whether `s` is an Elly keyword.
2810fn is_keyword(s: &str) -> bool {
2811    matches!(
2812        s,
2813        "Self"
2814            | "let"
2815            | "recur"
2816            | "import"
2817            | "const"
2818            | "local"
2819            | "with"
2820            | "as"
2821            | "when"
2822            | "match"
2823            | "case"
2824            | "of"
2825            | "if"
2826            | "elif"
2827            | "else"
2828            | "catch"
2829    )
2830}
2831
2832/// Whether `name` can be bound and referenced from source as a plain name.
2833pub fn is_bindable_name(name: &str) -> bool {
2834    muon::is_sym(name)
2835        && !is_keyword(name)
2836        && !name.starts_with("__")
2837        && name != "_"
2838        && !reads_as_number(name)
2839}
2840
2841/// Whether this item is a chain split point (e.g., `&`-binder or `let`/`recur`/`case`).
2842fn is_split_point(item: &Item) -> bool {
2843    is_binder(item)
2844        || matches!(
2845            head_keyword(item),
2846            Some("let") | Some("recur") | Some("case")
2847        )
2848}
2849
2850/// Whether this item is a `&`-prefixed binder.
2851fn is_binder(item: &Item) -> bool {
2852    matches!(item, Item::Prefixed { sigil: '&', .. })
2853}
2854
2855/// The keyword head of an item, if any (bare keyword or head of a keyword-headed run).
2856fn head_keyword<'a>(item: &Item<'a>) -> Option<&'a str> {
2857    match item {
2858        Item::Sym(s) if is_keyword(s) => Some(s),
2859        Item::Run(members) => match members.first() {
2860            Some(Item::Sym(s)) if is_keyword(s) => Some(s),
2861            _ => None,
2862        },
2863        _ => None,
2864    }
2865}