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
224impl Prepared {
225 /// The entry file's namespace.
226 pub(crate) fn entry_namespace(&self) -> Namespace {
227 let first = (0..self.program.forms().len())
228 .find(|i| self.program.owner_of(*i) == Some(crate::uses::ResolvedProgram::ENTRY));
229 match first {
230 Some(i) => namespace_of(&self.program, i),
231 None => match self
232 .program
233 .file(crate::uses::ResolvedProgram::ENTRY)
234 .and_then(|f| f.package.clone())
235 {
236 Some(p) => Namespace::Bidama(p),
237 None => Namespace::File(String::new()),
238 },
239 }
240 }
241}
242
243/// Parse, resolve, check and erase, in that order.
244///
245/// `builtins` is the name table of the interpreter that will evaluate the
246/// result ([`builtin_names`]); the check stage resolves the program's names
247/// against it.
248pub(crate) fn prepare(
249 entry: Entry<'_>,
250 loader: &dyn crate::uses::Loader,
251 surface: Option<&blue_lang_syntax::yakugo::Yakugo>,
252 builtins: &NameTable,
253) -> Result<Prepared, RunError> {
254 let mut program = parse_and_resolve(entry, loader, surface)?;
255
256 // `test` blocks are declarations for the harness, not code to run.
257 //
258 // Dropped here rather than in `resolve_uses`, because `blue test` calls
259 // the resolver and then NEEDS the entry file's blocks — so the two
260 // callers want different things and the split has to live at this level.
261 //
262 // Without this, `blue run` on a file containing its own tests fails with
263 // `unbound symbol: deftest`: every package in the bidama distribution
264 // carries tests, so every one of them was unrunnable.
265 //
266 // Through `retain`, which drops each form's owner with it. A plain filter
267 // over the forms alone would slide every later form onto the wrong file.
268 program.retain(|f| !crate::uses::is_test_form(f));
269
270 // CHECK, on the annotated tree — the only tree that has annotations.
271 //
272 // **On the REAL spanned tree, including every imported package's.** This
273 // was the one caller that checked a spanless lift, because `resolve_uses`
274 // flattened the entry file and its imports into one list and `Span` is a
275 // byte range with no file identity — so a real span here would have
276 // reported an imported package's error at that offset in the ENTRY file, a
277 // precise-looking answer pointing at unrelated code.
278 //
279 // The fix is not a wider `Span` (that type is upstream, and its own docs
280 // put file identity on the caller: spans "are meaningful only relative to
281 // the string that produced them, which the caller is responsible for
282 // holding onto"). blue holds onto it BESIDE the span, per top-level form —
283 // see `uses::ResolvedProgram`.
284 let (outcome, names) = check_stage(&program, builtins, false);
285 if !outcome.ok() {
286 return Err(RunError::Types(
287 outcome
288 .errors()
289 // `file:line:col: error[CODE]: message`, resolved against the
290 // file the form actually came from, then its help line.
291 .map(|d| render(&program, d))
292 .collect(),
293 ));
294 }
295
296 // ERASE, so the interpreter never sees a type — **on the spanned tree,
297 // and back out as one.**
298 //
299 // This used to be `erase_types(&program.sexps())` followed by a
300 // `lower_to_spanned` that stamped `Span::synthetic()` over every node, and
301 // the comment here said carrying real positions through was "a larger
302 // piece and is NOT built". It was not larger: erasure only ever DELETES
303 // nodes — the single node it invents is the `define` replacing
304 // `define-typed` — so there was never anything for a synthetic span to
305 // stand in for. See `crate::erase`.
306 //
307 // No lowering step follows. The tree the evaluator receives IS the tree the
308 // parser built, minus annotations, with the author's byte offsets intact.
309 let erased = erase_types(&lower(&program, &names));
310
311 Ok(Prepared {
312 program,
313 erased,
314 visited: outcome.stats.visited,
315 typed_decls: outcome.stats.typed_decls,
316 seams: outcome.seams.len(),
317 })
318}
319
320/// Parse the entry (in `surface`, if one is given) and splice in its imports.
321pub(crate) fn parse_and_resolve(
322 entry: Entry<'_>,
323 loader: &dyn crate::uses::Loader,
324 surface: Option<&blue_lang_syntax::yakugo::Yakugo>,
325) -> Result<crate::uses::ResolvedProgram, RunError> {
326 let forms = match surface {
327 Some(pack) => blue_lang_syntax::parse_program_tree_in(entry.text, pack)
328 .map_err(|e| RunError::Parse(e.to_string()))?,
329 None => loader
330 .parse(entry.text)
331 .map_err(|e| RunError::Parse(e.to_string()))?,
332 };
333
334 // RESOLVE imports first, so everything below sees ONE program.
335 //
336 // Before the check on purpose: imported code is type-checked at the point
337 // its consumer imports it, rather than at whatever later moment its code
338 // first runs. A package that does not typecheck should break its importer's
339 // build, not their production run.
340 //
341 // One program, but not one FILE: the result records which file each
342 // top-level form came from, which is what lets a diagnostic below name a
343 // place instead of only a problem.
344 crate::uses::resolve_uses(forms, entry, loader).map_err(RunError::Import)
345}
346
347/// **The check stage**: every rule in `blue_lang_check::RULES`, over a
348/// resolved program, with waivers applied.
349///
350/// One function, called by every door — `run`, the hosted loader, `blue test`
351/// and `blue check` — so a rule added to the registry is enforced by all of
352/// them at once. That is what makes an architecture rule a pipeline error
353/// rather than an optional report: there is no door that skips it.
354///
355/// Warnings (unused bindings, unused waivers) are reported for the ENTRY
356/// file only; an imported package's warnings belong to its author. Errors
357/// are reported for every file, because an imported package with one is
358/// broken for its importer.
359pub(crate) fn check_stage(
360 program: &crate::uses::ResolvedProgram,
361 builtins: &NameTable,
362 with_tests: bool,
363) -> (blue_lang_check::Outcome, NameTable) {
364 use crate::uses::ResolvedProgram;
365 let forms = program.forms();
366 let is_entry = |i: usize| program.owner_of(i) == Some(ResolvedProgram::ENTRY);
367
368 // Rules B0003–B0005: the typing ladder.
369 let mut outcome = blue_lang_check::check_program(forms);
370
371 // Rules B0001–B0002: names. The program's own scopes come first (the
372 // entry file, then each bidama in import order), then the interpreter's.
373 let table = program_names(program, builtins);
374 let whole = |i: usize| with_tests && is_entry(i);
375 let (names, resolved) = blue_lang_check::names::check_names_whole(
376 forms,
377 &table,
378 &|i| namespace_of(program, i),
379 &is_entry,
380 &whole,
381 );
382 outcome.diagnostics.extend(names);
383 outcome.stats.names_resolved = resolved;
384
385 // Waivers, per file: B0007 for a malformed one, B0008 for one that
386 // suppresses nothing.
387 let mut waivers = Vec::new();
388 for file in program.files() {
389 let spans: Vec<(usize, tatara_lisp::Span)> = forms
390 .iter()
391 .enumerate()
392 .filter(|(i, _)| program.owner_of(*i) == Some(file.id))
393 .map(|(i, f)| (i, f.span))
394 .collect();
395 let (found, malformed) = blue_lang_check::waiver::collect(&file.text, &spans);
396 waivers.extend(found);
397 outcome.diagnostics.extend(malformed);
398 }
399 outcome.waived = blue_lang_check::waiver::apply(&mut outcome.diagnostics, waivers, &is_entry);
400 // A rule whose census has not reached zero is computed, and counted, but
401 // not enforced: its findings move to `census` (see `RULES`' `ratchet`).
402 let (enforced, census): (Vec<_>, Vec<_>) = std::mem::take(&mut outcome.diagnostics)
403 .into_iter()
404 .partition(|d| d.code.rule().active());
405 outcome.diagnostics = enforced;
406 outcome.census = census;
407 outcome
408 .diagnostics
409 .sort_by_key(|d| (d.top_level, d.span.start, d.code));
410 (outcome, table)
411}
412
413/// The whole name table the check stage resolves against: the program's
414/// own scopes (each file and bidama, by namespace) followed by `builtins`.
415///
416/// **A top-level call to a builtin macro can define names**: `defflow(slug,
417/// trim, downcase)` expands to `(define slug …)`, and nothing in the source
418/// spells `define`. Such a call is expanded here, on a hostless fork, and what
419/// its expansion defines is bound in the calling file's namespace. Only
420/// BUILTIN macros are expanded: their bodies are the runtime's own
421/// templates. A program's own `defmacro` is not run at check time — checking a
422/// file (and an editor checking on every keystroke) must not execute the code
423/// it checks — so names a program macro generates are not seen; none of the
424/// corpus's macros generates one (measured 2026-09-29).
425#[must_use]
426pub fn program_names(program: &crate::uses::ResolvedProgram, builtins: &NameTable) -> NameTable {
427 use blue_lang_check::Binding;
428 let mut table = NameTable::new();
429 table.add_program(program.forms(), |i| namespace_of(program, i));
430 let builtin_macro = |head: &str| {
431 builtins
432 .scopes()
433 .iter()
434 .any(|s| s.namespace == Namespace::Macro && s.get(head).is_some())
435 };
436 let mut expander: Option<tatara_lisp_eval::Interpreter<()>> = None;
437 for (i, form) in program.forms().iter().enumerate() {
438 let Some(head) = form
439 .as_list()
440 .and_then(|items| items.first())
441 .and_then(tatara_lisp::Spanned::as_symbol)
442 else {
443 continue;
444 };
445 if !builtin_macro(head) {
446 continue;
447 }
448 let interp = expander.get_or_insert_with(crate::interpreter_hostless);
449 // A failed expansion defines nothing here; the evaluator will report
450 // it, with its position, when the form runs.
451 let Ok(expanded) = interp.fully_expand(form, &mut ()) else {
452 continue;
453 };
454 for (name, span, kind) in blue_lang_check::names::definitions_of(&expanded) {
455 table.define(
456 namespace_of(program, i),
457 Binding {
458 name,
459 kind,
460 span: Some(span),
461 top_level: Some(i),
462 },
463 );
464 }
465 }
466 for scope in builtins.scopes() {
467 table.push(scope.clone());
468 }
469 let form_file: Vec<usize> = (0..program.forms().len())
470 .map(|i| program.owner_of(i).map_or(usize::MAX, |f| f.index()))
471 .collect();
472 let mut imports: std::collections::BTreeMap<usize, blue_lang_check::names::FileImports> =
473 std::collections::BTreeMap::new();
474 for (file, import) in program.imports() {
475 let entry = imports.entry(file.index()).or_default();
476 entry.add(&import.package, import.names.iter().map(|(n, _)| n.clone()));
477 let at = import.span.start;
478 entry.use_at = Some(entry.use_at.map_or(at, |a| a.min(at)));
479 }
480 // A FACADE — a bidama that defines nothing and `use`s others (zenbu) —
481 // exists so a consumer can depend on "everything": `use("zenbu")` makes
482 // every member's QUALIFIER reachable (`toukei::median`), never a bare
483 // name. Followed to a fixpoint, so a facade of facades works too.
484 let facade_uses =
485 |pkg: &str,
486 imports: &std::collections::BTreeMap<usize, blue_lang_check::names::FileImports>| {
487 let defines = table.bidama(pkg).is_some_and(|s| !s.is_empty());
488 if defines {
489 return std::collections::BTreeSet::new();
490 }
491 program
492 .files()
493 .iter()
494 .filter(|f| f.package.as_deref() == Some(pkg))
495 .filter_map(|f| imports.get(&f.id.index()))
496 .flat_map(|i| i.uses.iter().cloned())
497 .collect::<std::collections::BTreeSet<String>>()
498 };
499 loop {
500 let mut grew = false;
501 let files: Vec<usize> = imports.keys().copied().collect();
502 for f in files {
503 let used: Vec<String> = imports[&f].uses.iter().cloned().collect();
504 for p in used {
505 for member in facade_uses(&p, &imports) {
506 if let Some(i) = imports.get_mut(&f) {
507 if i.uses.insert(member.clone()) {
508 i.via.insert(member, p.clone());
509 grew = true;
510 }
511 }
512 }
513 }
514 }
515 if !grew {
516 break;
517 }
518 }
519 let mut pkg_uses: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
520 std::collections::BTreeMap::new();
521 for (file, import) in program.imports() {
522 if let Some(p) = program.file(*file).and_then(|f| f.package.clone()) {
523 pkg_uses
524 .entry(p)
525 .or_default()
526 .insert(import.package.clone());
527 }
528 }
529 table.attach_files(form_file, imports);
530 table.attach_package_uses(pkg_uses);
531 table.attach_needs(program.needs().clone());
532 // Where each file lives and which distribution each bidama ships in: a
533 // bridge reference (B0021) is an error inside the bidama's own
534 // distribution and a warning outside it.
535 let canonical = |p: &std::path::Path| {
536 std::fs::canonicalize(p)
537 .unwrap_or_else(|_| p.to_path_buf())
538 .display()
539 .to_string()
540 };
541 let mut file_paths = std::collections::BTreeMap::new();
542 let mut pkg_roots = std::collections::BTreeMap::new();
543 for f in program.files() {
544 if let Some(path) = &f.path {
545 file_paths.insert(f.id.index(), canonical(path));
546 if let (Some(pkg), Some(root)) =
547 (&f.package, path.parent().and_then(std::path::Path::parent))
548 {
549 pkg_roots
550 .entry(pkg.clone())
551 .or_insert_with(|| canonical(root));
552 }
553 }
554 }
555 table.attach_paths(file_paths, pkg_roots);
556 let versions = program.versions().clone();
557 table.apply_legacy(program.forms(), &|i| namespace_of(program, i), &|p| {
558 versions.get(p).cloned()
559 });
560 table
561}
562
563/// The forms the evaluator runs, from a checked program: every `use`
564/// declaration inert (`nil`, so each index still names its top-level form)
565/// and every name at the key it runs under — the RESOLVED tree under
566/// per-bidama namespaces (`blue_lang_check::names::Resolved::resolved_tree`).
567///
568/// A definition runs as `retsu/first` (a script's as `%root/f`), a
569/// reference to it as the same key, and a builtin as its bare name. Keys
570/// cannot collide across namespaces, so a bidama's `first` no longer
571/// replaces the builtin for anyone who did not import it, and an importer's
572/// `helper` no longer replaces a bidama's own: the runtime binds exactly what
573/// the check stage resolved.
574#[must_use]
575pub fn lower(
576 program: &crate::uses::ResolvedProgram,
577 names: &NameTable,
578) -> Vec<tatara_lisp::Spanned> {
579 let resolved = blue_lang_check::names::resolve_program(program.forms(), names, &|i| {
580 namespace_of(program, i)
581 });
582 resolved
583 .resolved_tree(program.forms(), blue_lang_check::names::Rule::Namespaced)
584 .into_iter()
585 .zip(program.forms())
586 .map(|(resolved, written)| {
587 if crate::uses::use_target(written).is_some()
588 || blue_lang_syntax::scope::legacy_target(written).is_some()
589 {
590 tatara_lisp::Spanned::new(written.span, tatara_lisp::SpannedForm::Nil)
591 } else {
592 resolved
593 }
594 })
595 .collect()
596}
597
598/// The namespace top-level form `i` of `program` defines into.
599#[must_use]
600pub fn namespace_of(program: &crate::uses::ResolvedProgram, i: usize) -> Namespace {
601 let file = program.owner_of(i).and_then(|id| program.file(id));
602 match file {
603 Some(f) => match &f.package {
604 Some(p) => Namespace::Bidama(p.clone()),
605 None => Namespace::File(
606 f.path
607 .as_ref()
608 .map_or_else(|| "<anonymous>".to_string(), |p| p.display().to_string()),
609 ),
610 },
611 None => Namespace::File("<unknown file>".to_string()),
612 }
613}
614
615/// Names only the test harness binds.
616///
617/// In scope for EVERY check, not only for test blocks. A bidama may carry a
618/// test helper — a plain `def` that asserts, called only from its `test`
619/// blocks (`heni`'s `hn_end_to_end` is one) — and every program importing that
620/// bidama would otherwise be refused for a function it never calls. The
621/// refusal would be scoped to the importer's whole program, not to the fault.
622/// The cost, stated: an `assert` outside any test that `blue run` actually
623/// reaches is caught at runtime (`blue-assert` is unbound there), not here.
624///
625/// `blue-lang-test` registers these on its own interpreter, and this crate
626/// cannot depend on it (it depends on this one), so the list lives beside the
627/// only name in it: the lowered `assert`, which `blue-lang-syntax` owns.
628pub const HARNESS_NAMES: &[&str] = &[blue_lang_syntax::LOWERED_ASSERT];
629
630/// The check stage's builtin scopes, read off the interpreter that will run
631/// the program: the test harness's names ([`HARNESS_NAMES`]), then its special
632/// forms, its macros, and every value it binds — the last three in the order
633/// the evaluator consults for a head.
634///
635/// Read from a live interpreter rather than a list, for the reason
636/// `Interpreter::resolve_head` gives: a list is a second copy of the truth and
637/// goes stale on the next installer that lands. An embedder's own
638/// primitives are in scope here because the embedder installs them first.
639#[must_use]
640pub fn builtin_names<H: 'static>(interp: &tatara_lisp_eval::Interpreter<H>) -> NameTable {
641 use blue_lang_check::{Binding, Scope, ScopeKind};
642 use tatara_lisp_eval::HeadBinding;
643 let mut special = Scope::new(Namespace::SpecialForm);
644 let mut macros = Scope::new(Namespace::Macro);
645 let mut values = Scope::new(Namespace::Builtin);
646 // `reserved_head_names` reads the ROOT frame only, so a name installed on
647 // a fork (the input primitives, on every `run`) is invisible to it; those
648 // are asked about by name instead, which `resolve_head` answers through
649 // every frame.
650 let mut names: Vec<std::sync::Arc<str>> = interp.reserved_head_names().into_iter().collect();
651 names.extend(
652 crate::inputs::INPUT_PRIMITIVES
653 .iter()
654 .filter(|n| interp.resolve_head(n).is_some())
655 .map(|n| std::sync::Arc::from(*n)),
656 );
657 for name in names {
658 let (scope, kind) = match interp.resolve_head(&name) {
659 Some(HeadBinding::SpecialForm) => (&mut special, ScopeKind::SpecialForm),
660 Some(HeadBinding::Macro) => (&mut macros, ScopeKind::Macro),
661 _ => (&mut values, ScopeKind::Value),
662 };
663 scope.bind(Binding {
664 name: name.to_string(),
665 kind,
666 span: None,
667 top_level: None,
668 });
669 }
670 let mut table = NameTable::new();
671 let mut harness = Scope::new(Namespace::Harness);
672 for n in HARNESS_NAMES {
673 harness.bind(Binding {
674 name: (*n).to_string(),
675 kind: ScopeKind::Value,
676 span: None,
677 top_level: None,
678 });
679 }
680 table.push(harness);
681 table.push(special);
682 table.push(macros);
683 table.push(values);
684 table
685}
686
687/// A diagnostic as a person reads it: `file:line:col: error[B0001]: message`,
688/// then an indented `help:` line when it has one.
689#[must_use]
690pub fn render(program: &crate::uses::ResolvedProgram, d: &blue_lang_check::Diagnostic) -> String {
691 let head = d.to_string();
692 let mut out = program.locate(d.top_level, d.span, &head).to_string();
693 if let Some(help) = &d.help {
694 out.push_str("\n help: ");
695 out.push_str(help);
696 }
697 out
698}
699
700/// What [`check_entry`] checks.
701#[derive(Clone, Copy, Debug, PartialEq, Eq)]
702pub enum Checking {
703 /// The program `blue run` would evaluate: test blocks dropped.
704 Program,
705 /// The program plus the entry file's test blocks, as `blue test` and
706 /// `blue check` see it.
707 WithTests,
708}
709
710/// A program through the check stage, with everything the stage found.
711pub struct Checked {
712 pub program: crate::uses::ResolvedProgram,
713 pub outcome: blue_lang_check::Outcome,
714 /// The name table the stage resolved against: every program scope, then
715 /// the builtins. What an editor completes from.
716 pub names: NameTable,
717}
718
719impl Checked {
720 /// The forms an evaluator runs: [`lower`]ed, then erased — the tree
721 /// `run` evaluates, for a door that brings its own evaluator (the VM).
722 #[must_use]
723 pub fn erased(&self) -> Vec<tatara_lisp::Spanned> {
724 erase_types(&lower(&self.program, &self.names))
725 }
726
727 /// What `blue test` hands the harness: the program [`lower`]ed, spans
728 /// projected away.
729 #[must_use]
730 pub fn evaluable(&self) -> Vec<tatara_lisp::Sexp> {
731 lower(&self.program, &self.names)
732 .iter()
733 .map(tatara_lisp::Spanned::to_sexp)
734 .collect()
735 }
736
737 /// Every non-local reference, resolved under both rules — today's flat
738 /// one and per-bidama namespaces — and the resolved trees built from them
739 /// (`blue ast --resolved`).
740 #[must_use]
741 pub fn resolve(&self) -> blue_lang_check::names::Resolved {
742 blue_lang_check::names::resolve_program(self.program.forms(), &self.names, &|i| {
743 namespace_of(&self.program, i)
744 })
745 }
746}
747
748/// Parse, resolve and CHECK, without running: the door for `blue check`,
749/// `blue test` and the language server.
750///
751/// Returns every diagnostic, errors and warnings alike, rather than failing on
752/// the first error: a reader fixing a file wants the whole list, and an agent
753/// repairing one wants it in one pass. Whether errors stop anything is the
754/// caller's decision — `blue test` refuses to run tests over a program with
755/// one, exactly as `run` refuses to evaluate it.
756///
757/// The name oracle is the interpreter `blue run` would build: hostless plus
758/// input primitives.
759///
760/// # Errors
761///
762/// A parse or import error, which leaves no program to check.
763pub fn check_entry(
764 entry: Entry<'_>,
765 loader: &dyn crate::uses::Loader,
766 surface: Option<&blue_lang_syntax::yakugo::Yakugo>,
767 checking: Checking,
768) -> Result<Checked, RunError> {
769 let mut program = parse_and_resolve(entry, loader, surface)?;
770 if checking == Checking::Program {
771 program.retain(|f| !crate::uses::is_test_form(f));
772 }
773 let mut interp = crate::interpreter_hostless();
774 crate::inputs::install_input_primitives(&mut interp, Inputs::new());
775 let builtins = builtin_names(&interp);
776 let (outcome, names) = check_stage(&program, &builtins, checking == Checking::WithTests);
777 Ok(Checked {
778 program,
779 outcome,
780 names,
781 })
782}
783
784/// A syntax error in `text` as a [`B0006`](blue_lang_check::Code::B0006)
785/// diagnostic, so a tool reading `--format json` gets a parse failure in the
786/// same shape as every other finding. `None` when `text` parses.
787#[must_use]
788pub fn syntax_diagnostic(text: &str) -> Option<blue_lang_check::Diagnostic> {
789 let e = blue_lang_syntax::parse_program_tree(text).err()?;
790 Some(
791 blue_lang_check::Diagnostic::new(blue_lang_check::Code::B0006, e.message, e.span)
792 .at_top_level(0),
793 )
794}
795
796/// A runtime message as the author wrote the names in it: a definition runs
797/// under its key (`retsu/first`, `%root/f`), and a message naming one in
798/// backticks names it `retsu::first`, or `f` for the author's own script.
799#[must_use]
800pub fn display_keys(message: &str) -> String {
801 let root = format!(
802 "{}{}",
803 blue_lang_check::names::ROOT_QUALIFIER,
804 blue_lang_syntax::QUALIFIER
805 );
806 let mut out = String::with_capacity(message.len());
807 let mut parts = message.split('`');
808 if let Some(first) = parts.next() {
809 out.push_str(first);
810 }
811 for (i, part) in parts.enumerate() {
812 out.push('`');
813 // Odd pieces (0-based here) are inside backticks.
814 if i % 2 == 0 {
815 if let Some(rest) = part.strip_prefix(&root) {
816 out.push_str(rest);
817 } else if let Some((pkg, name)) = blue_lang_syntax::qualified(part) {
818 out.push_str(&format!("{pkg}::{name}"));
819 } else {
820 out.push_str(part);
821 }
822 } else {
823 out.push_str(part);
824 }
825 }
826 out
827}
828
829/// Evaluate a prepared program's top-level forms into `interp`, with `host`.
830pub(crate) fn eval_prepared<H: 'static>(
831 interp: &mut tatara_lisp_eval::Interpreter<H>,
832 prepared: &Prepared,
833 host: &mut H,
834) -> Result<Value, RunError> {
835 let Prepared {
836 program, erased, ..
837 } = prepared;
838
839 // RUN, one top-level form at a time, **counting them**.
840 //
841 // This is literally the loop `Interpreter::eval_program` runs internally
842 // (tatara-lisp-eval `eval.rs`) — unrolled here for exactly one reason: the
843 // INDEX. `resolve_uses` flattens N files into one form list and a `Span` is
844 // a byte range with no file identity, so an offset alone is ambiguous
845 // across files — 66 means something in every one of them. The index is the
846 // join key back to `ResolvedProgram`'s file table, and `eval_program`
847 // consumes it internally and hands back only the error.
848 //
849 // The same key, the same renderer and the same file table the type errors
850 // above already use. A runtime error was the one diagnostic in this
851 // function still reporting a bare message.
852 let mut value = Value::Nil;
853 for (top_level, form) in erased.iter().enumerate() {
854 value = interp.eval_top_form(form, host).map_err(|e| {
855 // `span()` is `None` for the arms that genuinely have no position
856 // (`Reader`, `Halted`, `NotImplemented`). Synthetic is the honest
857 // stand-in — `locate` renders it as a file with no line rather
858 // than inventing one.
859 let at = e.span().unwrap_or_else(tatara_lisp::Span::synthetic);
860 // `short_message`, NOT `Display`. Upstream's `Display` ends every
861 // positioned arm with ` at {span}` — a raw byte range — and once
862 // blue prefixes a resolved `path:line:col` that suffix is the same
863 // fact told twice, the second time in a unit no reader can spend.
864 //
865 // Worse than redundant: a byte range is exactly the thing this
866 // whole file-identity apparatus exists to stop being reported on
867 // its own, because an offset means something different in every
868 // file. On the one case blue deliberately declines to place — a
869 // raise inside a callee from another file — `Display` would print
870 // the CALLEE's offsets beside the CALLER's path, re-creating the
871 // precise-looking wrong answer `locate`'s guard just refused.
872 // `short_message` is upstream's own "no source context" accessor,
873 // and blue supplies the context.
874 //
875 // Through `messages::describe`, which is `short_message` except
876 // where blue can say more: a wrong argument count names the
877 // function the author called, read off the call in this tree,
878 // instead of upstream's `<closure>` and a Rust `Debug` arity.
879 let message = display_keys(&crate::messages::describe(&e, erased));
880 RunError::Eval(program.locate(top_level, at, &message).to_string())
881 })?;
882 }
883 Ok(value)
884}
885
886/// **A runtime error names a place.** The gates for the last stage that
887/// reported a bare message.
888///
889/// Each fixture is sized so that resolving the failing span against ANY file
890/// but the right one lands somewhere else — a different path and a different
891/// line — so a green run here is evidence about the join and not about the
892/// renderer being called at all.
893///
894/// **Each raise is an unbound name, WAIVED.** Since the check stage resolves
895/// names (B0001), an unbound call no longer reaches the evaluator; these
896/// fixtures need exactly that runtime raise, so each carries
897/// `# waive B0001: …` above the definition holding it — the one escape hatch,
898/// used for what it is for. The waiver adds a line above each failing call,
899/// which is why the positions below are one line later than their red runs
900/// (recorded against the unwaived fixtures) show.
901#[cfg(test)]
902mod position_tests {
903 use super::*;
904 use crate::uses::{Entry, Loader};
905 use std::collections::BTreeMap;
906 use std::path::Path;
907
908 struct MemLoader(BTreeMap<&'static str, &'static str>);
909
910 impl Loader for MemLoader {
911 fn load(&self, name: &str) -> Result<Vec<(String, String)>, String> {
912 self.0
913 .get(name)
914 .map(|s| vec![(format!("{name}.b"), (*s).to_owned())])
915 .ok_or_else(|| format!("no bidama named \"{name}\""))
916 }
917 }
918
919 /// A package whose OWN top-level code raises, deep inside a file that is
920 /// deliberately taller than either of the other two.
921 ///
922 /// Byte 66 — where `kore_wa_sonzai_shinai` starts — is past the end of the
923 /// entry file (30 bytes) and past the end of `kotae.b` (21 bytes). So the
924 /// only file this span can honestly resolve against is this one, and the
925 /// other two now refuse to answer rather than walking off their ends.
926 const BAKUHATSU: &str = "\
927def tsukawanai_a()
928 1
929end
930
931def tsukawanai_b()
932 2
933end
934
935# waive B0001: the fixture needs a raise at runtime
936def bakuhatsu()
937 kore_wa_sonzai_shinai()
938end
939
940bakuhatsu()";
941
942 const KOTAE: &str = "def kotae()\n 42\nend";
943
944 /// The same failing call, but only ever reached by a CALLER in another
945 /// file — the shape that exercises `RunError::Eval`'s stated limit.
946 const BAKUHATSU2: &str =
947 "# waive B0001: a raise at runtime\ndef yobu()\n kore_wa_sonzai_shinai()\nend";
948
949 fn loader() -> MemLoader {
950 MemLoader(BTreeMap::from([
951 ("kotae", KOTAE),
952 ("bakuhatsu", BAKUHATSU),
953 ("bakuhatsu2", BAKUHATSU2),
954 ]))
955 }
956
957 fn run_named(path: &str, src: &str) -> RunError {
958 run_in_surface(
959 Entry {
960 path: Some(Path::new(path)),
961 text: src,
962 },
963 Inputs::new(),
964 &loader(),
965 None,
966 )
967 .expect_err("the fixture must raise")
968 }
969
970 /// **The load-bearing gate: a raise inside an IMPORTED package reports the
971 /// IMPORTED file's path and line.**
972 ///
973 /// Hand-computed. In `bakuhatsu.b` the failing call sits on line 11 at
974 /// column 3, and the whole point of the fixture's height is that no other
975 /// file in the program can produce that pair: the entry file has 2 lines
976 /// and `kotae.b` has 3, so *any* mis-attribution is visible as a different
977 /// path AND a different position, never as a coincidence.
978 ///
979 /// **Three red runs, one per edit this change makes** — each isolates a
980 /// different half of the mechanism, which is what stops the gate being a
981 /// tautology over "some renderer ran".
982 ///
983 /// 1. `eval_program` + `.map_err(|e| RunError::Eval(e.to_string()))`
984 /// restored (the pre-change code):
985 /// ```text
986 /// left: "runtime error: unbound symbol: kore_wa_sonzai_shinai at 74..95"
987 /// right: "runtime error: bakuhatsu.b:10:3: unbound symbol `kore_wa_sonzai_shinai`"
988 /// ```
989 /// No place at all — the state this change is fixing — and the trailing
990 /// `at 74..95` is upstream's `Display`, an offset with no file, which is
991 /// why the loop renders `short_message` instead.
992 ///
993 /// 2. The loop kept, but `0` passed to `locate` in place of `top_level`:
994 /// ```text
995 /// left: "runtime error: kotae.b: unbound symbol `kore_wa_sonzai_shinai`"
996 /// right: "runtime error: bakuhatsu.b:10:3: unbound symbol `kore_wa_sonzai_shinai`"
997 /// ```
998 /// **This is the one that proves the INDEX is load-bearing** rather than
999 /// the renderer: form 0 belongs to `kotae.b`, so the wrong file is named
1000 /// — and named without a position, because the guard in `locate` sees
1001 /// that byte 74 is not a range in a 21-byte file and declines to invent
1002 /// one. A fixture with one imported package could not tell these apart.
1003 ///
1004 /// 3. `crate::lower_to_spanned(&crate::to_sexps(&erased))` reinstated
1005 /// between erasure and the loop:
1006 /// ```text
1007 /// left: "runtime error: bakuhatsu.b: unbound symbol `kore_wa_sonzai_shinai`"
1008 /// right: "runtime error: bakuhatsu.b:10:3: unbound symbol `kore_wa_sonzai_shinai`"
1009 /// ```
1010 /// The right FILE with no position — which is exactly the shape of the
1011 /// bug: the index survived the lift and every span did not.
1012 /// kotae loads first so bakuhatsu's forms do not start at index 0: the
1013 /// order is the fixture, and the waiver says so (B0015 wants them sorted).
1014 const TWO_IMPORTS: &str =
1015 "use(\"kotae\")\n# waive B0015: kotae loads first on purpose\nuse(\"bakuhatsu\")\n";
1016
1017 #[test]
1018 fn a_raise_inside_an_imported_package_names_that_package() {
1019 let err = run_named("entry.b", TWO_IMPORTS);
1020 assert_eq!(
1021 err.to_string(),
1022 "runtime error: bakuhatsu.b:11:3: unbound symbol `kore_wa_sonzai_shinai`"
1023 );
1024 }
1025
1026 /// Anti-vacuity for the fixture itself: the position asserted above is a
1027 /// FACT ABOUT `bakuhatsu.b`, checked against the source text rather than
1028 /// against the thing that produced it.
1029 ///
1030 /// Without this, `11:3` is just a number that happened to come out of the
1031 /// code under test, and a change that moved every reported line by one
1032 /// would move this assertion with it.
1033 #[test]
1034 fn line_11_column_3_of_the_fixture_is_the_failing_call() {
1035 let line = BAKUHATSU.lines().nth(10).expect("line 11 exists");
1036 assert_eq!(line, " kore_wa_sonzai_shinai()");
1037 assert_eq!(
1038 &line[2..],
1039 "kore_wa_sonzai_shinai()",
1040 "column 3 (1-indexed) is where the call starts"
1041 );
1042 // And the other two files cannot reach that far, which is what makes a
1043 // mis-attribution loud instead of plausible.
1044 let offset = BAKUHATSU.find("kore_wa_sonzai_shinai").expect("in fixture");
1045 assert!(
1046 offset > KOTAE.len(),
1047 "kotae.b could answer for byte {offset}"
1048 );
1049 assert!(
1050 offset > TWO_IMPORTS.len(),
1051 "the entry file could answer for byte {offset}"
1052 );
1053 }
1054
1055 /// **The `FileId(0)` path: a raise in the ENTRY file reports the entry
1056 /// file.** The single-file case, which is every program that imports
1057 /// nothing — and the one where the index and the span cannot disagree.
1058 ///
1059 /// **Red run** (2026-08-12), `eval_program` +
1060 /// `.map_err(|e| RunError::Eval(e.to_string()))` restored:
1061 /// ```text
1062 /// left: "runtime error: unbound symbol: nani_mo_nai at 17..28"
1063 /// right: "runtime error: honmono.b:5:1: unbound symbol `nani_mo_nai`"
1064 /// ```
1065 ///
1066 /// **Second red run**, `lower_to_spanned` reinstated after erasure — the
1067 /// one that isolates the SPAN half from the index half, since a
1068 /// single-file program cannot get its file wrong:
1069 /// ```text
1070 /// left: "runtime error: honmono.b: unbound symbol `nani_mo_nai`"
1071 /// right: "runtime error: honmono.b:5:1: unbound symbol `nani_mo_nai`"
1072 /// ```
1073 #[test]
1074 fn a_raise_in_the_entry_file_names_the_entry_file() {
1075 let err = run_named(
1076 "honmono.b",
1077 "def f()\n 1\nend\n\n# waive B0001: a raise at runtime\nnani_mo_nai()\n",
1078 );
1079 assert_eq!(
1080 err.to_string(),
1081 "runtime error: honmono.b:6:1: unbound symbol `nani_mo_nai`"
1082 );
1083 }
1084
1085 /// A raise from a form that came through the SURFACE-level erasure still
1086 /// reports a real position — the annotated path, where erasure rewrites
1087 /// the node rather than passing it through.
1088 ///
1089 /// Separate from the two above because the erasure rewrite is the only
1090 /// place a node is built rather than kept, and a synthetic span there
1091 /// would be invisible to a fixture whose failing form is untouched.
1092 ///
1093 /// **Red run** (2026-08-12), `lower_to_spanned` reinstated after erasure:
1094 /// ```text
1095 /// left: "runtime error: chuu.b: unbound symbol `mada_nai`"
1096 /// right: "runtime error: chuu.b:2:3: unbound symbol `mada_nai`"
1097 /// ```
1098 #[test]
1099 fn a_raise_inside_an_annotated_def_still_names_its_line() {
1100 let err = run_named(
1101 "chuu.b",
1102 "# waive B0001: a raise at runtime\ndef f(a: Int) -> Int\n mada_nai(a)\nend\n\nf(1)\n",
1103 );
1104 assert_eq!(
1105 err.to_string(),
1106 "runtime error: chuu.b:3:3: unbound symbol `mada_nai`"
1107 );
1108 }
1109
1110 /// **The stated limit, pinned rather than left to be discovered.**
1111 ///
1112 /// A top-level form in the entry file calls a function defined in an
1113 /// imported one, and the raise happens inside the callee. The index names
1114 /// the executing form (the entry's), the span names the callee's bytes,
1115 /// and the two disagree about the file. `locate`'s in-range guard is what
1116 /// keeps that from rendering as a precise-looking `entry:line:col`: the
1117 /// offset is not a range in the entry file, so no position is printed.
1118 ///
1119 /// This test asserts the CURRENT behaviour, including the part that is
1120 /// wrong — the path is the caller's. It is here so the next author reads
1121 /// the limit off a green suite instead of off a bug report. Closing it
1122 /// needs per-frame file identity at the evaluator; see `RunError::Eval`.
1123 ///
1124 /// **Red run** (2026-08-12), the `span.end <= file.text.len()` guard
1125 /// removed from `uses::ResolvedProgram::locate` — and it is the ONLY test
1126 /// in the crate that moves, which is the same run's evidence that the
1127 /// guard is a no-op on every check-time diagnostic:
1128 /// ```text
1129 /// left: "runtime error: yobidashi.b:1:14: unbound symbol `kore_wa_sonzai_shinai`"
1130 /// right: "runtime error: yobidashi.b: unbound symbol `kore_wa_sonzai_shinai`"
1131 /// ```
1132 /// `1:14` lands in the middle of `use("bakuhatsu2")` — the callee's start
1133 /// offset happens to be in range for the caller's file even though its end
1134 /// is not, so a wrong file gets a precise number pointing at innocent
1135 /// code. Exactly the failure this repo's file-identity work exists to
1136 /// refuse, which is why the guard tests BOTH ends.
1137 ///
1138 /// **Re-run 2026-09-29**, after the fixtures gained their waiver lines:
1139 /// the guard's END check replaced by a start check (`span.start <= len`),
1140 /// with the caller padded so the callee's start (byte 47) is in range and
1141 /// its end (byte 70) is not:
1142 /// ```text
1143 /// left: "runtime error: yobidashi.b:3:1: unbound symbol `kore_wa_sonzai_shinai`"
1144 /// right: "runtime error: yobidashi.b: unbound symbol `kore_wa_sonzai_shinai`"
1145 /// ```
1146 #[test]
1147 fn a_raise_in_a_callee_from_another_file_reports_no_position_rather_than_a_wrong_one() {
1148 // The comment is padding, and load-bearing: `bakuhatsu2.b`'s failing
1149 // call starts at byte 47 (after its waiver line) and ends at 70, and
1150 // this file is 57 bytes, so the start is in range here and the end is
1151 // not — the half-in-range case the guard's END check exists for.
1152 let err = run_named(
1153 "yobidashi.b",
1154 "use(\"bakuhatsu2\")\n# pad: 47 in range\nbakuhatsu2::yobu()\n",
1155 );
1156 assert_eq!(
1157 err.to_string(),
1158 "runtime error: yobidashi.b: unbound symbol `kore_wa_sonzai_shinai`",
1159 "the caller's file is named (the stated limit) but NOT with a \
1160 position it cannot justify"
1161 );
1162 }
1163}
1164
1165#[cfg(test)]
1166mod tests {
1167 use super::*;
1168
1169 fn int(src: &str) -> i64 {
1170 match run(src).unwrap_or_else(|e| panic!("{src:?}: {e}")).value {
1171 Value::Int(v) => v,
1172 other => panic!("{src:?} produced {other:?}"),
1173 }
1174 }
1175
1176 /// **The sliding scale, as one assertion.** Annotating changes the
1177 /// analysis and nothing else.
1178 #[test]
1179 fn annotating_buys_analysis_and_changes_nothing_else() {
1180 let plain = run("def add(a, b)\n a + b\nend\nadd(2, 3)").expect("plain");
1181 let typed = run("def add(a: Int, b: Int) -> Int\n a + b\nend\nadd(2, 3)").expect("typed");
1182
1183 assert!(matches!(plain.value, Value::Int(5)));
1184 assert!(
1185 matches!(typed.value, Value::Int(5)),
1186 "the annotated program must compute the same answer"
1187 );
1188 assert_eq!(plain.visited, 0, "no annotations means no analysis");
1189 assert!(
1190 typed.visited > 0,
1191 "an annotation must actually buy analysis, not just decorate"
1192 );
1193 assert_eq!(plain.typed_decls, 0);
1194 assert_eq!(typed.typed_decls, 1);
1195 }
1196
1197 /// **Checking happens before erasure.** This is the test that catches the
1198 /// reordering: a program with a declared-type violation must be rejected,
1199 /// and it can only be rejected while the annotations still exist.
1200 #[test]
1201 fn a_type_error_is_reported_and_the_program_does_not_run() {
1202 let err = run("def add(a: Int, b: Int) -> Str\n a + b\nend\nadd(1, 2)")
1203 .expect_err("a declared Str return from an Int body must be rejected");
1204 assert!(
1205 matches!(err, RunError::Types(ref d) if !d.is_empty()),
1206 "expected type diagnostics, got {err}"
1207 );
1208 }
1209
1210 /// And the untyped version of the same program runs, so the rejection
1211 /// above is the annotation's doing rather than a parse failure.
1212 #[test]
1213 fn the_same_program_without_annotations_runs() {
1214 assert_eq!(int("def add(a, b)\n a + b\nend\nadd(1, 2)"), 3);
1215 }
1216
1217 #[test]
1218 fn a_parse_error_is_reported_as_one() {
1219 assert!(matches!(run("def (").unwrap_err(), RunError::Parse(_)));
1220 }
1221
1222 /// Every stage reports in its own vocabulary, so a failure names which
1223 /// stage failed rather than surfacing as a generic error.
1224 #[test]
1225 fn a_runtime_error_is_reported_as_one() {
1226 let err = run("throw(error(\"boom\"))").expect_err("a raise");
1227 assert!(matches!(err, RunError::Eval(_)), "got {err}");
1228 }
1229
1230 /// Stdlib and primitives are both reachable through the pipeline — the
1231 /// gap that made `6 % 3` fail.
1232 #[test]
1233 fn the_pipeline_reaches_both_runtime_layers() {
1234 assert_eq!(int("6 % 3"), 0);
1235 assert_eq!(int("7 % 3"), 1);
1236 assert_eq!(int("2 + 3 * 4"), 14);
1237 }
1238
1239 /// **The deleted hop was a no-op on everything blue emits — so removing it
1240 /// is a swap, not a behaviour change.**
1241 ///
1242 /// The old lowering printed the erased tree and read it back through
1243 /// `tatara_lisp::read_spanned`. This walks a corpus and asserts the two
1244 /// paths land on the same tree, which is the equivalence the swap rests on.
1245 /// It is stated as a *measurement over this corpus*, not as a theorem:
1246 /// the round trip is not identity in general (that is precisely why it had
1247 /// to go), it merely happened to be identity for the bytes blue emits.
1248 #[test]
1249 fn the_deleted_round_trip_agreed_with_the_direct_lowering() {
1250 let corpus = [
1251 "def add(a, b)\n a + b\nend\nadd(2, 3)",
1252 "def fact(n)\n if n < 2\n 1\n else\n n * fact(n - 1)\n end\nend\nfact(5)",
1253 "def f(a, b)\n c = a + b\n c * 2\nend\nf(1, 2)",
1254 "defmacro sq(e)\n quote\n unquote(e) * unquote(e)\n end\nend\nsq(2 + 3)",
1255 "\"a string with spaces, a ( and a )\"",
1256 "def g(a: Int) -> Int\n a + 1\nend\ng(1)",
1257 "6 % 3",
1258 "1.5 + 2.25",
1259 ];
1260 for src in corpus {
1261 // Projected to `Sexp` because that is what the deleted hop
1262 // operated on. Erasure itself no longer goes near it.
1263 let erased = crate::to_sexps(&erase_types(&parse_tree(src).expect("parse")));
1264
1265 let direct: Vec<Sexp> = crate::lower_to_spanned(&erased)
1266 .iter()
1267 .map(tatara_lisp::Spanned::to_sexp)
1268 .collect();
1269 assert_eq!(direct, erased, "the direct lowering must be the identity");
1270
1271 let text = erased
1272 .iter()
1273 .map(ToString::to_string)
1274 .collect::<Vec<_>>()
1275 .join("\n");
1276 let round_tripped: Vec<Sexp> = tatara_lisp::read_spanned(&text)
1277 .unwrap_or_else(|e| panic!("{src:?}: the old path could not read back: {e:?}"))
1278 .iter()
1279 .map(tatara_lisp::Spanned::to_sexp)
1280 .collect();
1281 assert_eq!(
1282 round_tripped, erased,
1283 "{src:?}: the old print-and-reparse path changed the tree"
1284 );
1285 }
1286 }
1287
1288 /// Anti-vacuity for the test above: the round trip really is *not* the
1289 /// identity in general, so agreeing on the corpus was a property of what
1290 /// blue happens to emit rather than a property of the reader.
1291 ///
1292 /// **`Atom::Symbol`'s `Display` writes the name raw, with no escaping.**
1293 /// `Atom::Str` escapes and its docs explain at length why; the symbol arm
1294 /// is `f.write_str(s)`. So print-then-read is not inverse over the symbol
1295 /// domain, and the failure is *silent*: a symbol containing a space prints
1296 /// as two tokens, reads back as two symbols, and the result is a perfectly
1297 /// well-formed tree with a different meaning. No error, nothing to catch.
1298 ///
1299 /// Measured 2026-08-02 across the separators: `a b` and `x'y` come back
1300 /// `Ok` with a different tree; `x)y`, `x"y` and `x;y` come back `Err`;
1301 /// `x{y` and `x[y` DO round-trip at this level — those two are one symbol
1302 /// in and one symbol out, so the brace-fusion reported in tatara *source*
1303 /// is not what bites a printed tree. The silent pair is what makes this a
1304 /// miscompile class rather than a noisy one.
1305 #[test]
1306 fn the_round_trip_is_not_the_identity_in_general() {
1307 let tree = Sexp::List(vec![
1308 Sexp::Atom(tatara_lisp::Atom::Symbol("f".into())),
1309 Sexp::Atom(tatara_lisp::Atom::Symbol("a b".into())),
1310 ]);
1311 let text = tree.to_string();
1312 let back: Vec<Sexp> = tatara_lisp::read_spanned(&text)
1313 .expect("it reads back cleanly — that IS the problem")
1314 .iter()
1315 .map(tatara_lisp::Spanned::to_sexp)
1316 .collect();
1317 assert_ne!(
1318 back,
1319 vec![tree.clone()],
1320 "if print-then-read became inverse over symbols, the class would be \
1321 closed upstream and this test should be deleted rather than relaxed"
1322 );
1323 // …and the direct lowering is unaffected by any of it.
1324 let direct: Vec<Sexp> = crate::lower_to_spanned(std::slice::from_ref(&tree))
1325 .iter()
1326 .map(tatara_lisp::Spanned::to_sexp)
1327 .collect();
1328 assert_eq!(direct, vec![tree]);
1329 }
1330}
1331
1332#[cfg(test)]
1333mod macro_tests {
1334 use super::*;
1335
1336 fn int(src: &str) -> i64 {
1337 match run(src).unwrap_or_else(|e| panic!("{src:?}: {e}")).value {
1338 Value::Int(v) => v,
1339 other => panic!("{src:?} produced {other:?}"),
1340 }
1341 }
1342
1343 /// **A blue macro expands and runs.** Tenet 2's surface, end to end.
1344 #[test]
1345 fn a_macro_expands_and_runs() {
1346 assert_eq!(
1347 int("defmacro double(x)\n quote\n unquote(x) + unquote(x)\n end\nend\ndouble(21)"),
1348 42
1349 );
1350 }
1351
1352 /// A macro receives *source forms*, not values — so it can duplicate its
1353 /// argument, which a function cannot do without re-evaluating it.
1354 #[test]
1355 fn a_macro_operates_on_syntax_not_values() {
1356 assert_eq!(
1357 int("defmacro sq(e)\n quote\n unquote(e) * unquote(e)\n end\nend\nsq(2 + 3)"),
1358 25,
1359 "the argument form `2 + 3` must be substituted twice"
1360 );
1361 }
1362
1363 /// **A runaway macro is a typed error, not a dead compiler.** This is the
1364 /// property that makes the metaprogramming surface safe to hand to a user.
1365 ///
1366 /// The assertion was `contains("expansion limit")` and now reads
1367 /// `contains("expansion")`, because the pipeline renders `short_message`
1368 /// rather than `Display`: upstream words the same fact as "exceeded 256
1369 /// expansion steps" instead of "exceeded the expansion limit of 256
1370 /// rewrites". The PROPERTY is unchanged and still asserted — the macro is
1371 /// named, and the failure is attributed to expansion rather than to
1372 /// evaluation. **This reword was the whole measured blast radius of that
1373 /// switch**, one test in the workspace.
1374 ///
1375 /// The number is deliberately NOT pinned. It is upstream's constant, this
1376 /// test owns none of it, and matching it would turn an upstream bump into
1377 /// a red run here that proves nothing about blue.
1378 ///
1379 /// The third clause is new capability rather than repair: the message now
1380 /// carries `<anonymous>:6:1`, so a runaway macro says WHERE it ran away.
1381 #[test]
1382 fn a_runaway_macro_fails_the_compilation_rather_than_the_process() {
1383 let err =
1384 run("defmacro forever(x)\n quote\n forever(unquote(x))\n end\nend\nforever(1)")
1385 .expect_err("a self-referential macro must be rejected");
1386 let msg = err.to_string();
1387 assert!(
1388 msg.contains("forever") && msg.contains("expansion"),
1389 "the error must name the macro and the limit it hit: {msg}"
1390 );
1391 assert!(
1392 msg.contains("<anonymous>:6:1"),
1393 "and must place the call that ran away — line 6 is `forever(1)`: {msg}"
1394 );
1395 }
1396}
1397
1398#[cfg(test)]
1399mod input_tests {
1400 use super::*;
1401 use crate::inputs::{Declaration, Inputs};
1402
1403 /// A schema a macro will generate code from.
1404 const SCHEMA: &[u8] = b"3";
1405
1406 fn with_schema(src: &str) -> Result<Run, RunError> {
1407 let hash = Inputs::hash_of(SCHEMA);
1408 let mut inputs = Inputs::new();
1409 inputs
1410 .bind(
1411 &Declaration {
1412 name: "schema".to_string(),
1413 hash,
1414 },
1415 SCHEMA.to_vec(),
1416 )
1417 .expect("bind");
1418 run_with_inputs(src, inputs)
1419 }
1420
1421 fn decl_line() -> String {
1422 let mut s = String::from("definput(\"schema\", \"");
1423 s.push_str(&Inputs::hash_of(SCHEMA));
1424 s.push_str("\")\n");
1425 s
1426 }
1427
1428 /// **A macro reads a declared build input.** This is §VI OPEN #6 closed —
1429 /// the spec names it as gating blue's whole "stronger than Ruby's
1430 /// metaprogramming" claim, because a macro that cannot read a schema cannot
1431 /// generate code from one.
1432 #[test]
1433 fn a_macro_can_read_a_declared_build_input() {
1434 let src = decl_line() + "input(\"schema\")";
1435 let out = with_schema(&src).expect("run");
1436 assert!(
1437 matches!(out.value, Value::Str(ref s) if &**s == "3"),
1438 "got {:?}",
1439 out.value
1440 );
1441 }
1442
1443 /// **An undeclared input is an error, not a file read and not nil.**
1444 /// Returning nil is how a macro generates an empty table and nobody notices
1445 /// until runtime.
1446 #[test]
1447 fn an_undeclared_input_is_an_error() {
1448 let err = with_schema("input(\"not_declared\")").expect_err("must fail");
1449 let msg = err.to_string();
1450 assert!(msg.contains("not_declared"), "must name it: {msg}");
1451 assert!(msg.contains("definput"), "and say how to declare it: {msg}");
1452 }
1453
1454 /// **There is no path-based read at all.** The capability is the absence of
1455 /// the primitive, not a check inside one — so this is an unbound symbol.
1456 ///
1457 /// Holds for the DEFAULT surface — the one every embedder gets. The `sys`
1458 /// cargo feature (CLI only) is the one declared exception: it is the
1459 /// operator's own trusted host surface, and is asserted in
1460 /// `sys_read_file_is_the_trusted_cli_only_exception` below.
1461 #[cfg(not(feature = "sys"))]
1462 #[test]
1463 fn there_is_no_ambient_file_read() {
1464 for attempt in [
1465 "read_file(\"/etc/passwd\")",
1466 "File(\"/etc/passwd\")",
1467 "slurp(\"/etc/passwd\")",
1468 "open(\"/etc/passwd\")",
1469 ] {
1470 let err = with_schema(attempt).expect_err("must not resolve");
1471 assert!(
1472 err.to_string().contains("unbound"),
1473 "{attempt} must be UNBOUND — a capability removed by absence, \
1474 not guarded by a check: {err}"
1475 );
1476 }
1477 }
1478
1479 /// With the `sys` feature compiled in, `read_file` IS bound — that is the
1480 /// point of the feature. The doctrine does not move: this is the operator's
1481 /// own machine (the CLI), not an embedder's sandbox. Pin the boundary so a
1482 /// future default-build change is heard, and assert that `input()` still
1483 /// works beside it.
1484 #[cfg(feature = "sys")]
1485 #[test]
1486 fn sys_read_file_is_the_trusted_cli_only_exception() {
1487 let err = with_schema("definitely_not_a_primitive(\"x\")").expect_err("must not resolve");
1488 assert!(err.to_string().contains("unbound"), "{err}");
1489 assert!(
1490 with_schema("read_file(\"/etc/passwd\")").is_ok(),
1491 "with `sys` on, read_file is the trusted CLI surface"
1492 );
1493 let out = with_schema("input(\"schema\")").expect("run");
1494 assert!(
1495 matches!(out.value, Value::Str(ref s) if &**s == "3"),
1496 "input() still binds beside the sys surface: {:?}",
1497 out.value
1498 );
1499 }
1500
1501 /// Anti-vacuity: with no inputs supplied at all, even a declared name fails
1502 /// — so the success above is the binding's doing.
1503 #[test]
1504 fn a_declared_input_with_no_bytes_supplied_fails() {
1505 let src = decl_line() + "input(\"schema\")";
1506 assert!(run(&src).is_err(), "no bytes were supplied");
1507 }
1508}
1509
1510#[cfg(test)]
1511mod tier2_tests {
1512 use super::*;
1513 use crate::inputs::{Declaration, Inputs};
1514
1515 /// **The Tier-2 conversion §V.6.3 said was gated: a macro that emits real
1516 /// declarations FROM A SCHEMA.**
1517 ///
1518 /// `theory/BLUE.md` §VI OPEN #6 states the blocker plainly — "tenet 2
1519 /// installs a `NoLoader`, so a macro cannot read a schema — which gates
1520 /// every Tier-2 conversion in §V.6 and therefore blue's whole 'stronger than
1521 /// Ruby's metaprogramming' claim."
1522 ///
1523 /// Here the schema supplies a *value the generated code depends on*, read at
1524 /// expansion time. Ruby and Elixir can both do this — with the whole
1525 /// filesystem open. blue does it through a name bound to a content hash.
1526 #[test]
1527 fn a_macro_generates_code_from_a_schema() {
1528 let schema = b"7";
1529 let mut inputs = Inputs::new();
1530 inputs
1531 .bind(
1532 &Declaration {
1533 name: "arity".to_string(),
1534 hash: Inputs::hash_of(schema),
1535 },
1536 schema.to_vec(),
1537 )
1538 .expect("bind");
1539
1540 // The macro reads the input at EXPANSION time and splices the value it
1541 // found into the code it emits.
1542 let mut src = String::from("definput(\"arity\", \"");
1543 src.push_str(&Inputs::hash_of(schema));
1544 src.push_str("\")\n");
1545 src.push_str(
1546 "defmacro from_schema()\n quote\n unquote(to_int(input(\"arity\")))\n end\nend\n\
1547 from_schema() * 6",
1548 );
1549
1550 let out = run_with_inputs(&src, inputs).expect("run");
1551 assert!(
1552 matches!(out.value, Value::Int(42)),
1553 "the schema's 7 must reach the generated code: got {:?}",
1554 out.value
1555 );
1556 }
1557}