1
//! `$nomi_condition` struct + `$nomi_error` exception tag (Tier 3,
2
//! ADR-0026).
3
//!
4
//! A script raise (`(error 'code "msg")`) lowers to `struct.new
5
//! $nomi_condition` + `throw $nomi_error`; `(handler-case)` /
6
//! `(unwind-protect)` catch it via `try_table`, and a compiler-emitted
7
//! boundary wrapper around each host-invoked body catches any uncaught
8
//! raise and bridges it to the `__nomi_raise` host fn. The tag carries a
9
//! single `(ref null $nomi_condition)` payload so a `catch` delivers the
10
//! condition ref straight to the handler block.
11

            
12
use anodized::spec;
13
use wasm_encoder::{
14
    BlockType, Catch, ExportKind, Function, HeapType, Instruction, RefType, TagKind, TagType,
15
    ValType,
16
};
17

            
18
use super::CompileContext;
19
use crate::ast::WasmType;
20
use crate::compiler::emit::FunctionEmitter;
21
use crate::error::{Error, Result};
22

            
23
/// A condition's interned code + message and the indices a helper body needs
24
/// to `throw` it as a catchable `$nomi_error` while only borrowing `&self`.
25
#[derive(Clone, Copy)]
26
pub(super) struct ConditionTrap {
27
    i8_array_idx: u32,
28
    condition_idx: u32,
29
    tag: u32,
30
    code_data: u32,
31
    code_len: i32,
32
    message_data: u32,
33
    message_len: i32,
34
}
35

            
36
impl ConditionTrap {
37
    /// Builds the `$nomi_condition` (nil detail) and `throw`s it. `throw` never
38
    /// returns, so the body's declared result is satisfied by stack-polymorphism.
39
89403056
    pub(super) fn emit_throw(&self, f: &mut Function) {
40
89403056
        f.instruction(&Instruction::I32Const(0));
41
89403056
        f.instruction(&Instruction::I32Const(self.code_len));
42
89403056
        f.instruction(&Instruction::ArrayNewData {
43
89403056
            array_type_index: self.i8_array_idx,
44
89403056
            array_data_index: self.code_data,
45
89403056
        });
46
89403056
        f.instruction(&Instruction::I32Const(0));
47
89403056
        f.instruction(&Instruction::I32Const(self.message_len));
48
89403056
        f.instruction(&Instruction::ArrayNewData {
49
89403056
            array_type_index: self.i8_array_idx,
50
89403056
            array_data_index: self.message_data,
51
89403056
        });
52
89403056
        f.instruction(&Instruction::RefNull(HeapType::ANY));
53
89403056
        f.instruction(&Instruction::StructNew(self.condition_idx));
54
89403056
        f.instruction(&Instruction::Throw(self.tag));
55
89403056
    }
56
}
57

            
58
impl CompileContext {
59
    /// Interns a condition's strings as passive data. `code` is the UPPER-CASE
60
    /// symbol form: handler dispatch compares it byte-for-byte against the
61
    /// reader-folded clause symbol.
62
51759664
    pub(super) fn register_condition_trap(
63
51759664
        &mut self,
64
51759664
        code: &str,
65
51759664
        message: &str,
66
51759664
    ) -> Result<ConditionTrap> {
67
51759664
        let code_data = self.add_data(code.as_bytes())?;
68
51759664
        let message_data = self.add_data(message.as_bytes())?;
69
51759664
        let tag = self.nomi_error_tag()?;
70
        Ok(ConditionTrap {
71
51759664
            i8_array_idx: self.ids.ty_i8_array,
72
51759664
            condition_idx: self.condition_type_idx(),
73
51759664
            tag,
74
51759664
            code_data,
75
51759664
            code_len: data_len(code)?,
76
51759664
            message_data,
77
51759664
            message_len: data_len(message)?,
78
        })
79
51759664
    }
80
}
81

            
82
103519328
fn data_len(text: &str) -> Result<i32> {
83
103519328
    i32::try_from(text.len())
84
        .map_err(|_| Error::Compile("condition string exceeds i32 length".to_string()))
85
103519328
}
86

            
87
impl CompileContext {
88
    /// Registers the `$nomi_condition` struct (`code`, `message` —
89
    /// both `(ref $i8_array)` strings — and `detail`, any value or nil) and
90
    /// the `$nomi_error` tag whose payload is `(ref null $nomi_condition)`.
91
    /// Records the tag index in `nomi_error_tag`. Called once from
92
    /// `new_skeleton`.
93
    #[spec(
94
2352713
        captures: before = self.tag_count,
95
        ensures: |ref output| [
96
2352713
            output.is_err() || self.tag_count == before + 1,
97
2352713
            output.is_err() || self.nomi_error_tag == Some(before),
98
        ],
99
    )]
100
2352713
    pub(super) fn register_exception_support(&mut self) -> Result<()> {
101
2352713
        let string = self.string_ref();
102
2352713
        let condition_idx = self.register_struct_type(&[string, string, self.anyref()])?;
103
2352713
        self.ids.ty_nomi_condition = condition_idx;
104
2352713
        let payload = ValType::Ref(RefType {
105
2352713
            nullable: true,
106
2352713
            heap_type: HeapType::Concrete(condition_idx),
107
2352713
        });
108
2352713
        let sig = self.get_or_create_func_type(&[payload], &[])?;
109
2352713
        self.tags.tag(TagType {
110
2352713
            kind: TagKind::Exception,
111
2352713
            func_type_idx: sig,
112
2352713
        });
113
2352713
        let tag_idx = self.tag_count;
114
2352713
        self.tag_count = tag_idx
115
2352713
            .checked_add(1)
116
            .ok_or_else(|| crate::error::Error::Compile("wasm tag index space exhausted".into()))?;
117
2352713
        self.nomi_error_tag = Some(tag_idx);
118
2352713
        self.exports.export("nomi_error", ExportKind::Tag, tag_idx);
119
2352713
        Ok(())
120
2352713
    }
121

            
122
    /// Declares + exports `condition_new(code, message, detail) -> (ref
123
    /// $nomi_condition)`: the host cannot build the struct itself (its
124
    /// fields reference the guest's `$i8_array`), so it re-enters here.
125
2352712
    pub(super) fn declare_condition_helper(&mut self) -> Result<()> {
126
2352712
        let string = self.string_ref();
127
2352712
        let condition = ValType::Ref(RefType {
128
2352712
            nullable: false,
129
2352712
            heap_type: HeapType::Concrete(self.condition_type_idx()),
130
2352712
        });
131
2352712
        let detail = self.anyref();
132
2352712
        self.register_function("condition_new", &[string, string, detail], &[condition])?;
133
2352712
        self.export_func("condition_new")
134
2352712
    }
135

            
136
2352712
    pub(super) fn build_condition_helper(&mut self) {
137
2352712
        let mut f = Function::new([]);
138
2352712
        f.instruction(&Instruction::LocalGet(0));
139
2352712
        f.instruction(&Instruction::LocalGet(1));
140
2352712
        f.instruction(&Instruction::LocalGet(2));
141
2352712
        f.instruction(&Instruction::StructNew(self.condition_type_idx()));
142
2352712
        f.instruction(&Instruction::End);
143
2352712
        self.pending_helpers.push(f);
144
2352712
    }
145

            
146
    /// Index of the `$nomi_error` exception tag. Errors — rather than
147
    /// panicking — if called before `register_exception_support` (a
148
    /// compiler-internal ordering bug, not a script-reachable condition):
149
    /// every public constructor calls it before any other codegen can run,
150
    /// so a `None` here surfaces as a structured compile error instead of an
151
    /// abort.
152
54724497
    pub(in crate::compiler) fn nomi_error_tag(&self) -> Result<u32> {
153
54724497
        self.nomi_error_tag.ok_or_else(|| {
154
            Error::Compile(
155
                "internal: nomi_error tag read before register_exception_support ran".to_string(),
156
            )
157
        })
158
54724497
    }
159

            
160
    /// Type index of the `$nomi_condition` struct.
161
59429921
    pub(in crate::compiler) fn condition_type_idx(&self) -> u32 {
162
59429921
        self.ids.ty_nomi_condition
163
59429921
    }
164

            
165
    /// Wraps a host-invoked body in the Tier 3 boundary `try_table` that
166
    /// catches an uncaught `$nomi_error`, reads its `code`/`message`/`detail`,
167
    /// and bridges to `__nomi_raise` (ADR-0026). `body` emits the actual
168
    /// function body; it runs inside all three wrapper frames, so any
169
    /// `(return-from)` / `(go)` inside it sees the correct depth (the
170
    /// `try_table` helper bumps `block_depth`).
171
    ///
172
    /// Three nested frames (spike-validated, `wasm_exceptions_spike.rs`):
173
    /// ```text
174
    /// block $exit (result T?)
175
    ///   block $handler (result (ref null $nomi_condition))
176
    ///     try_table (result T?) (catch $nomi_error → $handler)
177
    ///       <body>
178
    ///     end
179
    ///     br $exit          ;; normal completion: carry T out, skip handler
180
    ///   end                 ;; catch lands here, condition ref on the stack
181
    ///   <code = struct.get 0; msg = struct.get 1; detail = struct.get 2; call __nomi_raise; unreachable>
182
    /// end
183
    /// ```
184
    /// `result_ty` is the body's result: `None` for `process` (void), `Some`
185
    /// for `should_apply` (i32) and `nomi-eval` (anyref). The void form
186
    /// drops the `(result T)` arity from `$exit` and the `try_table`.
187
2377872
    pub(in crate::compiler) fn emit_boundary_wrapper(
188
2377872
        &mut self,
189
2377872
        emit: &mut FunctionEmitter,
190
2377872
        result_ty: Option<WasmType>,
191
2377872
        body: impl FnOnce(&mut Self, &mut FunctionEmitter) -> Result<()>,
192
2377872
    ) -> Result<()> {
193
2377872
        let condition_idx = self.condition_type_idx();
194
2377872
        let cond_ref = ValType::Ref(RefType {
195
2377872
            nullable: true,
196
2377872
            heap_type: HeapType::Concrete(condition_idx),
197
2377872
        });
198
2377872
        let tag = self.nomi_error_tag()?;
199
2377872
        let raise = self.ids.nomi_raise;
200
        // Scratch local holding the caught condition while the handler
201
        // reads the fields. Declared `anyref` (no `WasmType` variant for
202
        // a bare struct type); the handler `ref.cast`s back to
203
        // `$nomi_condition` before each `struct.get`. Allocated before the
204
        // body so the body's own locals stack above it.
205
2377872
        let cond_local = self.alloc_local(WasmType::AnyRef)?;
206

            
207
2377872
        match result_ty {
208
            Some(ty) => {
209
760943
                let vt = self.wasm_val_type(ty)?;
210
760943
                emit.block_start_typed(BlockType::Result(vt));
211
            }
212
1616929
            None => emit.block_start(),
213
        }
214
2377872
        emit.block_start_typed(BlockType::Result(cond_ref));
215
2377872
        let try_ty = match result_ty {
216
760943
            Some(ty) => BlockType::Result(self.wasm_val_type(ty)?),
217
1616929
            None => BlockType::Empty,
218
        };
219
        // catch $nomi_error → `$handler` (the block immediately enclosing
220
        // the try_table, relative depth 0).
221
2377872
        emit.try_table(try_ty, &[Catch::One { tag, label: 0 }]);
222

            
223
2377872
        body(self, emit)?;
224

            
225
2165261
        emit.block_end()?; // close try_table
226
        // Normal completion: branch out to `$exit` (now relative depth 1),
227
        // carrying the body result past the handler tail.
228
2165261
        emit.br(1);
229
2165261
        emit.block_end()?; // close $handler — the catch edge lands here
230

            
231
        // Handler: caught `(ref $nomi_condition)` on the stack. Stash it
232
        // (as anyref), then read the fields back via `ref.cast` and
233
        // bridge to `__nomi_raise(code, message, detail)`; the call never returns.
234
2165261
        emit.local_set(cond_local);
235
2165261
        emit.local_get(cond_local);
236
2165261
        emit.ref_cast(condition_idx);
237
2165261
        emit.struct_get(condition_idx, 0); // code
238
2165261
        emit.local_get(cond_local);
239
2165261
        emit.ref_cast(condition_idx);
240
2165261
        emit.struct_get(condition_idx, 1); // message
241
2165261
        emit.local_get(cond_local);
242
2165261
        emit.ref_cast(condition_idx);
243
2165261
        emit.struct_get(condition_idx, 2); // detail
244
2165261
        emit.call(raise);
245
2165261
        emit.unreachable();
246

            
247
2165261
        emit.block_end()?; // close $exit
248
2165261
        Ok(())
249
2377872
    }
250
}