1
//! Guest-side helpers for the Ratio type — the integer-fraction
2
//! arithmetic kernel every numeric path bottoms out in.
3
//!
4
//! `ratio_new` reduces by GCD and normalizes the sign so equality
5
//! checks are byte-comparable. The arithmetic and comparison bodies live in
6
//! [`super::ratio_ops`], which never lets an i64 wrap.
7
//! All helpers are guest-side wasm functions registered up-front so
8
//! the codegen can `(call $ratio_*)` against stable function indices.
9

            
10
use super::CompileContext;
11
use super::exception::ConditionTrap;
12
use super::ratio_ops::CHECKED_OPS;
13
use crate::error::Result;
14
use wasm_encoder::{BlockType, Function, Instruction, ValType};
15

            
16
impl CompileContext {
17
    /// Declares the ratio helper signatures (no bodies). Runs before
18
    /// `resolve_ids` so every index exists when `WasmIds` is assembled; the
19
    /// bodies are emitted later by [`Self::build_ratio_helpers`].
20
2352712
    pub(super) fn declare_ratio_helpers(&mut self) -> Result<()> {
21
2352712
        let ratio_ref = self.ratio_ref();
22
2352712
        self.register_function("gcd", &[ValType::I64, ValType::I64], &[ValType::I64])?;
23
2352712
        self.register_function("ratio_new", &[ValType::I64, ValType::I64], &[ratio_ref])?;
24
2352712
        self.register_function("ratio_add", &[ratio_ref, ratio_ref], &[ratio_ref])?;
25
2352712
        self.register_function("ratio_sub", &[ratio_ref, ratio_ref], &[ratio_ref])?;
26
2352712
        self.register_function("ratio_mul", &[ratio_ref, ratio_ref], &[ratio_ref])?;
27
2352712
        self.register_function("ratio_div", &[ratio_ref, ratio_ref], &[ratio_ref])?;
28
2352712
        self.register_function("ratio_eq", &[ratio_ref, ratio_ref], &[ValType::I32])?;
29
2352712
        self.register_function("ratio_lt", &[ratio_ref, ratio_ref], &[ValType::I32])?;
30
2352712
        self.register_function("ratio_from_i64", &[ValType::I64], &[ratio_ref])?;
31
2352712
        self.register_function("ratio_to_i64", &[ratio_ref], &[ValType::I64])?;
32
2352712
        for name in CHECKED_OPS {
33
7058136
            self.register_function(name, &[ValType::I64, ValType::I64], &[ValType::I64])?;
34
        }
35
        // ADR-0033 Phase 6: the host resolves the `$ratio` struct's `HeapType`
36
        // from this export's result type to classify a heterogeneous anyref
37
        // cell — no runtime value is ever taken through it host-side.
38
2352712
        self.export_func("ratio_new")?;
39
2352712
        Ok(())
40
2352712
    }
41

            
42
    /// Emits the ratio helper bodies, in registration order so each maps to its
43
    /// reserved function index. Reads resolved indices from `self.ids`; the
44
    /// `division-by-zero` trap interns its strings here (in build order, so the
45
    /// data-segment index sequence is unchanged from the pre-split layout).
46
2352712
    pub(super) fn build_ratio_helpers(&mut self) -> Result<()> {
47
        // UPPER-CASE matches the reader's symbol case-folding so a script can
48
        // catch it with `(handler-case … (division-by-zero (e) …))`.
49
2352712
        let div_trap = self.register_condition_trap("DIVISION-BY-ZERO", "division by zero")?;
50
2352712
        let overflow = self.register_condition_trap(
51
2352712
            "ARITHMETIC-OVERFLOW",
52
2352712
            "rational arithmetic result outside the 64-bit range",
53
2352712
        )?;
54
2352712
        self.build_gcd_body();
55
2352712
        self.build_ratio_new_body(&div_trap);
56
2352712
        self.build_ratio_binop_bodies(&div_trap);
57
2352712
        self.build_ratio_cmp_bodies();
58
2352712
        self.build_ratio_from_i64_body();
59
2352712
        self.build_ratio_to_i64_body();
60
2352712
        self.build_checked_i64_bodies(&overflow);
61
2352712
        Ok(())
62
2352712
    }
63

            
64
2352712
    fn build_gcd_body(&mut self) {
65
        // Euclidean GCD: gcd(a, b) while b != 0 { t = b; b = a % b; a = t }; abs(a)
66
2352712
        let mut f = Function::new([(1, ValType::I64)]); // local $t
67
        // params: $a=0, $b=1, local: $t=2
68
2352712
        f.instruction(&Instruction::Block(wasm_encoder::BlockType::Empty));
69
2352712
        f.instruction(&Instruction::Loop(wasm_encoder::BlockType::Empty));
70
        // if b == 0, break
71
2352712
        f.instruction(&Instruction::LocalGet(1));
72
2352712
        f.instruction(&Instruction::I64Eqz);
73
2352712
        f.instruction(&Instruction::BrIf(1));
74
        // t = b
75
2352712
        f.instruction(&Instruction::LocalGet(1));
76
2352712
        f.instruction(&Instruction::LocalSet(2));
77
        // b = a % b
78
2352712
        f.instruction(&Instruction::LocalGet(0));
79
2352712
        f.instruction(&Instruction::LocalGet(1));
80
2352712
        f.instruction(&Instruction::I64RemS);
81
2352712
        f.instruction(&Instruction::LocalSet(1));
82
        // a = t
83
2352712
        f.instruction(&Instruction::LocalGet(2));
84
2352712
        f.instruction(&Instruction::LocalSet(0));
85
2352712
        f.instruction(&Instruction::Br(0));
86
2352712
        f.instruction(&Instruction::End); // loop
87
2352712
        f.instruction(&Instruction::End); // block
88
        // return abs(a): `select` keeps its first operand when the test holds
89
2352712
        f.instruction(&Instruction::I64Const(0));
90
2352712
        f.instruction(&Instruction::LocalGet(0));
91
2352712
        f.instruction(&Instruction::I64Sub);
92
2352712
        f.instruction(&Instruction::LocalGet(0));
93
2352712
        f.instruction(&Instruction::LocalGet(0));
94
2352712
        f.instruction(&Instruction::I64Const(0));
95
2352712
        f.instruction(&Instruction::I64LtS);
96
2352712
        f.instruction(&Instruction::Select);
97
2352712
        f.instruction(&Instruction::End);
98
2352712
        self.pending_helpers.push(f);
99
2352712
    }
100

            
101
2352712
    fn build_ratio_new_body(&mut self, div_trap: &ConditionTrap) {
102
2352712
        let ratio_idx = self.ids.ty_ratio;
103
2352712
        let gcd_func = self.ids.gcd;
104
        // ratio_new(num, denom) -> reduce by GCD, normalize sign
105
        // params: $num=0, $denom=1, locals: $g=2
106
2352712
        let mut f = Function::new([(1, ValType::I64)]);
107
        // denom == 0 → throw a catchable `division-by-zero` rather than build a
108
        // degenerate ratio (or trap in `gcd(0,0)` / a later `i64.div_s`).
109
2352712
        f.instruction(&Instruction::LocalGet(1));
110
2352712
        f.instruction(&Instruction::I64Eqz);
111
2352712
        f.instruction(&Instruction::If(BlockType::Empty));
112
2352712
        div_trap.emit_throw(&mut f);
113
2352712
        f.instruction(&Instruction::End);
114
        // g = gcd(num, denom)
115
2352712
        f.instruction(&Instruction::LocalGet(0));
116
2352712
        f.instruction(&Instruction::LocalGet(1));
117
2352712
        f.instruction(&Instruction::Call(gcd_func));
118
2352712
        f.instruction(&Instruction::LocalSet(2));
119
        // num = num / g
120
2352712
        f.instruction(&Instruction::LocalGet(0));
121
2352712
        f.instruction(&Instruction::LocalGet(2));
122
2352712
        f.instruction(&Instruction::I64DivS);
123
2352712
        f.instruction(&Instruction::LocalSet(0));
124
        // denom = denom / g
125
2352712
        f.instruction(&Instruction::LocalGet(1));
126
2352712
        f.instruction(&Instruction::LocalGet(2));
127
2352712
        f.instruction(&Instruction::I64DivS);
128
2352712
        f.instruction(&Instruction::LocalSet(1));
129
        // if denom < 0 { num = -num; denom = -denom }, checked: i64::MIN has
130
        // no negation
131
2352712
        f.instruction(&Instruction::LocalGet(1));
132
2352712
        f.instruction(&Instruction::I64Const(0));
133
2352712
        f.instruction(&Instruction::I64LtS);
134
2352712
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
135
2352712
        for local in [0, 1] {
136
4705424
            f.instruction(&Instruction::I64Const(0));
137
4705424
            f.instruction(&Instruction::LocalGet(local));
138
4705424
            f.instruction(&Instruction::Call(self.ids.i64_sub_checked));
139
4705424
            f.instruction(&Instruction::LocalSet(local));
140
        }
141
2352712
        f.instruction(&Instruction::End);
142
        // struct.new $ratio (num, denom)
143
2352712
        f.instruction(&Instruction::LocalGet(0));
144
2352712
        f.instruction(&Instruction::LocalGet(1));
145
2352712
        f.instruction(&Instruction::StructNew(ratio_idx));
146
2352712
        f.instruction(&Instruction::End);
147
2352712
        self.pending_helpers.push(f);
148
2352712
    }
149

            
150
2352712
    fn build_ratio_from_i64_body(&mut self) {
151
2352712
        let ratio_idx = self.ids.ty_ratio;
152
        // ratio_from_i64(n) -> struct.new $ratio (n, 1)
153
2352712
        let mut f = Function::new([]);
154
2352712
        f.instruction(&Instruction::LocalGet(0));
155
2352712
        f.instruction(&Instruction::I64Const(1));
156
2352712
        f.instruction(&Instruction::StructNew(ratio_idx));
157
2352712
        f.instruction(&Instruction::End);
158
2352712
        self.pending_helpers.push(f);
159
2352712
    }
160

            
161
2352712
    fn build_ratio_to_i64_body(&mut self) {
162
2352712
        let ratio_idx = self.ids.ty_ratio;
163
        // ratio_to_i64(r) -> r.numer / r.denom  (i64.div_s truncates toward zero,
164
        // matching ADR-0028's scalar->index narrowing). denom is never 0: the
165
        // only path that could build a denom-0 ratio is division by a zero
166
        // divisor, which `ratio_div` now throws on — so no guard is needed here.
167
2352712
        let mut f = Function::new([]);
168
2352712
        f.instruction(&Instruction::LocalGet(0));
169
2352712
        f.instruction(&Instruction::StructGet {
170
2352712
            struct_type_index: ratio_idx,
171
2352712
            field_index: 0,
172
2352712
        });
173
2352712
        f.instruction(&Instruction::LocalGet(0));
174
2352712
        f.instruction(&Instruction::StructGet {
175
2352712
            struct_type_index: ratio_idx,
176
2352712
            field_index: 1,
177
2352712
        });
178
2352712
        f.instruction(&Instruction::I64DivS);
179
2352712
        f.instruction(&Instruction::End);
180
2352712
        self.pending_helpers.push(f);
181
2352712
    }
182
}