Skip to main content

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 docs;
36pub mod domain;
37pub mod erase;
38pub mod hosted;
39pub mod inputs;
40pub mod json;
41pub mod messages;
42pub mod pipeline;
43pub mod stdlib;
44#[cfg(feature = "sys")]
45pub mod sys;
46pub mod uses;
47
48pub use erase::{erase_types, to_sexps};
49pub use inputs::{declarations, install_input_primitives, Declaration, InputError, Inputs};
50pub use pipeline::{
51    parse, parse_tree_with_depth, parse_with_depth, run, run_with_inputs, Run, RunError,
52};
53pub use stdlib::install_blue_stdlib;
54
55use tatara_lisp_eval::{install_full_stdlib_with, Interpreter};
56
57/// Build an interpreter with the complete blue runtime installed.
58///
59/// This is the *only* sanctioned way to obtain one. A caller that builds an
60/// `Interpreter` directly gets a partial runtime, and the failure shows up as
61/// an unbound symbol at the far end of a program.
62pub fn interpreter<H: 'static>(host: &mut H) -> Interpreter<H> {
63    let mut interp = Interpreter::new();
64    // The FULL substrate, not just `install_primitives`.
65    //
66    // blue called `install_primitives` + `install_lisp_stdlib_with` and got
67    // neither `install_hof` nor `install_map` — so `map`, `filter`, `fold` and
68    // every map literal were UNBOUND SYMBOLS. A language with no higher-order
69    // functions, in a workspace whose whole surface is Ruby's.
70    //
71    // Same shape as the stdlib gap this crate was created to fix: the substrate
72    // has layers, and naming them one at a time is how one gets missed. Call
73    // the composed installer.
74    install_full_stdlib_with(&mut interp, host);
75    // Layer 3: blue's own core — strings and number conversion, which
76    // tatara-lisp does not carry at all. See `stdlib` for why the
77    // character-counting semantics are blue's rather than the substrate's.
78    stdlib::install_blue_stdlib(&mut interp);
79    // Layer 4: blue's JSON surface — parse, stringify, read. Pure
80    // computation, no host imports, so it is installed unconditionally; the
81    // `wasm32-unknown-unknown` consumer keeps it. See `json` for why objects
82    // arrive as alists rather than Maps.
83    json::install_json_stdlib(&mut interp);
84    // Layer 4b: cryptography — BLAKE3 and Ed25519. Pure for the same reason
85    // JSON is: a deterministic function of its arguments, with the keypair's
86    // seed supplied by the caller rather than drawn from an entropy source,
87    // so it lowers to no import and the wasm consumer keeps it. See `crypto`.
88    crypto::install_crypto_stdlib(&mut interp);
89    // Layer 5: the host-side system surface — process, filesystem, env,
90    // clock. Feature-gated: every sys primitive is a host import, so the
91    // wasm consumer (which builds with `sys` OFF) keeps its zero-host-import
92    // surface by construction. Only the CLI turns it on.
93    #[cfg(feature = "sys")]
94    sys::install_sys_stdlib(&mut interp);
95    // Last, so installing the stdlib is not metered against the program.
96    apply_execution_bounds(&mut interp);
97    interp
98}
99
100/// The execution bounds every interpreter this crate builds runs under.
101static EXECUTION_BOUNDS: std::sync::OnceLock<ExecutionBounds> = std::sync::OnceLock::new();
102
103/// How much a blue program may do before it is refused: nested calls and
104/// evaluation steps.
105///
106/// Both are BOUNDS in the sense `blue-lang-cli`'s `config` module admits: a
107/// terminating program under bounds above its cost returns the same value, and
108/// one that exceeds either is refused with a catchable `depth-exceeded` or
109/// `fuel-exhausted` error naming the limit and the function — never a process
110/// abort, which is what exceeding the host stack was before tatara-lisp-eval
111/// 0.3.63. The walker and the VM run under the same bounds and refuse with the
112/// same message.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct ExecutionBounds {
115    /// Nested (non-tail) calls alive at once. Tail calls do not count.
116    pub max_call_depth: usize,
117    /// Evaluation steps per run; `None` is unbounded.
118    pub max_steps: Option<usize>,
119}
120
121impl ExecutionBounds {
122    /// Depth at tatara-lisp-eval's `DEFAULT_MAX_DEPTH`, steps unbounded.
123    ///
124    /// The two defaults differ for one reason: whether a program that works
125    /// today keeps working. A recursion past 100k frames never worked — it
126    /// aborted the process — so bounding depth removes no behaviour. A run
127    /// longer than any finite step count did work (simulations, tools on
128    /// nodes), so a default step bound would remove it; for a few hours of
129    /// 2026-09-29 blue shipped 50M (~3 s) and did exactly that. A host that
130    /// runs code it did not write, or a test that must see a runaway end,
131    /// sets `max_steps` itself.
132    pub const DEFAULT: Self = Self {
133        max_call_depth: tatara_lisp_eval::vm::DEFAULT_MAX_DEPTH,
134        max_steps: None,
135    };
136}
137
138/// Name the bounds for this process. The CLI calls this once with the resolved
139/// `BlueConfig`, before any interpreter is built; an embedder that never calls
140/// it runs under [`ExecutionBounds::DEFAULT`]. Only the first call counts,
141/// like `sys::set_program_args`.
142pub fn set_execution_bounds(bounds: ExecutionBounds) {
143    let _ = EXECUTION_BOUNDS.set(bounds);
144}
145
146/// The bounds interpreters are built with.
147#[must_use]
148pub fn execution_bounds() -> ExecutionBounds {
149    EXECUTION_BOUNDS
150        .get()
151        .copied()
152        .unwrap_or(ExecutionBounds::DEFAULT)
153}
154
155fn apply_execution_bounds<H: 'static>(interp: &mut Interpreter<H>) {
156    let b = execution_bounds();
157    // No quantum, so the tree-walker refuses nothing of this budget.
158    let _ = interp.set_budget(tatara_lisp_eval::vm::Budget {
159        fuel: b.max_steps,
160        max_depth: Some(b.max_call_depth),
161        quantum: None,
162    });
163}
164
165/// The prebuilt hostless substrate, built once per process.
166///
167/// **Measured 2026-08-01, and this is the entire reason the fork exists.**
168/// Profiling a trivial blue program found the run dominated by ONE thing:
169///
170/// ```text
171/// parse                     9.6 µs
172/// check                     1.6 µs
173/// interpreter_hostless()  5 820 µs   <- 98.4% of the run
174/// ```
175///
176/// Splitting that further: `Interpreter::new()` is 24 µs and
177/// `install_full_stdlib_with` is the rest — the stdlib was being rebuilt from
178/// scratch on every single `run()`, and blue's whole surface (`map`, `filter`,
179/// string ops) lives in it, so no program could avoid the cost.
180///
181/// `fork` already existed upstream for exactly this, and blue simply was not
182/// using it. tatara-lisp-eval's own `fork_cost.rs` opens with *"cheapness is
183/// the entire reason it exists"* — the capability was built, documented and
184/// guarded, and the consumer kept paying full price beside it.
185///
186/// | | per call |
187/// |---|---|
188/// | rebuild (`Interpreter::new` + `install_full_stdlib_with`) | **9.03 ms** |
189/// | `fork()` of a prebuilt base | **0.102 ms** |
190///
191/// **88× on the dominant cost.** This is purgatory's computation-layer clause
192/// made real: the stdlib is the most-reused computation in the language, and
193/// it was being discarded and recomputed rather than resurrected.
194///
195/// Isolation is `fork`'s contract, not an assumption made here — its
196/// correctness gates live upstream in `fork.rs`, and `fork_cost.rs` guards
197/// against a future change that deep-copies (which would keep every
198/// correctness test green while silently restoring the cost this removes).
199static HOSTLESS_BASE: std::sync::LazyLock<std::sync::Mutex<Interpreter<()>>> =
200    std::sync::LazyLock::new(|| std::sync::Mutex::new(interpreter(&mut ())));
201
202/// The common host-free case.
203///
204/// Forks the process-wide base rather than rebuilding the stdlib. Falls back to
205/// a full build if the lock is poisoned: a poisoned lock means another thread
206/// panicked mid-fork, and answering a correct-but-slow interpreter beats
207/// propagating someone else's panic into an unrelated caller.
208pub fn interpreter_hostless() -> Interpreter<()> {
209    let mut interp = match HOSTLESS_BASE.lock() {
210        Ok(base) => base.fork(),
211        Err(_) => interpreter(&mut ()),
212    };
213    // Again after the fork: the base may have been built before the bounds
214    // were named, and a fork inherits whatever its base had.
215    apply_execution_bounds(&mut interp);
216    interp
217}
218
219/// Lift spanless forms into what the evaluator eats.
220///
221/// **No longer on the `blue run` path, and that is the point.**
222/// [`erase::erase_types`] now takes and returns `Spanned`, so
223/// `pipeline::run_in_surface` hands the evaluator the *parser's own* tree with
224/// the author's positions on it — there is nothing left to lift. This
225/// function survives for a caller that genuinely holds spanless `Sexp` and
226/// has no position to preserve, and as the subject of the two tests below
227/// that pin why the hop it replaced was unsafe.
228///
229/// `Interpreter::eval_program` takes `&[Spanned]`; blue's stages produced
230/// `Sexp`. Two callers bridged that gap by *printing the tree and reading it
231/// back* — `forms.map(ToString::to_string).join("\n")` into
232/// `tatara_lisp::read_spanned`. Both stopped, and the round trip is gone from
233/// the pipeline.
234///
235/// **Why it had to go.** Printing a tree we already hold and re-parsing it puts
236/// the reader's lexer between blue and its own output, for nothing — and the
237/// printer and the reader are **not inverses**. `Atom::Str`'s `Display` escapes
238/// its payload and its own docs explain at length why; the `Atom::Symbol` arm
239/// is a bare `write_str`. So a symbol whose text carries a separator prints as
240/// several tokens and reads back as several symbols: a well-formed tree with a
241/// different meaning, no error raised. Measured 2026-08-02 —
242/// `pipeline::tests::the_round_trip_is_not_the_identity_in_general` pins which
243/// separators are silent and which are loud. The only thing that kept this from
244/// biting was blue happening not to emit those bytes. A stage that never
245/// serialises cannot be mis-read.
246///
247/// **What is given up: spans.** The old path's spans pointed into the
248/// re-printed lisp text, a buffer no human ever wrote and no diagnostic could
249/// usefully cite — they were positions in blue's own output, not in the
250/// author's source. `Span::synthetic` says the same thing honestly.
251///
252/// **Carrying real blue-source spans through erasure was the separate piece of
253/// work, and it is done — but NOT the way this doc predicted.** It said the
254/// work "would start from `Spanned::from_sexp_at`". It did not, and could not:
255/// `from_sexp_at` is a *lift*, stamping ONE span across a whole subtree, so
256/// starting there would have replaced a tree of synthetic spans with a tree of
257/// identical wrong ones. The actual shape was to stop projecting in the first
258/// place — erasure walks `Spanned` and keeps each node's own span, because it
259/// only ever deletes (see [`erase`]). **A pointer at the nearest-looking API is
260/// how a reader is sent to the wrong starting point**; the note is corrected
261/// here rather than deleted, because the wrong lead was load-bearing enough to
262/// be worth naming.
263#[must_use]
264pub fn lower_to_spanned(forms: &[tatara_lisp::Sexp]) -> Vec<tatara_lisp::Spanned> {
265    forms
266        .iter()
267        .map(tatara_lisp::Spanned::from_sexp_synthetic)
268        .collect()
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use tatara_lisp_eval::Value;
275
276    fn eval(src: &str) -> Value {
277        let forms = tatara_lisp::read_spanned(src).expect("read");
278        let mut interp = interpreter_hostless();
279        interp.eval_program(&forms, &mut ()).expect("eval")
280    }
281
282    /// Every layer is present. A test that only checked layer 1 is exactly
283    /// what let the stdlib gap survive.
284    #[test]
285    fn both_layers_are_installed() {
286        // Layer 1: a Rust primitive.
287        assert!(matches!(eval("(+ 1 2)"), Value::Int(3)));
288        // Layer 2: a stdlib definition, which is the layer that was missing.
289        assert!(matches!(eval("(mod 7 3)"), Value::Int(1)));
290        assert!(matches!(eval("(inc 41)"), Value::Int(42)));
291        assert!(matches!(eval("(first (list 9 8))"), Value::Int(9)));
292        // Layer 3: blue's own core — string and number conversion.
293        assert!(matches!(eval(r#"(length "héllo")"#), Value::Int(5)));
294        // Layer 4: the JSON surface.
295        assert!(matches!(
296            eval(r#"(json_parse "{\"outcome\":\"ok\"}")"#),
297            Value::List(_)
298        ));
299        // Layer 4b: cryptography.
300        assert!(matches!(eval(r#"(blake3_hex "")"#), Value::Str(_)));
301    }
302
303    /// Anti-vacuity: a bare interpreter really does LACK layer 2, so the test
304    /// above is measuring the runtime's contribution and not a property the
305    /// interpreter has for free.
306    #[test]
307    fn a_bare_interpreter_lacks_the_stdlib() {
308        let forms = tatara_lisp::read_spanned("(mod 7 3)").expect("read");
309        let mut bare = Interpreter::new();
310        tatara_lisp_eval::install_primitives(&mut bare);
311        assert!(
312            bare.eval_program(&forms, &mut ()).is_err(),
313            "if a bare interpreter already resolved `mod`, this crate would be measuring nothing"
314        );
315    }
316}