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