1
//! `to_stack` codegen for `+ - * / MOD`. An all-literal call const-folds; a
2
//! runtime call compiles each non-literal operand to a local (which yields
3
//! its real wasm type — including closure-call results the eval path cannot
4
//! reduce) and hands the operands to the shared emitter in [`super::emit`],
5
//! which applies the ADR-0028 dimension rules.
6

            
7
use super::ArithOp;
8
use crate::ast::{Expr, WasmType};
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::{
12
    compile_for_effect, compile_raising, compile_to_local, eval_value, is_division_by_zero,
13
    push_number,
14
};
15
use crate::error::Result;
16
use crate::runtime::SymbolTable;
17

            
18
use super::emit::{Slot, check_arity, emit_slots};
19
use super::eval::{Operands, fold_add, fold_div, fold_mod, fold_mul, fold_sub, try_fold};
20

            
21
/// Compile each operand once: a constant (syntactic, or one that resolves to
22
/// a `Number`) stays unemitted with the dimension its kind fixes; everything
23
/// else is emitted to a fresh local, capturing its real wasm type and its side
24
/// effects in operand order. The constant probe runs on a clone so it applies
25
/// no live mutation.
26
609069
fn collect_slots(
27
609069
    ctx: &mut CompileContext,
28
609069
    emit: &mut FunctionEmitter,
29
609069
    symbols: &mut SymbolTable,
30
609069
    args: &[Expr],
31
609069
) -> Result<Vec<Slot>> {
32
609069
    let mut slots = Vec::with_capacity(args.len());
33
609069
    for arg in args {
34
1220375
        match eval_value(&mut symbols.clone(), arg) {
35
            Ok(Expr::Number(n)) => {
36
                // A non-literal that *resolves* to a number (e.g. `(setf x 1)`)
37
                // still emits its effects on the live table, in operand order,
38
                // before the constant is recorded.
39
638446
                if !matches!(arg, Expr::Number(_)) {
40
85475
                    compile_for_effect(ctx, emit, symbols, arg)?;
41
552971
                }
42
638446
                slots.push(Slot::Literal(n));
43
            }
44
581929
            _ if compile_raising(ctx, emit, symbols, arg)? => slots.push(Slot::Raises),
45
575011
            _ => slots.push(match compile_to_local(ctx, emit, symbols, arg)? {
46
573900
                Some((local, ty)) => Slot::Runtime(local, ty),
47
97
                None => Slot::Raises,
48
            }),
49
        }
50
    }
51
607844
    Ok(slots)
52
609069
}
53

            
54
591853
pub(super) fn compile_add_to_stack(
55
591853
    ctx: &mut CompileContext,
56
591853
    emit: &mut FunctionEmitter,
57
591853
    symbols: &mut SymbolTable,
58
591853
    args: &[Expr],
59
591853
) -> Result<WasmType> {
60
591853
    compile_arith_to_stack(ctx, emit, symbols, args, ArithOp::Add)
61
591853
}
62

            
63
23823
pub(super) fn compile_sub_to_stack(
64
23823
    ctx: &mut CompileContext,
65
23823
    emit: &mut FunctionEmitter,
66
23823
    symbols: &mut SymbolTable,
67
23823
    args: &[Expr],
68
23823
) -> Result<WasmType> {
69
23823
    compile_arith_to_stack(ctx, emit, symbols, args, ArithOp::Sub)
70
23823
}
71

            
72
65353
pub(super) fn compile_mul_to_stack(
73
65353
    ctx: &mut CompileContext,
74
65353
    emit: &mut FunctionEmitter,
75
65353
    symbols: &mut SymbolTable,
76
65353
    args: &[Expr],
77
65353
) -> Result<WasmType> {
78
65353
    compile_arith_to_stack(ctx, emit, symbols, args, ArithOp::Mul)
79
65353
}
80

            
81
26416
pub(super) fn compile_div_to_stack(
82
26416
    ctx: &mut CompileContext,
83
26416
    emit: &mut FunctionEmitter,
84
26416
    symbols: &mut SymbolTable,
85
26416
    args: &[Expr],
86
26416
) -> Result<WasmType> {
87
26416
    compile_arith_to_stack(ctx, emit, symbols, args, ArithOp::Div)
88
26416
}
89

            
90
5059
pub(super) fn compile_mod_to_stack(
91
5059
    ctx: &mut CompileContext,
92
5059
    emit: &mut FunctionEmitter,
93
5059
    symbols: &mut SymbolTable,
94
5059
    args: &[Expr],
95
5059
) -> Result<WasmType> {
96
5059
    compile_arith_to_stack(ctx, emit, symbols, args, ArithOp::Mod)
97
5059
}
98

            
99
712504
fn compile_arith_to_stack(
100
712504
    ctx: &mut CompileContext,
101
712504
    emit: &mut FunctionEmitter,
102
712504
    symbols: &mut SymbolTable,
103
712504
    args: &[Expr],
104
712504
    op: ArithOp,
105
712504
) -> Result<WasmType> {
106
712504
    check_arity(op, args.len())?;
107
711664
    if let Some(operands) = try_fold(symbols, args, op)? {
108
99154
        let nums = &operands.values;
109
99154
        let folded = match op {
110
55512
            ArithOp::Add => fold_add(nums),
111
3981
            ArithOp::Sub => fold_sub(nums),
112
14992
            ArithOp::Mul => fold_mul(nums),
113
22567
            ArithOp::Div => fold_div(nums, operands.is_index()),
114
2102
            ArithOp::Mod => fold_mod(nums, operands.is_index()),
115
        };
116
99154
        return match folded {
117
80167
            Ok(value) => push_number(ctx, emit, operands.kinded(value)),
118
18987
            Err(err) if is_division_by_zero(&err) => {
119
17947
                emit_constant_operation(ctx, emit, op, &operands)
120
            }
121
1040
            Err(other) => Err(other),
122
        };
123
609069
    }
124
609069
    let slots = collect_slots(ctx, emit, symbols, args)?;
125
607844
    emit_slots(ctx, emit, op, &slots)
126
712504
}
127

            
128
/// An all-constant division by zero is emitted at runtime, so the condition is
129
/// the catchable `DIVISION-BY-ZERO` trap, not a compile error (ISS-065).
130
17947
fn emit_constant_operation(
131
17947
    ctx: &mut CompileContext,
132
17947
    emit: &mut FunctionEmitter,
133
17947
    op: ArithOp,
134
17947
    operands: &Operands,
135
17947
) -> Result<WasmType> {
136
17947
    let slots: Vec<Slot> = operands.nums.iter().copied().map(Slot::Literal).collect();
137
17947
    emit_slots(ctx, emit, op, &slots)
138
17947
}