Lines
100 %
Functions
Branches
//! Guest-side helpers for the Ratio type — the integer-fraction
//! arithmetic kernel every numeric path bottoms out in.
//!
//! `ratio_new` reduces by GCD and normalizes the sign so equality
//! checks are byte-comparable. The arithmetic and comparison bodies live in
//! [`super::ratio_ops`], which never lets an i64 wrap.
//! All helpers are guest-side wasm functions registered up-front so
//! the codegen can `(call $ratio_*)` against stable function indices.
use super::CompileContext;
use super::exception::ConditionTrap;
use super::ratio_ops::CHECKED_OPS;
use crate::error::Result;
use wasm_encoder::{BlockType, Function, Instruction, ValType};
impl CompileContext {
/// Declares the ratio helper signatures (no bodies). Runs before
/// `resolve_ids` so every index exists when `WasmIds` is assembled; the
/// bodies are emitted later by [`Self::build_ratio_helpers`].
pub(super) fn declare_ratio_helpers(&mut self) -> Result<()> {
let ratio_ref = self.ratio_ref();
self.register_function("gcd", &[ValType::I64, ValType::I64], &[ValType::I64])?;
self.register_function("ratio_new", &[ValType::I64, ValType::I64], &[ratio_ref])?;
self.register_function("ratio_add", &[ratio_ref, ratio_ref], &[ratio_ref])?;
self.register_function("ratio_sub", &[ratio_ref, ratio_ref], &[ratio_ref])?;
self.register_function("ratio_mul", &[ratio_ref, ratio_ref], &[ratio_ref])?;
self.register_function("ratio_div", &[ratio_ref, ratio_ref], &[ratio_ref])?;
self.register_function("ratio_eq", &[ratio_ref, ratio_ref], &[ValType::I32])?;
self.register_function("ratio_lt", &[ratio_ref, ratio_ref], &[ValType::I32])?;
self.register_function("ratio_from_i64", &[ValType::I64], &[ratio_ref])?;
self.register_function("ratio_to_i64", &[ratio_ref], &[ValType::I64])?;
for name in CHECKED_OPS {
self.register_function(name, &[ValType::I64, ValType::I64], &[ValType::I64])?;
}
// ADR-0033 Phase 6: the host resolves the `$ratio` struct's `HeapType`
// from this export's result type to classify a heterogeneous anyref
// cell — no runtime value is ever taken through it host-side.
self.export_func("ratio_new")?;
Ok(())
/// Emits the ratio helper bodies, in registration order so each maps to its
/// reserved function index. Reads resolved indices from `self.ids`; the
/// `division-by-zero` trap interns its strings here (in build order, so the
/// data-segment index sequence is unchanged from the pre-split layout).
pub(super) fn build_ratio_helpers(&mut self) -> Result<()> {
// UPPER-CASE matches the reader's symbol case-folding so a script can
// catch it with `(handler-case … (division-by-zero (e) …))`.
let div_trap = self.register_condition_trap("DIVISION-BY-ZERO", "division by zero")?;
let overflow = self.register_condition_trap(
"ARITHMETIC-OVERFLOW",
"rational arithmetic result outside the 64-bit range",
)?;
self.build_gcd_body();
self.build_ratio_new_body(&div_trap);
self.build_ratio_binop_bodies(&div_trap);
self.build_ratio_cmp_bodies();
self.build_ratio_from_i64_body();
self.build_ratio_to_i64_body();
self.build_checked_i64_bodies(&overflow);
fn build_gcd_body(&mut self) {
// Euclidean GCD: gcd(a, b) while b != 0 { t = b; b = a % b; a = t }; abs(a)
let mut f = Function::new([(1, ValType::I64)]); // local $t
// params: $a=0, $b=1, local: $t=2
f.instruction(&Instruction::Block(wasm_encoder::BlockType::Empty));
f.instruction(&Instruction::Loop(wasm_encoder::BlockType::Empty));
// if b == 0, break
f.instruction(&Instruction::LocalGet(1));
f.instruction(&Instruction::I64Eqz);
f.instruction(&Instruction::BrIf(1));
// t = b
f.instruction(&Instruction::LocalSet(2));
// b = a % b
f.instruction(&Instruction::LocalGet(0));
f.instruction(&Instruction::I64RemS);
f.instruction(&Instruction::LocalSet(1));
// a = t
f.instruction(&Instruction::LocalGet(2));
f.instruction(&Instruction::LocalSet(0));
f.instruction(&Instruction::Br(0));
f.instruction(&Instruction::End); // loop
f.instruction(&Instruction::End); // block
// return abs(a): `select` keeps its first operand when the test holds
f.instruction(&Instruction::I64Const(0));
f.instruction(&Instruction::I64Sub);
f.instruction(&Instruction::I64LtS);
f.instruction(&Instruction::Select);
f.instruction(&Instruction::End);
self.pending_helpers.push(f);
fn build_ratio_new_body(&mut self, div_trap: &ConditionTrap) {
let ratio_idx = self.ids.ty_ratio;
let gcd_func = self.ids.gcd;
// ratio_new(num, denom) -> reduce by GCD, normalize sign
// params: $num=0, $denom=1, locals: $g=2
let mut f = Function::new([(1, ValType::I64)]);
// denom == 0 → throw a catchable `division-by-zero` rather than build a
// degenerate ratio (or trap in `gcd(0,0)` / a later `i64.div_s`).
f.instruction(&Instruction::If(BlockType::Empty));
div_trap.emit_throw(&mut f);
// g = gcd(num, denom)
f.instruction(&Instruction::Call(gcd_func));
// num = num / g
f.instruction(&Instruction::I64DivS);
// denom = denom / g
// if denom < 0 { num = -num; denom = -denom }, checked: i64::MIN has
// no negation
f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
for local in [0, 1] {
f.instruction(&Instruction::LocalGet(local));
f.instruction(&Instruction::Call(self.ids.i64_sub_checked));
f.instruction(&Instruction::LocalSet(local));
// struct.new $ratio (num, denom)
f.instruction(&Instruction::StructNew(ratio_idx));
fn build_ratio_from_i64_body(&mut self) {
// ratio_from_i64(n) -> struct.new $ratio (n, 1)
let mut f = Function::new([]);
f.instruction(&Instruction::I64Const(1));
fn build_ratio_to_i64_body(&mut self) {
// ratio_to_i64(r) -> r.numer / r.denom (i64.div_s truncates toward zero,
// matching ADR-0028's scalar->index narrowing). denom is never 0: the
// only path that could build a denom-0 ratio is division by a zero
// divisor, which `ratio_div` now throws on — so no guard is needed here.
f.instruction(&Instruction::StructGet {
struct_type_index: ratio_idx,
field_index: 0,
});
field_index: 1,