1
//! Shared helpers for the comparison family — the `NATIVES` registry
2
//! const, eval/compile dispatchers, the bool-emit helpers, and the
3
//! type-classification and stack-coercion helpers consumed by both
4
//! `ordering` and `predicates`.
5

            
6
use crate::ast::{Expr, Fraction, Number, WasmType};
7
use crate::compiler::context::CompileContext;
8
use crate::compiler::emit::FunctionEmitter;
9
use crate::compiler::expr::{
10
    compile_for_effect, compile_for_stack, compile_nil, compile_t, format_expr, index_literal,
11
    probe_value,
12
};
13
use crate::error::{Error, Result};
14
use crate::runtime::SymbolTable;
15

            
16
use super::super::NativeSpec;
17
use super::super::arithmetic::{
18
    Dim, decided_over_dims, non_numeric_operand, refuse_dim_mix, shared_dim,
19
};
20

            
21
use super::ordering::{
22
    compile_eq, compile_eq_to_stack, compile_eql, compile_eql_to_stack, compile_equal,
23
    compile_equal_to_stack, compile_ge, compile_ge_to_stack, compile_gt, compile_gt_to_stack,
24
    compile_le, compile_le_to_stack, compile_lt, compile_lt_to_stack, compile_neq_to_stack,
25
    compile_num_neq, eql, equal, eval_eq, eval_ge, eval_gt, eval_le, eval_lt, num_neq,
26
};
27
use super::predicates::{
28
    compile_not, compile_not_to_stack, compile_null_p, compile_null_p_to_stack, not_fn, null_p,
29
};
30

            
31
pub(in crate::compiler::native) const NATIVES: &[NativeSpec] = &[
32
    NativeSpec {
33
        name: "=",
34
        eval: eval_eq,
35
        stack: Some(compile_eq_to_stack),
36
        effect: Some(compile_eq),
37
    },
38
    NativeSpec {
39
        name: "/=",
40
        eval: num_neq,
41
        stack: Some(compile_neq_to_stack),
42
        effect: Some(compile_num_neq),
43
    },
44
    NativeSpec {
45
        name: "<",
46
        eval: eval_lt,
47
        stack: Some(compile_lt_to_stack),
48
        effect: Some(compile_lt),
49
    },
50
    NativeSpec {
51
        name: ">",
52
        eval: eval_gt,
53
        stack: Some(compile_gt_to_stack),
54
        effect: Some(compile_gt),
55
    },
56
    NativeSpec {
57
        name: "<=",
58
        eval: eval_le,
59
        stack: Some(compile_le_to_stack),
60
        effect: Some(compile_le),
61
    },
62
    NativeSpec {
63
        name: ">=",
64
        eval: eval_ge,
65
        stack: Some(compile_ge_to_stack),
66
        effect: Some(compile_ge),
67
    },
68
    NativeSpec {
69
        name: "EQL",
70
        eval: eql,
71
        stack: Some(compile_eql_to_stack),
72
        effect: Some(compile_eql),
73
    },
74
    NativeSpec {
75
        name: "EQUAL",
76
        eval: equal,
77
        stack: Some(compile_equal_to_stack),
78
        effect: Some(compile_equal),
79
    },
80
    // Scheme-spelled aliases of the CL equality predicates — same
81
    // structural comparison, registered so the documented `EQ?` / `EQUAL?`
82
    // natives are not dead names the compiler rejects at codegen.
83
    NativeSpec {
84
        name: "EQ?",
85
        eval: eql,
86
        stack: Some(compile_eql_to_stack),
87
        effect: Some(compile_eql),
88
    },
89
    NativeSpec {
90
        name: "EQ",
91
        eval: eql,
92
        stack: Some(compile_eql_to_stack),
93
        effect: Some(compile_eql),
94
    },
95
    NativeSpec {
96
        name: "EQUAL?",
97
        eval: equal,
98
        stack: Some(compile_equal_to_stack),
99
        effect: Some(compile_equal),
100
    },
101
    NativeSpec {
102
        name: "NOT",
103
        eval: not_fn,
104
        stack: Some(compile_not_to_stack),
105
        effect: Some(compile_not),
106
    },
107
    NativeSpec {
108
        name: "NULL?",
109
        eval: null_p,
110
        stack: Some(compile_null_p_to_stack),
111
        effect: Some(compile_null_p),
112
    },
113
];
114

            
115
11731443
pub(in crate::compiler::native) fn bool_result(value: bool) -> Expr {
116
11731443
    if value { Expr::T } else { Expr::Nil }
117
11731443
}
118

            
119
6296
pub(super) fn emit_bool(
120
6296
    ctx: &mut CompileContext,
121
6296
    emit: &mut FunctionEmitter,
122
6296
    value: bool,
123
6296
) -> Result<()> {
124
6296
    if value {
125
3998
        compile_t(ctx, emit)
126
    } else {
127
2298
        compile_nil(ctx, emit)
128
    }
129
6296
}
130

            
131
3112967
pub(super) fn has_runtime(resolved: &[Expr]) -> bool {
132
3112967
    resolved.iter().any(crate::ast::Expr::is_wasm_runtime)
133
3112967
}
134

            
135
/// Classifies every arg on ONE disposable clone (so a later arg's probe
136
/// sees an earlier arg's compile-time effects, but NONE of them reach the
137
/// live table here) — purely for the all-constant fold / arg-type checks
138
/// in CODEGEN paths, which separately emit the real operands afterward
139
/// (via [`compile_args_for_effect`] for the constant fold, or the runtime
140
/// `compile_for_stack`/`compile_for_stack_as_*` calls the caller makes
141
/// itself). The pure eval-mirror comparisons (`num_cmp`/`num_neq`/`eql`/
142
/// `equal` in `dispatch.rs`) have no separate emission step at all, so they
143
/// evaluate their operands directly on the live table instead — see their
144
/// own `eval_all_for_effect`.
145
2673826
pub(super) fn resolve_all(symbols: &SymbolTable, args: &[Expr]) -> Result<Vec<Expr>> {
146
2673826
    let mut probe = symbols.clone();
147
2673826
    args.iter()
148
5353486
        .map(|arg| probe_value(&mut probe, arg))
149
        .collect()
150
2673826
}
151

            
152
/// Compiles every one of `args` for effect, in source order, on the LIVE
153
/// table — the single real application of a comparison's operands when
154
/// they all fold to a compile-time constant (see [`resolve_all`]).
155
87359
pub(super) fn compile_args_for_effect(
156
87359
    ctx: &mut CompileContext,
157
87359
    emit: &mut FunctionEmitter,
158
87359
    symbols: &mut SymbolTable,
159
87359
    args: &[Expr],
160
87359
) -> Result<()> {
161
87359
    for arg in args {
162
178476
        compile_for_effect(ctx, emit, symbols, arg)?;
163
    }
164
87359
    Ok(())
165
87359
}
166

            
167
/// The operands' values when every one is a constant of one kind; a kind mix
168
/// is an error.
169
17506995
pub(super) fn extract_numbers(resolved: &[Expr], name: &str) -> Result<Option<Vec<Fraction>>> {
170
17506995
    let Some(nums) = resolved
171
17506995
        .iter()
172
29376531
        .map(|e| match e {
173
23677124
            Expr::Number(n) => Some(*n),
174
5699407
            _ => None,
175
29376531
        })
176
        .collect::<Option<Vec<_>>>()
177
    else {
178
5699407
        return Ok(None);
179
    };
180
11807588
    for n in &nums {
181
23618929
        if let Number::Index(i) = n {
182
23617180
            index_literal(*i)?;
183
1749
        }
184
    }
185
23618923
    shared_dim(nums.iter().map(|n| Dim::of_number(*n)), name)?;
186
23618881
    Ok(Some(nums.iter().map(|n| n.value()).collect()))
187
17506995
}
188

            
189
11394585
fn operand_dim(operand: &Expr, name: &str) -> Result<Dim> {
190
11394585
    Dim::of_value(operand).ok_or_else(|| {
191
2971
        match operand.wasm_type().filter(|_| operand.is_wasm_runtime()) {
192
1087
            Some(ty) => non_numeric_operand(name, ty),
193
1884
            None => Error::Compile(format!(
194
1884
                "{name} expects numeric arguments, got {}",
195
1884
                format_expr(operand)
196
1884
            )),
197
        }
198
2971
    })
199
11394585
}
200

            
201
/// The wasm type every operand of a comparison shares; operands of different
202
/// dimensions are a mix, crossed only by an explicit `index->scalar` /
203
/// `scalar->index` / `convert-commodity`.
204
2581285
pub(in crate::compiler) fn validate_cmp_args(resolved: &[Expr], name: &str) -> Result<WasmType> {
205
2581285
    let dims = resolved
206
2581285
        .iter()
207
5158741
        .map(|r| operand_dim(r, name))
208
2095
        .collect::<Result<Vec<_>>>()?;
209
2579190
    let dim = shared_dim(dims, name)?;
210
2576997
    Ok(dim.map_or(WasmType::Ratio, Dim::wasm_type))
211
2581285
}
212

            
213
/// [`validate_cmp_args`], retried over the operands that yield a value when it
214
/// refuses: one that always raises has no dimension. The walk that finds them
215
/// runs only on that path.
216
3112965
pub(super) fn validate_valued_args(
217
3112965
    symbols: &SymbolTable,
218
3112965
    args: &[Expr],
219
3112965
    resolved: &[Expr],
220
3112965
    name: &str,
221
3112965
) -> Result<WasmType> {
222
3112965
    let dim = decided_over_dims(
223
3112965
        symbols,
224
3112965
        (args, resolved),
225
6235844
        |operand| operand_dim(operand, name),
226
3115083
        |dims| shared_dim(dims.iter().flatten().copied(), name),
227
2994
    )?;
228
3109971
    Ok(dim.map_or(WasmType::Ratio, Dim::wasm_type))
229
3112965
}
230

            
231
/// Whether two resolved operands are the same datum. Operands of different
232
/// static numeric kinds are a mix, as in an ordering comparison; `EQUAL` and
233
/// `ASSERT-EQUAL` look at every paired position of a list, `EQ` and `EQL` only
234
/// at the top level. A runtime operand of statically unknown type is compared
235
/// at run time.
236
42794
pub(in crate::compiler) fn same_datum(a: &Expr, b: &Expr, name: &str) -> Result<bool> {
237
42794
    match name {
238
20164
        "EQUAL" | "ASSERT-EQUAL" => refuse_kind_mix(a, b, name)?,
239
22630
        _ => refuse_dim_mix(a, b, name)?,
240
    }
241
42721
    Ok(a == b)
242
42794
}
243

            
244
25652
fn refuse_kind_mix(a: &Expr, b: &Expr, name: &str) -> Result<()> {
245
25652
    match (a, b) {
246
        (Expr::Datum(inner), other) | (other, Expr::Datum(inner)) => {
247
3672
            refuse_kind_mix(inner, other, name)
248
        }
249
924
        (Expr::List(left), Expr::List(right)) => left
250
924
            .iter()
251
924
            .zip(right)
252
1816
            .try_for_each(|(l, r)| refuse_kind_mix(l, r, name)),
253
        (Expr::Cons(car_a, cdr_a), Expr::Cons(car_b, cdr_b)) => {
254
            refuse_kind_mix(car_a, car_b, name)?;
255
            refuse_kind_mix(cdr_a, cdr_b, name)
256
        }
257
21056
        _ => refuse_dim_mix(a, b, name),
258
    }
259
25652
}
260

            
261
/// Push a value onto the WASM stack asserting it is a Commodity.
262
/// Refuses every other type — commodity comparisons must be homogeneous.
263
416
pub(super) fn compile_for_stack_as_commodity(
264
416
    ctx: &mut CompileContext,
265
416
    emit: &mut FunctionEmitter,
266
416
    symbols: &mut SymbolTable,
267
416
    expr: &Expr,
268
416
) -> Result<()> {
269
416
    let ty = compile_for_stack(ctx, emit, symbols, expr)?;
270
416
    match ty {
271
416
        WasmType::Commodity => Ok(()),
272
        _ => Err(Error::Compile(format!(
273
            "commodity comparison requires commodity-bearing operand, got {ty}"
274
        ))),
275
    }
276
416
}
277

            
278
#[cfg(test)]
279
#[path = "shared_tests.rs"]
280
mod tests;