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//! 4. **JSON** ([`json`]) and **cryptography** ([`crypto`]) — pure
30//! computation, installed unconditionally, so the wasm consumer keeps them.
31//! 5. **The host layer** (`sys`, behind the `sys` feature) — every name in it
32//! is a host import.
33
34pub mod crypto;
35pub mod domain;
36pub mod erase;
37pub mod hosted;
38pub mod inputs;
39pub mod json;
40pub mod pipeline;
41pub mod stdlib;
42#[cfg(feature = "sys")]
43pub mod sys;
44pub mod uses;
45
46pub use erase::{erase_types, to_sexps};
47pub use inputs::{declarations, install_input_primitives, Declaration, InputError, Inputs};
48pub use pipeline::{
49 parse, parse_tree_with_depth, parse_with_depth, run, run_with_inputs, Run, RunError,
50};
51pub use stdlib::install_blue_stdlib;
52
53use tatara_lisp_eval::{install_full_stdlib_with, Interpreter};
54
55/// Build an interpreter with the complete blue runtime installed.
56///
57/// This is the *only* sanctioned way to obtain one. A caller that builds an
58/// `Interpreter` directly gets a partial runtime, and the failure shows up as
59/// an unbound symbol at the far end of a program.
60pub fn interpreter<H: 'static>(host: &mut H) -> Interpreter<H> {
61 let mut interp = Interpreter::new();
62 // The FULL substrate, not just `install_primitives`.
63 //
64 // blue called `install_primitives` + `install_lisp_stdlib_with` and got
65 // neither `install_hof` nor `install_map` — so `map`, `filter`, `fold` and
66 // every map literal were UNBOUND SYMBOLS. A language with no higher-order
67 // functions, in a workspace whose whole surface is Ruby's.
68 //
69 // Same shape as the stdlib gap this crate was created to fix: the substrate
70 // has layers, and naming them one at a time is how one gets missed. Call
71 // the composed installer.
72 install_full_stdlib_with(&mut interp, host);
73 // Layer 3: blue's own core — strings and number conversion, which
74 // tatara-lisp does not carry at all. See `stdlib` for why the
75 // character-counting semantics are blue's rather than the substrate's.
76 stdlib::install_blue_stdlib(&mut interp);
77 // Layer 4: blue's JSON surface — parse, stringify, read. Pure
78 // computation, no host imports, so it is installed unconditionally; the
79 // `wasm32-unknown-unknown` consumer keeps it. See `json` for why objects
80 // arrive as alists rather than Maps.
81 json::install_json_stdlib(&mut interp);
82 // Layer 4b: cryptography — BLAKE3 and Ed25519. Pure for the same reason
83 // JSON is: a deterministic function of its arguments, with the keypair's
84 // seed supplied by the caller rather than drawn from an entropy source,
85 // so it lowers to no import and the wasm consumer keeps it. See `crypto`.
86 crypto::install_crypto_stdlib(&mut interp);
87 // Layer 5: the host-side system surface — process, filesystem, env,
88 // clock. Feature-gated: every sys primitive is a host import, so the
89 // wasm consumer (which builds with `sys` OFF) keeps its zero-host-import
90 // surface by construction. Only the CLI turns it on.
91 #[cfg(feature = "sys")]
92 sys::install_sys_stdlib(&mut interp);
93 interp
94}
95
96/// The prebuilt hostless substrate, built once per process.
97///
98/// **Measured 2026-08-01, and this is the entire reason the fork exists.**
99/// Profiling a trivial blue program found the run dominated by ONE thing:
100///
101/// ```text
102/// parse 9.6 µs
103/// check 1.6 µs
104/// interpreter_hostless() 5 820 µs <- 98.4% of the run
105/// ```
106///
107/// Splitting that further: `Interpreter::new()` is 24 µs and
108/// `install_full_stdlib_with` is the rest — the stdlib was being rebuilt from
109/// scratch on every single `run()`, and blue's whole surface (`map`, `filter`,
110/// string ops) lives in it, so no program could avoid the cost.
111///
112/// `fork` already existed upstream for exactly this, and blue simply was not
113/// using it. tatara-lisp-eval's own `fork_cost.rs` opens with *"cheapness is
114/// the entire reason it exists"* — the capability was built, documented and
115/// guarded, and the consumer kept paying full price beside it.
116///
117/// | | per call |
118/// |---|---|
119/// | rebuild (`Interpreter::new` + `install_full_stdlib_with`) | **9.03 ms** |
120/// | `fork()` of a prebuilt base | **0.102 ms** |
121///
122/// **88× on the dominant cost.** This is purgatory's computation-layer clause
123/// made real: the stdlib is the most-reused computation in the language, and
124/// it was being discarded and recomputed rather than resurrected.
125///
126/// Isolation is `fork`'s contract, not an assumption made here — its
127/// correctness gates live upstream in `fork.rs`, and `fork_cost.rs` guards
128/// against a future change that deep-copies (which would keep every
129/// correctness test green while silently restoring the cost this removes).
130static HOSTLESS_BASE: std::sync::LazyLock<std::sync::Mutex<Interpreter<()>>> =
131 std::sync::LazyLock::new(|| std::sync::Mutex::new(interpreter(&mut ())));
132
133/// The common host-free case.
134///
135/// Forks the process-wide base rather than rebuilding the stdlib. Falls back to
136/// a full build if the lock is poisoned: a poisoned lock means another thread
137/// panicked mid-fork, and answering a correct-but-slow interpreter beats
138/// propagating someone else's panic into an unrelated caller.
139pub fn interpreter_hostless() -> Interpreter<()> {
140 match HOSTLESS_BASE.lock() {
141 Ok(base) => base.fork(),
142 Err(_) => interpreter(&mut ()),
143 }
144}
145
146/// Lift spanless forms into what the evaluator eats.
147///
148/// **No longer on the `blue run` path, and that is the point.**
149/// [`erase::erase_types`] now takes and returns `Spanned`, so
150/// `pipeline::run_in_surface` hands the evaluator the *parser's own* tree with
151/// the author's positions on it — there is nothing left to lift. This
152/// function survives for a caller that genuinely holds spanless `Sexp` and
153/// has no position to preserve, and as the subject of the two tests below
154/// that pin why the hop it replaced was unsafe.
155///
156/// `Interpreter::eval_program` takes `&[Spanned]`; blue's stages produced
157/// `Sexp`. Two callers bridged that gap by *printing the tree and reading it
158/// back* — `forms.map(ToString::to_string).join("\n")` into
159/// `tatara_lisp::read_spanned`. Both stopped, and the round trip is gone from
160/// the pipeline.
161///
162/// **Why it had to go.** Printing a tree we already hold and re-parsing it puts
163/// the reader's lexer between blue and its own output, for nothing — and the
164/// printer and the reader are **not inverses**. `Atom::Str`'s `Display` escapes
165/// its payload and its own docs explain at length why; the `Atom::Symbol` arm
166/// is a bare `write_str`. So a symbol whose text carries a separator prints as
167/// several tokens and reads back as several symbols: a well-formed tree with a
168/// different meaning, no error raised. Measured 2026-08-02 —
169/// `pipeline::tests::the_round_trip_is_not_the_identity_in_general` pins which
170/// separators are silent and which are loud. The only thing that kept this from
171/// biting was blue happening not to emit those bytes. A stage that never
172/// serialises cannot be mis-read.
173///
174/// **What is given up: spans.** The old path's spans pointed into the
175/// re-printed lisp text, a buffer no human ever wrote and no diagnostic could
176/// usefully cite — they were positions in blue's own output, not in the
177/// author's source. `Span::synthetic` says the same thing honestly.
178///
179/// **Carrying real blue-source spans through erasure was the separate piece of
180/// work, and it is done — but NOT the way this doc predicted.** It said the
181/// work "would start from `Spanned::from_sexp_at`". It did not, and could not:
182/// `from_sexp_at` is a *lift*, stamping ONE span across a whole subtree, so
183/// starting there would have replaced a tree of synthetic spans with a tree of
184/// identical wrong ones. The actual shape was to stop projecting in the first
185/// place — erasure walks `Spanned` and keeps each node's own span, because it
186/// only ever deletes (see [`erase`]). **A pointer at the nearest-looking API is
187/// how a reader is sent to the wrong starting point**; the note is corrected
188/// here rather than deleted, because the wrong lead was load-bearing enough to
189/// be worth naming.
190#[must_use]
191pub fn lower_to_spanned(forms: &[tatara_lisp::Sexp]) -> Vec<tatara_lisp::Spanned> {
192 forms
193 .iter()
194 .map(tatara_lisp::Spanned::from_sexp_synthetic)
195 .collect()
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201 use tatara_lisp_eval::Value;
202
203 fn eval(src: &str) -> Value {
204 let forms = tatara_lisp::read_spanned(src).expect("read");
205 let mut interp = interpreter_hostless();
206 interp.eval_program(&forms, &mut ()).expect("eval")
207 }
208
209 /// Every layer is present. A test that only checked layer 1 is exactly
210 /// what let the stdlib gap survive.
211 #[test]
212 fn both_layers_are_installed() {
213 // Layer 1: a Rust primitive.
214 assert!(matches!(eval("(+ 1 2)"), Value::Int(3)));
215 // Layer 2: a stdlib definition, which is the layer that was missing.
216 assert!(matches!(eval("(mod 7 3)"), Value::Int(1)));
217 assert!(matches!(eval("(inc 41)"), Value::Int(42)));
218 assert!(matches!(eval("(first (list 9 8))"), Value::Int(9)));
219 // Layer 3: blue's own core — string and number conversion.
220 assert!(matches!(eval(r#"(length "héllo")"#), Value::Int(5)));
221 // Layer 4: the JSON surface.
222 assert!(matches!(
223 eval(r#"(json_parse "{\"outcome\":\"ok\"}")"#),
224 Value::List(_)
225 ));
226 // Layer 4b: cryptography.
227 assert!(matches!(eval(r#"(blake3_hex "")"#), Value::Str(_)));
228 }
229
230 /// Anti-vacuity: a bare interpreter really does LACK layer 2, so the test
231 /// above is measuring the runtime's contribution and not a property the
232 /// interpreter has for free.
233 #[test]
234 fn a_bare_interpreter_lacks_the_stdlib() {
235 let forms = tatara_lisp::read_spanned("(mod 7 3)").expect("read");
236 let mut bare = Interpreter::new();
237 tatara_lisp_eval::install_primitives(&mut bare);
238 assert!(
239 bare.eval_program(&forms, &mut ()).is_err(),
240 "if a bare interpreter already resolved `mod`, this crate would be measuring nothing"
241 );
242 }
243}