Skip to main content

rpc/natives/
catch_each.rs

1//! `(catch-each items var body)` host native — Tier 2's iteration-
2//! bounded error recovery (ADR-0025).
3//!
4//! Compiler-side lowering: the body is wrapped as a single-arg lambda
5//! and lifted to a real wasm fn via Tier 1.5's closure machinery. The
6//! call site extracts (funcref, env_anyref) from the `$closure_<sig>`
7//! struct and pushes them alongside the items pair-list, then emits
8//! `call $__nomi_catch_each`. The host walks the items chain in Rust:
9//! per element it invokes the funcref via `Func::call_async` with
10//! `(env, item)` args, recovers `wasmtime::Error`, classifies it, and
11//! collects the per-call outcome as a heterogeneous result cell.
12//!
13//! Each result cell is a list head: `(OK value)` for normal returns
14//! and `(ERR code msg)` for script-raised / engine-classified errors; the
15//! tags and the code are symbols.
16//! Both ride `$pair` chains whose cars are `anyref`, so the resulting
17//! list is `pair<anyref>`; consumers reach into a cell with the
18//! standard `CAR` / `CADR` / `CADDR` accessors.
19//!
20//! Engine-managed traps are *not* catchable: when
21//! `classify_runtime_error` returns `OutOfFuel`, `EpochInterrupt` or `FiberLimit`, the
22//! host fn re-throws the original error so it bubbles past `catch-each`
23//! to the outer caller. This rule is the load-bearing reason the fuel /
24//! epoch budgets continue to bound a hostile script — without it, a
25//! script could wrap an infinite loop in `catch-each` and keep running
26//! past the deadline. Host-infrastructure failures (`HostFailure`) are
27//! likewise re-thrown, so database diagnostics never become script data.
28
29use scripting::checked_ref::CheckedAnyRef;
30use scripting::runtime::{
31    EngineError, EvalValue, alloc_pair_chain, alloc_string_ref, alloc_value,
32    classify_runtime_error, err_code_and_message,
33};
34use wasmtime::{AnyRef, AsContextMut, Caller, Func, Linker, Rooted, StructRef, Val};
35
36use crate::host_failure::is_host_failure;
37use crate::natives::native::register_native;
38use crate::session::SessionData;
39
40pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
41    register_native(
42        linker,
43        "__nomi_catch_each",
44        |caller,
45         (cb, env, items): (
46            Option<Func>,
47            Option<Rooted<AnyRef>>,
48            Option<Rooted<StructRef>>,
49        )| {
50            Box::pin(async move {
51                let cb =
52                    cb.ok_or_else(|| wasmtime::Error::msg("catch-each: closure funcref is null"))?;
53                let item_anyrefs = collect_items(caller, items)?;
54                let mut result_cells: Vec<Option<Rooted<AnyRef>>> =
55                    Vec::with_capacity(item_anyrefs.len());
56                for item in item_anyrefs {
57                    let cell = invoke_one(caller, &cb, env, item).await?;
58                    result_cells.push(Some(cell));
59                }
60                alloc_pair_chain(caller, result_cells).await
61            })
62        },
63    )?;
64    Ok(())
65}
66
67/// Walks the `$pair` chain into a `Vec<Option<Rooted<AnyRef>>>` of cars
68/// without re-entering the guest. A null car is a legitimate item value
69/// (ADR-0033 Phase 5: `nil`, a `false` bool, or a nullable `StringRef`/
70/// `EntityRef`), not a malformed list — it rides through as `None` rather
71/// than being rejected. The cdr chains through nullable `$pair` structs
72/// (field index 1) until null.
73fn collect_items(
74    caller: &mut Caller<'_, SessionData>,
75    head: Option<Rooted<StructRef>>,
76) -> wasmtime::Result<Vec<Option<Rooted<AnyRef>>>> {
77    let mut out: Vec<Option<Rooted<AnyRef>>> = Vec::new();
78    let mut cursor = head;
79    while let Some(node) = cursor {
80        let car_val = node.field(caller.as_context_mut(), 0)?;
81        let car = match car_val {
82            Val::AnyRef(any) => any,
83            _ => {
84                return Err(wasmtime::Error::msg(
85                    "catch-each: items list car field is not anyref",
86                ));
87            }
88        };
89        out.push(car);
90        let cdr_val = node.field(caller.as_context_mut(), 1)?;
91        cursor = match cdr_val {
92            Val::AnyRef(Some(any)) => Some(any.checked_struct(caller.as_context_mut())?),
93            _ => None,
94        };
95    }
96    Ok(out)
97}
98
99/// Invokes `cb(env, item)`. On `Ok`, returns a `(ok value)` cell.
100/// On `Err`, classifies the trap: `OutOfFuel` / `EpochInterrupt` / `FiberLimit`
101/// and host-infrastructure failures re-throw to the outer caller (neither is
102/// catchable);
103/// every other classification produces an `(err code msg)` cell.
104async fn invoke_one(
105    caller: &mut Caller<'_, SessionData>,
106    cb: &Func,
107    env: Option<Rooted<AnyRef>>,
108    item: Option<Rooted<AnyRef>>,
109) -> wasmtime::Result<Rooted<AnyRef>> {
110    let mut results = [Val::AnyRef(None)];
111    let outcome = cb
112        .call_async(
113            caller.as_context_mut(),
114            &[Val::AnyRef(env), Val::AnyRef(item)],
115            &mut results,
116        )
117        .await;
118    match outcome {
119        Ok(()) => {
120            let value_any = match results[0] {
121                Val::AnyRef(any) => any,
122                _ => {
123                    return Err(wasmtime::Error::msg(
124                        "catch-each: closure returned non-anyref Val variant",
125                    ));
126                }
127            };
128            build_ok_cell(caller, value_any).await
129        }
130        Err(err) if is_host_failure(&err) => Err(err),
131        Err(err) => match classify_runtime_error(&err) {
132            EngineError::OutOfFuel | EngineError::EpochInterrupt | EngineError::FiberLimit => {
133                Err(err)
134            }
135            classified => build_err_cell(caller, &classified).await,
136        },
137    }
138}
139
140/// Builds the list `(ok value)` and returns its head as `anyref`. Always a
141/// two-element list — a `None` body return (a closure that yields `nil`)
142/// becomes an explicit `nil` car, never a shorter `(ok)` list (ADR-0033: a
143/// nil-punned length is exactly the ambiguity the model forbids). Reading
144/// `(car (cdr cell))` gives `nil` either way, but `length` no longer does.
145async fn build_ok_cell(
146    caller: &mut Caller<'_, SessionData>,
147    value: Option<Rooted<AnyRef>>,
148) -> wasmtime::Result<Rooted<AnyRef>> {
149    let tag = symbol_anyref(caller, "OK").await?;
150    pair_chain_to_anyref(caller, vec![Some(tag), value]).await
151}
152
153/// Builds the list `(err code msg)` and returns its head as `anyref`. A
154/// `HostCondition` or `ScriptRaised` becomes `(err CODE msg)` with a symbol
155/// code; its detail is not carried.
156async fn build_err_cell(
157    caller: &mut Caller<'_, SessionData>,
158    classified: &EngineError,
159) -> wasmtime::Result<Rooted<AnyRef>> {
160    let tag = symbol_anyref(caller, "ERR").await?;
161    let (code, message) = err_code_and_message(classified);
162    let code_any = symbol_anyref(caller, &code.to_uppercase()).await?;
163    let message_any = string_anyref(caller, message.as_bytes())?;
164    pair_chain_to_anyref(caller, vec![Some(tag), Some(code_any), Some(message_any)]).await
165}
166
167async fn pair_chain_to_anyref(
168    caller: &mut Caller<'_, SessionData>,
169    elems: Vec<Option<Rooted<AnyRef>>>,
170) -> wasmtime::Result<Rooted<AnyRef>> {
171    let head = alloc_pair_chain(caller, elems)
172        .await?
173        .ok_or_else(|| wasmtime::Error::msg("catch-each: built an empty result cell"))?;
174    Ok(head.to_anyref())
175}
176
177async fn symbol_anyref(
178    caller: &mut Caller<'_, SessionData>,
179    name: &str,
180) -> wasmtime::Result<Rooted<AnyRef>> {
181    alloc_value(caller, &EvalValue::Symbol(name.to_string()))
182        .await?
183        .ok_or_else(|| wasmtime::Error::msg("catch-each: symbol allocation returned nil"))
184}
185
186fn string_anyref(
187    caller: &mut Caller<'_, SessionData>,
188    bytes: &[u8],
189) -> wasmtime::Result<Rooted<AnyRef>> {
190    Ok(alloc_string_ref(caller, bytes)?.to_anyref())
191}