1
//! Constant-folding eval handlers for `+ - * / MOD` over the ADR-0028
2
//! lattice. An all-literal call folds to an `Expr::Number` (all-Index
3
//! operands fold with Index semantics — `/` truncates, `MOD` is floored —
4
//! so the eval surface agrees with the `i32.div_s` codegen and the floored `index_rem`);
5
//! otherwise the handler returns `Expr::WasmRuntime(result_dim)`, refusing the
6
//! dimension mixes codegen refuses.
7

            
8
use anodized::spec;
9
use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub};
10

            
11
use crate::ast::{Expr, Fraction, Number};
12
use crate::compiler::expr::{DIVISION_BY_ZERO, eval_value, fold_value, format_expr};
13
use crate::error::{Error, Result};
14
use crate::runtime::SymbolTable;
15

            
16
use super::ArithOp;
17
use super::emit::{Dim, decided_over_dims, op_name, scaling_dim, shared_dim};
18

            
19
/// The operands as numbers when every one is a fold-safe constant, so the
20
/// call folds without emitting them; `None` sends the call to codegen, which
21
/// compiles each operand's effects itself.
22
711664
#[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())]
23
711664
pub(super) fn try_fold(
24
711664
    symbols: &mut SymbolTable,
25
711664
    args: &[Expr],
26
711664
    op: ArithOp,
27
711664
) -> Result<Option<Operands>> {
28
711664
    let mut folded = Vec::with_capacity(args.len());
29
711664
    for arg in args {
30
912018
        match fold_value(symbols, arg)? {
31
304205
            Some(value) => folded.push(value),
32
607813
            None => return Ok(None),
33
        }
34
    }
35
103851
    Operands::of(&folded, op)
36
711664
}
37

            
38
/// The constant operands of a fold: each keeping its kind, and its value.
39
pub(super) struct Operands {
40
    pub(super) nums: Vec<Number>,
41
    pub(super) values: Vec<Fraction>,
42
}
43

            
44
impl Operands {
45
    /// The operands when every one is a number; a kind mix is an error.
46
18136412
    pub(super) fn of(values: &[Expr], op: ArithOp) -> Result<Option<Self>> {
47
18136412
        let Some(nums) = values
48
18136412
            .iter()
49
35508182
            .map(|value| match value {
50
34665136
                Expr::Number(n) => Some(*n),
51
843046
                _ => None,
52
35508182
            })
53
            .collect::<Option<Vec<_>>>()
54
        else {
55
843046
            return Ok(None);
56
        };
57
34589184
        shared_dim(nums.iter().map(|n| Dim::of_number(*n)), op_name(op))?;
58
34576596
        let values = nums.iter().map(|n| n.value()).collect();
59
17287072
        Ok(Some(Self { nums, values }))
60
18136412
    }
61

            
62
    /// Whether every operand is an index, so `/` truncates.
63
17300414
    pub(super) fn is_index(&self) -> bool {
64
34580820
        self.nums.iter().all(|n| matches!(n, Number::Index(_)))
65
17300414
    }
66

            
67
    /// The folded `value` as an eval value, in the fold's dimension.
68
17142510
    pub(super) fn folded(&self, value: Fraction) -> Expr {
69
17142510
        Expr::Number(self.kinded(value))
70
17142510
    }
71

            
72
    /// `value` as a literal of the fold's kind.
73
17222677
    pub(super) fn kinded(&self, value: Fraction) -> Number {
74
17222677
        match self.is_index() {
75
17205290
            true => Number::Index(*value.numer()),
76
17387
            false => Number::Scalar(value),
77
        }
78
17222677
    }
79
}
80

            
81
1772316
fn operand_dim(value: &Expr) -> Result<Dim> {
82
1772316
    Dim::of_value(value).ok_or_else(|| {
83
14510
        Error::Compile(format!(
84
14510
            "expected number arguments, got {}",
85
14510
            format_expr(value)
86
14510
        ))
87
14510
    })
88
1772316
}
89

            
90
/// The result of `+ - MOD` over operands that are not all constants: the one
91
/// dimension they share, an index when every operand raises.
92
769323
fn additive_type(
93
769323
    symbols: &SymbolTable,
94
769323
    args: &[Expr],
95
769323
    resolved: &[Expr],
96
769323
    op: ArithOp,
97
769323
) -> Result<Expr> {
98
787399
    let dim = decided_over_dims(symbols, (args, resolved), operand_dim, |dims| {
99
787399
        shared_dim(dims.iter().flatten().copied(), op_name(op))
100
787399
    })?;
101
737363
    Ok(Expr::WasmRuntime(dim.unwrap_or(Dim::Index).wasm_type()))
102
769323
}
103

            
104
/// The result of `*` / `/` over operands that are not all constants: the
105
/// dimension codegen's left-associative `combine_scaling` leaves.
106
72467
fn scaled_type(
107
72467
    symbols: &SymbolTable,
108
72467
    args: &[Expr],
109
72467
    resolved: &[Expr],
110
72467
    op: ArithOp,
111
72467
) -> Result<Expr> {
112
86363
    let dim = decided_over_dims(symbols, (args, resolved), operand_dim, |dims| {
113
86363
        scaling_dim(op, dims)
114
86363
    })?;
115
58569
    Ok(Expr::WasmRuntime(dim.wasm_type()))
116
72467
}
117

            
118
/// The `Fraction` (`Ratio<i64>`) operators panic (debug / `overflow-checks`) or
119
/// wrap (release) when a cross-multiply exceeds i64 — reachable from any
120
/// all-literal `(* huge huge)` / `(+ a/b c/d)` whose reduced terms overflow. So
121
/// const-fold through the `Checked*` traits and surface a structured
122
/// `Error::Compile` instead, per CLAUDE.md (never a panic / SIGABRT on input).
123
1043
fn overflow() -> Error {
124
1043
    Error::Compile("arithmetic overflow in constant expression".to_string())
125
1043
}
126

            
127
/// The one fold error that moves to the runtime trap (ISS-065): the guest
128
/// raises a catchable `DIVISION-BY-ZERO`, whereas a constant overflow has no
129
/// runtime condition and stays a compile error.
130
61476
fn division_by_zero() -> Error {
131
61476
    Error::Compile(DIVISION_BY_ZERO.to_string())
132
61476
}
133

            
134
17017937
pub(in crate::compiler) fn fold_add(nums: &[Fraction]) -> Result<Fraction> {
135
34037712
    nums.iter().try_fold(Fraction::from_integer(0), |a, b| {
136
34037712
        a.checked_add(b).ok_or_else(overflow)
137
34037712
    })
138
17017937
}
139

            
140
130985
#[spec(requires: !nums.is_empty())]
141
130985
pub(in crate::compiler) fn fold_sub(nums: &[Fraction]) -> Result<Fraction> {
142
130985
    if nums.len() == 1 {
143
633
        return Fraction::from_integer(0)
144
633
            .checked_sub(&nums[0])
145
633
            .ok_or_else(overflow);
146
130352
    }
147
130352
    nums[1..]
148
130352
        .iter()
149
130976
        .try_fold(nums[0], |a, b| a.checked_sub(b).ok_or_else(overflow))
150
130985
}
151

            
152
60414
pub(in crate::compiler) fn fold_mul(nums: &[Fraction]) -> Result<Fraction> {
153
121663
    nums.iter().try_fold(Fraction::from_integer(1), |a, b| {
154
121663
        a.checked_mul(b).ok_or_else(overflow)
155
121663
    })
156
60414
}
157

            
158
/// Const-fold `/`: all-integer operands divide as Index (truncating toward
159
/// zero, matching `i32.div_s`); any fractional operand divides rationally.
160
74174
#[spec(requires: !nums.is_empty())]
161
74174
pub(in crate::compiler) fn fold_div(nums: &[Fraction], index: bool) -> Result<Fraction> {
162
74174
    if nums.len() == 1 {
163
628
        if *nums[0].numer() == 0 {
164
208
            return Err(division_by_zero());
165
420
        }
166
420
        return Ok(if index {
167
            // `1 / numer` can't overflow, but keep the lattice's truncating
168
            // Index semantics.
169
208
            Fraction::from_integer(1 / *nums[0].numer())
170
        } else {
171
            // `recip` swaps numer/denom — infallible for a non-zero ratio.
172
212
            nums[0].recip()
173
        });
174
73546
    }
175
73546
    if index {
176
69100
        let mut acc = *nums[0].numer();
177
69100
        for n in &nums[1..] {
178
69516
            if *n.numer() == 0 {
179
60583
                return Err(division_by_zero());
180
8933
            }
181
            // `i64::MIN / -1` overflows — `checked_div` catches it.
182
8933
            acc = acc.checked_div(*n.numer()).ok_or_else(overflow)?;
183
        }
184
8517
        return Ok(Fraction::from_integer(acc));
185
4446
    }
186
4446
    let mut acc = nums[0];
187
4446
    for n in &nums[1..] {
188
4446
        if *n.numer() == 0 {
189
685
            return Err(division_by_zero());
190
3761
        }
191
        // Rational division cross-multiplies — can overflow i64.
192
3761
        acc = acc.checked_div(n).ok_or_else(overflow)?;
193
    }
194
3553
    Ok(acc)
195
74174
}
196

            
197
/// Const-fold `MOD`: floored modulo, the result taking the divisor's sign;
198
/// index operands stay in integers, as `index_rem` does.
199
3562
#[spec(requires: nums.len() == 2)]
200
3562
pub(in crate::compiler) fn fold_mod(nums: &[Fraction], index: bool) -> Result<Fraction> {
201
3562
    if *nums[1].numer() == 0 {
202
1875
        return Err(Error::Compile("division by zero in MOD".to_string()));
203
1687
    }
204
1687
    if index {
205
        // Raw `%` panics on `i64::MIN % -1` (overflow). wasm `i32.rem_s` defines
206
        // that case as 0 (it does NOT trap, unlike `i32.div_s`), so `checked_rem`
207
        // returning `None` there folds to 0 — keeping the eval surface in lockstep
208
        // with `i32.rem_s` codegen rather than panicking the compiler.
209
1476
        let (a, b) = (*nums[0].numer(), *nums[1].numer());
210
1476
        let r = a.checked_rem(b).unwrap_or(0);
211
1476
        let stepped = if r != 0 && (r < 0) != (b < 0) {
212
422
            r + b
213
        } else {
214
1054
            r
215
        };
216
1476
        return Ok(Fraction::from_integer(stepped));
217
211
    }
218
    // Floored modulo `a - b*floor(a/b)` cross-multiplies twice — guard both.
219
211
    let quotient = nums[0].checked_div(&nums[1]).ok_or_else(overflow)?.floor();
220
3
    let scaled = nums[1].checked_mul(&quotient).ok_or_else(overflow)?;
221
3
    nums[0].checked_sub(&scaled).ok_or_else(overflow)
222
3562
}
223

            
224
20273679
fn resolve_all(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Vec<Expr>> {
225
40506227
    args.iter().map(|arg| eval_value(symbols, arg)).collect()
226
20273679
}
227

            
228
19855056
pub(super) fn add(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
229
19855056
    let resolved = resolve_all(symbols, args)?;
230
17613950
    if let Some(operands) = Operands::of(&resolved, ArithOp::Add)? {
231
16962425
        return Ok(operands.folded(fold_add(&operands.values)?));
232
648746
    }
233
648746
    additive_type(symbols, args, &resolved, ArithOp::Add)
234
19855056
}
235

            
236
247154
pub(super) fn sub(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
237
247154
    if args.is_empty() {
238
1
        return Err(Error::Compile("- requires at least 1 argument".to_string()));
239
247153
    }
240
247153
    let resolved = resolve_all(symbols, args)?;
241
247135
    if let Some(operands) = Operands::of(&resolved, ArithOp::Sub)? {
242
127004
        return Ok(operands.folded(fold_sub(&operands.values)?));
243
120131
    }
244
120131
    additive_type(symbols, args, &resolved, ArithOp::Sub)
245
247154
}
246

            
247
116782
pub(super) fn mul(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
248
116782
    let resolved = resolve_all(symbols, args)?;
249
116782
    if let Some(operands) = Operands::of(&resolved, ArithOp::Mul)? {
250
45418
        return Ok(operands.folded(fold_mul(&operands.values)?));
251
71291
    }
252
71291
    scaled_type(symbols, args, &resolved, ArithOp::Mul)
253
116782
}
254

            
255
52783
pub(super) fn div(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
256
52783
    if args.is_empty() {
257
1
        return Err(Error::Compile("/ requires at least 1 argument".to_string()));
258
52782
    }
259
52782
    let resolved = resolve_all(symbols, args)?;
260
52782
    if let Some(operands) = Operands::of(&resolved, ArithOp::Div)? {
261
51606
        return Ok(operands.folded(fold_div(&operands.values, operands.is_index())?));
262
1176
    }
263
1176
    scaled_type(symbols, args, &resolved, ArithOp::Div)
264
52783
}
265

            
266
1907
pub(super) fn modulo(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
267
1907
    if args.len() != 2 {
268
1
        return Err(Error::Arity {
269
1
            name: "MOD".to_string(),
270
1
            expected: 2,
271
1
            actual: args.len(),
272
1
        });
273
1906
    }
274
1906
    let resolved = resolve_all(symbols, args)?;
275
1906
    if let Some(operands) = Operands::of(&resolved, ArithOp::Mod)? {
276
1460
        return Ok(operands.folded(fold_mod(&operands.values, operands.is_index())?));
277
446
    }
278
446
    additive_type(symbols, args, &resolved, ArithOp::Mod)
279
1907
}