1
//! Compound-money guest helpers (ADR-0028 E2): the bridge between the
2
//! `$commodity` struct's `(numer, denom, hi, lo)` ratio+id fields and its
3
//! runtime unit term (see [`super::unit_term`]).
4
//!
5
//! `commodity_new_with_term` is the single `struct.new $commodity` site;
6
//! `commodity_new` (the atomic constructor) delegates to it with a null term.
7
//! `commodity_mul` / `commodity_div` multiply/divide the ratios and combine
8
//! the unit terms — a same-currency division cancels to an EMPTY term
9
//! (dimensionless), a cross-currency one produces a compound term. The unit is
10
//! erased at the wasm↔host border by `commodity_assert_atomic`, which throws a
11
//! catchable `NON-ATOMIC-COMMODITY` if a non-atomic value reaches a host fn.
12

            
13
use super::CompileContext;
14
use super::exception::ConditionTrap;
15
use crate::error::Result;
16
use wasm_encoder::{BlockType, Function, HeapType, Instruction, ValType};
17

            
18
impl CompileContext {
19
    /// Registers the compound-helper SIGNATURES (and interns the
20
    /// `NON-ATOMIC-COMMODITY` condition), returning the trap. Split from body
21
    /// building so the caller registers these signatures up-front — their
22
    /// indices must exist before `commodity_new` / the binop unit-checks
23
    /// reference them — yet emits their BODIES last: `pending_helpers` maps
24
    /// bodies to function indices in registration order, so body-build order
25
    /// must match registration order.
26
2352712
    pub(super) fn declare_commodity_compound_signatures(&mut self) -> Result<()> {
27
2352712
        let commodity_ref = self.commodity_ref();
28
2352712
        let unit_ref = self.unit_term_ref();
29
2352712
        self.register_function(
30
2352712
            "commodity_new_with_term",
31
2352712
            &[
32
2352712
                ValType::I64,
33
2352712
                ValType::I64,
34
2352712
                ValType::I64,
35
2352712
                ValType::I64,
36
2352712
                unit_ref,
37
2352712
            ],
38
2352712
            &[commodity_ref],
39
2352712
        )?;
40
2352712
        self.register_function("materialize_unit", &[commodity_ref], &[unit_ref])?;
41
2352712
        self.register_function(
42
2352712
            "commodity_mul",
43
2352712
            &[commodity_ref, commodity_ref],
44
2352712
            &[commodity_ref],
45
2352712
        )?;
46
2352712
        self.register_function(
47
2352712
            "commodity_div",
48
2352712
            &[commodity_ref, commodity_ref],
49
2352712
            &[commodity_ref],
50
2352712
        )?;
51
2352712
        self.register_function(
52
2352712
            "commodity_assert_atomic",
53
2352712
            &[commodity_ref],
54
2352712
            &[commodity_ref],
55
2352712
        )?;
56
2352712
        Ok(())
57
2352712
    }
58

            
59
    /// Emits the compound-helper bodies, in the SAME order their signatures were
60
    /// registered by [`Self::register_commodity_compound_signatures`].
61
2352712
    pub(super) fn build_commodity_compound_bodies(&mut self, trap: &ConditionTrap) -> Result<()> {
62
2352712
        self.build_commodity_new_with_term_body();
63
2352712
        self.build_materialize_unit_body();
64
2352712
        self.build_commodity_mul_body();
65
2352712
        self.build_commodity_div_body()?;
66
2352712
        self.build_commodity_assert_atomic_body(trap);
67
2352712
        Ok(())
68
2352712
    }
69

            
70
2352712
    pub(super) fn register_non_atomic_trap(&mut self) -> Result<ConditionTrap> {
71
2352712
        self.register_condition_trap(
72
2352712
            "NON-ATOMIC-COMMODITY",
73
2352712
            "host functions require single-currency (atomic) money",
74
2352712
        )
75
2352712
    }
76

            
77
    /// The sole `struct.new $commodity` site: `(numer, denom, hi, lo, term)`,
78
    /// with one CANONICALIZATION — a non-null SINGLETON term `[(id, 1)]` is
79
    /// semantically ATOMIC money (e.g. `(* (/ usd usd) usd)` = dimensionless ×
80
    /// usd → a `[(usd,1)]` term), so it is rebuilt as atomic: null term, id from
81
    /// the triple. Otherwise: a null term stays atomic, an empty term stays
82
    /// dimensionless, and a true compound term (len > 3, or len 3 with exp ≠ 1)
83
    /// stays non-null with id fields 0. Without this, valid arithmetic that
84
    /// reduces to a single currency would be mis-flagged compound and rejected
85
    /// by the host-border guard / decoder.
86
2352712
    fn build_commodity_new_with_term_body(&mut self) {
87
2352712
        let commodity_idx = self.ids.ty_commodity;
88
2352712
        let unit_idx = self.ids.ty_unit_term;
89
2352712
        let commodity_ref = self.commodity_ref();
90
2352712
        let mut f = Function::new([]);
91

            
92
        // Keep id fields + term verbatim (atomic-null / dimensionless-empty /
93
        // compound). Used by every non-canonicalizable branch.
94
7058136
        let emit_passthrough = |f: &mut Function| {
95
7058136
            for p in 0..5 {
96
35290680
                f.instruction(&Instruction::LocalGet(p));
97
            }
98
7058136
            f.instruction(&Instruction::StructNew(commodity_idx));
99
7058136
        };
100

            
101
2352712
        f.instruction(&Instruction::LocalGet(4));
102
2352712
        f.instruction(&Instruction::RefIsNull);
103
2352712
        f.instruction(&Instruction::I32Eqz); // term non-null?
104
2352712
        f.instruction(&Instruction::If(BlockType::Result(commodity_ref)));
105
        // Non-null term: a `len == 3` term MIGHT be a singleton — only then is it
106
        // safe to read its exponent (`array.get 2` on a shorter term would trap).
107
2352712
        f.instruction(&Instruction::LocalGet(4));
108
2352712
        f.instruction(&Instruction::ArrayLen);
109
2352712
        f.instruction(&Instruction::I32Const(3));
110
2352712
        f.instruction(&Instruction::I32Eq);
111
2352712
        f.instruction(&Instruction::If(BlockType::Result(commodity_ref)));
112
2352712
        f.instruction(&Instruction::LocalGet(4));
113
2352712
        f.instruction(&Instruction::I32Const(2));
114
2352712
        f.instruction(&Instruction::ArrayGet(unit_idx)); // exponent
115
2352712
        f.instruction(&Instruction::I64Const(1));
116
2352712
        f.instruction(&Instruction::I64Eq);
117
2352712
        f.instruction(&Instruction::If(BlockType::Result(commodity_ref)));
118
        // Singleton exponent 1 → canonical atomic: id from the triple, null term.
119
2352712
        f.instruction(&Instruction::LocalGet(0));
120
2352712
        f.instruction(&Instruction::LocalGet(1));
121
2352712
        f.instruction(&Instruction::LocalGet(4));
122
2352712
        f.instruction(&Instruction::I32Const(0));
123
2352712
        f.instruction(&Instruction::ArrayGet(unit_idx)); // hi
124
2352712
        f.instruction(&Instruction::LocalGet(4));
125
2352712
        f.instruction(&Instruction::I32Const(1));
126
2352712
        f.instruction(&Instruction::ArrayGet(unit_idx)); // lo
127
2352712
        self.emit_null_unit_term(&mut f);
128
2352712
        f.instruction(&Instruction::StructNew(commodity_idx));
129
2352712
        f.instruction(&Instruction::Else);
130
2352712
        emit_passthrough(&mut f); // len 3, exp ≠ 1 → genuine compound
131
2352712
        f.instruction(&Instruction::End);
132
2352712
        f.instruction(&Instruction::Else);
133
2352712
        emit_passthrough(&mut f); // empty (dimensionless) or len > 3 (compound)
134
2352712
        f.instruction(&Instruction::End);
135
2352712
        f.instruction(&Instruction::Else);
136
2352712
        emit_passthrough(&mut f); // null term → atomic
137
2352712
        f.instruction(&Instruction::End);
138

            
139
2352712
        f.instruction(&Instruction::End);
140
2352712
        self.pending_helpers.push(f);
141
2352712
    }
142

            
143
    /// `materialize_unit(c)` → the effective unit term: a null (atomic) term
144
    /// becomes the singleton `[(c.hi, c.lo, 1)]`; a present term is returned
145
    /// as-is. The result is always non-null, so term arithmetic can `array.len`
146
    /// it without a trap.
147
2352712
    fn build_materialize_unit_body(&mut self) {
148
2352712
        let commodity_idx = self.ids.ty_commodity;
149
2352712
        let unit_ref = self.unit_term_ref();
150
2352712
        let unit_singleton = self.ids.unit_singleton;
151
2352712
        let mut f = Function::new([]);
152
2352712
        f.instruction(&Instruction::LocalGet(0));
153
2352712
        f.instruction(&Instruction::StructGet {
154
2352712
            struct_type_index: commodity_idx,
155
2352712
            field_index: 4,
156
2352712
        });
157
2352712
        f.instruction(&Instruction::RefIsNull);
158
2352712
        f.instruction(&Instruction::If(BlockType::Result(unit_ref)));
159
        // atomic: singleton from the id fields
160
2352712
        f.instruction(&Instruction::LocalGet(0));
161
2352712
        f.instruction(&Instruction::StructGet {
162
2352712
            struct_type_index: commodity_idx,
163
2352712
            field_index: 2,
164
2352712
        });
165
2352712
        f.instruction(&Instruction::LocalGet(0));
166
2352712
        f.instruction(&Instruction::StructGet {
167
2352712
            struct_type_index: commodity_idx,
168
2352712
            field_index: 3,
169
2352712
        });
170
2352712
        f.instruction(&Instruction::Call(unit_singleton));
171
2352712
        f.instruction(&Instruction::Else);
172
        // compound/dimensionless: the present term
173
2352712
        f.instruction(&Instruction::LocalGet(0));
174
2352712
        f.instruction(&Instruction::StructGet {
175
2352712
            struct_type_index: commodity_idx,
176
2352712
            field_index: 4,
177
2352712
        });
178
2352712
        f.instruction(&Instruction::End);
179
2352712
        f.instruction(&Instruction::End);
180
2352712
        self.pending_helpers.push(f);
181
2352712
    }
182

            
183
    /// `commodity_mul(a, b)` — multiply ratios, merge unit terms. Always
184
    /// produces a value whose unit is the term (id fields 0); a money × money
185
    /// is inherently compound.
186
2352712
    fn build_commodity_mul_body(&mut self) {
187
2352712
        self.build_commodity_combine_body(self.ids.ratio_mul, self.ids.unit_mul);
188
2352712
    }
189

            
190
    /// `commodity_div(a, b)` — divide ratios, subtract unit terms. Same
191
    /// currency cancels to an empty (dimensionless) term; different currencies
192
    /// give a compound term. `unit_div` has no `WasmIds` field (it is referenced
193
    /// only here), so its index is looked up from the declared func map once.
194
2352712
    fn build_commodity_div_body(&mut self) -> Result<()> {
195
2352712
        let unit_div = self.declared_func_index("unit_div")?;
196
2352712
        self.build_commodity_combine_body(self.ids.ratio_div, unit_div);
197
2352712
        Ok(())
198
2352712
    }
199

            
200
    /// Shared body for `commodity_mul`/`commodity_div`: `ratio_op` combines the
201
    /// two ratios, `unit_op` combines the two materialized unit terms, and the
202
    /// result is packed with id fields zeroed (the term is the unit of truth).
203
4705424
    fn build_commodity_combine_body(&mut self, ratio_op: u32, unit_op: u32) {
204
4705424
        let ratio_idx = self.ids.ty_ratio;
205
4705424
        let ratio_ref = self.ratio_ref();
206
4705424
        let unit_ref = self.unit_term_ref();
207
4705424
        let materialize = self.ids.materialize_unit;
208
4705424
        let new_with_term = self.ids.commodity_new_with_term;
209
        // locals: $r=2 (ratio_ref), $term=3 (unit_ref)
210
4705424
        let mut f = Function::new([(1, ratio_ref), (1, unit_ref)]);
211
4705424
        self.emit_ratio_from_commodity(&mut f, 0);
212
4705424
        self.emit_ratio_from_commodity(&mut f, 1);
213
4705424
        f.instruction(&Instruction::Call(ratio_op));
214
4705424
        f.instruction(&Instruction::LocalSet(2));
215
4705424
        f.instruction(&Instruction::LocalGet(0));
216
4705424
        f.instruction(&Instruction::Call(materialize));
217
4705424
        f.instruction(&Instruction::LocalGet(1));
218
4705424
        f.instruction(&Instruction::Call(materialize));
219
4705424
        f.instruction(&Instruction::Call(unit_op));
220
4705424
        f.instruction(&Instruction::LocalSet(3));
221
        // commodity_new_with_term(r.numer, r.denom, 0, 0, term)
222
4705424
        f.instruction(&Instruction::LocalGet(2));
223
4705424
        f.instruction(&Instruction::StructGet {
224
4705424
            struct_type_index: ratio_idx,
225
4705424
            field_index: 0,
226
4705424
        });
227
4705424
        f.instruction(&Instruction::LocalGet(2));
228
4705424
        f.instruction(&Instruction::StructGet {
229
4705424
            struct_type_index: ratio_idx,
230
4705424
            field_index: 1,
231
4705424
        });
232
4705424
        f.instruction(&Instruction::I64Const(0));
233
4705424
        f.instruction(&Instruction::I64Const(0));
234
4705424
        f.instruction(&Instruction::LocalGet(3));
235
4705424
        f.instruction(&Instruction::Call(new_with_term));
236
4705424
        f.instruction(&Instruction::End);
237
4705424
        self.pending_helpers.push(f);
238
4705424
    }
239

            
240
    /// `commodity_assert_atomic(c)` → `c` if its term is null (atomic), else a
241
    /// catchable `NON-ATOMIC-COMMODITY` throw. Emitted at the host border so a
242
    /// compound money never reaches a host fn (which sees only fields 0-3).
243
2352712
    fn build_commodity_assert_atomic_body(&mut self, trap: &ConditionTrap) {
244
2352712
        let commodity_idx = self.ids.ty_commodity;
245
2352712
        let mut f = Function::new([]);
246
2352712
        f.instruction(&Instruction::LocalGet(0));
247
2352712
        f.instruction(&Instruction::StructGet {
248
2352712
            struct_type_index: commodity_idx,
249
2352712
            field_index: 4,
250
2352712
        });
251
2352712
        f.instruction(&Instruction::RefIsNull);
252
2352712
        f.instruction(&Instruction::I32Eqz);
253
2352712
        f.instruction(&Instruction::If(BlockType::Empty));
254
2352712
        trap.emit_throw(&mut f);
255
2352712
        f.instruction(&Instruction::End);
256
2352712
        f.instruction(&Instruction::LocalGet(0));
257
2352712
        f.instruction(&Instruction::End);
258
2352712
        self.pending_helpers.push(f);
259
2352712
    }
260

            
261
    /// Pushes `ref.null $unit_term` (the ATOMIC term marker) onto the stack.
262
4705424
    pub(super) fn emit_null_unit_term(&self, f: &mut Function) {
263
4705424
        f.instruction(&Instruction::RefNull(HeapType::Concrete(
264
4705424
            self.ids.ty_unit_term,
265
4705424
        )));
266
4705424
    }
267
}