Skip to main content

blue_lang_syntax/
parse.rs

1//! Precedence-climbing parser, lowering straight to the tatara-lisp
2//! quoted form.
3//!
4//! **The load-bearing design decision, made here and once:** the parser's
5//! output IS a `tatara_lisp::Sexp`. There is no private blue AST that later
6//! gets converted. That is Tenet 1 — *blue source parses to tatara-lisp* —
7//! and building it any other way would make homoiconicity a conversion step
8//! rather than an identity, which is the difference between blue's macro
9//! story working and merely being claimed.
10//!
11//! The consequence to keep in view: every surface construct must have a
12//! well-defined s-expression it means. Where the mapping is not obvious it
13//! is written down in the test module, because the tests are the
14//! specification of the surface until the mechanized spec exists.
15//!
16//! ## Spans are built, not bolted on
17//!
18//! Every production returns a [`Spanned`] — tatara-lisp's parallel tree where
19//! **each node** carries the byte range that produced it — and the spanless
20//! [`parse_program`] is a projection of it via `Spanned::to_sexp`.
21//!
22//! That direction is deliberate and it is the second time this file has learned
23//! the lesson: the spanless tree is derivable from the spanned one and the
24//! reverse is not. When the parser produced `Sexp` and callers wanted positions,
25//! the only answers available were *invent one* (a squiggle under unrelated
26//! code) or *use nothing* — and the type checker took the second, so every type
27//! error in the editor was reported at line 0, column 0 regardless of where it
28//! was. A span discarded at the parser cannot be recovered by anything
29//! downstream, exactly as [`crate::lex`] says of trivia.
30//!
31//! Two honest limits, both stated where they are caused rather than inferred:
32//!
33//! - A node blue **synthesizes** (the `define` a `def` lowers to, the `not` an
34//!   `unless` lowers to, the `equal?` a `case` arm compares with) has no source
35//!   text of its own. It is given the span of the token that *caused* it — the
36//!   `def`, the `unless`, the `when` — which is where a reader looks when told
37//!   something about it.
38//! - An interpolation's inner expression is parsed from a **sub-source** (the
39//!   text between `#{` and `}`), so its own offsets are relative to that
40//!   substring and would point into the wrong buffer. Those nodes are stamped
41//!   with the whole string literal's span instead. Sub-span accuracy inside an
42//!   interpolation needs the lexer to record each part's offset in the outer
43//!   source, which it does not.
44
45use tatara_lisp::{Atom, Sexp, Spanned, SpannedForm};
46
47use crate::lex::{lex, Span, Token, TokenKind};
48use crate::spelling::{Note, Spelling};
49
50/// Why a source did not parse, and where.
51///
52/// **Structured, and located at the boundary.** `message` says what was
53/// expected and what was found, in blue's own words; `span` is the byte range
54/// of the offending text; `line` and `col` are that range's start, 1-based,
55/// with the column counted in characters. Every public entry point fills
56/// `line`/`col` from the source it was given, so `Display` reads
57/// `3:7: expected `)`, found `]`` and never a byte offset.
58///
59/// The byte offsets used to BE the display (`… at 10..11`), and a Rust
60/// `Debug` rendering named the token (`found Ident("y")`). Both are facts
61/// about the implementation; neither is something an author can act on.
62/// The span stays, as data, for any consumer that needs to point into the
63/// buffer — an editor squiggle, a diagnostic code attached downstream.
64#[derive(Clone, Debug, PartialEq)]
65pub struct ParseError {
66    pub message: String,
67    pub span: Span,
68    /// 1-based line of `span.start`.
69    pub line: usize,
70    /// 1-based column of `span.start`, in characters.
71    pub col: usize,
72}
73
74impl ParseError {
75    /// An error at `span`, not yet located: the parser sees tokens, not text,
76    /// so the line and column are filled by [`Self::located`] at the entry
77    /// point that holds the source.
78    pub(crate) fn new(message: impl Into<String>, span: Span) -> Self {
79        Self {
80            message: message.into(),
81            span,
82            line: 0,
83            col: 0,
84        }
85    }
86
87    /// Resolve `line`/`col` against the source this error's span indexes.
88    pub(crate) fn located(mut self, src: &str) -> Self {
89        let (line, col) = Span::line_col(src, self.span.start.min(src.len()));
90        self.line = line;
91        self.col = col;
92        self
93    }
94}
95
96impl std::fmt::Display for ParseError {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        write!(f, "{}:{}: {}", self.line, self.col, self.message)
99    }
100}
101
102impl std::error::Error for ParseError {}
103
104impl From<crate::lex::LexError> for ParseError {
105    fn from(e: crate::lex::LexError) -> Self {
106        Self::new(e.message, e.span)
107    }
108}
109
110thread_local! {
111    static PARSES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
112}
113
114/// How many programs this thread has parsed: an independent count for a
115/// caller that promises to parse a text once, read off the parser itself
116/// rather than off the caller's own bookkeeping.
117#[must_use]
118pub fn parses_on_this_thread() -> u64 {
119    PARSES.with(std::cell::Cell::get)
120}
121
122/// Parse a blue program into a sequence of tatara-lisp forms.
123pub fn parse_program(src: &str) -> Result<Vec<Sexp>, ParseError> {
124    parse_program_with_depth(src, MAX_EXPR_DEPTH)
125}
126
127/// Parse a blue program keeping **every node's** source span.
128///
129/// This is the parser's real output; [`parse_program`] projects the spans away.
130/// Reach for this one whenever a position is going to be shown to a human — an
131/// editor squiggle, a `line:col` in a CLI error, a future debugger's breakpoint
132/// table. Reach for [`parse_program`] only when the consumer genuinely does not
133/// care where anything was.
134pub fn parse_program_tree(src: &str) -> Result<Vec<Spanned>, ParseError> {
135    parse_program_tree_with_depth(src, MAX_EXPR_DEPTH)
136}
137
138/// [`parse_program_tree`] with the nesting bound supplied by the caller.
139pub fn parse_program_tree_with_depth(
140    src: &str,
141    max_depth: usize,
142) -> Result<Vec<Spanned>, ParseError> {
143    parse_program_documented_with_depth(src, max_depth).map(crate::doc::strip)
144}
145
146/// Parse keeping the documentation nodes `@doc` and `@moduledoc` lower to
147/// ([`crate::doc`]). Every other `parse_program*` door strips them.
148pub fn parse_program_documented(src: &str) -> Result<Vec<Spanned>, ParseError> {
149    parse_program_documented_with_depth(src, MAX_EXPR_DEPTH)
150}
151
152/// [`parse_program_documented`] with the nesting bound supplied by the caller.
153pub fn parse_program_documented_with_depth(
154    src: &str,
155    max_depth: usize,
156) -> Result<Vec<Spanned>, ParseError> {
157    if let Some(hit) = RECENT.with(|r| {
158        r.borrow()
159            .iter()
160            .find(|(d, s, _)| *d == max_depth && s.as_str() == src)
161            .map(|(_, _, t)| t.clone())
162    }) {
163        return hit;
164    }
165    PARSES.with(|n| n.set(n.get() + 1));
166    let parsed = lex(src)
167        .map_err(|e| ParseError::from(e).located(src))
168        .and_then(|toks| {
169            Parser::over(src, toks, max_depth)
170                .program()
171                .map_err(|e| e.located(src))
172        });
173    RECENT.with(|r| {
174        let mut r = r.borrow_mut();
175        if r.len() == RECENT_TEXTS {
176            drop(r.remove(0));
177        }
178        r.push((max_depth, src.to_string(), parsed.clone()));
179    });
180    parsed
181}
182
183/// A doc example's expression or statement: part of its text's parse, so
184/// neither counted nor kept apart from it.
185pub(crate) fn parse_snippet(src: &str) -> Result<Vec<Spanned>, ParseError> {
186    let toks = lex(src).map_err(|e| ParseError::from(e).located(src))?;
187    Parser::over(src, toks, MAX_EXPR_DEPTH)
188        .program()
189        .map(crate::doc::strip)
190        .map_err(|e| e.located(src))
191}
192
193/// How many recent texts each thread keeps the parse of. One text is read
194/// by several views in one check (the stripped tree, its documentation, its
195/// doctests, the doc rules); they share one parse.
196const RECENT_TEXTS: usize = 4;
197
198type Recent = Vec<(usize, String, Result<Vec<Spanned>, ParseError>)>;
199
200thread_local! {
201    static RECENT: std::cell::RefCell<Recent> = const { std::cell::RefCell::new(Vec::new()) };
202}
203
204/// Whether `x[key]` reads `key` as a map key, `get(x, key)`: a keyword or
205/// string literal. Any other key indexes a list, `nth(key, x)` (B0066).
206#[must_use]
207pub fn is_index_key(key: &Spanned) -> bool {
208    key.as_keyword().is_some() || key.as_string().is_some()
209}
210
211/// The text a constant string form spells, for a reader that takes text from
212/// a tree without evaluating it: a string, `line_break`, or `join_lines([…])` /
213/// `unlines([…])` over constant texts, which is how the parser reads a string
214/// holding a line break (B0065). `None` for anything computed.
215#[must_use]
216pub fn constant_text(s: &Sexp) -> Option<String> {
217    match s {
218        Sexp::Atom(Atom::Str(x)) => Some(x.to_string()),
219        Sexp::Atom(Atom::Symbol(h)) if h.as_str() == "line_break" => Some("\n".to_string()),
220        Sexp::List(items) => match items.as_slice() {
221            [Sexp::Atom(Atom::Symbol(h)), Sexp::List(list)]
222                if h.as_str() == "join_lines" || h.as_str() == "unlines" =>
223            {
224                let (Sexp::Atom(Atom::Symbol(l)), elems) = list.split_first()? else {
225                    return None;
226                };
227                if l.as_str() != "list" {
228                    return None;
229                }
230                let texts = elems
231                    .iter()
232                    .map(constant_text)
233                    .collect::<Option<Vec<_>>>()?;
234                Some(if h.as_str() == "join_lines" {
235                    texts.join("\n")
236                } else {
237                    texts.iter().map(|t| format!("{t}\n")).collect()
238                })
239            }
240            _ => None,
241        },
242        _ => None,
243    }
244}
245
246pub fn spelling_notes(src: &str) -> Result<Vec<Note>, ParseError> {
247    let mut p = Parser::over(
248        src,
249        lex(src).map_err(|e| ParseError::from(e).located(src))?,
250        MAX_EXPR_DEPTH,
251    );
252    p.program().map_err(|e| e.located(src))?;
253    Ok(p.notes)
254}
255
256/// Parse a program written in a [`Yakugo`](crate::yakugo::Yakugo) surface.
257///
258/// The pack is applied to the TOKEN STREAM, between lexing and parsing, so the
259/// parser below is untouched and every keyword site works by construction.
260/// What comes out is the same `Sexp` the English surface produces — that is
261/// the invariant the pack tests assert, and the only thing that makes a
262/// surface a surface rather than a dialect.
263///
264/// # Errors
265///
266/// Lex and parse errors propagate unchanged. A pack cannot repair source that
267/// does not tokenize, and reporting otherwise would name the wrong problem.
268pub fn parse_program_in(src: &str, pack: &crate::yakugo::Yakugo) -> Result<Vec<Sexp>, ParseError> {
269    Ok(parse_program_tree_in(src, pack)?
270        .iter()
271        .map(Spanned::to_sexp)
272        .collect())
273}
274
275/// [`parse_program_in`] keeping **every node's** source span.
276///
277/// The same relation [`parse_program_tree`] has to [`parse_program`], and it
278/// exists for the same reason: a surface is a spelling, so a program written in
279/// one has positions exactly as real as an English-surface program's. Without
280/// this door, `pipeline::run_in_surface` would have to lift a spanless tree back
281/// up and every type error in a `yakugo` program would report `<synthetic>` —
282/// a position the parser HAD and threw away one line earlier, which is the
283/// class `Diagnostic::span`'s own docs name.
284///
285/// [`parse_program_in`] is now its projection, so the two cannot drift.
286///
287/// # Errors
288///
289/// As [`parse_program_in`].
290pub fn parse_program_tree_in(
291    src: &str,
292    pack: &crate::yakugo::Yakugo,
293) -> Result<Vec<Spanned>, ParseError> {
294    let toks =
295        crate::yakugo::canonical_tokens(src, pack).map_err(|e| ParseError::from(e).located(src))?;
296    PARSES.with(|n| n.set(n.get() + 1));
297    let mut p = Parser::over(src, toks, MAX_EXPR_DEPTH);
298    p.program()
299        .map(crate::doc::strip)
300        .map_err(|e| e.located(src))
301}
302
303/// [`parse_program`] with the nesting bound supplied by the caller.
304///
305/// The bound is a **safety limit, not a dialect**: `max_depth` cannot change
306/// what any program means, only whether a pathological one is refused before
307/// the stack is at risk. That is why it is a parameter here and
308/// [`MAX_EXPR_DEPTH`] is only the default — a knob that could alter meaning
309/// would belong nowhere near a config file (see `blue-lang-cli`'s `config`
310/// module for the rule this obeys).
311pub fn parse_program_with_depth(src: &str, max_depth: usize) -> Result<Vec<Sexp>, ParseError> {
312    Ok(parse_program_tree_with_depth(src, max_depth)?
313        .iter()
314        .map(Spanned::to_sexp)
315        .collect())
316}
317
318/// Parse, keeping each top-level form's source span.
319///
320/// The spans are what let the formatter put comments back. A comment is not
321/// part of a program's *meaning*, so it has no place in the `Sexp` tree —
322/// putting it there would break canonicality, since two programs differing only
323/// in a comment would stop formatting identically. Instead the formatter renders
324/// the tree and re-interleaves comments by position, which needs to know where
325/// each form started and ended.
326///
327/// A projection of [`parse_program_tree`], which carries a span on every node
328/// rather than only the top-level ones. This entry point survives because the
329/// formatter wants exactly the top-level pairing and nothing deeper.
330pub fn parse_program_spanned(src: &str) -> Result<Vec<(Sexp, Span)>, ParseError> {
331    parse_program_spanned_with_depth(src, MAX_EXPR_DEPTH)
332}
333
334/// [`parse_program_spanned`] with the nesting bound supplied by the caller.
335pub fn parse_program_spanned_with_depth(
336    src: &str,
337    max_depth: usize,
338) -> Result<Vec<(Sexp, Span)>, ParseError> {
339    Ok(parse_program_tree_with_depth(src, max_depth)?
340        .iter()
341        .map(|f| (f.to_sexp(), f.span))
342        .collect())
343}
344
345/// Every comment in `src`, with its byte span and whether it sits alone on its
346/// line.
347///
348/// `own_line` is the distinction that decides placement: a comment alone on its
349/// line belongs *before* the form that follows, while one after code on the same
350/// line belongs *to* that line. Conflating them moves a trailing note onto the
351/// wrong row.
352pub fn comments(src: &str) -> Vec<Comment> {
353    lex(src)
354        .map(|toks| {
355            toks.iter()
356                .filter_map(|t| match &t.kind {
357                    TokenKind::Comment(text) => Some(Comment {
358                        text: text.clone(),
359                        span: t.span,
360                        own_line: line_before_is_blank(src, t.span.start),
361                    }),
362                    _ => None,
363                })
364                .collect()
365        })
366        .unwrap_or_default()
367}
368
369/// A comment, and where it sat.
370#[derive(Clone, Debug, PartialEq, Eq)]
371pub struct Comment {
372    /// The text, including the leading `#`.
373    pub text: String,
374    pub span: Span,
375    /// Nothing but whitespace precedes it on its line.
376    pub own_line: bool,
377}
378
379fn line_before_is_blank(src: &str, start: usize) -> bool {
380    src[..start.min(src.len())]
381        .rsplit('\n')
382        .next()
383        .is_some_and(|prefix| {
384            prefix
385                .trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}')
386                .is_empty()
387        })
388}
389
390/// Parse a single blue expression. Convenience for tests and the REPL.
391pub fn parse_expr(src: &str) -> Result<Sexp, ParseError> {
392    let forms = parse_program(src)?;
393    match forms.len() {
394        1 => Ok(forms.into_iter().next().expect("checked len")),
395        n => Err(ParseError::new(
396            format!("expected exactly one expression, found {n}"),
397            Span::new(0, src.len()),
398        )
399        .located(src)),
400    }
401}
402
403/// What an infix operator binds like, and what it lowers to.
404///
405/// **One row per operator, carrying both facts.** Precedence and callee
406/// used to live apart, and the cost was immediate: the surface spelling was
407/// emitted verbatim, so `a == b` lowered to `(== a b)` — a symbol no
408/// interpreter binds — and the program died at *runtime* with `unbound
409/// symbol ==`. Splitting the two invites exactly that: add an operator to
410/// the precedence table, forget the lowering, ship a parse that cannot run.
411/// Joined here, "has a precedence" and "has a callee" are the same fact.
412#[derive(Clone, Copy, Debug)]
413pub struct Infix {
414    /// Surface spelling.
415    pub op: &'static str,
416    /// Left and right binding power. Higher binds tighter.
417    pub power: (u8, u8),
418    /// The tatara-lisp callee this lowers to.
419    pub callee: &'static str,
420    /// One line for a reader: what the operator computes, and the trap in it
421    /// when there is one. `blue reference` prints it; a row without one fails
422    /// `every_operator_and_keyword_is_described`.
423    pub doc: &'static str,
424}
425
426/// The complete infix table. Precedence follows Ruby's where Ruby has an
427/// opinion; `|>` (below) sits under everything so `a |> f |> g` chains
428/// without parentheses.
429pub const INFIX: &[Infix] = &[
430    Infix {
431        op: "or",
432        power: (1, 2),
433        callee: "or",
434        doc: "Logical or: the left value if truthy, otherwise the right; the right is evaluated only when needed. `||` is read as `or` and written `or` (B0025).",
435    },
436    Infix {
437        op: "and",
438        power: (3, 4),
439        callee: "and",
440        doc: "Logical and: the right value if the left is truthy, otherwise the left; short-circuits. `&&` is read as `and` and written `and` (B0025).",
441    },
442    // `==` is STRUCTURAL equality, so it lowers to `equal?` and not to `=`.
443    //
444    // tatara's `=` is NUMERIC comparison: `"a" = "a"` is a type error, not
445    // false. Lowering `==` to it meant every string, list or nil comparison
446    // failed with "expected number, got string" — found by blue's own spec
447    // suite the moment a test compared two strings, which is the first thing
448    // anybody does.
449    //
450    // `equal?` is structural and total over the value domain: strings, lists
451    // and nil all compare, and numbers still compare as numbers.
452    Infix {
453        op: "==",
454        power: (5, 6),
455        callee: "equal?",
456        doc: "Structural equality over every value (okite D0001): 4 == 4.0, lists and maps by content, nil only equals nil.",
457    },
458    Infix {
459        op: "!=",
460        power: (5, 6),
461        callee: "not=",
462        doc: "Exactly not(a == b) (okite D0002).",
463    },
464    Infix {
465        op: "<",
466        power: (5, 6),
467        callee: "<",
468        doc: "Numeric less-than. A string operand is a type error: order text with compare(a, b).",
469    },
470    Infix {
471        op: "<=",
472        power: (5, 6),
473        callee: "<=",
474        doc: "Numeric less-than-or-equal. Numbers only, like <.",
475    },
476    Infix {
477        op: ">",
478        power: (5, 6),
479        callee: ">",
480        doc: "Numeric greater-than. Numbers only, like <.",
481    },
482    Infix {
483        op: ">=",
484        power: (5, 6),
485        callee: ">=",
486        doc: "Numeric greater-than-or-equal. Numbers only, like <.",
487    },
488    Infix {
489        op: "+",
490        power: (7, 8),
491        callee: "+",
492        doc: "Numeric addition; an Int and a Float give a Float. Not string concatenation: interpolate instead.",
493    },
494    Infix {
495        op: "-",
496        power: (7, 8),
497        callee: "-",
498        doc: "Numeric subtraction. Written before an operand with nothing on its left, it is unary minus: -n.",
499    },
500    Infix {
501        op: "*",
502        power: (9, 10),
503        callee: "*",
504        doc: "Numeric multiplication.",
505    },
506    Infix {
507        op: "/",
508        power: (9, 10),
509        callee: "/",
510        doc: "Division that never truncates (okite D0008): 7 / 2 is 3.5, while 6 / 2 stays the Int 3. Integer division is floor(a / b).",
511    },
512    Infix {
513        op: "%",
514        power: (9, 10),
515        callee: "mod",
516        doc: "Euclidean remainder: never negative, so (0 - 7) % 3 is 2, not -1. A zero divisor is a runtime error.",
517    },
518];
519
520/// Every surface keyword that BEGINS an expression.
521///
522/// Exists so the formatter's corpus can be checked against it. Three separate
523/// times a form was added to this parser, the formatter was not extended, and
524/// all three formatting laws still passed — because the corpus is
525/// hand-maintained and contained no example of the new form. The annotated
526/// `def` rendered as a method send; `defmacro` rendered as
527/// `defmacro(double, x(), …)`, which does not re-parse at all.
528///
529/// A law cannot notice a case nobody wrote down. `blue-lang-fmt`'s
530/// `every_surface_keyword_appears_in_the_corpus` closes that by making the
531/// omission itself the failure, so adding a keyword here forces the corpus
532/// entry that exercises the other three laws over it.
533///
534/// `do` and `end` are absent deliberately: they are block delimiters, not
535/// expression heads, and have no standalone rendering to test.
536/// The master verbs a bare call dispatches on the subject's space.
537pub const MASTER_VERBS: &[&str] = &[
538    "read", "need", "has?", "put", "update", "delete", "create", "diff", "info", "exists?",
539];
540
541/// The callee `assert e` lowers to.
542///
543/// **Owned here, by the lowering itself, and read by every consumer.** It was
544/// briefly a literal here and a separate `const` in `blue-lang-test`, and the
545/// shadowing gate then could not see a parser that lowered to the wrong name:
546/// the gate checked its own copy. Same duplication class as the operator table.
547pub const LOWERED_ASSERT: &str = "blue-assert";
548
549/// The callee a `{...}` map literal lowers to.
550///
551/// **`hash-map`, not `map`.** tatara binds `map` to the higher-order function,
552/// so a literal lowering to `(map …)` called the HOF with the key/value pairs
553/// as arguments and failed with "expected list, got int". Same shadowing class
554/// as [`LOWERED_ASSERT`], caught by the same gate once the name was listed
555/// there — it was not, which is why this shipped.
556pub const LOWERED_MAP: &str = "hash-map";
557
558/// The callee string interpolation lowers to.
559///
560/// blue's own `concat`, which renders either side through `to_s` — that is what
561/// lets `"n=#{42}"` interpolate a number. Not `+`, which is arithmetic.
562pub const LOWERED_CONCAT: &str = "concat";
563
564pub const OPTIONAL_MARKER: &str = "&optional";
565
566pub const LOWERED_OPTIONAL_ARITY: &str = "blue-optional-arity";
567
568pub const LOWERED_OPTIONAL_ARG: &str = "blue-optional-arg";
569
570pub const LOWERED_FIELD: &str = "blue-field";
571
572pub const LOWERED_MERGE: &str = "blue-merge";
573
574pub const LOWERED_SPLICE: &str = "blue-splice";
575
576pub const LOWERED_KWARGS: &str = "blue-kwargs";
577
578pub const LOWERED_ERROR_MATCH: &str = "blue-rescues?";
579
580pub const LOWERED_ENSURE: &str = "blue-ensure";
581
582pub const LOWERED_RERAISE: &str = "blue-reraise";
583
584pub const LOWERED_ATTEMPTED: &str = "blue-attempted";
585
586pub const LOWERED_FAILED: &str = "blue-failed";
587
588pub const LOWERED_HEADS: &[&str] = &[
589    "list",
590    "concat",
591    "not",
592    "apply",
593    "equal?",
594    "not=",
595    "and",
596    "or",
597    "mod",
598    "join_lines",
599    "unlines",
600    "line_break",
601];
602
603pub const RESCUED: &str = "rescued-error";
604
605pub const SURFACE_KEYWORDS: &[&str] = &[
606    "if",
607    "begin",
608    "unless",
609    "def",
610    "defmacro",
611    "quote",
612    "unquote",
613    "unquote_splice",
614    "test",
615    "assert",
616    "fn",
617    "case",
618];
619
620/// The words that are reserved but are not heads of a `SURFACE_KEYWORDS` form
621/// — block delimiters and the three literals.
622///
623/// Split out as data rather than inlined in a `matches!` because a reserved
624/// word is not only the parser's business: a highlighter has to paint exactly
625/// this set, and one that reads `SURFACE_KEYWORDS` alone silently under-paints
626/// `do` / `end` / `else` / `elsif`. That was not hypothetical — escriba's
627/// `escriba-render/src/langs.rs` hand-transcribed "SURFACE_KEYWORDS plus the
628/// four block words `is_reserved_word` adds", because the union was
629/// unreachable from outside this module. A transcription is a second
630/// definition, and it drifts the first time this list changes.
631pub const BLOCK_KEYWORDS: &[&str] = &[
632    "do", "end", "else", "elsif", "rescue", "ensure", "true", "false", "nil",
633];
634
635pub const OPERATOR_KEYWORDS: &[&str] = &["and", "or", "not"];
636
637/// A surface keyword may not be rebound. `if = 1` is a mistake, not a binding,
638/// and letting it through would shadow the form for the rest of the file.
639///
640/// Public because it is the ONE answer to "is this identifier a keyword" —
641/// the parser's rebinding check and every downstream highlighter read it here
642/// rather than each carrying its own copy of the list.
643pub fn is_reserved_word(name: &str) -> bool {
644    SURFACE_KEYWORDS.contains(&name)
645        || BLOCK_KEYWORDS.contains(&name)
646        || OPERATOR_KEYWORDS.contains(&name)
647}
648
649/// Can `name` be written as the head of a call — `name(…)`?
650///
651/// True exactly when the lexer reads `name` as one identifier and it is not
652/// reserved. Answered BY the lexer rather than by a character class copied
653/// from it, so the two cannot disagree: the formatter asks this before
654/// printing a tree as `name(args)`, and a head such as `hash-map`, `not=` or
655/// `if` — which a tree can carry and a call cannot spell — must get a
656/// different rendering or none.
657pub fn is_callable_name(name: &str) -> bool {
658    // `retsu/first` is written `retsu::first(…)`.
659    if qualified(name).is_some() {
660        return true;
661    }
662    !is_reserved_word(name)
663        && matches!(
664            lex(name).as_deref(),
665            Ok([t, e]) if matches!(&t.kind, TokenKind::Ident(n) if n == name)
666                && e.kind == TokenKind::Eof
667        )
668}
669
670/// The character a qualified name's AST symbol joins its two halves with:
671/// `retsu::first` is the symbol `retsu/first`. The surface never writes it
672/// (`/` is division, and no identifier can contain it), which is what makes
673/// a symbol with text on both sides of one `/` unambiguously qualified.
674pub const QUALIFIER: char = '/';
675
676/// The qualifier that names a builtin: `blue::count` is the interpreter's
677/// `count`, whatever a program defines. No package may be named it.
678pub const BUILTIN_QUALIFIER: &str = "blue";
679
680/// The AST symbol for `pkg::name`.
681#[must_use]
682pub fn qualify(pkg: &str, name: &str) -> String {
683    format!("{pkg}{QUALIFIER}{name}")
684}
685
686/// `retsu/first` → `Some(("retsu", "first"))`: the package and the name of a
687/// qualified symbol. `None` for every other symbol, `/` (division) included.
688///
689/// The ONE reader of the shape, so the formatter, the name table and the
690/// runtime's renderer cannot disagree about what counts as qualified.
691#[must_use]
692pub fn qualified(sym: &str) -> Option<(&str, &str)> {
693    let (pkg, name) = sym.split_once(QUALIFIER)?;
694    let ident = |s: &str| {
695        matches!(
696            lex(s).as_deref(),
697            Ok([t, e]) if matches!(&t.kind, TokenKind::Ident(n) if n == s) && e.kind == TokenKind::Eof
698        )
699    };
700    let named = |s: &str| ident(s) || matches!(s, "true" | "false" | "nil");
701    (ident(pkg) && !is_reserved_word(pkg) && named(name)).then_some((pkg, name))
702}
703
704/// One line for a reader on each reserved word: what it writes, and the shape.
705///
706/// Beside the two tables rather than inside them, because both are `&[&str]`
707/// read by the formatter's corpus gate and by highlighters outside this repo;
708/// changing their type would break every one of those readers.
709/// `every_operator_and_keyword_is_described` makes a word without a line here a
710/// red build, so the omission cannot ship. `blue reference` prints these.
711#[must_use]
712pub fn keyword_doc(word: &str) -> &'static str {
713    match word {
714        "if" => "`if c … elsif d … else … end`: an expression; its value is the branch taken, nil when none is. An `else` that is empty or `nil` is dropped (B0035).",
715        "unless" => "`unless c … end` is read as `if not c` and written that way (B0026).",
716        "begin" => "`begin … rescue :kind as e … rescue e … ensure … end`: run the statements; a `rescue` clause catches an error by kind, binding it with `as`, and `rescue e` catches every error; `ensure` always runs. A def body takes the same clauses without `begin`.",
717        "rescue" => "A clause of `begin` or `def`: `rescue :a, :b as e`, `rescue e` (every error, last). Inline, `x rescue fallback` is fallback when x raises; it binds loosest, below `|>`.",
718        "ensure" => "The last clause of `begin` or `def`: statements that run whether the block returned or raised; the block's value or error is kept.",
719        "and" => "`a and b`: logical and; `&&` is read as `and` and written `and` (B0025).",
720        "or" => "`a or b`: logical or; `||` is read as `or` and written `or` (B0025).",
721        "not" => "`not x`: true when x is false or nil; `!x` is read as `not x` and written `not x` (B0025). `not (a == b)` is written `a != b` (B0034).",
722        "def" => "`def name(a, b) … end`: a named function; its value is the last expression. Parameters may be typed: `def f(n: Int) -> Int`.",
723        "defmacro" => "`defmacro name(x) quote … unquote(x) … end end`: a macro, a rewrite of the unevaluated form.",
724        "quote" => "`quote … end`: the form itself as data, not its value. Used inside `defmacro`.",
725        "unquote" => "`unquote(x)`: inside `quote`, splice in the value of `x`.",
726        "unquote_splice" => "`unquote_splice(xs)`: inside `quote`, splice the items of the form `xs` in place, not the form itself.",
727        "test" => "`test \"what must hold\" … end`: a test block, run by `blue test` and ignored by `blue run`.",
728        "assert" => "`assert expr`: inside a test, fail it unless `expr` is truthy; the failure quotes the expression.",
729        "fn" => "`fn(x) x * 2 end`: an anonymous function, a value. Blue has no brace or do blocks.",
730        "case" => "`case v when 1 … when 2 … else … end`: compares with `==`; it does not destructure.",
731        "do" => "Reserved and refused: blue has no do-blocks. Pass `fn(x) … end` instead.",
732        "end" => "Closes `def`, `defmacro`, `if`, `case`, `fn`, `test` and `quote`.",
733        "else" => "The branch of `if` or `case` taken when nothing before it matched.",
734        "elsif" => "A further condition in an `if` chain; an `else` holding only an `if` is written `elsif` (B0027).",
735        "true" => "The boolean true.",
736        "false" => "The boolean false. Only `false` and `nil` are falsy; 0, \"\" and [] are truthy.",
737        "nil" => "The absent value. It is not `[]` (okite D0004), and only `nil == nil`.",
738        _ => "",
739    }
740}
741
742fn infix(op: &str) -> Option<&'static Infix> {
743    INFIX.iter().find(|i| i.op == op)
744}
745
746pub const SYMBOL_SPELLINGS: &[(&str, &str)] = &[("&&", "and"), ("||", "or"), ("!", "not")];
747
748fn word_for(op: &str) -> &str {
749    SYMBOL_SPELLINGS
750        .iter()
751        .find(|(sym, _)| *sym == op)
752        .map_or(op, |(_, word)| word)
753}
754
755fn infix_of(kind: &TokenKind) -> Option<&'static Infix> {
756    match kind {
757        TokenKind::Op(o) => infix(word_for(o)),
758        TokenKind::Ident(w) if w == "and" || w == "or" => infix(w),
759        _ => None,
760    }
761}
762
763const PIPE_POWER: (u8, u8) = (0, 1);
764const RESCUE_POWER: (u8, u8) = (0, 1);
765
766struct Parser {
767    toks: Vec<Token>,
768    pos: usize,
769    /// Current expression-nesting depth, bounded by [`Self::max_depth`].
770    ///
771    /// Without this the parser does not fail on deep input — it **aborts the
772    /// process** with a stack overflow (SIGABRT), which `catch_unwind` cannot
773    /// catch. Measured 2026-08-01: `"(".repeat(2_000)` killed the test runner
774    /// outright. Every consumer inherited it — an LSP parsing a half-typed
775    /// line, a formatter, and shikumi loading a `.b` config off disk.
776    depth: usize,
777    /// The bound [`Self::depth`] is checked against.
778    ///
779    /// Defaults to [`MAX_EXPR_DEPTH`] on every entry point that does not name
780    /// one; `parse_program_with_depth` exists so an operator can raise it
781    /// without recompiling. It is a **bound**, so raising it changes no
782    /// program's meaning — only which pathological inputs are refused.
783    max_depth: usize,
784    src: String,
785    comment_spans: Vec<Span>,
786    notes: Vec<Note>,
787    /// How many `quote` bodies enclose the parser: a string inside one is
788    /// data, so its `\n` is kept as written rather than lowered (B0065).
789    quoting: usize,
790}
791
792/// Maximum expression nesting before the parser refuses.
793///
794/// Chosen well above anything human-written (blue's own `spec/*.b` peaks in
795/// single digits) and far below the measured overflow point, so the bound is
796/// hit as a typed `Err` long before the stack is at risk. A limit that is
797/// merely *near* the crash point is not a safety bound; it is a race.
798pub const MAX_EXPR_DEPTH: usize = 256;
799
800/// The parser's internal error: a [`ParseError`] behind a pointer.
801///
802/// Every production returns a `Result`, and a debug build keeps several per
803/// frame down the recursion, so the error's size is paid at every level of
804/// nesting whether or not anything fails. Measured 2026-09-29 on a 2 MiB
805/// debug thread, parsing `(((…1…)))` with no bound: the unboxed 40-byte error
806/// overflowed between 255 and 260 levels, barely past [`MAX_EXPR_DEPTH`];
807/// adding `line`/`col` unboxed moved it to 240–250, under the bound, and
808/// `depth_beyond_the_limit_is_an_err_not_an_abort` aborted. Boxed, the
809/// overflow is between 300 and 310. The error path is cold; the pointer is
810/// what keeps the bound a bound.
811type Fail = Box<ParseError>;
812
813fn fail(message: impl Into<String>, span: Span) -> Fail {
814    Box::new(ParseError::new(message, span))
815}
816
817impl Parser {
818    fn over(src: &str, all: Vec<Token>, max_depth: usize) -> Self {
819        let comment_spans = all
820            .iter()
821            .filter(|t| matches!(t.kind, TokenKind::Comment(_)))
822            .map(|t| t.span)
823            .collect();
824        let toks = all
825            .into_iter()
826            .filter(|t| !matches!(t.kind, TokenKind::Comment(_)))
827            .collect();
828        Parser {
829            toks,
830            pos: 0,
831            depth: 0,
832            max_depth,
833            src: src.to_string(),
834            comment_spans,
835            notes: Vec::new(),
836            quoting: 0,
837        }
838    }
839
840    fn note(&mut self, spelling: Spelling, span: Span, written: &str, canonical: &str) {
841        self.notes.push(Note {
842            spelling,
843            span,
844            written: written.to_string(),
845            canonical: canonical.to_string(),
846        });
847    }
848
849    fn text(&self, span: Span) -> &str {
850        self.src.get(span.start..span.end).unwrap_or("")
851    }
852
853    fn comment_within(&self, lo: usize, hi: usize) -> bool {
854        self.comment_spans
855            .iter()
856            .any(|c| c.start >= lo && c.start < hi)
857    }
858
859    fn touches_previous(&self) -> bool {
860        let here = self.peek_span();
861        self.toks
862            .get(self.pos.wrapping_sub(1))
863            .is_some_and(|prev| prev.span.end == here.start)
864    }
865
866    fn peek(&self) -> &TokenKind {
867        &self.toks[self.pos.min(self.toks.len() - 1)].kind
868    }
869
870    fn peek_span(&self) -> Span {
871        self.toks[self.pos.min(self.toks.len() - 1)].span
872    }
873
874    fn bump(&mut self) -> TokenKind {
875        let k = self.toks[self.pos.min(self.toks.len() - 1)].kind.clone();
876        if self.pos < self.toks.len() {
877            self.pos += 1;
878        }
879        k
880    }
881
882    fn at(&self, k: &TokenKind) -> bool {
883        self.peek() == k
884    }
885
886    fn eat(&mut self, k: &TokenKind) -> bool {
887        if self.at(k) {
888            self.bump();
889            true
890        } else {
891            false
892        }
893    }
894
895    fn expect(&mut self, k: &TokenKind, what: &str) -> Result<(), Fail> {
896        if self.eat(k) {
897            Ok(())
898        } else {
899            Err(self.error(format!("expected {what}, found {}", self.peek())))
900        }
901    }
902
903    fn error(&self, message: impl Into<String>) -> Fail {
904        fail(message, self.peek_span())
905    }
906
907    /// Skip statement separators (newlines and semicolon-free layout).
908    fn skip_newlines(&mut self) {
909        while matches!(self.peek(), TokenKind::Newline) {
910            self.bump();
911        }
912    }
913
914    fn at_ident(&self, name: &str) -> bool {
915        matches!(self.peek(), TokenKind::Ident(n) if n == name)
916    }
917
918    /// Byte offset where the next token begins — the anchor a production spans
919    /// *from*. Paired with [`Self::span_since`].
920    fn mark(&self) -> usize {
921        self.peek_span().start
922    }
923
924    /// The span from `start` to the end of the **last consumed** token.
925    ///
926    /// `pos` has already advanced past that token, so this looks one back. Call
927    /// it after a production has consumed everything it owns; calling it early
928    /// yields a span that stops short of the node it describes.
929    fn span_since(&self, start: usize) -> Span {
930        let end = self
931            .toks
932            .get(self.pos.saturating_sub(1))
933            .map_or(start, |t| t.span.end);
934        Span::new(start, end.max(start))
935    }
936
937    fn program(&mut self) -> Result<Vec<Spanned>, Fail> {
938        let mut out = Vec::new();
939        loop {
940            self.skip_newlines();
941            if matches!(self.peek(), TokenKind::Eof) {
942                break;
943            }
944            if let TokenKind::Doc { module, text } = self.peek().clone() {
945                out.push(self.documentation(module, text, out.is_empty())?);
946                continue;
947            }
948            out.push(self.statement()?);
949            self.end_of_statement(&[])?;
950        }
951        Ok(out)
952    }
953
954    /// `@moduledoc """…"""` as the first form, or `@doc """…"""` over the
955    /// definition it documents ([`crate::doc`]).
956    fn documentation(&mut self, module: bool, text: String, first: bool) -> Result<Spanned, Fail> {
957        let span = self.peek_span();
958        self.bump();
959        let word = if module { "@moduledoc" } else { "@doc" };
960        let head = sym_at(
961            Span::new(span.start, span.start + word.len()),
962            if module {
963                crate::doc::MODULEDOC_HEAD
964            } else {
965                crate::doc::DOC_HEAD
966            },
967        );
968        let text = crate::doc::text_node(span, text);
969        self.end_of_statement(&[])?;
970        if module {
971            if !first {
972                return Err(fail(
973                    "`@moduledoc` is the first form of a file: it documents the whole file",
974                    span,
975                ));
976            }
977            return Ok(list_at(span, vec![head, text]));
978        }
979        self.skip_newlines();
980        if matches!(self.peek(), TokenKind::Doc { .. } | TokenKind::Eof) {
981            return Err(fail(
982                "`@doc` documents the definition below it, and none follows",
983                span,
984            ));
985        }
986        let def = self.statement()?;
987        self.end_of_statement(&[])?;
988        if !crate::doc::is_definition(&def) {
989            return Err(fail(
990                "`@doc` documents the definition below it: a `def`, a `defmacro` or a \
991                 top-level `name = value`",
992                span,
993            ));
994        }
995        Ok(list_at(
996            Span::new(span.start, def.span.end),
997            vec![head, text, def],
998        ))
999    }
1000
1001    /// **A statement ends at the end of its line.** Refuse anything else.
1002    ///
1003    /// The lexer has always said newlines "are statement separators", and the
1004    /// parser never asked for one: `program` and `body` looped over
1005    /// `statement()` and started the next one wherever the last stopped. So a
1006    /// form blue does not have became two forms it does, silently —
1007    /// `y = xs[0]` parsed as `y = xs` then the list `[0]`, and Ruby's
1008    /// `a = f x` as `a = f` then `x`. Both ran; both bound the wrong value.
1009    ///
1010    /// **Refused rather than given a meaning**, because each would be a second
1011    /// spelling of a tree blue already spells one way (§0's FORM axis):
1012    /// indexing is the call `nth(i, xs)`, and a call has parentheses. `;` is
1013    /// refused by the lexer for the same reason — one separator, the newline.
1014    ///
1015    /// What may follow a statement: a newline, the end of the file, or — in a
1016    /// body — the keyword that closes it, which is what keeps
1017    /// `fn(x) x + 1 end` a one-line lambda.
1018    fn end_of_statement(&self, terminators: &[&str]) -> Result<(), Fail> {
1019        let next = self.peek();
1020        if matches!(next, TokenKind::Newline | TokenKind::Eof)
1021            || terminators.iter().any(|t| self.at_ident(t))
1022        {
1023            return Ok(());
1024        }
1025        let prev = self.toks.get(self.pos.wrapping_sub(1)).map(|t| &t.kind);
1026        let prev_name = match prev {
1027            Some(TokenKind::Ident(n)) => Some(n.as_str()),
1028            _ => None,
1029        };
1030        let callee = prev_name.unwrap_or("f");
1031        let why = match (prev, next) {
1032            (Some(TokenKind::Ident(t)), _) if t == "then" => {
1033                "blue's `if` has no `then`: put the branch on the next line".to_string()
1034            }
1035            (_, TokenKind::Ident(d)) if d == "do" => "blue has no `do` blocks: pass a function \
1036                 as an argument, `f(xs, fn(x) … end)`"
1037                .to_string(),
1038            (_, TokenKind::LBracket) => {
1039                let index = match (self.toks.get(self.pos + 1), self.toks.get(self.pos + 2)) {
1040                    (Some(i), Some(close)) if close.kind == TokenKind::RBracket => match &i.kind {
1041                        TokenKind::Int(n) => n.to_string(),
1042                        TokenKind::Ident(n) => n.clone(),
1043                        _ => "i".to_string(),
1044                    },
1045                    _ => "i".to_string(),
1046                };
1047                let list = prev_name.unwrap_or("xs");
1048                format!(
1049                    "an index touches what it indexes: write `{list}[{index}]`, with no space \
1050                     before `[`"
1051                )
1052            }
1053            (_, TokenKind::LBrace) => "blue has no brace blocks: pass a function as an \
1054                 argument, `map(xs, fn(x) … end)`"
1055                .to_string(),
1056            (
1057                Some(TokenKind::Ident(_)),
1058                TokenKind::Ident(_)
1059                | TokenKind::Int(_)
1060                | TokenKind::Float(_)
1061                | TokenKind::Str(_)
1062                | TokenKind::InterpolatedStr { .. }
1063                | TokenKind::Sym(_)
1064                | TokenKind::True
1065                | TokenKind::False
1066                | TokenKind::Nil,
1067            ) => {
1068                let arg = match next {
1069                    TokenKind::Ident(a) => a.clone(),
1070                    _ => "x".to_string(),
1071                };
1072                format!("a call needs parentheses: write `{callee}({arg})`")
1073            }
1074            _ => "put each statement on its own line".to_string(),
1075        };
1076        Err(self.error(format!("expected the end of the line, found {next}: {why}")))
1077    }
1078
1079    /// A statement: either a binding or an expression.
1080    ///
1081    /// `x = 5` lowers to `(define x 5)`. Blue had NO way to name a value — a
1082    /// capability probe found `x = 5` was a parse error, which makes every
1083    /// program a single expression. That is more fundamental than anything else
1084    /// the probe found.
1085    ///
1086    /// Only at STATEMENT position, never inside an expression, so `f(x = 1)` is
1087    /// still an error rather than a silent binding. Ruby allows assignment as an
1088    /// expression and it is a well-known footgun — `if x = 1` where `==` was
1089    /// meant. Blue declines it, and the cost is only that a walrus-style idiom
1090    /// has to be two lines.
1091    fn statement(&mut self) -> Result<Spanned, Fail> {
1092        // The SECOND recursion cycle, and it needs the same guard as `expr`.
1093        //
1094        // Guarding `expr` alone was not enough — measured 2026-08-01: with the
1095        // expression bound in place, `"def a\n".repeat(2_000)` STILL aborted
1096        // the process. Block nesting (`def` opening a body that contains more
1097        // statements) recurses through here, not through `expr`, so a fix
1098        // applied to one cycle silently left the other reachable. Two paths to
1099        // the same crash; one guard covered one of them.
1100        //
1101        // Shares `self.depth` with `expr` on purpose: what the stack cares
1102        // about is TOTAL nesting, not which grammar production produced it, so
1103        // two independent counters would each permit their own full budget and
1104        // together exceed what the stack can hold.
1105        let max = self.max_depth;
1106        if self.depth >= max {
1107            return Err(self.error(format!(
1108                "statement nests deeper than {max}; refusing to \
1109                 recurse further (this is a limit, not a syntax error)"
1110            )));
1111        }
1112        self.depth += 1;
1113        let r = self.statement_inner();
1114        self.depth -= 1;
1115        r
1116    }
1117
1118    fn statement_inner(&mut self) -> Result<Spanned, Fail> {
1119        if let TokenKind::Ident(name) = self.peek().clone() {
1120            if self.peek_at(1) == "=" && !is_reserved_word(&name) {
1121                let name_span = self.peek_span();
1122                self.bump(); // name
1123                self.bump(); // =
1124                self.skip_newlines();
1125                let value = self.expr(0)?;
1126                // `define` is synthesized — `x = 5` contains no such word — so
1127                // it takes the span of the name being bound, which is what a
1128                // reader looks at when told something about the binding.
1129                return Ok(list_at(
1130                    self.span_since(name_span.start),
1131                    vec![sym_at(name_span, "define"), sym_at(name_span, &name), value],
1132                ));
1133            }
1134        }
1135        let e = self.expr(0)?;
1136        if let SpannedForm::List(items) = &e.form {
1137            if items.len() == 3
1138                && items[0].as_symbol() == Some("define")
1139                && items[1].as_symbol().is_some()
1140                && self.text(items[0].span) == "define"
1141            {
1142                self.note(Spelling::OperatorSpelling, e.span, "define(x, v)", "x = v");
1143            }
1144        }
1145        Ok(e)
1146    }
1147
1148    /// The token `n` positions ahead, for the two-token lookahead a binding
1149    /// needs. Returns `Eof` past the end rather than panicking.
1150    fn peek_at(&self, n: usize) -> String {
1151        match self.toks.get(self.pos + n).map(|t| &t.kind) {
1152            Some(TokenKind::Op(o)) => o.clone(),
1153            _ => String::new(),
1154        }
1155    }
1156
1157    /// Pratt loop.
1158    fn expr(&mut self, min_bp: u8) -> Result<Spanned, Fail> {
1159        // Depth guard at the single recursion cycle (`expr` -> `prefix` ->
1160        // `expr`). Returning an Err here converts an UNRECOVERABLE abort into
1161        // an ordinary parse failure a caller can render — the difference
1162        // between an LSP showing a squiggle and an LSP being gone.
1163        //
1164        // The decrement is deliberately not RAII: every exit from this
1165        // function is via `?` or a normal return, and both are covered by the
1166        // explicit decrements below. A guard object would be tidier but would
1167        // also hide the invariant this comment is here to state.
1168        let max = self.max_depth;
1169        if self.depth >= max {
1170            return Err(self.error(format!(
1171                "expression nests deeper than {max}; refusing to \
1172                 recurse further (this is a limit, not a syntax error)"
1173            )));
1174        }
1175        self.depth += 1;
1176        let r = self.expr_inner(min_bp);
1177        self.depth -= 1;
1178        r
1179    }
1180
1181    #[inline(never)]
1182    fn rescue_node(&self, start: usize, op_span: Span, lhs: Spanned, fallback: Spanned) -> Spanned {
1183        list_at(
1184            self.span_since(start),
1185            vec![
1186                sym_at(op_span, "try"),
1187                lhs,
1188                list_at(
1189                    op_span.merge(fallback.span),
1190                    vec![
1191                        sym_at(op_span, "catch"),
1192                        list_at(op_span, vec![sym_at(op_span, "_")]),
1193                        fallback,
1194                    ],
1195                ),
1196            ],
1197        )
1198    }
1199
1200    #[inline(never)]
1201    fn infix_spelling(&mut self, callee: Option<&str>, op_span: Span) {
1202        let written = self.text(op_span).to_string();
1203        match (callee, self.peek().clone()) {
1204            (None, _) => self.note(Spelling::CallForm, op_span, "|>", "a call"),
1205            (Some(c), TokenKind::Op(o)) if word_for(&o) != o => {
1206                self.note(Spelling::LogicalSymbol, op_span, &written, c);
1207            }
1208            (Some(_), TokenKind::Op(o)) if written != o => {
1209                self.note(Spelling::OperatorSpelling, op_span, &written, &o);
1210            }
1211            _ => {}
1212        }
1213    }
1214
1215    #[inline(never)]
1216    fn nil_test(
1217        &mut self,
1218        start: usize,
1219        op_span: Span,
1220        lhs: &Spanned,
1221        rhs: &Spanned,
1222    ) -> Option<Spanned> {
1223        let (subject, written) = match (&lhs.form, &rhs.form) {
1224            (_, SpannedForm::Nil) if !matches!(lhs.form, SpannedForm::Nil) => (lhs, "x == nil"),
1225            (SpannedForm::Nil, _) if !matches!(rhs.form, SpannedForm::Nil) => (rhs, "nil == x"),
1226            _ => return None,
1227        };
1228        let span = self.span_since(start);
1229        self.note(Spelling::NilTest, span, written, "x.nil?");
1230        Some(list_at(
1231            span,
1232            vec![
1233                sym_at(op_span, LOWERED_FIELD),
1234                subject.clone(),
1235                atom_at(op_span, Atom::Keyword("nil?".to_string())),
1236            ],
1237        ))
1238    }
1239
1240    #[inline(never)]
1241    fn infix_node(
1242        &mut self,
1243        start: usize,
1244        callee: Option<&str>,
1245        op_span: Span,
1246        lhs: Spanned,
1247        rhs: Spanned,
1248    ) -> Spanned {
1249        if callee == Some("-") && matches!(lhs.form, SpannedForm::Atom(Atom::Int(0))) {
1250            self.note(
1251                Spelling::OperatorSpelling,
1252                lhs.span.merge(op_span),
1253                "0 - x",
1254                "-x",
1255            );
1256        }
1257
1258        if callee == Some("equal?") {
1259            if let Some(test) = self.nil_test(start, op_span, &lhs, &rhs) {
1260                return test;
1261            }
1262        }
1263
1264        if callee.is_none() {
1265            // `x |> f`      => (f x)
1266            // `x |> f(a)`   => (f x a)   — the pipeline threads into
1267            //                  the FIRST argument position, as Elixir's
1268            //                  does; that is what makes it composable.
1269            let rhs_span = rhs.span;
1270            let threaded = match rhs.form {
1271                SpannedForm::List(mut items) if !items.is_empty() => {
1272                    items.insert(1, lhs);
1273                    list_at(self.span_since(start), items)
1274                }
1275                callee => list_at(
1276                    self.span_since(start),
1277                    vec![Spanned::new(rhs_span, callee), lhs],
1278                ),
1279            };
1280            match &threaded.form {
1281                SpannedForm::List(items)
1282                    if items.len() == 2 && items[0].as_symbol() == Some("not") =>
1283                {
1284                    let (head, operand) = (items[0].span, items[1].clone());
1285                    self.negation(head, threaded.span, operand)
1286                }
1287                SpannedForm::List(items)
1288                    if items.len() == 4
1289                        && items[0].as_symbol() == Some("if")
1290                        && matches!(items[3].form, SpannedForm::Nil) =>
1291                {
1292                    list_at(threaded.span, items[..3].to_vec())
1293                }
1294                SpannedForm::List(items)
1295                    if items.len() == 3 && items[0].as_symbol() == Some("equal?") =>
1296                {
1297                    let (op, a, b) = (items[0].span, items[1].clone(), items[2].clone());
1298                    match self.nil_test(start, op, &a, &b) {
1299                        Some(test) => test,
1300                        None => threaded,
1301                    }
1302                }
1303                _ => threaded,
1304            }
1305        } else {
1306            // The callee symbol takes the OPERATOR's span, not the whole
1307            // expression's: `a + b` lowers to `(+ a b)` and the `+` node is
1308            // the one byte-range in the source that means it. Handing it the
1309            // whole expression's span would make a diagnostic about the
1310            // operator underline both operands too.
1311            list_at(
1312                self.span_since(start),
1313                vec![sym_at(op_span, callee.unwrap_or_default()), lhs, rhs],
1314            )
1315        }
1316    }
1317
1318    fn expr_inner(&mut self, min_bp: u8) -> Result<Spanned, Fail> {
1319        let start = self.mark();
1320        let mut lhs = self.prefix()?;
1321
1322        loop {
1323            // Postfix: `.name`, `.name(args)`, `(args)`
1324            match self.peek() {
1325                TokenKind::Dot => {
1326                    let dot = self.peek_span();
1327                    self.bump();
1328                    lhs = self.finish_send(start, lhs, dot)?;
1329                    continue;
1330                }
1331                TokenKind::LParen | TokenKind::LBracket
1332                    if self.at(&TokenKind::LParen) || self.touches_previous() =>
1333                {
1334                    lhs = self.applied(start, lhs)?;
1335                    continue;
1336                }
1337                _ => {}
1338            }
1339
1340            // Infix
1341            // `callee == None` marks the pipeline, which is a rewrite rather
1342            // than a call.
1343            let op_span = self.peek_span();
1344            if self.at_ident("rescue") {
1345                if RESCUE_POWER.0 < min_bp {
1346                    break;
1347                }
1348                self.bump();
1349                self.skip_newlines();
1350                let fallback = self.expr(RESCUE_POWER.1)?;
1351                lhs = self.rescue_node(start, op_span, lhs, fallback);
1352                continue;
1353            }
1354            let (callee, (lbp, rbp)) = match self.peek() {
1355                TokenKind::Pipe => (None, PIPE_POWER),
1356                other => match infix_of(other) {
1357                    Some(i) => (Some(i.callee), i.power),
1358                    None => break,
1359                },
1360            };
1361            if lbp < min_bp {
1362                break;
1363            }
1364            self.infix_spelling(callee, op_span);
1365            self.bump();
1366            self.skip_newlines();
1367            let rhs = self.expr(rbp)?;
1368            lhs = self.infix_node(start, callee, op_span, lhs, rhs);
1369        }
1370
1371        Ok(lhs)
1372    }
1373
1374    #[inline(never)]
1375    fn interpolation(span: Span, parts: &[String], exprs: &[String]) -> Result<Spanned, Fail> {
1376        // Every node here carries the WHOLE string literal's span.
1377        //
1378        // The inner expression is parsed from `raw` — a substring — so
1379        // its own offsets index that substring, not `src`. Carrying them
1380        // through would produce spans that look real and point into a
1381        // buffer nobody has: for `"a#{x}"` at offset 40, `x`'s span
1382        // would be 0..1, i.e. the start of the file. The lexer does not
1383        // record where each part sat in the outer source, so the string
1384        // literal is the most precise honest answer available.
1385        let mut acc = atom_at(span, Atom::Str(parts[0].clone()));
1386        for (i, raw) in exprs.iter().enumerate() {
1387            let inner = parse_expr(raw).map_err(|e| {
1388                fail(
1389                    format!("in interpolation `#{{{raw}}}`: {}", e.message),
1390                    span,
1391                )
1392            })?;
1393            let inner = Spanned::from_sexp_at(&inner, span);
1394            acc = list_at(span, vec![sym_at(span, LOWERED_CONCAT), acc, inner]);
1395            // `parts.len() == exprs.len() + 1` by construction, so this
1396            // index is always in range.
1397            acc = list_at(
1398                span,
1399                vec![
1400                    sym_at(span, LOWERED_CONCAT),
1401                    acc,
1402                    atom_at(span, Atom::Str(parts[i + 1].clone())),
1403                ],
1404            );
1405        }
1406        Ok(acc)
1407    }
1408
1409    /// A string literal holding a `\n` is read as the lines it spells
1410    /// (B0065): `"a\nb"` is `join_lines(["a", "b"])`, text ending in a newline
1411    /// is `unlines([…])` without the empty last line, and `"\n"` alone is
1412    /// `line_break`. A line that is one interpolation, `#{x}`, is `x` itself:
1413    /// `join_lines` renders each element as interpolation does. So the escape
1414    /// and the call are one tree, and `blue fmt` writes the call.
1415    #[inline(never)]
1416    fn lines_literal(
1417        &mut self,
1418        span: Span,
1419        parts: Vec<String>,
1420        exprs: Vec<String>,
1421    ) -> Result<Spanned, Fail> {
1422        let mut lines: Vec<(Vec<String>, Vec<String>)> = vec![(vec![String::new()], Vec::new())];
1423        for (i, part) in parts.iter().enumerate() {
1424            let mut pieces = part.split('\n');
1425            if let Some(head) = pieces.next() {
1426                if let Some(last) = lines.last_mut().and_then(|l| l.0.last_mut()) {
1427                    last.push_str(head);
1428                }
1429            }
1430            for piece in pieces {
1431                lines.push((vec![piece.to_string()], Vec::new()));
1432            }
1433            if let Some(raw) = exprs.get(i) {
1434                if let Some(line) = lines.last_mut() {
1435                    line.1.push(raw.clone());
1436                    line.0.push(String::new());
1437                }
1438            }
1439        }
1440        let empty = |l: &(Vec<String>, Vec<String>)| l.1.is_empty() && l.0 == [""];
1441        if lines.len() == 2 && lines.iter().all(empty) {
1442            self.note(Spelling::NewlineEscape, span, "\"\\n\"", "line_break");
1443            return Ok(sym_at(span, "line_break"));
1444        }
1445        let trailing = lines.last().is_some_and(empty);
1446        if trailing {
1447            lines.pop();
1448        }
1449        let head = if trailing { "unlines" } else { "join_lines" };
1450        let mut items = vec![sym_at(span, "list")];
1451        for (lits, raws) in &lines {
1452            let item = if raws.is_empty() {
1453                atom_at(span, Atom::Str(lits[0].clone()))
1454            } else if raws.len() == 1 && lits.iter().all(String::is_empty) {
1455                let inner = parse_expr(&raws[0]).map_err(|e| {
1456                    fail(
1457                        format!("in interpolation `#{{{}}}`: {}", raws[0], e.message),
1458                        span,
1459                    )
1460                })?;
1461                Spanned::from_sexp_at(&inner, span)
1462            } else {
1463                Self::interpolation(span, lits, raws)?
1464            };
1465            items.push(item);
1466        }
1467        self.note(
1468            Spelling::NewlineEscape,
1469            span,
1470            "\"…\\n…\"",
1471            &format!("{head}([…])"),
1472        );
1473        Ok(list_at(
1474            span,
1475            vec![sym_at(span, head), list_at(span, items)],
1476        ))
1477    }
1478
1479    /// `f(args)` or `x[k]` after `lhs`. One out-of-line step for both, so
1480    /// `expr_inner`, whose frame the depth bound is measured against, holds
1481    /// one result slot for them rather than one per form.
1482    #[inline(never)]
1483    fn applied(&mut self, start: usize, lhs: Spanned) -> Result<Spanned, Fail> {
1484        if self.at(&TokenKind::LParen) {
1485            let (args, splat) = self.call_args()?;
1486            let call = self.call_node(self.span_since(start), vec![lhs], args, splat);
1487            Ok(self.call_spelling(call))
1488        } else {
1489            self.index(start, lhs)
1490        }
1491    }
1492
1493    /// `x[k]`: `get(x, k)` for a keyword or string literal key, else
1494    /// `nth(k, x)` (B0066).
1495    #[inline(never)]
1496    fn index(&mut self, start: usize, object: Spanned) -> Result<Spanned, Fail> {
1497        let open = self.peek_span();
1498        self.bump();
1499        self.skip_newlines();
1500        let key = self.expr(0)?;
1501        self.skip_newlines();
1502        self.expect(&TokenKind::RBracket, "`]` closing the index")?;
1503        let span = self.span_since(start);
1504        Ok(if is_index_key(&key) {
1505            list_at(span, vec![sym_at(open, "get"), object, key])
1506        } else {
1507            list_at(span, vec![sym_at(open, "nth"), key, object])
1508        })
1509    }
1510
1511    #[inline(never)]
1512    fn not_prefix(&mut self, span: Span) -> Result<Spanned, Fail> {
1513        if self.at(&TokenKind::LParen) && self.touches_previous() {
1514            self.note(Spelling::OperatorSpelling, span, "not(x)", "not x");
1515            let (args, splat) = self.call_args()?;
1516            if args.len() != 1 || splat.is_some() {
1517                let call = self.call_node(
1518                    self.span_since(span.start),
1519                    vec![sym_at(span, "not")],
1520                    args,
1521                    splat,
1522                );
1523                return Ok(call);
1524            }
1525            let operand = args.into_iter().next().expect("one argument");
1526            return Ok(self.negation(span, self.span_since(span.start), operand));
1527        }
1528        let rhs = self.expr(11)?;
1529        Ok(self.negation(span, self.span_since(span.start), rhs))
1530    }
1531
1532    fn prefix(&mut self) -> Result<Spanned, Fail> {
1533        if self.at(&TokenKind::LParen) {
1534            let span = self.peek_span();
1535            self.bump();
1536            if self.arrow_lambda_ahead() {
1537                return self.arrow_lambda(span);
1538            }
1539            return self.group();
1540        }
1541        self.prefix_token()
1542    }
1543
1544    fn group(&mut self) -> Result<Spanned, Fail> {
1545        self.skip_newlines();
1546        let inner = self.expr(0)?;
1547        self.skip_newlines();
1548        self.expect(&TokenKind::RParen, "`)`")?;
1549        Ok(inner)
1550    }
1551
1552    #[inline(never)]
1553    fn prefix_token(&mut self) -> Result<Spanned, Fail> {
1554        let span = self.peek_span();
1555        match self.bump() {
1556            TokenKind::Int(v) => Ok(atom_at(span, Atom::Int(v))),
1557            TokenKind::Float(v) => Ok(atom_at(span, Atom::Float(v))),
1558            TokenKind::Str(s) if self.quoting == 0 && s.contains('\n') => {
1559                self.lines_literal(span, vec![s], Vec::new())
1560            }
1561            TokenKind::Str(s) => Ok(atom_at(span, Atom::Str(s))),
1562            TokenKind::Doc { module, .. } => Err(fail(
1563                format!(
1564                    "`{}` sits at the top level, above the definition it documents, never \
1565                     inside a form",
1566                    if module { "@moduledoc" } else { "@doc" }
1567                ),
1568                span,
1569            )),
1570
1571            // `"a#{x}b"` → `(concat (concat "a" x) "b")`.
1572            //
1573            // Lowered to `concat`, not to `+`: blue's `+` is arithmetic (see
1574            // the INFIX table), and interpolation must render a value of ANY
1575            // type — `concat` goes through `to_s`, which is what makes
1576            // `"n=#{42}"` work.
1577            //
1578            // The expression source is parsed HERE with the ordinary parser
1579            // rather than lexed inside the string, so an interpolation can hold
1580            // anything an expression can and the two can never drift.
1581            TokenKind::InterpolatedStr { parts, exprs }
1582                if self.quoting == 0 && parts.iter().any(|p| p.contains('\n')) =>
1583            {
1584                self.lines_literal(span, parts, exprs)
1585            }
1586            TokenKind::InterpolatedStr { parts, exprs } => Self::interpolation(span, &parts, &exprs),
1587            TokenKind::Sym(s) => Ok(atom_at(span, Atom::Keyword(s))),
1588            TokenKind::True => Ok(atom_at(span, Atom::Bool(true))),
1589            TokenKind::False => Ok(atom_at(span, Atom::Bool(false))),
1590            TokenKind::Nil => Ok(Spanned::new(span, SpannedForm::Nil)),
1591
1592            TokenKind::Op(o) if o == "-" => {
1593                let rhs = self.expr(11)?; // binds tighter than `*`
1594                Ok(list_at(
1595                    self.span_since(span.start),
1596                    vec![sym_at(span, "-"), atom_at(span, Atom::Int(0)), rhs],
1597                ))
1598            }
1599            TokenKind::Op(o) if o == "!" => {
1600                let written = self.text(span).to_string();
1601                self.note(Spelling::LogicalSymbol, span, &written, "not");
1602                let rhs = self.expr(11)?;
1603                Ok(self.negation(span, self.span_since(span.start), rhs))
1604            }
1605            TokenKind::Ident(w) if w == "not" => self.not_prefix(span),
1606            TokenKind::Ident(w) if (w == "and" || w == "or") && self.at(&TokenKind::LParen) => {
1607                Ok(sym_at(span, &w))
1608            }
1609            TokenKind::Ident(w) if w == "and" || w == "or" => Err(fail(
1610                format!("`{w}` joins two expressions: `a {w} b`"),
1611                span,
1612            )),
1613
1614            TokenKind::LParen => {
1615                self.skip_newlines();
1616                let inner = self.expr(0)?;
1617                self.skip_newlines();
1618                self.expect(&TokenKind::RParen, "`)`")?;
1619                // The inner expression's own span, NOT one widened to include
1620                // the parentheses: grouping is not part of the expression's
1621                // meaning, and `(a + b)` should underline `a + b`.
1622                Ok(inner)
1623            }
1624
1625            TokenKind::LBracket => self.list_literal(span),
1626            TokenKind::LBrace => self.map_literal(span),
1627
1628            TokenKind::Ident(name) if self.at(&TokenKind::PathSep) => {
1629                self.qualified_name(span, &name)
1630            }
1631            TokenKind::PathSep => Err(fail(
1632                "a qualified name is `package::name`, with the package written before `::`",
1633                span,
1634            )),
1635            TokenKind::Ident(name) => match name.as_str() {
1636                "if" => self.if_form(span, false),
1637                "begin" if !(self.at(&TokenKind::LParen) && self.touches_previous()) => {
1638                    self.begin_form(span)
1639                }
1640                "rescue" | "ensure" => Err(fail(
1641                    format!("`{name}` belongs to a `begin … end` block or a `def` body, after the statements it protects"),
1642                    span,
1643                )),
1644                "unless" => {
1645                    self.note(Spelling::Unless, span, "unless", "if not");
1646                    self.if_form(span, true)
1647                }
1648                "def" => self.def_form(span),
1649                "defmacro" => self.defmacro_form(span),
1650                "case" => self.case_form(span),
1651                "fn" => self.lambda_form(span),
1652                "test" => self.test_form(span),
1653                "assert" => self.assert_form(span),
1654                "quote" => self.quote_form(span),
1655                "unquote" => self.unquote_form(span, false),
1656                "unquote_splice" => self.unquote_form(span, true),
1657                "do" => Err(fail(
1658                    "blue has no `do` blocks: pass a function as an argument, \
1659                     `f(xs, fn(x) … end)`",
1660                    span,
1661                )),
1662                "end" => Err(fail(
1663                    "unexpected `end`: nothing open here for it to close",
1664                    span,
1665                )),
1666                _ => Ok(sym_at(span, &name)),
1667            },
1668
1669            other => Err(fail(format!("expected an expression, found {other}"), span)),
1670        }
1671    }
1672
1673    /// After `package`, at `::`: `retsu::first` lowers to the ONE symbol
1674    /// `retsu/first` — tatara's `require` shape, so a qualified name means the
1675    /// same thing in both lisps.
1676    ///
1677    /// After `::` any identifier is a name, reserved words included:
1678    /// `kueri::if` names kueri's definition, never the `if` form, because a
1679    /// reserved word is reserved only where it could start a form. The
1680    /// package side is never a reserved word, and a name has exactly one
1681    /// qualifier (`a::b::c` is refused), since a package is one level deep.
1682    fn qualified_name(&mut self, pkg_span: Span, pkg: &str) -> Result<Spanned, Fail> {
1683        if is_reserved_word(pkg) {
1684            return Err(fail(
1685                format!("`{pkg}` is a reserved word and cannot name a package"),
1686                pkg_span,
1687            ));
1688        }
1689        self.bump(); // ::
1690        let name_span = self.peek_span();
1691        let name = match self.bump() {
1692            TokenKind::Ident(n) => n,
1693            // `true`, `false` and `nil` lex as their own tokens.
1694            TokenKind::True => "true".to_string(),
1695            TokenKind::False => "false".to_string(),
1696            TokenKind::Nil => "nil".to_string(),
1697            other => {
1698                return Err(fail(
1699                    format!("expected a name after `{pkg}::`, found {other}"),
1700                    name_span,
1701                ))
1702            }
1703        };
1704        if self.at(&TokenKind::PathSep) {
1705            return Err(self.error(format!(
1706                "a qualified name has one qualifier: `package::name`, and `{pkg}::{name}::…` has two"
1707            )));
1708        }
1709        Ok(sym_at(
1710            self.span_since(pkg_span.start),
1711            &qualify(pkg, &name),
1712        ))
1713    }
1714
1715    /// After a `.`: `recv.name` or `recv.name(args)`.
1716    ///
1717    /// **A bare `recv.name` is a SEND, not a field read.** Blue commits to
1718    /// the uniform access principle here: a structure exposes no public
1719    /// fields, so a field can later become a computed method without
1720    /// breaking a caller.
1721    #[inline(never)]
1722    fn negation(&mut self, head: Span, whole: Span, operand: Spanned) -> Spanned {
1723        if let SpannedForm::List(items) = &operand.form {
1724            let flipped = match items.first().and_then(Spanned::as_symbol) {
1725                Some("equal?") => Some("not="),
1726                Some("not=") => Some("equal?"),
1727                _ => None,
1728            };
1729            if let (Some(to), 3) = (flipped, items.len()) {
1730                let (written, canonical) = if to == "not=" {
1731                    ("not (a == b)", "a != b")
1732                } else {
1733                    ("not (a != b)", "a == b")
1734                };
1735                self.note(Spelling::NegatedComparison, whole, written, canonical);
1736                let mut out = items.clone();
1737                out[0] = sym_at(items[0].span, to);
1738                if to == "equal?" {
1739                    if let Some(test) =
1740                        self.nil_test(whole.start, items[0].span, &items[1], &items[2])
1741                    {
1742                        return test;
1743                    }
1744                }
1745                return list_at(whole, out);
1746            }
1747        }
1748        list_at(whole, vec![sym_at(head, "not"), operand])
1749    }
1750
1751    #[inline(never)]
1752    fn call_spelling(&mut self, call: Spanned) -> Spanned {
1753        let SpannedForm::List(items) = &call.form else {
1754            return call;
1755        };
1756        let Some(head) = items.first().and_then(Spanned::as_symbol) else {
1757            return call;
1758        };
1759        let argc = items.len() - 1;
1760        if head == "get" && argc == 2 && is_index_key(&items[2]) {
1761            self.note(Spelling::Index, call.span, "get(m, :k)", "m[:k]");
1762            return call;
1763        }
1764        if head == "nth" && argc == 2 && !is_index_key(&items[1]) {
1765            self.note(Spelling::Index, call.span, "nth(i, xs)", "xs[i]");
1766            return call;
1767        }
1768        if head == "equal?" && argc == 2 {
1769            let (op_span, start) = (items[0].span, call.span.start);
1770            if let Some(test) = self.nil_test(start, op_span, &items[1], &items[2]) {
1771                return test;
1772            }
1773        }
1774        let operator = match (head, argc) {
1775            ("and" | "or" | "mod" | "equal?", 2) => Some(head),
1776            ("list", _) => Some("list"),
1777            _ => None,
1778        };
1779        if let Some(op) = operator {
1780            let canonical = match op {
1781                "list" => "[…]".to_string(),
1782                "mod" => "a % b".to_string(),
1783                "equal?" => "a == b".to_string(),
1784                other => format!("a {other} b"),
1785            };
1786            self.note(
1787                Spelling::OperatorSpelling,
1788                call.span,
1789                &format!("{head}(…)"),
1790                &canonical,
1791            );
1792            return call;
1793        }
1794        if head == "apply"
1795            && self.text(items[0].span) == "apply"
1796            && argc >= 2
1797            && items[1].as_symbol().is_some_and(is_callable_name)
1798        {
1799            self.note(Spelling::Apply, call.span, "apply(f, …, xs)", "f(…, *xs)");
1800            return call;
1801        }
1802        if head == "try" {
1803            return self.try_spelling(call);
1804        }
1805        call
1806    }
1807
1808    fn try_spelling(&mut self, call: Spanned) -> Spanned {
1809        let SpannedForm::List(items) = &call.form else {
1810            return call;
1811        };
1812        let Some((catch, body)) = items[1..].split_last() else {
1813            return call;
1814        };
1815        let Some(clause) = catch.as_list() else {
1816            return call;
1817        };
1818        let binder = match clause {
1819            [head, binding, handler @ ..]
1820                if head.as_symbol() == Some("catch") && !handler.is_empty() =>
1821            {
1822                match binding.as_list() {
1823                    Some([b]) => b.as_symbol().map(|n| (n.to_string(), b.span)),
1824                    _ => None,
1825                }
1826            }
1827            _ => None,
1828        };
1829        let Some((name, binder_span)) = binder else {
1830            return call;
1831        };
1832        if body.is_empty() {
1833            return call;
1834        }
1835        self.note(Spelling::TryCatch, call.span, "try(…, catch(…))", "rescue");
1836        let handler = &clause[2..];
1837        let rename =
1838            name.starts_with('_') && name != "_" && !handler.iter().any(|h| mentions(h, &name));
1839        let body = if body.len() == 1 {
1840            body[0].clone()
1841        } else {
1842            let span = cover(body, call.span);
1843            let mut list = vec![sym_at(Span::new(span.start, span.start), "begin")];
1844            list.extend(body.iter().cloned());
1845            list_at(span, list)
1846        };
1847        let handler = if handler.len() == 1 {
1848            handler[0].clone()
1849        } else {
1850            let span = cover(handler, catch.span);
1851            let mut list = vec![sym_at(Span::new(span.start, span.start), "begin")];
1852            list.extend(handler.iter().cloned());
1853            list_at(span, list)
1854        };
1855        let binder = sym_at(binder_span, if rename { "_" } else { &name });
1856        list_at(
1857            call.span,
1858            vec![
1859                items[0].clone(),
1860                body,
1861                list_at(
1862                    catch.span,
1863                    vec![
1864                        clause[0].clone(),
1865                        list_at(clause[1].span, vec![binder]),
1866                        handler,
1867                    ],
1868                ),
1869            ],
1870        )
1871    }
1872
1873    fn finish_send(&mut self, start: usize, recv: Spanned, dot: Span) -> Result<Spanned, Fail> {
1874        let name_span = self.peek_span();
1875        let name = match self.bump() {
1876            // A RESERVED WORD is not a method name.
1877            //
1878            // Found by the formatter property suite, minimal input `1.def`.
1879            // The send parsed happily into `(def 1)` — `def` is just an
1880            // identifier to the lexer — and the formatter then rendered that
1881            // as `def(1)`, which the parser rejects. So `format` turned valid
1882            // source into source that does not parse: corruption, not a style
1883            // choice, and silent until a round-trip property looked.
1884            //
1885            // Rejecting here rather than teaching the formatter to quote it
1886            // fixes the class instead of the symptom: `x.if`, `x.end` and
1887            // `x.case` all lower onto special forms the same way, and none of
1888            // them is a method anyone meant to call.
1889            TokenKind::Ident(n) if is_reserved_word(&n) => {
1890                return Err(self.error(format!(
1891                    "`{n}` is a reserved word and cannot be a method name — \
1892                     `recv.{n}` would lower onto the `{n}` form itself"
1893                )))
1894            }
1895            TokenKind::Ident(n) => n,
1896            other => {
1897                return Err(fail(
1898                    format!("expected a method name after `.`, found {other}"),
1899                    name_span,
1900                ))
1901            }
1902        };
1903        if !self.at(&TokenKind::LParen) {
1904            return Ok(list_at(
1905                self.span_since(start),
1906                vec![
1907                    sym_at(dot, LOWERED_FIELD),
1908                    recv,
1909                    atom_at(name_span, Atom::Keyword(name)),
1910                ],
1911            ));
1912        }
1913        self.note(
1914            Spelling::CallForm,
1915            dot.merge(name_span),
1916            &format!("x.{name}(…)"),
1917            &format!("{name}(x, …)"),
1918        );
1919        let (args, splat) = self.call_args()?;
1920        Ok(self.call_node(
1921            self.span_since(start),
1922            vec![sym_at(name_span, &name), recv],
1923            args,
1924            splat,
1925        ))
1926    }
1927
1928    fn call_node(
1929        &self,
1930        span: Span,
1931        head: Vec<Spanned>,
1932        args: Vec<Spanned>,
1933        splat: Option<Span>,
1934    ) -> Spanned {
1935        let mut list = Vec::with_capacity(head.len() + args.len() + 1);
1936        if let Some(at) = splat {
1937            list.push(sym_at(at, "apply"));
1938        }
1939        list.extend(head);
1940        list.extend(args);
1941        list_at(span, list)
1942    }
1943
1944    fn call_args(&mut self) -> Result<(Vec<Spanned>, Option<Span>), Fail> {
1945        self.expect(&TokenKind::LParen, "`(`")?;
1946        let mut args = Vec::new();
1947        let mut splat = None;
1948        self.skip_newlines();
1949        if self.eat(&TokenKind::RParen) {
1950            return Ok((args, splat));
1951        }
1952        loop {
1953            self.skip_newlines();
1954            if splat.is_some() {
1955                return Err(
1956                    self.error("a splat `*xs` passes a list as the LAST arguments: write it last")
1957                );
1958            }
1959            if self.at_spread() || matches!(self.peek(), TokenKind::Label(_)) {
1960                let open = self.peek_span();
1961                let (segments, spread) = self.map_entries(open, &TokenKind::RParen)?;
1962                if !spread {
1963                    return Err(fail(
1964                        "a keyword entry in a call needs a `**` spread: pass a map, f({a: 1})",
1965                        open,
1966                    ));
1967                }
1968                args.push(self.merged(open, LOWERED_KWARGS, segments));
1969                return Ok((args, splat));
1970            }
1971            if matches!(self.peek(), TokenKind::Op(o) if o == "*") {
1972                splat = Some(self.peek_span());
1973                self.bump();
1974            }
1975            args.push(self.expr(0)?);
1976            self.skip_newlines();
1977            if self.eat(&TokenKind::Comma) {
1978                if self.trailing_comma(&TokenKind::RParen) {
1979                    break;
1980                }
1981                continue;
1982            }
1983            self.expect(&TokenKind::RParen, "`,` or `)`")?;
1984            break;
1985        }
1986        Ok((args, splat))
1987    }
1988
1989    fn trailing_comma(&mut self, closer: &TokenKind) -> bool {
1990        let comma = self
1991            .toks
1992            .get(self.pos.wrapping_sub(1))
1993            .map_or(self.peek_span(), |t| t.span);
1994        self.skip_newlines();
1995        if self.at(closer) {
1996            self.note(Spelling::TrailingComma, comma, ",", "");
1997            self.bump();
1998            return true;
1999        }
2000        false
2001    }
2002
2003    fn list_literal(&mut self, open: Span) -> Result<Spanned, Fail> {
2004        let mut items = vec![sym_at(open, "list")];
2005        self.skip_newlines();
2006        if self.eat(&TokenKind::RBracket) {
2007            return Ok(list_at(self.span_since(open.start), items));
2008        }
2009        loop {
2010            self.skip_newlines();
2011            items.push(self.expr(0)?);
2012            self.skip_newlines();
2013            if self.eat(&TokenKind::Comma) {
2014                if self.trailing_comma(&TokenKind::RBracket) {
2015                    break;
2016                }
2017                continue;
2018            }
2019            self.expect(&TokenKind::RBracket, "`,` or `]`")?;
2020            break;
2021        }
2022        Ok(list_at(self.span_since(open.start), items))
2023    }
2024
2025    /// `{a: 1, "k" => v}` — both spellings, one tree.
2026    ///
2027    /// This is §V.13's rendering law at the parser: `a: 1` and `:a => 1`
2028    /// produce the *same* s-expression, which is precisely why the
2029    /// formatter may always choose the shorthand. The rocket survives only
2030    /// where the key is not a plain symbol.
2031    fn map_literal(&mut self, open: Span) -> Result<Spanned, Fail> {
2032        self.skip_newlines();
2033        if self.eat(&TokenKind::RBrace) {
2034            return Ok(list_at(
2035                self.span_since(open.start),
2036                vec![sym_at(open, LOWERED_MAP)],
2037            ));
2038        }
2039        let (mut segments, spread) = self.map_entries(open, &TokenKind::RBrace)?;
2040        if !spread {
2041            return Ok(segments.remove(0));
2042        }
2043        Ok(self.merged(open, LOWERED_MERGE, segments))
2044    }
2045
2046    fn merged(&self, open: Span, head: &str, segments: Vec<Spanned>) -> Spanned {
2047        let mut items = vec![sym_at(open, head)];
2048        items.extend(segments);
2049        list_at(self.span_since(open.start), items)
2050    }
2051
2052    fn at_spread(&self) -> bool {
2053        matches!(self.peek(), TokenKind::Op(o) if o == "**")
2054    }
2055
2056    fn map_entries(
2057        &mut self,
2058        open: Span,
2059        closer: &TokenKind,
2060    ) -> Result<(Vec<Spanned>, bool), Fail> {
2061        let mut segments = Vec::new();
2062        let mut items = vec![sym_at(open, LOWERED_MAP)];
2063        let mut spread = false;
2064        loop {
2065            self.skip_newlines();
2066            if self.at_spread() {
2067                let star = self.peek_span();
2068                self.bump();
2069                let value = self.expr(0)?;
2070                if items.len() > 1 {
2071                    let span = items[1].span.merge(items[items.len() - 1].span);
2072                    items[0] = sym_at(items[1].span, LOWERED_MAP);
2073                    segments.push(list_at(span, std::mem::take(&mut items)));
2074                    items = vec![sym_at(open, LOWERED_MAP)];
2075                }
2076                segments.push(list_at(
2077                    star.merge(value.span),
2078                    vec![sym_at(star, LOWERED_SPLICE), value],
2079                ));
2080                spread = true;
2081            } else {
2082                self.map_entry(&mut items, closer)?;
2083            }
2084            self.skip_newlines();
2085            if self.eat(&TokenKind::Comma) {
2086                if self.trailing_comma(closer) {
2087                    break;
2088                }
2089                continue;
2090            }
2091            self.expect(closer, "`,` or the end of the entries")?;
2092            break;
2093        }
2094        if items.len() > 1 || !spread {
2095            let whole = self.span_since(open.start);
2096            segments.push(list_at(whole, items));
2097        }
2098        Ok((segments, spread))
2099    }
2100
2101    fn map_entry(&mut self, items: &mut Vec<Spanned>, closer: &TokenKind) -> Result<(), Fail> {
2102        match self.peek().clone() {
2103            TokenKind::Label(name) => {
2104                let label_span = self.peek_span();
2105                self.bump();
2106                self.skip_newlines();
2107                items.push(atom_at(label_span, Atom::Keyword(name.clone())));
2108                if matches!(self.peek(), TokenKind::Comma) || self.at(closer) {
2109                    items.push(sym_at(label_span, &name));
2110                } else {
2111                    let value = self.expr(0)?;
2112                    if matches!(&value.form, SpannedForm::Atom(Atom::Symbol(s)) if *s == name)
2113                        && label_name(&name)
2114                    {
2115                        let written = format!("{name}: {name}");
2116                        let canonical = format!("{name}:");
2117                        self.note(
2118                            Spelling::MapPun,
2119                            label_span.merge(value.span),
2120                            &written,
2121                            &canonical,
2122                        );
2123                    }
2124                    items.push(value);
2125                }
2126            }
2127            _ => {
2128                let k = self.expr(0)?;
2129                self.skip_newlines();
2130                if let SpannedForm::Atom(Atom::Keyword(name)) = &k.form {
2131                    if blue_lang_name(name) {
2132                        let written = format!(":{name} =>");
2133                        let canonical = format!("{name}:");
2134                        self.note(Spelling::KeywordRocket, k.span, &written, &canonical);
2135                    }
2136                }
2137                self.expect(&TokenKind::Rocket, "`=>` in a map literal")?;
2138                self.skip_newlines();
2139                items.push(k);
2140                items.push(self.expr(0)?);
2141            }
2142        }
2143        Ok(())
2144    }
2145
2146    /// `if c ... [else ...] end`, and `unless` as its negation.
2147    ///
2148    /// `unless` lowers to `(if (not c) ...)` rather than to a distinct
2149    /// form: one tree per meaning, so the formatter and every downstream
2150    /// tool see exactly one shape.
2151    /// An `elsif` arm: an `if` that does NOT consume the closing `end`.
2152    ///
2153    /// `if / elsif / elsif / else / end` is one `end` for the whole chain, so
2154    /// every arm but the first must leave it for its parent.
2155    fn if_chain(&mut self, head: Span) -> Result<Spanned, Fail> {
2156        let cond = self.expr(0)?;
2157        let then = self.body(&["elsif", "else", "end"])?;
2158        let els = self.else_part()?;
2159        let mut out = vec![sym_at(head, "if"), cond, then];
2160        if let Some(e) = els {
2161            out.push(e);
2162        }
2163        Ok(list_at(self.span_since(head.start), out))
2164    }
2165
2166    fn else_part(&mut self) -> Result<Option<Spanned>, Fail> {
2167        if self.at_ident("elsif") {
2168            let elsif = self.peek_span();
2169            self.bump();
2170            return Ok(Some(self.if_chain(elsif)?));
2171        }
2172        if !self.at_ident("else") {
2173            self.expect_ident("end")?;
2174            return Ok(None);
2175        }
2176        let else_span = self.peek_span();
2177        self.bump();
2178        let save = self.pos;
2179        self.skip_newlines();
2180        let leads_with_if = self.at_ident("if") || self.at_ident("unless");
2181        self.pos = save;
2182        let e = self.body(&["end"])?;
2183        let end_at = self.peek_span().start;
2184        self.expect_ident("end")?;
2185        if matches!(e.form, SpannedForm::Nil) && !self.comment_within(else_span.start, end_at) {
2186            self.note(Spelling::ElseNil, else_span, "else nil", "no else");
2187            return Ok(None);
2188        }
2189        let single_if = matches!(&e.form, SpannedForm::List(items)
2190            if (items.len() == 3 || items.len() == 4) && items[0].as_symbol() == Some("if"));
2191        if leads_with_if && single_if {
2192            self.note(Spelling::ElseIf, else_span, "else if", "elsif");
2193        }
2194        Ok(Some(e))
2195    }
2196
2197    fn if_form(&mut self, head: Span, negate: bool) -> Result<Spanned, Fail> {
2198        let cond = self.expr(0)?;
2199        let cond = if negate {
2200            // `unless c` lowers to `(if (not c) …)`. The synthesized `not` takes
2201            // the `unless` keyword's span — that word is what put it there.
2202            let inner = cond.span;
2203            self.negation(head, head.merge(inner), cond)
2204        } else {
2205            cond
2206        };
2207        // `elsif` terminates the then-body too, or the chain is swallowed.
2208        //
2209        // It used to be absent entirely — not a keyword, not reserved, nowhere
2210        // in this file — so `elsif cond` parsed as a stray expression inside
2211        // the then-body and the branch it guarded VANISHED. No error: the
2212        // program ran and returned the `else` value. Measured:
2213        //
2214        //   if a < 1 then 1 elsif a < 5 then 2 else 3 end   with a = 3
2215        //     wanted 2, returned 3
2216        //
2217        // A silent wrong answer in the most-used control form in the language,
2218        // reachable by writing the Ruby every blue user already knows.
2219        let then = self.body(&["elsif", "else", "end"])?;
2220        let els = self.else_part()?;
2221        let mut out = vec![sym_at(head, "if"), cond, then];
2222        if let Some(e) = els {
2223            out.push(e);
2224        }
2225        Ok(list_at(self.span_since(head.start), out))
2226    }
2227
2228    /// `def name(a, b) ... end`            => `(define (name a b) body)`
2229    /// `def name(a: T, b: T) -> R ... end`  => `(define-typed (name (a T) (b T)) R body)`
2230    ///
2231    /// **The two shapes are deliberately different heads.** §0 says an
2232    /// unannotated program gets ZERO analysis, and the cleanest way to
2233    /// mean that is for untyped code not to reach the typing machinery at
2234    /// all — not to reach it and be waved through. A checker that must
2235    /// walk every node to discover there is nothing to check has already
2236    /// paid the cost the ladder exists to avoid.
2237    ///
2238    /// Annotations are per-parameter, so a signature may be partially
2239    /// annotated. That is the ladder at its finest grain: `a: Int` is
2240    /// checked and a bare `b` stays `dyn`, in the same signature.
2241    /// `case subject / when a / … / else / … / end` => a `cond` over equality.
2242    ///
2243    /// **Value matching, not destructuring.** Elixir's `case` binds pattern
2244    /// variables; blue's compares with the same `equal?` the `==` operator uses,
2245    /// so `when [1, 2]` matches a list by value. Destructuring needs a pattern
2246    /// language and a binder, which blue does not have — and a `case` that
2247    /// *looked* like Elixir's while silently only comparing would be worse than
2248    /// one that plainly compares.
2249    ///
2250    /// The subject is evaluated ONCE, into a binding, so `case expensive()` does
2251    /// not re-run per arm. That is a correctness property, not an optimisation:
2252    /// a subject with a side effect would fire once per `when`.
2253    fn case_form(&mut self, head: Span) -> Result<Spanned, Fail> {
2254        let subject = self.expr(0)?;
2255        self.skip_newlines();
2256
2257        // A fresh name the surface cannot spell, so it cannot capture a user
2258        // binding of the same name.
2259        let subject_var = "case-subject";
2260        let mut arms: Vec<Spanned> = Vec::new();
2261        let mut otherwise: Option<Spanned> = None;
2262        // The `else` keyword's own span, so the synthesized `(else body)` clause
2263        // sits where the author wrote it rather than back at `case`.
2264        let mut else_kw: Option<Span> = None;
2265
2266        loop {
2267            self.skip_newlines();
2268            if self.at_ident("end") {
2269                break;
2270            }
2271            let maybe_else = self.peek_span();
2272            if self.eat_ident("else") {
2273                else_kw = Some(maybe_else);
2274                otherwise = Some(self.body(&["end"])?);
2275                continue;
2276            }
2277            let when = self.peek_span();
2278            if !self.eat_ident("when") {
2279                return Err(self.error(format!(
2280                    "expected `when`, `else` or `end` in a case, found {}",
2281                    self.peek()
2282                )));
2283            }
2284            self.skip_newlines();
2285            let pattern = self.expr(0)?;
2286            let body = self.body(&["when", "else", "end"])?;
2287            // The synthesized comparison takes the arm's `when` span: that word
2288            // is what put an `equal?` there, and it is where a reader looks when
2289            // told an arm cannot match.
2290            let test = list_at(
2291                when.merge(pattern.span),
2292                vec![sym_at(when, "equal?"), sym_at(when, subject_var), pattern],
2293            );
2294            arms.push(list_at(when.merge(body.span), vec![test, body]));
2295        }
2296        self.expect_ident("end")?;
2297
2298        if arms.is_empty() && otherwise.is_none() {
2299            return Err(self.error("a case needs at least one `when` or an `else`".to_string()));
2300        }
2301
2302        // A case with no matching arm and no else is NIL, matching Ruby. Elixir
2303        // raises CaseClauseError; blue follows Ruby because its `if` without an
2304        // else is already nil, and having two different answers to "no branch
2305        // taken" in one language is the inconsistency.
2306        let mut cond = vec![sym_at(head, "cond")];
2307        cond.extend(arms);
2308        // The `else` clause spans its own keyword through its body. Anchoring it
2309        // at `head` — the `case` keyword — put a node whose subtree sits at the
2310        // END of the form at a span near its START, so the else body escaped its
2311        // parent's range entirely. `every_node_sits_inside_its_parents_span`
2312        // caught that; it is the kind of mistake no output-shape test can see,
2313        // because the tree is correct and only the positions are wrong.
2314        let else_span = else_kw.unwrap_or(head);
2315        let else_body = otherwise.unwrap_or_else(|| Spanned::new(else_span, SpannedForm::Nil));
2316        cond.push(list_at(
2317            else_span.merge(else_body.span),
2318            vec![sym_at(else_span, "else"), else_body],
2319        ));
2320
2321        let whole = self.span_since(head.start);
2322        let binding = list_at(
2323            head.merge(subject.span),
2324            vec![sym_at(head, subject_var), subject],
2325        );
2326        Ok(list_at(
2327            whole,
2328            vec![
2329                sym_at(head, "let"),
2330                list_at(binding.span, vec![binding]),
2331                list_at(whole, cond),
2332            ],
2333        ))
2334    }
2335
2336    /// Is the `(` just consumed the head of `(a, b) -> expr`? Only bare names
2337    /// and commas between the parens, then `->`, all on one line.
2338    fn arrow_lambda_ahead(&self) -> bool {
2339        let mut i = self.pos;
2340        let kind = |i: usize| self.toks.get(i).map(|t| &t.kind);
2341        if !matches!(kind(i), Some(TokenKind::RParen)) {
2342            loop {
2343                if matches!(kind(i), Some(TokenKind::Op(o)) if o == "*") {
2344                    i += 1;
2345                }
2346                if !matches!(kind(i), Some(TokenKind::Ident(_))) {
2347                    return false;
2348                }
2349                i += 1;
2350                match kind(i) {
2351                    Some(TokenKind::Comma) => i += 1,
2352                    Some(TokenKind::RParen) => break,
2353                    _ => return false,
2354                }
2355            }
2356        }
2357        matches!(kind(i + 1), Some(TokenKind::Op(o)) if o == "->")
2358    }
2359
2360    /// `(a, b) -> expr` => `(lambda (a b) expr)`: the inline spelling of a
2361    /// one-expression `fn`. `->` is unambiguous here: the return-type arrow
2362    /// only follows a `def` header, never a parenthesised name list in
2363    /// expression position. The formatter spells a lambda this way exactly
2364    /// when its body is one expression that fits the line, and as a broken
2365    /// `fn … end` otherwise.
2366    fn arrow_lambda(&mut self, head: Span) -> Result<Spanned, Fail> {
2367        let mut params: Vec<Spanned> = Vec::new();
2368        while !self.at(&TokenKind::RParen) {
2369            let p_span = self.peek_span();
2370            if self.at_star() {
2371                params.extend(self.rest_parameter()?);
2372                break;
2373            }
2374            match self.bump() {
2375                TokenKind::Ident(p) => params.push(sym_at(p_span, &p)),
2376                other => {
2377                    return Err(fail(
2378                        format!("expected a parameter name, found {other}"),
2379                        p_span,
2380                    ))
2381                }
2382            }
2383            self.eat(&TokenKind::Comma);
2384        }
2385        self.bump();
2386        self.bump();
2387        self.skip_newlines();
2388        let params_span = cover(&params, head);
2389        let body = self.expr(0)?;
2390        Ok(list_at(
2391            self.span_since(head.start),
2392            vec![sym_at(head, "lambda"), list_at(params_span, params), body],
2393        ))
2394    }
2395
2396    fn rest_parameter(&mut self) -> Result<[Spanned; 2], Fail> {
2397        let star = self.peek_span();
2398        self.bump();
2399        let name_span = self.peek_span();
2400        match self.bump() {
2401            TokenKind::Ident(p) => {
2402                let whole = star.merge(name_span);
2403                Ok([sym_at(whole, "&rest"), sym_at(whole, &p)])
2404            }
2405            other => Err(fail(
2406                format!("expected a parameter name after `*`, found {other}"),
2407                name_span,
2408            )),
2409        }
2410    }
2411
2412    fn at_star(&self) -> bool {
2413        matches!(self.peek(), TokenKind::Op(o) if o == "*")
2414    }
2415
2416    fn optional_mark(
2417        &self,
2418        name: String,
2419        span: Span,
2420        optional_from: &mut Option<usize>,
2421        index: usize,
2422    ) -> Result<String, Fail> {
2423        match name.strip_suffix('?').filter(|n| !n.is_empty()) {
2424            Some(bare) => {
2425                optional_from.get_or_insert(index);
2426                Ok(bare.to_string())
2427            }
2428            None if optional_from.is_some() => Err(fail(
2429                format!("the required parameter `{name}` cannot follow an optional one"),
2430                span,
2431            )),
2432            None => Ok(name),
2433        }
2434    }
2435
2436    fn rest_is_last(&mut self) -> Result<(), Fail> {
2437        self.skip_newlines();
2438        if self.at(&TokenKind::Comma) {
2439            return Err(self.error("a rest parameter `*name` comes last".to_string()));
2440        }
2441        Ok(())
2442    }
2443
2444    /// `fn(a, b) ... end` => `(lambda (a b) body)`
2445    ///
2446    /// Without this the higher-order functions are unreachable in practice:
2447    /// `map(inc, xs)` works only because `inc` happens to be a named stdlib
2448    /// function, and there was no way to write the one-off the call site
2449    /// actually wants.
2450    ///
2451    /// `fn … end` is the block spelling and always breaks over lines; the
2452    /// inline spelling is `(x) -> expr` ([`Self::arrow_lambda`]).
2453    fn lambda_form(&mut self, head: Span) -> Result<Spanned, Fail> {
2454        let mut params: Vec<Spanned> = Vec::new();
2455        if !self.at(&TokenKind::LParen) {
2456            self.note(Spelling::ParameterList, head, "fn", "fn()");
2457        }
2458        if self.at(&TokenKind::LParen) {
2459            self.bump();
2460            self.skip_newlines();
2461            if !self.eat(&TokenKind::RParen) {
2462                loop {
2463                    self.skip_newlines();
2464                    let p_span = self.peek_span();
2465                    if self.at_star() {
2466                        params.extend(self.rest_parameter()?);
2467                        self.rest_is_last()?;
2468                        self.expect(&TokenKind::RParen, "`)` after the rest parameter")?;
2469                        break;
2470                    }
2471                    match self.bump() {
2472                        TokenKind::Ident(p) => params.push(sym_at(p_span, &p)),
2473                        other => {
2474                            return Err(fail(
2475                                format!("expected a parameter name, found {other}"),
2476                                p_span,
2477                            ))
2478                        }
2479                    }
2480                    self.skip_newlines();
2481                    if self.eat(&TokenKind::Comma) {
2482                        if self.trailing_comma(&TokenKind::RParen) {
2483                            break;
2484                        }
2485                        continue;
2486                    }
2487                    self.expect(&TokenKind::RParen, "`,` or `)`")?;
2488                    break;
2489                }
2490            }
2491        }
2492        let params_span = cover(&params, head);
2493        let body = self.body(&["end"])?;
2494        self.expect_ident("end")?;
2495        Ok(list_at(
2496            self.span_since(head.start),
2497            vec![sym_at(head, "lambda"), list_at(params_span, params), body],
2498        ))
2499    }
2500
2501    /// `test "name" ... end` => `(deftest "name" body)`
2502    ///
2503    /// A string, not an identifier: a test name is prose for a human report,
2504    /// and forcing it into an identifier is how test names become
2505    /// `test_adds_two_numbers_correctly`.
2506    fn test_form(&mut self, head: Span) -> Result<Spanned, Fail> {
2507        let name_span = self.peek_span();
2508        let name = match self.bump() {
2509            TokenKind::Str(s) => s,
2510            other => {
2511                return Err(fail(
2512                    format!("expected a string name after `test`, found {other}"),
2513                    name_span,
2514                ))
2515            }
2516        };
2517        let body = self.body(&["end"])?;
2518        self.expect_ident("end")?;
2519        Ok(list_at(
2520            self.span_since(head.start),
2521            vec![
2522                sym_at(head, "deftest"),
2523                atom_at(name_span, Atom::Str(name)),
2524                body,
2525            ],
2526        ))
2527    }
2528
2529    /// `assert expr` => `(blue-assert 'expr expr)`
2530    ///
2531    /// **`blue-assert`, not `assert`.** tatara-lisp's stdlib already defines
2532    /// `assert` as a macro — `(defmacro assert (pred message) …)` — and a macro
2533    /// in the expander is consulted before any primitive in the registry. So
2534    /// lowering to `assert` bound `pred` to the *quoted form*, which is
2535    /// truthy, and **every assertion silently passed**. A test framework whose
2536    /// assertions always pass is the worst defect it can have: every test in
2537    /// the suite goes green.
2538    ///
2539    /// The lesson generalizes: any name blue lowers to that tatara already
2540    /// binds is silently captured. `blue_lang_test`'s
2541    /// `no_lowered_name_is_shadowed_by_the_runtime` gates the whole class.
2542    ///
2543    /// **Both the form and the value.** A test framework whose failure says
2544    /// only "assertion failed" makes the author re-derive what they were
2545    /// checking; one that shows the expression does not. The quoted form is
2546    /// the expression as DATA, so the runner can render it — and it renders it
2547    /// through `blue-lang-fmt`, meaning the failure message is in canonical
2548    /// blue syntax rather than the underlying tatara-lisp.
2549    ///
2550    /// This is homoiconicity paying for itself: the capture needs no source
2551    /// map, no macro hygiene, and no string of the original text.
2552    fn assert_form(&mut self, head: Span) -> Result<Spanned, Fail> {
2553        let e = self.expr(0)?;
2554        let quoted = Spanned::new(e.span, SpannedForm::Quote(Box::new(e.clone())));
2555        Ok(list_at(
2556            self.span_since(head.start),
2557            vec![sym_at(head, LOWERED_ASSERT), quoted, e],
2558        ))
2559    }
2560
2561    /// `defmacro name(a, b) ... end` => `(defmacro name (a b) body)`
2562    ///
2563    /// **Deliberately untyped.** A macro's parameters are *source forms*, not
2564    /// values, so `a: Int` would be a category error: the argument at expansion
2565    /// time is a fragment of syntax. §IV's ladder types values; macro
2566    /// parameters are not on it. Annotating one is rejected rather than
2567    /// silently ignored — an ignored annotation is how an author comes to
2568    /// believe a check is running.
2569    fn defmacro_form(&mut self, head: Span) -> Result<Spanned, Fail> {
2570        let name_span = self.peek_span();
2571        let name = match self.bump() {
2572            TokenKind::Ident(n) => n,
2573            other => {
2574                return Err(fail(
2575                    format!("expected a name after `defmacro`, found {other}"),
2576                    name_span,
2577                ))
2578            }
2579        };
2580        self.not_reserved(&name, name_span, "a `defmacro` name")?;
2581        let mut params: Vec<Spanned> = Vec::new();
2582        if self.at(&TokenKind::LParen) {
2583            self.bump();
2584            self.skip_newlines();
2585            if !self.eat(&TokenKind::RParen) {
2586                loop {
2587                    self.skip_newlines();
2588                    let p_span = self.peek_span();
2589                    match self.bump() {
2590                        TokenKind::Ident(p) => params.push(sym_at(p_span, &p)),
2591                        TokenKind::Label(p) => {
2592                            return Err(self.error(format!(
2593                                "macro parameter `{p}` cannot be typed: a macro receives \
2594                                 source forms, not values"
2595                            )))
2596                        }
2597                        other => {
2598                            return Err(fail(
2599                                format!("expected a parameter name, found {other}"),
2600                                p_span,
2601                            ))
2602                        }
2603                    }
2604                    self.skip_newlines();
2605                    if self.eat(&TokenKind::Comma) {
2606                        if self.trailing_comma(&TokenKind::RParen) {
2607                            break;
2608                        }
2609                        continue;
2610                    }
2611                    self.expect(&TokenKind::RParen, "`,` or `)`")?;
2612                    break;
2613                }
2614            }
2615        }
2616        if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
2617            return Err(self.error(
2618                "a macro has no return type: it produces source forms, not values".to_string(),
2619            ));
2620        }
2621
2622        let params_span = cover(&params, name_span);
2623        let body = self.body(&["end"])?;
2624        self.expect_ident("end")?;
2625
2626        // `(defmacro name (params) body)` — tatara-lisp's own shape, so blue
2627        // registers into the SAME expander rather than a parallel one.
2628        Ok(list_at(
2629            self.span_since(head.start),
2630            vec![
2631                sym_at(head, "defmacro"),
2632                sym_at(name_span, &name),
2633                list_at(params_span, params),
2634                body,
2635            ],
2636        ))
2637    }
2638
2639    /// `quote ... end` => `` `body `` (a quasiquote).
2640    ///
2641    /// Quasiquote rather than plain quote, because a macro body that could not
2642    /// splice its arguments in would be useless — this is Elixir's `quote do`,
2643    /// which is likewise a template and not inert data.
2644    fn quote_form(&mut self, head: Span) -> Result<Spanned, Fail> {
2645        self.quoting += 1;
2646        let body = self.body(&["end"]);
2647        self.quoting -= 1;
2648        let body = body?;
2649        self.expect_ident("end")?;
2650        // `Sexp::Quasiquote`, NOT `(quasiquote body)` as a list.
2651        //
2652        // The list form Displays as the text `(quasiquote …)`, which the
2653        // tatara-lisp reader reads back as an ordinary list whose head happens
2654        // to be the symbol `quasiquote` — losing the structure. The evaluator
2655        // then reached the inner `,x` with no enclosing quasiquote and rejected
2656        // it: "unquote outside of quasiquote". Building the real variant makes
2657        // it Display as `` ` `` and survive the round trip.
2658        Ok(Spanned::new(
2659            self.span_since(head.start),
2660            SpannedForm::Quasiquote(Box::new(body)),
2661        ))
2662    }
2663
2664    /// `unquote(expr)` => `,expr`; `unquote_splice(expr)` => `,@expr`.
2665    fn unquote_form(&mut self, head: Span, splice: bool) -> Result<Spanned, Fail> {
2666        self.expect(&TokenKind::LParen, "`(` after unquote")?;
2667        self.skip_newlines();
2668        let inner = self.expr(0)?;
2669        self.skip_newlines();
2670        self.expect(&TokenKind::RParen, "`)`")?;
2671        let span = self.span_since(head.start);
2672        Ok(Spanned::new(
2673            span,
2674            if splice {
2675                SpannedForm::UnquoteSplice(Box::new(inner))
2676            } else {
2677                SpannedForm::Unquote(Box::new(inner))
2678            },
2679        ))
2680    }
2681
2682    fn protected_body(&mut self, head: Span) -> Result<Spanned, Fail> {
2683        let body = self.body(&["rescue", "ensure", "end"])?;
2684        if self.at_ident("rescue") || self.at_ident("ensure") {
2685            return self.rescue_tail(head, body);
2686        }
2687        Ok(body)
2688    }
2689
2690    fn begin_form(&mut self, head: Span) -> Result<Spanned, Fail> {
2691        let body = self.body(&["rescue", "ensure", "end"])?;
2692        if !(self.at_ident("rescue") || self.at_ident("ensure")) {
2693            return Err(self.error(
2694                "a `begin` block protects its statements with `rescue` or `ensure`; without either, write the statements directly",
2695            ));
2696        }
2697        let tree = self.rescue_tail(head, body)?;
2698        self.expect_ident("end")?;
2699        Ok(Spanned::new(self.span_since(head.start), tree.form))
2700    }
2701
2702    fn rescue_tail(&mut self, head: Span, body: Spanned) -> Result<Spanned, Fail> {
2703        let mut clauses: Vec<Spanned> = Vec::new();
2704        let mut catch_all: Option<(Spanned, Spanned, Span)> = None;
2705        while self.at_ident("rescue") {
2706            let kw = self.peek_span();
2707            self.bump();
2708            if catch_all.is_some() {
2709                return Err(fail(
2710                    "a `rescue NAME` catches every error, so it is the last `rescue`; put the kinds it would shadow above it",
2711                    kw,
2712                ));
2713            }
2714            match self.peek().clone() {
2715                TokenKind::Sym(_) => {
2716                    let mut kinds = Vec::new();
2717                    loop {
2718                        let k_span = self.peek_span();
2719                        match self.bump() {
2720                            TokenKind::Sym(k) => kinds.push(atom_at(k_span, Atom::Keyword(k))),
2721                            other => {
2722                                return Err(fail(
2723                                    format!("expected an error kind such as `:not_found`, found {other}"),
2724                                    k_span,
2725                                ))
2726                            }
2727                        }
2728                        if self.eat(&TokenKind::Comma) {
2729                            self.skip_newlines();
2730                            continue;
2731                        }
2732                        break;
2733                    }
2734                    let binder = if self.eat_ident("as") {
2735                        let b_span = self.peek_span();
2736                        match self.bump() {
2737                            TokenKind::Ident(b) if !is_reserved_word(&b) => Some(sym_at(b_span, &b)),
2738                            other => {
2739                                return Err(fail(
2740                                    format!("expected the name the error is bound to after `as`, found {other}"),
2741                                    b_span,
2742                                ))
2743                            }
2744                        }
2745                    } else {
2746                        None
2747                    };
2748                    let handler = self.body(&["rescue", "ensure", "end"])?;
2749                    let mut test = vec![sym_at(kw, LOWERED_ERROR_MATCH), sym_at(kw, RESCUED)];
2750                    test.extend(kinds);
2751                    let test = list_at(cover(&test, kw), test);
2752                    let handler = match binder {
2753                        Some(b) => let_bound(b, handler, kw),
2754                        None => handler,
2755                    };
2756                    clauses.push(list_at(kw.merge(handler.span), vec![test, handler]));
2757                }
2758                TokenKind::Ident(b) if !is_reserved_word(&b) => {
2759                    let b_span = self.peek_span();
2760                    self.bump();
2761                    let handler = self.body(&["rescue", "ensure", "end"])?;
2762                    catch_all = Some((sym_at(b_span, &b), handler, kw));
2763                }
2764                _ => {
2765                    return Err(fail(
2766                        "`rescue` names what it catches: `rescue :kind`, `rescue :a, :b as e`, or `rescue e` for every error (`rescue _` discards it)",
2767                        kw,
2768                    ))
2769                }
2770            }
2771        }
2772        let ensure = if self.at_ident("ensure") {
2773            self.bump();
2774            let cleanup = self.body(&["rescue", "end"])?;
2775            if self.at_ident("rescue") {
2776                return Err(self.error("`ensure` comes after every `rescue` of its block"));
2777            }
2778            Some(cleanup)
2779        } else {
2780            None
2781        };
2782        let whole = self.span_since(head.start);
2783        let protected = if clauses.is_empty() {
2784            match catch_all {
2785                None => body,
2786                Some((binder, handler, kw)) => list_at(
2787                    whole,
2788                    vec![
2789                        sym_at(head, "try"),
2790                        body,
2791                        list_at(
2792                            kw.merge(handler.span),
2793                            vec![
2794                                sym_at(kw, "catch"),
2795                                list_at(binder.span, vec![binder]),
2796                                handler,
2797                            ],
2798                        ),
2799                    ],
2800                ),
2801            }
2802        } else {
2803            let first_kw = clauses[0].span;
2804            let otherwise = match catch_all {
2805                Some((binder, handler, kw)) => {
2806                    let bound = let_bound(binder, handler, kw);
2807                    list_at(kw.merge(bound.span), vec![sym_at(kw, "else"), bound])
2808                }
2809                None => list_at(
2810                    head,
2811                    vec![
2812                        sym_at(head, "else"),
2813                        list_at(
2814                            head,
2815                            vec![sym_at(head, LOWERED_RERAISE), sym_at(head, RESCUED)],
2816                        ),
2817                    ],
2818                ),
2819            };
2820            let mut cond = vec![sym_at(first_kw, "cond")];
2821            cond.extend(clauses);
2822            cond.push(otherwise);
2823            let cond_span = cover(&cond, first_kw);
2824            list_at(
2825                whole,
2826                vec![
2827                    sym_at(head, "try"),
2828                    body,
2829                    list_at(
2830                        cond_span,
2831                        vec![
2832                            sym_at(first_kw, "catch"),
2833                            list_at(first_kw, vec![sym_at(first_kw, RESCUED)]),
2834                            list_at(cond_span, cond),
2835                        ],
2836                    ),
2837                ],
2838            )
2839        };
2840        Ok(match ensure {
2841            None => protected,
2842            Some(cleanup) => {
2843                let attempted = list_at(
2844                    protected.span,
2845                    vec![sym_at(head, LOWERED_ATTEMPTED), protected],
2846                );
2847                let failed = list_at(
2848                    head,
2849                    vec![sym_at(head, LOWERED_FAILED), sym_at(head, RESCUED)],
2850                );
2851                let caught = list_at(
2852                    whole,
2853                    vec![
2854                        sym_at(head, "try"),
2855                        attempted,
2856                        list_at(
2857                            head,
2858                            vec![
2859                                sym_at(head, "catch"),
2860                                list_at(head, vec![sym_at(head, RESCUED)]),
2861                                failed,
2862                            ],
2863                        ),
2864                    ],
2865                );
2866                list_at(
2867                    whole,
2868                    vec![sym_at(head, LOWERED_ENSURE), caught, thunk(cleanup, head)],
2869                )
2870            }
2871        })
2872    }
2873
2874    fn def_form(&mut self, head: Span) -> Result<Spanned, Fail> {
2875        let name_span = self.peek_span();
2876        let name = match self.bump() {
2877            TokenKind::Ident(n) => n,
2878            other => {
2879                return Err(fail(
2880                    format!("expected a name after `def`, found {other}"),
2881                    name_span,
2882                ))
2883            }
2884        };
2885        self.not_reserved(&name, name_span, "a `def` name")?;
2886        let mut params: Vec<(String, Span, Option<Spanned>)> = Vec::new();
2887        let mut optional_from: Option<usize> = None;
2888        let mut rest: Vec<Spanned> = Vec::new();
2889        if !self.at(&TokenKind::LParen) {
2890            self.note(
2891                Spelling::ParameterList,
2892                name_span,
2893                &format!("def {name}"),
2894                &format!("def {name}()"),
2895            );
2896        }
2897        if self.at(&TokenKind::LParen) {
2898            self.bump();
2899            self.skip_newlines();
2900            if !self.eat(&TokenKind::RParen) {
2901                loop {
2902                    self.skip_newlines();
2903                    let p_span = self.peek_span();
2904                    if self.at_star() {
2905                        if optional_from.is_some() {
2906                            return Err(fail(
2907                                "a rest parameter cannot follow an optional one",
2908                                p_span,
2909                            ));
2910                        }
2911                        rest = self.rest_parameter()?.to_vec();
2912                        self.rest_is_last()?;
2913                        self.expect(&TokenKind::RParen, "`)` after the rest parameter")?;
2914                        break;
2915                    }
2916                    match self.bump() {
2917                        // `a` — unannotated
2918                        TokenKind::Ident(p) => {
2919                            self.not_reserved(&p, p_span, "a parameter name")?;
2920                            let p =
2921                                self.optional_mark(p, p_span, &mut optional_from, params.len())?;
2922                            params.push((p, p_span, None));
2923                        }
2924                        // `a:` came through as one token, so a type follows
2925                        TokenKind::Label(p) => {
2926                            self.not_reserved(&p, p_span, "a parameter name")?;
2927                            let p =
2928                                self.optional_mark(p, p_span, &mut optional_from, params.len())?;
2929                            self.skip_newlines();
2930                            let ty = self.type_expr()?;
2931                            params.push((p, p_span, Some(ty)));
2932                        }
2933                        other => {
2934                            return Err(fail(
2935                                format!("expected a parameter name, found {other}"),
2936                                p_span,
2937                            ))
2938                        }
2939                    }
2940                    self.skip_newlines();
2941                    if self.eat(&TokenKind::Comma) {
2942                        if self.trailing_comma(&TokenKind::RParen) {
2943                            break;
2944                        }
2945                        continue;
2946                    }
2947                    self.expect(&TokenKind::RParen, "`,` or `)`")?;
2948                    break;
2949                }
2950            }
2951        }
2952        // The signature list spans the name through the closing `)`.
2953        let sig_span = self.span_since(name_span.start);
2954
2955        // Optional `-> R`
2956        let ret = if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
2957            self.bump();
2958            self.skip_newlines();
2959            Some(self.type_expr()?)
2960        } else {
2961            None
2962        };
2963
2964        let begins = {
2965            let save = self.pos;
2966            self.skip_newlines();
2967            let at = self.at_ident("begin").then(|| self.peek_span());
2968            self.pos = save;
2969            at
2970        };
2971        let body = self.protected_body(head)?;
2972        if let Some(b) = begins {
2973            let protects = matches!(&body.form, SpannedForm::List(items)
2974                if matches!(items.first().and_then(Spanned::as_symbol), Some("try") | Some(LOWERED_ENSURE)));
2975            if protects && body.span.start == b.start {
2976                self.note(
2977                    Spelling::TryCatch,
2978                    b,
2979                    "begin … end as a whole def body",
2980                    "the clauses on the def itself",
2981                );
2982            }
2983        }
2984        self.expect_ident("end")?;
2985        let whole = self.span_since(head.start);
2986
2987        let annotated = ret.is_some() || params.iter().any(|(_, _, t)| t.is_some());
2988        if !annotated {
2989            let mut sig = vec![sym_at(name_span, &name)];
2990            for (i, (p, s, _)) in params.into_iter().enumerate() {
2991                if optional_from == Some(i) {
2992                    sig.push(sym_at(s, OPTIONAL_MARKER));
2993                }
2994                sig.push(sym_at(s, &p));
2995            }
2996            sig.extend(rest);
2997            return Ok(list_at(
2998                whole,
2999                vec![sym_at(head, "define"), list_at(sig_span, sig), body],
3000            ));
3001        }
3002
3003        // Typed shape. An un-annotated parameter in an otherwise annotated
3004        // signature is written `(p dyn)` so the checker sees the ladder
3005        // position explicitly rather than inferring it from absence.
3006        //
3007        // A `dyn` written by the parser rather than the author takes the
3008        // parameter's own span, so a diagnostic about it points at the
3009        // parameter — the only thing in the source it could mean.
3010        let mut sig = vec![sym_at(name_span, &name)];
3011        for (i, (p, s, t)) in params.into_iter().enumerate() {
3012            if optional_from == Some(i) {
3013                sig.push(sym_at(s, OPTIONAL_MARKER));
3014            }
3015            let ty = t.unwrap_or_else(|| sym_at(s, "dyn"));
3016            sig.push(list_at(s.merge(ty.span), vec![sym_at(s, &p), ty]));
3017        }
3018        sig.extend(rest);
3019        Ok(list_at(
3020            whole,
3021            vec![
3022                sym_at(head, "define-typed"),
3023                list_at(sig_span, sig),
3024                ret.unwrap_or_else(|| sym_at(head, "dyn")),
3025                body,
3026            ],
3027        ))
3028    }
3029
3030    /// A type expression: a name, or a constructor over types of any arity.
3031    fn type_expr(&mut self) -> Result<Spanned, Fail> {
3032        let name_span = self.peek_span();
3033        let name = match self.bump() {
3034            TokenKind::Ident(n) => n,
3035            other => {
3036                return Err(fail(
3037                    format!("expected a type name, found {other}"),
3038                    name_span,
3039                ))
3040            }
3041        };
3042        self.not_reserved(&name, name_span, "a type name")?;
3043        if self.at(&TokenKind::LParen) {
3044            self.bump();
3045            self.skip_newlines();
3046            let mut list = vec![sym_at(name_span, &name)];
3047            if !self.eat(&TokenKind::RParen) {
3048                loop {
3049                    self.skip_newlines();
3050                    list.push(self.type_expr()?);
3051                    self.skip_newlines();
3052                    if self.eat(&TokenKind::Comma) {
3053                        if self.trailing_comma(&TokenKind::RParen) {
3054                            break;
3055                        }
3056                        continue;
3057                    }
3058                    self.expect(&TokenKind::RParen, "`,` or `)`")?;
3059                    break;
3060                }
3061            }
3062            return Ok(list_at(self.span_since(name_span.start), list));
3063        }
3064        Ok(sym_at(name_span, &name))
3065    }
3066
3067    fn not_reserved(&self, name: &str, at: Span, what: &str) -> Result<(), Fail> {
3068        if is_reserved_word(name) {
3069            return Err(fail(
3070                format!("`{name}` is a reserved word and cannot be {what}"),
3071                at,
3072            ));
3073        }
3074        Ok(())
3075    }
3076
3077    /// Consume `name` if it is the next token, else leave the position alone.
3078    fn eat_ident(&mut self, name: &str) -> bool {
3079        if self.at_ident(name) {
3080            self.bump();
3081            true
3082        } else {
3083            false
3084        }
3085    }
3086
3087    fn expect_ident(&mut self, name: &str) -> Result<(), Fail> {
3088        if self.at_ident(name) {
3089            self.bump();
3090            Ok(())
3091        } else {
3092            Err(self.error(format!("expected `{name}`, found {}", self.peek())))
3093        }
3094    }
3095
3096    /// A sequence of expressions up to one of `terminators`, wrapped in
3097    /// `(begin ...)` when there is more than one.
3098    fn body(&mut self, terminators: &[&str]) -> Result<Spanned, Fail> {
3099        // Anchored BEFORE the leading newlines are skipped, so an empty body's
3100        // span sits where the body would have started.
3101        let start = self.mark();
3102        let mut forms = Vec::new();
3103        loop {
3104            self.skip_newlines();
3105            if matches!(self.peek(), TokenKind::Eof) {
3106                return Err(self.error(format!(
3107                    "unterminated block: expected {} before the end of the file",
3108                    one_of(terminators)
3109                )));
3110            }
3111            if terminators.iter().any(|t| self.at_ident(t)) {
3112                break;
3113            }
3114            forms.push(self.statement()?);
3115            self.end_of_statement(terminators)?;
3116        }
3117        Ok(match forms.len() {
3118            0 => Spanned::new(Span::new(start, start), SpannedForm::Nil),
3119            1 => forms.into_iter().next().expect("checked len"),
3120            _ => {
3121                // `cover`, NOT `span_since`: the loop breaks *before* consuming
3122                // the terminator but *after* `skip_newlines`, so the last token
3123                // behind `pos` can be a newline and `span_since` would stretch
3124                // the body across trailing blank lines. The forms know exactly
3125                // where they are.
3126                let span = cover(&forms, Span::new(start, start));
3127                // The synthesized `begin` is zero-width at the FIRST FORM's
3128                // start, not at `start`. `start` is anchored before the leading
3129                // newlines are skipped, so it sits earlier than the body itself
3130                // — and a head node outside its own list's span is a span bug
3131                // that `every_node_sits_inside_its_parents_span` reports.
3132                let head = Span::new(span.start, span.start);
3133                let mut list = vec![sym_at(head, "begin")];
3134                list.extend(forms);
3135                list_at(span, list)
3136            }
3137        })
3138    }
3139}
3140
3141/// `` `a` ``, `` `a` or `b` ``, `` `a`, `b` or `c` `` — a list of keywords as
3142/// a sentence says it.
3143fn one_of(words: &[&str]) -> String {
3144    let quoted: Vec<String> = words.iter().map(|w| format!("`{w}`")).collect();
3145    match quoted.split_last() {
3146        None => String::new(),
3147        Some((last, [])) => last.clone(),
3148        Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
3149    }
3150}
3151
3152fn let_bound(binder: Spanned, body: Spanned, at: Span) -> Spanned {
3153    let span = at.merge(body.span);
3154    let pair = list_at(binder.span, vec![binder, sym_at(at, RESCUED)]);
3155    list_at(
3156        span,
3157        vec![sym_at(at, "let"), list_at(pair.span, vec![pair]), body],
3158    )
3159}
3160
3161fn thunk(body: Spanned, at: Span) -> Spanned {
3162    let span = at.merge(body.span);
3163    list_at(
3164        span,
3165        vec![sym_at(at, "lambda"), list_at(at, Vec::new()), body],
3166    )
3167}
3168
3169/// Whether `name:` lexes as exactly one label spelling `name`: the parser's and
3170/// the formatter's shared test for a key that can be punned (`{name:}`). It asks
3171/// the lexer, so a name ending in `?` or `!` puns too and no second list of
3172/// "plain names" can drift from what a label is.
3173#[must_use]
3174pub fn label_name(name: &str) -> bool {
3175    matches!(
3176        lex(&format!("{name}:")).as_deref(),
3177        Ok([t, e]) if matches!(&t.kind, TokenKind::Label(n) if n == name) && e.kind == TokenKind::Eof
3178    )
3179}
3180
3181fn blue_lang_name(name: &str) -> bool {
3182    matches!(
3183        lex(name).as_deref(),
3184        Ok([t, e]) if matches!(&t.kind, TokenKind::Ident(n) if n == name) && e.kind == TokenKind::Eof
3185    ) && !name.ends_with(['?', '!'])
3186}
3187
3188fn mentions(form: &Spanned, name: &str) -> bool {
3189    match &form.form {
3190        SpannedForm::Atom(Atom::Symbol(s)) => s == name,
3191        SpannedForm::List(items) => items.iter().any(|i| mentions(i, name)),
3192        SpannedForm::Quote(i)
3193        | SpannedForm::Quasiquote(i)
3194        | SpannedForm::Unquote(i)
3195        | SpannedForm::UnquoteSplice(i) => mentions(i, name),
3196        _ => false,
3197    }
3198}
3199
3200/// A symbol node at `span`.
3201fn sym_at(span: Span, s: &str) -> Spanned {
3202    Spanned::new(span, SpannedForm::Atom(Atom::Symbol(s.to_string())))
3203}
3204
3205/// An atom node at `span`.
3206fn atom_at(span: Span, a: Atom) -> Spanned {
3207    Spanned::new(span, SpannedForm::Atom(a))
3208}
3209
3210/// A list node at `span`.
3211fn list_at(span: Span, items: Vec<Spanned>) -> Spanned {
3212    Spanned::new(span, SpannedForm::List(items))
3213}
3214
3215/// The smallest span covering every node in `items`, or `fallback` when there
3216/// are none.
3217///
3218/// The fallback is a parameter rather than `Span::synthetic()` because a
3219/// synthetic span is a claim that a node has no source origin at all — and an
3220/// empty parameter list in `def f()` very much has one. Defaulting to synthetic
3221/// here is how "no span" leaks into a tree where every node does have a place.
3222fn cover(items: &[Spanned], fallback: Span) -> Span {
3223    let merged = items
3224        .iter()
3225        .fold(Span::synthetic(), |acc, s| acc.merge(s.span));
3226    if merged.is_synthetic() {
3227        fallback
3228    } else {
3229        merged
3230    }
3231}
3232
3233#[cfg(test)]
3234mod tests {
3235    use super::*;
3236
3237    /// Render an `Sexp` to canonical text so tests can state the expected
3238    /// quoted form as a string. This is `Display`, which tatara-lisp owns —
3239    /// blue does not build Lisp syntax by concatenation.
3240    fn q(src: &str) -> String {
3241        parse_expr(src)
3242            .map(|s| s.to_string())
3243            .unwrap_or_else(|e| panic!("{src:?}: {e}"))
3244    }
3245
3246    #[test]
3247    fn a_reserved_word_is_not_a_def_name_a_parameter_or_a_type() {
3248        for src in [
3249            "def def a(x)\n  x\nend",
3250            "def end()\n  1\nend",
3251            "def f(end)\n  1\nend",
3252            "def f(a: not)\n  1\nend",
3253            "def f(a) -> not a\n  a\nend",
3254            "def f(a: List(1 + 2))\n  a\nend",
3255            "defmacro defmacro m(a)\n  quote\n    a\n  end\nend",
3256        ] {
3257            assert!(parse_program(src).is_err(), "{src:?} parsed");
3258        }
3259    }
3260
3261    #[test]
3262    fn a_type_application_takes_types_of_any_arity() {
3263        assert_eq!(
3264            q("def f(a: Map(Str, List(Int))) -> Unit()\n  a\nend"),
3265            "(define-typed (f (a (Map Str (List Int)))) (Unit) a)"
3266        );
3267    }
3268
3269    // ---- the thesis: Ruby-shaped source becomes tatara-lisp ----------
3270
3271    #[test]
3272    fn arithmetic_respects_precedence() {
3273        assert_eq!(q("1 + 2 * 3"), "(+ 1 (* 2 3))");
3274        assert_eq!(q("(1 + 2) * 3"), "(* (+ 1 2) 3)");
3275    }
3276
3277    #[test]
3278    fn comparison_binds_looser_than_arithmetic() {
3279        assert_eq!(q("a + 1 < b"), "(< (+ a 1) b)");
3280    }
3281
3282    /// The expected tree names `or`/`and`, not `||`/`&&`: the surface
3283    /// spelling is the SURFACE's, and lowering renames it to the form
3284    /// tatara-lisp actually has. This test previously asserted the verbatim
3285    /// spelling, which is how `(== a b)` — a symbol nothing binds — shipped.
3286    #[test]
3287    fn logical_operators_bind_loosest_and_lower_to_tataras_names() {
3288        assert_eq!(q("a && b || c"), "(or (and a b) c)");
3289    }
3290
3291    #[test]
3292    fn left_associativity() {
3293        assert_eq!(q("1 - 2 - 3"), "(- (- 1 2) 3)");
3294    }
3295
3296    #[test]
3297    fn a_dot_without_parentheses_reads_a_field() {
3298        assert_eq!(q("user.name"), "(blue-field user :name)");
3299    }
3300
3301    #[test]
3302    fn method_call_with_args() {
3303        assert_eq!(q("user.greet(1, 2)"), "(greet user 1 2)");
3304    }
3305
3306    #[test]
3307    fn chained_fields_read_left_to_right() {
3308        assert_eq!(q("a.b.c"), "(blue-field (blue-field a :b) :c)");
3309        assert_eq!(q("a.b(1).c"), "(blue-field (b a 1) :c)");
3310    }
3311
3312    #[test]
3313    fn plain_call() {
3314        assert_eq!(q("f(1, 2)"), "(f 1 2)");
3315    }
3316
3317    /// The pipeline threads into the FIRST argument, as Elixir's does —
3318    /// that is what makes `|>` composable rather than decorative.
3319    #[test]
3320    fn pipeline_threads_into_first_argument() {
3321        assert_eq!(q("x |> f"), "(f x)");
3322        assert_eq!(q("x |> f(1)"), "(f x 1)");
3323        assert_eq!(q("x |> f |> g"), "(g (f x))");
3324    }
3325
3326    #[test]
3327    fn pipeline_binds_looser_than_arithmetic() {
3328        assert_eq!(q("1 + 2 |> f"), "(f (+ 1 2))");
3329    }
3330
3331    // ---- §V.13's rendering law, enforced at the parser ---------------
3332
3333    /// `a: 1` and `:a => 1` are the SAME TREE. That is exactly why the
3334    /// formatter may always render the shorthand: they are not two
3335    /// spellings of two things, they are two spellings of one thing.
3336    #[test]
3337    fn label_and_rocket_produce_the_same_tree_for_a_symbol_key() {
3338        assert_eq!(q("{a: 1}"), q("{:a => 1}"));
3339        assert_eq!(q("{a: 1}"), "(hash-map :a 1)");
3340    }
3341
3342    /// And where the key is NOT a plain symbol, the rocket is the only
3343    /// spelling — so it survives because it must, never as a style choice.
3344    #[test]
3345    fn a_string_key_has_no_shorthand() {
3346        assert_eq!(q(r#"{"k" => 1}"#), r#"(hash-map "k" 1)"#);
3347    }
3348
3349    #[test]
3350    fn a_newline_escape_and_its_lines_are_one_tree() {
3351        for (escaped, lines) in [
3352            (r#""a\nb""#, r#"join_lines(["a", "b"])"#),
3353            (r##""#{m}\n#{h}""##, "join_lines([m, h])"),
3354            (r##""n=#{n}\ndone\n""##, r##"unlines(["n=#{n}", "done"])"##),
3355            (r#""\n""#, "line_break"),
3356            (r#""a\n\n\tb\n""#, r#"unlines(["a", "", "\tb"])"#),
3357            (r#""\na""#, r#"join_lines(["", "a"])"#),
3358            (r#""\n\n""#, r#"unlines(["", ""])"#),
3359        ] {
3360            assert_eq!(q(escaped), q(lines), "{escaped}");
3361        }
3362        assert_eq!(q(r#""a\tb""#), q(r#""a\tb""#));
3363        assert!(!q(r#""a\tb""#).contains("join_lines"));
3364    }
3365
3366    #[test]
3367    fn a_newline_escape_is_noted_and_a_quoted_one_is_data() {
3368        let notes = spelling_notes(r#""a\nb""#).unwrap();
3369        assert_eq!(notes.len(), 1);
3370        assert_eq!(notes[0].spelling, Spelling::NewlineEscape);
3371        assert!(spelling_notes(r#""a\tb""#).unwrap().is_empty());
3372        let quoted = q("def f()\n  quote\n    \"x\\ny\"\n  end\nend\n");
3373        assert!(!quoted.contains("join_lines"), "{quoted}");
3374        assert!(
3375            spelling_notes("def f()\n  quote\n    \"x\\ny\"\n  end\nend\n")
3376                .unwrap()
3377                .is_empty()
3378        );
3379    }
3380
3381    #[test]
3382    fn list_literal() {
3383        assert_eq!(q("[1, 2, 3]"), "(list 1 2 3)");
3384        assert_eq!(q("[]"), "(list)");
3385    }
3386
3387    // ---- blocks ------------------------------------------------------
3388
3389    #[test]
3390    fn if_else_end() {
3391        assert_eq!(q("if a\n  1\nelse\n  2\nend"), "(if a 1 2)");
3392    }
3393
3394    #[test]
3395    fn if_without_else() {
3396        assert_eq!(q("if a\n  1\nend"), "(if a 1)");
3397    }
3398
3399    /// `unless` lowers to `(if (not c) …)` — one tree per meaning, so
3400    /// every downstream tool sees exactly one shape.
3401    #[test]
3402    fn unless_is_a_negated_if() {
3403        assert_eq!(q("unless a\n  1\nend"), "(if (not a) 1)");
3404    }
3405
3406    #[test]
3407    fn multi_statement_body_becomes_begin() {
3408        assert_eq!(q("if a\n  1\n  2\nend"), "(if a (begin 1 2))");
3409    }
3410
3411    #[test]
3412    fn def_lowers_to_define() {
3413        assert_eq!(
3414            q("def add(a, b)\n  a + b\nend"),
3415            "(define (add a b) (+ a b))"
3416        );
3417    }
3418
3419    #[test]
3420    fn def_with_no_params() {
3421        assert_eq!(q("def zero()\n  0\nend"), "(define (zero) 0)");
3422    }
3423
3424    fn refused(src: &str) -> String {
3425        match parse_expr(src) {
3426            Ok(s) => panic!("{src:?} should be refused, parsed to {s}"),
3427            Err(e) => e.to_string(),
3428        }
3429    }
3430
3431    #[test]
3432    fn a_question_mark_parameter_is_optional() {
3433        assert_eq!(q("def f(a, b?)\n  b\nend"), "(define (f a &optional b) b)");
3434        assert_eq!(q("def f(a?, b?)\n  a\nend"), "(define (f &optional a b) a)");
3435        assert_eq!(q("def f(a?)\n  a\nend"), "(define (f &optional a) a)");
3436    }
3437
3438    #[test]
3439    fn an_annotated_optional_parameter_keeps_its_type_after_the_marker() {
3440        assert_eq!(
3441            q("def f(a: Int, b?: Str) -> Int\n  a\nend"),
3442            "(define-typed (f (a Int) &optional (b Str)) Int a)"
3443        );
3444        assert_eq!(
3445            q("def f(a, b?: Str)\n  a\nend"),
3446            "(define-typed (f (a dyn) &optional (b Str)) dyn a)"
3447        );
3448    }
3449
3450    #[test]
3451    fn a_def_without_question_marks_carries_no_marker() {
3452        assert_eq!(q("def f(a, b)\n  a\nend"), "(define (f a b) a)");
3453        assert_eq!(q("def f(a, *r)\n  a\nend"), "(define (f a &rest r) a)");
3454    }
3455
3456    #[test]
3457    fn a_required_parameter_cannot_follow_an_optional_one() {
3458        assert!(refused("def f(a?, b)\n  a\nend").contains("`b` cannot follow an optional"));
3459        assert!(refused("def f(a, b?, c: Int)\n  a\nend").contains("`c` cannot follow"));
3460    }
3461
3462    #[test]
3463    fn a_rest_parameter_cannot_follow_an_optional_one() {
3464        assert!(refused("def f(a, b?, *r)\n  a\nend").contains("rest parameter cannot follow"));
3465    }
3466
3467    // ---- literals ----------------------------------------------------
3468
3469    #[test]
3470    fn literals_lower_to_atoms() {
3471        assert_eq!(q("42"), "42");
3472        assert_eq!(q("true"), "#t");
3473        assert_eq!(q(":ok"), ":ok");
3474        assert_eq!(q(r#""hi""#), r#""hi""#);
3475    }
3476
3477    #[test]
3478    fn unary_minus_and_not() {
3479        assert_eq!(q("-x"), "(- 0 x)");
3480        assert_eq!(q("!x"), "(not x)");
3481    }
3482
3483    // ---- programs and errors -----------------------------------------
3484
3485    #[test]
3486    fn a_program_is_a_sequence_of_forms() {
3487        let forms = parse_program("def f()\n  1\nend\nf()").expect("parse");
3488        assert_eq!(forms.len(), 2);
3489        assert_eq!(forms[1].to_string(), "(f)");
3490    }
3491
3492    #[test]
3493    fn unterminated_block_is_an_error_naming_what_was_expected() {
3494        let e = parse_program("if a\n  1").expect_err("must fail");
3495        assert!(e.message.contains("unterminated"), "{}", e.message);
3496    }
3497
3498    #[test]
3499    fn a_parse_error_carries_a_span_into_the_source() {
3500        let src = "1 + )";
3501        let e = parse_program(src).expect_err("must fail");
3502        assert!(e.span.start < src.len(), "span {:?} outside source", e.span);
3503    }
3504
3505    // ---- one statement per line -------------------------------------
3506
3507    /// `y = xs[0]` was TWO statements, `(define y xs)` and `(list 0)`: nothing
3508    /// required a separator between statements, so the parser finished `xs`,
3509    /// saw a list literal and started a new statement on the same line. The
3510    /// program ran and `y` was the whole list. Found by the 2026-09-29 audit.
3511    #[test]
3512    fn a_spaced_index_is_refused_naming_the_touching_one() {
3513        let e = parse_program("y = xs [0]").expect_err("must not split into two statements");
3514        assert!(e.message.contains("`xs[0]`"), "{}", e.message);
3515        assert_eq!((e.line, e.col), (1, 8), "{e}");
3516    }
3517
3518    #[test]
3519    fn an_index_is_the_tree_of_get_or_nth() {
3520        for (short, long) in [
3521            ("m[:k]", "get(m, :k)"),
3522            (r#"m["k"]"#, r#"get(m, "k")"#),
3523            ("xs[0]", "nth(0, xs)"),
3524            ("xs[i + 1]", "nth(i + 1, xs)"),
3525            ("f(x)[2]", "nth(2, f(x))"),
3526            ("m[:a][:b]", "get(get(m, :a), :b)"),
3527            ("xs[0][:k]", "get(nth(0, xs), :k)"),
3528            ("[1, 2][1]", "nth(1, [1, 2])"),
3529        ] {
3530            assert_eq!(q(short), q(long), "{short}");
3531        }
3532        assert_eq!(q("get(m, k)"), "(get m k)");
3533        let notes = spelling_notes("get(m, :k)\nnth(0, xs)\nget(m, k)\n").unwrap();
3534        assert_eq!(
3535            notes
3536                .iter()
3537                .filter(|n| n.spelling == Spelling::Index)
3538                .count(),
3539            2
3540        );
3541    }
3542
3543    /// `a = f x` — Ruby's command call — parsed as `a = f` and then `x`.
3544    #[test]
3545    fn a_call_without_parentheses_is_refused_naming_the_call() {
3546        let e = parse_program("a = f x").expect_err("must not split into two statements");
3547        assert!(e.message.contains("`f(x)`"), "{}", e.message);
3548        assert_eq!((e.line, e.col), (1, 7), "{e}");
3549    }
3550
3551    /// The same rule inside a block body, and in every body shape.
3552    #[test]
3553    fn two_statements_on_one_line_are_refused_in_a_body() {
3554        for src in [
3555            "def f(xs)\n  xs [0]\nend",
3556            "if a\n  f x\nend",
3557            "fn(x) x 1 end",
3558            "test \"t\"\n  assert a b\nend",
3559            "1 2",
3560        ] {
3561            assert!(parse_program(src).is_err(), "{src:?} must not parse");
3562        }
3563    }
3564
3565    /// `(x) -> e` is the inline spelling of `fn(x) e end`: one tree.
3566    #[test]
3567    fn an_arrow_lambda_lowers_to_the_same_tree_as_fn() {
3568        for (arrow, block) in [
3569            ("(x) -> x * 2", "fn(x) x * 2 end"),
3570            ("(a, b) -> a + b", "fn(a, b) a + b end"),
3571            ("() -> 1", "fn() 1 end"),
3572            ("map(xs, (x) -> x + 1)", "map(xs, fn(x) x + 1 end)"),
3573        ] {
3574            let a = parse_program(arrow).expect(arrow);
3575            let b = parse_program(block).expect(block);
3576            assert_eq!(format!("{a:?}"), format!("{b:?}"), "{arrow}");
3577        }
3578        assert_eq!(
3579            parse_program("(x)").map(|p| p.len()).ok(),
3580            Some(1),
3581            "a parenthesised name is still a group"
3582        );
3583    }
3584
3585    /// The controls: every place a statement legitimately ends on its line.
3586    /// A block keyword closing the body on the same line is one of them, which
3587    /// is what keeps a one-line lambda one line.
3588    #[test]
3589    fn a_statement_may_end_at_a_newline_the_end_or_a_closing_keyword() {
3590        for src in [
3591            "fn(x) x + 1 end",
3592            "map(fn(x) x end, xs)",
3593            "if a\n  1\nelse\n  2\nend",
3594            "if a 1 else 2 end",
3595            "case x\nwhen 1 :a\nwhen 2 :b\nelse :c\nend",
3596            "x = 1\ny = 2",
3597            "x = 1",
3598        ] {
3599            assert!(
3600                parse_program(src).is_ok(),
3601                "{src:?}: {:?}",
3602                parse_program(src)
3603            );
3604        }
3605    }
3606
3607    /// `if c then a else b end` read `then` as a statement and `a` as another.
3608    #[test]
3609    fn then_is_refused_by_name() {
3610        let e = parse_program("x = if c then 1 else 2 end").expect_err("then is not a keyword");
3611        assert!(e.message.contains("`then`"), "{}", e.message);
3612    }
3613
3614    /// A brace block after a send is not a map literal the author meant.
3615    #[test]
3616    fn a_brace_block_is_refused_naming_fn() {
3617        let e = parse_program("xs.map { |x| x }").expect_err("no brace blocks");
3618        assert!(e.message.contains("fn(x)"), "{}", e.message);
3619    }
3620
3621    // ---- qualified names ------------------------------------------------
3622
3623    /// `retsu::first(xs)` is one symbol, tatara's `require` shape.
3624    ///
3625    /// Red run (2026-09-29), before the `::` token: `expected an expression,
3626    /// found `:``.
3627    #[test]
3628    fn a_qualified_name_is_one_symbol() {
3629        assert_eq!(q("retsu::first(xs)"), "(retsu/first xs)");
3630        assert_eq!(q("retsu::first"), "retsu/first");
3631        assert_eq!(q("xs |> retsu::first"), "(retsu/first xs)");
3632        assert_eq!(q("blue::length(xs)"), "(blue/length xs)");
3633    }
3634
3635    /// Whitespace around `::` is layout, not meaning.
3636    #[test]
3637    fn whitespace_around_the_qualifier_is_accepted() {
3638        assert_eq!(q("retsu :: first(xs)"), "(retsu/first xs)");
3639    }
3640
3641    /// After `::` a reserved word is a name: `kueri::if` is kueri's
3642    /// definition, not the `if` form.
3643    #[test]
3644    fn a_reserved_word_after_the_qualifier_is_a_name() {
3645        assert_eq!(q("kueri::if(a, b)"), "(kueri/if a b)");
3646        assert_eq!(q("heni::test(x)"), "(heni/test x)");
3647        assert_eq!(q("sabi::fn"), "sabi/fn");
3648    }
3649
3650    #[test]
3651    fn a_qualified_name_has_exactly_one_qualifier() {
3652        for (src, says) in [
3653            ("::first(xs)", "`package::name`"),
3654            ("a::b::c", "one qualifier"),
3655            ("if::x", "reserved word"),
3656            ("retsu::1", "expected a name after `retsu::`"),
3657        ] {
3658            let e = parse_program(src).expect_err(src);
3659            assert!(e.message.contains(says), "{src}: {}", e.message);
3660        }
3661    }
3662
3663    /// The one reader of the shape: division is not qualified, and neither
3664    /// is anything the surface could not have written.
3665    #[test]
3666    fn qualified_reads_only_the_package_name_shape() {
3667        assert_eq!(qualified("retsu/first"), Some(("retsu", "first")));
3668        assert_eq!(qualified("kueri/if"), Some(("kueri", "if")));
3669        assert_eq!(qualified("nisshi/pair?"), Some(("nisshi", "pair?")));
3670        for not in ["/", "a/", "/a", "a/b/c", "if/x", "hash-map", "a"] {
3671            assert_eq!(qualified(not), None, "{not}");
3672        }
3673        assert!(is_callable_name("kueri/if"));
3674    }
3675
3676    /// `:pair?` is the symbol `pair?`: an import list can name a predicate.
3677    ///
3678    /// Red run (2026-09-29), before: `unexpected character `?``, found by
3679    /// `blue migrate` listing nisshi's `pair?`.
3680    #[test]
3681    fn a_symbol_may_end_in_a_question_or_bang() {
3682        assert_eq!(q("[:pair?, :set!]"), "(list :pair? :set!)");
3683        assert_eq!(q("use(\"n\", [:empty?])"), "(use \"n\" (list :empty?))");
3684        assert_eq!(q(":a != :b"), "(not= :a :b)");
3685    }
3686
3687    // ---- errors a person can read -------------------------------------
3688
3689    /// `line:col` and blue's words, never `at 10..11` and `Ident("y")`.
3690    #[test]
3691    fn a_parse_error_displays_line_col_and_the_source_text() {
3692        let e = parse_program("x = 1\ny = [1, 2 y]").expect_err("must fail");
3693        assert_eq!(e.to_string(), "2:11: expected `,` or `]`, found `y`");
3694        assert_eq!(e.span, Span::new(16, 17), "the span stays, as data");
3695    }
3696
3697    /// Every token kind renders without Rust's `Debug` shape.
3698    #[test]
3699    fn no_error_message_names_a_rust_variant() {
3700        for src in [
3701            "f(1 2)",
3702            "{a: 1 b}",
3703            "def 1\nend",
3704            "x.1",
3705            "if a\n",
3706            "fn(1) 2 end",
3707            "[1 :b]",
3708            "1 +",
3709            "(1",
3710        ] {
3711            let e = parse_program(src).expect_err(src);
3712            let shown = e.to_string();
3713            for tell in [
3714                "Ident(", "Int(", "Op(", "Label(", "Sym(", "Str(", "LParen", "RBracket", "Eof",
3715                "Newline", "..",
3716            ] {
3717                assert!(!shown.contains(tell), "{src:?} -> {shown}");
3718            }
3719            assert!(e.line >= 1 && e.col >= 1, "{src:?} not located: {shown}");
3720        }
3721    }
3722
3723    /// A lex error reaches the author through the same door, located.
3724    #[test]
3725    fn a_lex_error_is_located_too() {
3726        let e = parse_program("x = 1\ny = 2; z = 3").expect_err("no semicolons");
3727        assert_eq!((e.line, e.col), (2, 6), "{e}");
3728        assert!(e.message.contains("new line"), "{e}");
3729    }
3730
3731    /// Anti-vacuity: `q` must be able to FAIL. If every input parsed, the
3732    /// assertions above would be worthless.
3733    #[test]
3734    fn the_parser_rejects_garbage() {
3735        assert!(parse_program("def").is_err());
3736        assert!(parse_program("(1").is_err());
3737        assert!(parse_program("end").is_err());
3738    }
3739}