blue_lang_runtime/lib.rs
1//! The blue runtime — **one** definition of what a blue program runs against.
2//!
3//! Before this crate existed, every consumer hand-rolled its own
4//! `Interpreter::new()` + `install_primitives(...)` pair — three of them, in
5//! three crates — and they had silently drifted: none of them loaded the Lisp
6//! stdlib. So `6 % 3` lowered correctly to `(mod 6 3)`, `mod` was genuinely
7//! defined, and the program still died with `unbound symbol: mod`, because
8//! the definition lived in a stdlib nobody loaded.
9//!
10//! That is the duplication tax in its usual shape: the bug is not in any one
11//! copy, it is in there *being* copies. One function now owns the answer.
12//!
13//! ## Layers
14//!
15//! A blue interpreter is built in two layers, and both are required:
16//!
17//! 1. **Rust primitives** — arithmetic, comparison, list ops, I/O.
18//! 2. **The full tatara stdlib** — primitives, higher-order functions
19//! (`map`/`filter`/`fold`), maps, channels, fibers, type-check, and
20//! everything tatara defines in tatara-lisp itself
21//! (`mod`, `rem`, `first`, `inc`, `even?`, the actor and transducer
22//! helpers, …). Loading it is not optional garnish: blue's own operator
23//! lowering depends on it.
24//! 3. **blue's own core** ([`stdlib`]) — strings and number conversion, which
25//! tatara-lisp does not have in any form. A Ruby-surface language without
26//! `length` or `upcase` is not usable, and the semantics are Ruby's
27//! (characters, not bytes), which is why they are blue's and not the
28//! substrate's.
29
30pub mod erase;
31pub mod inputs;
32pub mod pipeline;
33pub mod stdlib;
34pub mod uses;
35
36pub use erase::erase_types;
37pub use inputs::{declarations, install_input_primitives, Declaration, InputError, Inputs};
38pub use pipeline::{parse, parse_with_depth, run, run_with_inputs, Run, RunError};
39pub use stdlib::install_blue_stdlib;
40
41use tatara_lisp_eval::{install_full_stdlib_with, Interpreter};
42
43/// Build an interpreter with the complete blue runtime installed.
44///
45/// This is the *only* sanctioned way to obtain one. A caller that builds an
46/// `Interpreter` directly gets a partial runtime, and the failure shows up as
47/// an unbound symbol at the far end of a program.
48pub fn interpreter<H: 'static>(host: &mut H) -> Interpreter<H> {
49 let mut interp = Interpreter::new();
50 // The FULL substrate, not just `install_primitives`.
51 //
52 // blue called `install_primitives` + `install_lisp_stdlib_with` and got
53 // neither `install_hof` nor `install_map` — so `map`, `filter`, `fold` and
54 // every map literal were UNBOUND SYMBOLS. A language with no higher-order
55 // functions, in a workspace whose whole surface is Ruby's.
56 //
57 // Same shape as the stdlib gap this crate was created to fix: the substrate
58 // has layers, and naming them one at a time is how one gets missed. Call
59 // the composed installer.
60 install_full_stdlib_with(&mut interp, host);
61 // Layer 3: blue's own core — strings and number conversion, which
62 // tatara-lisp does not carry at all. See `stdlib` for why the
63 // character-counting semantics are blue's rather than the substrate's.
64 stdlib::install_blue_stdlib(&mut interp);
65 interp
66}
67
68/// The prebuilt hostless substrate, built once per process.
69///
70/// **Measured 2026-08-01, and this is the entire reason the fork exists.**
71/// Profiling a trivial blue program found the run dominated by ONE thing:
72///
73/// ```text
74/// parse 9.6 µs
75/// check 1.6 µs
76/// interpreter_hostless() 5 820 µs <- 98.4% of the run
77/// ```
78///
79/// Splitting that further: `Interpreter::new()` is 24 µs and
80/// `install_full_stdlib_with` is the rest — the stdlib was being rebuilt from
81/// scratch on every single `run()`, and blue's whole surface (`map`, `filter`,
82/// string ops) lives in it, so no program could avoid the cost.
83///
84/// `fork` already existed upstream for exactly this, and blue simply was not
85/// using it. tatara-lisp-eval's own `fork_cost.rs` opens with *"cheapness is
86/// the entire reason it exists"* — the capability was built, documented and
87/// guarded, and the consumer kept paying full price beside it.
88///
89/// | | per call |
90/// |---|---|
91/// | rebuild (`Interpreter::new` + `install_full_stdlib_with`) | **9.03 ms** |
92/// | `fork()` of a prebuilt base | **0.102 ms** |
93///
94/// **88× on the dominant cost.** This is purgatory's computation-layer clause
95/// made real: the stdlib is the most-reused computation in the language, and
96/// it was being discarded and recomputed rather than resurrected.
97///
98/// Isolation is `fork`'s contract, not an assumption made here — its
99/// correctness gates live upstream in `fork.rs`, and `fork_cost.rs` guards
100/// against a future change that deep-copies (which would keep every
101/// correctness test green while silently restoring the cost this removes).
102static HOSTLESS_BASE: std::sync::LazyLock<std::sync::Mutex<Interpreter<()>>> =
103 std::sync::LazyLock::new(|| std::sync::Mutex::new(interpreter(&mut ())));
104
105/// The common host-free case.
106///
107/// Forks the process-wide base rather than rebuilding the stdlib. Falls back to
108/// a full build if the lock is poisoned: a poisoned lock means another thread
109/// panicked mid-fork, and answering a correct-but-slow interpreter beats
110/// propagating someone else's panic into an unrelated caller.
111pub fn interpreter_hostless() -> Interpreter<()> {
112 match HOSTLESS_BASE.lock() {
113 Ok(base) => base.fork(),
114 Err(_) => interpreter(&mut ()),
115 }
116}
117
118/// Lift blue's emitted forms into what the evaluator eats. **The one door.**
119///
120/// `Interpreter::eval_program` takes `&[Spanned]`; blue's stages produce
121/// `Sexp`. Two callers bridged that gap by *printing the tree and reading it
122/// back* — `forms.map(ToString::to_string).join("\n")` into
123/// `tatara_lisp::read_spanned`. Both now call this instead, and the round trip
124/// is gone.
125///
126/// **Why it had to go.** Printing a tree we already hold and re-parsing it puts
127/// the reader's lexer between blue and its own output, for nothing — and the
128/// printer and the reader are **not inverses**. `Atom::Str`'s `Display` escapes
129/// its payload and its own docs explain at length why; the `Atom::Symbol` arm
130/// is a bare `write_str`. So a symbol whose text carries a separator prints as
131/// several tokens and reads back as several symbols: a well-formed tree with a
132/// different meaning, no error raised. Measured 2026-08-02 —
133/// `pipeline::tests::the_round_trip_is_not_the_identity_in_general` pins which
134/// separators are silent and which are loud. The only thing that kept this from
135/// biting was blue happening not to emit those bytes. A stage that never
136/// serialises cannot be mis-read.
137///
138/// **What is given up: spans.** The old path's spans pointed into the
139/// re-printed lisp text, a buffer no human ever wrote and no diagnostic could
140/// usefully cite — they were positions in blue's own output, not in the
141/// author's source. `Span::synthetic` says the same thing honestly. Carrying
142/// real blue-source spans through erasure is a separate piece of work and
143/// would start from `Spanned::from_sexp_at`, not from a printer.
144#[must_use]
145pub fn lower_to_spanned(forms: &[tatara_lisp::Sexp]) -> Vec<tatara_lisp::Spanned> {
146 forms
147 .iter()
148 .map(tatara_lisp::Spanned::from_sexp_synthetic)
149 .collect()
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155 use tatara_lisp_eval::Value;
156
157 fn eval(src: &str) -> Value {
158 let forms = tatara_lisp::read_spanned(src).expect("read");
159 let mut interp = interpreter_hostless();
160 interp.eval_program(&forms, &mut ()).expect("eval")
161 }
162
163 /// Both layers are present. A test that only checked layer 1 is exactly
164 /// what let the stdlib gap survive.
165 #[test]
166 fn both_layers_are_installed() {
167 // Layer 1: a Rust primitive.
168 assert!(matches!(eval("(+ 1 2)"), Value::Int(3)));
169 // Layer 2: a stdlib definition, which is the layer that was missing.
170 assert!(matches!(eval("(mod 7 3)"), Value::Int(1)));
171 assert!(matches!(eval("(inc 41)"), Value::Int(42)));
172 assert!(matches!(eval("(first (list 9 8))"), Value::Int(9)));
173 }
174
175 /// Anti-vacuity: a bare interpreter really does LACK layer 2, so the test
176 /// above is measuring the runtime's contribution and not a property the
177 /// interpreter has for free.
178 #[test]
179 fn a_bare_interpreter_lacks_the_stdlib() {
180 let forms = tatara_lisp::read_spanned("(mod 7 3)").expect("read");
181 let mut bare = Interpreter::new();
182 tatara_lisp_eval::install_primitives(&mut bare);
183 assert!(
184 bare.eval_program(&forms, &mut ()).is_err(),
185 "if a bare interpreter already resolved `mod`, this crate would be measuring nothing"
186 );
187 }
188}