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

            
29
use scripting::checked_ref::CheckedAnyRef;
30
use scripting::runtime::{
31
    EngineError, EvalValue, alloc_pair_chain, alloc_string_ref, alloc_value,
32
    classify_runtime_error, err_code_and_message,
33
};
34
use wasmtime::{AnyRef, AsContextMut, Caller, Func, Linker, Rooted, StructRef, Val};
35

            
36
use crate::host_failure::is_host_failure;
37
use crate::natives::native::register_native;
38
use crate::session::SessionData;
39

            
40
236810
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
41
236810
    register_native(
42
236810
        linker,
43
236810
        "__nomi_catch_each",
44
        |caller,
45
         (cb, env, items): (
46
            Option<Func>,
47
            Option<Rooted<AnyRef>>,
48
            Option<Rooted<StructRef>>,
49
13941
        )| {
50
13941
            Box::pin(async move {
51
                let cb =
52
13941
                    cb.ok_or_else(|| wasmtime::Error::msg("catch-each: closure funcref is null"))?;
53
13941
                let item_anyrefs = collect_items(caller, items)?;
54
                let mut result_cells: Vec<Option<Rooted<AnyRef>>> =
55
13941
                    Vec::with_capacity(item_anyrefs.len());
56
13941
                for item in item_anyrefs {
57
15553
                    let cell = invoke_one(caller, &cb, env, item).await?;
58
5153
                    result_cells.push(Some(cell));
59
                }
60
3541
                alloc_pair_chain(caller, result_cells).await
61
13941
            })
62
13941
        },
63
    )?;
64
236810
    Ok(())
65
236810
}
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.
73
13941
fn collect_items(
74
13941
    caller: &mut Caller<'_, SessionData>,
75
13941
    head: Option<Rooted<StructRef>>,
76
13941
) -> wasmtime::Result<Vec<Option<Rooted<AnyRef>>>> {
77
13941
    let mut out: Vec<Option<Rooted<AnyRef>>> = Vec::new();
78
13941
    let mut cursor = head;
79
29814
    while let Some(node) = cursor {
80
15873
        let car_val = node.field(caller.as_context_mut(), 0)?;
81
15873
        let car = match car_val {
82
15873
            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
15873
        out.push(car);
90
15873
        let cdr_val = node.field(caller.as_context_mut(), 1)?;
91
15873
        cursor = match cdr_val {
92
2092
            Val::AnyRef(Some(any)) => Some(any.checked_struct(caller.as_context_mut())?),
93
13781
            _ => None,
94
        };
95
    }
96
13941
    Ok(out)
97
13941
}
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.
104
15553
async fn invoke_one(
105
15553
    caller: &mut Caller<'_, SessionData>,
106
15553
    cb: &Func,
107
15553
    env: Option<Rooted<AnyRef>>,
108
15553
    item: Option<Rooted<AnyRef>>,
109
15553
) -> wasmtime::Result<Rooted<AnyRef>> {
110
15553
    let mut results = [Val::AnyRef(None)];
111
15553
    let outcome = cb
112
15553
        .call_async(
113
15553
            caller.as_context_mut(),
114
15553
            &[Val::AnyRef(env), Val::AnyRef(item)],
115
15553
            &mut results,
116
15553
        )
117
15553
        .await;
118
15553
    match outcome {
119
        Ok(()) => {
120
4346
            let value_any = match results[0] {
121
4346
                Val::AnyRef(any) => any,
122
                _ => {
123
                    return Err(wasmtime::Error::msg(
124
                        "catch-each: closure returned non-anyref Val variant",
125
                    ));
126
                }
127
            };
128
4346
            build_ok_cell(caller, value_any).await
129
        }
130
11207
        Err(err) if is_host_failure(&err) => Err(err),
131
11207
        Err(err) => match classify_runtime_error(&err) {
132
            EngineError::OutOfFuel | EngineError::EpochInterrupt | EngineError::FiberLimit => {
133
10400
                Err(err)
134
            }
135
807
            classified => build_err_cell(caller, &classified).await,
136
        },
137
    }
138
15553
}
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.
145
4346
async fn build_ok_cell(
146
4346
    caller: &mut Caller<'_, SessionData>,
147
4346
    value: Option<Rooted<AnyRef>>,
148
4346
) -> wasmtime::Result<Rooted<AnyRef>> {
149
4346
    let tag = symbol_anyref(caller, "OK").await?;
150
4346
    pair_chain_to_anyref(caller, vec![Some(tag), value]).await
151
4346
}
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.
156
807
async fn build_err_cell(
157
807
    caller: &mut Caller<'_, SessionData>,
158
807
    classified: &EngineError,
159
807
) -> wasmtime::Result<Rooted<AnyRef>> {
160
807
    let tag = symbol_anyref(caller, "ERR").await?;
161
807
    let (code, message) = err_code_and_message(classified);
162
807
    let code_any = symbol_anyref(caller, &code.to_uppercase()).await?;
163
807
    let message_any = string_anyref(caller, message.as_bytes())?;
164
807
    pair_chain_to_anyref(caller, vec![Some(tag), Some(code_any), Some(message_any)]).await
165
807
}
166

            
167
5153
async fn pair_chain_to_anyref(
168
5153
    caller: &mut Caller<'_, SessionData>,
169
5153
    elems: Vec<Option<Rooted<AnyRef>>>,
170
5153
) -> wasmtime::Result<Rooted<AnyRef>> {
171
5153
    let head = alloc_pair_chain(caller, elems)
172
5153
        .await?
173
        .ok_or_else(|| wasmtime::Error::msg("catch-each: built an empty result cell"))?;
174
5153
    Ok(head.to_anyref())
175
5153
}
176

            
177
5960
async fn symbol_anyref(
178
5960
    caller: &mut Caller<'_, SessionData>,
179
5960
    name: &str,
180
5960
) -> wasmtime::Result<Rooted<AnyRef>> {
181
5960
    alloc_value(caller, &EvalValue::Symbol(name.to_string()))
182
5960
        .await?
183
        .ok_or_else(|| wasmtime::Error::msg("catch-each: symbol allocation returned nil"))
184
5960
}
185

            
186
807
fn string_anyref(
187
807
    caller: &mut Caller<'_, SessionData>,
188
807
    bytes: &[u8],
189
807
) -> wasmtime::Result<Rooted<AnyRef>> {
190
807
    Ok(alloc_string_ref(caller, bytes)?.to_anyref())
191
807
}