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