Lines
91.35 %
Functions
83.33 %
Branches
100 %
//! `(catch-each items var body)` host native — Tier 2's iteration-
//! bounded error recovery (ADR-0025).
//!
//! Compiler-side lowering: the body is wrapped as a single-arg lambda
//! and lifted to a real wasm fn via Tier 1.5's closure machinery. The
//! call site extracts (funcref, env_anyref) from the `$closure_<sig>`
//! struct and pushes them alongside the items pair-list, then emits
//! `call $__nomi_catch_each`. The host walks the items chain in Rust:
//! per element it invokes the funcref via `Func::call_async` with
//! `(env, item)` args, recovers `wasmtime::Error`, classifies it, and
//! collects the per-call outcome as a heterogeneous result cell.
//! Each result cell is a list head: `(OK value)` for normal returns
//! and `(ERR code msg)` for script-raised / engine-classified errors; the
//! tags and the code are symbols.
//! Both ride `$pair` chains whose cars are `anyref`, so the resulting
//! list is `pair<anyref>`; consumers reach into a cell with the
//! standard `CAR` / `CADR` / `CADDR` accessors.
//! Engine-managed traps are *not* catchable: when
//! `classify_runtime_error` returns `OutOfFuel`, `EpochInterrupt` or `FiberLimit`, the
//! host fn re-throws the original error so it bubbles past `catch-each`
//! to the outer caller. This rule is the load-bearing reason the fuel /
//! epoch budgets continue to bound a hostile script — without it, a
//! script could wrap an infinite loop in `catch-each` and keep running
//! past the deadline. Host-infrastructure failures (`HostFailure`) are
//! likewise re-thrown, so database diagnostics never become script data.
use scripting::checked_ref::CheckedAnyRef;
use scripting::runtime::{
EngineError, EvalValue, alloc_pair_chain, alloc_string_ref, alloc_value,
classify_runtime_error, err_code_and_message,
};
use wasmtime::{AnyRef, AsContextMut, Caller, Func, Linker, Rooted, StructRef, Val};
use crate::host_failure::is_host_failure;
use crate::natives::native::register_native;
use crate::session::SessionData;
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
register_native(
linker,
"__nomi_catch_each",
|caller,
(cb, env, items): (
Option<Func>,
Option<Rooted<AnyRef>>,
Option<Rooted<StructRef>>,
)| {
Box::pin(async move {
let cb =
cb.ok_or_else(|| wasmtime::Error::msg("catch-each: closure funcref is null"))?;
let item_anyrefs = collect_items(caller, items)?;
let mut result_cells: Vec<Option<Rooted<AnyRef>>> =
Vec::with_capacity(item_anyrefs.len());
for item in item_anyrefs {
let cell = invoke_one(caller, &cb, env, item).await?;
result_cells.push(Some(cell));
}
alloc_pair_chain(caller, result_cells).await
})
},
)?;
Ok(())
/// Walks the `$pair` chain into a `Vec<Option<Rooted<AnyRef>>>` of cars
/// without re-entering the guest. A null car is a legitimate item value
/// (ADR-0033 Phase 5: `nil`, a `false` bool, or a nullable `StringRef`/
/// `EntityRef`), not a malformed list — it rides through as `None` rather
/// than being rejected. The cdr chains through nullable `$pair` structs
/// (field index 1) until null.
fn collect_items(
caller: &mut Caller<'_, SessionData>,
head: Option<Rooted<StructRef>>,
) -> wasmtime::Result<Vec<Option<Rooted<AnyRef>>>> {
let mut out: Vec<Option<Rooted<AnyRef>>> = Vec::new();
let mut cursor = head;
while let Some(node) = cursor {
let car_val = node.field(caller.as_context_mut(), 0)?;
let car = match car_val {
Val::AnyRef(any) => any,
_ => {
return Err(wasmtime::Error::msg(
"catch-each: items list car field is not anyref",
));
out.push(car);
let cdr_val = node.field(caller.as_context_mut(), 1)?;
cursor = match cdr_val {
Val::AnyRef(Some(any)) => Some(any.checked_struct(caller.as_context_mut())?),
_ => None,
Ok(out)
/// Invokes `cb(env, item)`. On `Ok`, returns a `(ok value)` cell.
/// On `Err`, classifies the trap: `OutOfFuel` / `EpochInterrupt` / `FiberLimit`
/// and host-infrastructure failures re-throw to the outer caller (neither is
/// catchable);
/// every other classification produces an `(err code msg)` cell.
async fn invoke_one(
cb: &Func,
env: Option<Rooted<AnyRef>>,
item: Option<Rooted<AnyRef>>,
) -> wasmtime::Result<Rooted<AnyRef>> {
let mut results = [Val::AnyRef(None)];
let outcome = cb
.call_async(
caller.as_context_mut(),
&[Val::AnyRef(env), Val::AnyRef(item)],
&mut results,
)
.await;
match outcome {
Ok(()) => {
let value_any = match results[0] {
"catch-each: closure returned non-anyref Val variant",
build_ok_cell(caller, value_any).await
Err(err) if is_host_failure(&err) => Err(err),
Err(err) => match classify_runtime_error(&err) {
EngineError::OutOfFuel | EngineError::EpochInterrupt | EngineError::FiberLimit => {
Err(err)
classified => build_err_cell(caller, &classified).await,
/// Builds the list `(ok value)` and returns its head as `anyref`. Always a
/// two-element list — a `None` body return (a closure that yields `nil`)
/// becomes an explicit `nil` car, never a shorter `(ok)` list (ADR-0033: a
/// nil-punned length is exactly the ambiguity the model forbids). Reading
/// `(car (cdr cell))` gives `nil` either way, but `length` no longer does.
async fn build_ok_cell(
value: Option<Rooted<AnyRef>>,
let tag = symbol_anyref(caller, "OK").await?;
pair_chain_to_anyref(caller, vec![Some(tag), value]).await
/// Builds the list `(err code msg)` and returns its head as `anyref`. A
/// `HostCondition` or `ScriptRaised` becomes `(err CODE msg)` with a symbol
/// code; its detail is not carried.
async fn build_err_cell(
classified: &EngineError,
let tag = symbol_anyref(caller, "ERR").await?;
let (code, message) = err_code_and_message(classified);
let code_any = symbol_anyref(caller, &code.to_uppercase()).await?;
let message_any = string_anyref(caller, message.as_bytes())?;
pair_chain_to_anyref(caller, vec![Some(tag), Some(code_any), Some(message_any)]).await
async fn pair_chain_to_anyref(
elems: Vec<Option<Rooted<AnyRef>>>,
let head = alloc_pair_chain(caller, elems)
.await?
.ok_or_else(|| wasmtime::Error::msg("catch-each: built an empty result cell"))?;
Ok(head.to_anyref())
async fn symbol_anyref(
name: &str,
alloc_value(caller, &EvalValue::Symbol(name.to_string()))
.ok_or_else(|| wasmtime::Error::msg("catch-each: symbol allocation returned nil"))
fn string_anyref(
bytes: &[u8],
Ok(alloc_string_ref(caller, bytes)?.to_anyref())