1
//! Resolved wasm function / type indices for a `CompileContext`.
2
//!
3
//! Emit code used to resolve indices by string — `ctx.func("ratio_new")` /
4
//! `ctx.type_idx("pair")` — through a `HashMap[key]` that **panicked** on a
5
//! miss (a missing helper, or a name registered in one module mode but read in
6
//! the other, e.g. `log` before it was added to eval mode). The name set is a
7
//! CLOSED, STATIC universe registered by the context constructor, so a miss is
8
//! a compiler bug — but it must surface as a structured `Error::Compile`, never
9
//! a SIGABRT (CLAUDE.md).
10
//!
11
//! `WasmIds` resolves every emit-referenced name ONCE at the end of
12
//! construction into a typed field. Emit then reads `ctx.ids.ratio_new` — a
13
//! plain `u32`, infallible, no hashing, no panic. A forgotten field is a Rust
14
//! "missing field in initializer" compile error; the `EntityKind` resolver is an
15
//! exhaustive `match`, so a new entity variant without a mapping is a Rust
16
//! compile error too. **The missing-key panic class cannot recur.**
17
//!
18
//! Indices are per-compilation, module-internal wasm section indices — never
19
//! serialized, never crossing a process/disk/rpc boundary — so this is a pure
20
//! internal-representation change with no effect on emitted bytes or script
21
//! portability.
22

            
23
use anodized::spec;
24

            
25
use crate::ast::EntityKind;
26
use crate::error::{Error, Result};
27

            
28
use super::CompileContext;
29
use crate::compiler::layout::OutputLimit;
30

            
31
/// Wasm function indices referenced by emit code, resolved at construction.
32
/// Common helpers are present in BOTH module modes; the three `get_*` host
33
/// imports are SCRIPT-mode only (their emit sites — the entity natives — run
34
/// only on the script path), so they are `Option` and read through accessors
35
/// that return a structured error rather than panicking if read in eval mode.
36
#[derive(Debug, Clone)]
37
pub(in crate::compiler) struct WasmIds {
38
    // ratio helpers
39
    pub gcd: u32,
40
    pub ratio_new: u32,
41
    pub ratio_add: u32,
42
    pub ratio_sub: u32,
43
    pub ratio_mul: u32,
44
    pub ratio_div: u32,
45
    pub ratio_eq: u32,
46
    pub ratio_lt: u32,
47
    pub ratio_from_i64: u32,
48
    pub ratio_to_i64: u32,
49
    pub i64_mul_checked: u32,
50
    pub i64_add_checked: u32,
51
    pub i64_sub_checked: u32,
52
    // unit-term helpers
53
    pub unit_singleton: u32,
54
    pub unit_mul: u32,
55
    pub unit_negate: u32,
56
    pub unit_eq: u32,
57
    pub materialize_unit: u32,
58
    // commodity helpers
59
    pub commodity_add: u32,
60
    pub commodity_sub: u32,
61
    pub commodity_mul: u32,
62
    pub commodity_div: u32,
63
    pub commodity_mul_by_ratio: u32,
64
    pub commodity_div_by_ratio: u32,
65
    pub commodity_neg: u32,
66
    pub commodity_eq: u32,
67
    pub commodity_lt: u32,
68
    pub commodity_assert_atomic: u32,
69
    pub commodity_new: u32,
70
    pub commodity_new_with_term: u32,
71
    // pair + string
72
    pub pair_new: u32,
73
    pub box_index: u32,
74
    pub index_div: u32,
75
    pub index_rem: u32,
76
    pub index_add: u32,
77
    pub index_sub: u32,
78
    pub index_mul: u32,
79
    pub index_narrow: u32,
80
    pub box_bool: u32,
81
    pub car_of_nil: u32,
82
    /// Catchable `OUTPUT-OVERFLOW` thrown when an output entity would not fit
83
    /// in the output buffer.
84
    pub output_overflow: u32,
85
    /// Catchable `TYPE-ERROR` ("not a list") thrown when a list consumer's
86
    /// `AnyRef` operand is neither null nor a `$pair` (ADR-0033).
87
    pub not_a_list: u32,
88
    /// Catchable `TYPE-ERROR` ("nil is not a string") thrown when a
89
    /// `StringRef` consumer receives `nil` (ADR-0033 Phase 5).
90
    pub nil_string: u32,
91
    /// Catchable `TYPE-ERROR` ("nil is not an entity") thrown when an
92
    /// `EntityRef` consumer receives `nil` (ADR-0033 Phase 5).
93
    pub nil_entity: u32,
94
    pub string_eq: u32,
95
    pub symbol_eq: u32,
96
    pub pair_equal: u32,
97
    pub anyref_equal: u32,
98
    pub symbol_designator: u32,
99
    pub symbol_keyword_p: u32,
100
    /// Catchable `TYPE-ERROR` ("not a symbol") thrown when `SYMBOL-NAME`'s
101
    /// `AnyRef` operand is neither nil, `t` nor a `$symbol`.
102
    pub not_a_symbol: u32,
103
    /// Catchable `TYPE-ERROR`s thrown by `THE` when its `AnyRef` operand is
104
    /// not an index / scalar / money / string.
105
    pub not_an_index: u32,
106
    pub not_a_scalar: u32,
107
    pub not_money: u32,
108
    pub not_a_string: u32,
109
    pub not_printable: u32,
110
    pub not_a_function: u32,
111
    pub wrong_function_arguments: u32,
112
    pub symbol_not_callable: u32,
113
    // boundary imports
114
    pub nomi_raise: u32, // both modes
115
    pub log: u32,        // both modes
116
    pub log_value: u32,  // both modes
117
    // eval-mode-only import (catch-each lowering)
118
    pub nomi_catch_each: Option<u32>,
119
    // script-mode-only env imports (entity-native emit sites)
120
    pub get_output_offset: Option<u32>,
121
    pub get_input_offset: Option<u32>,
122
    pub get_input_entities_count: Option<u32>,
123

            
124
    // types
125
    pub ty_i8_array: u32,
126
    pub ty_ratio: u32,
127
    pub ty_pair: u32,
128
    pub ty_symbol: u32,
129
    pub ty_commodity: u32,
130
    pub ty_unit_term: u32,
131
    pub ty_nomi_condition: u32,
132
    /// The `$t_ty` empty struct type — `t` is the sole (module-global)
133
    /// instance, identified by reference equality, never by type test
134
    /// (ADR-0033: WasmGC struct types are structural, so an empty struct type
135
    /// is not unique).
136
    pub ty_t: u32,
137
    /// Wasm global index of the exported `t` singleton
138
    /// (`(global (ref $t_ty) (struct.new $t_ty))`).
139
    pub global_t: u32,
140
    // entity struct types (indexed by EntityKind via `entity_type`)
141
    pub ty_account: u32,
142
    pub ty_commodity_entity: u32,
143
    pub ty_transaction: u32,
144
    pub ty_split: u32,
145
    pub ty_tag_entity: u32,
146
    pub ty_price: u32,
147
    pub ty_ssh_key: u32,
148
    /// The non-final `$closure_base` struct every `$closure_<sig>` extends,
149
    /// so one `ref.test` recognises a closure of any signature.
150
    pub ty_closure_base: u32,
151
    /// `(array (mut anyref))`: a struct's layout and its field values.
152
    pub ty_slots: u32,
153
    /// The one shape of every `DEFSTRUCT` instance: serial, layout, values.
154
    pub ty_struct: u32,
155
    pub struct_new: u32,
156
    pub struct_copy: u32,
157
}
158

            
159
impl WasmIds {
160
    /// Pre-resolution poison. Every index is `u32::MAX` (an out-of-range wasm
161
    /// section index), so a read *before* `resolve_ids` overwrites it fails wasm
162
    /// validation loudly rather than silently emitting index 0. The two public
163
    /// constructors overwrite this unconditionally before emit can run; it only
164
    /// fills the `ids` field for the brief construction window in which the
165
    /// helper indices it would resolve don't yet exist. This is NOT a `Default`
166
    /// — it's a single named poison value, and the real completeness checkpoint
167
    /// is the all-fields literal in `resolve_ids`.
168
    pub(super) const UNRESOLVED: Self = Self {
169
        gcd: u32::MAX,
170
        ratio_new: u32::MAX,
171
        ratio_add: u32::MAX,
172
        ratio_sub: u32::MAX,
173
        ratio_mul: u32::MAX,
174
        ratio_div: u32::MAX,
175
        ratio_eq: u32::MAX,
176
        ratio_lt: u32::MAX,
177
        ratio_from_i64: u32::MAX,
178
        ratio_to_i64: u32::MAX,
179
        i64_mul_checked: u32::MAX,
180
        i64_add_checked: u32::MAX,
181
        i64_sub_checked: u32::MAX,
182
        unit_singleton: u32::MAX,
183
        unit_mul: u32::MAX,
184
        unit_negate: u32::MAX,
185
        unit_eq: u32::MAX,
186
        materialize_unit: u32::MAX,
187
        commodity_add: u32::MAX,
188
        commodity_sub: u32::MAX,
189
        commodity_mul: u32::MAX,
190
        commodity_div: u32::MAX,
191
        commodity_mul_by_ratio: u32::MAX,
192
        commodity_div_by_ratio: u32::MAX,
193
        commodity_neg: u32::MAX,
194
        commodity_eq: u32::MAX,
195
        commodity_lt: u32::MAX,
196
        commodity_assert_atomic: u32::MAX,
197
        commodity_new: u32::MAX,
198
        commodity_new_with_term: u32::MAX,
199
        pair_new: u32::MAX,
200
        box_index: u32::MAX,
201
        index_div: u32::MAX,
202
        index_rem: u32::MAX,
203
        index_add: u32::MAX,
204
        index_sub: u32::MAX,
205
        index_mul: u32::MAX,
206
        index_narrow: u32::MAX,
207
        box_bool: u32::MAX,
208
        car_of_nil: u32::MAX,
209
        output_overflow: u32::MAX,
210
        not_a_list: u32::MAX,
211
        nil_string: u32::MAX,
212
        nil_entity: u32::MAX,
213
        string_eq: u32::MAX,
214
        symbol_eq: u32::MAX,
215
        pair_equal: u32::MAX,
216
        anyref_equal: u32::MAX,
217
        symbol_designator: u32::MAX,
218
        symbol_keyword_p: u32::MAX,
219
        not_a_symbol: u32::MAX,
220
        not_an_index: u32::MAX,
221
        not_a_scalar: u32::MAX,
222
        not_money: u32::MAX,
223
        not_a_string: u32::MAX,
224
        not_printable: u32::MAX,
225
        not_a_function: u32::MAX,
226
        wrong_function_arguments: u32::MAX,
227
        symbol_not_callable: u32::MAX,
228
        nomi_raise: u32::MAX,
229
        log: u32::MAX,
230
        log_value: u32::MAX,
231
        nomi_catch_each: None,
232
        get_output_offset: None,
233
        get_input_offset: None,
234
        get_input_entities_count: None,
235
        ty_i8_array: u32::MAX,
236
        ty_ratio: u32::MAX,
237
        ty_pair: u32::MAX,
238
        ty_symbol: u32::MAX,
239
        ty_commodity: u32::MAX,
240
        ty_unit_term: u32::MAX,
241
        ty_nomi_condition: u32::MAX,
242
        ty_t: u32::MAX,
243
        global_t: u32::MAX,
244
        ty_account: u32::MAX,
245
        ty_commodity_entity: u32::MAX,
246
        ty_transaction: u32::MAX,
247
        ty_split: u32::MAX,
248
        ty_tag_entity: u32::MAX,
249
        ty_price: u32::MAX,
250
        ty_ssh_key: u32::MAX,
251
        ty_closure_base: u32::MAX,
252
        ty_slots: u32::MAX,
253
        ty_struct: u32::MAX,
254
        struct_new: u32::MAX,
255
        struct_copy: u32::MAX,
256
    };
257

            
258
    /// The wasm struct-type index for an entity kind. Exhaustive over
259
    /// `EntityKind` — a new variant without an arm is a Rust compile error.
260
    /// `Condition` shares the `$nomi_condition` struct (exception support),
261
    /// matching `EntityKind::type_name`.
262
    #[must_use]
263
51341672
    pub fn entity_type(&self, kind: EntityKind) -> u32 {
264
51341672
        match kind {
265
7393865
            EntityKind::Account => self.ty_account,
266
7362213
            EntityKind::Commodity => self.ty_commodity_entity,
267
7264453
            EntityKind::Transaction => self.ty_transaction,
268
7264435
            EntityKind::Split => self.ty_split,
269
7261125
            EntityKind::Tag => self.ty_tag_entity,
270
7256738
            EntityKind::Price => self.ty_price,
271
7257986
            EntityKind::SshKey => self.ty_ssh_key,
272
280857
            EntityKind::Condition => self.ty_nomi_condition,
273
        }
274
51341672
    }
275

            
276
    /// Stores the wasm struct-type index for an entity kind as it registers in
277
    /// `new_skeleton`. Exhaustive over `EntityKind` (mirrors `entity_type`), so
278
    /// a new variant without an arm is a Rust compile error.
279
16468991
    #[spec(ensures: self.entity_type(kind) == idx)]
280
16468991
    pub fn set_entity_type(&mut self, kind: EntityKind, idx: u32) {
281
16468991
        let slot = match kind {
282
2352713
            EntityKind::Account => &mut self.ty_account,
283
2352713
            EntityKind::Commodity => &mut self.ty_commodity_entity,
284
2352713
            EntityKind::Transaction => &mut self.ty_transaction,
285
2352713
            EntityKind::Split => &mut self.ty_split,
286
2352713
            EntityKind::Tag => &mut self.ty_tag_entity,
287
2352713
            EntityKind::Price => &mut self.ty_price,
288
2352713
            EntityKind::SshKey => &mut self.ty_ssh_key,
289
            EntityKind::Condition => &mut self.ty_nomi_condition,
290
        };
291
16468991
        *slot = idx;
292
16468991
    }
293

            
294
    /// A mode-specific import index, or a structured error if read in a module
295
    /// mode that didn't register it (rather than panicking).
296
2095442
    fn mode_import(opt: Option<u32>, name: &str) -> Result<u32> {
297
2095442
        opt.ok_or_else(|| {
298
230
            Error::Compile(format!(
299
230
                "wasm import '{name}' is not registered in this module mode"
300
230
            ))
301
230
        })
302
2095442
    }
303

            
304
9779
    pub fn nomi_catch_each(&self) -> Result<u32> {
305
9779
        Self::mode_import(self.nomi_catch_each, "__nomi_catch_each")
306
9779
    }
307

            
308
1638164
    pub fn get_output_offset(&self) -> Result<u32> {
309
1638164
        Self::mode_import(self.get_output_offset, "get_output_offset")
310
1638164
    }
311

            
312
299705
    pub fn get_input_offset(&self) -> Result<u32> {
313
299705
        Self::mode_import(self.get_input_offset, "get_input_offset")
314
299705
    }
315

            
316
147794
    pub fn get_input_entities_count(&self) -> Result<u32> {
317
147794
        Self::mode_import(self.get_input_entities_count, "get_input_entities_count")
318
147794
    }
319
}
320

            
321
impl CompileContext {
322
    /// Resolves every emit-referenced HELPER-FUNCTION name from the
323
    /// (fully-declared) `func_names` map into the function fields of `WasmIds`,
324
    /// preserving the TYPE fields already populated in `new_skeleton` (the
325
    /// type-ref accessors need those mid-skeleton, before this runs). Called
326
    /// ONCE after all `declare_*` have run. A missing common name is a
327
    /// structured `Error::Compile` (a compiler bug surfaced cleanly, not a
328
    /// panic); the mode-specific imports resolve to `None` in the other mode by
329
    /// design.
330
    /// Resolves the ids and bounds the output serializer's writes by them.
331
3970080
    pub(super) fn install_ids(&mut self) -> Result<()> {
332
3970080
        self.ids = self.resolve_ids()?;
333
3970080
        let overflow_fn = self.ids.output_overflow;
334
3970080
        let limit = self
335
3970080
            .ids
336
3970080
            .get_input_offset
337
            .map(|input_offset_fn| OutputLimit {
338
3234736
                input_offset_fn,
339
3234736
                overflow_fn,
340
3234736
            });
341
3970080
        self.serializer.set_limit(limit);
342
3970080
        Ok(())
343
3970080
    }
344

            
345
3970080
    pub(super) fn resolve_ids(&self) -> Result<WasmIds> {
346
254085120
        let f = |name: &str| -> Result<u32> {
347
254085120
            self.func_names.get(name).copied().ok_or_else(|| {
348
                Error::Compile(format!(
349
                    "internal: wasm function '{name}' was not registered during context construction"
350
                ))
351
            })
352
254085120
        };
353
        Ok(WasmIds {
354
3970080
            gcd: f("gcd")?,
355
3970080
            ratio_new: f("ratio_new")?,
356
3970080
            ratio_add: f("ratio_add")?,
357
3970080
            ratio_sub: f("ratio_sub")?,
358
3970080
            ratio_mul: f("ratio_mul")?,
359
3970080
            ratio_div: f("ratio_div")?,
360
3970080
            ratio_eq: f("ratio_eq")?,
361
3970080
            ratio_lt: f("ratio_lt")?,
362
3970080
            ratio_from_i64: f("ratio_from_i64")?,
363
3970080
            ratio_to_i64: f("ratio_to_i64")?,
364
3970080
            i64_mul_checked: f("i64_mul_checked")?,
365
3970080
            i64_add_checked: f("i64_add_checked")?,
366
3970080
            i64_sub_checked: f("i64_sub_checked")?,
367
3970080
            unit_singleton: f("unit_singleton")?,
368
3970080
            unit_mul: f("unit_mul")?,
369
3970080
            unit_negate: f("unit_negate")?,
370
3970080
            unit_eq: f("unit_eq")?,
371
3970080
            materialize_unit: f("materialize_unit")?,
372
3970080
            commodity_add: f("commodity_add")?,
373
3970080
            commodity_sub: f("commodity_sub")?,
374
3970080
            commodity_mul: f("commodity_mul")?,
375
3970080
            commodity_div: f("commodity_div")?,
376
3970080
            commodity_mul_by_ratio: f("commodity_mul_by_ratio")?,
377
3970080
            commodity_div_by_ratio: f("commodity_div_by_ratio")?,
378
3970080
            commodity_neg: f("commodity_neg")?,
379
3970080
            commodity_eq: f("commodity_eq")?,
380
3970080
            commodity_lt: f("commodity_lt")?,
381
3970080
            commodity_assert_atomic: f("commodity_assert_atomic")?,
382
3970080
            commodity_new: f("commodity_new")?,
383
3970080
            commodity_new_with_term: f("commodity_new_with_term")?,
384
3970080
            pair_new: f("pair_new")?,
385
3970080
            box_index: f("box_index")?,
386
3970080
            index_div: f("index_div")?,
387
3970080
            index_rem: f("index_rem")?,
388
3970080
            index_add: f("index_add")?,
389
3970080
            index_sub: f("index_sub")?,
390
3970080
            index_mul: f("index_mul")?,
391
3970080
            index_narrow: f("index_narrow")?,
392
3970080
            box_bool: f("box_bool")?,
393
3970080
            car_of_nil: f("car_of_nil")?,
394
3970080
            output_overflow: f("output_overflow")?,
395
3970080
            not_a_list: f("not_a_list")?,
396
3970080
            nil_string: f("nil_string")?,
397
3970080
            nil_entity: f("nil_entity")?,
398
3970080
            string_eq: f("string_eq")?,
399
3970080
            symbol_eq: f("symbol_eq")?,
400
3970080
            pair_equal: f("pair_equal")?,
401
3970080
            anyref_equal: f("anyref_equal")?,
402
3970080
            symbol_designator: f("symbol_designator")?,
403
3970080
            symbol_keyword_p: f("symbol_keyword_p")?,
404
3970080
            not_a_symbol: f("not_a_symbol")?,
405
3970080
            not_an_index: f("not_an_index")?,
406
3970080
            not_a_scalar: f("not_a_scalar")?,
407
3970080
            not_money: f("not_money")?,
408
3970080
            not_a_string: f("not_a_string")?,
409
3970080
            not_printable: f("not_printable")?,
410
3970080
            not_a_function: f("not_a_function")?,
411
3970080
            wrong_function_arguments: f("wrong_function_arguments")?,
412
3970080
            symbol_not_callable: f("symbol_not_callable")?,
413
3970080
            nomi_raise: f("__nomi_raise")?,
414
3970080
            log: f("log")?,
415
3970080
            log_value: f("log_value")?,
416
3970080
            nomi_catch_each: self.func_names.get("__nomi_catch_each").copied(),
417
3970080
            get_output_offset: self.func_names.get("get_output_offset").copied(),
418
3970080
            get_input_offset: self.func_names.get("get_input_offset").copied(),
419
3970080
            get_input_entities_count: self.func_names.get("get_input_entities_count").copied(),
420
            // Type fields were populated in `new_skeleton` (the type-ref
421
            // accessors needed them while declaring helper signatures); carry
422
            // them through unchanged.
423
3970080
            ty_i8_array: self.ids.ty_i8_array,
424
3970080
            ty_ratio: self.ids.ty_ratio,
425
3970080
            ty_pair: self.ids.ty_pair,
426
3970080
            ty_symbol: self.ids.ty_symbol,
427
3970080
            ty_commodity: self.ids.ty_commodity,
428
3970080
            ty_unit_term: self.ids.ty_unit_term,
429
3970080
            ty_nomi_condition: self.ids.ty_nomi_condition,
430
3970080
            ty_t: self.ids.ty_t,
431
3970080
            global_t: self.ids.global_t,
432
3970080
            ty_account: self.ids.ty_account,
433
3970080
            ty_commodity_entity: self.ids.ty_commodity_entity,
434
3970080
            ty_transaction: self.ids.ty_transaction,
435
3970080
            ty_split: self.ids.ty_split,
436
3970080
            ty_tag_entity: self.ids.ty_tag_entity,
437
3970080
            ty_price: self.ids.ty_price,
438
3970080
            ty_ssh_key: self.ids.ty_ssh_key,
439
3970080
            ty_closure_base: self.ids.ty_closure_base,
440
3970080
            ty_slots: self.ids.ty_slots,
441
3970080
            ty_struct: self.ids.ty_struct,
442
3970080
            struct_new: f("struct_new")?,
443
3970080
            struct_copy: f("struct_copy")?,
444
        })
445
3970080
    }
446
}