1
//! `(unwind-protect body cleanup...)` — guaranteed cleanup (Tier 3.4,
2
//! ADR-0026).
3
//!
4
//! ```lisp
5
//! (unwind-protect
6
//!     (acquire-and-do-risky-stuff)
7
//!   (release-resource))
8
//! ```
9
//!
10
//! `cleanup` runs on BOTH normal completion of `body` AND on a `$nomi_error`
11
//! raised inside it; the raise is then re-raised (cleanup never swallows it).
12
//! The form's value is `body`'s value on normal completion.
13
//!
14
//! Lowering (single-tag `Catch::One`, same shape family as the Tier 3.2
15
//! boundary wrapper and `(handler-case)`). Cleanup is emitted EXACTLY ONCE:
16
//! both exit paths converge on a `(ref null $nomi_condition)` — the caught
17
//! condition on the exceptional path, a null sentinel on the normal path —
18
//! so a single cleanup splice covers both, after which `ref.is_null` decides
19
//! whether to return the stashed body value or re-raise.
20
//! ```text
21
//! block $done (result T)
22
//!   block $unwind (result (ref null $nomi_condition))
23
//!     try_table (result T) (catch $nomi_error → $unwind)
24
//!       <body → T>
25
//!     end
26
//!     local.set $result               ; normal: stash T, push null sentinel
27
//!     ref.null $nomi_condition
28
//!   end                               ; catch edge delivers the condition
29
//!   local.set $cond                   ; cond = caught condition | null
30
//!   <cleanup for effect>              ; runs once, on BOTH paths
31
//!   local.get $cond
32
//!   ref.is_null
33
//!   (if (result T)
34
//!     (then local.get $result)        ; normal: return the stashed value
35
//!     (else local.get $cond; ref.cast; throw $nomi_error))  ; re-raise
36
//! end
37
//! ```
38
//!
39
//! `Catch::One` on `$nomi_error` (the only exception tag) catches every
40
//! catchable error — engine deadlines (`OutOfFuel` / `EpochInterrupt`) are
41
//! NOT wasm exceptions and bypass `try_table` entirely, so cleanup does not
42
//! run for them (documented in `doc/scripting/error-handling.org`). Re-raise
43
//! re-`throw`s a fresh `$nomi_error` carrying the SAME condition struct;
44
//! nomiscript conditions have no observable identity, so this needs no
45
//! `exnref` / `throw_ref` and stays uniform with handler-case. The null
46
//! sentinel is unambiguous: `(error)` and every boundary throw build the
47
//! condition with `struct.new` (always non-null).
48
//!
49
//! Cleanup compiles on the LIVE symbol table (not a clone): it shares the
50
//! surrounding lexical scope, so a `(setf x …)` in cleanup must promote `x`
51
//! to the same runtime local a later read of `x` resolves to. Emitting it
52
//! once — at a single wasm depth — also keeps any relative `br` inside
53
//! cleanup (a `return-from` / `go` out of it) correct without duplication.
54

            
55
use wasm_encoder::{BlockType, Catch, HeapType, RefType, ValType};
56

            
57
use crate::ast::{Expr, WasmType};
58
use crate::compiler::context::CompileContext;
59
use crate::compiler::emit::FunctionEmitter;
60
use crate::compiler::expr::{
61
    compile_for_effect, compile_for_stack, eval_value, serialize_stack_to_output,
62
};
63
use crate::error::{Error, Result};
64
use crate::runtime::SymbolTable;
65

            
66
use super::block_exits::form_diverges;
67

            
68
const UNWIND_PROTECT: &str = "unwind-protect";
69

            
70
8526
pub(super) fn eval_unwind_protect(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
71
8526
    let (body, cleanup) = parse(args)?;
72
8526
    let body_diverges = form_diverges(&mut symbols.clone(), body)?;
73
8526
    let body_val = eval_value(symbols, body);
74
    // Cleanup shares the surrounding lexical scope, so eval it on the LIVE
75
    // table (like BLOCK's body) — a `(setf x …)` in cleanup must promote `x`
76
    // for a later read to resolve to the same runtime local. It also runs when
77
    // the body raised a transfer, which then continues past it.
78
8526
    if matches!(body_val, Ok(_) | Err(Error::Transfer { .. })) {
79
8526
        for form in cleanup {
80
8526
            eval_value(symbols, form)?;
81
        }
82
    }
83
8525
    let body_val = body_val?;
84
8525
    if !body_val.is_wasm_runtime() && !body_diverges {
85
        // Body folds to a constant and can't raise — that's the value.
86
97
        return Ok(body_val);
87
8428
    }
88
    // Runtime result: the value is the body's; cleanup is effect-only.
89
8428
    Ok(Expr::WasmRuntime(runtime_type(&body_val)))
90
8526
}
91

            
92
/// The `WasmType` an eval result carries on the stack, mirroring the literal
93
/// lowerings the stack-compile path uses. Bool/nil literals lower to `Bool`
94
/// (matching `compile_for_stack`), so a bound unwind-protect result is sized
95
/// to the value codegen actually pushes — else a runtime-boolean body would
96
/// mis-serialize as Number.
97
8428
fn runtime_type(val: &Expr) -> WasmType {
98
8428
    crate::compiler::expr::classify_stack_type(val).unwrap_or(WasmType::I32)
99
8428
}
100

            
101
3129
pub(super) fn compile_unwind_protect(
102
3129
    ctx: &mut CompileContext,
103
3129
    emit: &mut FunctionEmitter,
104
3129
    symbols: &mut SymbolTable,
105
3129
    args: &[Expr],
106
3129
) -> Result<()> {
107
3129
    let ty = compile_unwind_protect_for_stack(ctx, emit, symbols, args)?;
108
2920
    serialize_stack_to_output(ctx, emit, ty)
109
3129
}
110

            
111
3763
pub(super) fn compile_unwind_protect_for_effect(
112
3763
    ctx: &mut CompileContext,
113
3763
    emit: &mut FunctionEmitter,
114
3763
    symbols: &mut SymbolTable,
115
3763
    args: &[Expr],
116
3763
) -> Result<()> {
117
3763
    compile_unwind_protect_for_stack(ctx, emit, symbols, args)?;
118
3763
    emit.drop_value();
119
3763
    Ok(())
120
3763
}
121

            
122
15383
pub(super) fn compile_unwind_protect_for_stack(
123
15383
    ctx: &mut CompileContext,
124
15383
    emit: &mut FunctionEmitter,
125
15383
    symbols: &mut SymbolTable,
126
15383
    args: &[Expr],
127
15383
) -> Result<WasmType> {
128
15383
    let (body, cleanup) = parse(args)?;
129
    // Two roles: it types the result and seals the try_table.
130
15175
    let body_diverges = form_diverges(&mut symbols.clone(), body)?;
131
15175
    protect(
132
15175
        ctx,
133
15175
        emit,
134
15175
        symbols,
135
15175
        cleanup,
136
15175
        body_diverges,
137
15175
        |ctx, scratch, symbols| compile_for_stack(ctx, scratch, symbols, body),
138
    )
139
15383
}
140

            
141
/// Runs `cleanup` on every exit of the code `compile_body` emits: normal,
142
/// a crossing `return-from` / `go`, and a throw. `compile_body` lowers the
143
/// protected code for the stack into the emitter it is given.
144
35020
pub(in crate::compiler) fn protect(
145
35020
    ctx: &mut CompileContext,
146
35020
    emit: &mut FunctionEmitter,
147
35020
    symbols: &mut SymbolTable,
148
35020
    cleanup: &[Expr],
149
35020
    body_diverges: bool,
150
35020
    compile_body: impl FnOnce(
151
35020
        &mut CompileContext,
152
35020
        &mut FunctionEmitter,
153
35020
        &mut SymbolTable,
154
35020
    ) -> Result<WasmType>,
155
35020
) -> Result<WasmType> {
156
    // `result_local` stashes the body's value on the normal path while
157
    // cleanup runs; `cond_local` (anyref) holds the caught condition on the
158
    // exceptional path, or null on the normal path. Both allocated before the
159
    // body so the body's own locals stack above them.
160
35020
    let cond_local = ctx.alloc_local(WasmType::AnyRef)?;
161

            
162
    // --- Phase 1: compile body + cleanup into scratches on LIVE symbols. ---
163
    // Body runs inside $done/$unwind/try_table (parent + 3). Cleanup runs once
164
    // at the $done level after $unwind closes (parent + 1). Both compile
165
    // against the live table (shared lexical scope): the body may promote a
166
    // binding to a runtime local that cleanup then reads/writes. Body first,
167
    // so its promotions are visible to cleanup.
168
35020
    let parent_depth = emit.block_depth();
169

            
170
    // While the body compiles, register an unwind frame so a non-local exit
171
    // (`(return-from)` / `(go)` to a target outside this unwind-protect) emits
172
    // this cleanup inline before its `br` — CL unwind semantics. The frame's
173
    // `threshold` is `parent_depth`: an exit landing at depth `<= parent_depth`
174
    // leaves the unwind-protect. Cleanup is recompiled (for effect) at each
175
    // crossing exit; the normal/exceptional paths below emit their own copy.
176
35020
    let mut body_scratch = FunctionEmitter::new_seeded(parent_depth + 3);
177
35020
    ctx.push_unwind_frame(parent_depth, cleanup.to_vec());
178
35020
    let body_result = compile_body(ctx, &mut body_scratch, symbols);
179
35020
    ctx.pop_unwind_frame()?;
180
35020
    let body_ty = body_result?;
181
34303
    let body_diverges = body_diverges || !body_scratch.is_reachable();
182
34303
    let result_ty = if body_diverges {
183
11342
        WasmType::I32
184
    } else {
185
22961
        body_ty
186
    };
187
34303
    let result_local = ctx.alloc_local(result_ty)?;
188

            
189
34303
    let mut cleanup_scratch = FunctionEmitter::new_seeded(parent_depth + 1);
190
34303
    for form in cleanup {
191
72778
        compile_for_effect(ctx, &mut cleanup_scratch, symbols, form)?;
192
    }
193

            
194
    // --- Phase 2: emit the real structure, splicing the scratches. ---
195
34303
    let condition_idx = ctx.condition_type_idx();
196
34303
    let cond_ref = ValType::Ref(RefType {
197
34303
        nullable: true,
198
34303
        heap_type: HeapType::Concrete(condition_idx),
199
34303
    });
200
34303
    let result_vt = ctx.wasm_val_type(result_ty)?;
201
34303
    let tag = ctx.nomi_error_tag()?;
202

            
203
34303
    emit.block_start_typed(BlockType::Result(result_vt)); // $done
204
34303
    emit.block_start_typed(BlockType::Result(cond_ref)); // $unwind
205
34303
    emit.try_table(
206
34303
        BlockType::Result(result_vt),
207
34303
        &[Catch::One { tag, label: 0 }],
208
34303
    );
209
34303
    emit.splice(&body_scratch)?;
210
34303
    if body_diverges {
211
        // Dead tail after a body that always raises; reset to polymorphic so
212
        // the try_table's declared result type is satisfied vacuously.
213
11342
        emit.unreachable();
214
22961
    }
215
34303
    emit.block_end()?; // close try_table
216
    // Normal completion: body result T on the stack. Stash it and push the
217
    // null sentinel so the $unwind block yields `(ref null $nomi_condition)`
218
    // on both edges (catch delivers the real condition).
219
34303
    emit.local_set(result_local);
220
34303
    emit.ref_null(condition_idx);
221
34303
    emit.block_end()?; // close $unwind — both edges converge with cond-or-null
222

            
223
    // cond = caught condition (exceptional) | null (normal). Run cleanup once,
224
    // on both paths, then branch.
225
34303
    emit.local_set(cond_local);
226
34303
    emit.splice(&cleanup_scratch)?;
227
34303
    emit.local_get(cond_local);
228
34303
    emit.ref_is_null();
229
34303
    emit.if_block(BlockType::Result(result_vt));
230
34303
    emit.local_get(result_local); // normal: the stashed body value
231
34303
    emit.else_block();
232
34303
    emit.local_get(cond_local); // exceptional: re-raise the same condition
233
34303
    emit.ref_cast(condition_idx);
234
34303
    emit.throw(tag);
235
34303
    emit.block_end()?; // close if
236

            
237
34303
    emit.block_end()?; // close $done
238
34303
    if body_diverges {
239
        // The then-arm above is statically live but never runs: the body
240
        // always exits, so the form completes only by a re-raise or an exit.
241
11342
        emit.unreachable();
242
22961
    }
243
34303
    Ok(result_ty)
244
35020
}
245

            
246
/// Emit, for effect, the cleanup of every active `(unwind-protect)` an exit
247
/// to `target_depth` crosses (innermost-first) — the CL guarantee that a
248
/// non-local `(return-from)` / `(go)` runs intervening cleanups before
249
/// transferring control. Called from the exit-site codegen (`block.rs`,
250
/// `tagbody.rs`) just before the `br`, with the exit value (if any) already
251
/// on the stack: cleanup is stack-neutral (effect position), so it doesn't
252
/// disturb that value. A no-op when no unwind-protect is crossed (the common
253
/// case keeps its bare `br`).
254
99527
pub(super) fn emit_crossing_cleanups(
255
99527
    ctx: &mut CompileContext,
256
99527
    emit: &mut FunctionEmitter,
257
99527
    symbols: &mut SymbolTable,
258
99527
    target_depth: u32,
259
99527
) -> Result<()> {
260
    // Crossed frames are popped one at a time, innermost first, so an exit
261
    // inside a cleanup still crosses the outer frames. Each emits the outer
262
    // cleanups itself before its own `br`; the repeats on the dead
263
    // fall-through after the cleanup are harmless. The cleanups compile
264
    // against a CLONE of the symbol table: this exit path diverges, and a
265
    // sibling branch must not observe their compile-time side effects.
266
99527
    let mut clone = symbols.clone();
267
99527
    let mut crossed = Vec::new();
268
99527
    let mut compiled = Ok(());
269
103825
    while let Some(frame) = ctx.pop_unwind_frame_crossing(target_depth) {
270
4298
        if compiled.is_ok() {
271
4298
            compiled = frame
272
4298
                .cleanup
273
4298
                .iter()
274
5238
                .try_for_each(|form| compile_for_effect(ctx, emit, &mut clone, form));
275
        }
276
4298
        crossed.push(frame);
277
    }
278
99527
    crossed.reverse();
279
99527
    ctx.restore_unwind_frames(crossed);
280
99527
    compiled
281
99527
}
282

            
283
/// Parse `(unwind-protect body cleanup...)`: a required body form followed by
284
/// zero or more cleanup forms.
285
23909
fn parse(args: &[Expr]) -> Result<(&Expr, &[Expr])> {
286
23909
    args.split_first().ok_or_else(|| {
287
208
        Error::Compile(format!(
288
208
            "{UNWIND_PROTECT} requires a protected body form and zero or more cleanup forms"
289
208
        ))
290
208
    })
291
23909
}