1
//! `(catch-each items var body)` codegen — Tier 2's named recovery
2
//! primitive (ADR-0025).
3
//!
4
//! Lowering: compile `body` as `(lambda (var) body)` via the Tier 1.5
5
//! closure machinery to get a `$closure_<sig>` value on the stack;
6
//! extract its funcref + env, push the items pair-list, then call the
7
//! `__nomi_catch_each` host import. The host walks the chain in Rust,
8
//! invokes the funcref per item recovering per-call `wasmtime::Error`,
9
//! and returns a heterogeneous `pair<anyref>` of `(ok . v)` / `(err
10
//! . (code . msg))` cells. Engine traps (`OutOfFuel` /
11
//! `EpochInterrupt`) bypass capture and re-throw to the outer call site
12
//! — they're never catchable.
13

            
14
use crate::ast::{Expr, LambdaParams, PairElement, WasmType};
15
use crate::compiler::context::CompileContext;
16
use crate::compiler::emit::FunctionEmitter;
17
use crate::compiler::expr::format_form;
18
use crate::compiler::expr::{compile_for_stack, eval_value, serialize_stack_to_output};
19
use crate::compiler::native::{chain_pair_element, compile_constant_list};
20
use crate::compiler::special::try_emit_lambda_for_host_iter;
21
use crate::error::{Error, Result};
22
use crate::reserved::reject_reserved;
23
use crate::runtime::SymbolTable;
24

            
25
const RESULT_TY: WasmType = WasmType::PairRef(PairElement::AnyRef);
26

            
27
1674
pub(super) fn compile_catch_each(
28
1674
    ctx: &mut CompileContext,
29
1674
    emit: &mut FunctionEmitter,
30
1674
    symbols: &mut SymbolTable,
31
1674
    args: &[Expr],
32
1674
) -> Result<()> {
33
1674
    let ty = compile_catch_each_for_stack(ctx, emit, symbols, args)?;
34
    serialize_stack_to_output(ctx, emit, ty)
35
1674
}
36

            
37
1664
pub(super) fn compile_catch_each_for_effect(
38
1664
    ctx: &mut CompileContext,
39
1664
    emit: &mut FunctionEmitter,
40
1664
    symbols: &mut SymbolTable,
41
1664
    args: &[Expr],
42
1664
) -> Result<()> {
43
1664
    compile_catch_each_for_stack(ctx, emit, symbols, args)?;
44
1456
    emit.drop_value();
45
1456
    Ok(())
46
1664
}
47

            
48
11663
pub(super) fn compile_catch_each_for_stack(
49
11663
    ctx: &mut CompileContext,
50
11663
    emit: &mut FunctionEmitter,
51
11663
    symbols: &mut SymbolTable,
52
11663
    args: &[Expr],
53
11663
) -> Result<WasmType> {
54
11663
    let (items_expr, var_name, body) = parse_form(symbols, args)?;
55

            
56
11657
    let elem_ty = infer_items_elem_type(symbols, items_expr)?;
57
11655
    let params = LambdaParams::simple(vec![var_name.to_string()]);
58
11655
    let sig = try_emit_lambda_for_host_iter(ctx, emit, symbols, &params, body, &[elem_ty])?
59
        .ok_or_else(|| {
60
            Error::Compile(
61
                "catch-each: body lambda is out of v1 first-class-closure scope; \
62
                 rewrite the body to use only required parameters"
63
                    .to_string(),
64
            )
65
        })?;
66

            
67
9985
    let closure_ty = WasmType::Closure(sig);
68
9985
    let closure_local = ctx.alloc_local(closure_ty)?;
69
9985
    emit.local_set(closure_local);
70

            
71
9985
    let closure_type_idx = ctx.closure_sig(sig)?.closure_type_idx;
72
9985
    emit.local_get(closure_local);
73
9985
    emit.struct_get(closure_type_idx, 0);
74
9985
    emit.local_get(closure_local);
75
9985
    emit.struct_get(closure_type_idx, 1);
76

            
77
9985
    let items_ty = compile_items_for_stack(ctx, emit, symbols, items_expr)?;
78
9985
    enforce_items_pair(items_ty)?;
79

            
80
9777
    let func_idx = ctx.ids.nomi_catch_each()?;
81
9776
    emit.call(func_idx);
82
9776
    emit.ref_cast_nullable(ctx.ids.ty_pair);
83
9776
    Ok(RESULT_TY)
84
11663
}
85

            
86
/// Infers the user-visible element type of the items pair-list. The
87
/// closure body's iteration variable must bind at this type so the body
88
/// can use it in arithmetic / typed positions; the host fn passes raw
89
/// anyref per element and the closure's prologue downcasts to this type
90
/// before the body runs. Empty-list / heterogeneous-AnyRef shapes fall
91
/// back to AnyRef so the body can still reference the variable, just
92
/// untyped.
93
11657
fn infer_items_elem_type(symbols: &mut SymbolTable, items_expr: &Expr) -> Result<WasmType> {
94
11657
    let resolved = eval_value(symbols, items_expr)?;
95
11655
    Ok(match resolved.wasm_type() {
96
2704
        Some(WasmType::PairRef(elem)) => elem.as_wasm_type(),
97
8951
        _ => fallback_elem_type_from_literal(&resolved),
98
    })
99
11657
}
100

            
101
/// A constant items list binds the iteration variable at the element the LIST
102
/// chain materializes with, so the body sees the same type CAR extracts.
103
17278
fn fallback_elem_type_from_literal(expr: &Expr) -> WasmType {
104
17278
    match expr {
105
8327
        Expr::Datum(inner) => fallback_elem_type_from_literal(inner),
106
        Expr::List(elems) => {
107
8327
            chain_pair_element(elems).map_or(WasmType::AnyRef, PairElement::as_wasm_type)
108
        }
109
624
        _ => WasmType::AnyRef,
110
    }
111
17278
}
112

            
113
4595
pub(super) fn catch_each_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
114
4595
    let (items_expr, _, _) = parse_form(symbols, args)?;
115
4595
    let items_value = eval_value(symbols, items_expr)?;
116
4595
    enforce_items_pair_value(&items_value)?;
117
4595
    Ok(Expr::WasmRuntime(RESULT_TY))
118
4595
}
119

            
120
16258
fn parse_form<'a>(
121
16258
    symbols: &SymbolTable,
122
16258
    args: &'a [Expr],
123
16258
) -> Result<(&'a Expr, &'a str, &'a Expr)> {
124
16258
    if args.len() != 3 {
125
        return Err(Error::Arity {
126
            name: "catch-each".to_string(),
127
            expected: 3,
128
            actual: args.len(),
129
        });
130
16258
    }
131
16258
    let var_name = args[1].as_symbol().ok_or_else(|| {
132
3
        Error::Compile(format!(
133
3
            "catch-each: variable must be a symbol, got {}",
134
3
            format_form(&args[1])
135
3
        ))
136
3
    })?;
137
16255
    reject_reserved(symbols, var_name)?;
138
16252
    Ok((&args[0], var_name, &args[2]))
139
16258
}
140

            
141
/// Materializes `items_expr` as a `pair<...>` value on the stack.
142
/// `(list)` resolves to `Expr::Nil` / `Expr::List([])`, which
143
/// `compile_for_stack` lowers to `i32_const(0)` (legacy `Nil` slot).
144
/// `catch-each` needs a *typed* pair-null, so detect empties up front
145
/// and emit `ref.null $pair` directly.
146
9985
fn compile_items_for_stack(
147
9985
    ctx: &mut CompileContext,
148
9985
    emit: &mut FunctionEmitter,
149
9985
    symbols: &mut SymbolTable,
150
9985
    items_expr: &Expr,
151
9985
) -> Result<WasmType> {
152
9985
    let resolved = eval_value(symbols, items_expr)?;
153
9985
    if is_empty_list(&resolved) {
154
208
        emit.ref_null(ctx.ids.ty_pair);
155
208
        return Ok(RESULT_TY);
156
9777
    }
157
    // A symbol / quote naming a constant list has no stack lowering of its
158
    // own; materialize it by the same chain rule `infer_items_elem_type` uses.
159
9777
    if !matches!(items_expr, Expr::List(_))
160
416
        && let Expr::Datum(inner) = &resolved
161
208
        && let Expr::List(members) = inner.as_ref()
162
    {
163
208
        let elem = chain_pair_element(members)?;
164
208
        return compile_constant_list(ctx, emit, symbols, members.clone(), elem);
165
9569
    }
166
9569
    compile_for_stack(ctx, emit, symbols, items_expr)
167
9985
}
168

            
169
17266
fn is_empty_list(expr: &Expr) -> bool {
170
17266
    match expr {
171
208
        Expr::Nil => true,
172
7281
        Expr::List(elems) => elems.is_empty(),
173
7281
        Expr::Datum(inner) => is_empty_list(inner),
174
2496
        _ => false,
175
    }
176
17266
}
177

            
178
9985
fn enforce_items_pair(ty: WasmType) -> Result<()> {
179
9985
    match ty {
180
9777
        WasmType::PairRef(_) => Ok(()),
181
208
        other => Err(Error::Compile(format!(
182
208
            "catch-each: items expression must be a pair list, got {other}"
183
208
        ))),
184
    }
185
9985
}
186

            
187
4595
fn enforce_items_pair_value(value: &Expr) -> Result<()> {
188
4595
    match value.wasm_type() {
189
4595
        Some(WasmType::PairRef(_)) | None => Ok(()),
190
        Some(other) => Err(Error::Compile(format!(
191
            "catch-each: items expression must be a pair list, got {other}"
192
        ))),
193
    }
194
4595
}