1
//! Guest-side helpers for the Commodity type.
2
//!
3
//! Mirrors `register_ratio_helpers` but for commodity-bearing values.
4
//! `commodity_new` is a thin wrapper around `struct.new commodity`;
5
//! the arithmetic helpers (`commodity_add`, `commodity_sub`, ...) do
6
//! an id-equality check at the front and, on mismatch, `throw` a
7
//! `$nomi_error` carrying a `commodity-mismatch` condition (ADR-0014 +
8
//! ADR-0026). The throw is catchable by an in-module `(handler-case)` /
9
//! `(unwind-protect)`; an uncaught one is bridged to `__nomi_raise` by the
10
//! boundary wrapper, surfacing the same `commodity-mismatch` wire code as
11
//! before — engine errors now travel the single exception channel rather
12
//! than the lone `unreachable` trap. Scaling helpers
13
//! (`commodity_mul_by_ratio`, `commodity_div_by_ratio`) accept a pure Ratio
14
//! second operand and keep the commodity id from the first.
15

            
16
use super::CompileContext;
17
use super::exception::ConditionTrap;
18
use crate::error::Result;
19
use wasm_encoder::{Function, Instruction, ValType};
20

            
21
impl CompileContext {
22
    /// Declares the commodity helper signatures (atomic + compound), no bodies.
23
    /// The compound signatures are registered here too so every commodity index
24
    /// exists before `resolve_ids`; bodies are emitted by
25
    /// [`Self::build_commodity_helpers`] in the same registration order.
26
2352712
    pub(super) fn declare_commodity_helpers(&mut self) -> Result<()> {
27
2352712
        let commodity_ref = self.commodity_ref();
28
2352712
        let ratio_ref = self.ratio_ref();
29
2352712
        self.register_function(
30
2352712
            "commodity_new",
31
2352712
            &[ValType::I64, ValType::I64, ValType::I64, ValType::I64],
32
2352712
            &[commodity_ref],
33
2352712
        )?;
34
2352712
        self.register_function(
35
2352712
            "commodity_add",
36
2352712
            &[commodity_ref, commodity_ref],
37
2352712
            &[commodity_ref],
38
2352712
        )?;
39
2352712
        self.register_function(
40
2352712
            "commodity_sub",
41
2352712
            &[commodity_ref, commodity_ref],
42
2352712
            &[commodity_ref],
43
2352712
        )?;
44
2352712
        self.register_function("commodity_neg", &[commodity_ref], &[commodity_ref])?;
45
2352712
        self.register_function(
46
2352712
            "commodity_mul_by_ratio",
47
2352712
            &[commodity_ref, ratio_ref],
48
2352712
            &[commodity_ref],
49
2352712
        )?;
50
2352712
        self.register_function(
51
2352712
            "commodity_div_by_ratio",
52
2352712
            &[commodity_ref, ratio_ref],
53
2352712
            &[commodity_ref],
54
2352712
        )?;
55
2352712
        self.register_function(
56
2352712
            "commodity_eq",
57
2352712
            &[commodity_ref, commodity_ref],
58
2352712
            &[ValType::I32],
59
2352712
        )?;
60
2352712
        self.register_function(
61
2352712
            "commodity_lt",
62
2352712
            &[commodity_ref, commodity_ref],
63
2352712
            &[ValType::I32],
64
2352712
        )?;
65
        // Exported so the host (`alloc_commodity_ref`) constructs commodity
66
        // values by re-entering this helper rather than building the now
67
        // ref-bearing 5-field struct itself (ADR-0028 E0), mirroring the
68
        // `pair_new` / entity-allocator re-entry pattern.
69
2352712
        self.export_func("commodity_new")?;
70
        // Compound-money helpers (ADR-0028 E2): SIGNATURES only, registered
71
        // after the atomic ones so the function-index order is unchanged.
72
2352712
        self.declare_commodity_compound_signatures()
73
2352712
    }
74

            
75
    /// Emits the commodity helper bodies in registration order. Traps are
76
    /// interned here (build order), so the data-segment index sequence matches
77
    /// the pre-split layout; `&self`-borrowing throw sites read `self.ids`.
78
2352712
    pub(super) fn build_commodity_helpers(&mut self) -> Result<()> {
79
2352712
        let trap = self.register_mismatch_trap()?;
80
2352712
        let non_atomic = self.register_non_atomic_trap()?;
81
2352712
        self.build_commodity_new_body();
82
2352712
        self.build_commodity_binop_bodies(trap);
83
2352712
        self.build_commodity_neg_body();
84
2352712
        self.build_commodity_scale_bodies();
85
2352712
        self.build_commodity_cmp_bodies(trap);
86
2352712
        self.build_commodity_compound_bodies(&non_atomic)?;
87
2352712
        Ok(())
88
2352712
    }
89

            
90
    /// Interns the `commodity-mismatch` condition so each id-check site (which
91
    /// only borrows `&self`) can emit its `throw`. UPPER-CASE to match the
92
    /// reader's symbol case-folding: handler dispatch compares the code
93
    /// byte-for-byte against the upcased clause symbol, and the uncaught wire
94
    /// `:code` is `COMMODITY-MISMATCH` too.
95
2352712
    fn register_mismatch_trap(&mut self) -> Result<ConditionTrap> {
96
2352712
        self.register_condition_trap(
97
2352712
            "COMMODITY-MISMATCH",
98
2352712
            "cannot combine values of different commodities",
99
2352712
        )
100
2352712
    }
101

            
102
2352712
    fn build_commodity_new_body(&mut self) {
103
2352712
        let new_with_term = self.ids.commodity_new_with_term;
104
        // params: $numer=0, $denom=1, $commodity_hi=2, $commodity_lo=3.
105
        // The atomic constructor: delegate to `commodity_new_with_term` with a
106
        // NULL unit term (ATOMIC `[(atom,1)]`). No reduction — callers pass the
107
        // canonical (numer, denom) pair they want.
108
2352712
        let mut f = Function::new([]);
109
2352712
        f.instruction(&Instruction::LocalGet(0));
110
2352712
        f.instruction(&Instruction::LocalGet(1));
111
2352712
        f.instruction(&Instruction::LocalGet(2));
112
2352712
        f.instruction(&Instruction::LocalGet(3));
113
2352712
        self.emit_null_unit_term(&mut f);
114
2352712
        f.instruction(&Instruction::Call(new_with_term));
115
2352712
        f.instruction(&Instruction::End);
116
2352712
        self.pending_helpers.push(f);
117
2352712
    }
118

            
119
    /// Emits the prologue of a same-commodity binop: compares both i64
120
    /// halves of the UUID pair and, on mismatch, throws a `commodity-mismatch`
121
    /// `$nomi_error` (ADR-0026). Caller-supplied param indices (0 and 1 for
122
    /// the standard two-Commodity shape).
123
9410848
    fn emit_commodity_id_check(&self, f: &mut Function, trap: ConditionTrap, a: u32, b: u32) {
124
9410848
        let commodity_idx = self.ids.ty_commodity;
125
        // hi mismatch
126
9410848
        f.instruction(&Instruction::LocalGet(a));
127
9410848
        f.instruction(&Instruction::StructGet {
128
9410848
            struct_type_index: commodity_idx,
129
9410848
            field_index: 2,
130
9410848
        });
131
9410848
        f.instruction(&Instruction::LocalGet(b));
132
9410848
        f.instruction(&Instruction::StructGet {
133
9410848
            struct_type_index: commodity_idx,
134
9410848
            field_index: 2,
135
9410848
        });
136
9410848
        f.instruction(&Instruction::I64Ne);
137
        // lo mismatch
138
9410848
        f.instruction(&Instruction::LocalGet(a));
139
9410848
        f.instruction(&Instruction::StructGet {
140
9410848
            struct_type_index: commodity_idx,
141
9410848
            field_index: 3,
142
9410848
        });
143
9410848
        f.instruction(&Instruction::LocalGet(b));
144
9410848
        f.instruction(&Instruction::StructGet {
145
9410848
            struct_type_index: commodity_idx,
146
9410848
            field_index: 3,
147
9410848
        });
148
9410848
        f.instruction(&Instruction::I64Ne);
149
        // either half differs → build the condition and throw $nomi_error.
150
9410848
        f.instruction(&Instruction::I32Or);
151
9410848
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
152
9410848
        trap.emit_throw(f);
153
9410848
        f.instruction(&Instruction::End);
154
9410848
    }
155

            
156
    /// Unit-aware prologue for add/sub/eq/lt (ADR-0028 E2): when both operands
157
    /// are ATOMIC (null term) it is the cheap hi/lo id-check above; otherwise it
158
    /// compares the materialized unit terms with `unit_eq` and throws
159
    /// `commodity-mismatch` if they differ. Atomic money keeps the exact
160
    /// fast-path behaviour it had before compound money existed.
161
9410848
    fn emit_commodity_unit_check(&self, f: &mut Function, trap: ConditionTrap, a: u32, b: u32) {
162
9410848
        let commodity_idx = self.ids.ty_commodity;
163
9410848
        let materialize = self.ids.materialize_unit;
164
9410848
        let unit_eq = self.ids.unit_eq;
165
        // both terms null?
166
9410848
        f.instruction(&Instruction::LocalGet(a));
167
9410848
        f.instruction(&Instruction::StructGet {
168
9410848
            struct_type_index: commodity_idx,
169
9410848
            field_index: 4,
170
9410848
        });
171
9410848
        f.instruction(&Instruction::RefIsNull);
172
9410848
        f.instruction(&Instruction::LocalGet(b));
173
9410848
        f.instruction(&Instruction::StructGet {
174
9410848
            struct_type_index: commodity_idx,
175
9410848
            field_index: 4,
176
9410848
        });
177
9410848
        f.instruction(&Instruction::RefIsNull);
178
9410848
        f.instruction(&Instruction::I32And);
179
9410848
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
180
9410848
        self.emit_commodity_id_check(f, trap, a, b);
181
9410848
        f.instruction(&Instruction::Else);
182
        // compound: compare materialized terms by multiset equality
183
9410848
        f.instruction(&Instruction::LocalGet(a));
184
9410848
        f.instruction(&Instruction::Call(materialize));
185
9410848
        f.instruction(&Instruction::LocalGet(b));
186
9410848
        f.instruction(&Instruction::Call(materialize));
187
9410848
        f.instruction(&Instruction::Call(unit_eq));
188
9410848
        f.instruction(&Instruction::I32Eqz);
189
9410848
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
190
9410848
        trap.emit_throw(f);
191
9410848
        f.instruction(&Instruction::End);
192
9410848
        f.instruction(&Instruction::End);
193
9410848
    }
194

            
195
    /// Pushes a fresh `ratio_ref` built from the (numer, denom) fields of
196
    /// the commodity at the given param index. Uses `struct.new ratio`
197
    /// directly (no normalization) since the values are already canonical
198
    /// from a prior `ratio_new` / `commodity_new`.
199
32937968
    pub(super) fn emit_ratio_from_commodity(&self, f: &mut Function, param_idx: u32) {
200
32937968
        let commodity_idx = self.ids.ty_commodity;
201
32937968
        let ratio_idx = self.ids.ty_ratio;
202
32937968
        f.instruction(&Instruction::LocalGet(param_idx));
203
32937968
        f.instruction(&Instruction::StructGet {
204
32937968
            struct_type_index: commodity_idx,
205
32937968
            field_index: 0,
206
32937968
        });
207
32937968
        f.instruction(&Instruction::LocalGet(param_idx));
208
32937968
        f.instruction(&Instruction::StructGet {
209
32937968
            struct_type_index: commodity_idx,
210
32937968
            field_index: 1,
211
32937968
        });
212
32937968
        f.instruction(&Instruction::StructNew(ratio_idx));
213
32937968
    }
214

            
215
    /// After a same-commodity binop / scaling produces a result `ratio_ref` (in
216
    /// local $r), repackages it as a `commodity_ref` carrying the id AND unit
217
    /// term of param $a. Add/sub verify both operands share a term, and scaling
218
    /// leaves the unit unchanged, so propagating $a's term (field 4) is correct
219
    /// for every caller and keeps compound money compound (ADR-0028 E2).
220
9410848
    fn emit_commodity_repack(&self, f: &mut Function, ratio_local: u32, a_param: u32) {
221
9410848
        let ratio_idx = self.ids.ty_ratio;
222
9410848
        let commodity_idx = self.ids.ty_commodity;
223
9410848
        let new_with_term = self.ids.commodity_new_with_term;
224
9410848
        f.instruction(&Instruction::LocalGet(ratio_local));
225
9410848
        f.instruction(&Instruction::StructGet {
226
9410848
            struct_type_index: ratio_idx,
227
9410848
            field_index: 0,
228
9410848
        });
229
9410848
        f.instruction(&Instruction::LocalGet(ratio_local));
230
9410848
        f.instruction(&Instruction::StructGet {
231
9410848
            struct_type_index: ratio_idx,
232
9410848
            field_index: 1,
233
9410848
        });
234
9410848
        f.instruction(&Instruction::LocalGet(a_param));
235
9410848
        f.instruction(&Instruction::StructGet {
236
9410848
            struct_type_index: commodity_idx,
237
9410848
            field_index: 2,
238
9410848
        });
239
9410848
        f.instruction(&Instruction::LocalGet(a_param));
240
9410848
        f.instruction(&Instruction::StructGet {
241
9410848
            struct_type_index: commodity_idx,
242
9410848
            field_index: 3,
243
9410848
        });
244
9410848
        f.instruction(&Instruction::LocalGet(a_param));
245
9410848
        f.instruction(&Instruction::StructGet {
246
9410848
            struct_type_index: commodity_idx,
247
9410848
            field_index: 4,
248
9410848
        });
249
9410848
        f.instruction(&Instruction::Call(new_with_term));
250
9410848
    }
251

            
252
2352712
    fn build_commodity_binop_bodies(&mut self, trap: ConditionTrap) {
253
2352712
        let ratio_ref = self.ratio_ref();
254
2352712
        let ratio_add = self.ids.ratio_add;
255
2352712
        let ratio_sub = self.ids.ratio_sub;
256

            
257
        // commodity_add(a, b): id-check, then ratio_add(a.ratio, b.ratio),
258
        // re-pack as commodity carrying a's id. Locals: $r=2 (ratio_ref).
259
2352712
        let mut f = Function::new([(1, ratio_ref)]);
260
2352712
        self.emit_commodity_unit_check(&mut f, trap, 0, 1);
261
2352712
        self.emit_ratio_from_commodity(&mut f, 0);
262
2352712
        self.emit_ratio_from_commodity(&mut f, 1);
263
2352712
        f.instruction(&Instruction::Call(ratio_add));
264
2352712
        f.instruction(&Instruction::LocalSet(2));
265
2352712
        self.emit_commodity_repack(&mut f, 2, 0);
266
2352712
        f.instruction(&Instruction::End);
267
2352712
        self.pending_helpers.push(f);
268

            
269
        // commodity_sub(a, b): id-check, then ratio_sub.
270
2352712
        let mut f = Function::new([(1, ratio_ref)]);
271
2352712
        self.emit_commodity_unit_check(&mut f, trap, 0, 1);
272
2352712
        self.emit_ratio_from_commodity(&mut f, 0);
273
2352712
        self.emit_ratio_from_commodity(&mut f, 1);
274
2352712
        f.instruction(&Instruction::Call(ratio_sub));
275
2352712
        f.instruction(&Instruction::LocalSet(2));
276
2352712
        self.emit_commodity_repack(&mut f, 2, 0);
277
2352712
        f.instruction(&Instruction::End);
278
2352712
        self.pending_helpers.push(f);
279
2352712
    }
280

            
281
2352712
    fn build_commodity_neg_body(&mut self) {
282
2352712
        let commodity_idx = self.ids.ty_commodity;
283
2352712
        let new_with_term = self.ids.commodity_new_with_term;
284
        // commodity_neg(a) = commodity_new_with_term(-a.numer, a.denom, a.hi,
285
        // a.lo, a.term). Negation flips the sign but preserves the unit term, so
286
        // a compound money stays compound (ADR-0028 E2).
287
2352712
        let mut f = Function::new([]);
288
        // -a.numer = 0 - a.numer, checked: negating i64::MIN overflows
289
2352712
        f.instruction(&Instruction::I64Const(0));
290
2352712
        f.instruction(&Instruction::LocalGet(0));
291
2352712
        f.instruction(&Instruction::StructGet {
292
2352712
            struct_type_index: commodity_idx,
293
2352712
            field_index: 0,
294
2352712
        });
295
2352712
        f.instruction(&Instruction::Call(self.ids.i64_sub_checked));
296
        // a.denom
297
2352712
        f.instruction(&Instruction::LocalGet(0));
298
2352712
        f.instruction(&Instruction::StructGet {
299
2352712
            struct_type_index: commodity_idx,
300
2352712
            field_index: 1,
301
2352712
        });
302
        // a.hi
303
2352712
        f.instruction(&Instruction::LocalGet(0));
304
2352712
        f.instruction(&Instruction::StructGet {
305
2352712
            struct_type_index: commodity_idx,
306
2352712
            field_index: 2,
307
2352712
        });
308
        // a.lo
309
2352712
        f.instruction(&Instruction::LocalGet(0));
310
2352712
        f.instruction(&Instruction::StructGet {
311
2352712
            struct_type_index: commodity_idx,
312
2352712
            field_index: 3,
313
2352712
        });
314
        // a.term
315
2352712
        f.instruction(&Instruction::LocalGet(0));
316
2352712
        f.instruction(&Instruction::StructGet {
317
2352712
            struct_type_index: commodity_idx,
318
2352712
            field_index: 4,
319
2352712
        });
320
2352712
        f.instruction(&Instruction::Call(new_with_term));
321
2352712
        f.instruction(&Instruction::End);
322
2352712
        self.pending_helpers.push(f);
323
2352712
    }
324

            
325
2352712
    fn build_commodity_scale_bodies(&mut self) {
326
2352712
        let ratio_ref = self.ratio_ref();
327
2352712
        let ratio_mul = self.ids.ratio_mul;
328
2352712
        let ratio_div = self.ids.ratio_div;
329

            
330
        // commodity_mul_by_ratio(c, r): ratio_mul(c.ratio, r) -> repack with c's id.
331
        // Param 0=c (commodity_ref), param 1=r (ratio_ref). Local 2=result ratio_ref.
332
2352712
        let mut f = Function::new([(1, ratio_ref)]);
333
2352712
        self.emit_ratio_from_commodity(&mut f, 0);
334
2352712
        f.instruction(&Instruction::LocalGet(1));
335
2352712
        f.instruction(&Instruction::Call(ratio_mul));
336
2352712
        f.instruction(&Instruction::LocalSet(2));
337
2352712
        self.emit_commodity_repack(&mut f, 2, 0);
338
2352712
        f.instruction(&Instruction::End);
339
2352712
        self.pending_helpers.push(f);
340

            
341
        // commodity_div_by_ratio(c, r): ratio_div(c.ratio, r) -> repack with c's id.
342
2352712
        let mut f = Function::new([(1, ratio_ref)]);
343
2352712
        self.emit_ratio_from_commodity(&mut f, 0);
344
2352712
        f.instruction(&Instruction::LocalGet(1));
345
2352712
        f.instruction(&Instruction::Call(ratio_div));
346
2352712
        f.instruction(&Instruction::LocalSet(2));
347
2352712
        self.emit_commodity_repack(&mut f, 2, 0);
348
2352712
        f.instruction(&Instruction::End);
349
2352712
        self.pending_helpers.push(f);
350
2352712
    }
351

            
352
2352712
    fn build_commodity_cmp_bodies(&mut self, trap: ConditionTrap) {
353
2352712
        let ratio_eq = self.ids.ratio_eq;
354
2352712
        let ratio_lt = self.ids.ratio_lt;
355

            
356
        // commodity_eq(a, b): id-check, ratio_eq(a.ratio, b.ratio).
357
2352712
        let mut f = Function::new([]);
358
2352712
        self.emit_commodity_unit_check(&mut f, trap, 0, 1);
359
2352712
        self.emit_ratio_from_commodity(&mut f, 0);
360
2352712
        self.emit_ratio_from_commodity(&mut f, 1);
361
2352712
        f.instruction(&Instruction::Call(ratio_eq));
362
2352712
        f.instruction(&Instruction::End);
363
2352712
        self.pending_helpers.push(f);
364

            
365
        // commodity_lt(a, b): id-check, ratio_lt(a.ratio, b.ratio).
366
2352712
        let mut f = Function::new([]);
367
2352712
        self.emit_commodity_unit_check(&mut f, trap, 0, 1);
368
2352712
        self.emit_ratio_from_commodity(&mut f, 0);
369
2352712
        self.emit_ratio_from_commodity(&mut f, 1);
370
2352712
        f.instruction(&Instruction::Call(ratio_lt));
371
2352712
        f.instruction(&Instruction::End);
372
2352712
        self.pending_helpers.push(f);
373
2352712
    }
374
}