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
16use tatara_lisp::{Atom, Sexp};
17
18use crate::lex::{lex, Span, Token, TokenKind};
19
20#[derive(Clone, Debug, PartialEq)]
21pub struct ParseError {
22 pub message: String,
23 pub span: Span,
24}
25
26impl std::fmt::Display for ParseError {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 write!(
29 f,
30 "{} at {}..{}",
31 self.message, self.span.start, self.span.end
32 )
33 }
34}
35
36impl std::error::Error for ParseError {}
37
38impl From<crate::lex::LexError> for ParseError {
39 fn from(e: crate::lex::LexError) -> Self {
40 Self {
41 message: e.message,
42 span: e.span,
43 }
44 }
45}
46
47/// Parse a blue program into a sequence of tatara-lisp forms.
48pub fn parse_program(src: &str) -> Result<Vec<Sexp>, ParseError> {
49 Ok(parse_program_spanned(src)?
50 .into_iter()
51 .map(|(form, _)| form)
52 .collect())
53}
54
55/// Parse, keeping each top-level form's source span.
56///
57/// The spans are what let the formatter put comments back. A comment is not
58/// part of a program's *meaning*, so it has no place in the `Sexp` tree —
59/// putting it there would break canonicality, since two programs differing only
60/// in a comment would stop formatting identically. Instead the formatter renders
61/// the tree and re-interleaves comments by position, which needs to know where
62/// each form started and ended.
63pub fn parse_program_spanned(src: &str) -> Result<Vec<(Sexp, Span)>, ParseError> {
64 let toks: Vec<Token> = lex(src)?
65 .into_iter()
66 .filter(|t| !matches!(t.kind, TokenKind::Comment(_)))
67 .collect();
68 let mut p = Parser {
69 toks,
70 pos: 0,
71 depth: 0,
72 };
73 p.program_spanned()
74}
75
76/// Every comment in `src`, with its byte span and whether it sits alone on its
77/// line.
78///
79/// `own_line` is the distinction that decides placement: a comment alone on its
80/// line belongs *before* the form that follows, while one after code on the same
81/// line belongs *to* that line. Conflating them moves a trailing note onto the
82/// wrong row.
83pub fn comments(src: &str) -> Vec<Comment> {
84 lex(src)
85 .map(|toks| {
86 toks.iter()
87 .filter_map(|t| match &t.kind {
88 TokenKind::Comment(text) => Some(Comment {
89 text: text.clone(),
90 span: t.span,
91 own_line: line_before_is_blank(src, t.span.start),
92 }),
93 _ => None,
94 })
95 .collect()
96 })
97 .unwrap_or_default()
98}
99
100/// A comment, and where it sat.
101#[derive(Clone, Debug, PartialEq, Eq)]
102pub struct Comment {
103 /// The text, including the leading `#`.
104 pub text: String,
105 pub span: Span,
106 /// Nothing but whitespace precedes it on its line.
107 pub own_line: bool,
108}
109
110fn line_before_is_blank(src: &str, start: usize) -> bool {
111 src[..start.min(src.len())]
112 .rsplit('\n')
113 .next()
114 .is_some_and(|prefix| prefix.trim().is_empty())
115}
116
117/// Parse a single blue expression. Convenience for tests and the REPL.
118pub fn parse_expr(src: &str) -> Result<Sexp, ParseError> {
119 let forms = parse_program(src)?;
120 match forms.len() {
121 1 => Ok(forms.into_iter().next().expect("checked len")),
122 n => Err(ParseError {
123 message: format!("expected exactly one expression, found {n}"),
124 span: Span::new(0, src.len()),
125 }),
126 }
127}
128
129/// What an infix operator binds like, and what it lowers to.
130///
131/// **One row per operator, carrying both facts.** Precedence and callee
132/// used to live apart, and the cost was immediate: the surface spelling was
133/// emitted verbatim, so `a == b` lowered to `(== a b)` — a symbol no
134/// interpreter binds — and the program died at *runtime* with `unbound
135/// symbol ==`. Splitting the two invites exactly that: add an operator to
136/// the precedence table, forget the lowering, ship a parse that cannot run.
137/// Joined here, "has a precedence" and "has a callee" are the same fact.
138#[derive(Clone, Copy, Debug)]
139pub struct Infix {
140 /// Surface spelling.
141 pub op: &'static str,
142 /// Left and right binding power. Higher binds tighter.
143 pub power: (u8, u8),
144 /// The tatara-lisp callee this lowers to.
145 pub callee: &'static str,
146}
147
148/// The complete infix table. Precedence follows Ruby's where Ruby has an
149/// opinion; `|>` (below) sits under everything so `a |> f |> g` chains
150/// without parentheses.
151pub const INFIX: &[Infix] = &[
152 Infix {
153 op: "||",
154 power: (1, 2),
155 callee: "or",
156 },
157 Infix {
158 op: "&&",
159 power: (3, 4),
160 callee: "and",
161 },
162 // `==` is STRUCTURAL equality, so it lowers to `equal?` and not to `=`.
163 //
164 // tatara's `=` is NUMERIC comparison: `"a" = "a"` is a type error, not
165 // false. Lowering `==` to it meant every string, list or nil comparison
166 // failed with "expected number, got string" — found by blue's own spec
167 // suite the moment a test compared two strings, which is the first thing
168 // anybody does.
169 //
170 // `equal?` is structural and total over the value domain: strings, lists
171 // and nil all compare, and numbers still compare as numbers.
172 Infix {
173 op: "==",
174 power: (5, 6),
175 callee: "equal?",
176 },
177 Infix {
178 op: "!=",
179 power: (5, 6),
180 callee: "not=",
181 },
182 Infix {
183 op: "<",
184 power: (5, 6),
185 callee: "<",
186 },
187 Infix {
188 op: "<=",
189 power: (5, 6),
190 callee: "<=",
191 },
192 Infix {
193 op: ">",
194 power: (5, 6),
195 callee: ">",
196 },
197 Infix {
198 op: ">=",
199 power: (5, 6),
200 callee: ">=",
201 },
202 Infix {
203 op: "+",
204 power: (7, 8),
205 callee: "+",
206 },
207 Infix {
208 op: "-",
209 power: (7, 8),
210 callee: "-",
211 },
212 Infix {
213 op: "*",
214 power: (9, 10),
215 callee: "*",
216 },
217 Infix {
218 op: "/",
219 power: (9, 10),
220 callee: "/",
221 },
222 Infix {
223 op: "%",
224 power: (9, 10),
225 callee: "mod",
226 },
227];
228
229/// Every surface keyword that BEGINS an expression.
230///
231/// Exists so the formatter's corpus can be checked against it. Three separate
232/// times a form was added to this parser, the formatter was not extended, and
233/// all three formatting laws still passed — because the corpus is
234/// hand-maintained and contained no example of the new form. The annotated
235/// `def` rendered as a method send; `defmacro` rendered as
236/// `defmacro(double, x(), …)`, which does not re-parse at all.
237///
238/// A law cannot notice a case nobody wrote down. `blue-lang-fmt`'s
239/// `every_surface_keyword_appears_in_the_corpus` closes that by making the
240/// omission itself the failure, so adding a keyword here forces the corpus
241/// entry that exercises the other three laws over it.
242///
243/// `do` and `end` are absent deliberately: they are block delimiters, not
244/// expression heads, and have no standalone rendering to test.
245/// The callee `assert e` lowers to.
246///
247/// **Owned here, by the lowering itself, and read by every consumer.** It was
248/// briefly a literal here and a separate `const` in `blue-lang-test`, and the
249/// shadowing gate then could not see a parser that lowered to the wrong name:
250/// the gate checked its own copy. Same duplication class as the operator table.
251pub const LOWERED_ASSERT: &str = "blue-assert";
252
253/// The callee a `{...}` map literal lowers to.
254///
255/// **`hash-map`, not `map`.** tatara binds `map` to the higher-order function,
256/// so a literal lowering to `(map …)` called the HOF with the key/value pairs
257/// as arguments and failed with "expected list, got int". Same shadowing class
258/// as [`LOWERED_ASSERT`], caught by the same gate once the name was listed
259/// there — it was not, which is why this shipped.
260pub const LOWERED_MAP: &str = "hash-map";
261
262/// The callee string interpolation lowers to.
263///
264/// blue's own `concat`, which renders either side through `to_s` — that is what
265/// lets `"n=#{42}"` interpolate a number. Not `+`, which is arithmetic.
266pub const LOWERED_CONCAT: &str = "concat";
267
268pub const SURFACE_KEYWORDS: &[&str] = &[
269 "if",
270 "unless",
271 "def",
272 "defmacro",
273 "quote",
274 "unquote",
275 "unquote_splice",
276 "test",
277 "assert",
278 "fn",
279 "case",
280];
281
282/// A surface keyword may not be rebound. `if = 1` is a mistake, not a binding,
283/// and letting it through would shadow the form for the rest of the file.
284fn is_reserved_word(name: &str) -> bool {
285 SURFACE_KEYWORDS.contains(&name)
286 || matches!(name, "do" | "end" | "else" | "true" | "false" | "nil")
287}
288
289fn infix(op: &str) -> Option<&'static Infix> {
290 INFIX.iter().find(|i| i.op == op)
291}
292
293const PIPE_POWER: (u8, u8) = (0, 1);
294
295struct Parser {
296 toks: Vec<Token>,
297 pos: usize,
298 /// Current expression-nesting depth, bounded by [`MAX_EXPR_DEPTH`].
299 ///
300 /// Without this the parser does not fail on deep input — it **aborts the
301 /// process** with a stack overflow (SIGABRT), which `catch_unwind` cannot
302 /// catch. Measured 2026-08-01: `"(".repeat(2_000)` killed the test runner
303 /// outright. Every consumer inherited it — an LSP parsing a half-typed
304 /// line, a formatter, and shikumi loading a `.b` config off disk.
305 depth: usize,
306}
307
308/// Maximum expression nesting before the parser refuses.
309///
310/// Chosen well above anything human-written (blue's own `spec/*.b` peaks in
311/// single digits) and far below the measured overflow point, so the bound is
312/// hit as a typed `Err` long before the stack is at risk. A limit that is
313/// merely *near* the crash point is not a safety bound; it is a race.
314pub const MAX_EXPR_DEPTH: usize = 256;
315
316impl Parser {
317 fn peek(&self) -> &TokenKind {
318 &self.toks[self.pos.min(self.toks.len() - 1)].kind
319 }
320
321 fn peek_span(&self) -> Span {
322 self.toks[self.pos.min(self.toks.len() - 1)].span
323 }
324
325 fn bump(&mut self) -> TokenKind {
326 let k = self.toks[self.pos.min(self.toks.len() - 1)].kind.clone();
327 if self.pos < self.toks.len() {
328 self.pos += 1;
329 }
330 k
331 }
332
333 fn at(&self, k: &TokenKind) -> bool {
334 self.peek() == k
335 }
336
337 fn eat(&mut self, k: &TokenKind) -> bool {
338 if self.at(k) {
339 self.bump();
340 true
341 } else {
342 false
343 }
344 }
345
346 fn expect(&mut self, k: &TokenKind, what: &str) -> Result<(), ParseError> {
347 if self.eat(k) {
348 Ok(())
349 } else {
350 Err(self.error(format!("expected {what}, found {:?}", self.peek())))
351 }
352 }
353
354 fn error(&self, message: impl Into<String>) -> ParseError {
355 ParseError {
356 message: message.into(),
357 span: self.peek_span(),
358 }
359 }
360
361 /// Skip statement separators (newlines and semicolon-free layout).
362 fn skip_newlines(&mut self) {
363 while matches!(self.peek(), TokenKind::Newline) {
364 self.bump();
365 }
366 }
367
368 fn at_ident(&self, name: &str) -> bool {
369 matches!(self.peek(), TokenKind::Ident(n) if n == name)
370 }
371
372 fn program_spanned(&mut self) -> Result<Vec<(Sexp, Span)>, ParseError> {
373 let mut out = Vec::new();
374 loop {
375 self.skip_newlines();
376 if matches!(self.peek(), TokenKind::Eof) {
377 break;
378 }
379 let start = self.peek_span().start;
380 let form = self.statement()?;
381 // The last token consumed ends the form. `pos` has already advanced
382 // past it, so look one back.
383 let end = self
384 .toks
385 .get(self.pos.saturating_sub(1))
386 .map_or(start, |t| t.span.end);
387 out.push((form, Span::new(start, end)));
388 }
389 Ok(out)
390 }
391
392 /// A statement: either a binding or an expression.
393 ///
394 /// `x = 5` lowers to `(define x 5)`. Blue had NO way to name a value — a
395 /// capability probe found `x = 5` was a parse error, which makes every
396 /// program a single expression. That is more fundamental than anything else
397 /// the probe found.
398 ///
399 /// Only at STATEMENT position, never inside an expression, so `f(x = 1)` is
400 /// still an error rather than a silent binding. Ruby allows assignment as an
401 /// expression and it is a well-known footgun — `if x = 1` where `==` was
402 /// meant. Blue declines it, and the cost is only that a walrus-style idiom
403 /// has to be two lines.
404 fn statement(&mut self) -> Result<Sexp, ParseError> {
405 if let TokenKind::Ident(name) = self.peek().clone() {
406 if self.peek_at(1) == "=" && !is_reserved_word(&name) {
407 self.bump(); // name
408 self.bump(); // =
409 self.skip_newlines();
410 let value = self.expr(0)?;
411 return Ok(Sexp::List(vec![sym("define"), sym(&name), value]));
412 }
413 }
414 self.expr(0)
415 }
416
417 /// The token `n` positions ahead, for the two-token lookahead a binding
418 /// needs. Returns `Eof` past the end rather than panicking.
419 fn peek_at(&self, n: usize) -> String {
420 match self.toks.get(self.pos + n).map(|t| &t.kind) {
421 Some(TokenKind::Op(o)) => o.clone(),
422 _ => String::new(),
423 }
424 }
425
426 /// Pratt loop.
427 fn expr(&mut self, min_bp: u8) -> Result<Sexp, ParseError> {
428 // Depth guard at the single recursion cycle (`expr` -> `prefix` ->
429 // `expr`). Returning an Err here converts an UNRECOVERABLE abort into
430 // an ordinary parse failure a caller can render — the difference
431 // between an LSP showing a squiggle and an LSP being gone.
432 //
433 // The decrement is deliberately not RAII: every exit from this
434 // function is via `?` or a normal return, and both are covered by the
435 // explicit decrements below. A guard object would be tidier but would
436 // also hide the invariant this comment is here to state.
437 if self.depth >= MAX_EXPR_DEPTH {
438 return Err(self.error(format!(
439 "expression nests deeper than {MAX_EXPR_DEPTH}; refusing to \
440 recurse further (this is a limit, not a syntax error)"
441 )));
442 }
443 self.depth += 1;
444 let r = self.expr_inner(min_bp);
445 self.depth -= 1;
446 r
447 }
448
449 fn expr_inner(&mut self, min_bp: u8) -> Result<Sexp, ParseError> {
450 let mut lhs = self.prefix()?;
451
452 loop {
453 // Postfix: `.name`, `.name(args)`, `(args)`
454 match self.peek() {
455 TokenKind::Dot => {
456 self.bump();
457 lhs = self.finish_send(lhs)?;
458 continue;
459 }
460 TokenKind::LParen => {
461 // A call on an expression already parsed: `f(x)`.
462 let args = self.paren_args()?;
463 let mut list = vec![lhs];
464 list.extend(args);
465 lhs = Sexp::List(list);
466 continue;
467 }
468 _ => {}
469 }
470
471 // Infix
472 // `callee == None` marks the pipeline, which is a rewrite rather
473 // than a call.
474 let (callee, (lbp, rbp)) = match self.peek() {
475 TokenKind::Pipe => (None, PIPE_POWER),
476 TokenKind::Op(o) => match infix(o) {
477 Some(i) => (Some(i.callee), i.power),
478 None => break,
479 },
480 _ => break,
481 };
482 if lbp < min_bp {
483 break;
484 }
485 self.bump();
486 self.skip_newlines();
487 let rhs = self.expr(rbp)?;
488
489 lhs = if callee.is_none() {
490 // `x |> f` => (f x)
491 // `x |> f(a)` => (f x a) — the pipeline threads into
492 // the FIRST argument position, as Elixir's
493 // does; that is what makes it composable.
494 match rhs {
495 Sexp::List(mut items) if !items.is_empty() => {
496 items.insert(1, lhs);
497 Sexp::List(items)
498 }
499 callee => Sexp::List(vec![callee, lhs]),
500 }
501 } else {
502 Sexp::List(vec![sym(callee.unwrap()), lhs, rhs])
503 };
504 }
505
506 Ok(lhs)
507 }
508
509 fn prefix(&mut self) -> Result<Sexp, ParseError> {
510 let span = self.peek_span();
511 match self.bump() {
512 TokenKind::Int(v) => Ok(Sexp::Atom(Atom::Int(v))),
513 TokenKind::Float(v) => Ok(Sexp::Atom(Atom::Float(v))),
514 TokenKind::Str(s) => Ok(Sexp::Atom(Atom::Str(s))),
515
516 // `"a#{x}b"` → `(concat (concat "a" x) "b")`.
517 //
518 // Lowered to `concat`, not to `+`: blue's `+` is arithmetic (see
519 // the INFIX table), and interpolation must render a value of ANY
520 // type — `concat` goes through `to_s`, which is what makes
521 // `"n=#{42}"` work.
522 //
523 // The expression source is parsed HERE with the ordinary parser
524 // rather than lexed inside the string, so an interpolation can hold
525 // anything an expression can and the two can never drift.
526 TokenKind::InterpolatedStr { parts, exprs } => {
527 let mut acc = Sexp::Atom(Atom::Str(parts[0].clone()));
528 for (i, raw) in exprs.iter().enumerate() {
529 let inner = parse_expr(raw).map_err(|e| ParseError {
530 message: format!("in interpolation `#{{{raw}}}`: {}", e.message),
531 span,
532 })?;
533 acc = Sexp::List(vec![sym(LOWERED_CONCAT), acc, inner]);
534 // `parts.len() == exprs.len() + 1` by construction, so this
535 // index is always in range.
536 acc = Sexp::List(vec![
537 sym(LOWERED_CONCAT),
538 acc,
539 Sexp::Atom(Atom::Str(parts[i + 1].clone())),
540 ]);
541 }
542 Ok(acc)
543 }
544 TokenKind::Sym(s) => Ok(Sexp::Atom(Atom::Keyword(s))),
545 TokenKind::True => Ok(Sexp::Atom(Atom::Bool(true))),
546 TokenKind::False => Ok(Sexp::Atom(Atom::Bool(false))),
547 TokenKind::Nil => Ok(Sexp::Nil),
548
549 TokenKind::Op(o) if o == "-" => {
550 let rhs = self.expr(11)?; // binds tighter than `*`
551 Ok(Sexp::List(vec![sym("-"), Sexp::Atom(Atom::Int(0)), rhs]))
552 }
553 TokenKind::Op(o) if o == "!" => {
554 let rhs = self.expr(11)?;
555 Ok(Sexp::List(vec![sym("not"), rhs]))
556 }
557
558 TokenKind::LParen => {
559 self.skip_newlines();
560 let inner = self.expr(0)?;
561 self.skip_newlines();
562 self.expect(&TokenKind::RParen, "`)`")?;
563 Ok(inner)
564 }
565
566 TokenKind::LBracket => self.list_literal(),
567 TokenKind::LBrace => self.map_literal(),
568
569 TokenKind::Ident(name) => match name.as_str() {
570 "if" => self.if_form(false),
571 "unless" => self.if_form(true),
572 "def" => self.def_form(),
573 "defmacro" => self.defmacro_form(),
574 "case" => self.case_form(),
575 "fn" => self.lambda_form(),
576 "test" => self.test_form(),
577 "assert" => self.assert_form(),
578 "quote" => self.quote_form(),
579 "unquote" => self.unquote_form(false),
580 "unquote_splice" => self.unquote_form(true),
581 "do" => Err(ParseError {
582 message: "`do` without a preceding call".into(),
583 span,
584 }),
585 "end" => Err(ParseError {
586 message: "unexpected `end`".into(),
587 span,
588 }),
589 _ => Ok(sym(&name)),
590 },
591
592 other => Err(ParseError {
593 message: format!("expected an expression, found {other:?}"),
594 span,
595 }),
596 }
597 }
598
599 /// After a `.`: `recv.name` or `recv.name(args)`.
600 ///
601 /// **A bare `recv.name` is a SEND, not a field read.** Blue commits to
602 /// the uniform access principle here: a structure exposes no public
603 /// fields, so a field can later become a computed method without
604 /// breaking a caller.
605 fn finish_send(&mut self, recv: Sexp) -> Result<Sexp, ParseError> {
606 let name = match self.bump() {
607 TokenKind::Ident(n) => n,
608 other => {
609 return Err(self.error(format!("expected a method name after `.`, found {other:?}")))
610 }
611 };
612 let mut list = vec![sym(&name), recv];
613 if self.at(&TokenKind::LParen) {
614 list.extend(self.paren_args()?);
615 }
616 Ok(Sexp::List(list))
617 }
618
619 fn paren_args(&mut self) -> Result<Vec<Sexp>, ParseError> {
620 self.expect(&TokenKind::LParen, "`(`")?;
621 let mut args = Vec::new();
622 self.skip_newlines();
623 if self.eat(&TokenKind::RParen) {
624 return Ok(args);
625 }
626 loop {
627 self.skip_newlines();
628 args.push(self.expr(0)?);
629 self.skip_newlines();
630 if self.eat(&TokenKind::Comma) {
631 continue;
632 }
633 self.expect(&TokenKind::RParen, "`,` or `)`")?;
634 break;
635 }
636 Ok(args)
637 }
638
639 fn list_literal(&mut self) -> Result<Sexp, ParseError> {
640 let mut items = vec![sym("list")];
641 self.skip_newlines();
642 if self.eat(&TokenKind::RBracket) {
643 return Ok(Sexp::List(items));
644 }
645 loop {
646 self.skip_newlines();
647 items.push(self.expr(0)?);
648 self.skip_newlines();
649 if self.eat(&TokenKind::Comma) {
650 continue;
651 }
652 self.expect(&TokenKind::RBracket, "`,` or `]`")?;
653 break;
654 }
655 Ok(Sexp::List(items))
656 }
657
658 /// `{a: 1, "k" => v}` — both spellings, one tree.
659 ///
660 /// This is §V.13's rendering law at the parser: `a: 1` and `:a => 1`
661 /// produce the *same* s-expression, which is precisely why the
662 /// formatter may always choose the shorthand. The rocket survives only
663 /// where the key is not a plain symbol.
664 fn map_literal(&mut self) -> Result<Sexp, ParseError> {
665 let mut items = vec![sym(LOWERED_MAP)];
666 self.skip_newlines();
667 if self.eat(&TokenKind::RBrace) {
668 return Ok(Sexp::List(items));
669 }
670 loop {
671 self.skip_newlines();
672 match self.peek().clone() {
673 TokenKind::Label(name) => {
674 self.bump();
675 self.skip_newlines();
676 items.push(Sexp::Atom(Atom::Keyword(name)));
677 items.push(self.expr(0)?);
678 }
679 _ => {
680 let k = self.expr(0)?;
681 self.skip_newlines();
682 self.expect(&TokenKind::Rocket, "`=>` in a map literal")?;
683 self.skip_newlines();
684 items.push(k);
685 items.push(self.expr(0)?);
686 }
687 }
688 self.skip_newlines();
689 if self.eat(&TokenKind::Comma) {
690 continue;
691 }
692 self.expect(&TokenKind::RBrace, "`,` or `}`")?;
693 break;
694 }
695 Ok(Sexp::List(items))
696 }
697
698 /// `if c ... [else ...] end`, and `unless` as its negation.
699 ///
700 /// `unless` lowers to `(if (not c) ...)` rather than to a distinct
701 /// form: one tree per meaning, so the formatter and every downstream
702 /// tool see exactly one shape.
703 fn if_form(&mut self, negate: bool) -> Result<Sexp, ParseError> {
704 let cond = self.expr(0)?;
705 let cond = if negate {
706 Sexp::List(vec![sym("not"), cond])
707 } else {
708 cond
709 };
710 let then = self.body(&["else", "end"])?;
711 let els = if self.at_ident("else") {
712 self.bump();
713 let e = self.body(&["end"])?;
714 self.expect_ident("end")?;
715 Some(e)
716 } else {
717 self.expect_ident("end")?;
718 None
719 };
720 let mut out = vec![sym("if"), cond, then];
721 if let Some(e) = els {
722 out.push(e);
723 }
724 Ok(Sexp::List(out))
725 }
726
727 /// `def name(a, b) ... end` => `(define (name a b) body)`
728 /// `def name(a: T, b: T) -> R ... end` => `(define-typed (name (a T) (b T)) R body)`
729 ///
730 /// **The two shapes are deliberately different heads.** §0 says an
731 /// unannotated program gets ZERO analysis, and the cleanest way to
732 /// mean that is for untyped code not to reach the typing machinery at
733 /// all — not to reach it and be waved through. A checker that must
734 /// walk every node to discover there is nothing to check has already
735 /// paid the cost the ladder exists to avoid.
736 ///
737 /// Annotations are per-parameter, so a signature may be partially
738 /// annotated. That is the ladder at its finest grain: `a: Int` is
739 /// checked and a bare `b` stays `dyn`, in the same signature.
740 /// `case subject / when a / … / else / … / end` => a `cond` over equality.
741 ///
742 /// **Value matching, not destructuring.** Elixir's `case` binds pattern
743 /// variables; blue's compares with the same `equal?` the `==` operator uses,
744 /// so `when [1, 2]` matches a list by value. Destructuring needs a pattern
745 /// language and a binder, which blue does not have — and a `case` that
746 /// *looked* like Elixir's while silently only comparing would be worse than
747 /// one that plainly compares.
748 ///
749 /// The subject is evaluated ONCE, into a binding, so `case expensive()` does
750 /// not re-run per arm. That is a correctness property, not an optimisation:
751 /// a subject with a side effect would fire once per `when`.
752 fn case_form(&mut self) -> Result<Sexp, ParseError> {
753 let subject = self.expr(0)?;
754 self.skip_newlines();
755
756 // A fresh name the surface cannot spell, so it cannot capture a user
757 // binding of the same name.
758 let subject_var = "case-subject";
759 let mut arms: Vec<Sexp> = Vec::new();
760 let mut otherwise: Option<Sexp> = None;
761
762 loop {
763 self.skip_newlines();
764 if self.at_ident("end") {
765 break;
766 }
767 if self.eat_ident("else") {
768 otherwise = Some(self.body(&["end"])?);
769 continue;
770 }
771 if !self.eat_ident("when") {
772 return Err(self.error(format!(
773 "expected `when`, `else` or `end` in a case, found {:?}",
774 self.peek()
775 )));
776 }
777 self.skip_newlines();
778 let pattern = self.expr(0)?;
779 let body = self.body(&["when", "else", "end"])?;
780 arms.push(Sexp::List(vec![
781 Sexp::List(vec![sym("equal?"), sym(subject_var), pattern]),
782 body,
783 ]));
784 }
785 self.expect_ident("end")?;
786
787 if arms.is_empty() && otherwise.is_none() {
788 return Err(self.error("a case needs at least one `when` or an `else`".to_string()));
789 }
790
791 // A case with no matching arm and no else is NIL, matching Ruby. Elixir
792 // raises CaseClauseError; blue follows Ruby because its `if` without an
793 // else is already nil, and having two different answers to "no branch
794 // taken" in one language is the inconsistency.
795 let mut cond = vec![sym("cond")];
796 cond.extend(arms);
797 cond.push(Sexp::List(vec![
798 sym("else"),
799 otherwise.unwrap_or(Sexp::Nil),
800 ]));
801
802 Ok(Sexp::List(vec![
803 sym("let"),
804 Sexp::List(vec![Sexp::List(vec![sym(subject_var), subject])]),
805 Sexp::List(cond),
806 ]))
807 }
808
809 /// `fn(a, b) ... end` => `(lambda (a b) body)`
810 ///
811 /// Without this the higher-order functions are unreachable in practice:
812 /// `map(inc, xs)` works only because `inc` happens to be a named stdlib
813 /// function, and there was no way to write the one-off the call site
814 /// actually wants.
815 ///
816 /// `fn` rather than Ruby's `->` or `lambda`: `->` collides with the return-
817 /// type arrow the typed `def` already uses, and reusing one glyph for two
818 /// unrelated things is the ambiguity the FORM axis exists to prevent.
819 fn lambda_form(&mut self) -> Result<Sexp, ParseError> {
820 let mut params: Vec<String> = Vec::new();
821 if self.at(&TokenKind::LParen) {
822 self.bump();
823 self.skip_newlines();
824 if !self.eat(&TokenKind::RParen) {
825 loop {
826 self.skip_newlines();
827 match self.bump() {
828 TokenKind::Ident(p) => params.push(p),
829 other => {
830 return Err(
831 self.error(format!("expected a parameter name, found {other:?}"))
832 )
833 }
834 }
835 self.skip_newlines();
836 if self.eat(&TokenKind::Comma) {
837 continue;
838 }
839 self.expect(&TokenKind::RParen, "`,` or `)`")?;
840 break;
841 }
842 }
843 }
844 let body = self.body(&["end"])?;
845 self.expect_ident("end")?;
846 Ok(Sexp::List(vec![
847 sym("lambda"),
848 Sexp::List(params.iter().map(|p| sym(p)).collect()),
849 body,
850 ]))
851 }
852
853 /// `test "name" ... end` => `(deftest "name" body)`
854 ///
855 /// A string, not an identifier: a test name is prose for a human report,
856 /// and forcing it into an identifier is how test names become
857 /// `test_adds_two_numbers_correctly`.
858 fn test_form(&mut self) -> Result<Sexp, ParseError> {
859 let name = match self.bump() {
860 TokenKind::Str(s) => s,
861 other => {
862 return Err(self.error(format!(
863 "expected a string name after `test`, found {other:?}"
864 )))
865 }
866 };
867 let body = self.body(&["end"])?;
868 self.expect_ident("end")?;
869 Ok(Sexp::List(vec![
870 sym("deftest"),
871 Sexp::Atom(Atom::Str(name)),
872 body,
873 ]))
874 }
875
876 /// `assert expr` => `(blue-assert 'expr expr)`
877 ///
878 /// **`blue-assert`, not `assert`.** tatara-lisp's stdlib already defines
879 /// `assert` as a macro — `(defmacro assert (pred message) …)` — and a macro
880 /// in the expander is consulted before any primitive in the registry. So
881 /// lowering to `assert` bound `pred` to the *quoted form*, which is
882 /// truthy, and **every assertion silently passed**. A test framework whose
883 /// assertions always pass is the worst defect it can have: every test in
884 /// the suite goes green.
885 ///
886 /// The lesson generalizes: any name blue lowers to that tatara already
887 /// binds is silently captured. `blue_lang_test`'s
888 /// `no_lowered_name_is_shadowed_by_the_runtime` gates the whole class.
889 ///
890 /// **Both the form and the value.** A test framework whose failure says
891 /// only "assertion failed" makes the author re-derive what they were
892 /// checking; one that shows the expression does not. The quoted form is
893 /// the expression as DATA, so the runner can render it — and it renders it
894 /// through `blue-lang-fmt`, meaning the failure message is in canonical
895 /// blue syntax rather than the underlying tatara-lisp.
896 ///
897 /// This is homoiconicity paying for itself: the capture needs no source
898 /// map, no macro hygiene, and no string of the original text.
899 fn assert_form(&mut self) -> Result<Sexp, ParseError> {
900 let e = self.expr(0)?;
901 Ok(Sexp::List(vec![
902 sym(LOWERED_ASSERT),
903 Sexp::Quote(Box::new(e.clone())),
904 e,
905 ]))
906 }
907
908 /// `defmacro name(a, b) ... end` => `(defmacro name (a b) body)`
909 ///
910 /// **Deliberately untyped.** A macro's parameters are *source forms*, not
911 /// values, so `a: Int` would be a category error: the argument at expansion
912 /// time is a fragment of syntax. §IV's ladder types values; macro
913 /// parameters are not on it. Annotating one is rejected rather than
914 /// silently ignored — an ignored annotation is how an author comes to
915 /// believe a check is running.
916 fn defmacro_form(&mut self) -> Result<Sexp, ParseError> {
917 let name = match self.bump() {
918 TokenKind::Ident(n) => n,
919 other => {
920 return Err(self.error(format!("expected a name after `defmacro`, found {other:?}")))
921 }
922 };
923 let mut params: Vec<String> = Vec::new();
924 if self.at(&TokenKind::LParen) {
925 self.bump();
926 self.skip_newlines();
927 if !self.eat(&TokenKind::RParen) {
928 loop {
929 self.skip_newlines();
930 match self.bump() {
931 TokenKind::Ident(p) => params.push(p),
932 TokenKind::Label(p) => {
933 return Err(self.error(format!(
934 "macro parameter `{p}` cannot be typed: a macro receives \
935 source forms, not values"
936 )))
937 }
938 other => {
939 return Err(
940 self.error(format!("expected a parameter name, found {other:?}"))
941 )
942 }
943 }
944 self.skip_newlines();
945 if self.eat(&TokenKind::Comma) {
946 continue;
947 }
948 self.expect(&TokenKind::RParen, "`,` or `)`")?;
949 break;
950 }
951 }
952 }
953 if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
954 return Err(self.error(
955 "a macro has no return type: it produces source forms, not values".to_string(),
956 ));
957 }
958
959 let body = self.body(&["end"])?;
960 self.expect_ident("end")?;
961
962 // `(defmacro name (params) body)` — tatara-lisp's own shape, so blue
963 // registers into the SAME expander rather than a parallel one.
964 Ok(Sexp::List(vec![
965 sym("defmacro"),
966 sym(&name),
967 Sexp::List(params.iter().map(|p| sym(p)).collect()),
968 body,
969 ]))
970 }
971
972 /// `quote ... end` => `` `body `` (a quasiquote).
973 ///
974 /// Quasiquote rather than plain quote, because a macro body that could not
975 /// splice its arguments in would be useless — this is Elixir's `quote do`,
976 /// which is likewise a template and not inert data.
977 fn quote_form(&mut self) -> Result<Sexp, ParseError> {
978 let body = self.body(&["end"])?;
979 self.expect_ident("end")?;
980 // `Sexp::Quasiquote`, NOT `(quasiquote body)` as a list.
981 //
982 // The list form Displays as the text `(quasiquote …)`, which the
983 // tatara-lisp reader reads back as an ordinary list whose head happens
984 // to be the symbol `quasiquote` — losing the structure. The evaluator
985 // then reached the inner `,x` with no enclosing quasiquote and rejected
986 // it: "unquote outside of quasiquote". Building the real variant makes
987 // it Display as `` ` `` and survive the round trip.
988 Ok(Sexp::Quasiquote(Box::new(body)))
989 }
990
991 /// `unquote(expr)` => `,expr`; `unquote_splice(expr)` => `,@expr`.
992 fn unquote_form(&mut self, splice: bool) -> Result<Sexp, ParseError> {
993 self.expect(&TokenKind::LParen, "`(` after unquote")?;
994 self.skip_newlines();
995 let inner = self.expr(0)?;
996 self.skip_newlines();
997 self.expect(&TokenKind::RParen, "`)`")?;
998 Ok(if splice {
999 Sexp::UnquoteSplice(Box::new(inner))
1000 } else {
1001 Sexp::Unquote(Box::new(inner))
1002 })
1003 }
1004
1005 fn def_form(&mut self) -> Result<Sexp, ParseError> {
1006 let name = match self.bump() {
1007 TokenKind::Ident(n) => n,
1008 other => {
1009 return Err(self.error(format!("expected a name after `def`, found {other:?}")))
1010 }
1011 };
1012 let mut params: Vec<(String, Option<Sexp>)> = Vec::new();
1013 if self.at(&TokenKind::LParen) {
1014 self.bump();
1015 self.skip_newlines();
1016 if !self.eat(&TokenKind::RParen) {
1017 loop {
1018 self.skip_newlines();
1019 match self.bump() {
1020 // `a` — unannotated
1021 TokenKind::Ident(p) => params.push((p, None)),
1022 // `a:` came through as one token, so a type follows
1023 TokenKind::Label(p) => {
1024 self.skip_newlines();
1025 let ty = self.type_expr()?;
1026 params.push((p, Some(ty)));
1027 }
1028 other => {
1029 return Err(
1030 self.error(format!("expected a parameter name, found {other:?}"))
1031 )
1032 }
1033 }
1034 self.skip_newlines();
1035 if self.eat(&TokenKind::Comma) {
1036 continue;
1037 }
1038 self.expect(&TokenKind::RParen, "`,` or `)`")?;
1039 break;
1040 }
1041 }
1042 }
1043
1044 // Optional `-> R`
1045 let ret = if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
1046 self.bump();
1047 self.skip_newlines();
1048 Some(self.type_expr()?)
1049 } else {
1050 None
1051 };
1052
1053 let body = self.body(&["end"])?;
1054 self.expect_ident("end")?;
1055
1056 let annotated = ret.is_some() || params.iter().any(|(_, t)| t.is_some());
1057 if !annotated {
1058 let mut sig = vec![sym(&name)];
1059 sig.extend(params.into_iter().map(|(p, _)| sym(&p)));
1060 return Ok(Sexp::List(vec![sym("define"), Sexp::List(sig), body]));
1061 }
1062
1063 // Typed shape. An un-annotated parameter in an otherwise annotated
1064 // signature is written `(p dyn)` so the checker sees the ladder
1065 // position explicitly rather than inferring it from absence.
1066 let mut sig = vec![sym(&name)];
1067 for (p, t) in params {
1068 let ty = t.unwrap_or_else(|| sym("dyn"));
1069 sig.push(Sexp::List(vec![sym(&p), ty]));
1070 }
1071 Ok(Sexp::List(vec![
1072 sym("define-typed"),
1073 Sexp::List(sig),
1074 ret.unwrap_or_else(|| sym("dyn")),
1075 body,
1076 ]))
1077 }
1078
1079 /// A type expression. Currently a bare name (`Int`, `Str`, `dyn`) or a
1080 /// one-argument constructor (`List(Int)`).
1081 fn type_expr(&mut self) -> Result<Sexp, ParseError> {
1082 let name = match self.bump() {
1083 TokenKind::Ident(n) => n,
1084 other => return Err(self.error(format!("expected a type name, found {other:?}"))),
1085 };
1086 if self.at(&TokenKind::LParen) {
1087 let args = self.paren_args()?;
1088 let mut list = vec![sym(&name)];
1089 list.extend(args);
1090 return Ok(Sexp::List(list));
1091 }
1092 Ok(sym(&name))
1093 }
1094
1095 /// Consume `name` if it is the next token, else leave the position alone.
1096 fn eat_ident(&mut self, name: &str) -> bool {
1097 if self.at_ident(name) {
1098 self.bump();
1099 true
1100 } else {
1101 false
1102 }
1103 }
1104
1105 fn expect_ident(&mut self, name: &str) -> Result<(), ParseError> {
1106 if self.at_ident(name) {
1107 self.bump();
1108 Ok(())
1109 } else {
1110 Err(self.error(format!("expected `{name}`, found {:?}", self.peek())))
1111 }
1112 }
1113
1114 /// A sequence of expressions up to one of `terminators`, wrapped in
1115 /// `(begin ...)` when there is more than one.
1116 fn body(&mut self, terminators: &[&str]) -> Result<Sexp, ParseError> {
1117 let mut forms = Vec::new();
1118 loop {
1119 self.skip_newlines();
1120 if matches!(self.peek(), TokenKind::Eof) {
1121 return Err(self.error(format!(
1122 "unterminated block: expected one of {terminators:?}"
1123 )));
1124 }
1125 if terminators.iter().any(|t| self.at_ident(t)) {
1126 break;
1127 }
1128 forms.push(self.statement()?);
1129 }
1130 Ok(match forms.len() {
1131 0 => Sexp::Nil,
1132 1 => forms.into_iter().next().expect("checked len"),
1133 _ => {
1134 let mut list = vec![sym("begin")];
1135 list.extend(forms);
1136 Sexp::List(list)
1137 }
1138 })
1139 }
1140}
1141
1142fn sym(s: &str) -> Sexp {
1143 Sexp::Atom(Atom::Symbol(s.to_string()))
1144}
1145
1146#[cfg(test)]
1147mod tests {
1148 use super::*;
1149
1150 /// Render an `Sexp` to canonical text so tests can state the expected
1151 /// quoted form as a string. This is `Display`, which tatara-lisp owns —
1152 /// blue does not build Lisp syntax by concatenation.
1153 fn q(src: &str) -> String {
1154 parse_expr(src)
1155 .map(|s| s.to_string())
1156 .unwrap_or_else(|e| panic!("{src:?}: {e}"))
1157 }
1158
1159 // ---- the thesis: Ruby-shaped source becomes tatara-lisp ----------
1160
1161 #[test]
1162 fn arithmetic_respects_precedence() {
1163 assert_eq!(q("1 + 2 * 3"), "(+ 1 (* 2 3))");
1164 assert_eq!(q("(1 + 2) * 3"), "(* (+ 1 2) 3)");
1165 }
1166
1167 #[test]
1168 fn comparison_binds_looser_than_arithmetic() {
1169 assert_eq!(q("a + 1 < b"), "(< (+ a 1) b)");
1170 }
1171
1172 /// The expected tree names `or`/`and`, not `||`/`&&`: the surface
1173 /// spelling is the SURFACE's, and lowering renames it to the form
1174 /// tatara-lisp actually has. This test previously asserted the verbatim
1175 /// spelling, which is how `(== a b)` — a symbol nothing binds — shipped.
1176 #[test]
1177 fn logical_operators_bind_loosest_and_lower_to_tataras_names() {
1178 assert_eq!(q("a && b || c"), "(or (and a b) c)");
1179 }
1180
1181 #[test]
1182 fn left_associativity() {
1183 assert_eq!(q("1 - 2 - 3"), "(- (- 1 2) 3)");
1184 }
1185
1186 /// A bare `recv.name` is a SEND. Blue commits to uniform access here,
1187 /// so a field can later become a computed method without breaking
1188 /// callers.
1189 #[test]
1190 fn method_call_without_parens_is_a_send() {
1191 assert_eq!(q("user.name"), "(name user)");
1192 }
1193
1194 #[test]
1195 fn method_call_with_args() {
1196 assert_eq!(q("user.greet(1, 2)"), "(greet user 1 2)");
1197 }
1198
1199 #[test]
1200 fn chained_sends_read_left_to_right() {
1201 assert_eq!(q("a.b.c"), "(c (b a))");
1202 }
1203
1204 #[test]
1205 fn plain_call() {
1206 assert_eq!(q("f(1, 2)"), "(f 1 2)");
1207 }
1208
1209 /// The pipeline threads into the FIRST argument, as Elixir's does —
1210 /// that is what makes `|>` composable rather than decorative.
1211 #[test]
1212 fn pipeline_threads_into_first_argument() {
1213 assert_eq!(q("x |> f"), "(f x)");
1214 assert_eq!(q("x |> f(1)"), "(f x 1)");
1215 assert_eq!(q("x |> f |> g"), "(g (f x))");
1216 }
1217
1218 #[test]
1219 fn pipeline_binds_looser_than_arithmetic() {
1220 assert_eq!(q("1 + 2 |> f"), "(f (+ 1 2))");
1221 }
1222
1223 // ---- §V.13's rendering law, enforced at the parser ---------------
1224
1225 /// `a: 1` and `:a => 1` are the SAME TREE. That is exactly why the
1226 /// formatter may always render the shorthand: they are not two
1227 /// spellings of two things, they are two spellings of one thing.
1228 #[test]
1229 fn label_and_rocket_produce_the_same_tree_for_a_symbol_key() {
1230 assert_eq!(q("{a: 1}"), q("{:a => 1}"));
1231 assert_eq!(q("{a: 1}"), "(hash-map :a 1)");
1232 }
1233
1234 /// And where the key is NOT a plain symbol, the rocket is the only
1235 /// spelling — so it survives because it must, never as a style choice.
1236 #[test]
1237 fn a_string_key_has_no_shorthand() {
1238 assert_eq!(q(r#"{"k" => 1}"#), r#"(hash-map "k" 1)"#);
1239 }
1240
1241 #[test]
1242 fn list_literal() {
1243 assert_eq!(q("[1, 2, 3]"), "(list 1 2 3)");
1244 assert_eq!(q("[]"), "(list)");
1245 }
1246
1247 // ---- blocks ------------------------------------------------------
1248
1249 #[test]
1250 fn if_else_end() {
1251 assert_eq!(q("if a\n 1\nelse\n 2\nend"), "(if a 1 2)");
1252 }
1253
1254 #[test]
1255 fn if_without_else() {
1256 assert_eq!(q("if a\n 1\nend"), "(if a 1)");
1257 }
1258
1259 /// `unless` lowers to `(if (not c) …)` — one tree per meaning, so
1260 /// every downstream tool sees exactly one shape.
1261 #[test]
1262 fn unless_is_a_negated_if() {
1263 assert_eq!(q("unless a\n 1\nend"), "(if (not a) 1)");
1264 }
1265
1266 #[test]
1267 fn multi_statement_body_becomes_begin() {
1268 assert_eq!(q("if a\n 1\n 2\nend"), "(if a (begin 1 2))");
1269 }
1270
1271 #[test]
1272 fn def_lowers_to_define() {
1273 assert_eq!(
1274 q("def add(a, b)\n a + b\nend"),
1275 "(define (add a b) (+ a b))"
1276 );
1277 }
1278
1279 #[test]
1280 fn def_with_no_params() {
1281 assert_eq!(q("def zero()\n 0\nend"), "(define (zero) 0)");
1282 }
1283
1284 // ---- literals ----------------------------------------------------
1285
1286 #[test]
1287 fn literals_lower_to_atoms() {
1288 assert_eq!(q("42"), "42");
1289 assert_eq!(q("true"), "#t");
1290 assert_eq!(q(":ok"), ":ok");
1291 assert_eq!(q(r#""hi""#), r#""hi""#);
1292 }
1293
1294 #[test]
1295 fn unary_minus_and_not() {
1296 assert_eq!(q("-x"), "(- 0 x)");
1297 assert_eq!(q("!x"), "(not x)");
1298 }
1299
1300 // ---- programs and errors -----------------------------------------
1301
1302 #[test]
1303 fn a_program_is_a_sequence_of_forms() {
1304 let forms = parse_program("def f()\n 1\nend\nf()").expect("parse");
1305 assert_eq!(forms.len(), 2);
1306 assert_eq!(forms[1].to_string(), "(f)");
1307 }
1308
1309 #[test]
1310 fn unterminated_block_is_an_error_naming_what_was_expected() {
1311 let e = parse_program("if a\n 1").expect_err("must fail");
1312 assert!(e.message.contains("unterminated"), "{}", e.message);
1313 }
1314
1315 #[test]
1316 fn a_parse_error_carries_a_span_into_the_source() {
1317 let src = "1 + )";
1318 let e = parse_program(src).expect_err("must fail");
1319 assert!(e.span.start < src.len(), "span {:?} outside source", e.span);
1320 }
1321
1322 /// Anti-vacuity: `q` must be able to FAIL. If every input parsed, the
1323 /// assertions above would be worthless.
1324 #[test]
1325 fn the_parser_rejects_garbage() {
1326 assert!(parse_program("def").is_err());
1327 assert!(parse_program("(1").is_err());
1328 assert!(parse_program("end").is_err());
1329 }
1330}