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};
48
49/// Why a source did not parse, and where.
50///
51/// **Structured, and located at the boundary.** `message` says what was
52/// expected and what was found, in blue's own words; `span` is the byte range
53/// of the offending text; `line` and `col` are that range's start, 1-based,
54/// with the column counted in characters. Every public entry point fills
55/// `line`/`col` from the source it was given, so `Display` reads
56/// `3:7: expected `)`, found `]`` and never a byte offset.
57///
58/// The byte offsets used to BE the display (`… at 10..11`), and a Rust
59/// `Debug` rendering named the token (`found Ident("y")`). Both are facts
60/// about the implementation; neither is something an author can act on.
61/// The span stays, as data, for any consumer that needs to point into the
62/// buffer — an editor squiggle, a diagnostic code attached downstream.
63#[derive(Clone, Debug, PartialEq)]
64pub struct ParseError {
65 pub message: String,
66 pub span: Span,
67 /// 1-based line of `span.start`.
68 pub line: usize,
69 /// 1-based column of `span.start`, in characters.
70 pub col: usize,
71}
72
73impl ParseError {
74 /// An error at `span`, not yet located: the parser sees tokens, not text,
75 /// so the line and column are filled by [`Self::located`] at the entry
76 /// point that holds the source.
77 fn new(message: impl Into<String>, span: Span) -> Self {
78 Self {
79 message: message.into(),
80 span,
81 line: 0,
82 col: 0,
83 }
84 }
85
86 /// Resolve `line`/`col` against the source this error's span indexes.
87 fn located(mut self, src: &str) -> Self {
88 let (line, col) = Span::line_col(src, self.span.start.min(src.len()));
89 self.line = line;
90 self.col = col;
91 self
92 }
93}
94
95impl std::fmt::Display for ParseError {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 write!(f, "{}:{}: {}", self.line, self.col, self.message)
98 }
99}
100
101impl std::error::Error for ParseError {}
102
103impl From<crate::lex::LexError> for ParseError {
104 fn from(e: crate::lex::LexError) -> Self {
105 Self::new(e.message, e.span)
106 }
107}
108
109/// Parse a blue program into a sequence of tatara-lisp forms.
110pub fn parse_program(src: &str) -> Result<Vec<Sexp>, ParseError> {
111 parse_program_with_depth(src, MAX_EXPR_DEPTH)
112}
113
114/// Parse a blue program keeping **every node's** source span.
115///
116/// This is the parser's real output; [`parse_program`] projects the spans away.
117/// Reach for this one whenever a position is going to be shown to a human — an
118/// editor squiggle, a `line:col` in a CLI error, a future debugger's breakpoint
119/// table. Reach for [`parse_program`] only when the consumer genuinely does not
120/// care where anything was.
121pub fn parse_program_tree(src: &str) -> Result<Vec<Spanned>, ParseError> {
122 parse_program_tree_with_depth(src, MAX_EXPR_DEPTH)
123}
124
125/// [`parse_program_tree`] with the nesting bound supplied by the caller.
126pub fn parse_program_tree_with_depth(
127 src: &str,
128 max_depth: usize,
129) -> Result<Vec<Spanned>, ParseError> {
130 let toks: Vec<Token> = lex(src)
131 .map_err(|e| ParseError::from(e).located(src))?
132 .into_iter()
133 .filter(|t| !matches!(t.kind, TokenKind::Comment(_)))
134 .collect();
135 let mut p = Parser {
136 toks,
137 pos: 0,
138 depth: 0,
139 max_depth,
140 };
141 p.program().map_err(|e| e.located(src))
142}
143
144/// Parse a program written in a [`Yakugo`](crate::yakugo::Yakugo) surface.
145///
146/// The pack is applied to the TOKEN STREAM, between lexing and parsing, so the
147/// parser below is untouched and every keyword site works by construction.
148/// What comes out is the same `Sexp` the English surface produces — that is
149/// the invariant the pack tests assert, and the only thing that makes a
150/// surface a surface rather than a dialect.
151///
152/// # Errors
153///
154/// Lex and parse errors propagate unchanged. A pack cannot repair source that
155/// does not tokenize, and reporting otherwise would name the wrong problem.
156pub fn parse_program_in(src: &str, pack: &crate::yakugo::Yakugo) -> Result<Vec<Sexp>, ParseError> {
157 Ok(parse_program_tree_in(src, pack)?
158 .iter()
159 .map(Spanned::to_sexp)
160 .collect())
161}
162
163/// [`parse_program_in`] keeping **every node's** source span.
164///
165/// The same relation [`parse_program_tree`] has to [`parse_program`], and it
166/// exists for the same reason: a surface is a spelling, so a program written in
167/// one has positions exactly as real as an English-surface program's. Without
168/// this door, `pipeline::run_in_surface` would have to lift a spanless tree back
169/// up and every type error in a `yakugo` program would report `<synthetic>` —
170/// a position the parser HAD and threw away one line earlier, which is the
171/// class `Diagnostic::span`'s own docs name.
172///
173/// [`parse_program_in`] is now its projection, so the two cannot drift.
174///
175/// # Errors
176///
177/// As [`parse_program_in`].
178pub fn parse_program_tree_in(
179 src: &str,
180 pack: &crate::yakugo::Yakugo,
181) -> Result<Vec<Spanned>, ParseError> {
182 let toks: Vec<Token> = crate::yakugo::canonical_tokens(src, pack)
183 .map_err(|e| ParseError::from(e).located(src))?
184 .into_iter()
185 .filter(|t| !matches!(t.kind, TokenKind::Comment(_)))
186 .collect();
187 let mut p = Parser {
188 toks,
189 pos: 0,
190 depth: 0,
191 max_depth: MAX_EXPR_DEPTH,
192 };
193 p.program().map_err(|e| e.located(src))
194}
195
196/// [`parse_program`] with the nesting bound supplied by the caller.
197///
198/// The bound is a **safety limit, not a dialect**: `max_depth` cannot change
199/// what any program means, only whether a pathological one is refused before
200/// the stack is at risk. That is why it is a parameter here and
201/// [`MAX_EXPR_DEPTH`] is only the default — a knob that could alter meaning
202/// would belong nowhere near a config file (see `blue-lang-cli`'s `config`
203/// module for the rule this obeys).
204pub fn parse_program_with_depth(src: &str, max_depth: usize) -> Result<Vec<Sexp>, ParseError> {
205 Ok(parse_program_tree_with_depth(src, max_depth)?
206 .iter()
207 .map(Spanned::to_sexp)
208 .collect())
209}
210
211/// Parse, keeping each top-level form's source span.
212///
213/// The spans are what let the formatter put comments back. A comment is not
214/// part of a program's *meaning*, so it has no place in the `Sexp` tree —
215/// putting it there would break canonicality, since two programs differing only
216/// in a comment would stop formatting identically. Instead the formatter renders
217/// the tree and re-interleaves comments by position, which needs to know where
218/// each form started and ended.
219///
220/// A projection of [`parse_program_tree`], which carries a span on every node
221/// rather than only the top-level ones. This entry point survives because the
222/// formatter wants exactly the top-level pairing and nothing deeper.
223pub fn parse_program_spanned(src: &str) -> Result<Vec<(Sexp, Span)>, ParseError> {
224 parse_program_spanned_with_depth(src, MAX_EXPR_DEPTH)
225}
226
227/// [`parse_program_spanned`] with the nesting bound supplied by the caller.
228pub fn parse_program_spanned_with_depth(
229 src: &str,
230 max_depth: usize,
231) -> Result<Vec<(Sexp, Span)>, ParseError> {
232 Ok(parse_program_tree_with_depth(src, max_depth)?
233 .iter()
234 .map(|f| (f.to_sexp(), f.span))
235 .collect())
236}
237
238/// Every comment in `src`, with its byte span and whether it sits alone on its
239/// line.
240///
241/// `own_line` is the distinction that decides placement: a comment alone on its
242/// line belongs *before* the form that follows, while one after code on the same
243/// line belongs *to* that line. Conflating them moves a trailing note onto the
244/// wrong row.
245pub fn comments(src: &str) -> Vec<Comment> {
246 lex(src)
247 .map(|toks| {
248 toks.iter()
249 .filter_map(|t| match &t.kind {
250 TokenKind::Comment(text) => Some(Comment {
251 text: text.clone(),
252 span: t.span,
253 own_line: line_before_is_blank(src, t.span.start),
254 }),
255 _ => None,
256 })
257 .collect()
258 })
259 .unwrap_or_default()
260}
261
262/// A comment, and where it sat.
263#[derive(Clone, Debug, PartialEq, Eq)]
264pub struct Comment {
265 /// The text, including the leading `#`.
266 pub text: String,
267 pub span: Span,
268 /// Nothing but whitespace precedes it on its line.
269 pub own_line: bool,
270}
271
272fn line_before_is_blank(src: &str, start: usize) -> bool {
273 src[..start.min(src.len())]
274 .rsplit('\n')
275 .next()
276 .is_some_and(|prefix| prefix.trim().is_empty())
277}
278
279/// Parse a single blue expression. Convenience for tests and the REPL.
280pub fn parse_expr(src: &str) -> Result<Sexp, ParseError> {
281 let forms = parse_program(src)?;
282 match forms.len() {
283 1 => Ok(forms.into_iter().next().expect("checked len")),
284 n => Err(ParseError::new(
285 format!("expected exactly one expression, found {n}"),
286 Span::new(0, src.len()),
287 )
288 .located(src)),
289 }
290}
291
292/// What an infix operator binds like, and what it lowers to.
293///
294/// **One row per operator, carrying both facts.** Precedence and callee
295/// used to live apart, and the cost was immediate: the surface spelling was
296/// emitted verbatim, so `a == b` lowered to `(== a b)` — a symbol no
297/// interpreter binds — and the program died at *runtime* with `unbound
298/// symbol ==`. Splitting the two invites exactly that: add an operator to
299/// the precedence table, forget the lowering, ship a parse that cannot run.
300/// Joined here, "has a precedence" and "has a callee" are the same fact.
301#[derive(Clone, Copy, Debug)]
302pub struct Infix {
303 /// Surface spelling.
304 pub op: &'static str,
305 /// Left and right binding power. Higher binds tighter.
306 pub power: (u8, u8),
307 /// The tatara-lisp callee this lowers to.
308 pub callee: &'static str,
309 /// One line for a reader: what the operator computes, and the trap in it
310 /// when there is one. `blue reference` prints it; a row without one fails
311 /// `every_operator_and_keyword_is_described`.
312 pub doc: &'static str,
313}
314
315/// The complete infix table. Precedence follows Ruby's where Ruby has an
316/// opinion; `|>` (below) sits under everything so `a |> f |> g` chains
317/// without parentheses.
318pub const INFIX: &[Infix] = &[
319 Infix {
320 op: "||",
321 power: (1, 2),
322 callee: "or",
323 doc: "Logical or: the left value if truthy, otherwise the right; the right is evaluated only when needed.",
324 },
325 Infix {
326 op: "&&",
327 power: (3, 4),
328 callee: "and",
329 doc: "Logical and: the right value if the left is truthy, otherwise the left; short-circuits.",
330 },
331 // `==` is STRUCTURAL equality, so it lowers to `equal?` and not to `=`.
332 //
333 // tatara's `=` is NUMERIC comparison: `"a" = "a"` is a type error, not
334 // false. Lowering `==` to it meant every string, list or nil comparison
335 // failed with "expected number, got string" — found by blue's own spec
336 // suite the moment a test compared two strings, which is the first thing
337 // anybody does.
338 //
339 // `equal?` is structural and total over the value domain: strings, lists
340 // and nil all compare, and numbers still compare as numbers.
341 Infix {
342 op: "==",
343 power: (5, 6),
344 callee: "equal?",
345 doc: "Structural equality over every value (okite D0001): 4 == 4.0, lists and maps by content, nil only equals nil.",
346 },
347 Infix {
348 op: "!=",
349 power: (5, 6),
350 callee: "not=",
351 doc: "Exactly not(a == b) (okite D0002).",
352 },
353 Infix {
354 op: "<",
355 power: (5, 6),
356 callee: "<",
357 doc: "Numeric less-than. A string operand is a type error: order text with compare(a, b).",
358 },
359 Infix {
360 op: "<=",
361 power: (5, 6),
362 callee: "<=",
363 doc: "Numeric less-than-or-equal. Numbers only, like <.",
364 },
365 Infix {
366 op: ">",
367 power: (5, 6),
368 callee: ">",
369 doc: "Numeric greater-than. Numbers only, like <.",
370 },
371 Infix {
372 op: ">=",
373 power: (5, 6),
374 callee: ">=",
375 doc: "Numeric greater-than-or-equal. Numbers only, like <.",
376 },
377 Infix {
378 op: "+",
379 power: (7, 8),
380 callee: "+",
381 doc: "Numeric addition; an Int and a Float give a Float. Not string concatenation: interpolate instead.",
382 },
383 Infix {
384 op: "-",
385 power: (7, 8),
386 callee: "-",
387 doc: "Numeric subtraction. Written before an operand with nothing on its left, it is unary minus: -n.",
388 },
389 Infix {
390 op: "*",
391 power: (9, 10),
392 callee: "*",
393 doc: "Numeric multiplication.",
394 },
395 Infix {
396 op: "/",
397 power: (9, 10),
398 callee: "/",
399 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).",
400 },
401 Infix {
402 op: "%",
403 power: (9, 10),
404 callee: "mod",
405 doc: "Euclidean remainder: never negative, so (0 - 7) % 3 is 2, not -1. A zero divisor is a runtime error.",
406 },
407];
408
409/// Every surface keyword that BEGINS an expression.
410///
411/// Exists so the formatter's corpus can be checked against it. Three separate
412/// times a form was added to this parser, the formatter was not extended, and
413/// all three formatting laws still passed — because the corpus is
414/// hand-maintained and contained no example of the new form. The annotated
415/// `def` rendered as a method send; `defmacro` rendered as
416/// `defmacro(double, x(), …)`, which does not re-parse at all.
417///
418/// A law cannot notice a case nobody wrote down. `blue-lang-fmt`'s
419/// `every_surface_keyword_appears_in_the_corpus` closes that by making the
420/// omission itself the failure, so adding a keyword here forces the corpus
421/// entry that exercises the other three laws over it.
422///
423/// `do` and `end` are absent deliberately: they are block delimiters, not
424/// expression heads, and have no standalone rendering to test.
425/// The callee `assert e` lowers to.
426///
427/// **Owned here, by the lowering itself, and read by every consumer.** It was
428/// briefly a literal here and a separate `const` in `blue-lang-test`, and the
429/// shadowing gate then could not see a parser that lowered to the wrong name:
430/// the gate checked its own copy. Same duplication class as the operator table.
431pub const LOWERED_ASSERT: &str = "blue-assert";
432
433/// The callee a `{...}` map literal lowers to.
434///
435/// **`hash-map`, not `map`.** tatara binds `map` to the higher-order function,
436/// so a literal lowering to `(map …)` called the HOF with the key/value pairs
437/// as arguments and failed with "expected list, got int". Same shadowing class
438/// as [`LOWERED_ASSERT`], caught by the same gate once the name was listed
439/// there — it was not, which is why this shipped.
440pub const LOWERED_MAP: &str = "hash-map";
441
442/// The callee string interpolation lowers to.
443///
444/// blue's own `concat`, which renders either side through `to_s` — that is what
445/// lets `"n=#{42}"` interpolate a number. Not `+`, which is arithmetic.
446pub const LOWERED_CONCAT: &str = "concat";
447
448pub const SURFACE_KEYWORDS: &[&str] = &[
449 "if",
450 "unless",
451 "def",
452 "defmacro",
453 "quote",
454 "unquote",
455 "unquote_splice",
456 "test",
457 "assert",
458 "fn",
459 "case",
460];
461
462/// The words that are reserved but are not heads of a `SURFACE_KEYWORDS` form
463/// — block delimiters and the three literals.
464///
465/// Split out as data rather than inlined in a `matches!` because a reserved
466/// word is not only the parser's business: a highlighter has to paint exactly
467/// this set, and one that reads `SURFACE_KEYWORDS` alone silently under-paints
468/// `do` / `end` / `else` / `elsif`. That was not hypothetical — escriba's
469/// `escriba-render/src/langs.rs` hand-transcribed "SURFACE_KEYWORDS plus the
470/// four block words `is_reserved_word` adds", because the union was
471/// unreachable from outside this module. A transcription is a second
472/// definition, and it drifts the first time this list changes.
473pub const BLOCK_KEYWORDS: &[&str] = &["do", "end", "else", "elsif", "true", "false", "nil"];
474
475/// A surface keyword may not be rebound. `if = 1` is a mistake, not a binding,
476/// and letting it through would shadow the form for the rest of the file.
477///
478/// Public because it is the ONE answer to "is this identifier a keyword" —
479/// the parser's rebinding check and every downstream highlighter read it here
480/// rather than each carrying its own copy of the list.
481pub fn is_reserved_word(name: &str) -> bool {
482 SURFACE_KEYWORDS.contains(&name) || BLOCK_KEYWORDS.contains(&name)
483}
484
485/// Can `name` be written as the head of a call — `name(…)`?
486///
487/// True exactly when the lexer reads `name` as one identifier and it is not
488/// reserved. Answered BY the lexer rather than by a character class copied
489/// from it, so the two cannot disagree: the formatter asks this before
490/// printing a tree as `name(args)`, and a head such as `hash-map`, `not=` or
491/// `if` — which a tree can carry and a call cannot spell — must get a
492/// different rendering or none.
493pub fn is_callable_name(name: &str) -> bool {
494 // `retsu/first` is written `retsu::first(…)`.
495 if qualified(name).is_some() {
496 return true;
497 }
498 !is_reserved_word(name)
499 && matches!(
500 lex(name).as_deref(),
501 Ok([t, e]) if matches!(&t.kind, TokenKind::Ident(n) if n == name)
502 && e.kind == TokenKind::Eof
503 )
504}
505
506/// The character a qualified name's AST symbol joins its two halves with:
507/// `retsu::first` is the symbol `retsu/first`. The surface never writes it
508/// (`/` is division, and no identifier can contain it), which is what makes
509/// a symbol with text on both sides of one `/` unambiguously qualified.
510pub const QUALIFIER: char = '/';
511
512/// The AST symbol for `pkg::name`.
513#[must_use]
514pub fn qualify(pkg: &str, name: &str) -> String {
515 format!("{pkg}{QUALIFIER}{name}")
516}
517
518/// `retsu/first` → `Some(("retsu", "first"))`: the package and the name of a
519/// qualified symbol. `None` for every other symbol, `/` (division) included.
520///
521/// The ONE reader of the shape, so the formatter, the name table and the
522/// runtime's renderer cannot disagree about what counts as qualified.
523#[must_use]
524pub fn qualified(sym: &str) -> Option<(&str, &str)> {
525 let (pkg, name) = sym.split_once(QUALIFIER)?;
526 let ident = |s: &str| {
527 matches!(
528 lex(s).as_deref(),
529 Ok([t, e]) if matches!(&t.kind, TokenKind::Ident(n) if n == s) && e.kind == TokenKind::Eof
530 )
531 };
532 let named = |s: &str| ident(s) || matches!(s, "true" | "false" | "nil");
533 (ident(pkg) && !is_reserved_word(pkg) && named(name)).then_some((pkg, name))
534}
535
536/// One line for a reader on each reserved word: what it writes, and the shape.
537///
538/// Beside the two tables rather than inside them, because both are `&[&str]`
539/// read by the formatter's corpus gate and by highlighters outside this repo;
540/// changing their type would break every one of those readers.
541/// `every_operator_and_keyword_is_described` makes a word without a line here a
542/// red build, so the omission cannot ship. `blue reference` prints these.
543#[must_use]
544pub fn keyword_doc(word: &str) -> &'static str {
545 match word {
546 "if" => "`if c … elsif d … else … end`: an expression; its value is the branch taken, nil when none is.",
547 "unless" => "`unless c … end`: `if !c`. The formatter writes it as `if !c`.",
548 "def" => "`def name(a, b) … end`: a named function; its value is the last expression. Parameters may be typed: `def f(n: Int) -> Int`.",
549 "defmacro" => "`defmacro name(x) quote … unquote(x) … end end`: a macro, a rewrite of the unevaluated form.",
550 "quote" => "`quote … end`: the form itself as data, not its value. Used inside `defmacro`.",
551 "unquote" => "`unquote(x)`: inside `quote`, splice in the value of `x`.",
552 "unquote_splice" => "`unquote_splice(xs)`: inside `quote`, splice the items of the form `xs` in place, not the form itself.",
553 "test" => "`test \"what must hold\" … end`: a test block, run by `blue test` and ignored by `blue run`.",
554 "assert" => "`assert expr`: inside a test, fail it unless `expr` is truthy; the failure quotes the expression.",
555 "fn" => "`fn(x) x * 2 end`: an anonymous function, a value. Blue has no brace or do blocks.",
556 "case" => "`case v when 1 … when 2 … else … end`: compares with `==`; it does not destructure.",
557 "do" => "Reserved and refused: blue has no do-blocks. Pass `fn(x) … end` instead.",
558 "end" => "Closes `def`, `defmacro`, `if`, `case`, `fn`, `test` and `quote`.",
559 "else" => "The branch of `if` or `case` taken when nothing before it matched.",
560 "elsif" => "A further condition in an `if` chain; the formatter writes nested `else if` as `elsif`.",
561 "true" => "The boolean true.",
562 "false" => "The boolean false. Only `false` and `nil` are falsy; 0, \"\" and [] are truthy.",
563 "nil" => "The absent value. It is not `[]` (okite D0004), and only `nil == nil`.",
564 _ => "",
565 }
566}
567
568fn infix(op: &str) -> Option<&'static Infix> {
569 INFIX.iter().find(|i| i.op == op)
570}
571
572const PIPE_POWER: (u8, u8) = (0, 1);
573
574struct Parser {
575 toks: Vec<Token>,
576 pos: usize,
577 /// Current expression-nesting depth, bounded by [`Self::max_depth`].
578 ///
579 /// Without this the parser does not fail on deep input — it **aborts the
580 /// process** with a stack overflow (SIGABRT), which `catch_unwind` cannot
581 /// catch. Measured 2026-08-01: `"(".repeat(2_000)` killed the test runner
582 /// outright. Every consumer inherited it — an LSP parsing a half-typed
583 /// line, a formatter, and shikumi loading a `.b` config off disk.
584 depth: usize,
585 /// The bound [`Self::depth`] is checked against.
586 ///
587 /// Defaults to [`MAX_EXPR_DEPTH`] on every entry point that does not name
588 /// one; `parse_program_with_depth` exists so an operator can raise it
589 /// without recompiling. It is a **bound**, so raising it changes no
590 /// program's meaning — only which pathological inputs are refused.
591 max_depth: usize,
592}
593
594/// Maximum expression nesting before the parser refuses.
595///
596/// Chosen well above anything human-written (blue's own `spec/*.b` peaks in
597/// single digits) and far below the measured overflow point, so the bound is
598/// hit as a typed `Err` long before the stack is at risk. A limit that is
599/// merely *near* the crash point is not a safety bound; it is a race.
600pub const MAX_EXPR_DEPTH: usize = 256;
601
602/// The parser's internal error: a [`ParseError`] behind a pointer.
603///
604/// Every production returns a `Result`, and a debug build keeps several per
605/// frame down the recursion, so the error's size is paid at every level of
606/// nesting whether or not anything fails. Measured 2026-09-29 on a 2 MiB
607/// debug thread, parsing `(((…1…)))` with no bound: the unboxed 40-byte error
608/// overflowed between 255 and 260 levels, barely past [`MAX_EXPR_DEPTH`];
609/// adding `line`/`col` unboxed moved it to 240–250, under the bound, and
610/// `depth_beyond_the_limit_is_an_err_not_an_abort` aborted. Boxed, the
611/// overflow is between 300 and 310. The error path is cold; the pointer is
612/// what keeps the bound a bound.
613type Fail = Box<ParseError>;
614
615fn fail(message: impl Into<String>, span: Span) -> Fail {
616 Box::new(ParseError::new(message, span))
617}
618
619impl Parser {
620 fn peek(&self) -> &TokenKind {
621 &self.toks[self.pos.min(self.toks.len() - 1)].kind
622 }
623
624 fn peek_span(&self) -> Span {
625 self.toks[self.pos.min(self.toks.len() - 1)].span
626 }
627
628 fn bump(&mut self) -> TokenKind {
629 let k = self.toks[self.pos.min(self.toks.len() - 1)].kind.clone();
630 if self.pos < self.toks.len() {
631 self.pos += 1;
632 }
633 k
634 }
635
636 fn at(&self, k: &TokenKind) -> bool {
637 self.peek() == k
638 }
639
640 fn eat(&mut self, k: &TokenKind) -> bool {
641 if self.at(k) {
642 self.bump();
643 true
644 } else {
645 false
646 }
647 }
648
649 fn expect(&mut self, k: &TokenKind, what: &str) -> Result<(), Fail> {
650 if self.eat(k) {
651 Ok(())
652 } else {
653 Err(self.error(format!("expected {what}, found {}", self.peek())))
654 }
655 }
656
657 fn error(&self, message: impl Into<String>) -> Fail {
658 fail(message, self.peek_span())
659 }
660
661 /// Skip statement separators (newlines and semicolon-free layout).
662 fn skip_newlines(&mut self) {
663 while matches!(self.peek(), TokenKind::Newline) {
664 self.bump();
665 }
666 }
667
668 fn at_ident(&self, name: &str) -> bool {
669 matches!(self.peek(), TokenKind::Ident(n) if n == name)
670 }
671
672 /// Byte offset where the next token begins — the anchor a production spans
673 /// *from*. Paired with [`Self::span_since`].
674 fn mark(&self) -> usize {
675 self.peek_span().start
676 }
677
678 /// The span from `start` to the end of the **last consumed** token.
679 ///
680 /// `pos` has already advanced past that token, so this looks one back. Call
681 /// it after a production has consumed everything it owns; calling it early
682 /// yields a span that stops short of the node it describes.
683 fn span_since(&self, start: usize) -> Span {
684 let end = self
685 .toks
686 .get(self.pos.saturating_sub(1))
687 .map_or(start, |t| t.span.end);
688 Span::new(start, end.max(start))
689 }
690
691 fn program(&mut self) -> Result<Vec<Spanned>, Fail> {
692 let mut out = Vec::new();
693 loop {
694 self.skip_newlines();
695 if matches!(self.peek(), TokenKind::Eof) {
696 break;
697 }
698 out.push(self.statement()?);
699 self.end_of_statement(&[])?;
700 }
701 Ok(out)
702 }
703
704 /// **A statement ends at the end of its line.** Refuse anything else.
705 ///
706 /// The lexer has always said newlines "are statement separators", and the
707 /// parser never asked for one: `program` and `body` looped over
708 /// `statement()` and started the next one wherever the last stopped. So a
709 /// form blue does not have became two forms it does, silently —
710 /// `y = xs[0]` parsed as `y = xs` then the list `[0]`, and Ruby's
711 /// `a = f x` as `a = f` then `x`. Both ran; both bound the wrong value.
712 ///
713 /// **Refused rather than given a meaning**, because each would be a second
714 /// spelling of a tree blue already spells one way (§0's FORM axis):
715 /// indexing is the call `nth(i, xs)`, and a call has parentheses. `;` is
716 /// refused by the lexer for the same reason — one separator, the newline.
717 ///
718 /// What may follow a statement: a newline, the end of the file, or — in a
719 /// body — the keyword that closes it, which is what keeps
720 /// `fn(x) x + 1 end` a one-line lambda.
721 fn end_of_statement(&self, terminators: &[&str]) -> Result<(), Fail> {
722 let next = self.peek();
723 if matches!(next, TokenKind::Newline | TokenKind::Eof)
724 || terminators.iter().any(|t| self.at_ident(t))
725 {
726 return Ok(());
727 }
728 let prev = self.toks.get(self.pos.wrapping_sub(1)).map(|t| &t.kind);
729 let prev_name = match prev {
730 Some(TokenKind::Ident(n)) => Some(n.as_str()),
731 _ => None,
732 };
733 let callee = prev_name.unwrap_or("f");
734 let why = match (prev, next) {
735 (Some(TokenKind::Ident(t)), _) if t == "then" => {
736 "blue's `if` has no `then`: put the branch on the next line".to_string()
737 }
738 (_, TokenKind::Ident(d)) if d == "do" => "blue has no `do` blocks: pass a function \
739 as an argument, `f(xs, fn(x) … end)`"
740 .to_string(),
741 (_, TokenKind::LBracket) => {
742 let index = match (self.toks.get(self.pos + 1), self.toks.get(self.pos + 2)) {
743 (Some(i), Some(close)) if close.kind == TokenKind::RBracket => match &i.kind {
744 TokenKind::Int(n) => n.to_string(),
745 TokenKind::Ident(n) => n.clone(),
746 _ => "i".to_string(),
747 },
748 _ => "i".to_string(),
749 };
750 let list = prev_name.unwrap_or("xs");
751 format!(
752 "blue has no `xs[i]` indexing: write `nth({index}, {list})` \
753 (or `first({list})`, `last({list})`)"
754 )
755 }
756 (_, TokenKind::LBrace) => "blue has no brace blocks: pass a function as an \
757 argument, `map(xs, fn(x) … end)`"
758 .to_string(),
759 (
760 Some(TokenKind::Ident(_)),
761 TokenKind::Ident(_)
762 | TokenKind::Int(_)
763 | TokenKind::Float(_)
764 | TokenKind::Str(_)
765 | TokenKind::InterpolatedStr { .. }
766 | TokenKind::Sym(_)
767 | TokenKind::True
768 | TokenKind::False
769 | TokenKind::Nil,
770 ) => {
771 let arg = match next {
772 TokenKind::Ident(a) => a.clone(),
773 _ => "x".to_string(),
774 };
775 format!("a call needs parentheses: write `{callee}({arg})`")
776 }
777 _ => "put each statement on its own line".to_string(),
778 };
779 Err(self.error(format!("expected the end of the line, found {next}: {why}")))
780 }
781
782 /// A statement: either a binding or an expression.
783 ///
784 /// `x = 5` lowers to `(define x 5)`. Blue had NO way to name a value — a
785 /// capability probe found `x = 5` was a parse error, which makes every
786 /// program a single expression. That is more fundamental than anything else
787 /// the probe found.
788 ///
789 /// Only at STATEMENT position, never inside an expression, so `f(x = 1)` is
790 /// still an error rather than a silent binding. Ruby allows assignment as an
791 /// expression and it is a well-known footgun — `if x = 1` where `==` was
792 /// meant. Blue declines it, and the cost is only that a walrus-style idiom
793 /// has to be two lines.
794 fn statement(&mut self) -> Result<Spanned, Fail> {
795 // The SECOND recursion cycle, and it needs the same guard as `expr`.
796 //
797 // Guarding `expr` alone was not enough — measured 2026-08-01: with the
798 // expression bound in place, `"def a\n".repeat(2_000)` STILL aborted
799 // the process. Block nesting (`def` opening a body that contains more
800 // statements) recurses through here, not through `expr`, so a fix
801 // applied to one cycle silently left the other reachable. Two paths to
802 // the same crash; one guard covered one of them.
803 //
804 // Shares `self.depth` with `expr` on purpose: what the stack cares
805 // about is TOTAL nesting, not which grammar production produced it, so
806 // two independent counters would each permit their own full budget and
807 // together exceed what the stack can hold.
808 let max = self.max_depth;
809 if self.depth >= max {
810 return Err(self.error(format!(
811 "statement nests deeper than {max}; refusing to \
812 recurse further (this is a limit, not a syntax error)"
813 )));
814 }
815 self.depth += 1;
816 let r = self.statement_inner();
817 self.depth -= 1;
818 r
819 }
820
821 fn statement_inner(&mut self) -> Result<Spanned, Fail> {
822 if let TokenKind::Ident(name) = self.peek().clone() {
823 if self.peek_at(1) == "=" && !is_reserved_word(&name) {
824 let name_span = self.peek_span();
825 self.bump(); // name
826 self.bump(); // =
827 self.skip_newlines();
828 let value = self.expr(0)?;
829 // `define` is synthesized — `x = 5` contains no such word — so
830 // it takes the span of the name being bound, which is what a
831 // reader looks at when told something about the binding.
832 return Ok(list_at(
833 self.span_since(name_span.start),
834 vec![sym_at(name_span, "define"), sym_at(name_span, &name), value],
835 ));
836 }
837 }
838 self.expr(0)
839 }
840
841 /// The token `n` positions ahead, for the two-token lookahead a binding
842 /// needs. Returns `Eof` past the end rather than panicking.
843 fn peek_at(&self, n: usize) -> String {
844 match self.toks.get(self.pos + n).map(|t| &t.kind) {
845 Some(TokenKind::Op(o)) => o.clone(),
846 _ => String::new(),
847 }
848 }
849
850 /// Pratt loop.
851 fn expr(&mut self, min_bp: u8) -> Result<Spanned, Fail> {
852 // Depth guard at the single recursion cycle (`expr` -> `prefix` ->
853 // `expr`). Returning an Err here converts an UNRECOVERABLE abort into
854 // an ordinary parse failure a caller can render — the difference
855 // between an LSP showing a squiggle and an LSP being gone.
856 //
857 // The decrement is deliberately not RAII: every exit from this
858 // function is via `?` or a normal return, and both are covered by the
859 // explicit decrements below. A guard object would be tidier but would
860 // also hide the invariant this comment is here to state.
861 let max = self.max_depth;
862 if self.depth >= max {
863 return Err(self.error(format!(
864 "expression nests deeper than {max}; refusing to \
865 recurse further (this is a limit, not a syntax error)"
866 )));
867 }
868 self.depth += 1;
869 let r = self.expr_inner(min_bp);
870 self.depth -= 1;
871 r
872 }
873
874 fn expr_inner(&mut self, min_bp: u8) -> Result<Spanned, Fail> {
875 let start = self.mark();
876 let mut lhs = self.prefix()?;
877
878 loop {
879 // Postfix: `.name`, `.name(args)`, `(args)`
880 match self.peek() {
881 TokenKind::Dot => {
882 self.bump();
883 lhs = self.finish_send(start, lhs)?;
884 continue;
885 }
886 TokenKind::LParen => {
887 // A call on an expression already parsed: `f(x)`.
888 let args = self.paren_args()?;
889 let mut list = vec![lhs];
890 list.extend(args);
891 lhs = list_at(self.span_since(start), list);
892 continue;
893 }
894 _ => {}
895 }
896
897 // Infix
898 // `callee == None` marks the pipeline, which is a rewrite rather
899 // than a call.
900 let op_span = self.peek_span();
901 let (callee, (lbp, rbp)) = match self.peek() {
902 TokenKind::Pipe => (None, PIPE_POWER),
903 TokenKind::Op(o) => match infix(o) {
904 Some(i) => (Some(i.callee), i.power),
905 None => break,
906 },
907 _ => break,
908 };
909 if lbp < min_bp {
910 break;
911 }
912 self.bump();
913 self.skip_newlines();
914 let rhs = self.expr(rbp)?;
915
916 lhs = if callee.is_none() {
917 // `x |> f` => (f x)
918 // `x |> f(a)` => (f x a) — the pipeline threads into
919 // the FIRST argument position, as Elixir's
920 // does; that is what makes it composable.
921 let rhs_span = rhs.span;
922 match rhs.form {
923 SpannedForm::List(mut items) if !items.is_empty() => {
924 items.insert(1, lhs);
925 list_at(self.span_since(start), items)
926 }
927 callee => list_at(
928 self.span_since(start),
929 vec![Spanned::new(rhs_span, callee), lhs],
930 ),
931 }
932 } else {
933 // The callee symbol takes the OPERATOR's span, not the whole
934 // expression's: `a + b` lowers to `(+ a b)` and the `+` node is
935 // the one byte-range in the source that means it. Handing it the
936 // whole expression's span would make a diagnostic about the
937 // operator underline both operands too.
938 list_at(
939 self.span_since(start),
940 vec![sym_at(op_span, callee.unwrap()), lhs, rhs],
941 )
942 };
943 }
944
945 Ok(lhs)
946 }
947
948 fn prefix(&mut self) -> Result<Spanned, Fail> {
949 let span = self.peek_span();
950 match self.bump() {
951 TokenKind::Int(v) => Ok(atom_at(span, Atom::Int(v))),
952 TokenKind::Float(v) => Ok(atom_at(span, Atom::Float(v))),
953 TokenKind::Str(s) => Ok(atom_at(span, Atom::Str(s))),
954
955 // `"a#{x}b"` → `(concat (concat "a" x) "b")`.
956 //
957 // Lowered to `concat`, not to `+`: blue's `+` is arithmetic (see
958 // the INFIX table), and interpolation must render a value of ANY
959 // type — `concat` goes through `to_s`, which is what makes
960 // `"n=#{42}"` work.
961 //
962 // The expression source is parsed HERE with the ordinary parser
963 // rather than lexed inside the string, so an interpolation can hold
964 // anything an expression can and the two can never drift.
965 TokenKind::InterpolatedStr { parts, exprs } => {
966 // Every node here carries the WHOLE string literal's span.
967 //
968 // The inner expression is parsed from `raw` — a substring — so
969 // its own offsets index that substring, not `src`. Carrying them
970 // through would produce spans that look real and point into a
971 // buffer nobody has: for `"a#{x}"` at offset 40, `x`'s span
972 // would be 0..1, i.e. the start of the file. The lexer does not
973 // record where each part sat in the outer source, so the string
974 // literal is the most precise honest answer available.
975 let mut acc = atom_at(span, Atom::Str(parts[0].clone()));
976 for (i, raw) in exprs.iter().enumerate() {
977 let inner = parse_expr(raw).map_err(|e| {
978 fail(
979 format!("in interpolation `#{{{raw}}}`: {}", e.message),
980 span,
981 )
982 })?;
983 let inner = Spanned::from_sexp_at(&inner, span);
984 acc = list_at(span, vec![sym_at(span, LOWERED_CONCAT), acc, inner]);
985 // `parts.len() == exprs.len() + 1` by construction, so this
986 // index is always in range.
987 acc = list_at(
988 span,
989 vec![
990 sym_at(span, LOWERED_CONCAT),
991 acc,
992 atom_at(span, Atom::Str(parts[i + 1].clone())),
993 ],
994 );
995 }
996 Ok(acc)
997 }
998 TokenKind::Sym(s) => Ok(atom_at(span, Atom::Keyword(s))),
999 TokenKind::True => Ok(atom_at(span, Atom::Bool(true))),
1000 TokenKind::False => Ok(atom_at(span, Atom::Bool(false))),
1001 TokenKind::Nil => Ok(Spanned::new(span, SpannedForm::Nil)),
1002
1003 TokenKind::Op(o) if o == "-" => {
1004 let rhs = self.expr(11)?; // binds tighter than `*`
1005 Ok(list_at(
1006 self.span_since(span.start),
1007 vec![sym_at(span, "-"), atom_at(span, Atom::Int(0)), rhs],
1008 ))
1009 }
1010 TokenKind::Op(o) if o == "!" => {
1011 let rhs = self.expr(11)?;
1012 Ok(list_at(
1013 self.span_since(span.start),
1014 vec![sym_at(span, "not"), rhs],
1015 ))
1016 }
1017
1018 TokenKind::LParen => {
1019 self.skip_newlines();
1020 let inner = self.expr(0)?;
1021 self.skip_newlines();
1022 self.expect(&TokenKind::RParen, "`)`")?;
1023 // The inner expression's own span, NOT one widened to include
1024 // the parentheses: grouping is not part of the expression's
1025 // meaning, and `(a + b)` should underline `a + b`.
1026 Ok(inner)
1027 }
1028
1029 TokenKind::LBracket => self.list_literal(span),
1030 TokenKind::LBrace => self.map_literal(span),
1031
1032 TokenKind::Ident(name) if self.at(&TokenKind::PathSep) => {
1033 self.qualified_name(span, &name)
1034 }
1035 TokenKind::PathSep => Err(fail(
1036 "a qualified name is `package::name`, with the package written before `::`",
1037 span,
1038 )),
1039 TokenKind::Ident(name) => match name.as_str() {
1040 "if" => self.if_form(span, false),
1041 "unless" => self.if_form(span, true),
1042 "def" => self.def_form(span),
1043 "defmacro" => self.defmacro_form(span),
1044 "case" => self.case_form(span),
1045 "fn" => self.lambda_form(span),
1046 "test" => self.test_form(span),
1047 "assert" => self.assert_form(span),
1048 "quote" => self.quote_form(span),
1049 "unquote" => self.unquote_form(span, false),
1050 "unquote_splice" => self.unquote_form(span, true),
1051 "do" => Err(fail(
1052 "blue has no `do` blocks: pass a function as an argument, \
1053 `f(xs, fn(x) … end)`",
1054 span,
1055 )),
1056 "end" => Err(fail(
1057 "unexpected `end`: nothing open here for it to close",
1058 span,
1059 )),
1060 _ => Ok(sym_at(span, &name)),
1061 },
1062
1063 other => Err(fail(format!("expected an expression, found {other}"), span)),
1064 }
1065 }
1066
1067 /// After `package`, at `::`: `retsu::first` lowers to the ONE symbol
1068 /// `retsu/first` — tatara's `require` shape, so a qualified name means the
1069 /// same thing in both lisps.
1070 ///
1071 /// After `::` any identifier is a name, reserved words included:
1072 /// `kueri::if` names kueri's definition, never the `if` form, because a
1073 /// reserved word is reserved only where it could start a form. The
1074 /// package side is never a reserved word, and a name has exactly one
1075 /// qualifier (`a::b::c` is refused), since a package is one level deep.
1076 fn qualified_name(&mut self, pkg_span: Span, pkg: &str) -> Result<Spanned, Fail> {
1077 if is_reserved_word(pkg) {
1078 return Err(fail(
1079 format!("`{pkg}` is a reserved word and cannot name a package"),
1080 pkg_span,
1081 ));
1082 }
1083 self.bump(); // ::
1084 let name_span = self.peek_span();
1085 let name = match self.bump() {
1086 TokenKind::Ident(n) => n,
1087 // `true`, `false` and `nil` lex as their own tokens.
1088 TokenKind::True => "true".to_string(),
1089 TokenKind::False => "false".to_string(),
1090 TokenKind::Nil => "nil".to_string(),
1091 other => {
1092 return Err(fail(
1093 format!("expected a name after `{pkg}::`, found {other}"),
1094 name_span,
1095 ))
1096 }
1097 };
1098 if self.at(&TokenKind::PathSep) {
1099 return Err(self.error(format!(
1100 "a qualified name has one qualifier: `package::name`, and `{pkg}::{name}::…` has two"
1101 )));
1102 }
1103 Ok(sym_at(
1104 self.span_since(pkg_span.start),
1105 &qualify(pkg, &name),
1106 ))
1107 }
1108
1109 /// After a `.`: `recv.name` or `recv.name(args)`.
1110 ///
1111 /// **A bare `recv.name` is a SEND, not a field read.** Blue commits to
1112 /// the uniform access principle here: a structure exposes no public
1113 /// fields, so a field can later become a computed method without
1114 /// breaking a caller.
1115 fn finish_send(&mut self, start: usize, recv: Spanned) -> Result<Spanned, Fail> {
1116 let name_span = self.peek_span();
1117 let name = match self.bump() {
1118 // A RESERVED WORD is not a method name.
1119 //
1120 // Found by the formatter property suite, minimal input `1.def`.
1121 // The send parsed happily into `(def 1)` — `def` is just an
1122 // identifier to the lexer — and the formatter then rendered that
1123 // as `def(1)`, which the parser rejects. So `format` turned valid
1124 // source into source that does not parse: corruption, not a style
1125 // choice, and silent until a round-trip property looked.
1126 //
1127 // Rejecting here rather than teaching the formatter to quote it
1128 // fixes the class instead of the symptom: `x.if`, `x.end` and
1129 // `x.case` all lower onto special forms the same way, and none of
1130 // them is a method anyone meant to call.
1131 TokenKind::Ident(n) if is_reserved_word(&n) => {
1132 return Err(self.error(format!(
1133 "`{n}` is a reserved word and cannot be a method name — \
1134 `recv.{n}` would lower onto the `{n}` form itself"
1135 )))
1136 }
1137 TokenKind::Ident(n) => n,
1138 other => {
1139 return Err(fail(
1140 format!("expected a method name after `.`, found {other}"),
1141 name_span,
1142 ))
1143 }
1144 };
1145 let mut list = vec![sym_at(name_span, &name), recv];
1146 if self.at(&TokenKind::LParen) {
1147 list.extend(self.paren_args()?);
1148 }
1149 Ok(list_at(self.span_since(start), list))
1150 }
1151
1152 fn paren_args(&mut self) -> Result<Vec<Spanned>, Fail> {
1153 self.expect(&TokenKind::LParen, "`(`")?;
1154 let mut args = Vec::new();
1155 self.skip_newlines();
1156 if self.eat(&TokenKind::RParen) {
1157 return Ok(args);
1158 }
1159 loop {
1160 self.skip_newlines();
1161 args.push(self.expr(0)?);
1162 self.skip_newlines();
1163 if self.eat(&TokenKind::Comma) {
1164 continue;
1165 }
1166 self.expect(&TokenKind::RParen, "`,` or `)`")?;
1167 break;
1168 }
1169 Ok(args)
1170 }
1171
1172 fn list_literal(&mut self, open: Span) -> Result<Spanned, Fail> {
1173 let mut items = vec![sym_at(open, "list")];
1174 self.skip_newlines();
1175 if self.eat(&TokenKind::RBracket) {
1176 return Ok(list_at(self.span_since(open.start), items));
1177 }
1178 loop {
1179 self.skip_newlines();
1180 items.push(self.expr(0)?);
1181 self.skip_newlines();
1182 if self.eat(&TokenKind::Comma) {
1183 continue;
1184 }
1185 self.expect(&TokenKind::RBracket, "`,` or `]`")?;
1186 break;
1187 }
1188 Ok(list_at(self.span_since(open.start), items))
1189 }
1190
1191 /// `{a: 1, "k" => v}` — both spellings, one tree.
1192 ///
1193 /// This is §V.13's rendering law at the parser: `a: 1` and `:a => 1`
1194 /// produce the *same* s-expression, which is precisely why the
1195 /// formatter may always choose the shorthand. The rocket survives only
1196 /// where the key is not a plain symbol.
1197 fn map_literal(&mut self, open: Span) -> Result<Spanned, Fail> {
1198 let mut items = vec![sym_at(open, LOWERED_MAP)];
1199 self.skip_newlines();
1200 if self.eat(&TokenKind::RBrace) {
1201 return Ok(list_at(self.span_since(open.start), items));
1202 }
1203 loop {
1204 self.skip_newlines();
1205 match self.peek().clone() {
1206 TokenKind::Label(name) => {
1207 let label_span = self.peek_span();
1208 self.bump();
1209 self.skip_newlines();
1210 items.push(atom_at(label_span, Atom::Keyword(name)));
1211 items.push(self.expr(0)?);
1212 }
1213 _ => {
1214 let k = self.expr(0)?;
1215 self.skip_newlines();
1216 self.expect(&TokenKind::Rocket, "`=>` in a map literal")?;
1217 self.skip_newlines();
1218 items.push(k);
1219 items.push(self.expr(0)?);
1220 }
1221 }
1222 self.skip_newlines();
1223 if self.eat(&TokenKind::Comma) {
1224 continue;
1225 }
1226 self.expect(&TokenKind::RBrace, "`,` or `}`")?;
1227 break;
1228 }
1229 Ok(list_at(self.span_since(open.start), items))
1230 }
1231
1232 /// `if c ... [else ...] end`, and `unless` as its negation.
1233 ///
1234 /// `unless` lowers to `(if (not c) ...)` rather than to a distinct
1235 /// form: one tree per meaning, so the formatter and every downstream
1236 /// tool see exactly one shape.
1237 /// An `elsif` arm: an `if` that does NOT consume the closing `end`.
1238 ///
1239 /// `if / elsif / elsif / else / end` is one `end` for the whole chain, so
1240 /// every arm but the first must leave it for its parent.
1241 fn if_chain(&mut self, head: Span) -> Result<Spanned, Fail> {
1242 let cond = self.expr(0)?;
1243 let then = self.body(&["elsif", "else", "end"])?;
1244 let els = if self.at_ident("elsif") {
1245 let elsif = self.peek_span();
1246 self.bump();
1247 Some(self.if_chain(elsif)?)
1248 } else if self.at_ident("else") {
1249 self.bump();
1250 let e = self.body(&["end"])?;
1251 self.expect_ident("end")?;
1252 Some(e)
1253 } else {
1254 self.expect_ident("end")?;
1255 None
1256 };
1257 let mut out = vec![sym_at(head, "if"), cond, then];
1258 if let Some(e) = els {
1259 out.push(e);
1260 }
1261 Ok(list_at(self.span_since(head.start), out))
1262 }
1263
1264 fn if_form(&mut self, head: Span, negate: bool) -> Result<Spanned, Fail> {
1265 let cond = self.expr(0)?;
1266 let cond = if negate {
1267 // `unless c` lowers to `(if (not c) …)`. The synthesized `not` takes
1268 // the `unless` keyword's span — that word is what put it there.
1269 let inner = cond.span;
1270 list_at(head.merge(inner), vec![sym_at(head, "not"), cond])
1271 } else {
1272 cond
1273 };
1274 // `elsif` terminates the then-body too, or the chain is swallowed.
1275 //
1276 // It used to be absent entirely — not a keyword, not reserved, nowhere
1277 // in this file — so `elsif cond` parsed as a stray expression inside
1278 // the then-body and the branch it guarded VANISHED. No error: the
1279 // program ran and returned the `else` value. Measured:
1280 //
1281 // if a < 1 then 1 elsif a < 5 then 2 else 3 end with a = 3
1282 // wanted 2, returned 3
1283 //
1284 // A silent wrong answer in the most-used control form in the language,
1285 // reachable by writing the Ruby every blue user already knows.
1286 let then = self.body(&["elsif", "else", "end"])?;
1287 let els = if self.at_ident("elsif") {
1288 let elsif = self.peek_span();
1289 self.bump();
1290 // The chain shares ONE `end`, so recurse without consuming it and
1291 // let the outermost `if` close the whole thing.
1292 Some(self.if_chain(elsif)?)
1293 } else if self.at_ident("else") {
1294 self.bump();
1295 let e = self.body(&["end"])?;
1296 self.expect_ident("end")?;
1297 Some(e)
1298 } else {
1299 self.expect_ident("end")?;
1300 None
1301 };
1302 let mut out = vec![sym_at(head, "if"), cond, then];
1303 if let Some(e) = els {
1304 out.push(e);
1305 }
1306 Ok(list_at(self.span_since(head.start), out))
1307 }
1308
1309 /// `def name(a, b) ... end` => `(define (name a b) body)`
1310 /// `def name(a: T, b: T) -> R ... end` => `(define-typed (name (a T) (b T)) R body)`
1311 ///
1312 /// **The two shapes are deliberately different heads.** §0 says an
1313 /// unannotated program gets ZERO analysis, and the cleanest way to
1314 /// mean that is for untyped code not to reach the typing machinery at
1315 /// all — not to reach it and be waved through. A checker that must
1316 /// walk every node to discover there is nothing to check has already
1317 /// paid the cost the ladder exists to avoid.
1318 ///
1319 /// Annotations are per-parameter, so a signature may be partially
1320 /// annotated. That is the ladder at its finest grain: `a: Int` is
1321 /// checked and a bare `b` stays `dyn`, in the same signature.
1322 /// `case subject / when a / … / else / … / end` => a `cond` over equality.
1323 ///
1324 /// **Value matching, not destructuring.** Elixir's `case` binds pattern
1325 /// variables; blue's compares with the same `equal?` the `==` operator uses,
1326 /// so `when [1, 2]` matches a list by value. Destructuring needs a pattern
1327 /// language and a binder, which blue does not have — and a `case` that
1328 /// *looked* like Elixir's while silently only comparing would be worse than
1329 /// one that plainly compares.
1330 ///
1331 /// The subject is evaluated ONCE, into a binding, so `case expensive()` does
1332 /// not re-run per arm. That is a correctness property, not an optimisation:
1333 /// a subject with a side effect would fire once per `when`.
1334 fn case_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1335 let subject = self.expr(0)?;
1336 self.skip_newlines();
1337
1338 // A fresh name the surface cannot spell, so it cannot capture a user
1339 // binding of the same name.
1340 let subject_var = "case-subject";
1341 let mut arms: Vec<Spanned> = Vec::new();
1342 let mut otherwise: Option<Spanned> = None;
1343 // The `else` keyword's own span, so the synthesized `(else body)` clause
1344 // sits where the author wrote it rather than back at `case`.
1345 let mut else_kw: Option<Span> = None;
1346
1347 loop {
1348 self.skip_newlines();
1349 if self.at_ident("end") {
1350 break;
1351 }
1352 let maybe_else = self.peek_span();
1353 if self.eat_ident("else") {
1354 else_kw = Some(maybe_else);
1355 otherwise = Some(self.body(&["end"])?);
1356 continue;
1357 }
1358 let when = self.peek_span();
1359 if !self.eat_ident("when") {
1360 return Err(self.error(format!(
1361 "expected `when`, `else` or `end` in a case, found {}",
1362 self.peek()
1363 )));
1364 }
1365 self.skip_newlines();
1366 let pattern = self.expr(0)?;
1367 let body = self.body(&["when", "else", "end"])?;
1368 // The synthesized comparison takes the arm's `when` span: that word
1369 // is what put an `equal?` there, and it is where a reader looks when
1370 // told an arm cannot match.
1371 let test = list_at(
1372 when.merge(pattern.span),
1373 vec![sym_at(when, "equal?"), sym_at(when, subject_var), pattern],
1374 );
1375 arms.push(list_at(when.merge(body.span), vec![test, body]));
1376 }
1377 self.expect_ident("end")?;
1378
1379 if arms.is_empty() && otherwise.is_none() {
1380 return Err(self.error("a case needs at least one `when` or an `else`".to_string()));
1381 }
1382
1383 // A case with no matching arm and no else is NIL, matching Ruby. Elixir
1384 // raises CaseClauseError; blue follows Ruby because its `if` without an
1385 // else is already nil, and having two different answers to "no branch
1386 // taken" in one language is the inconsistency.
1387 let mut cond = vec![sym_at(head, "cond")];
1388 cond.extend(arms);
1389 // The `else` clause spans its own keyword through its body. Anchoring it
1390 // at `head` — the `case` keyword — put a node whose subtree sits at the
1391 // END of the form at a span near its START, so the else body escaped its
1392 // parent's range entirely. `every_node_sits_inside_its_parents_span`
1393 // caught that; it is the kind of mistake no output-shape test can see,
1394 // because the tree is correct and only the positions are wrong.
1395 let else_span = else_kw.unwrap_or(head);
1396 let else_body = otherwise.unwrap_or_else(|| Spanned::new(else_span, SpannedForm::Nil));
1397 cond.push(list_at(
1398 else_span.merge(else_body.span),
1399 vec![sym_at(else_span, "else"), else_body],
1400 ));
1401
1402 let whole = self.span_since(head.start);
1403 let binding = list_at(
1404 head.merge(subject.span),
1405 vec![sym_at(head, subject_var), subject],
1406 );
1407 Ok(list_at(
1408 whole,
1409 vec![
1410 sym_at(head, "let"),
1411 list_at(binding.span, vec![binding]),
1412 list_at(whole, cond),
1413 ],
1414 ))
1415 }
1416
1417 /// `fn(a, b) ... end` => `(lambda (a b) body)`
1418 ///
1419 /// Without this the higher-order functions are unreachable in practice:
1420 /// `map(inc, xs)` works only because `inc` happens to be a named stdlib
1421 /// function, and there was no way to write the one-off the call site
1422 /// actually wants.
1423 ///
1424 /// `fn` rather than Ruby's `->` or `lambda`: `->` collides with the return-
1425 /// type arrow the typed `def` already uses, and reusing one glyph for two
1426 /// unrelated things is the ambiguity the FORM axis exists to prevent.
1427 fn lambda_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1428 let mut params: Vec<Spanned> = Vec::new();
1429 if self.at(&TokenKind::LParen) {
1430 self.bump();
1431 self.skip_newlines();
1432 if !self.eat(&TokenKind::RParen) {
1433 loop {
1434 self.skip_newlines();
1435 let p_span = self.peek_span();
1436 match self.bump() {
1437 TokenKind::Ident(p) => params.push(sym_at(p_span, &p)),
1438 other => {
1439 return Err(fail(
1440 format!("expected a parameter name, found {other}"),
1441 p_span,
1442 ))
1443 }
1444 }
1445 self.skip_newlines();
1446 if self.eat(&TokenKind::Comma) {
1447 continue;
1448 }
1449 self.expect(&TokenKind::RParen, "`,` or `)`")?;
1450 break;
1451 }
1452 }
1453 }
1454 let params_span = cover(¶ms, head);
1455 let body = self.body(&["end"])?;
1456 self.expect_ident("end")?;
1457 Ok(list_at(
1458 self.span_since(head.start),
1459 vec![sym_at(head, "lambda"), list_at(params_span, params), body],
1460 ))
1461 }
1462
1463 /// `test "name" ... end` => `(deftest "name" body)`
1464 ///
1465 /// A string, not an identifier: a test name is prose for a human report,
1466 /// and forcing it into an identifier is how test names become
1467 /// `test_adds_two_numbers_correctly`.
1468 fn test_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1469 let name_span = self.peek_span();
1470 let name = match self.bump() {
1471 TokenKind::Str(s) => s,
1472 other => {
1473 return Err(fail(
1474 format!("expected a string name after `test`, found {other}"),
1475 name_span,
1476 ))
1477 }
1478 };
1479 let body = self.body(&["end"])?;
1480 self.expect_ident("end")?;
1481 Ok(list_at(
1482 self.span_since(head.start),
1483 vec![
1484 sym_at(head, "deftest"),
1485 atom_at(name_span, Atom::Str(name)),
1486 body,
1487 ],
1488 ))
1489 }
1490
1491 /// `assert expr` => `(blue-assert 'expr expr)`
1492 ///
1493 /// **`blue-assert`, not `assert`.** tatara-lisp's stdlib already defines
1494 /// `assert` as a macro — `(defmacro assert (pred message) …)` — and a macro
1495 /// in the expander is consulted before any primitive in the registry. So
1496 /// lowering to `assert` bound `pred` to the *quoted form*, which is
1497 /// truthy, and **every assertion silently passed**. A test framework whose
1498 /// assertions always pass is the worst defect it can have: every test in
1499 /// the suite goes green.
1500 ///
1501 /// The lesson generalizes: any name blue lowers to that tatara already
1502 /// binds is silently captured. `blue_lang_test`'s
1503 /// `no_lowered_name_is_shadowed_by_the_runtime` gates the whole class.
1504 ///
1505 /// **Both the form and the value.** A test framework whose failure says
1506 /// only "assertion failed" makes the author re-derive what they were
1507 /// checking; one that shows the expression does not. The quoted form is
1508 /// the expression as DATA, so the runner can render it — and it renders it
1509 /// through `blue-lang-fmt`, meaning the failure message is in canonical
1510 /// blue syntax rather than the underlying tatara-lisp.
1511 ///
1512 /// This is homoiconicity paying for itself: the capture needs no source
1513 /// map, no macro hygiene, and no string of the original text.
1514 fn assert_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1515 let e = self.expr(0)?;
1516 let quoted = Spanned::new(e.span, SpannedForm::Quote(Box::new(e.clone())));
1517 Ok(list_at(
1518 self.span_since(head.start),
1519 vec![sym_at(head, LOWERED_ASSERT), quoted, e],
1520 ))
1521 }
1522
1523 /// `defmacro name(a, b) ... end` => `(defmacro name (a b) body)`
1524 ///
1525 /// **Deliberately untyped.** A macro's parameters are *source forms*, not
1526 /// values, so `a: Int` would be a category error: the argument at expansion
1527 /// time is a fragment of syntax. §IV's ladder types values; macro
1528 /// parameters are not on it. Annotating one is rejected rather than
1529 /// silently ignored — an ignored annotation is how an author comes to
1530 /// believe a check is running.
1531 fn defmacro_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1532 let name_span = self.peek_span();
1533 let name = match self.bump() {
1534 TokenKind::Ident(n) => n,
1535 other => {
1536 return Err(fail(
1537 format!("expected a name after `defmacro`, found {other}"),
1538 name_span,
1539 ))
1540 }
1541 };
1542 let mut params: Vec<Spanned> = Vec::new();
1543 if self.at(&TokenKind::LParen) {
1544 self.bump();
1545 self.skip_newlines();
1546 if !self.eat(&TokenKind::RParen) {
1547 loop {
1548 self.skip_newlines();
1549 let p_span = self.peek_span();
1550 match self.bump() {
1551 TokenKind::Ident(p) => params.push(sym_at(p_span, &p)),
1552 TokenKind::Label(p) => {
1553 return Err(self.error(format!(
1554 "macro parameter `{p}` cannot be typed: a macro receives \
1555 source forms, not values"
1556 )))
1557 }
1558 other => {
1559 return Err(fail(
1560 format!("expected a parameter name, found {other}"),
1561 p_span,
1562 ))
1563 }
1564 }
1565 self.skip_newlines();
1566 if self.eat(&TokenKind::Comma) {
1567 continue;
1568 }
1569 self.expect(&TokenKind::RParen, "`,` or `)`")?;
1570 break;
1571 }
1572 }
1573 }
1574 if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
1575 return Err(self.error(
1576 "a macro has no return type: it produces source forms, not values".to_string(),
1577 ));
1578 }
1579
1580 let params_span = cover(¶ms, name_span);
1581 let body = self.body(&["end"])?;
1582 self.expect_ident("end")?;
1583
1584 // `(defmacro name (params) body)` — tatara-lisp's own shape, so blue
1585 // registers into the SAME expander rather than a parallel one.
1586 Ok(list_at(
1587 self.span_since(head.start),
1588 vec![
1589 sym_at(head, "defmacro"),
1590 sym_at(name_span, &name),
1591 list_at(params_span, params),
1592 body,
1593 ],
1594 ))
1595 }
1596
1597 /// `quote ... end` => `` `body `` (a quasiquote).
1598 ///
1599 /// Quasiquote rather than plain quote, because a macro body that could not
1600 /// splice its arguments in would be useless — this is Elixir's `quote do`,
1601 /// which is likewise a template and not inert data.
1602 fn quote_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1603 let body = self.body(&["end"])?;
1604 self.expect_ident("end")?;
1605 // `Sexp::Quasiquote`, NOT `(quasiquote body)` as a list.
1606 //
1607 // The list form Displays as the text `(quasiquote …)`, which the
1608 // tatara-lisp reader reads back as an ordinary list whose head happens
1609 // to be the symbol `quasiquote` — losing the structure. The evaluator
1610 // then reached the inner `,x` with no enclosing quasiquote and rejected
1611 // it: "unquote outside of quasiquote". Building the real variant makes
1612 // it Display as `` ` `` and survive the round trip.
1613 Ok(Spanned::new(
1614 self.span_since(head.start),
1615 SpannedForm::Quasiquote(Box::new(body)),
1616 ))
1617 }
1618
1619 /// `unquote(expr)` => `,expr`; `unquote_splice(expr)` => `,@expr`.
1620 fn unquote_form(&mut self, head: Span, splice: bool) -> Result<Spanned, Fail> {
1621 self.expect(&TokenKind::LParen, "`(` after unquote")?;
1622 self.skip_newlines();
1623 let inner = self.expr(0)?;
1624 self.skip_newlines();
1625 self.expect(&TokenKind::RParen, "`)`")?;
1626 let span = self.span_since(head.start);
1627 Ok(Spanned::new(
1628 span,
1629 if splice {
1630 SpannedForm::UnquoteSplice(Box::new(inner))
1631 } else {
1632 SpannedForm::Unquote(Box::new(inner))
1633 },
1634 ))
1635 }
1636
1637 fn def_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1638 let name_span = self.peek_span();
1639 let name = match self.bump() {
1640 TokenKind::Ident(n) => n,
1641 other => {
1642 return Err(fail(
1643 format!("expected a name after `def`, found {other}"),
1644 name_span,
1645 ))
1646 }
1647 };
1648 let mut params: Vec<(String, Span, Option<Spanned>)> = Vec::new();
1649 if self.at(&TokenKind::LParen) {
1650 self.bump();
1651 self.skip_newlines();
1652 if !self.eat(&TokenKind::RParen) {
1653 loop {
1654 self.skip_newlines();
1655 let p_span = self.peek_span();
1656 match self.bump() {
1657 // `a` — unannotated
1658 TokenKind::Ident(p) => params.push((p, p_span, None)),
1659 // `a:` came through as one token, so a type follows
1660 TokenKind::Label(p) => {
1661 self.skip_newlines();
1662 let ty = self.type_expr()?;
1663 params.push((p, p_span, Some(ty)));
1664 }
1665 other => {
1666 return Err(fail(
1667 format!("expected a parameter name, found {other}"),
1668 p_span,
1669 ))
1670 }
1671 }
1672 self.skip_newlines();
1673 if self.eat(&TokenKind::Comma) {
1674 continue;
1675 }
1676 self.expect(&TokenKind::RParen, "`,` or `)`")?;
1677 break;
1678 }
1679 }
1680 }
1681 // The signature list spans the name through the closing `)`.
1682 let sig_span = self.span_since(name_span.start);
1683
1684 // Optional `-> R`
1685 let ret = if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
1686 self.bump();
1687 self.skip_newlines();
1688 Some(self.type_expr()?)
1689 } else {
1690 None
1691 };
1692
1693 let body = self.body(&["end"])?;
1694 self.expect_ident("end")?;
1695 let whole = self.span_since(head.start);
1696
1697 let annotated = ret.is_some() || params.iter().any(|(_, _, t)| t.is_some());
1698 if !annotated {
1699 let mut sig = vec![sym_at(name_span, &name)];
1700 sig.extend(params.into_iter().map(|(p, s, _)| sym_at(s, &p)));
1701 return Ok(list_at(
1702 whole,
1703 vec![sym_at(head, "define"), list_at(sig_span, sig), body],
1704 ));
1705 }
1706
1707 // Typed shape. An un-annotated parameter in an otherwise annotated
1708 // signature is written `(p dyn)` so the checker sees the ladder
1709 // position explicitly rather than inferring it from absence.
1710 //
1711 // A `dyn` written by the parser rather than the author takes the
1712 // parameter's own span, so a diagnostic about it points at the
1713 // parameter — the only thing in the source it could mean.
1714 let mut sig = vec![sym_at(name_span, &name)];
1715 for (p, s, t) in params {
1716 let ty = t.unwrap_or_else(|| sym_at(s, "dyn"));
1717 sig.push(list_at(s.merge(ty.span), vec![sym_at(s, &p), ty]));
1718 }
1719 Ok(list_at(
1720 whole,
1721 vec![
1722 sym_at(head, "define-typed"),
1723 list_at(sig_span, sig),
1724 ret.unwrap_or_else(|| sym_at(head, "dyn")),
1725 body,
1726 ],
1727 ))
1728 }
1729
1730 /// A type expression. Currently a bare name (`Int`, `Str`, `dyn`) or a
1731 /// one-argument constructor (`List(Int)`).
1732 fn type_expr(&mut self) -> Result<Spanned, Fail> {
1733 let name_span = self.peek_span();
1734 let name = match self.bump() {
1735 TokenKind::Ident(n) => n,
1736 other => {
1737 return Err(fail(
1738 format!("expected a type name, found {other}"),
1739 name_span,
1740 ))
1741 }
1742 };
1743 if self.at(&TokenKind::LParen) {
1744 let args = self.paren_args()?;
1745 let mut list = vec![sym_at(name_span, &name)];
1746 list.extend(args);
1747 return Ok(list_at(self.span_since(name_span.start), list));
1748 }
1749 Ok(sym_at(name_span, &name))
1750 }
1751
1752 /// Consume `name` if it is the next token, else leave the position alone.
1753 fn eat_ident(&mut self, name: &str) -> bool {
1754 if self.at_ident(name) {
1755 self.bump();
1756 true
1757 } else {
1758 false
1759 }
1760 }
1761
1762 fn expect_ident(&mut self, name: &str) -> Result<(), Fail> {
1763 if self.at_ident(name) {
1764 self.bump();
1765 Ok(())
1766 } else {
1767 Err(self.error(format!("expected `{name}`, found {}", self.peek())))
1768 }
1769 }
1770
1771 /// A sequence of expressions up to one of `terminators`, wrapped in
1772 /// `(begin ...)` when there is more than one.
1773 fn body(&mut self, terminators: &[&str]) -> Result<Spanned, Fail> {
1774 // Anchored BEFORE the leading newlines are skipped, so an empty body's
1775 // span sits where the body would have started.
1776 let start = self.mark();
1777 let mut forms = Vec::new();
1778 loop {
1779 self.skip_newlines();
1780 if matches!(self.peek(), TokenKind::Eof) {
1781 return Err(self.error(format!(
1782 "unterminated block: expected {} before the end of the file",
1783 one_of(terminators)
1784 )));
1785 }
1786 if terminators.iter().any(|t| self.at_ident(t)) {
1787 break;
1788 }
1789 forms.push(self.statement()?);
1790 self.end_of_statement(terminators)?;
1791 }
1792 Ok(match forms.len() {
1793 0 => Spanned::new(Span::new(start, start), SpannedForm::Nil),
1794 1 => forms.into_iter().next().expect("checked len"),
1795 _ => {
1796 // `cover`, NOT `span_since`: the loop breaks *before* consuming
1797 // the terminator but *after* `skip_newlines`, so the last token
1798 // behind `pos` can be a newline and `span_since` would stretch
1799 // the body across trailing blank lines. The forms know exactly
1800 // where they are.
1801 let span = cover(&forms, Span::new(start, start));
1802 // The synthesized `begin` is zero-width at the FIRST FORM's
1803 // start, not at `start`. `start` is anchored before the leading
1804 // newlines are skipped, so it sits earlier than the body itself
1805 // — and a head node outside its own list's span is a span bug
1806 // that `every_node_sits_inside_its_parents_span` reports.
1807 let head = Span::new(span.start, span.start);
1808 let mut list = vec![sym_at(head, "begin")];
1809 list.extend(forms);
1810 list_at(span, list)
1811 }
1812 })
1813 }
1814}
1815
1816/// `` `a` ``, `` `a` or `b` ``, `` `a`, `b` or `c` `` — a list of keywords as
1817/// a sentence says it.
1818fn one_of(words: &[&str]) -> String {
1819 let quoted: Vec<String> = words.iter().map(|w| format!("`{w}`")).collect();
1820 match quoted.split_last() {
1821 None => String::new(),
1822 Some((last, [])) => last.clone(),
1823 Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
1824 }
1825}
1826
1827/// A symbol node at `span`.
1828fn sym_at(span: Span, s: &str) -> Spanned {
1829 Spanned::new(span, SpannedForm::Atom(Atom::Symbol(s.to_string())))
1830}
1831
1832/// An atom node at `span`.
1833fn atom_at(span: Span, a: Atom) -> Spanned {
1834 Spanned::new(span, SpannedForm::Atom(a))
1835}
1836
1837/// A list node at `span`.
1838fn list_at(span: Span, items: Vec<Spanned>) -> Spanned {
1839 Spanned::new(span, SpannedForm::List(items))
1840}
1841
1842/// The smallest span covering every node in `items`, or `fallback` when there
1843/// are none.
1844///
1845/// The fallback is a parameter rather than `Span::synthetic()` because a
1846/// synthetic span is a claim that a node has no source origin at all — and an
1847/// empty parameter list in `def f()` very much has one. Defaulting to synthetic
1848/// here is how "no span" leaks into a tree where every node does have a place.
1849fn cover(items: &[Spanned], fallback: Span) -> Span {
1850 let merged = items
1851 .iter()
1852 .fold(Span::synthetic(), |acc, s| acc.merge(s.span));
1853 if merged.is_synthetic() {
1854 fallback
1855 } else {
1856 merged
1857 }
1858}
1859
1860#[cfg(test)]
1861mod tests {
1862 use super::*;
1863
1864 /// Render an `Sexp` to canonical text so tests can state the expected
1865 /// quoted form as a string. This is `Display`, which tatara-lisp owns —
1866 /// blue does not build Lisp syntax by concatenation.
1867 fn q(src: &str) -> String {
1868 parse_expr(src)
1869 .map(|s| s.to_string())
1870 .unwrap_or_else(|e| panic!("{src:?}: {e}"))
1871 }
1872
1873 // ---- the thesis: Ruby-shaped source becomes tatara-lisp ----------
1874
1875 #[test]
1876 fn arithmetic_respects_precedence() {
1877 assert_eq!(q("1 + 2 * 3"), "(+ 1 (* 2 3))");
1878 assert_eq!(q("(1 + 2) * 3"), "(* (+ 1 2) 3)");
1879 }
1880
1881 #[test]
1882 fn comparison_binds_looser_than_arithmetic() {
1883 assert_eq!(q("a + 1 < b"), "(< (+ a 1) b)");
1884 }
1885
1886 /// The expected tree names `or`/`and`, not `||`/`&&`: the surface
1887 /// spelling is the SURFACE's, and lowering renames it to the form
1888 /// tatara-lisp actually has. This test previously asserted the verbatim
1889 /// spelling, which is how `(== a b)` — a symbol nothing binds — shipped.
1890 #[test]
1891 fn logical_operators_bind_loosest_and_lower_to_tataras_names() {
1892 assert_eq!(q("a && b || c"), "(or (and a b) c)");
1893 }
1894
1895 #[test]
1896 fn left_associativity() {
1897 assert_eq!(q("1 - 2 - 3"), "(- (- 1 2) 3)");
1898 }
1899
1900 /// A bare `recv.name` is a SEND. Blue commits to uniform access here,
1901 /// so a field can later become a computed method without breaking
1902 /// callers.
1903 #[test]
1904 fn method_call_without_parens_is_a_send() {
1905 assert_eq!(q("user.name"), "(name user)");
1906 }
1907
1908 #[test]
1909 fn method_call_with_args() {
1910 assert_eq!(q("user.greet(1, 2)"), "(greet user 1 2)");
1911 }
1912
1913 #[test]
1914 fn chained_sends_read_left_to_right() {
1915 assert_eq!(q("a.b.c"), "(c (b a))");
1916 }
1917
1918 #[test]
1919 fn plain_call() {
1920 assert_eq!(q("f(1, 2)"), "(f 1 2)");
1921 }
1922
1923 /// The pipeline threads into the FIRST argument, as Elixir's does —
1924 /// that is what makes `|>` composable rather than decorative.
1925 #[test]
1926 fn pipeline_threads_into_first_argument() {
1927 assert_eq!(q("x |> f"), "(f x)");
1928 assert_eq!(q("x |> f(1)"), "(f x 1)");
1929 assert_eq!(q("x |> f |> g"), "(g (f x))");
1930 }
1931
1932 #[test]
1933 fn pipeline_binds_looser_than_arithmetic() {
1934 assert_eq!(q("1 + 2 |> f"), "(f (+ 1 2))");
1935 }
1936
1937 // ---- §V.13's rendering law, enforced at the parser ---------------
1938
1939 /// `a: 1` and `:a => 1` are the SAME TREE. That is exactly why the
1940 /// formatter may always render the shorthand: they are not two
1941 /// spellings of two things, they are two spellings of one thing.
1942 #[test]
1943 fn label_and_rocket_produce_the_same_tree_for_a_symbol_key() {
1944 assert_eq!(q("{a: 1}"), q("{:a => 1}"));
1945 assert_eq!(q("{a: 1}"), "(hash-map :a 1)");
1946 }
1947
1948 /// And where the key is NOT a plain symbol, the rocket is the only
1949 /// spelling — so it survives because it must, never as a style choice.
1950 #[test]
1951 fn a_string_key_has_no_shorthand() {
1952 assert_eq!(q(r#"{"k" => 1}"#), r#"(hash-map "k" 1)"#);
1953 }
1954
1955 #[test]
1956 fn list_literal() {
1957 assert_eq!(q("[1, 2, 3]"), "(list 1 2 3)");
1958 assert_eq!(q("[]"), "(list)");
1959 }
1960
1961 // ---- blocks ------------------------------------------------------
1962
1963 #[test]
1964 fn if_else_end() {
1965 assert_eq!(q("if a\n 1\nelse\n 2\nend"), "(if a 1 2)");
1966 }
1967
1968 #[test]
1969 fn if_without_else() {
1970 assert_eq!(q("if a\n 1\nend"), "(if a 1)");
1971 }
1972
1973 /// `unless` lowers to `(if (not c) …)` — one tree per meaning, so
1974 /// every downstream tool sees exactly one shape.
1975 #[test]
1976 fn unless_is_a_negated_if() {
1977 assert_eq!(q("unless a\n 1\nend"), "(if (not a) 1)");
1978 }
1979
1980 #[test]
1981 fn multi_statement_body_becomes_begin() {
1982 assert_eq!(q("if a\n 1\n 2\nend"), "(if a (begin 1 2))");
1983 }
1984
1985 #[test]
1986 fn def_lowers_to_define() {
1987 assert_eq!(
1988 q("def add(a, b)\n a + b\nend"),
1989 "(define (add a b) (+ a b))"
1990 );
1991 }
1992
1993 #[test]
1994 fn def_with_no_params() {
1995 assert_eq!(q("def zero()\n 0\nend"), "(define (zero) 0)");
1996 }
1997
1998 // ---- literals ----------------------------------------------------
1999
2000 #[test]
2001 fn literals_lower_to_atoms() {
2002 assert_eq!(q("42"), "42");
2003 assert_eq!(q("true"), "#t");
2004 assert_eq!(q(":ok"), ":ok");
2005 assert_eq!(q(r#""hi""#), r#""hi""#);
2006 }
2007
2008 #[test]
2009 fn unary_minus_and_not() {
2010 assert_eq!(q("-x"), "(- 0 x)");
2011 assert_eq!(q("!x"), "(not x)");
2012 }
2013
2014 // ---- programs and errors -----------------------------------------
2015
2016 #[test]
2017 fn a_program_is_a_sequence_of_forms() {
2018 let forms = parse_program("def f()\n 1\nend\nf()").expect("parse");
2019 assert_eq!(forms.len(), 2);
2020 assert_eq!(forms[1].to_string(), "(f)");
2021 }
2022
2023 #[test]
2024 fn unterminated_block_is_an_error_naming_what_was_expected() {
2025 let e = parse_program("if a\n 1").expect_err("must fail");
2026 assert!(e.message.contains("unterminated"), "{}", e.message);
2027 }
2028
2029 #[test]
2030 fn a_parse_error_carries_a_span_into_the_source() {
2031 let src = "1 + )";
2032 let e = parse_program(src).expect_err("must fail");
2033 assert!(e.span.start < src.len(), "span {:?} outside source", e.span);
2034 }
2035
2036 // ---- one statement per line -------------------------------------
2037
2038 /// `y = xs[0]` was TWO statements, `(define y xs)` and `(list 0)`: nothing
2039 /// required a separator between statements, so the parser finished `xs`,
2040 /// saw a list literal and started a new statement on the same line. The
2041 /// program ran and `y` was the whole list. Found by the 2026-09-29 audit.
2042 #[test]
2043 fn postfix_indexing_is_refused_naming_nth() {
2044 let e = parse_program("y = xs[0]").expect_err("must not split into two statements");
2045 assert!(e.message.contains("`nth(0, xs)`"), "{}", e.message);
2046 assert_eq!((e.line, e.col), (1, 7), "{e}");
2047 }
2048
2049 /// `a = f x` — Ruby's command call — parsed as `a = f` and then `x`.
2050 #[test]
2051 fn a_call_without_parentheses_is_refused_naming_the_call() {
2052 let e = parse_program("a = f x").expect_err("must not split into two statements");
2053 assert!(e.message.contains("`f(x)`"), "{}", e.message);
2054 assert_eq!((e.line, e.col), (1, 7), "{e}");
2055 }
2056
2057 /// The same rule inside a block body, and in every body shape.
2058 #[test]
2059 fn two_statements_on_one_line_are_refused_in_a_body() {
2060 for src in [
2061 "def f(xs)\n xs[0]\nend",
2062 "if a\n f x\nend",
2063 "fn(x) x 1 end",
2064 "test \"t\"\n assert a b\nend",
2065 "1 2",
2066 ] {
2067 assert!(parse_program(src).is_err(), "{src:?} must not parse");
2068 }
2069 }
2070
2071 /// The controls: every place a statement legitimately ends on its line.
2072 /// A block keyword closing the body on the same line is one of them, which
2073 /// is what keeps a one-line lambda one line.
2074 #[test]
2075 fn a_statement_may_end_at_a_newline_the_end_or_a_closing_keyword() {
2076 for src in [
2077 "fn(x) x + 1 end",
2078 "map(fn(x) x end, xs)",
2079 "if a\n 1\nelse\n 2\nend",
2080 "if a 1 else 2 end",
2081 "case x\nwhen 1 :a\nwhen 2 :b\nelse :c\nend",
2082 "x = 1\ny = 2",
2083 "x = 1",
2084 ] {
2085 assert!(
2086 parse_program(src).is_ok(),
2087 "{src:?}: {:?}",
2088 parse_program(src)
2089 );
2090 }
2091 }
2092
2093 /// `if c then a else b end` read `then` as a statement and `a` as another.
2094 #[test]
2095 fn then_is_refused_by_name() {
2096 let e = parse_program("x = if c then 1 else 2 end").expect_err("then is not a keyword");
2097 assert!(e.message.contains("`then`"), "{}", e.message);
2098 }
2099
2100 /// A brace block after a send is not a map literal the author meant.
2101 #[test]
2102 fn a_brace_block_is_refused_naming_fn() {
2103 let e = parse_program("xs.map { |x| x }").expect_err("no brace blocks");
2104 assert!(e.message.contains("fn(x)"), "{}", e.message);
2105 }
2106
2107 // ---- qualified names ------------------------------------------------
2108
2109 /// `retsu::first(xs)` is one symbol, tatara's `require` shape.
2110 ///
2111 /// Red run (2026-09-29), before the `::` token: `expected an expression,
2112 /// found `:``.
2113 #[test]
2114 fn a_qualified_name_is_one_symbol() {
2115 assert_eq!(q("retsu::first(xs)"), "(retsu/first xs)");
2116 assert_eq!(q("retsu::first"), "retsu/first");
2117 assert_eq!(q("xs |> retsu::first"), "(retsu/first xs)");
2118 assert_eq!(q("blue::length(xs)"), "(blue/length xs)");
2119 }
2120
2121 /// Whitespace around `::` is layout, not meaning.
2122 #[test]
2123 fn whitespace_around_the_qualifier_is_accepted() {
2124 assert_eq!(q("retsu :: first(xs)"), "(retsu/first xs)");
2125 }
2126
2127 /// After `::` a reserved word is a name: `kueri::if` is kueri's
2128 /// definition, not the `if` form.
2129 #[test]
2130 fn a_reserved_word_after_the_qualifier_is_a_name() {
2131 assert_eq!(q("kueri::if(a, b)"), "(kueri/if a b)");
2132 assert_eq!(q("heni::test(x)"), "(heni/test x)");
2133 assert_eq!(q("sabi::fn"), "sabi/fn");
2134 }
2135
2136 #[test]
2137 fn a_qualified_name_has_exactly_one_qualifier() {
2138 for (src, says) in [
2139 ("::first(xs)", "`package::name`"),
2140 ("a::b::c", "one qualifier"),
2141 ("if::x", "reserved word"),
2142 ("retsu::1", "expected a name after `retsu::`"),
2143 ] {
2144 let e = parse_program(src).expect_err(src);
2145 assert!(e.message.contains(says), "{src}: {}", e.message);
2146 }
2147 }
2148
2149 /// The one reader of the shape: division is not qualified, and neither
2150 /// is anything the surface could not have written.
2151 #[test]
2152 fn qualified_reads_only_the_package_name_shape() {
2153 assert_eq!(qualified("retsu/first"), Some(("retsu", "first")));
2154 assert_eq!(qualified("kueri/if"), Some(("kueri", "if")));
2155 assert_eq!(qualified("nisshi/pair?"), Some(("nisshi", "pair?")));
2156 for not in ["/", "a/", "/a", "a/b/c", "if/x", "hash-map", "a"] {
2157 assert_eq!(qualified(not), None, "{not}");
2158 }
2159 assert!(is_callable_name("kueri/if"));
2160 }
2161
2162 /// `:pair?` is the symbol `pair?`: an import list can name a predicate.
2163 ///
2164 /// Red run (2026-09-29), before: `unexpected character `?``, found by
2165 /// `blue migrate` listing nisshi's `pair?`.
2166 #[test]
2167 fn a_symbol_may_end_in_a_question_or_bang() {
2168 assert_eq!(q("[:pair?, :set!]"), "(list :pair? :set!)");
2169 assert_eq!(q("use(\"n\", [:empty?])"), "(use \"n\" (list :empty?))");
2170 assert_eq!(q(":a != :b"), "(not= :a :b)");
2171 }
2172
2173 // ---- errors a person can read -------------------------------------
2174
2175 /// `line:col` and blue's words, never `at 10..11` and `Ident("y")`.
2176 #[test]
2177 fn a_parse_error_displays_line_col_and_the_source_text() {
2178 let e = parse_program("x = 1\ny = [1, 2 y]").expect_err("must fail");
2179 assert_eq!(e.to_string(), "2:11: expected `,` or `]`, found `y`");
2180 assert_eq!(e.span, Span::new(16, 17), "the span stays, as data");
2181 }
2182
2183 /// Every token kind renders without Rust's `Debug` shape.
2184 #[test]
2185 fn no_error_message_names_a_rust_variant() {
2186 for src in [
2187 "f(1 2)",
2188 "{a: 1 b}",
2189 "def 1\nend",
2190 "x.1",
2191 "if a\n",
2192 "fn(1) 2 end",
2193 "[1 :b]",
2194 "1 +",
2195 "(1",
2196 ] {
2197 let e = parse_program(src).expect_err(src);
2198 let shown = e.to_string();
2199 for tell in [
2200 "Ident(", "Int(", "Op(", "Label(", "Sym(", "Str(", "LParen", "RBracket", "Eof",
2201 "Newline", "..",
2202 ] {
2203 assert!(!shown.contains(tell), "{src:?} -> {shown}");
2204 }
2205 assert!(e.line >= 1 && e.col >= 1, "{src:?} not located: {shown}");
2206 }
2207 }
2208
2209 /// A lex error reaches the author through the same door, located.
2210 #[test]
2211 fn a_lex_error_is_located_too() {
2212 let e = parse_program("x = 1\ny = 2; z = 3").expect_err("no semicolons");
2213 assert_eq!((e.line, e.col), (2, 6), "{e}");
2214 assert!(e.message.contains("new line"), "{e}");
2215 }
2216
2217 /// Anti-vacuity: `q` must be able to FAIL. If every input parsed, the
2218 /// assertions above would be worthless.
2219 #[test]
2220 fn the_parser_rejects_garbage() {
2221 assert!(parse_program("def").is_err());
2222 assert!(parse_program("(1").is_err());
2223 assert!(parse_program("end").is_err());
2224 }
2225}