Lines
100 %
Functions
Branches
//! Constant-folding eval handlers for `+ - * / MOD` over the ADR-0028
//! lattice. An all-literal call folds to an `Expr::Number` (all-Index
//! operands fold with Index semantics — `/` truncates, `MOD` is floored —
//! so the eval surface agrees with the `i32.div_s` codegen and the floored `index_rem`);
//! otherwise the handler returns `Expr::WasmRuntime(result_dim)`, refusing the
//! dimension mixes codegen refuses.
use anodized::spec;
use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub};
use crate::ast::{Expr, Fraction, Number};
use crate::compiler::expr::{DIVISION_BY_ZERO, eval_value, fold_value, format_expr};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::ArithOp;
use super::emit::{Dim, decided_over_dims, op_name, scaling_dim, shared_dim};
/// The operands as numbers when every one is a fold-safe constant, so the
/// call folds without emitting them; `None` sends the call to codegen, which
/// compiles each operand's effects itself.
#[spec(ensures: |ref output| output.as_ref().is_ok_and(|nums| nums.as_ref().is_none_or(|ops| ops.nums.len() == args.len())) || output.is_err())]
pub(super) fn try_fold(
symbols: &mut SymbolTable,
args: &[Expr],
op: ArithOp,
) -> Result<Option<Operands>> {
let mut folded = Vec::with_capacity(args.len());
for arg in args {
match fold_value(symbols, arg)? {
Some(value) => folded.push(value),
None => return Ok(None),
}
Operands::of(&folded, op)
/// The constant operands of a fold: each keeping its kind, and its value.
pub(super) struct Operands {
pub(super) nums: Vec<Number>,
pub(super) values: Vec<Fraction>,
impl Operands {
/// The operands when every one is a number; a kind mix is an error.
pub(super) fn of(values: &[Expr], op: ArithOp) -> Result<Option<Self>> {
let Some(nums) = values
.iter()
.map(|value| match value {
Expr::Number(n) => Some(*n),
_ => None,
})
.collect::<Option<Vec<_>>>()
else {
return Ok(None);
};
shared_dim(nums.iter().map(|n| Dim::of_number(*n)), op_name(op))?;
let values = nums.iter().map(|n| n.value()).collect();
Ok(Some(Self { nums, values }))
/// Whether every operand is an index, so `/` truncates.
pub(super) fn is_index(&self) -> bool {
self.nums.iter().all(|n| matches!(n, Number::Index(_)))
/// The folded `value` as an eval value, in the fold's dimension.
pub(super) fn folded(&self, value: Fraction) -> Expr {
Expr::Number(self.kinded(value))
/// `value` as a literal of the fold's kind.
pub(super) fn kinded(&self, value: Fraction) -> Number {
match self.is_index() {
true => Number::Index(*value.numer()),
false => Number::Scalar(value),
fn operand_dim(value: &Expr) -> Result<Dim> {
Dim::of_value(value).ok_or_else(|| {
Error::Compile(format!(
"expected number arguments, got {}",
format_expr(value)
))
/// The result of `+ - MOD` over operands that are not all constants: the one
/// dimension they share, an index when every operand raises.
fn additive_type(
symbols: &SymbolTable,
resolved: &[Expr],
) -> Result<Expr> {
let dim = decided_over_dims(symbols, (args, resolved), operand_dim, |dims| {
shared_dim(dims.iter().flatten().copied(), op_name(op))
})?;
Ok(Expr::WasmRuntime(dim.unwrap_or(Dim::Index).wasm_type()))
/// The result of `*` / `/` over operands that are not all constants: the
/// dimension codegen's left-associative `combine_scaling` leaves.
fn scaled_type(
scaling_dim(op, dims)
Ok(Expr::WasmRuntime(dim.wasm_type()))
/// The `Fraction` (`Ratio<i64>`) operators panic (debug / `overflow-checks`) or
/// wrap (release) when a cross-multiply exceeds i64 — reachable from any
/// all-literal `(* huge huge)` / `(+ a/b c/d)` whose reduced terms overflow. So
/// const-fold through the `Checked*` traits and surface a structured
/// `Error::Compile` instead, per CLAUDE.md (never a panic / SIGABRT on input).
fn overflow() -> Error {
Error::Compile("arithmetic overflow in constant expression".to_string())
/// The one fold error that moves to the runtime trap (ISS-065): the guest
/// raises a catchable `DIVISION-BY-ZERO`, whereas a constant overflow has no
/// runtime condition and stays a compile error.
fn division_by_zero() -> Error {
Error::Compile(DIVISION_BY_ZERO.to_string())
pub(in crate::compiler) fn fold_add(nums: &[Fraction]) -> Result<Fraction> {
nums.iter().try_fold(Fraction::from_integer(0), |a, b| {
a.checked_add(b).ok_or_else(overflow)
#[spec(requires: !nums.is_empty())]
pub(in crate::compiler) fn fold_sub(nums: &[Fraction]) -> Result<Fraction> {
if nums.len() == 1 {
return Fraction::from_integer(0)
.checked_sub(&nums[0])
.ok_or_else(overflow);
nums[1..]
.try_fold(nums[0], |a, b| a.checked_sub(b).ok_or_else(overflow))
pub(in crate::compiler) fn fold_mul(nums: &[Fraction]) -> Result<Fraction> {
nums.iter().try_fold(Fraction::from_integer(1), |a, b| {
a.checked_mul(b).ok_or_else(overflow)
/// Const-fold `/`: all-integer operands divide as Index (truncating toward
/// zero, matching `i32.div_s`); any fractional operand divides rationally.
pub(in crate::compiler) fn fold_div(nums: &[Fraction], index: bool) -> Result<Fraction> {
if *nums[0].numer() == 0 {
return Err(division_by_zero());
return Ok(if index {
// `1 / numer` can't overflow, but keep the lattice's truncating
// Index semantics.
Fraction::from_integer(1 / *nums[0].numer())
} else {
// `recip` swaps numer/denom — infallible for a non-zero ratio.
nums[0].recip()
});
if index {
let mut acc = *nums[0].numer();
for n in &nums[1..] {
if *n.numer() == 0 {
// `i64::MIN / -1` overflows — `checked_div` catches it.
acc = acc.checked_div(*n.numer()).ok_or_else(overflow)?;
return Ok(Fraction::from_integer(acc));
let mut acc = nums[0];
// Rational division cross-multiplies — can overflow i64.
acc = acc.checked_div(n).ok_or_else(overflow)?;
Ok(acc)
/// Const-fold `MOD`: floored modulo, the result taking the divisor's sign;
/// index operands stay in integers, as `index_rem` does.
#[spec(requires: nums.len() == 2)]
pub(in crate::compiler) fn fold_mod(nums: &[Fraction], index: bool) -> Result<Fraction> {
if *nums[1].numer() == 0 {
return Err(Error::Compile("division by zero in MOD".to_string()));
// Raw `%` panics on `i64::MIN % -1` (overflow). wasm `i32.rem_s` defines
// that case as 0 (it does NOT trap, unlike `i32.div_s`), so `checked_rem`
// returning `None` there folds to 0 — keeping the eval surface in lockstep
// with `i32.rem_s` codegen rather than panicking the compiler.
let (a, b) = (*nums[0].numer(), *nums[1].numer());
let r = a.checked_rem(b).unwrap_or(0);
let stepped = if r != 0 && (r < 0) != (b < 0) {
r + b
r
return Ok(Fraction::from_integer(stepped));
// Floored modulo `a - b*floor(a/b)` cross-multiplies twice — guard both.
let quotient = nums[0].checked_div(&nums[1]).ok_or_else(overflow)?.floor();
let scaled = nums[1].checked_mul("ient).ok_or_else(overflow)?;
nums[0].checked_sub(&scaled).ok_or_else(overflow)
fn resolve_all(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Vec<Expr>> {
args.iter().map(|arg| eval_value(symbols, arg)).collect()
pub(super) fn add(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
let resolved = resolve_all(symbols, args)?;
if let Some(operands) = Operands::of(&resolved, ArithOp::Add)? {
return Ok(operands.folded(fold_add(&operands.values)?));
additive_type(symbols, args, &resolved, ArithOp::Add)
pub(super) fn sub(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
if args.is_empty() {
return Err(Error::Compile("- requires at least 1 argument".to_string()));
if let Some(operands) = Operands::of(&resolved, ArithOp::Sub)? {
return Ok(operands.folded(fold_sub(&operands.values)?));
additive_type(symbols, args, &resolved, ArithOp::Sub)
pub(super) fn mul(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
if let Some(operands) = Operands::of(&resolved, ArithOp::Mul)? {
return Ok(operands.folded(fold_mul(&operands.values)?));
scaled_type(symbols, args, &resolved, ArithOp::Mul)
pub(super) fn div(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
return Err(Error::Compile("/ requires at least 1 argument".to_string()));
if let Some(operands) = Operands::of(&resolved, ArithOp::Div)? {
return Ok(operands.folded(fold_div(&operands.values, operands.is_index())?));
scaled_type(symbols, args, &resolved, ArithOp::Div)
pub(super) fn modulo(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
if args.len() != 2 {
return Err(Error::Arity {
name: "MOD".to_string(),
expected: 2,
actual: args.len(),
if let Some(operands) = Operands::of(&resolved, ArithOp::Mod)? {
return Ok(operands.folded(fold_mod(&operands.values, operands.is_index())?));
additive_type(symbols, args, &resolved, ArithOp::Mod)