1
//! `(handler-case)` — pattern-match recovery from a raised condition
2
//! (Tier 3.3, ADR-0026).
3
//!
4
//! ```lisp
5
//! (handler-case <body>
6
//!   (no-such-account (e) (log (error-message e)))
7
//!   (commodity-mismatch (e) (recover))
8
//!   (t (e) (error-code e)))            ; t = catch-all (optional, last)
9
//! ```
10
//!
11
//! Lowering (single-value `Catch::One`, the same shape as the Tier 3.2
12
//! boundary wrapper):
13
//! ```text
14
//! block $outer (result T)
15
//!   block $handler (result (ref null $nomi_condition))
16
//!     try_table (result B) (catch $nomi_error → $handler)
17
//!       <body → B>
18
//!     end
19
//!     <box B → T>                     ; outside the try_table
20
//!     br $outer                       ; normal completion carries T out
21
//!   end                               ; catch edge: condition ref on stack
22
//!   local.set $cond
23
//!   <flat dispatch>                   ; each clause an independent `if` that
24
//!                                     ; `br $outer`s on match; t = uncond.;
25
//!                                     ; no match → re-throw same condition
26
//! end
27
//! ```
28
//!
29
//! Result type `T` is discovered at emit time and unified across the body
30
//! and every reachable clause body (mirrors BLOCK's emit-time discovery);
31
//! a diverging arm contributes no type. Re-raise on no-match re-`throw`s a
32
//! fresh `$nomi_error` carrying the SAME condition struct — nomiscript
33
//! conditions have no observable identity, so this is equivalent to
34
//! re-raising the original and avoids needing an exnref.
35

            
36
use wasm_encoder::{BlockType, Catch, HeapType, RefType, ValType};
37

            
38
use crate::ast::{EntityKind, Expr, WasmType};
39
use crate::compiler::context::CompileContext;
40
use crate::compiler::emit::FunctionEmitter;
41
use crate::compiler::expr::{bind_local, compile_for_effect, format_form};
42
use crate::compiler::expr::{eval_value, fold_value, probe_value, serialize_stack_to_output};
43
use crate::compiler::special::needs_cell;
44
use crate::error::{Error, Result};
45
use crate::reserved::reject_reserved;
46
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
47

            
48
use super::arms::{
49
    Arm, arm_of_form, box_arm_value, compile_arm, finish_arm_raw, finish_branch_arm,
50
    in_runtime_branch, reconcile_arms,
51
};
52
use super::block_exits::form_diverges;
53
use super::skip_region::{in_region, split_at_signal};
54

            
55
const HANDLER_CASE: &str = "handler-case";
56
const CATCH_ALL: &str = "T";
57

            
58
/// One parsed clause: `code` is `None` for the `t` catch-all, else the
59
/// (reader-upcased) condition-code symbol; `var` is the condition binding;
60
/// `body` is the clause's body forms.
61
struct Clause<'a> {
62
    code: Option<&'a str>,
63
    var: &'a str,
64
    body: &'a [Expr],
65
}
66

            
67
22654
pub(super) fn eval_handler_case(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
68
22654
    let (body, clauses) = parse(symbols, args)?;
69
22654
    if let Some(folded) = fold_value(&mut symbols.clone(), body)? {
70
1047
        return Ok(folded);
71
21607
    }
72
21607
    let body_val = probe_value(&mut symbols.clone(), body)?;
73
21607
    let body_diverges = form_diverges(&mut symbols.clone(), body)?;
74
    // Otherwise the form has a runtime result. Its type must match what
75
    // `compile_handler_case_for_stack` emits: the unified type of the body
76
    // (when it can fall through) plus every reachable clause body — NOT just
77
    // the body, which is wrong when the body always throws (e.g. an `(error)`
78
    // body whose value comes from a clause). Callers that materialise a
79
    // runtime value (let/defvar binding, lambda arg) trust this type to size
80
    // the local, so a body-only type yields an invalid module.
81
21607
    let mut arms: Vec<Arm> = Vec::new();
82
21607
    if !body_diverges {
83
13080
        arms.push(arm_of_form(body, &body_val)?);
84
8527
    }
85
21607
    for clause in &clauses {
86
21607
        let mut clause_syms = symbols.clone();
87
21607
        clause_syms.enter_runtime_branch()?;
88
21607
        clause_syms.define(Symbol::new(clause.var, SymbolKind::Variable).with_value(
89
21607
            Expr::WasmLocal(0, WasmType::EntityRef(EntityKind::Condition)),
90
21607
        ));
91
21607
        let (cval, cdiverges) = eval_clause_value(&mut clause_syms, clause)?;
92
21399
        if !cdiverges {
93
18873
            let value_form = clause.body.last().unwrap_or(&EMPTY_CLAUSE_VALUE);
94
18873
            arms.push(arm_of_form(value_form, &cval)?);
95
2526
        }
96
    }
97
21399
    Ok(Expr::WasmRuntime(reconcile_arms(&arms)))
98
22654
}
99

            
100
/// Eval-time value + divergence of a clause body, mirroring the
101
/// compile-side `compile_clause_body` walk (last form is the value; an
102
/// earlier diverging form makes the rest dead).
103
21607
fn eval_clause_value(symbols: &mut SymbolTable, clause: &Clause<'_>) -> Result<(Expr, bool)> {
104
21607
    if clause.body.is_empty() {
105
        return Ok((Expr::Nil, false));
106
21607
    }
107
21607
    let last = clause.body.len() - 1;
108
21607
    for (idx, form) in clause.body.iter().enumerate() {
109
21815
        if idx == last {
110
21399
            let diverges = form_diverges(&mut symbols.clone(), form)?;
111
21399
            return Ok((eval_value(symbols, form)?, diverges));
112
416
        }
113
416
        if form_diverges(&mut symbols.clone(), form)? {
114
            eval_value(symbols, form)?;
115
            return Ok((Expr::Nil, true));
116
416
        }
117
416
        eval_value(symbols, form)?;
118
    }
119
    Ok((Expr::Nil, false))
120
21607
}
121

            
122
20115
pub(super) fn compile_handler_case(
123
20115
    ctx: &mut CompileContext,
124
20115
    emit: &mut FunctionEmitter,
125
20115
    symbols: &mut SymbolTable,
126
20115
    args: &[Expr],
127
20115
) -> Result<()> {
128
20115
    let ty = compile_handler_case_for_stack(ctx, emit, symbols, args)?;
129
16545
    serialize_stack_to_output(ctx, emit, ty)
130
20115
}
131

            
132
7508
pub(super) fn compile_handler_case_for_effect(
133
7508
    ctx: &mut CompileContext,
134
7508
    emit: &mut FunctionEmitter,
135
7508
    symbols: &mut SymbolTable,
136
7508
    args: &[Expr],
137
7508
) -> Result<()> {
138
7508
    compile_handler_case_for_stack(ctx, emit, symbols, args)?;
139
5844
    emit.drop_value();
140
5844
    Ok(())
141
7508
}
142

            
143
75497
pub(super) fn compile_handler_case_for_stack(
144
75497
    ctx: &mut CompileContext,
145
75497
    emit: &mut FunctionEmitter,
146
75497
    symbols: &mut SymbolTable,
147
75497
    args: &[Expr],
148
75497
) -> Result<WasmType> {
149
75497
    let (body, clauses) = parse(symbols, args)?;
150

            
151
    // Stash local for the caught condition, allocated before the body so the
152
    // body's own locals stack above it (matches the boundary wrapper).
153
75069
    let cond_local = ctx.alloc_local(WasmType::EntityRef(EntityKind::Condition))?;
154

            
155
    // --- Phase 1: compile every arm into its own scratch, collect types. ---
156
    // Each scratch is seeded at the depth it will actually be spliced into,
157
    // so relative `br` targets of a `(return-from)` / `(go)` inside the arm
158
    // stay correct after splicing:
159
    //   - body: inside $outer/$handler/try_table → parent + 3.
160
    //   - a non-`t` clause: inside $outer + its own guard `if` → parent + 2.
161
    //   - the `t` clause: inside $outer only (no guard `if`) → parent + 1.
162
75069
    let parent_depth = emit.block_depth();
163
75069
    let body_depth = parent_depth + 3;
164

            
165
75069
    let mut body_scratch = FunctionEmitter::new_seeded(body_depth);
166
75069
    let split = split_at_signal(symbols, body);
167
75069
    for form in split.leading {
168
624
        compile_for_effect(ctx, &mut body_scratch, symbols, form)?;
169
    }
170
75069
    let (body, region) = (split.rest.as_ref(), split.region);
171
75069
    let body_arm = in_region(symbols, region.as_ref(), |symbols| {
172
75069
        compile_arm(ctx, &mut body_scratch, symbols, body, None)
173
75069
    })?;
174

            
175
70662
    let mut clause_arms: Vec<ClauseArm<'_>> = Vec::with_capacity(clauses.len());
176
70662
    for clause in &clauses {
177
71090
        let clause_depth = if clause.code.is_some() {
178
54505
            parent_depth + 2
179
        } else {
180
16585
            parent_depth + 1
181
        };
182
71090
        let mut scratch = FunctionEmitter::new_seeded(clause_depth);
183
71090
        let mut clause_syms = symbols.clone();
184
71090
        let cond_ty = WasmType::EntityRef(EntityKind::Condition);
185
71090
        let var_value = if needs_cell(symbols, clause.var, clause.body)? {
186
3
            scratch.local_get(cond_local);
187
3
            Expr::WasmLocal(bind_local(ctx, &mut scratch, cond_ty, true)?, cond_ty)
188
        } else {
189
71087
            Expr::WasmLocal(cond_local, cond_ty)
190
        };
191
71090
        clause_syms.define(Symbol::new(clause.var, SymbolKind::Variable).with_value(var_value));
192
        // A clause runs only when its condition is raised: a compile-time
193
        // effect in it is refused, not applied to (and lost with) this clone.
194
71090
        let (value_form, arm) = in_runtime_branch(&mut clause_syms, |clause_syms| {
195
71090
            compile_clause_body(ctx, &mut scratch, clause_syms, clause)
196
71090
        })?;
197
70668
        clause_arms.push(ClauseArm {
198
70668
            scratch,
199
70668
            symbols: clause_syms,
200
70668
            value_form,
201
70668
            arm,
202
70668
        });
203
    }
204

            
205
70240
    let arms: Vec<Arm> = body_arm
206
70240
        .into_iter()
207
70668
        .chain(clause_arms.iter().filter_map(|clause| clause.arm))
208
        .collect();
209
70240
    let result_ty = reconcile_arms(&arms);
210
    // The body's value is boxed after the `try_table`, where it lands: a box
211
    // that raises must not be caught by this form's own clauses.
212
    // A deferred arm compiles its forms here, after the clauses, which must not see them.
213
70240
    let body_ty = match body_arm {
214
49290
        Some(arm) => in_region(symbols, region.as_ref(), |symbols| {
215
49290
            finish_arm_raw(ctx, &mut body_scratch, symbols, body, arm, result_ty)
216
49290
        })?,
217
20950
        None => result_ty,
218
    };
219
67951
    let mut clause_scratches: Vec<FunctionEmitter> = Vec::with_capacity(clauses.len());
220
67951
    for mut clause in clause_arms {
221
68379
        if let Some(arm) = clause.arm {
222
61907
            finish_branch_arm(
223
61907
                ctx,
224
61907
                &mut clause.scratch,
225
61907
                &mut clause.symbols,
226
61907
                clause.value_form,
227
61907
                arm,
228
61907
                result_ty,
229
61907
            )?;
230
6472
        }
231
68379
        clause_scratches.push(clause.scratch);
232
    }
233

            
234
    // --- Phase 2: emit the real structure, splicing the scratch bodies. ---
235
67951
    let cond_ref = ValType::Ref(RefType {
236
67951
        nullable: true,
237
67951
        heap_type: HeapType::Concrete(ctx.condition_type_idx()),
238
67951
    });
239
67951
    let result_vt = ctx.wasm_val_type(result_ty)?;
240
67951
    let tag = ctx.nomi_error_tag()?;
241

            
242
67951
    emit.block_start_typed(BlockType::Result(result_vt)); // $outer
243
67951
    emit.block_start_typed(BlockType::Result(cond_ref)); // $handler
244
67951
    emit.try_table(
245
67951
        BlockType::Result(ctx.wasm_val_type(body_ty)?),
246
67951
        &[Catch::One { tag, label: 0 }],
247
    );
248
67951
    emit.splice(&body_scratch)?;
249
67951
    emit.block_end()?; // close try_table
250
67951
    box_arm_value(ctx, emit, body_ty, result_ty);
251
67951
    emit.br(1); // normal completion → $outer, skip handler
252
67951
    emit.block_end()?; // close $handler — catch lands here, condition on stack
253

            
254
67951
    emit.local_set(cond_local);
255
67951
    emit_dispatch(ctx, emit, &clauses, &clause_scratches, cond_local)?;
256
67951
    emit.block_end()?; // close $outer
257
67951
    Ok(result_ty)
258
75497
}
259

            
260
/// A compiled clause awaiting the unified result type: its scratch, the
261
/// clause scope, the value form and its arm (`None` when the clause
262
/// diverges).
263
struct ClauseArm<'a> {
264
    scratch: FunctionEmitter,
265
    symbols: SymbolTable,
266
    value_form: &'a Expr,
267
    arm: Option<Arm>,
268
}
269

            
270
static EMPTY_CLAUSE_VALUE: Expr = Expr::Nil;
271

            
272
/// Compiles a clause body (already has `e` bound in `symbols`) into `emit`:
273
/// its leading forms for effect, its value form as an arm. An empty body is
274
/// `nil`.
275
///
276
/// Whether an earlier form makes the rest dead is read from `emit`'s OWN
277
/// simulated reachability after compiling it — never from a syntactic
278
/// `form_diverges` belief. `form_diverges` doesn't classify every diverging
279
/// form (e.g. `GO`), so a leading form that diverges only in the
280
/// simulator's eyes would otherwise still compile the value form into dead
281
/// code, pushing a concrete value onto what is actually a polymorphic
282
/// stack. Once `emit.is_reachable()` is false, the value form is never
283
/// compiled at all — dead code has no business being compiled, whatever
284
/// stack shape it would produce — and this returns `None` immediately.
285
71090
fn compile_clause_body<'a>(
286
71090
    ctx: &mut CompileContext,
287
71090
    emit: &mut FunctionEmitter,
288
71090
    symbols: &mut SymbolTable,
289
71090
    clause: &Clause<'a>,
290
71090
) -> Result<(&'a Expr, Option<Arm>)> {
291
71090
    let Some((value_form, leading)) = clause.body.split_last() else {
292
        return Ok((&EMPTY_CLAUSE_VALUE, Some(Arm::Nil)));
293
    };
294
71090
    for form in leading {
295
1257
        crate::compiler::expr::compile_for_effect(ctx, emit, symbols, form)?;
296
1049
        if !emit.is_reachable() {
297
416
            return Ok((value_form, None));
298
633
        }
299
    }
300
70466
    let arm = compile_arm(ctx, emit, symbols, value_form, None)?;
301
70252
    Ok((value_form, arm))
302
71090
}
303

            
304
/// Emit the flat dispatch at depth `parent+1` (only `$outer` open). Each
305
/// non-`t` clause is an independent `if` (Empty type) whose body, on match,
306
/// runs the spliced clause and `br $outer`s — so every clause body sits at
307
/// the same depth. A `t` clause runs unconditionally. With no `t`, a
308
/// fall-through re-throws the same condition.
309
67951
fn emit_dispatch(
310
67951
    ctx: &mut CompileContext,
311
67951
    emit: &mut FunctionEmitter,
312
67951
    clauses: &[Clause<'_>],
313
67951
    scratches: &[FunctionEmitter],
314
67951
    cond_local: u32,
315
67951
) -> Result<()> {
316
67951
    let condition_idx = ctx.condition_type_idx();
317
67951
    let string_eq = ctx.ids.string_eq;
318
67951
    let tag = ctx.nomi_error_tag()?;
319

            
320
67951
    for (clause, scratch) in clauses.iter().zip(scratches) {
321
68379
        match clause.code {
322
            Some(code) => {
323
                // condition.code == "CODE" ?  → guard an Empty `if`.
324
54083
                emit.local_get(cond_local);
325
54083
                emit.ref_cast(condition_idx);
326
54083
                emit.struct_get(condition_idx, 0);
327
54083
                push_string_literal(ctx, emit, code)?;
328
54083
                emit.call(string_eq);
329
54083
                emit.if_block(BlockType::Empty);
330
                // A value is on the stack to carry out with `br(1)` exactly
331
                // when the scratch's own simulated end state is reachable —
332
                // `compile_arm` seals every diverging arm with
333
                // `scratch.unreachable()`, so a genuinely dead scratch is
334
                // always validator-unreachable here, with no separate
335
                // "was a value form even compiled" bookkeeping needed.
336
54083
                let carries_a_value = scratch.is_reachable();
337
54083
                emit.splice(scratch)?;
338
54083
                if carries_a_value {
339
48015
                    emit.br(1);
340
6068
                }
341
54083
                emit.block_end()?;
342
            }
343
            None => {
344
                // `t` catch-all (last clause, unchanged from before this
345
                // phase): runs unconditionally at `$outer`'s own depth, so
346
                // its value falls through directly to `$outer`'s `end` —
347
                // no `br` is ever emitted here, matching today's behaviour.
348
14296
                emit.splice(scratch)?;
349
14296
                return Ok(());
350
            }
351
        }
352
    }
353

            
354
    // No `t` and nothing matched: re-throw a fresh $nomi_error carrying the
355
    // same condition (no observable identity loss). The local is
356
    // nullable, so cast to the non-null `$nomi_condition` (the tag param
357
    // type) before throwing. `throw` is stack-polymorphic, satisfying
358
    // `$outer`'s declared result type.
359
53655
    emit.local_get(cond_local);
360
53655
    emit.ref_cast(condition_idx);
361
53655
    emit.throw(tag);
362
53655
    Ok(())
363
67951
}
364

            
365
54083
fn push_string_literal(
366
54083
    ctx: &mut CompileContext,
367
54083
    emit: &mut FunctionEmitter,
368
54083
    value: &str,
369
54083
) -> Result<()> {
370
54083
    let data_idx = ctx.add_data(value.as_bytes())?;
371
54083
    emit.i32_const(0);
372
54083
    emit.i32_const(value.len() as i32);
373
54083
    emit.array_new_data(ctx.ids.ty_i8_array, data_idx);
374
54083
    Ok(())
375
54083
}
376

            
377
/// Parse `(handler-case body clause...)`. Requires ≥1 body form; clauses
378
/// follow. Each clause is `(code-sym (var) body...)`; `t` is the catch-all
379
/// and, if present, must be the last clause.
380
98151
fn parse<'a>(symbols: &SymbolTable, args: &'a [Expr]) -> Result<(&'a Expr, Vec<Clause<'a>>)> {
381
98151
    let (body, clause_exprs) = args.split_first().ok_or_else(|| {
382
        Error::Compile(format!(
383
            "{HANDLER_CASE} requires a body and zero or more clauses"
384
        ))
385
    })?;
386
98151
    let mut clauses = Vec::with_capacity(clause_exprs.len());
387
98151
    for (i, clause) in clause_exprs.iter().enumerate() {
388
98579
        let elems = clause.as_list().ok_or_else(|| {
389
3
            Error::Compile(format!(
390
3
                "{HANDLER_CASE}: clause must be a list, got {}",
391
3
                format_form(clause)
392
3
            ))
393
3
        })?;
394
98576
        if elems.len() < 2 {
395
            return Err(Error::Compile(format!(
396
                "{HANDLER_CASE}: clause needs a code symbol, a (var), and a body"
397
            )));
398
98576
        }
399
98576
        let code = match &elems[0] {
400
            // `t` reads as the `t` constant, not a symbol — it's the
401
            // catch-all marker. A symbol head is a condition code.
402
23781
            Expr::T => None,
403
74792
            Expr::Symbol(s) if s == CATCH_ALL => None,
404
74792
            Expr::Symbol(s) => Some(s.as_str()),
405
            other => {
406
3
                return Err(Error::Compile(format!(
407
3
                    "{HANDLER_CASE}: clause head must be a code symbol or t, got {}",
408
3
                    format_form(other)
409
3
                )));
410
            }
411
        };
412
98573
        if code.is_none() && i + 1 != clause_exprs.len() {
413
208
            return Err(Error::Compile(format!(
414
208
                "{HANDLER_CASE}: the t catch-all clause must be last"
415
208
            )));
416
98365
        }
417
98365
        let var = match elems[1].as_list() {
418
            Some([Expr::Symbol(v)]) => {
419
98154
                reject_reserved(symbols, v)?;
420
98151
                v.as_str()
421
            }
422
            _ => {
423
211
                return Err(Error::Compile(format!(
424
211
                    "{HANDLER_CASE}: clause binding must be a single (var), got {}",
425
211
                    format_form(&elems[1])
426
211
                )));
427
            }
428
        };
429
98151
        clauses.push(Clause {
430
98151
            code,
431
98151
            var,
432
98151
            body: &elems[2..],
433
98151
        });
434
    }
435
97723
    Ok((body, clauses))
436
98151
}