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(self.span_since(pkg_span.start), &qualify(pkg, &name)))
1104 }
1105
1106 /// After a `.`: `recv.name` or `recv.name(args)`.
1107 ///
1108 /// **A bare `recv.name` is a SEND, not a field read.** Blue commits to
1109 /// the uniform access principle here: a structure exposes no public
1110 /// fields, so a field can later become a computed method without
1111 /// breaking a caller.
1112 fn finish_send(&mut self, start: usize, recv: Spanned) -> Result<Spanned, Fail> {
1113 let name_span = self.peek_span();
1114 let name = match self.bump() {
1115 // A RESERVED WORD is not a method name.
1116 //
1117 // Found by the formatter property suite, minimal input `1.def`.
1118 // The send parsed happily into `(def 1)` — `def` is just an
1119 // identifier to the lexer — and the formatter then rendered that
1120 // as `def(1)`, which the parser rejects. So `format` turned valid
1121 // source into source that does not parse: corruption, not a style
1122 // choice, and silent until a round-trip property looked.
1123 //
1124 // Rejecting here rather than teaching the formatter to quote it
1125 // fixes the class instead of the symptom: `x.if`, `x.end` and
1126 // `x.case` all lower onto special forms the same way, and none of
1127 // them is a method anyone meant to call.
1128 TokenKind::Ident(n) if is_reserved_word(&n) => {
1129 return Err(self.error(format!(
1130 "`{n}` is a reserved word and cannot be a method name — \
1131 `recv.{n}` would lower onto the `{n}` form itself"
1132 )))
1133 }
1134 TokenKind::Ident(n) => n,
1135 other => {
1136 return Err(fail(
1137 format!("expected a method name after `.`, found {other}"),
1138 name_span,
1139 ))
1140 }
1141 };
1142 let mut list = vec![sym_at(name_span, &name), recv];
1143 if self.at(&TokenKind::LParen) {
1144 list.extend(self.paren_args()?);
1145 }
1146 Ok(list_at(self.span_since(start), list))
1147 }
1148
1149 fn paren_args(&mut self) -> Result<Vec<Spanned>, Fail> {
1150 self.expect(&TokenKind::LParen, "`(`")?;
1151 let mut args = Vec::new();
1152 self.skip_newlines();
1153 if self.eat(&TokenKind::RParen) {
1154 return Ok(args);
1155 }
1156 loop {
1157 self.skip_newlines();
1158 args.push(self.expr(0)?);
1159 self.skip_newlines();
1160 if self.eat(&TokenKind::Comma) {
1161 continue;
1162 }
1163 self.expect(&TokenKind::RParen, "`,` or `)`")?;
1164 break;
1165 }
1166 Ok(args)
1167 }
1168
1169 fn list_literal(&mut self, open: Span) -> Result<Spanned, Fail> {
1170 let mut items = vec![sym_at(open, "list")];
1171 self.skip_newlines();
1172 if self.eat(&TokenKind::RBracket) {
1173 return Ok(list_at(self.span_since(open.start), items));
1174 }
1175 loop {
1176 self.skip_newlines();
1177 items.push(self.expr(0)?);
1178 self.skip_newlines();
1179 if self.eat(&TokenKind::Comma) {
1180 continue;
1181 }
1182 self.expect(&TokenKind::RBracket, "`,` or `]`")?;
1183 break;
1184 }
1185 Ok(list_at(self.span_since(open.start), items))
1186 }
1187
1188 /// `{a: 1, "k" => v}` — both spellings, one tree.
1189 ///
1190 /// This is §V.13's rendering law at the parser: `a: 1` and `:a => 1`
1191 /// produce the *same* s-expression, which is precisely why the
1192 /// formatter may always choose the shorthand. The rocket survives only
1193 /// where the key is not a plain symbol.
1194 fn map_literal(&mut self, open: Span) -> Result<Spanned, Fail> {
1195 let mut items = vec![sym_at(open, LOWERED_MAP)];
1196 self.skip_newlines();
1197 if self.eat(&TokenKind::RBrace) {
1198 return Ok(list_at(self.span_since(open.start), items));
1199 }
1200 loop {
1201 self.skip_newlines();
1202 match self.peek().clone() {
1203 TokenKind::Label(name) => {
1204 let label_span = self.peek_span();
1205 self.bump();
1206 self.skip_newlines();
1207 items.push(atom_at(label_span, Atom::Keyword(name)));
1208 items.push(self.expr(0)?);
1209 }
1210 _ => {
1211 let k = self.expr(0)?;
1212 self.skip_newlines();
1213 self.expect(&TokenKind::Rocket, "`=>` in a map literal")?;
1214 self.skip_newlines();
1215 items.push(k);
1216 items.push(self.expr(0)?);
1217 }
1218 }
1219 self.skip_newlines();
1220 if self.eat(&TokenKind::Comma) {
1221 continue;
1222 }
1223 self.expect(&TokenKind::RBrace, "`,` or `}`")?;
1224 break;
1225 }
1226 Ok(list_at(self.span_since(open.start), items))
1227 }
1228
1229 /// `if c ... [else ...] end`, and `unless` as its negation.
1230 ///
1231 /// `unless` lowers to `(if (not c) ...)` rather than to a distinct
1232 /// form: one tree per meaning, so the formatter and every downstream
1233 /// tool see exactly one shape.
1234 /// An `elsif` arm: an `if` that does NOT consume the closing `end`.
1235 ///
1236 /// `if / elsif / elsif / else / end` is one `end` for the whole chain, so
1237 /// every arm but the first must leave it for its parent.
1238 fn if_chain(&mut self, head: Span) -> Result<Spanned, Fail> {
1239 let cond = self.expr(0)?;
1240 let then = self.body(&["elsif", "else", "end"])?;
1241 let els = if self.at_ident("elsif") {
1242 let elsif = self.peek_span();
1243 self.bump();
1244 Some(self.if_chain(elsif)?)
1245 } else if self.at_ident("else") {
1246 self.bump();
1247 let e = self.body(&["end"])?;
1248 self.expect_ident("end")?;
1249 Some(e)
1250 } else {
1251 self.expect_ident("end")?;
1252 None
1253 };
1254 let mut out = vec![sym_at(head, "if"), cond, then];
1255 if let Some(e) = els {
1256 out.push(e);
1257 }
1258 Ok(list_at(self.span_since(head.start), out))
1259 }
1260
1261 fn if_form(&mut self, head: Span, negate: bool) -> Result<Spanned, Fail> {
1262 let cond = self.expr(0)?;
1263 let cond = if negate {
1264 // `unless c` lowers to `(if (not c) …)`. The synthesized `not` takes
1265 // the `unless` keyword's span — that word is what put it there.
1266 let inner = cond.span;
1267 list_at(head.merge(inner), vec![sym_at(head, "not"), cond])
1268 } else {
1269 cond
1270 };
1271 // `elsif` terminates the then-body too, or the chain is swallowed.
1272 //
1273 // It used to be absent entirely — not a keyword, not reserved, nowhere
1274 // in this file — so `elsif cond` parsed as a stray expression inside
1275 // the then-body and the branch it guarded VANISHED. No error: the
1276 // program ran and returned the `else` value. Measured:
1277 //
1278 // if a < 1 then 1 elsif a < 5 then 2 else 3 end with a = 3
1279 // wanted 2, returned 3
1280 //
1281 // A silent wrong answer in the most-used control form in the language,
1282 // reachable by writing the Ruby every blue user already knows.
1283 let then = self.body(&["elsif", "else", "end"])?;
1284 let els = if self.at_ident("elsif") {
1285 let elsif = self.peek_span();
1286 self.bump();
1287 // The chain shares ONE `end`, so recurse without consuming it and
1288 // let the outermost `if` close the whole thing.
1289 Some(self.if_chain(elsif)?)
1290 } else if self.at_ident("else") {
1291 self.bump();
1292 let e = self.body(&["end"])?;
1293 self.expect_ident("end")?;
1294 Some(e)
1295 } else {
1296 self.expect_ident("end")?;
1297 None
1298 };
1299 let mut out = vec![sym_at(head, "if"), cond, then];
1300 if let Some(e) = els {
1301 out.push(e);
1302 }
1303 Ok(list_at(self.span_since(head.start), out))
1304 }
1305
1306 /// `def name(a, b) ... end` => `(define (name a b) body)`
1307 /// `def name(a: T, b: T) -> R ... end` => `(define-typed (name (a T) (b T)) R body)`
1308 ///
1309 /// **The two shapes are deliberately different heads.** §0 says an
1310 /// unannotated program gets ZERO analysis, and the cleanest way to
1311 /// mean that is for untyped code not to reach the typing machinery at
1312 /// all — not to reach it and be waved through. A checker that must
1313 /// walk every node to discover there is nothing to check has already
1314 /// paid the cost the ladder exists to avoid.
1315 ///
1316 /// Annotations are per-parameter, so a signature may be partially
1317 /// annotated. That is the ladder at its finest grain: `a: Int` is
1318 /// checked and a bare `b` stays `dyn`, in the same signature.
1319 /// `case subject / when a / … / else / … / end` => a `cond` over equality.
1320 ///
1321 /// **Value matching, not destructuring.** Elixir's `case` binds pattern
1322 /// variables; blue's compares with the same `equal?` the `==` operator uses,
1323 /// so `when [1, 2]` matches a list by value. Destructuring needs a pattern
1324 /// language and a binder, which blue does not have — and a `case` that
1325 /// *looked* like Elixir's while silently only comparing would be worse than
1326 /// one that plainly compares.
1327 ///
1328 /// The subject is evaluated ONCE, into a binding, so `case expensive()` does
1329 /// not re-run per arm. That is a correctness property, not an optimisation:
1330 /// a subject with a side effect would fire once per `when`.
1331 fn case_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1332 let subject = self.expr(0)?;
1333 self.skip_newlines();
1334
1335 // A fresh name the surface cannot spell, so it cannot capture a user
1336 // binding of the same name.
1337 let subject_var = "case-subject";
1338 let mut arms: Vec<Spanned> = Vec::new();
1339 let mut otherwise: Option<Spanned> = None;
1340 // The `else` keyword's own span, so the synthesized `(else body)` clause
1341 // sits where the author wrote it rather than back at `case`.
1342 let mut else_kw: Option<Span> = None;
1343
1344 loop {
1345 self.skip_newlines();
1346 if self.at_ident("end") {
1347 break;
1348 }
1349 let maybe_else = self.peek_span();
1350 if self.eat_ident("else") {
1351 else_kw = Some(maybe_else);
1352 otherwise = Some(self.body(&["end"])?);
1353 continue;
1354 }
1355 let when = self.peek_span();
1356 if !self.eat_ident("when") {
1357 return Err(self.error(format!(
1358 "expected `when`, `else` or `end` in a case, found {}",
1359 self.peek()
1360 )));
1361 }
1362 self.skip_newlines();
1363 let pattern = self.expr(0)?;
1364 let body = self.body(&["when", "else", "end"])?;
1365 // The synthesized comparison takes the arm's `when` span: that word
1366 // is what put an `equal?` there, and it is where a reader looks when
1367 // told an arm cannot match.
1368 let test = list_at(
1369 when.merge(pattern.span),
1370 vec![sym_at(when, "equal?"), sym_at(when, subject_var), pattern],
1371 );
1372 arms.push(list_at(when.merge(body.span), vec![test, body]));
1373 }
1374 self.expect_ident("end")?;
1375
1376 if arms.is_empty() && otherwise.is_none() {
1377 return Err(self.error("a case needs at least one `when` or an `else`".to_string()));
1378 }
1379
1380 // A case with no matching arm and no else is NIL, matching Ruby. Elixir
1381 // raises CaseClauseError; blue follows Ruby because its `if` without an
1382 // else is already nil, and having two different answers to "no branch
1383 // taken" in one language is the inconsistency.
1384 let mut cond = vec![sym_at(head, "cond")];
1385 cond.extend(arms);
1386 // The `else` clause spans its own keyword through its body. Anchoring it
1387 // at `head` — the `case` keyword — put a node whose subtree sits at the
1388 // END of the form at a span near its START, so the else body escaped its
1389 // parent's range entirely. `every_node_sits_inside_its_parents_span`
1390 // caught that; it is the kind of mistake no output-shape test can see,
1391 // because the tree is correct and only the positions are wrong.
1392 let else_span = else_kw.unwrap_or(head);
1393 let else_body = otherwise.unwrap_or_else(|| Spanned::new(else_span, SpannedForm::Nil));
1394 cond.push(list_at(
1395 else_span.merge(else_body.span),
1396 vec![sym_at(else_span, "else"), else_body],
1397 ));
1398
1399 let whole = self.span_since(head.start);
1400 let binding = list_at(
1401 head.merge(subject.span),
1402 vec![sym_at(head, subject_var), subject],
1403 );
1404 Ok(list_at(
1405 whole,
1406 vec![
1407 sym_at(head, "let"),
1408 list_at(binding.span, vec![binding]),
1409 list_at(whole, cond),
1410 ],
1411 ))
1412 }
1413
1414 /// `fn(a, b) ... end` => `(lambda (a b) body)`
1415 ///
1416 /// Without this the higher-order functions are unreachable in practice:
1417 /// `map(inc, xs)` works only because `inc` happens to be a named stdlib
1418 /// function, and there was no way to write the one-off the call site
1419 /// actually wants.
1420 ///
1421 /// `fn` rather than Ruby's `->` or `lambda`: `->` collides with the return-
1422 /// type arrow the typed `def` already uses, and reusing one glyph for two
1423 /// unrelated things is the ambiguity the FORM axis exists to prevent.
1424 fn lambda_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1425 let mut params: Vec<Spanned> = Vec::new();
1426 if self.at(&TokenKind::LParen) {
1427 self.bump();
1428 self.skip_newlines();
1429 if !self.eat(&TokenKind::RParen) {
1430 loop {
1431 self.skip_newlines();
1432 let p_span = self.peek_span();
1433 match self.bump() {
1434 TokenKind::Ident(p) => params.push(sym_at(p_span, &p)),
1435 other => {
1436 return Err(fail(
1437 format!("expected a parameter name, found {other}"),
1438 p_span,
1439 ))
1440 }
1441 }
1442 self.skip_newlines();
1443 if self.eat(&TokenKind::Comma) {
1444 continue;
1445 }
1446 self.expect(&TokenKind::RParen, "`,` or `)`")?;
1447 break;
1448 }
1449 }
1450 }
1451 let params_span = cover(¶ms, head);
1452 let body = self.body(&["end"])?;
1453 self.expect_ident("end")?;
1454 Ok(list_at(
1455 self.span_since(head.start),
1456 vec![sym_at(head, "lambda"), list_at(params_span, params), body],
1457 ))
1458 }
1459
1460 /// `test "name" ... end` => `(deftest "name" body)`
1461 ///
1462 /// A string, not an identifier: a test name is prose for a human report,
1463 /// and forcing it into an identifier is how test names become
1464 /// `test_adds_two_numbers_correctly`.
1465 fn test_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1466 let name_span = self.peek_span();
1467 let name = match self.bump() {
1468 TokenKind::Str(s) => s,
1469 other => {
1470 return Err(fail(
1471 format!("expected a string name after `test`, found {other}"),
1472 name_span,
1473 ))
1474 }
1475 };
1476 let body = self.body(&["end"])?;
1477 self.expect_ident("end")?;
1478 Ok(list_at(
1479 self.span_since(head.start),
1480 vec![
1481 sym_at(head, "deftest"),
1482 atom_at(name_span, Atom::Str(name)),
1483 body,
1484 ],
1485 ))
1486 }
1487
1488 /// `assert expr` => `(blue-assert 'expr expr)`
1489 ///
1490 /// **`blue-assert`, not `assert`.** tatara-lisp's stdlib already defines
1491 /// `assert` as a macro — `(defmacro assert (pred message) …)` — and a macro
1492 /// in the expander is consulted before any primitive in the registry. So
1493 /// lowering to `assert` bound `pred` to the *quoted form*, which is
1494 /// truthy, and **every assertion silently passed**. A test framework whose
1495 /// assertions always pass is the worst defect it can have: every test in
1496 /// the suite goes green.
1497 ///
1498 /// The lesson generalizes: any name blue lowers to that tatara already
1499 /// binds is silently captured. `blue_lang_test`'s
1500 /// `no_lowered_name_is_shadowed_by_the_runtime` gates the whole class.
1501 ///
1502 /// **Both the form and the value.** A test framework whose failure says
1503 /// only "assertion failed" makes the author re-derive what they were
1504 /// checking; one that shows the expression does not. The quoted form is
1505 /// the expression as DATA, so the runner can render it — and it renders it
1506 /// through `blue-lang-fmt`, meaning the failure message is in canonical
1507 /// blue syntax rather than the underlying tatara-lisp.
1508 ///
1509 /// This is homoiconicity paying for itself: the capture needs no source
1510 /// map, no macro hygiene, and no string of the original text.
1511 fn assert_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1512 let e = self.expr(0)?;
1513 let quoted = Spanned::new(e.span, SpannedForm::Quote(Box::new(e.clone())));
1514 Ok(list_at(
1515 self.span_since(head.start),
1516 vec![sym_at(head, LOWERED_ASSERT), quoted, e],
1517 ))
1518 }
1519
1520 /// `defmacro name(a, b) ... end` => `(defmacro name (a b) body)`
1521 ///
1522 /// **Deliberately untyped.** A macro's parameters are *source forms*, not
1523 /// values, so `a: Int` would be a category error: the argument at expansion
1524 /// time is a fragment of syntax. §IV's ladder types values; macro
1525 /// parameters are not on it. Annotating one is rejected rather than
1526 /// silently ignored — an ignored annotation is how an author comes to
1527 /// believe a check is running.
1528 fn defmacro_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1529 let name_span = self.peek_span();
1530 let name = match self.bump() {
1531 TokenKind::Ident(n) => n,
1532 other => {
1533 return Err(fail(
1534 format!("expected a name after `defmacro`, found {other}"),
1535 name_span,
1536 ))
1537 }
1538 };
1539 let mut params: Vec<Spanned> = Vec::new();
1540 if self.at(&TokenKind::LParen) {
1541 self.bump();
1542 self.skip_newlines();
1543 if !self.eat(&TokenKind::RParen) {
1544 loop {
1545 self.skip_newlines();
1546 let p_span = self.peek_span();
1547 match self.bump() {
1548 TokenKind::Ident(p) => params.push(sym_at(p_span, &p)),
1549 TokenKind::Label(p) => {
1550 return Err(self.error(format!(
1551 "macro parameter `{p}` cannot be typed: a macro receives \
1552 source forms, not values"
1553 )))
1554 }
1555 other => {
1556 return Err(fail(
1557 format!("expected a parameter name, found {other}"),
1558 p_span,
1559 ))
1560 }
1561 }
1562 self.skip_newlines();
1563 if self.eat(&TokenKind::Comma) {
1564 continue;
1565 }
1566 self.expect(&TokenKind::RParen, "`,` or `)`")?;
1567 break;
1568 }
1569 }
1570 }
1571 if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
1572 return Err(self.error(
1573 "a macro has no return type: it produces source forms, not values".to_string(),
1574 ));
1575 }
1576
1577 let params_span = cover(¶ms, name_span);
1578 let body = self.body(&["end"])?;
1579 self.expect_ident("end")?;
1580
1581 // `(defmacro name (params) body)` — tatara-lisp's own shape, so blue
1582 // registers into the SAME expander rather than a parallel one.
1583 Ok(list_at(
1584 self.span_since(head.start),
1585 vec![
1586 sym_at(head, "defmacro"),
1587 sym_at(name_span, &name),
1588 list_at(params_span, params),
1589 body,
1590 ],
1591 ))
1592 }
1593
1594 /// `quote ... end` => `` `body `` (a quasiquote).
1595 ///
1596 /// Quasiquote rather than plain quote, because a macro body that could not
1597 /// splice its arguments in would be useless — this is Elixir's `quote do`,
1598 /// which is likewise a template and not inert data.
1599 fn quote_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1600 let body = self.body(&["end"])?;
1601 self.expect_ident("end")?;
1602 // `Sexp::Quasiquote`, NOT `(quasiquote body)` as a list.
1603 //
1604 // The list form Displays as the text `(quasiquote …)`, which the
1605 // tatara-lisp reader reads back as an ordinary list whose head happens
1606 // to be the symbol `quasiquote` — losing the structure. The evaluator
1607 // then reached the inner `,x` with no enclosing quasiquote and rejected
1608 // it: "unquote outside of quasiquote". Building the real variant makes
1609 // it Display as `` ` `` and survive the round trip.
1610 Ok(Spanned::new(
1611 self.span_since(head.start),
1612 SpannedForm::Quasiquote(Box::new(body)),
1613 ))
1614 }
1615
1616 /// `unquote(expr)` => `,expr`; `unquote_splice(expr)` => `,@expr`.
1617 fn unquote_form(&mut self, head: Span, splice: bool) -> Result<Spanned, Fail> {
1618 self.expect(&TokenKind::LParen, "`(` after unquote")?;
1619 self.skip_newlines();
1620 let inner = self.expr(0)?;
1621 self.skip_newlines();
1622 self.expect(&TokenKind::RParen, "`)`")?;
1623 let span = self.span_since(head.start);
1624 Ok(Spanned::new(
1625 span,
1626 if splice {
1627 SpannedForm::UnquoteSplice(Box::new(inner))
1628 } else {
1629 SpannedForm::Unquote(Box::new(inner))
1630 },
1631 ))
1632 }
1633
1634 fn def_form(&mut self, head: Span) -> Result<Spanned, Fail> {
1635 let name_span = self.peek_span();
1636 let name = match self.bump() {
1637 TokenKind::Ident(n) => n,
1638 other => {
1639 return Err(fail(
1640 format!("expected a name after `def`, found {other}"),
1641 name_span,
1642 ))
1643 }
1644 };
1645 let mut params: Vec<(String, Span, Option<Spanned>)> = Vec::new();
1646 if self.at(&TokenKind::LParen) {
1647 self.bump();
1648 self.skip_newlines();
1649 if !self.eat(&TokenKind::RParen) {
1650 loop {
1651 self.skip_newlines();
1652 let p_span = self.peek_span();
1653 match self.bump() {
1654 // `a` — unannotated
1655 TokenKind::Ident(p) => params.push((p, p_span, None)),
1656 // `a:` came through as one token, so a type follows
1657 TokenKind::Label(p) => {
1658 self.skip_newlines();
1659 let ty = self.type_expr()?;
1660 params.push((p, p_span, Some(ty)));
1661 }
1662 other => {
1663 return Err(fail(
1664 format!("expected a parameter name, found {other}"),
1665 p_span,
1666 ))
1667 }
1668 }
1669 self.skip_newlines();
1670 if self.eat(&TokenKind::Comma) {
1671 continue;
1672 }
1673 self.expect(&TokenKind::RParen, "`,` or `)`")?;
1674 break;
1675 }
1676 }
1677 }
1678 // The signature list spans the name through the closing `)`.
1679 let sig_span = self.span_since(name_span.start);
1680
1681 // Optional `-> R`
1682 let ret = if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
1683 self.bump();
1684 self.skip_newlines();
1685 Some(self.type_expr()?)
1686 } else {
1687 None
1688 };
1689
1690 let body = self.body(&["end"])?;
1691 self.expect_ident("end")?;
1692 let whole = self.span_since(head.start);
1693
1694 let annotated = ret.is_some() || params.iter().any(|(_, _, t)| t.is_some());
1695 if !annotated {
1696 let mut sig = vec![sym_at(name_span, &name)];
1697 sig.extend(params.into_iter().map(|(p, s, _)| sym_at(s, &p)));
1698 return Ok(list_at(
1699 whole,
1700 vec![sym_at(head, "define"), list_at(sig_span, sig), body],
1701 ));
1702 }
1703
1704 // Typed shape. An un-annotated parameter in an otherwise annotated
1705 // signature is written `(p dyn)` so the checker sees the ladder
1706 // position explicitly rather than inferring it from absence.
1707 //
1708 // A `dyn` written by the parser rather than the author takes the
1709 // parameter's own span, so a diagnostic about it points at the
1710 // parameter — the only thing in the source it could mean.
1711 let mut sig = vec![sym_at(name_span, &name)];
1712 for (p, s, t) in params {
1713 let ty = t.unwrap_or_else(|| sym_at(s, "dyn"));
1714 sig.push(list_at(s.merge(ty.span), vec![sym_at(s, &p), ty]));
1715 }
1716 Ok(list_at(
1717 whole,
1718 vec![
1719 sym_at(head, "define-typed"),
1720 list_at(sig_span, sig),
1721 ret.unwrap_or_else(|| sym_at(head, "dyn")),
1722 body,
1723 ],
1724 ))
1725 }
1726
1727 /// A type expression. Currently a bare name (`Int`, `Str`, `dyn`) or a
1728 /// one-argument constructor (`List(Int)`).
1729 fn type_expr(&mut self) -> Result<Spanned, Fail> {
1730 let name_span = self.peek_span();
1731 let name = match self.bump() {
1732 TokenKind::Ident(n) => n,
1733 other => {
1734 return Err(fail(
1735 format!("expected a type name, found {other}"),
1736 name_span,
1737 ))
1738 }
1739 };
1740 if self.at(&TokenKind::LParen) {
1741 let args = self.paren_args()?;
1742 let mut list = vec![sym_at(name_span, &name)];
1743 list.extend(args);
1744 return Ok(list_at(self.span_since(name_span.start), list));
1745 }
1746 Ok(sym_at(name_span, &name))
1747 }
1748
1749 /// Consume `name` if it is the next token, else leave the position alone.
1750 fn eat_ident(&mut self, name: &str) -> bool {
1751 if self.at_ident(name) {
1752 self.bump();
1753 true
1754 } else {
1755 false
1756 }
1757 }
1758
1759 fn expect_ident(&mut self, name: &str) -> Result<(), Fail> {
1760 if self.at_ident(name) {
1761 self.bump();
1762 Ok(())
1763 } else {
1764 Err(self.error(format!("expected `{name}`, found {}", self.peek())))
1765 }
1766 }
1767
1768 /// A sequence of expressions up to one of `terminators`, wrapped in
1769 /// `(begin ...)` when there is more than one.
1770 fn body(&mut self, terminators: &[&str]) -> Result<Spanned, Fail> {
1771 // Anchored BEFORE the leading newlines are skipped, so an empty body's
1772 // span sits where the body would have started.
1773 let start = self.mark();
1774 let mut forms = Vec::new();
1775 loop {
1776 self.skip_newlines();
1777 if matches!(self.peek(), TokenKind::Eof) {
1778 return Err(self.error(format!(
1779 "unterminated block: expected {} before the end of the file",
1780 one_of(terminators)
1781 )));
1782 }
1783 if terminators.iter().any(|t| self.at_ident(t)) {
1784 break;
1785 }
1786 forms.push(self.statement()?);
1787 self.end_of_statement(terminators)?;
1788 }
1789 Ok(match forms.len() {
1790 0 => Spanned::new(Span::new(start, start), SpannedForm::Nil),
1791 1 => forms.into_iter().next().expect("checked len"),
1792 _ => {
1793 // `cover`, NOT `span_since`: the loop breaks *before* consuming
1794 // the terminator but *after* `skip_newlines`, so the last token
1795 // behind `pos` can be a newline and `span_since` would stretch
1796 // the body across trailing blank lines. The forms know exactly
1797 // where they are.
1798 let span = cover(&forms, Span::new(start, start));
1799 // The synthesized `begin` is zero-width at the FIRST FORM's
1800 // start, not at `start`. `start` is anchored before the leading
1801 // newlines are skipped, so it sits earlier than the body itself
1802 // — and a head node outside its own list's span is a span bug
1803 // that `every_node_sits_inside_its_parents_span` reports.
1804 let head = Span::new(span.start, span.start);
1805 let mut list = vec![sym_at(head, "begin")];
1806 list.extend(forms);
1807 list_at(span, list)
1808 }
1809 })
1810 }
1811}
1812
1813/// `` `a` ``, `` `a` or `b` ``, `` `a`, `b` or `c` `` — a list of keywords as
1814/// a sentence says it.
1815fn one_of(words: &[&str]) -> String {
1816 let quoted: Vec<String> = words.iter().map(|w| format!("`{w}`")).collect();
1817 match quoted.split_last() {
1818 None => String::new(),
1819 Some((last, [])) => last.clone(),
1820 Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
1821 }
1822}
1823
1824/// A symbol node at `span`.
1825fn sym_at(span: Span, s: &str) -> Spanned {
1826 Spanned::new(span, SpannedForm::Atom(Atom::Symbol(s.to_string())))
1827}
1828
1829/// An atom node at `span`.
1830fn atom_at(span: Span, a: Atom) -> Spanned {
1831 Spanned::new(span, SpannedForm::Atom(a))
1832}
1833
1834/// A list node at `span`.
1835fn list_at(span: Span, items: Vec<Spanned>) -> Spanned {
1836 Spanned::new(span, SpannedForm::List(items))
1837}
1838
1839/// The smallest span covering every node in `items`, or `fallback` when there
1840/// are none.
1841///
1842/// The fallback is a parameter rather than `Span::synthetic()` because a
1843/// synthetic span is a claim that a node has no source origin at all — and an
1844/// empty parameter list in `def f()` very much has one. Defaulting to synthetic
1845/// here is how "no span" leaks into a tree where every node does have a place.
1846fn cover(items: &[Spanned], fallback: Span) -> Span {
1847 let merged = items
1848 .iter()
1849 .fold(Span::synthetic(), |acc, s| acc.merge(s.span));
1850 if merged.is_synthetic() {
1851 fallback
1852 } else {
1853 merged
1854 }
1855}
1856
1857#[cfg(test)]
1858mod tests {
1859 use super::*;
1860
1861 /// Render an `Sexp` to canonical text so tests can state the expected
1862 /// quoted form as a string. This is `Display`, which tatara-lisp owns —
1863 /// blue does not build Lisp syntax by concatenation.
1864 fn q(src: &str) -> String {
1865 parse_expr(src)
1866 .map(|s| s.to_string())
1867 .unwrap_or_else(|e| panic!("{src:?}: {e}"))
1868 }
1869
1870 // ---- the thesis: Ruby-shaped source becomes tatara-lisp ----------
1871
1872 #[test]
1873 fn arithmetic_respects_precedence() {
1874 assert_eq!(q("1 + 2 * 3"), "(+ 1 (* 2 3))");
1875 assert_eq!(q("(1 + 2) * 3"), "(* (+ 1 2) 3)");
1876 }
1877
1878 #[test]
1879 fn comparison_binds_looser_than_arithmetic() {
1880 assert_eq!(q("a + 1 < b"), "(< (+ a 1) b)");
1881 }
1882
1883 /// The expected tree names `or`/`and`, not `||`/`&&`: the surface
1884 /// spelling is the SURFACE's, and lowering renames it to the form
1885 /// tatara-lisp actually has. This test previously asserted the verbatim
1886 /// spelling, which is how `(== a b)` — a symbol nothing binds — shipped.
1887 #[test]
1888 fn logical_operators_bind_loosest_and_lower_to_tataras_names() {
1889 assert_eq!(q("a && b || c"), "(or (and a b) c)");
1890 }
1891
1892 #[test]
1893 fn left_associativity() {
1894 assert_eq!(q("1 - 2 - 3"), "(- (- 1 2) 3)");
1895 }
1896
1897 /// A bare `recv.name` is a SEND. Blue commits to uniform access here,
1898 /// so a field can later become a computed method without breaking
1899 /// callers.
1900 #[test]
1901 fn method_call_without_parens_is_a_send() {
1902 assert_eq!(q("user.name"), "(name user)");
1903 }
1904
1905 #[test]
1906 fn method_call_with_args() {
1907 assert_eq!(q("user.greet(1, 2)"), "(greet user 1 2)");
1908 }
1909
1910 #[test]
1911 fn chained_sends_read_left_to_right() {
1912 assert_eq!(q("a.b.c"), "(c (b a))");
1913 }
1914
1915 #[test]
1916 fn plain_call() {
1917 assert_eq!(q("f(1, 2)"), "(f 1 2)");
1918 }
1919
1920 /// The pipeline threads into the FIRST argument, as Elixir's does —
1921 /// that is what makes `|>` composable rather than decorative.
1922 #[test]
1923 fn pipeline_threads_into_first_argument() {
1924 assert_eq!(q("x |> f"), "(f x)");
1925 assert_eq!(q("x |> f(1)"), "(f x 1)");
1926 assert_eq!(q("x |> f |> g"), "(g (f x))");
1927 }
1928
1929 #[test]
1930 fn pipeline_binds_looser_than_arithmetic() {
1931 assert_eq!(q("1 + 2 |> f"), "(f (+ 1 2))");
1932 }
1933
1934 // ---- §V.13's rendering law, enforced at the parser ---------------
1935
1936 /// `a: 1` and `:a => 1` are the SAME TREE. That is exactly why the
1937 /// formatter may always render the shorthand: they are not two
1938 /// spellings of two things, they are two spellings of one thing.
1939 #[test]
1940 fn label_and_rocket_produce_the_same_tree_for_a_symbol_key() {
1941 assert_eq!(q("{a: 1}"), q("{:a => 1}"));
1942 assert_eq!(q("{a: 1}"), "(hash-map :a 1)");
1943 }
1944
1945 /// And where the key is NOT a plain symbol, the rocket is the only
1946 /// spelling — so it survives because it must, never as a style choice.
1947 #[test]
1948 fn a_string_key_has_no_shorthand() {
1949 assert_eq!(q(r#"{"k" => 1}"#), r#"(hash-map "k" 1)"#);
1950 }
1951
1952 #[test]
1953 fn list_literal() {
1954 assert_eq!(q("[1, 2, 3]"), "(list 1 2 3)");
1955 assert_eq!(q("[]"), "(list)");
1956 }
1957
1958 // ---- blocks ------------------------------------------------------
1959
1960 #[test]
1961 fn if_else_end() {
1962 assert_eq!(q("if a\n 1\nelse\n 2\nend"), "(if a 1 2)");
1963 }
1964
1965 #[test]
1966 fn if_without_else() {
1967 assert_eq!(q("if a\n 1\nend"), "(if a 1)");
1968 }
1969
1970 /// `unless` lowers to `(if (not c) …)` — one tree per meaning, so
1971 /// every downstream tool sees exactly one shape.
1972 #[test]
1973 fn unless_is_a_negated_if() {
1974 assert_eq!(q("unless a\n 1\nend"), "(if (not a) 1)");
1975 }
1976
1977 #[test]
1978 fn multi_statement_body_becomes_begin() {
1979 assert_eq!(q("if a\n 1\n 2\nend"), "(if a (begin 1 2))");
1980 }
1981
1982 #[test]
1983 fn def_lowers_to_define() {
1984 assert_eq!(
1985 q("def add(a, b)\n a + b\nend"),
1986 "(define (add a b) (+ a b))"
1987 );
1988 }
1989
1990 #[test]
1991 fn def_with_no_params() {
1992 assert_eq!(q("def zero()\n 0\nend"), "(define (zero) 0)");
1993 }
1994
1995 // ---- literals ----------------------------------------------------
1996
1997 #[test]
1998 fn literals_lower_to_atoms() {
1999 assert_eq!(q("42"), "42");
2000 assert_eq!(q("true"), "#t");
2001 assert_eq!(q(":ok"), ":ok");
2002 assert_eq!(q(r#""hi""#), r#""hi""#);
2003 }
2004
2005 #[test]
2006 fn unary_minus_and_not() {
2007 assert_eq!(q("-x"), "(- 0 x)");
2008 assert_eq!(q("!x"), "(not x)");
2009 }
2010
2011 // ---- programs and errors -----------------------------------------
2012
2013 #[test]
2014 fn a_program_is_a_sequence_of_forms() {
2015 let forms = parse_program("def f()\n 1\nend\nf()").expect("parse");
2016 assert_eq!(forms.len(), 2);
2017 assert_eq!(forms[1].to_string(), "(f)");
2018 }
2019
2020 #[test]
2021 fn unterminated_block_is_an_error_naming_what_was_expected() {
2022 let e = parse_program("if a\n 1").expect_err("must fail");
2023 assert!(e.message.contains("unterminated"), "{}", e.message);
2024 }
2025
2026 #[test]
2027 fn a_parse_error_carries_a_span_into_the_source() {
2028 let src = "1 + )";
2029 let e = parse_program(src).expect_err("must fail");
2030 assert!(e.span.start < src.len(), "span {:?} outside source", e.span);
2031 }
2032
2033 // ---- one statement per line -------------------------------------
2034
2035 /// `y = xs[0]` was TWO statements, `(define y xs)` and `(list 0)`: nothing
2036 /// required a separator between statements, so the parser finished `xs`,
2037 /// saw a list literal and started a new statement on the same line. The
2038 /// program ran and `y` was the whole list. Found by the 2026-09-29 audit.
2039 #[test]
2040 fn postfix_indexing_is_refused_naming_nth() {
2041 let e = parse_program("y = xs[0]").expect_err("must not split into two statements");
2042 assert!(e.message.contains("`nth(0, xs)`"), "{}", e.message);
2043 assert_eq!((e.line, e.col), (1, 7), "{e}");
2044 }
2045
2046 /// `a = f x` — Ruby's command call — parsed as `a = f` and then `x`.
2047 #[test]
2048 fn a_call_without_parentheses_is_refused_naming_the_call() {
2049 let e = parse_program("a = f x").expect_err("must not split into two statements");
2050 assert!(e.message.contains("`f(x)`"), "{}", e.message);
2051 assert_eq!((e.line, e.col), (1, 7), "{e}");
2052 }
2053
2054 /// The same rule inside a block body, and in every body shape.
2055 #[test]
2056 fn two_statements_on_one_line_are_refused_in_a_body() {
2057 for src in [
2058 "def f(xs)\n xs[0]\nend",
2059 "if a\n f x\nend",
2060 "fn(x) x 1 end",
2061 "test \"t\"\n assert a b\nend",
2062 "1 2",
2063 ] {
2064 assert!(parse_program(src).is_err(), "{src:?} must not parse");
2065 }
2066 }
2067
2068 /// The controls: every place a statement legitimately ends on its line.
2069 /// A block keyword closing the body on the same line is one of them, which
2070 /// is what keeps a one-line lambda one line.
2071 #[test]
2072 fn a_statement_may_end_at_a_newline_the_end_or_a_closing_keyword() {
2073 for src in [
2074 "fn(x) x + 1 end",
2075 "map(fn(x) x end, xs)",
2076 "if a\n 1\nelse\n 2\nend",
2077 "if a 1 else 2 end",
2078 "case x\nwhen 1 :a\nwhen 2 :b\nelse :c\nend",
2079 "x = 1\ny = 2",
2080 "x = 1",
2081 ] {
2082 assert!(
2083 parse_program(src).is_ok(),
2084 "{src:?}: {:?}",
2085 parse_program(src)
2086 );
2087 }
2088 }
2089
2090 /// `if c then a else b end` read `then` as a statement and `a` as another.
2091 #[test]
2092 fn then_is_refused_by_name() {
2093 let e = parse_program("x = if c then 1 else 2 end").expect_err("then is not a keyword");
2094 assert!(e.message.contains("`then`"), "{}", e.message);
2095 }
2096
2097 /// A brace block after a send is not a map literal the author meant.
2098 #[test]
2099 fn a_brace_block_is_refused_naming_fn() {
2100 let e = parse_program("xs.map { |x| x }").expect_err("no brace blocks");
2101 assert!(e.message.contains("fn(x)"), "{}", e.message);
2102 }
2103
2104 // ---- qualified names ------------------------------------------------
2105
2106 /// `retsu::first(xs)` is one symbol, tatara's `require` shape.
2107 ///
2108 /// Red run (2026-09-29), before the `::` token: `expected an expression,
2109 /// found `:``.
2110 #[test]
2111 fn a_qualified_name_is_one_symbol() {
2112 assert_eq!(q("retsu::first(xs)"), "(retsu/first xs)");
2113 assert_eq!(q("retsu::first"), "retsu/first");
2114 assert_eq!(q("xs |> retsu::first"), "(retsu/first xs)");
2115 assert_eq!(q("blue::length(xs)"), "(blue/length xs)");
2116 }
2117
2118 /// Whitespace around `::` is layout, not meaning.
2119 #[test]
2120 fn whitespace_around_the_qualifier_is_accepted() {
2121 assert_eq!(q("retsu :: first(xs)"), "(retsu/first xs)");
2122 }
2123
2124 /// After `::` a reserved word is a name: `kueri::if` is kueri's
2125 /// definition, not the `if` form.
2126 #[test]
2127 fn a_reserved_word_after_the_qualifier_is_a_name() {
2128 assert_eq!(q("kueri::if(a, b)"), "(kueri/if a b)");
2129 assert_eq!(q("heni::test(x)"), "(heni/test x)");
2130 assert_eq!(q("sabi::fn"), "sabi/fn");
2131 }
2132
2133 #[test]
2134 fn a_qualified_name_has_exactly_one_qualifier() {
2135 for (src, says) in [
2136 ("::first(xs)", "`package::name`"),
2137 ("a::b::c", "one qualifier"),
2138 ("if::x", "reserved word"),
2139 ("retsu::1", "expected a name after `retsu::`"),
2140 ] {
2141 let e = parse_program(src).expect_err(src);
2142 assert!(e.message.contains(says), "{src}: {}", e.message);
2143 }
2144 }
2145
2146 /// The one reader of the shape: division is not qualified, and neither
2147 /// is anything the surface could not have written.
2148 #[test]
2149 fn qualified_reads_only_the_package_name_shape() {
2150 assert_eq!(qualified("retsu/first"), Some(("retsu", "first")));
2151 assert_eq!(qualified("kueri/if"), Some(("kueri", "if")));
2152 assert_eq!(qualified("nisshi/pair?"), Some(("nisshi", "pair?")));
2153 for not in ["/", "a/", "/a", "a/b/c", "if/x", "hash-map", "a"] {
2154 assert_eq!(qualified(not), None, "{not}");
2155 }
2156 assert!(is_callable_name("kueri/if"));
2157 }
2158
2159 /// `:pair?` is the symbol `pair?`: an import list can name a predicate.
2160 ///
2161 /// Red run (2026-09-29), before: `unexpected character `?``, found by
2162 /// `blue migrate` listing nisshi's `pair?`.
2163 #[test]
2164 fn a_symbol_may_end_in_a_question_or_bang() {
2165 assert_eq!(q("[:pair?, :set!]"), "(list :pair? :set!)");
2166 assert_eq!(q("use(\"n\", [:empty?])"), "(use \"n\" (list :empty?))");
2167 assert_eq!(q(":a != :b"), "(not= :a :b)");
2168 }
2169
2170 // ---- errors a person can read -------------------------------------
2171
2172 /// `line:col` and blue's words, never `at 10..11` and `Ident("y")`.
2173 #[test]
2174 fn a_parse_error_displays_line_col_and_the_source_text() {
2175 let e = parse_program("x = 1\ny = [1, 2 y]").expect_err("must fail");
2176 assert_eq!(e.to_string(), "2:11: expected `,` or `]`, found `y`");
2177 assert_eq!(e.span, Span::new(16, 17), "the span stays, as data");
2178 }
2179
2180 /// Every token kind renders without Rust's `Debug` shape.
2181 #[test]
2182 fn no_error_message_names_a_rust_variant() {
2183 for src in [
2184 "f(1 2)",
2185 "{a: 1 b}",
2186 "def 1\nend",
2187 "x.1",
2188 "if a\n",
2189 "fn(1) 2 end",
2190 "[1 :b]",
2191 "1 +",
2192 "(1",
2193 ] {
2194 let e = parse_program(src).expect_err(src);
2195 let shown = e.to_string();
2196 for tell in [
2197 "Ident(", "Int(", "Op(", "Label(", "Sym(", "Str(", "LParen", "RBracket", "Eof",
2198 "Newline", "..",
2199 ] {
2200 assert!(!shown.contains(tell), "{src:?} -> {shown}");
2201 }
2202 assert!(e.line >= 1 && e.col >= 1, "{src:?} not located: {shown}");
2203 }
2204 }
2205
2206 /// A lex error reaches the author through the same door, located.
2207 #[test]
2208 fn a_lex_error_is_located_too() {
2209 let e = parse_program("x = 1\ny = 2; z = 3").expect_err("no semicolons");
2210 assert_eq!((e.line, e.col), (2, 6), "{e}");
2211 assert!(e.message.contains("new line"), "{e}");
2212 }
2213
2214 /// Anti-vacuity: `q` must be able to FAIL. If every input parsed, the
2215 /// assertions above would be worthless.
2216 #[test]
2217 fn the_parser_rejects_garbage() {
2218 assert!(parse_program("def").is_err());
2219 assert!(parse_program("(1").is_err());
2220 assert!(parse_program("end").is_err());
2221 }
2222}