blue_lang_runtime/pipeline.rs
1//! The blue pipeline: **parse → check → erase → run**, in that order, once.
2//!
3//! The order is the whole reason this module exists. Each stage is available
4//! separately for tools that want one, but the *default* path is a single
5//! function, because two of the four orderings are silently wrong:
6//!
7//! - **Erase before check** discards every annotation, so a program with type
8//! errors passes. The checker sees `(define …)` and has nothing to check.
9//! - **Run before check** reports a type error after the side effects.
10//!
11//! Neither fails loudly. Both produce a green run on a program that should
12//! have been rejected. Leaving the order to each caller means every caller
13//! is one reordering away from turning the type checker off — so the order
14//! lives here, and callers ask for a *result*, not a sequence of steps.
15
16use tatara_lisp::Sexp;
17use tatara_lisp_eval::Value;
18
19use blue_lang_check::{NameTable, Namespace};
20
21use crate::erase::erase_types;
22use crate::inputs::Inputs;
23use crate::uses::Entry;
24
25/// Why a run stopped short.
26#[derive(Debug, thiserror::Error)]
27pub enum RunError {
28 #[error("parse error: {0}")]
29 Parse(String),
30 /// The check stage rejected the program — a type error, an unbound name,
31 /// or any other error-severity rule in `blue_lang_check::RULES`. Carries
32 /// every error, not just the first: a caller fixing one wants to see the
33 /// rest. (The variant keeps its first name because it is public API on a
34 /// released crate.)
35 ///
36 /// Each one is already rendered `file:line:col: message` against the file
37 /// the offending form came from — which, in a program with imports, is
38 /// frequently not the file the user named. The rendering happens here
39 /// rather than at the consumer because here is where the file table exists;
40 /// see `uses::ResolvedProgram::locate`.
41 #[error("{} error(s) in the check stage:\n{}", .0.len(), .0.join("\n"))]
42 Types(Vec<String>),
43 /// **No longer reachable, and that is the point.** This reported "blue
44 /// emitted a tree the reader could not read back" — a failure only a
45 /// print-then-reparse hop could have. [`crate::lower_to_spanned`] deleted
46 /// the hop, so there is nothing left to fail: the tree the evaluator gets
47 /// IS the tree erasure produced, not a re-reading of its text.
48 ///
49 /// Kept rather than removed because it is public API on a released crate
50 /// and a consumer may still match on it, per ★★ MODULARIZE, DON'T DELETE.
51 /// It is retired, not orphaned — if a future stage ever serialises again
52 /// it has a typed home. **Nothing constructs it today**; do not read its
53 /// presence as evidence the pipeline can still fail this way.
54 #[error("the emitted tatara-lisp could not be read back: {0}")]
55 Lower(String),
56 /// The program ran and raised.
57 ///
58 /// Rendered `file:line:col: message` against the file the failing form's
59 /// top-level form came from — the same `uses::ResolvedProgram::locate`
60 /// machinery, the same file table and the same join key the type errors
61 /// above use. Until erasure learned to carry spans this was a bare
62 /// message, because the evaluator was handed a tree whose every node had
63 /// been stamped `Span::synthetic()` on the way in.
64 ///
65 /// **The honest limit, stated so nobody reads more into a position than is
66 /// there.** The index names the top-level form that was EXECUTING; the span
67 /// names where the failing text SITS. Those agree on the file whenever the
68 /// failing code is in the same file as the top-level form that reached it —
69 /// which is every single-file program, and an imported package whose own
70 /// top-level code raises. They can disagree when a top-level form in file A
71 /// calls a function defined in file B and the raise happens inside B: the
72 /// path reported is A's. `locate` refuses to print a `line:col` it cannot
73 /// justify (the span must be a real range in that file), so the usual shape
74 /// of that case is a file with no position rather than a precise-looking
75 /// wrong one — but a same-length pair of files can still put a plausible
76 /// number on the wrong file. Closing it needs per-frame file identity at
77 /// the evaluator, which is a call stack blue does not have.
78 #[error("runtime error: {0}")]
79 Eval(String),
80 /// A `use("name")` could not be resolved.
81 ///
82 /// Its own variant rather than folded into `Parse`, because the reader's
83 /// next action is different: a parse error is in the source in front of
84 /// them, an import error is in their packaging — a missing bidama, a
85 /// BLUE_PATH that does not contain it, or no loader at all.
86 #[error("import error: {0}")]
87 Import(String),
88}
89
90/// What a run produced, plus what the checker did on the way.
91#[derive(Debug)]
92pub struct Run {
93 pub value: Value,
94 /// Nodes the type walk visited. Zero for a fully untyped program — this
95 /// is what makes "no annotations, no analysis" a *measurement* rather
96 /// than a claim.
97 pub visited: usize,
98 /// Declarations that carried an annotation.
99 pub typed_decls: usize,
100 /// Boundaries where typed code meets untyped code.
101 pub seams: usize,
102}
103
104/// Parse blue source to tatara-lisp forms.
105pub fn parse(src: &str) -> Result<Vec<Sexp>, RunError> {
106 parse_with_depth(src, blue_lang_syntax::MAX_EXPR_DEPTH)
107}
108
109/// [`parse`] with the parser's nesting bound supplied by the caller.
110///
111/// The bound exists so a stack overflow — which `catch_unwind` cannot catch —
112/// arrives as a typed `Err` instead. It is a *limit*, not a dialect: raising
113/// it changes no program's meaning, which is exactly why it is safe to expose
114/// as configuration (`blue-lang-cli`'s `config` module holds the rule).
115pub fn parse_with_depth(src: &str, max_depth: usize) -> Result<Vec<Sexp>, RunError> {
116 blue_lang_syntax::parse_program_with_depth(src, max_depth)
117 .map_err(|e| RunError::Parse(e.to_string()))
118}
119
120/// [`parse_with_depth`] keeping **every node's** source span.
121///
122/// The door for anything that will report a position to a human. It exists here,
123/// beside the spanless one, so a caller that wants spans still parses under the
124/// CONFIGURED nesting bound — a separate `blue_lang_syntax` call would be the
125/// second door `parse_with_depth`'s own docs exist to prevent, with
126/// `max_expr_depth` true of some subcommands and not others.
127pub fn parse_tree_with_depth(
128 src: &str,
129 max_depth: usize,
130) -> Result<Vec<blue_lang_syntax::Spanned>, RunError> {
131 blue_lang_syntax::parse_program_tree_with_depth(src, max_depth)
132 .map_err(|e| RunError::Parse(e.to_string()))
133}
134
135/// [`parse`] keeping **every node's** source span.
136///
137/// The spanned twin of [`parse`], at the same default bound — the door for
138/// anything downstream of a parse that will report a position, which since
139/// `use` learned to carry file identity is every path through
140/// [`run_in_surface`].
141pub fn parse_tree(src: &str) -> Result<Vec<blue_lang_syntax::Spanned>, RunError> {
142 parse_tree_with_depth(src, blue_lang_syntax::MAX_EXPR_DEPTH)
143}
144
145/// Run blue source with no build inputs.
146pub fn run(src: &str) -> Result<Run, RunError> {
147 run_with_inputs(src, Inputs::new())
148}
149
150/// Run blue source, giving the macro phase access to verified build inputs.
151///
152/// `inputs` is already verified — [`Inputs`] cannot hold bytes that do not match
153/// their declared hash — so nothing here re-checks. The capability a macro gains
154/// is exactly "these hashed bytes", never a path.
155pub fn run_with_inputs(src: &str, inputs: Inputs) -> Result<Run, RunError> {
156 run_with_loader(src, inputs, &crate::uses::NoLoader)
157}
158
159/// Run blue source with a loader, so `use("name")` can resolve.
160///
161/// Split from [`run_with_inputs`] rather than folded into it because loading a
162/// package reads a filesystem, and this crate has a `wasm32-unknown-unknown`
163/// consumer with zero host imports. The capability is injected by callers that
164/// have it — `blue_lang_pkg::LoadPath` is the real one — and absent by default,
165/// where a `use` is a typed error naming the package.
166pub fn run_with_loader(
167 src: &str,
168 inputs: Inputs,
169 loader: &dyn crate::uses::Loader,
170) -> Result<Run, RunError> {
171 run_in_surface(Entry::anonymous(src), inputs, loader, None)
172}
173
174/// Run blue source written in a `yakugo` surface.
175///
176/// The pack applies at PARSE time and nowhere else — by the time the checker
177/// sees the program it is canonical, so every stage below is identical whatever
178/// surface the author wrote in. That is what makes a surface a surface: it
179/// changes how a program is spelled and nothing about how it runs.
180///
181/// `entry` carries the source AND the file it was read from, because a type
182/// error has to be reported somewhere: a caller with a path should pass it, and
183/// one without ([`Entry::anonymous`]) gets diagnostics that say so rather than
184/// diagnostics that guess. Imported packages name themselves through the
185/// loader either way.
186///
187/// # Errors
188///
189/// As [`run_with_loader`].
190pub fn run_in_surface(
191 entry: Entry<'_>,
192 inputs: Inputs,
193 loader: &dyn crate::uses::Loader,
194 surface: Option<&blue_lang_syntax::yakugo::Yakugo>,
195) -> Result<Run, RunError> {
196 // The interpreter is built BEFORE the check stage, because it is the check
197 // stage's name oracle: every builtin, macro and special form a program may
198 // name is read off the interpreter that will run it, never off a list.
199 // Building it is not a stage; nothing is evaluated until `eval_prepared`.
200 let mut interp = crate::interpreter_hostless();
201 crate::inputs::install_input_primitives(&mut interp, inputs);
202 let prepared = prepare(entry, loader, surface, &builtin_names(&interp))?;
203 let value = eval_prepared(&mut interp, &prepared, &mut ())?;
204 Ok(Run {
205 value,
206 visited: prepared.visited,
207 typed_decls: prepared.typed_decls,
208 seams: prepared.seams,
209 })
210}
211
212/// A program past every stage before evaluation: parsed, its imports
213/// resolved, type-checked and erased. What [`run_in_surface`] and
214/// [`crate::hosted::load_hosted`] both evaluate, so the stage order this
215/// module exists to own is written once for both.
216pub(crate) struct Prepared {
217 program: crate::uses::ResolvedProgram,
218 erased: Vec<tatara_lisp::Spanned>,
219 visited: usize,
220 typed_decls: usize,
221 seams: usize,
222}
223
224/// Parse, resolve, check and erase, in that order.
225///
226/// `builtins` is the name table of the interpreter that will evaluate the
227/// result ([`builtin_names`]); the check stage resolves the program's names
228/// against it.
229pub(crate) fn prepare(
230 entry: Entry<'_>,
231 loader: &dyn crate::uses::Loader,
232 surface: Option<&blue_lang_syntax::yakugo::Yakugo>,
233 builtins: &NameTable,
234) -> Result<Prepared, RunError> {
235 let mut program = parse_and_resolve(entry, loader, surface)?;
236
237 // `test` blocks are declarations for the harness, not code to run.
238 //
239 // Dropped here rather than in `resolve_uses`, because `blue test` calls
240 // the resolver and then NEEDS the entry file's blocks — so the two
241 // callers want different things and the split has to live at this level.
242 //
243 // Without this, `blue run` on a file containing its own tests fails with
244 // `unbound symbol: deftest`: every package in the bidama distribution
245 // carries tests, so every one of them was unrunnable.
246 //
247 // Through `retain`, which drops each form's owner with it. A plain filter
248 // over the forms alone would slide every later form onto the wrong file.
249 program.retain(|f| !crate::uses::is_test_form(f));
250
251 // CHECK, on the annotated tree — the only tree that has annotations.
252 //
253 // **On the REAL spanned tree, including every imported package's.** This
254 // was the one caller that checked a spanless lift, because `resolve_uses`
255 // flattened the entry file and its imports into one list and `Span` is a
256 // byte range with no file identity — so a real span here would have
257 // reported an imported package's error at that offset in the ENTRY file, a
258 // precise-looking answer pointing at unrelated code.
259 //
260 // The fix is not a wider `Span` (that type is upstream, and its own docs
261 // put file identity on the caller: spans "are meaningful only relative to
262 // the string that produced them, which the caller is responsible for
263 // holding onto"). blue holds onto it BESIDE the span, per top-level form —
264 // see `uses::ResolvedProgram`.
265 let (outcome, _) = check_stage(&program, builtins);
266 if !outcome.ok() {
267 return Err(RunError::Types(
268 outcome
269 .errors()
270 // `file:line:col: error[CODE]: message`, resolved against the
271 // file the form actually came from, then its help line.
272 .map(|d| render(&program, d))
273 .collect(),
274 ));
275 }
276
277 // ERASE, so the interpreter never sees a type — **on the spanned tree,
278 // and back out as one.**
279 //
280 // This used to be `erase_types(&program.sexps())` followed by a
281 // `lower_to_spanned` that stamped `Span::synthetic()` over every node, and
282 // the comment here said carrying real positions through was "a larger
283 // piece and is NOT built". It was not larger: erasure only ever DELETES
284 // nodes — the single node it invents is the `define` replacing
285 // `define-typed` — so there was never anything for a synthetic span to
286 // stand in for. See `crate::erase`.
287 //
288 // No lowering step follows. The tree the evaluator receives IS the tree the
289 // parser built, minus annotations, with the author's byte offsets intact.
290 let erased = erase_types(program.forms());
291
292 Ok(Prepared {
293 program,
294 erased,
295 visited: outcome.stats.visited,
296 typed_decls: outcome.stats.typed_decls,
297 seams: outcome.seams.len(),
298 })
299}
300
301/// Parse the entry (in `surface`, if one is given) and splice in its imports.
302fn parse_and_resolve(
303 entry: Entry<'_>,
304 loader: &dyn crate::uses::Loader,
305 surface: Option<&blue_lang_syntax::yakugo::Yakugo>,
306) -> Result<crate::uses::ResolvedProgram, RunError> {
307 let forms = match surface {
308 Some(pack) => blue_lang_syntax::parse_program_tree_in(entry.text, pack)
309 .map_err(|e| RunError::Parse(e.to_string()))?,
310 None => parse_tree(entry.text)?,
311 };
312
313 // RESOLVE imports first, so everything below sees ONE program.
314 //
315 // Before the check on purpose: imported code is type-checked at the point
316 // its consumer imports it, rather than at whatever later moment its code
317 // first runs. A package that does not typecheck should break its importer's
318 // build, not their production run.
319 //
320 // One program, but not one FILE: the result records which file each
321 // top-level form came from, which is what lets a diagnostic below name a
322 // place instead of only a problem.
323 crate::uses::resolve_uses(forms, entry, loader).map_err(RunError::Import)
324}
325
326/// **The check stage**: every rule in `blue_lang_check::RULES`, over a
327/// resolved program, with waivers applied.
328///
329/// One function, called by every door — `run`, the hosted loader, `blue test`
330/// and `blue check` — so a rule added to the registry is enforced by all of
331/// them at once. That is what makes an architecture rule a pipeline error
332/// rather than an optional report: there is no door that skips it.
333///
334/// Warnings (unused bindings, unused waivers) are reported for the ENTRY
335/// file only; an imported package's warnings belong to its author. Errors
336/// are reported for every file, because an imported package with one is
337/// broken for its importer.
338fn check_stage(
339 program: &crate::uses::ResolvedProgram,
340 builtins: &NameTable,
341) -> (blue_lang_check::Outcome, NameTable) {
342 use crate::uses::ResolvedProgram;
343 let forms = program.forms();
344 let is_entry = |i: usize| program.owner_of(i) == Some(ResolvedProgram::ENTRY);
345
346 // Rules B0003–B0005: the typing ladder.
347 let mut outcome = blue_lang_check::check_program(forms);
348
349 // Rules B0001–B0002: names. The program's own scopes come first (the
350 // entry file, then each bidama in import order), then the interpreter's.
351 let table = program_names(program, builtins);
352 let (names, resolved) =
353 blue_lang_check::check_names(forms, &table, &|i| namespace_of(program, i), &is_entry);
354 outcome.diagnostics.extend(names);
355 outcome.stats.names_resolved = resolved;
356
357 // Waivers, per file: B0007 for a malformed one, B0008 for one that
358 // suppresses nothing.
359 let mut waivers = Vec::new();
360 for file in program.files() {
361 let spans: Vec<(usize, tatara_lisp::Span)> = forms
362 .iter()
363 .enumerate()
364 .filter(|(i, _)| program.owner_of(*i) == Some(file.id))
365 .map(|(i, f)| (i, f.span))
366 .collect();
367 let (found, malformed) = blue_lang_check::waiver::collect(&file.text, &spans);
368 waivers.extend(found);
369 outcome.diagnostics.extend(malformed);
370 }
371 outcome.waived = blue_lang_check::waiver::apply(&mut outcome.diagnostics, waivers, &is_entry);
372 outcome
373 .diagnostics
374 .sort_by_key(|d| (d.top_level, d.span.start, d.code));
375 (outcome, table)
376}
377
378/// The whole name table the check stage resolves against: the program's
379/// own scopes (each file and bidama, by namespace) followed by `builtins`.
380#[must_use]
381///
382/// **A top-level call to a builtin macro can define names**: `defflow(slug,
383/// trim, downcase)` expands to `(define slug …)`, and nothing in the source
384/// spells `define`. Such a call is expanded here, on a hostless fork, and what
385/// its expansion defines is bound in the calling file's namespace. Only
386/// BUILTIN macros are expanded: their bodies are the runtime's own
387/// templates. A program's own `defmacro` is not run at check time — checking a
388/// file (and an editor checking on every keystroke) must not execute the code
389/// it checks — so names a program macro generates are not seen; none of the
390/// corpus's macros generates one (measured 2026-09-29).
391#[must_use]
392pub fn program_names(program: &crate::uses::ResolvedProgram, builtins: &NameTable) -> NameTable {
393 use blue_lang_check::Binding;
394 let mut table = NameTable::new();
395 table.add_program(program.forms(), |i| namespace_of(program, i));
396 let builtin_macro = |head: &str| {
397 builtins
398 .scopes()
399 .iter()
400 .any(|s| s.namespace == Namespace::Macro && s.get(head).is_some())
401 };
402 let mut expander: Option<tatara_lisp_eval::Interpreter<()>> = None;
403 for (i, form) in program.forms().iter().enumerate() {
404 let Some(head) = form
405 .as_list()
406 .and_then(|items| items.first())
407 .and_then(tatara_lisp::Spanned::as_symbol)
408 else {
409 continue;
410 };
411 if !builtin_macro(head) {
412 continue;
413 }
414 let interp = expander.get_or_insert_with(crate::interpreter_hostless);
415 // A failed expansion defines nothing here; the evaluator will report
416 // it, with its position, when the form runs.
417 let Ok(expanded) = interp.fully_expand(form, &mut ()) else {
418 continue;
419 };
420 for (name, span, kind) in blue_lang_check::names::definitions_of(&expanded) {
421 table.define(
422 namespace_of(program, i),
423 Binding {
424 name,
425 kind,
426 span: Some(span),
427 top_level: Some(i),
428 },
429 );
430 }
431 }
432 for scope in builtins.scopes() {
433 table.push(scope.clone());
434 }
435 table
436}
437
438/// The namespace top-level form `i` of `program` defines into.
439#[must_use]
440pub fn namespace_of(program: &crate::uses::ResolvedProgram, i: usize) -> Namespace {
441 let file = program.owner_of(i).and_then(|id| program.file(id));
442 match file {
443 Some(f) => match &f.package {
444 Some(p) => Namespace::Bidama(p.clone()),
445 None => Namespace::File(
446 f.path
447 .as_ref()
448 .map_or_else(|| "<anonymous>".to_string(), |p| p.display().to_string()),
449 ),
450 },
451 None => Namespace::File("<unknown file>".to_string()),
452 }
453}
454
455/// Names only the test harness binds.
456///
457/// In scope for EVERY check, not only for test blocks. A bidama may carry a
458/// test helper — a plain `def` that asserts, called only from its `test`
459/// blocks (`heni`'s `hn_end_to_end` is one) — and every program importing that
460/// bidama would otherwise be refused for a function it never calls. The
461/// refusal would be scoped to the importer's whole program, not to the fault.
462/// The cost, stated: an `assert` outside any test that `blue run` actually
463/// reaches is caught at runtime (`blue-assert` is unbound there), not here.
464///
465/// `blue-lang-test` registers these on its own interpreter, and this crate
466/// cannot depend on it (it depends on this one), so the list lives beside the
467/// only name in it: the lowered `assert`, which `blue-lang-syntax` owns.
468pub const HARNESS_NAMES: &[&str] = &[blue_lang_syntax::LOWERED_ASSERT];
469
470/// The check stage's builtin scopes, read off the interpreter that will run
471/// the program: the test harness's names ([`HARNESS_NAMES`]), then its special
472/// forms, its macros, and every value it binds — the last three in the order
473/// the evaluator consults for a head.
474///
475/// Read from a live interpreter rather than a list, for the reason
476/// `Interpreter::resolve_head` gives: a list is a second copy of the truth and
477/// goes stale on the next installer that lands. An embedder's own
478/// primitives are in scope here because the embedder installs them first.
479#[must_use]
480pub fn builtin_names<H: 'static>(interp: &tatara_lisp_eval::Interpreter<H>) -> NameTable {
481 use blue_lang_check::{Binding, Scope, ScopeKind};
482 use tatara_lisp_eval::HeadBinding;
483 let mut special = Scope::new(Namespace::SpecialForm);
484 let mut macros = Scope::new(Namespace::Macro);
485 let mut values = Scope::new(Namespace::Builtin);
486 // `reserved_head_names` reads the ROOT frame only, so a name installed on
487 // a fork (the input primitives, on every `run`) is invisible to it; those
488 // are asked about by name instead, which `resolve_head` answers through
489 // every frame.
490 let mut names: Vec<std::sync::Arc<str>> = interp.reserved_head_names().into_iter().collect();
491 names.extend(
492 crate::inputs::INPUT_PRIMITIVES
493 .iter()
494 .filter(|n| interp.resolve_head(n).is_some())
495 .map(|n| std::sync::Arc::from(*n)),
496 );
497 for name in names {
498 let (scope, kind) = match interp.resolve_head(&name) {
499 Some(HeadBinding::SpecialForm) => (&mut special, ScopeKind::SpecialForm),
500 Some(HeadBinding::Macro) => (&mut macros, ScopeKind::Macro),
501 _ => (&mut values, ScopeKind::Value),
502 };
503 scope.bind(Binding {
504 name: name.to_string(),
505 kind,
506 span: None,
507 top_level: None,
508 });
509 }
510 let mut table = NameTable::new();
511 let mut harness = Scope::new(Namespace::Harness);
512 for n in HARNESS_NAMES {
513 harness.bind(Binding {
514 name: (*n).to_string(),
515 kind: ScopeKind::Value,
516 span: None,
517 top_level: None,
518 });
519 }
520 table.push(harness);
521 table.push(special);
522 table.push(macros);
523 table.push(values);
524 table
525}
526
527/// A diagnostic as a person reads it: `file:line:col: error[B0001]: message`,
528/// then an indented `help:` line when it has one.
529#[must_use]
530pub fn render(program: &crate::uses::ResolvedProgram, d: &blue_lang_check::Diagnostic) -> String {
531 let head = d.to_string();
532 let mut out = program.locate(d.top_level, d.span, &head).to_string();
533 if let Some(help) = &d.help {
534 out.push_str("\n help: ");
535 out.push_str(help);
536 }
537 out
538}
539
540/// What [`check_entry`] checks.
541#[derive(Clone, Copy, Debug, PartialEq, Eq)]
542pub enum Checking {
543 /// The program `blue run` would evaluate: test blocks dropped.
544 Program,
545 /// The program plus the entry file's test blocks, as `blue test` and
546 /// `blue check` see it.
547 WithTests,
548}
549
550/// A program through the check stage, with everything the stage found.
551pub struct Checked {
552 pub program: crate::uses::ResolvedProgram,
553 pub outcome: blue_lang_check::Outcome,
554 /// The name table the stage resolved against: every program scope, then
555 /// the builtins. What an editor completes from.
556 pub names: NameTable,
557}
558
559impl Checked {
560 /// Every non-local reference, resolved under both rules — today's flat
561 /// one and per-bidama namespaces — and the resolved trees built from them
562 /// (`blue ast --resolved`).
563 #[must_use]
564 pub fn resolve(&self) -> blue_lang_check::names::Resolved {
565 blue_lang_check::names::resolve_program(self.program.forms(), &self.names, &|i| {
566 namespace_of(&self.program, i)
567 })
568 }
569}
570
571/// Parse, resolve and CHECK, without running: the door for `blue check`,
572/// `blue test` and the language server.
573///
574/// Returns every diagnostic, errors and warnings alike, rather than failing on
575/// the first error: a reader fixing a file wants the whole list, and an agent
576/// repairing one wants it in one pass. Whether errors stop anything is the
577/// caller's decision — `blue test` refuses to run tests over a program with
578/// one, exactly as `run` refuses to evaluate it.
579///
580/// The name oracle is the interpreter `blue run` would build: hostless plus
581/// input primitives.
582///
583/// # Errors
584///
585/// A parse or import error, which leaves no program to check.
586pub fn check_entry(
587 entry: Entry<'_>,
588 loader: &dyn crate::uses::Loader,
589 surface: Option<&blue_lang_syntax::yakugo::Yakugo>,
590 checking: Checking,
591) -> Result<Checked, RunError> {
592 let mut program = parse_and_resolve(entry, loader, surface)?;
593 if checking == Checking::Program {
594 program.retain(|f| !crate::uses::is_test_form(f));
595 }
596 let mut interp = crate::interpreter_hostless();
597 crate::inputs::install_input_primitives(&mut interp, Inputs::new());
598 let builtins = builtin_names(&interp);
599 let (outcome, names) = check_stage(&program, &builtins);
600 Ok(Checked {
601 program,
602 outcome,
603 names,
604 })
605}
606
607/// A syntax error in `text` as a [`B0006`](blue_lang_check::Code::B0006)
608/// diagnostic, so a tool reading `--format json` gets a parse failure in the
609/// same shape as every other finding. `None` when `text` parses.
610#[must_use]
611pub fn syntax_diagnostic(text: &str) -> Option<blue_lang_check::Diagnostic> {
612 let e = blue_lang_syntax::parse_program_tree(text).err()?;
613 Some(
614 blue_lang_check::Diagnostic::new(blue_lang_check::Code::B0006, e.message, e.span)
615 .at_top_level(0),
616 )
617}
618
619/// Evaluate a prepared program's top-level forms into `interp`, with `host`.
620pub(crate) fn eval_prepared<H: 'static>(
621 interp: &mut tatara_lisp_eval::Interpreter<H>,
622 prepared: &Prepared,
623 host: &mut H,
624) -> Result<Value, RunError> {
625 let Prepared {
626 program, erased, ..
627 } = prepared;
628
629 // RUN, one top-level form at a time, **counting them**.
630 //
631 // This is literally the loop `Interpreter::eval_program` runs internally
632 // (tatara-lisp-eval `eval.rs`) — unrolled here for exactly one reason: the
633 // INDEX. `resolve_uses` flattens N files into one form list and a `Span` is
634 // a byte range with no file identity, so an offset alone is ambiguous
635 // across files — 66 means something in every one of them. The index is the
636 // join key back to `ResolvedProgram`'s file table, and `eval_program`
637 // consumes it internally and hands back only the error.
638 //
639 // The same key, the same renderer and the same file table the type errors
640 // above already use. A runtime error was the one diagnostic in this
641 // function still reporting a bare message.
642 let mut value = Value::Nil;
643 for (top_level, form) in erased.iter().enumerate() {
644 value = interp.eval_top_form(form, host).map_err(|e| {
645 // `span()` is `None` for the arms that genuinely have no position
646 // (`Reader`, `Halted`, `NotImplemented`). Synthetic is the honest
647 // stand-in — `locate` renders it as a file with no line rather
648 // than inventing one.
649 let at = e.span().unwrap_or_else(tatara_lisp::Span::synthetic);
650 // `short_message`, NOT `Display`. Upstream's `Display` ends every
651 // positioned arm with ` at {span}` — a raw byte range — and once
652 // blue prefixes a resolved `path:line:col` that suffix is the same
653 // fact told twice, the second time in a unit no reader can spend.
654 //
655 // Worse than redundant: a byte range is exactly the thing this
656 // whole file-identity apparatus exists to stop being reported on
657 // its own, because an offset means something different in every
658 // file. On the one case blue deliberately declines to place — a
659 // raise inside a callee from another file — `Display` would print
660 // the CALLEE's offsets beside the CALLER's path, re-creating the
661 // precise-looking wrong answer `locate`'s guard just refused.
662 // `short_message` is upstream's own "no source context" accessor,
663 // and blue supplies the context.
664 //
665 // Through `messages::describe`, which is `short_message` except
666 // where blue can say more: a wrong argument count names the
667 // function the author called, read off the call in this tree,
668 // instead of upstream's `<closure>` and a Rust `Debug` arity.
669 let message = crate::messages::describe(&e, erased);
670 RunError::Eval(program.locate(top_level, at, &message).to_string())
671 })?;
672 }
673 Ok(value)
674}
675
676/// **A runtime error names a place.** The gates for the last stage that
677/// reported a bare message.
678///
679/// Each fixture is sized so that resolving the failing span against ANY file
680/// but the right one lands somewhere else — a different path and a different
681/// line — so a green run here is evidence about the join and not about the
682/// renderer being called at all.
683///
684/// **Each raise is an unbound name, WAIVED.** Since the check stage resolves
685/// names (B0001), an unbound call no longer reaches the evaluator; these
686/// fixtures need exactly that runtime raise, so each carries
687/// `# waive B0001: …` above the definition holding it — the one escape hatch,
688/// used for what it is for. The waiver adds a line above each failing call,
689/// which is why the positions below are one line later than their red runs
690/// (recorded against the unwaived fixtures) show.
691#[cfg(test)]
692mod position_tests {
693 use super::*;
694 use crate::uses::{Entry, Loader};
695 use std::collections::BTreeMap;
696 use std::path::Path;
697
698 struct MemLoader(BTreeMap<&'static str, &'static str>);
699
700 impl Loader for MemLoader {
701 fn load(&self, name: &str) -> Result<Vec<(String, String)>, String> {
702 self.0
703 .get(name)
704 .map(|s| vec![(format!("{name}.b"), (*s).to_owned())])
705 .ok_or_else(|| format!("no bidama named \"{name}\""))
706 }
707 }
708
709 /// A package whose OWN top-level code raises, deep inside a file that is
710 /// deliberately taller than either of the other two.
711 ///
712 /// Byte 66 — where `kore_wa_sonzai_shinai` starts — is past the end of the
713 /// entry file (30 bytes) and past the end of `kotae.b` (21 bytes). So the
714 /// only file this span can honestly resolve against is this one, and the
715 /// other two now refuse to answer rather than walking off their ends.
716 const BAKUHATSU: &str = "\
717def tsukawanai_a()
718 1
719end
720
721def tsukawanai_b()
722 2
723end
724
725# waive B0001: the fixture needs a raise at runtime
726def bakuhatsu()
727 kore_wa_sonzai_shinai()
728end
729
730bakuhatsu()";
731
732 const KOTAE: &str = "def kotae()\n 42\nend";
733
734 /// The same failing call, but only ever reached by a CALLER in another
735 /// file — the shape that exercises `RunError::Eval`'s stated limit.
736 const BAKUHATSU2: &str =
737 "# waive B0001: a raise at runtime\ndef yobu()\n kore_wa_sonzai_shinai()\nend";
738
739 fn loader() -> MemLoader {
740 MemLoader(BTreeMap::from([
741 ("kotae", KOTAE),
742 ("bakuhatsu", BAKUHATSU),
743 ("bakuhatsu2", BAKUHATSU2),
744 ]))
745 }
746
747 fn run_named(path: &str, src: &str) -> RunError {
748 run_in_surface(
749 Entry {
750 path: Some(Path::new(path)),
751 text: src,
752 },
753 Inputs::new(),
754 &loader(),
755 None,
756 )
757 .expect_err("the fixture must raise")
758 }
759
760 /// **The load-bearing gate: a raise inside an IMPORTED package reports the
761 /// IMPORTED file's path and line.**
762 ///
763 /// Hand-computed. In `bakuhatsu.b` the failing call sits on line 11 at
764 /// column 3, and the whole point of the fixture's height is that no other
765 /// file in the program can produce that pair: the entry file has 2 lines
766 /// and `kotae.b` has 3, so *any* mis-attribution is visible as a different
767 /// path AND a different position, never as a coincidence.
768 ///
769 /// **Three red runs, one per edit this change makes** — each isolates a
770 /// different half of the mechanism, which is what stops the gate being a
771 /// tautology over "some renderer ran".
772 ///
773 /// 1. `eval_program` + `.map_err(|e| RunError::Eval(e.to_string()))`
774 /// restored (the pre-change code):
775 /// ```text
776 /// left: "runtime error: unbound symbol: kore_wa_sonzai_shinai at 74..95"
777 /// right: "runtime error: bakuhatsu.b:10:3: unbound symbol `kore_wa_sonzai_shinai`"
778 /// ```
779 /// No place at all — the state this change is fixing — and the trailing
780 /// `at 74..95` is upstream's `Display`, an offset with no file, which is
781 /// why the loop renders `short_message` instead.
782 ///
783 /// 2. The loop kept, but `0` passed to `locate` in place of `top_level`:
784 /// ```text
785 /// left: "runtime error: kotae.b: unbound symbol `kore_wa_sonzai_shinai`"
786 /// right: "runtime error: bakuhatsu.b:10:3: unbound symbol `kore_wa_sonzai_shinai`"
787 /// ```
788 /// **This is the one that proves the INDEX is load-bearing** rather than
789 /// the renderer: form 0 belongs to `kotae.b`, so the wrong file is named
790 /// — and named without a position, because the guard in `locate` sees
791 /// that byte 74 is not a range in a 21-byte file and declines to invent
792 /// one. A fixture with one imported package could not tell these apart.
793 ///
794 /// 3. `crate::lower_to_spanned(&crate::to_sexps(&erased))` reinstated
795 /// between erasure and the loop:
796 /// ```text
797 /// left: "runtime error: bakuhatsu.b: unbound symbol `kore_wa_sonzai_shinai`"
798 /// right: "runtime error: bakuhatsu.b:10:3: unbound symbol `kore_wa_sonzai_shinai`"
799 /// ```
800 /// The right FILE with no position — which is exactly the shape of the
801 /// bug: the index survived the lift and every span did not.
802 #[test]
803 fn a_raise_inside_an_imported_package_names_that_package() {
804 let err = run_named("entry.b", "use(\"kotae\")\nuse(\"bakuhatsu\")\n");
805 assert_eq!(
806 err.to_string(),
807 "runtime error: bakuhatsu.b:11:3: unbound symbol `kore_wa_sonzai_shinai`"
808 );
809 }
810
811 /// Anti-vacuity for the fixture itself: the position asserted above is a
812 /// FACT ABOUT `bakuhatsu.b`, checked against the source text rather than
813 /// against the thing that produced it.
814 ///
815 /// Without this, `11:3` is just a number that happened to come out of the
816 /// code under test, and a change that moved every reported line by one
817 /// would move this assertion with it.
818 #[test]
819 fn line_11_column_3_of_the_fixture_is_the_failing_call() {
820 let line = BAKUHATSU.lines().nth(10).expect("line 11 exists");
821 assert_eq!(line, " kore_wa_sonzai_shinai()");
822 assert_eq!(
823 &line[2..],
824 "kore_wa_sonzai_shinai()",
825 "column 3 (1-indexed) is where the call starts"
826 );
827 // And the other two files cannot reach that far, which is what makes a
828 // mis-attribution loud instead of plausible.
829 let offset = BAKUHATSU.find("kore_wa_sonzai_shinai").expect("in fixture");
830 assert!(
831 offset > KOTAE.len(),
832 "kotae.b could answer for byte {offset}"
833 );
834 assert!(
835 offset > "use(\"kotae\")\nuse(\"bakuhatsu\")\n".len(),
836 "the entry file could answer for byte {offset}"
837 );
838 }
839
840 /// **The `FileId(0)` path: a raise in the ENTRY file reports the entry
841 /// file.** The single-file case, which is every program that imports
842 /// nothing — and the one where the index and the span cannot disagree.
843 ///
844 /// **Red run** (2026-08-12), `eval_program` +
845 /// `.map_err(|e| RunError::Eval(e.to_string()))` restored:
846 /// ```text
847 /// left: "runtime error: unbound symbol: nani_mo_nai at 17..28"
848 /// right: "runtime error: honmono.b:5:1: unbound symbol `nani_mo_nai`"
849 /// ```
850 ///
851 /// **Second red run**, `lower_to_spanned` reinstated after erasure — the
852 /// one that isolates the SPAN half from the index half, since a
853 /// single-file program cannot get its file wrong:
854 /// ```text
855 /// left: "runtime error: honmono.b: unbound symbol `nani_mo_nai`"
856 /// right: "runtime error: honmono.b:5:1: unbound symbol `nani_mo_nai`"
857 /// ```
858 #[test]
859 fn a_raise_in_the_entry_file_names_the_entry_file() {
860 let err = run_named(
861 "honmono.b",
862 "def f()\n 1\nend\n\n# waive B0001: a raise at runtime\nnani_mo_nai()\n",
863 );
864 assert_eq!(
865 err.to_string(),
866 "runtime error: honmono.b:6:1: unbound symbol `nani_mo_nai`"
867 );
868 }
869
870 /// A raise from a form that came through the SURFACE-level erasure still
871 /// reports a real position — the annotated path, where erasure rewrites
872 /// the node rather than passing it through.
873 ///
874 /// Separate from the two above because the erasure rewrite is the only
875 /// place a node is built rather than kept, and a synthetic span there
876 /// would be invisible to a fixture whose failing form is untouched.
877 ///
878 /// **Red run** (2026-08-12), `lower_to_spanned` reinstated after erasure:
879 /// ```text
880 /// left: "runtime error: chuu.b: unbound symbol `mada_nai`"
881 /// right: "runtime error: chuu.b:2:3: unbound symbol `mada_nai`"
882 /// ```
883 #[test]
884 fn a_raise_inside_an_annotated_def_still_names_its_line() {
885 let err = run_named(
886 "chuu.b",
887 "# waive B0001: a raise at runtime\ndef f(a: Int) -> Int\n mada_nai(a)\nend\n\nf(1)\n",
888 );
889 assert_eq!(
890 err.to_string(),
891 "runtime error: chuu.b:3:3: unbound symbol `mada_nai`"
892 );
893 }
894
895 /// **The stated limit, pinned rather than left to be discovered.**
896 ///
897 /// A top-level form in the entry file calls a function defined in an
898 /// imported one, and the raise happens inside the callee. The index names
899 /// the executing form (the entry's), the span names the callee's bytes,
900 /// and the two disagree about the file. `locate`'s in-range guard is what
901 /// keeps that from rendering as a precise-looking `entry:line:col`: the
902 /// offset is not a range in the entry file, so no position is printed.
903 ///
904 /// This test asserts the CURRENT behaviour, including the part that is
905 /// wrong — the path is the caller's. It is here so the next author reads
906 /// the limit off a green suite instead of off a bug report. Closing it
907 /// needs per-frame file identity at the evaluator; see `RunError::Eval`.
908 ///
909 /// **Red run** (2026-08-12), the `span.end <= file.text.len()` guard
910 /// removed from `uses::ResolvedProgram::locate` — and it is the ONLY test
911 /// in the crate that moves, which is the same run's evidence that the
912 /// guard is a no-op on every check-time diagnostic:
913 /// ```text
914 /// left: "runtime error: yobidashi.b:1:14: unbound symbol `kore_wa_sonzai_shinai`"
915 /// right: "runtime error: yobidashi.b: unbound symbol `kore_wa_sonzai_shinai`"
916 /// ```
917 /// `1:14` lands in the middle of `use("bakuhatsu2")` — the callee's start
918 /// offset happens to be in range for the caller's file even though its end
919 /// is not, so a wrong file gets a precise number pointing at innocent
920 /// code. Exactly the failure this repo's file-identity work exists to
921 /// refuse, which is why the guard tests BOTH ends.
922 ///
923 /// **Re-run 2026-09-29**, after the fixtures gained their waiver lines:
924 /// the guard's END check replaced by a start check (`span.start <= len`),
925 /// with the caller padded so the callee's start (byte 47) is in range and
926 /// its end (byte 70) is not:
927 /// ```text
928 /// left: "runtime error: yobidashi.b:3:1: unbound symbol `kore_wa_sonzai_shinai`"
929 /// right: "runtime error: yobidashi.b: unbound symbol `kore_wa_sonzai_shinai`"
930 /// ```
931 #[test]
932 fn a_raise_in_a_callee_from_another_file_reports_no_position_rather_than_a_wrong_one() {
933 // The comment is padding, and load-bearing: `bakuhatsu2.b`'s failing
934 // call starts at byte 47 (after its waiver line) and ends at 70, and
935 // this file is 54 bytes, so the start is in range here and the end is
936 // not — the half-in-range case the guard's END check exists for.
937 let err = run_named(
938 "yobidashi.b",
939 "use(\"bakuhatsu2\")\n# pad so byte 47 is in range\nyobu()\n",
940 );
941 assert_eq!(
942 err.to_string(),
943 "runtime error: yobidashi.b: unbound symbol `kore_wa_sonzai_shinai`",
944 "the caller's file is named (the stated limit) but NOT with a \
945 position it cannot justify"
946 );
947 }
948}
949
950#[cfg(test)]
951mod tests {
952 use super::*;
953
954 fn int(src: &str) -> i64 {
955 match run(src).unwrap_or_else(|e| panic!("{src:?}: {e}")).value {
956 Value::Int(v) => v,
957 other => panic!("{src:?} produced {other:?}"),
958 }
959 }
960
961 /// **The sliding scale, as one assertion.** Annotating changes the
962 /// analysis and nothing else.
963 #[test]
964 fn annotating_buys_analysis_and_changes_nothing_else() {
965 let plain = run("def add(a, b)\n a + b\nend\nadd(2, 3)").expect("plain");
966 let typed = run("def add(a: Int, b: Int) -> Int\n a + b\nend\nadd(2, 3)").expect("typed");
967
968 assert!(matches!(plain.value, Value::Int(5)));
969 assert!(
970 matches!(typed.value, Value::Int(5)),
971 "the annotated program must compute the same answer"
972 );
973 assert_eq!(plain.visited, 0, "no annotations means no analysis");
974 assert!(
975 typed.visited > 0,
976 "an annotation must actually buy analysis, not just decorate"
977 );
978 assert_eq!(plain.typed_decls, 0);
979 assert_eq!(typed.typed_decls, 1);
980 }
981
982 /// **Checking happens before erasure.** This is the test that catches the
983 /// reordering: a program with a declared-type violation must be rejected,
984 /// and it can only be rejected while the annotations still exist.
985 #[test]
986 fn a_type_error_is_reported_and_the_program_does_not_run() {
987 let err = run("def add(a: Int, b: Int) -> Str\n a + b\nend\nadd(1, 2)")
988 .expect_err("a declared Str return from an Int body must be rejected");
989 assert!(
990 matches!(err, RunError::Types(ref d) if !d.is_empty()),
991 "expected type diagnostics, got {err}"
992 );
993 }
994
995 /// And the untyped version of the same program runs, so the rejection
996 /// above is the annotation's doing rather than a parse failure.
997 #[test]
998 fn the_same_program_without_annotations_runs() {
999 assert_eq!(int("def add(a, b)\n a + b\nend\nadd(1, 2)"), 3);
1000 }
1001
1002 #[test]
1003 fn a_parse_error_is_reported_as_one() {
1004 assert!(matches!(run("def (").unwrap_err(), RunError::Parse(_)));
1005 }
1006
1007 /// Every stage reports in its own vocabulary, so a failure names which
1008 /// stage failed rather than surfacing as a generic error.
1009 #[test]
1010 fn a_runtime_error_is_reported_as_one() {
1011 let err = run("throw(error(\"boom\"))").expect_err("a raise");
1012 assert!(matches!(err, RunError::Eval(_)), "got {err}");
1013 }
1014
1015 /// Stdlib and primitives are both reachable through the pipeline — the
1016 /// gap that made `6 % 3` fail.
1017 #[test]
1018 fn the_pipeline_reaches_both_runtime_layers() {
1019 assert_eq!(int("6 % 3"), 0);
1020 assert_eq!(int("7 % 3"), 1);
1021 assert_eq!(int("2 + 3 * 4"), 14);
1022 }
1023
1024 /// **The deleted hop was a no-op on everything blue emits — so removing it
1025 /// is a swap, not a behaviour change.**
1026 ///
1027 /// The old lowering printed the erased tree and read it back through
1028 /// `tatara_lisp::read_spanned`. This walks a corpus and asserts the two
1029 /// paths land on the same tree, which is the equivalence the swap rests on.
1030 /// It is stated as a *measurement over this corpus*, not as a theorem:
1031 /// the round trip is not identity in general (that is precisely why it had
1032 /// to go), it merely happened to be identity for the bytes blue emits.
1033 #[test]
1034 fn the_deleted_round_trip_agreed_with_the_direct_lowering() {
1035 let corpus = [
1036 "def add(a, b)\n a + b\nend\nadd(2, 3)",
1037 "def fact(n)\n if n < 2\n 1\n else\n n * fact(n - 1)\n end\nend\nfact(5)",
1038 "def f(a, b)\n c = a + b\n c * 2\nend\nf(1, 2)",
1039 "defmacro sq(e)\n quote\n unquote(e) * unquote(e)\n end\nend\nsq(2 + 3)",
1040 "\"a string with spaces, a ( and a )\"",
1041 "def g(a: Int) -> Int\n a + 1\nend\ng(1)",
1042 "6 % 3",
1043 "1.5 + 2.25",
1044 ];
1045 for src in corpus {
1046 // Projected to `Sexp` because that is what the deleted hop
1047 // operated on. Erasure itself no longer goes near it.
1048 let erased = crate::to_sexps(&erase_types(&parse_tree(src).expect("parse")));
1049
1050 let direct: Vec<Sexp> = crate::lower_to_spanned(&erased)
1051 .iter()
1052 .map(tatara_lisp::Spanned::to_sexp)
1053 .collect();
1054 assert_eq!(direct, erased, "the direct lowering must be the identity");
1055
1056 let text = erased
1057 .iter()
1058 .map(ToString::to_string)
1059 .collect::<Vec<_>>()
1060 .join("\n");
1061 let round_tripped: Vec<Sexp> = tatara_lisp::read_spanned(&text)
1062 .unwrap_or_else(|e| panic!("{src:?}: the old path could not read back: {e:?}"))
1063 .iter()
1064 .map(tatara_lisp::Spanned::to_sexp)
1065 .collect();
1066 assert_eq!(
1067 round_tripped, erased,
1068 "{src:?}: the old print-and-reparse path changed the tree"
1069 );
1070 }
1071 }
1072
1073 /// Anti-vacuity for the test above: the round trip really is *not* the
1074 /// identity in general, so agreeing on the corpus was a property of what
1075 /// blue happens to emit rather than a property of the reader.
1076 ///
1077 /// **`Atom::Symbol`'s `Display` writes the name raw, with no escaping.**
1078 /// `Atom::Str` escapes and its docs explain at length why; the symbol arm
1079 /// is `f.write_str(s)`. So print-then-read is not inverse over the symbol
1080 /// domain, and the failure is *silent*: a symbol containing a space prints
1081 /// as two tokens, reads back as two symbols, and the result is a perfectly
1082 /// well-formed tree with a different meaning. No error, nothing to catch.
1083 ///
1084 /// Measured 2026-08-02 across the separators: `a b` and `x'y` come back
1085 /// `Ok` with a different tree; `x)y`, `x"y` and `x;y` come back `Err`;
1086 /// `x{y` and `x[y` DO round-trip at this level — those two are one symbol
1087 /// in and one symbol out, so the brace-fusion reported in tatara *source*
1088 /// is not what bites a printed tree. The silent pair is what makes this a
1089 /// miscompile class rather than a noisy one.
1090 #[test]
1091 fn the_round_trip_is_not_the_identity_in_general() {
1092 let tree = Sexp::List(vec![
1093 Sexp::Atom(tatara_lisp::Atom::Symbol("f".into())),
1094 Sexp::Atom(tatara_lisp::Atom::Symbol("a b".into())),
1095 ]);
1096 let text = tree.to_string();
1097 let back: Vec<Sexp> = tatara_lisp::read_spanned(&text)
1098 .expect("it reads back cleanly — that IS the problem")
1099 .iter()
1100 .map(tatara_lisp::Spanned::to_sexp)
1101 .collect();
1102 assert_ne!(
1103 back,
1104 vec![tree.clone()],
1105 "if print-then-read became inverse over symbols, the class would be \
1106 closed upstream and this test should be deleted rather than relaxed"
1107 );
1108 // …and the direct lowering is unaffected by any of it.
1109 let direct: Vec<Sexp> = crate::lower_to_spanned(std::slice::from_ref(&tree))
1110 .iter()
1111 .map(tatara_lisp::Spanned::to_sexp)
1112 .collect();
1113 assert_eq!(direct, vec![tree]);
1114 }
1115}
1116
1117#[cfg(test)]
1118mod macro_tests {
1119 use super::*;
1120
1121 fn int(src: &str) -> i64 {
1122 match run(src).unwrap_or_else(|e| panic!("{src:?}: {e}")).value {
1123 Value::Int(v) => v,
1124 other => panic!("{src:?} produced {other:?}"),
1125 }
1126 }
1127
1128 /// **A blue macro expands and runs.** Tenet 2's surface, end to end.
1129 #[test]
1130 fn a_macro_expands_and_runs() {
1131 assert_eq!(
1132 int("defmacro double(x)\n quote\n unquote(x) + unquote(x)\n end\nend\ndouble(21)"),
1133 42
1134 );
1135 }
1136
1137 /// A macro receives *source forms*, not values — so it can duplicate its
1138 /// argument, which a function cannot do without re-evaluating it.
1139 #[test]
1140 fn a_macro_operates_on_syntax_not_values() {
1141 assert_eq!(
1142 int("defmacro sq(e)\n quote\n unquote(e) * unquote(e)\n end\nend\nsq(2 + 3)"),
1143 25,
1144 "the argument form `2 + 3` must be substituted twice"
1145 );
1146 }
1147
1148 /// **A runaway macro is a typed error, not a dead compiler.** This is the
1149 /// property that makes the metaprogramming surface safe to hand to a user.
1150 ///
1151 /// The assertion was `contains("expansion limit")` and now reads
1152 /// `contains("expansion")`, because the pipeline renders `short_message`
1153 /// rather than `Display`: upstream words the same fact as "exceeded 256
1154 /// expansion steps" instead of "exceeded the expansion limit of 256
1155 /// rewrites". The PROPERTY is unchanged and still asserted — the macro is
1156 /// named, and the failure is attributed to expansion rather than to
1157 /// evaluation. **This reword was the whole measured blast radius of that
1158 /// switch**, one test in the workspace.
1159 ///
1160 /// The number is deliberately NOT pinned. It is upstream's constant, this
1161 /// test owns none of it, and matching it would turn an upstream bump into
1162 /// a red run here that proves nothing about blue.
1163 ///
1164 /// The third clause is new capability rather than repair: the message now
1165 /// carries `<anonymous>:6:1`, so a runaway macro says WHERE it ran away.
1166 #[test]
1167 fn a_runaway_macro_fails_the_compilation_rather_than_the_process() {
1168 let err =
1169 run("defmacro forever(x)\n quote\n forever(unquote(x))\n end\nend\nforever(1)")
1170 .expect_err("a self-referential macro must be rejected");
1171 let msg = err.to_string();
1172 assert!(
1173 msg.contains("forever") && msg.contains("expansion"),
1174 "the error must name the macro and the limit it hit: {msg}"
1175 );
1176 assert!(
1177 msg.contains("<anonymous>:6:1"),
1178 "and must place the call that ran away — line 6 is `forever(1)`: {msg}"
1179 );
1180 }
1181}
1182
1183#[cfg(test)]
1184mod input_tests {
1185 use super::*;
1186 use crate::inputs::{Declaration, Inputs};
1187
1188 /// A schema a macro will generate code from.
1189 const SCHEMA: &[u8] = b"3";
1190
1191 fn with_schema(src: &str) -> Result<Run, RunError> {
1192 let hash = Inputs::hash_of(SCHEMA);
1193 let mut inputs = Inputs::new();
1194 inputs
1195 .bind(
1196 &Declaration {
1197 name: "schema".to_string(),
1198 hash,
1199 },
1200 SCHEMA.to_vec(),
1201 )
1202 .expect("bind");
1203 run_with_inputs(src, inputs)
1204 }
1205
1206 fn decl_line() -> String {
1207 let mut s = String::from("definput(\"schema\", \"");
1208 s.push_str(&Inputs::hash_of(SCHEMA));
1209 s.push_str("\")\n");
1210 s
1211 }
1212
1213 /// **A macro reads a declared build input.** This is §VI OPEN #6 closed —
1214 /// the spec names it as gating blue's whole "stronger than Ruby's
1215 /// metaprogramming" claim, because a macro that cannot read a schema cannot
1216 /// generate code from one.
1217 #[test]
1218 fn a_macro_can_read_a_declared_build_input() {
1219 let src = decl_line() + "input(\"schema\")";
1220 let out = with_schema(&src).expect("run");
1221 assert!(
1222 matches!(out.value, Value::Str(ref s) if &**s == "3"),
1223 "got {:?}",
1224 out.value
1225 );
1226 }
1227
1228 /// **An undeclared input is an error, not a file read and not nil.**
1229 /// Returning nil is how a macro generates an empty table and nobody notices
1230 /// until runtime.
1231 #[test]
1232 fn an_undeclared_input_is_an_error() {
1233 let err = with_schema("input(\"not_declared\")").expect_err("must fail");
1234 let msg = err.to_string();
1235 assert!(msg.contains("not_declared"), "must name it: {msg}");
1236 assert!(msg.contains("definput"), "and say how to declare it: {msg}");
1237 }
1238
1239 /// **There is no path-based read at all.** The capability is the absence of
1240 /// the primitive, not a check inside one — so this is an unbound symbol.
1241 ///
1242 /// Holds for the DEFAULT surface — the one every embedder gets. The `sys`
1243 /// cargo feature (CLI only) is the one declared exception: it is the
1244 /// operator's own trusted host surface, and is asserted in
1245 /// `sys_read_file_is_the_trusted_cli_only_exception` below.
1246 #[cfg(not(feature = "sys"))]
1247 #[test]
1248 fn there_is_no_ambient_file_read() {
1249 for attempt in [
1250 "read_file(\"/etc/passwd\")",
1251 "File(\"/etc/passwd\")",
1252 "slurp(\"/etc/passwd\")",
1253 "open(\"/etc/passwd\")",
1254 ] {
1255 let err = with_schema(attempt).expect_err("must not resolve");
1256 assert!(
1257 err.to_string().contains("unbound"),
1258 "{attempt} must be UNBOUND — a capability removed by absence, \
1259 not guarded by a check: {err}"
1260 );
1261 }
1262 }
1263
1264 /// With the `sys` feature compiled in, `read_file` IS bound — that is the
1265 /// point of the feature. The doctrine does not move: this is the operator's
1266 /// own machine (the CLI), not an embedder's sandbox. Pin the boundary so a
1267 /// future default-build change is heard, and assert that `input()` still
1268 /// works beside it.
1269 #[cfg(feature = "sys")]
1270 #[test]
1271 fn sys_read_file_is_the_trusted_cli_only_exception() {
1272 let err = with_schema("definitely_not_a_primitive(\"x\")").expect_err("must not resolve");
1273 assert!(err.to_string().contains("unbound"), "{err}");
1274 assert!(
1275 with_schema("read_file(\"/etc/passwd\")").is_ok(),
1276 "with `sys` on, read_file is the trusted CLI surface"
1277 );
1278 let out = with_schema("input(\"schema\")").expect("run");
1279 assert!(
1280 matches!(out.value, Value::Str(ref s) if &**s == "3"),
1281 "input() still binds beside the sys surface: {:?}",
1282 out.value
1283 );
1284 }
1285
1286 /// Anti-vacuity: with no inputs supplied at all, even a declared name fails
1287 /// — so the success above is the binding's doing.
1288 #[test]
1289 fn a_declared_input_with_no_bytes_supplied_fails() {
1290 let src = decl_line() + "input(\"schema\")";
1291 assert!(run(&src).is_err(), "no bytes were supplied");
1292 }
1293}
1294
1295#[cfg(test)]
1296mod tier2_tests {
1297 use super::*;
1298 use crate::inputs::{Declaration, Inputs};
1299
1300 /// **The Tier-2 conversion §V.6.3 said was gated: a macro that emits real
1301 /// declarations FROM A SCHEMA.**
1302 ///
1303 /// `theory/BLUE.md` §VI OPEN #6 states the blocker plainly — "tenet 2
1304 /// installs a `NoLoader`, so a macro cannot read a schema — which gates
1305 /// every Tier-2 conversion in §V.6 and therefore blue's whole 'stronger than
1306 /// Ruby's metaprogramming' claim."
1307 ///
1308 /// Here the schema supplies a *value the generated code depends on*, read at
1309 /// expansion time. Ruby and Elixir can both do this — with the whole
1310 /// filesystem open. blue does it through a name bound to a content hash.
1311 #[test]
1312 fn a_macro_generates_code_from_a_schema() {
1313 let schema = b"7";
1314 let mut inputs = Inputs::new();
1315 inputs
1316 .bind(
1317 &Declaration {
1318 name: "arity".to_string(),
1319 hash: Inputs::hash_of(schema),
1320 },
1321 schema.to_vec(),
1322 )
1323 .expect("bind");
1324
1325 // The macro reads the input at EXPANSION time and splices the value it
1326 // found into the code it emits.
1327 let mut src = String::from("definput(\"arity\", \"");
1328 src.push_str(&Inputs::hash_of(schema));
1329 src.push_str("\")\n");
1330 src.push_str(
1331 "defmacro from_schema()\n quote\n unquote(to_int(input(\"arity\")))\n end\nend\n\
1332 from_schema() * 6",
1333 );
1334
1335 let out = run_with_inputs(&src, inputs).expect("run");
1336 assert!(
1337 matches!(out.value, Value::Int(42)),
1338 "the schema's 7 must reach the generated code: got {:?}",
1339 out.value
1340 );
1341 }
1342}