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