1
//! Eval handlers + the effect-path compile wrappers. Eval handlers
2
//! constant-fold over `Expr::Number` args; the compile wrappers
3
//! detect the const-fold path inline and only re-enter `to_stack`
4
//! when at least one arg is a runtime value.
5

            
6
use crate::ast::{Expr, Fraction, WasmType};
7
use crate::compiler::context::CompileContext;
8
use crate::compiler::emit::FunctionEmitter;
9
use crate::compiler::expr::{eval_value, serialize_stack_to_output};
10
use crate::error::{Error, Result};
11
use crate::runtime::SymbolTable;
12

            
13
use super::super::shared::{
14
    bool_result, compile_args_for_effect, emit_bool, extract_numbers, has_runtime, resolve_all,
15
    same_datum, validate_valued_args,
16
};
17
use super::to_stack::{
18
    compile_cmp_to_stack_by_name, compile_eql_to_stack, compile_equal_to_stack,
19
    compile_neq_to_stack,
20
};
21

            
22
9698733
pub(in crate::compiler::native::comparison) fn eval_eq(
23
9698733
    s: &mut SymbolTable,
24
9698733
    args: &[Expr],
25
9698733
) -> Result<Expr> {
26
9698733
    num_cmp(s, args, "=", |a, b| a == b)
27
9698733
}
28
55415
pub(in crate::compiler::native::comparison) fn eval_lt(
29
55415
    s: &mut SymbolTable,
30
55415
    args: &[Expr],
31
55415
) -> Result<Expr> {
32
55415
    num_cmp(s, args, "<", |a, b| a < b)
33
55415
}
34
3687026
pub(in crate::compiler::native::comparison) fn eval_gt(
35
3687026
    s: &mut SymbolTable,
36
3687026
    args: &[Expr],
37
3687026
) -> Result<Expr> {
38
3687026
    num_cmp(s, args, ">", |a, b| a > b)
39
3687026
}
40
38074
pub(in crate::compiler::native::comparison) fn eval_le(
41
38074
    s: &mut SymbolTable,
42
38074
    args: &[Expr],
43
38074
) -> Result<Expr> {
44
38074
    num_cmp(s, args, "<=", |a, b| a <= b)
45
38074
}
46
1359517
pub(in crate::compiler::native::comparison) fn eval_ge(
47
1359517
    s: &mut SymbolTable,
48
1359517
    args: &[Expr],
49
1359517
) -> Result<Expr> {
50
1359517
    num_cmp(s, args, ">=", |a, b| a >= b)
51
1359517
}
52

            
53
7305
pub(in crate::compiler::native::comparison) fn compile_eq(
54
7305
    ctx: &mut CompileContext,
55
7305
    emit: &mut FunctionEmitter,
56
7305
    s: &mut SymbolTable,
57
7305
    args: &[Expr],
58
7305
) -> Result<()> {
59
7305
    compile_num_cmp(ctx, emit, s, args, "=", |a, b| a == b)
60
7305
}
61
1930
pub(in crate::compiler::native::comparison) fn compile_lt(
62
1930
    ctx: &mut CompileContext,
63
1930
    emit: &mut FunctionEmitter,
64
1930
    s: &mut SymbolTable,
65
1930
    args: &[Expr],
66
1930
) -> Result<()> {
67
1930
    compile_num_cmp(ctx, emit, s, args, "<", |a, b| a < b)
68
1930
}
69
1046
pub(in crate::compiler::native::comparison) fn compile_gt(
70
1046
    ctx: &mut CompileContext,
71
1046
    emit: &mut FunctionEmitter,
72
1046
    s: &mut SymbolTable,
73
1046
    args: &[Expr],
74
1046
) -> Result<()> {
75
1460
    compile_num_cmp(ctx, emit, s, args, ">", |a, b| a > b)
76
1046
}
77
840
pub(in crate::compiler::native::comparison) fn compile_le(
78
840
    ctx: &mut CompileContext,
79
840
    emit: &mut FunctionEmitter,
80
840
    s: &mut SymbolTable,
81
840
    args: &[Expr],
82
840
) -> Result<()> {
83
1047
    compile_num_cmp(ctx, emit, s, args, "<=", |a, b| a <= b)
84
840
}
85
838
pub(in crate::compiler::native::comparison) fn compile_ge(
86
838
    ctx: &mut CompileContext,
87
838
    emit: &mut FunctionEmitter,
88
838
    s: &mut SymbolTable,
89
838
    args: &[Expr],
90
838
) -> Result<()> {
91
838
    compile_num_cmp(ctx, emit, s, args, ">=", |a, b| a >= b)
92
838
}
93

            
94
/// Evaluates every one of `args` EXACTLY ONCE, in source order, directly on
95
/// the caller's LIVE table. Eval-only comparisons (unlike the codegen
96
/// paths, which separately probe-on-a-clone then emit-for-real) have no
97
/// second "emission" step at all — this single pass over the live table IS
98
/// the one place their operands' compile-time effects apply, whether the
99
/// result folds to a constant or turns out to need a runtime placeholder.
100
/// A disposable clone here would leave a runtime-detected operand's effects
101
/// (a nested `setf`/`defvar`) unapplied, and — for a caller like `eq?`
102
/// classifying ITS OWN two operands in sequence — would let a later operand
103
/// probe against stale state that later real emission has already moved
104
/// past (predicting the wrong static type for it).
105
14838970
fn eval_all_for_effect(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Vec<Expr>> {
106
29677994
    args.iter().map(|arg| eval_value(symbols, arg)).collect()
107
14838970
}
108

            
109
14838765
fn num_cmp(
110
14838765
    symbols: &mut SymbolTable,
111
14838765
    args: &[Expr],
112
14838765
    name: &str,
113
14838765
    cmp: fn(&Fraction, &Fraction) -> bool,
114
14838765
) -> Result<Expr> {
115
14838765
    if args.is_empty() {
116
420
        return Err(Error::Compile(format!(
117
420
            "{name} requires at least 1 argument"
118
420
        )));
119
14838345
    }
120
14838345
    let resolved = eval_all_for_effect(symbols, args)?;
121
14832562
    if let Some(nums) = extract_numbers(&resolved, name)? {
122
11720202
        let result = nums.windows(2).all(|w| cmp(&w[0], &w[1]));
123
11720201
        return Ok(bool_result(result));
124
3112343
    }
125
3112343
    if has_runtime(&resolved) {
126
3112341
        validate_valued_args(symbols, args, &resolved, name)?;
127
3109347
        return Ok(Expr::WasmRuntime(WasmType::Bool));
128
2
    }
129
2
    Err(Error::Compile(format!("{name} expects numeric arguments")))
130
14838765
}
131

            
132
625
pub(in crate::compiler::native::comparison) fn num_neq(
133
625
    symbols: &mut SymbolTable,
134
625
    args: &[Expr],
135
625
) -> Result<Expr> {
136
625
    if args.is_empty() {
137
        return Err(Error::Compile(
138
            "/= requires at least 1 argument".to_string(),
139
        ));
140
625
    }
141
625
    let resolved = eval_all_for_effect(symbols, args)?;
142
625
    if let Some(nums) = extract_numbers(&resolved, "/=")? {
143
2
        let result = (0..nums.len()).all(|i| (i + 1..nums.len()).all(|j| nums[i] != nums[j]));
144
1
        return Ok(bool_result(result));
145
624
    }
146
624
    if has_runtime(&resolved) {
147
624
        validate_valued_args(symbols, args, &resolved, "/=")?;
148
624
        return Ok(Expr::WasmRuntime(WasmType::Bool));
149
    }
150
    Err(Error::Compile("/= expects numeric arguments".to_string()))
151
625
}
152

            
153
15838
pub(in crate::compiler::native::comparison) fn eql(
154
15838
    symbols: &mut SymbolTable,
155
15838
    args: &[Expr],
156
15838
) -> Result<Expr> {
157
15838
    eval_identity(symbols, args, "EQL")
158
15838
}
159

            
160
2118
pub(in crate::compiler::native::comparison) fn equal(
161
2118
    symbols: &mut SymbolTable,
162
2118
    args: &[Expr],
163
2118
) -> Result<Expr> {
164
2118
    eval_identity(symbols, args, "EQUAL")
165
2118
}
166

            
167
17956
fn eval_identity(symbols: &mut SymbolTable, args: &[Expr], name: &str) -> Result<Expr> {
168
17956
    let [first, second] = args else {
169
        return Err(Error::Arity {
170
            name: name.to_string(),
171
            expected: 2,
172
            actual: args.len(),
173
        });
174
    };
175
17956
    let a = eval_value(symbols, first)?;
176
17956
    let b = eval_value(symbols, second)?;
177
17956
    let same = same_datum(&a, &b, name)?;
178
17939
    if a.is_wasm_runtime() || b.is_wasm_runtime() {
179
15966
        return Ok(Expr::WasmRuntime(WasmType::Bool));
180
1973
    }
181
1973
    Ok(bool_result(same))
182
17956
}
183

            
184
11959
fn compile_num_cmp(
185
11959
    ctx: &mut CompileContext,
186
11959
    emit: &mut FunctionEmitter,
187
11959
    symbols: &mut SymbolTable,
188
11959
    args: &[Expr],
189
11959
    name: &str,
190
11959
    cmp: fn(&Fraction, &Fraction) -> bool,
191
11959
) -> Result<()> {
192
11959
    if args.is_empty() {
193
2
        return Err(Error::Compile(format!(
194
2
            "{name} requires at least 1 argument"
195
2
        )));
196
11957
    }
197
11957
    let resolved = resolve_all(symbols, args)?;
198
11949
    if let Some(nums) = extract_numbers(&resolved, name)? {
199
6492
        let result = nums.windows(2).all(|w| cmp(&w[0], &w[1]));
200
3574
        compile_args_for_effect(ctx, emit, symbols, args)?;
201
3574
        emit_bool(ctx, emit, result)?;
202
3574
        return Ok(());
203
8371
    }
204
8371
    let ty = compile_cmp_to_stack_by_name(ctx, emit, symbols, args, name, cmp)?;
205
7105
    serialize_stack_to_output(ctx, emit, ty)?;
206
7105
    Ok(())
207
11959
}
208

            
209
1048
pub(in crate::compiler::native::comparison) fn compile_num_neq(
210
1048
    ctx: &mut CompileContext,
211
1048
    emit: &mut FunctionEmitter,
212
1048
    symbols: &mut SymbolTable,
213
1048
    args: &[Expr],
214
1048
) -> Result<()> {
215
1048
    if args.is_empty() {
216
        return Err(Error::Compile(
217
            "/= requires at least 1 argument".to_string(),
218
        ));
219
1048
    }
220
1048
    let resolved = resolve_all(symbols, args)?;
221
1047
    if let Some(nums) = extract_numbers(&resolved, "/=")? {
222
1464
        let result = (0..nums.len()).all(|i| (i + 1..nums.len()).all(|j| nums[i] != nums[j]));
223
836
        compile_args_for_effect(ctx, emit, symbols, args)?;
224
836
        emit_bool(ctx, emit, result)?;
225
836
        return Ok(());
226
211
    }
227
211
    let ty = compile_neq_to_stack(ctx, emit, symbols, args)?;
228
211
    serialize_stack_to_output(ctx, emit, ty)?;
229
211
    Ok(())
230
1048
}
231

            
232
7022
pub(in crate::compiler::native::comparison) fn compile_eql(
233
7022
    ctx: &mut CompileContext,
234
7022
    emit: &mut FunctionEmitter,
235
7022
    symbols: &mut SymbolTable,
236
7022
    args: &[Expr],
237
7022
) -> Result<()> {
238
7022
    let ty = compile_eql_to_stack(ctx, emit, symbols, args)?;
239
6584
    serialize_stack_to_output(ctx, emit, ty)
240
7022
}
241

            
242
2600
pub(in crate::compiler::native::comparison) fn compile_equal(
243
2600
    ctx: &mut CompileContext,
244
2600
    emit: &mut FunctionEmitter,
245
2600
    symbols: &mut SymbolTable,
246
2600
    args: &[Expr],
247
2600
) -> Result<()> {
248
2600
    let ty = compile_equal_to_stack(ctx, emit, symbols, args)?;
249
2382
    serialize_stack_to_output(ctx, emit, ty)
250
2600
}