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;
61#[cfg(feature = "sys")]
62pub mod provide;
63pub mod receipt;
64pub mod session;
65pub mod spread;
66pub mod stdlib;
67#[cfg(feature = "sys")]
68pub mod sys;
69pub mod timings;
70pub mod uses;
71pub mod xml;
72
73pub use erase::{erase_types, to_sexps};
74pub use inputs::{declarations, install_input_primitives, Declaration, InputError, Inputs};
75pub use pipeline::{
76 parse, parse_tree_with_depth, parse_with_depth, run, run_with_inputs, Run, RunError,
77};
78pub use stdlib::install_blue_stdlib;
79
80pub use blue_lang_proc::{Frame, HostIo, Identities, Receipt};
81
82use tatara_lisp_eval::{install_full_stdlib_with, Interpreter};
83
84/// Build an interpreter with the complete blue runtime installed.
85///
86/// This is the *only* sanctioned way to obtain one. A caller that builds an
87/// `Interpreter` directly gets a partial runtime, and the failure shows up as
88/// an unbound symbol at the far end of a program.
89pub fn interpreter<H: 'static>(host: &mut H) -> Interpreter<H> {
90 let mut interp = Interpreter::new();
91 // The FULL substrate, not just `install_primitives`.
92 //
93 // blue called `install_primitives` + `install_lisp_stdlib_with` and got
94 // neither `install_hof` nor `install_map` — so `map`, `filter`, `fold` and
95 // every map literal were UNBOUND SYMBOLS. A language with no higher-order
96 // functions, in a workspace whose whole surface is Ruby's.
97 //
98 // Same shape as the stdlib gap this crate was created to fix: the substrate
99 // has layers, and naming them one at a time is how one gets missed. Call
100 // the composed installer.
101 install_full_stdlib_with(&mut interp, host);
102 // Layer 3: blue's own core — strings and number conversion, which
103 // tatara-lisp does not carry at all. See `stdlib` for why the
104 // character-counting semantics are blue's rather than the substrate's.
105 stdlib::install_blue_stdlib(&mut interp);
106 // Layer 4: blue's JSON surface — parse, stringify, read. Pure
107 // computation, no host imports, so it is installed unconditionally; the
108 // `wasm32-unknown-unknown` consumer keeps it. See `json` for why objects
109 // arrive as alists rather than Maps.
110 json::install_json_stdlib(&mut interp);
111 // Layer 4b: cryptography — BLAKE3 and Ed25519. Pure for the same reason
112 // JSON is: a deterministic function of its arguments, with the keypair's
113 // seed supplied by the caller rather than drawn from an entropy source,
114 // so it lowers to no import and the wasm consumer keeps it. See `crypto`.
115 crypto::install_crypto_stdlib(&mut interp);
116 nix::install_nix_stdlib(&mut interp);
117 xml::install_xml_stdlib(&mut interp);
118 // Layer 5: the host-side system surface — process, filesystem, env,
119 // clock, network. Feature-gated: every sys primitive is a host import, so the
120 // wasm consumer (which builds with `sys` OFF) keeps its zero-host-import
121 // surface by construction. Only the CLI turns it on.
122 #[cfg(feature = "sys")]
123 sys::install_sys_stdlib(&mut interp);
124 // Layer 6: processes. Bound here so every name oracle built from this
125 // interpreter (the check stage, the LSP, `blue reference`) knows them.
126 attach_node(&mut interp);
127 // Last, so installing the stdlib is not metered against the program.
128 apply_execution_bounds(&mut interp);
129 interp
130}
131
132/// Give `interp` a process node of its own: its program becomes the node's
133/// root, and `spawn` starts processes in this node and no other.
134///
135/// [`interpreter_hostless`] calls it on every fork, so two programs never
136/// share processes. A door that forks an interpreter per unit of work (a test
137/// per fork) calls it on each fork for the same reason.
138pub fn attach_node<H: 'static>(interp: &mut Interpreter<H>) {
139 dispatch::install(interp);
140 blue_lang_proc::install(interp, blue_lang_proc::Node::new(node_config()));
141}
142
143/// [`attach_node`] for a program that runs under `frame`: every process it
144/// starts is held to the same frame, so a host name the program may not call
145/// is refused in its children too. Without this a spawned child would run on
146/// the full runtime and a frame would be one `spawn` away from meaningless.
147pub fn attach_node_in_frame<H: 'static>(interp: &mut Interpreter<H>, frame: &blue_lang_waku::Waku) {
148 attach_node_held(interp, &Hold::from(frame.clone()));
149}
150
151/// [`attach_node_in_frame`] with the hold's providers bound in every child.
152pub fn attach_node_held<H: 'static>(interp: &mut Interpreter<H>, hold: &Hold) {
153 attach_node_accounted(interp, Some(hold), &Account::default());
154}
155
156/// Give `interp` a node whose processes are held to `hold`, when there is
157/// one, and give `account` of them: each child's host calls tally into its
158/// ledger, its identities name each trace's and receipt's definition, and
159/// with a receipts directory every held process writes a receipt there when
160/// an incarnation ends.
161pub fn attach_node_accounted<H: 'static>(
162 interp: &mut Interpreter<H>,
163 hold: Option<&Hold>,
164 account: &Account,
165) {
166 let mut config = node_config();
167 config.host_io = account.host_io.clone();
168 config.identities = account.identities.clone();
169 if let Some(hold) = hold {
170 config.frame = Some(hold.frame());
171 config.receipts = account.receipts.clone().map(receipt::sink);
172 let held = hold.clone();
173 let io = account.host_io.clone();
174 config.child = std::sync::Arc::new(move || {
175 let mut child = child_interpreter();
176 held.bind(&mut child, "this process's frame", &io);
177 child
178 });
179 }
180 dispatch::install(interp);
181 blue_lang_proc::install(interp, blue_lang_proc::Node::new(config));
182}
183
184/// The account a run gives of itself besides its value, filled while it runs
185/// and read after it ends, whether it returned or raised.
186#[derive(Clone, Default)]
187pub struct Account {
188 /// Host calls through granted host names, per process.
189 pub host_io: HostIo,
190 /// Each definition's `def_hash`, and the run's under [`receipt::RUN`].
191 pub identities: Identities,
192 /// How the identities are computed from the program, once it is lowered.
193 /// Without one, no trace or receipt names a `def_hash`.
194 pub identify: Option<Identify>,
195 /// Where each held process writes its receipt; none are written without.
196 pub receipts: Option<std::path::PathBuf>,
197}
198
199/// The table of a lowered program's identities, computed when first asked.
200pub type Identified =
201 Box<dyn FnOnce() -> std::collections::BTreeMap<String, String> + Send + 'static>;
202
203/// Given a checked program, its lowered tree and the key of the entry's
204/// `main` if it has one: each definition key with its `def_hash`, and
205/// [`receipt::RUN`] with the run's, computed only when first asked.
206/// `blue-lang-mondou` computes it; this crate only calls it.
207pub type Identify = fn(
208 &uses::ResolvedProgram,
209 std::sync::Arc<Vec<tatara_lisp::Spanned>>,
210 Option<String>,
211) -> Identified;
212
213/// What a run is held to: the frame it may reach the host through, and the
214/// capabilities pure providers stand in for.
215#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct Hold {
217 pub frame: blue_lang_waku::Waku,
218 pub provisions: blue_lang_waku::Provisions,
219}
220
221impl From<blue_lang_waku::Waku> for Hold {
222 fn from(frame: blue_lang_waku::Waku) -> Self {
223 Self {
224 frame,
225 provisions: blue_lang_waku::Provisions::default(),
226 }
227 }
228}
229
230/// The name a scoped provider binds the host name `word` under. No blue
231/// source can write it, so only the references [`Hold::rebind_scoped`] moves
232/// onto it reach the provider.
233#[must_use]
234pub fn provided_name(word: &str) -> String {
235 format!("%provided/{word}")
236}
237
238impl Hold {
239 /// Every host capability neither the frame grants nor a whole-program
240 /// provider stands in for. A scoped provider's capability stays here:
241 /// code outside its packages gets the frame's answer.
242 #[must_use]
243 pub fn withheld(&self) -> Vec<blue_lang_waku::Capability> {
244 let reach = self.provisions.widen(&self.frame.reach);
245 blue_lang_waku::Capability::host_effects()
246 .into_iter()
247 .filter(|cap| !reach.grants(*cap))
248 .collect()
249 }
250
251 /// Every host capability a call can reach the host through: granted by
252 /// the frame, and no whole-program provider standing in for it. A scoped
253 /// provider's capability the frame grants is here: code outside its
254 /// packages reaches the host.
255 #[must_use]
256 pub fn granted(&self) -> Vec<blue_lang_waku::Capability> {
257 blue_lang_waku::Capability::host_effects()
258 .into_iter()
259 .filter(|cap| {
260 self.frame.reach.grants(*cap)
261 && self.provisions.get(*cap).is_none_or(|p| p.scope.is_some())
262 })
263 .collect()
264 }
265
266 /// Every host name neither the frame grants nor a whole-program provider
267 /// stands in for. A scoped provider's names stay here: code outside its
268 /// packages gets the frame's answer.
269 #[must_use]
270 pub fn withheld_host_names(&self) -> Vec<(&'static str, blue_lang_waku::Capability)> {
271 names_of(self.withheld())
272 }
273
274 /// Every host name a call can reach the host through.
275 #[must_use]
276 pub fn granted_host_names(&self) -> Vec<(&'static str, blue_lang_waku::Capability)> {
277 names_of(self.granted())
278 }
279
280 /// The hold as an artifact names it.
281 #[must_use]
282 pub fn frame(&self) -> Frame {
283 Frame {
284 granted: self.granted(),
285 provided: self.provisions.iter().cloned().collect(),
286 withheld: self.withheld(),
287 }
288 }
289
290 /// The frame block of a receipt for a run held here that made `host_io`
291 /// host calls: exactly `{"granted":[…],"withheld":[…],"host_io":n}`.
292 #[must_use]
293 pub fn frame_summary(&self, host_io: u64) -> serde_json::Value {
294 self.frame().block(host_io)
295 }
296
297 /// Bind the hold into `interp`: a breach for every withheld host name,
298 /// then each whole-program provider over its capability's names and each
299 /// scoped one under [`provided_name`], then a shim over every granted
300 /// host name that tallies each call into `io`. A withheld or provided
301 /// name gets no shim, so a pure frame tallies nothing.
302 pub fn bind<H: 'static>(&self, interp: &mut Interpreter<H>, who: &'static str, io: &HostIo) {
303 refuse_host_names(interp, &self.withheld_host_names(), who);
304 #[cfg(feature = "sys")]
305 provide::provide(interp, &self.provisions);
306 count_host_names(interp, &self.granted_host_names(), io);
307 }
308
309 /// Move each scoped provider's host names, where a file of a package it
310 /// serves writes them in `forms`, onto [`provided_name`]. A provider
311 /// serves the packages its `for:` names and every package they `use`, by
312 /// the imports `program` resolved; `forms` is `program`'s evaluated tree,
313 /// top-level form for top-level form. Returns the host names the entry
314 /// file may not write: [`Hold::withheld_host_names`] less those a scoped
315 /// provider serves the entry's own package.
316 pub fn rebind_scoped(
317 &self,
318 program: &uses::ResolvedProgram,
319 forms: &mut [tatara_lisp::Spanned],
320 ) -> Vec<(&'static str, blue_lang_waku::Capability)> {
321 let served: Vec<(
322 blue_lang_waku::Capability,
323 std::collections::BTreeSet<String>,
324 )> = self
325 .provisions
326 .scoped()
327 .map(|(cap, named)| (cap, program.reached_from(named)))
328 .collect();
329 let serves = |package: Option<&str>, cap: blue_lang_waku::Capability| {
330 package.is_some_and(|p| served.iter().any(|(c, s)| *c == cap && s.contains(p)))
331 };
332 if !served.is_empty() {
333 uses::rename_written(program, forms, &|package, name| {
334 let cap = blue_lang_waku::Provision::capability_of(name)?;
335 serves(package, cap).then(|| provided_name(name))
336 });
337 }
338 let entry = program
339 .file(uses::ResolvedProgram::ENTRY)
340 .and_then(|f| f.package.as_deref());
341 self.withheld_host_names()
342 .into_iter()
343 .filter(|(_, cap)| !serves(entry, *cap))
344 .collect()
345 }
346}
347
348fn names_of(
349 caps: Vec<blue_lang_waku::Capability>,
350) -> Vec<(&'static str, blue_lang_waku::Capability)> {
351 caps.into_iter()
352 .flat_map(|cap| cap.names().into_iter().map(move |n| (n, cap)))
353 .collect()
354}
355
356/// Shim each of `granted` that `interp` defines so a call that reaches it
357/// tallies one host call into `io`. The shim is registered under its own
358/// name and the host name rebound to it, so the original stays reachable by
359/// its name and reports its own arity errors.
360fn count_host_names<H: 'static>(
361 interp: &mut Interpreter<H>,
362 granted: &[(&'static str, blue_lang_waku::Capability)],
363 io: &HostIo,
364) {
365 for &(name, _) in granted {
366 let Some(original @ tatara_lisp_eval::Value::NativeFn(_)) = interp.lookup_global(name)
367 else {
368 continue;
369 };
370 let tatara_lisp_eval::Value::NativeFn(nf) = &original else {
371 continue;
372 };
373 let arity = nf.arity;
374 let io = io.clone();
375 let shim = format!("%io:{name}");
376 interp.register_higher_order_fn(
377 shim.clone(),
378 tatara_lisp_eval::ffi::Arity::Any,
379 move |args: &[tatara_lisp_eval::Value],
380 host: &mut H,
381 caller: &tatara_lisp_eval::ffi::Caller<H>,
382 span| {
383 if arity.check(args.len()).is_ok() {
384 io.tally();
385 }
386 caller.apply_value(&original, args.to_vec(), host, span)
387 },
388 );
389 if let Some(v) = interp.lookup_global(&shim) {
390 interp.define_global(name, v);
391 }
392 }
393}
394
395/// Every host name `frame` does not grant, with its capability.
396#[must_use]
397pub fn ungranted_host_names(
398 frame: &blue_lang_waku::Waku,
399) -> Vec<(&'static str, blue_lang_waku::Capability)> {
400 Hold::from(frame.clone()).withheld_host_names()
401}
402
403/// The kind of the fatal error a capability breach raises.
404pub const BREACH: &str = "capability-breach";
405
406/// The exit status a run that ended on a capability breach returns:
407/// `EX_NOPERM` (sysexits.h). `blue run` and an appliance both answer it.
408pub const BREACH_EXIT: u8 = 77;
409
410/// The fatal error a call to `name` raises when `who` does not grant `cap`.
411/// No `rescue` catches it: the run ends.
412#[must_use]
413pub fn breach(
414 name: &str,
415 cap: blue_lang_waku::Capability,
416 who: &str,
417 at: tatara_lisp::Span,
418) -> tatara_lisp_eval::EvalError {
419 tatara_lisp_eval::EvalError::fatal(
420 BREACH,
421 format!(
422 "`{name}` reaches the host ({}), which {who} does not grant",
423 cap.label()
424 ),
425 at,
426 )
427}
428
429/// Is `e` a capability breach?
430#[must_use]
431pub fn is_breach(e: &tatara_lisp_eval::EvalError) -> bool {
432 matches!(e, tatara_lisp_eval::EvalError::Fatal { kind, .. } if &**kind == BREACH)
433}
434
435/// Bind each of `refused` that `interp` defines to a breach naming `who`.
436pub fn refuse_host_names<H: 'static>(
437 interp: &mut Interpreter<H>,
438 refused: &[(&'static str, blue_lang_waku::Capability)],
439 who: &'static str,
440) {
441 refuse_host_names_noting(interp, refused, who, |_, _, _| {});
442}
443
444/// [`refuse_host_names`], calling `note` with the host, the capability and
445/// the name before each breach is raised.
446pub fn refuse_host_names_noting<H: 'static>(
447 interp: &mut Interpreter<H>,
448 refused: &[(&'static str, blue_lang_waku::Capability)],
449 who: &'static str,
450 note: fn(&mut H, blue_lang_waku::Capability, &'static str),
451) {
452 for &(name, cap) in refused {
453 if interp.lookup_global(name).is_none() {
454 continue;
455 }
456 interp.register_fn(
457 name,
458 tatara_lisp_eval::ffi::Arity::Any,
459 move |_: &[tatara_lisp_eval::Value], host: &mut H, span| {
460 note(host, cap, name);
461 Err(breach(name, cap, who, span))
462 },
463 );
464 }
465}
466
467/// The node every interpreter's processes run under: the execution bounds
468/// per incarnation, a scheduling quantum, and the host's clock when there is
469/// a host (a node with no host has a virtual clock: time passes only when
470/// every process waits).
471fn node_config() -> blue_lang_proc::NodeConfig {
472 let b = execution_bounds();
473 let mut config = blue_lang_proc::NodeConfig::new(std::sync::Arc::new(child_interpreter));
474 config.budget = tatara_lisp_eval::vm::Budget {
475 fuel: b.max_steps,
476 max_depth: Some(b.max_call_depth),
477 quantum: Some(blue_lang_proc::node::DEFAULT_QUANTUM),
478 };
479 config.clock = if cfg!(feature = "sys") {
480 blue_lang_proc::ClockKind::Real
481 } else {
482 blue_lang_proc::ClockKind::Virtual
483 };
484 config
485}
486
487/// A fresh interpreter for a child process: the hostless base, forked. The
488/// node adds its child words to it.
489fn child_interpreter() -> Interpreter<()> {
490 let mut interp = match HOSTLESS_BASE.lock() {
491 Ok(base) => base.fork(),
492 Err(_) => interpreter(&mut ()),
493 };
494 apply_execution_bounds(&mut interp);
495 interp
496}
497
498/// The execution bounds every interpreter this crate builds runs under.
499static EXECUTION_BOUNDS: std::sync::OnceLock<ExecutionBounds> = std::sync::OnceLock::new();
500
501/// How much a blue program may do before it is refused: nested calls and
502/// evaluation steps.
503///
504/// Both are BOUNDS in the sense `blue-lang-cli`'s `config` module admits: a
505/// terminating program under bounds above its cost returns the same value, and
506/// one that exceeds either is refused with a catchable `depth-exceeded` or
507/// `fuel-exhausted` error naming the limit and the function — never a process
508/// abort, which is what exceeding the host stack was before tatara-lisp-eval
509/// 0.3.63. The walker and the VM run under the same bounds and refuse with the
510/// same message.
511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
512pub struct ExecutionBounds {
513 /// Nested (non-tail) calls alive at once. Tail calls do not count.
514 pub max_call_depth: usize,
515 /// Evaluation steps per run; `None` is unbounded.
516 pub max_steps: Option<usize>,
517}
518
519impl ExecutionBounds {
520 /// Depth at tatara-lisp-eval's `DEFAULT_MAX_DEPTH`, steps unbounded.
521 ///
522 /// The two defaults differ for one reason: whether a program that works
523 /// today keeps working. A recursion past 100k frames never worked — it
524 /// aborted the process — so bounding depth removes no behaviour. A run
525 /// longer than any finite step count did work (simulations, tools on
526 /// nodes), so a default step bound would remove it; for a few hours of
527 /// 2026-09-29 blue shipped 50M (~3 s) and did exactly that. A host that
528 /// runs code it did not write, or a test that must see a runaway end,
529 /// sets `max_steps` itself.
530 pub const DEFAULT: Self = Self {
531 max_call_depth: tatara_lisp_eval::vm::DEFAULT_MAX_DEPTH,
532 max_steps: None,
533 };
534}
535
536/// Name the bounds for this process. The CLI calls this once with the resolved
537/// `BlueConfig`, before any interpreter is built; an embedder that never calls
538/// it runs under [`ExecutionBounds::DEFAULT`]. Only the first call counts,
539/// like `sys::set_program_args`.
540pub fn set_execution_bounds(bounds: ExecutionBounds) {
541 let _ = EXECUTION_BOUNDS.set(bounds);
542}
543
544/// The bounds interpreters are built with.
545#[must_use]
546pub fn execution_bounds() -> ExecutionBounds {
547 EXECUTION_BOUNDS
548 .get()
549 .copied()
550 .unwrap_or(ExecutionBounds::DEFAULT)
551}
552
553fn apply_execution_bounds<H: 'static>(interp: &mut Interpreter<H>) {
554 let b = execution_bounds();
555 // No quantum, so the tree-walker refuses nothing of this budget.
556 let _ = interp.set_budget(tatara_lisp_eval::vm::Budget {
557 fuel: b.max_steps,
558 max_depth: Some(b.max_call_depth),
559 quantum: None,
560 });
561}
562
563/// The prebuilt hostless substrate, built once per process.
564///
565/// **Measured 2026-08-01, and this is the entire reason the fork exists.**
566/// Profiling a trivial blue program found the run dominated by ONE thing:
567///
568/// ```text
569/// parse 9.6 µs
570/// check 1.6 µs
571/// interpreter_hostless() 5 820 µs <- 98.4% of the run
572/// ```
573///
574/// Splitting that further: `Interpreter::new()` is 24 µs and
575/// `install_full_stdlib_with` is the rest — the stdlib was being rebuilt from
576/// scratch on every single `run()`, and blue's whole surface (`map`, `filter`,
577/// string ops) lives in it, so no program could avoid the cost.
578///
579/// `fork` already existed upstream for exactly this, and blue simply was not
580/// using it. tatara-lisp-eval's own `fork_cost.rs` opens with *"cheapness is
581/// the entire reason it exists"* — the capability was built, documented and
582/// guarded, and the consumer kept paying full price beside it.
583///
584/// | | per call |
585/// |---|---|
586/// | rebuild (`Interpreter::new` + `install_full_stdlib_with`) | **9.03 ms** |
587/// | `fork()` of a prebuilt base | **0.102 ms** |
588///
589/// **88× on the dominant cost.** This is purgatory's computation-layer clause
590/// made real: the stdlib is the most-reused computation in the language, and
591/// it was being discarded and recomputed rather than resurrected.
592///
593/// Isolation is `fork`'s contract, not an assumption made here — its
594/// correctness gates live upstream in `fork.rs`, and `fork_cost.rs` guards
595/// against a future change that deep-copies (which would keep every
596/// correctness test green while silently restoring the cost this removes).
597static HOSTLESS_BASE: std::sync::LazyLock<std::sync::Mutex<Interpreter<()>>> =
598 std::sync::LazyLock::new(|| {
599 std::sync::Mutex::new(timings::stage(timings::Stage::Runtime, || {
600 interpreter(&mut ())
601 }))
602 });
603
604/// The common host-free case.
605///
606/// Forks the process-wide base rather than rebuilding the stdlib. Falls back to
607/// a full build if the lock is poisoned: a poisoned lock means another thread
608/// panicked mid-fork, and answering a correct-but-slow interpreter beats
609/// propagating someone else's panic into an unrelated caller.
610pub fn interpreter_hostless() -> Interpreter<()> {
611 let mut interp = match HOSTLESS_BASE.lock() {
612 Ok(base) => base.fork(),
613 Err(_) => interpreter(&mut ()),
614 };
615 // Again after the fork: the base may have been built before the bounds
616 // were named, and a fork inherits whatever its base had.
617 apply_execution_bounds(&mut interp);
618 // A node per fork: the base's own node would be shared by every program.
619 attach_node(&mut interp);
620 interp
621}
622
623/// Lift spanless forms into what the evaluator eats.
624///
625/// **No longer on the `blue run` path, and that is the point.**
626/// [`erase::erase_types`] now takes and returns `Spanned`, so
627/// `pipeline::run_in_surface` hands the evaluator the *parser's own* tree with
628/// the author's positions on it — there is nothing left to lift. This
629/// function survives for a caller that genuinely holds spanless `Sexp` and
630/// has no position to preserve, and as the subject of the two tests below
631/// that pin why the hop it replaced was unsafe.
632///
633/// `Interpreter::eval_program` takes `&[Spanned]`; blue's stages produced
634/// `Sexp`. Two callers bridged that gap by *printing the tree and reading it
635/// back* — `forms.map(ToString::to_string).join("\n")` into
636/// `tatara_lisp::read_spanned`. Both stopped, and the round trip is gone from
637/// the pipeline.
638///
639/// **Why it had to go.** Printing a tree we already hold and re-parsing it puts
640/// the reader's lexer between blue and its own output, for nothing — and the
641/// printer and the reader are **not inverses**. `Atom::Str`'s `Display` escapes
642/// its payload and its own docs explain at length why; the `Atom::Symbol` arm
643/// is a bare `write_str`. So a symbol whose text carries a separator prints as
644/// several tokens and reads back as several symbols: a well-formed tree with a
645/// different meaning, no error raised. Measured 2026-08-02 —
646/// `pipeline::tests::the_round_trip_is_not_the_identity_in_general` pins which
647/// separators are silent and which are loud. The only thing that kept this from
648/// biting was blue happening not to emit those bytes. A stage that never
649/// serialises cannot be mis-read.
650///
651/// **What is given up: spans.** The old path's spans pointed into the
652/// re-printed lisp text, a buffer no human ever wrote and no diagnostic could
653/// usefully cite — they were positions in blue's own output, not in the
654/// author's source. `Span::synthetic` says the same thing honestly.
655///
656/// **Carrying real blue-source spans through erasure was the separate piece of
657/// work, and it is done — but NOT the way this doc predicted.** It said the
658/// work "would start from `Spanned::from_sexp_at`". It did not, and could not:
659/// `from_sexp_at` is a *lift*, stamping ONE span across a whole subtree, so
660/// starting there would have replaced a tree of synthetic spans with a tree of
661/// identical wrong ones. The actual shape was to stop projecting in the first
662/// place — erasure walks `Spanned` and keeps each node's own span, because it
663/// only ever deletes (see [`erase`]). **A pointer at the nearest-looking API is
664/// how a reader is sent to the wrong starting point**; the note is corrected
665/// here rather than deleted, because the wrong lead was load-bearing enough to
666/// be worth naming.
667#[must_use]
668pub fn lower_to_spanned(forms: &[tatara_lisp::Sexp]) -> Vec<tatara_lisp::Spanned> {
669 forms
670 .iter()
671 .map(tatara_lisp::Spanned::from_sexp_synthetic)
672 .collect()
673}
674
675#[cfg(test)]
676mod tests {
677 use super::*;
678 use tatara_lisp_eval::Value;
679
680 fn eval(src: &str) -> Value {
681 let forms = tatara_lisp::read_spanned(src).expect("read");
682 let mut interp = interpreter_hostless();
683 interp.eval_program(&forms, &mut ()).expect("eval")
684 }
685
686 /// Every layer is present. A test that only checked layer 1 is exactly
687 /// what let the stdlib gap survive.
688 #[test]
689 fn both_layers_are_installed() {
690 // Layer 1: a Rust primitive.
691 assert!(matches!(eval("(+ 1 2)"), Value::Int(3)));
692 // Layer 2: a stdlib definition, which is the layer that was missing.
693 assert!(matches!(eval("(mod 7 3)"), Value::Int(1)));
694 assert!(matches!(eval("(inc 41)"), Value::Int(42)));
695 assert!(matches!(eval("(first (list 9 8))"), Value::Int(9)));
696 // Layer 3: blue's own core — string and number conversion.
697 assert!(matches!(eval(r#"(length "héllo")"#), Value::Int(5)));
698 // Layer 4: the JSON surface.
699 assert!(matches!(
700 eval(r#"(json_parse "{\"outcome\":\"ok\"}")"#),
701 Value::List(_)
702 ));
703 // Layer 4b: cryptography.
704 assert!(matches!(eval(r#"(blake3_hex "")"#), Value::Str(_)));
705 }
706
707 #[cfg(feature = "sys")]
708 mod held {
709 use super::super::*;
710 use blue_lang_waku::{Capability, Provided, Provision, Provisions};
711 use tatara_lisp_eval::Value;
712
713 fn held(host: &[Capability], provided: &[Provided]) -> (Hold, Interpreter<()>, HostIo) {
714 let mut provisions = Provisions::default();
715 for p in provided {
716 provisions.add(p.clone()).expect("one provider each");
717 }
718 let hold = Hold {
719 frame: session::frame_granting(host),
720 provisions,
721 };
722 let mut interp = interpreter_hostless();
723 let io = HostIo::new();
724 hold.bind(&mut interp, "this test's frame", &io);
725 (hold, interp, io)
726 }
727
728 fn call(interp: &mut Interpreter<()>, src: &str) -> Result<Value, String> {
729 let forms = tatara_lisp::read_spanned(src).expect("read");
730 interp
731 .eval_program(&forms, &mut ())
732 .map_err(|e| e.to_string())
733 }
734
735 #[test]
736 fn a_pure_hold_shims_no_name_so_nothing_can_tally() {
737 let (hold, mut interp, io) = held(&[], &[]);
738 assert!(hold.granted_host_names().is_empty());
739 for (name, _) in hold.withheld_host_names() {
740 assert!(
741 interp.lookup_global(&format!("%io:{name}")).is_none(),
742 "`{name}` is withheld, so it has no counting shim"
743 );
744 }
745 assert!(call(&mut interp, "(getenv \"HOME\")").is_err());
746 assert!(call(&mut interp, "(now_ms)").is_err());
747 assert_eq!(io.total(), 0);
748 }
749
750 #[test]
751 fn a_granted_name_tallies_each_call_and_a_provided_or_withheld_one_none() {
752 let (hold, mut interp, io) = held(
753 &[Capability::Environment],
754 &[Provision::DeterministicStepped {
755 at_ms: 10,
756 step_ms: 1,
757 }
758 .into()],
759 );
760 assert_eq!(hold.granted(), [Capability::Environment]);
761 call(&mut interp, "(getenv \"HOME\")").expect("granted");
762 call(&mut interp, "(argv)").expect("granted");
763 assert_eq!(io.total(), 2, "two calls through granted names");
764 assert_eq!(
765 call(&mut interp, "(now_ms)").expect("provided").to_string(),
766 "10"
767 );
768 assert!(call(&mut interp, "(read_file \"/etc/hosts\")").is_err());
769 assert_eq!(io.total(), 2, "a provider and a breach reach no host");
770 let wrong = call(&mut interp, "(getenv)").expect_err("arity");
771 assert!(
772 wrong.contains("getenv"),
773 "the original names itself: {wrong}"
774 );
775 assert_eq!(
776 io.total(),
777 2,
778 "a call refused for its arity reached no host"
779 );
780 }
781
782 #[test]
783 fn an_unrestricted_hold_shims_every_host_name_but_a_provided_one() {
784 let hold = Hold {
785 frame: blue_lang_waku::Waku::top(),
786 provisions: {
787 let mut p = Provisions::default();
788 p.add(Provision::NullSink).expect("one");
789 p
790 },
791 };
792 assert!(hold.withheld().is_empty());
793 assert!(!hold.granted().contains(&Capability::FileSystem));
794 assert_eq!(hold.granted().len(), Capability::host_effects().len() - 1);
795 let f = hold.frame();
796 assert_eq!(f.provided, [Provided::from(Provision::NullSink)]);
797 assert_eq!(f.granted, hold.granted());
798 }
799
800 #[test]
801 fn a_scoped_provider_binds_its_alias_uncounted_and_leaves_the_host_name_counted() {
802 let scoped = Provided {
803 provision: Provision::NullSink,
804 scope: Some(std::collections::BTreeSet::from(["kazu".to_string()])),
805 };
806 let (hold, mut interp, io) =
807 held(&[Capability::FileSystem], std::slice::from_ref(&scoped));
808 assert_eq!(hold.granted(), [Capability::FileSystem]);
809 assert_eq!(hold.frame().provided, [scoped]);
810 let alias = provided_name("read_file");
811 assert!(
812 interp.lookup_global(&alias).is_some(),
813 "the scoped alias is bound"
814 );
815 let _ = call(&mut interp, &format!("({alias} \"/etc/hosts\")"));
816 assert_eq!(io.total(), 0, "the provider reaches no host");
817 call(&mut interp, "(read_file \"/etc/hosts\")").expect("granted");
818 assert_eq!(io.total(), 1, "code outside the scope reaches the host");
819 }
820
821 #[test]
822 fn the_frame_summary_is_exactly_granted_withheld_and_host_io() {
823 let (hold, _, _) = held(&[Capability::Clock], &[]);
824 assert_eq!(
825 blue_lang_proc::receipt::canonical(&hold.frame_summary(4)),
826 r#"{"granted":["clock"],"host_io":4,"withheld":["process","filesystem","environment","network","entropy"]}"#
827 );
828 }
829 }
830
831 /// Anti-vacuity: a bare interpreter really does LACK layer 2, so the test
832 /// above is measuring the runtime's contribution and not a property the
833 /// interpreter has for free.
834 #[test]
835 fn a_bare_interpreter_lacks_the_stdlib() {
836 let forms = tatara_lisp::read_spanned("(mod 7 3)").expect("read");
837 let mut bare = Interpreter::new();
838 tatara_lisp_eval::install_primitives(&mut bare);
839 assert!(
840 bare.eval_program(&forms, &mut ()).is_err(),
841 "if a bare interpreter already resolved `mod`, this crate would be measuring nothing"
842 );
843 }
844}