Lines
95.33 %
Functions
97.73 %
Branches
100 %
//! Shared helpers for the comparison family — the `NATIVES` registry
//! const, eval/compile dispatchers, the bool-emit helpers, and the
//! type-classification and stack-coercion helpers consumed by both
//! `ordering` and `predicates`.
use crate::ast::{Expr, Fraction, Number, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
compile_for_effect, compile_for_stack, compile_nil, compile_t, format_expr, index_literal,
probe_value,
};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::super::NativeSpec;
use super::super::arithmetic::{
Dim, decided_over_dims, non_numeric_operand, refuse_dim_mix, shared_dim,
use super::ordering::{
compile_eq, compile_eq_to_stack, compile_eql, compile_eql_to_stack, compile_equal,
compile_equal_to_stack, compile_ge, compile_ge_to_stack, compile_gt, compile_gt_to_stack,
compile_le, compile_le_to_stack, compile_lt, compile_lt_to_stack, compile_neq_to_stack,
compile_num_neq, eql, equal, eval_eq, eval_ge, eval_gt, eval_le, eval_lt, num_neq,
use super::predicates::{
compile_not, compile_not_to_stack, compile_null_p, compile_null_p_to_stack, not_fn, null_p,
pub(in crate::compiler::native) const NATIVES: &[NativeSpec] = &[
NativeSpec {
name: "=",
eval: eval_eq,
stack: Some(compile_eq_to_stack),
effect: Some(compile_eq),
},
name: "/=",
eval: num_neq,
stack: Some(compile_neq_to_stack),
effect: Some(compile_num_neq),
name: "<",
eval: eval_lt,
stack: Some(compile_lt_to_stack),
effect: Some(compile_lt),
name: ">",
eval: eval_gt,
stack: Some(compile_gt_to_stack),
effect: Some(compile_gt),
name: "<=",
eval: eval_le,
stack: Some(compile_le_to_stack),
effect: Some(compile_le),
name: ">=",
eval: eval_ge,
stack: Some(compile_ge_to_stack),
effect: Some(compile_ge),
name: "EQL",
eval: eql,
stack: Some(compile_eql_to_stack),
effect: Some(compile_eql),
name: "EQUAL",
eval: equal,
stack: Some(compile_equal_to_stack),
effect: Some(compile_equal),
// Scheme-spelled aliases of the CL equality predicates — same
// structural comparison, registered so the documented `EQ?` / `EQUAL?`
// natives are not dead names the compiler rejects at codegen.
name: "EQ?",
name: "EQ",
name: "EQUAL?",
name: "NOT",
eval: not_fn,
stack: Some(compile_not_to_stack),
effect: Some(compile_not),
name: "NULL?",
eval: null_p,
stack: Some(compile_null_p_to_stack),
effect: Some(compile_null_p),
];
pub(in crate::compiler::native) fn bool_result(value: bool) -> Expr {
if value { Expr::T } else { Expr::Nil }
}
pub(super) fn emit_bool(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
value: bool,
) -> Result<()> {
if value {
compile_t(ctx, emit)
} else {
compile_nil(ctx, emit)
pub(super) fn has_runtime(resolved: &[Expr]) -> bool {
resolved.iter().any(crate::ast::Expr::is_wasm_runtime)
/// Classifies every arg on ONE disposable clone (so a later arg's probe
/// sees an earlier arg's compile-time effects, but NONE of them reach the
/// live table here) — purely for the all-constant fold / arg-type checks
/// in CODEGEN paths, which separately emit the real operands afterward
/// (via [`compile_args_for_effect`] for the constant fold, or the runtime
/// `compile_for_stack`/`compile_for_stack_as_*` calls the caller makes
/// itself). The pure eval-mirror comparisons (`num_cmp`/`num_neq`/`eql`/
/// `equal` in `dispatch.rs`) have no separate emission step at all, so they
/// evaluate their operands directly on the live table instead — see their
/// own `eval_all_for_effect`.
pub(super) fn resolve_all(symbols: &SymbolTable, args: &[Expr]) -> Result<Vec<Expr>> {
let mut probe = symbols.clone();
args.iter()
.map(|arg| probe_value(&mut probe, arg))
.collect()
/// Compiles every one of `args` for effect, in source order, on the LIVE
/// table — the single real application of a comparison's operands when
/// they all fold to a compile-time constant (see [`resolve_all`]).
pub(super) fn compile_args_for_effect(
symbols: &mut SymbolTable,
args: &[Expr],
for arg in args {
compile_for_effect(ctx, emit, symbols, arg)?;
Ok(())
/// The operands' values when every one is a constant of one kind; a kind mix
/// is an error.
pub(super) fn extract_numbers(resolved: &[Expr], name: &str) -> Result<Option<Vec<Fraction>>> {
let Some(nums) = resolved
.iter()
.map(|e| match e {
Expr::Number(n) => Some(*n),
_ => None,
})
.collect::<Option<Vec<_>>>()
else {
return Ok(None);
for n in &nums {
if let Number::Index(i) = n {
index_literal(*i)?;
shared_dim(nums.iter().map(|n| Dim::of_number(*n)), name)?;
Ok(Some(nums.iter().map(|n| n.value()).collect()))
fn operand_dim(operand: &Expr, name: &str) -> Result<Dim> {
Dim::of_value(operand).ok_or_else(|| {
match operand.wasm_type().filter(|_| operand.is_wasm_runtime()) {
Some(ty) => non_numeric_operand(name, ty),
None => Error::Compile(format!(
"{name} expects numeric arguments, got {}",
format_expr(operand)
)),
/// The wasm type every operand of a comparison shares; operands of different
/// dimensions are a mix, crossed only by an explicit `index->scalar` /
/// `scalar->index` / `convert-commodity`.
pub(in crate::compiler) fn validate_cmp_args(resolved: &[Expr], name: &str) -> Result<WasmType> {
let dims = resolved
.map(|r| operand_dim(r, name))
.collect::<Result<Vec<_>>>()?;
let dim = shared_dim(dims, name)?;
Ok(dim.map_or(WasmType::Ratio, Dim::wasm_type))
/// [`validate_cmp_args`], retried over the operands that yield a value when it
/// refuses: one that always raises has no dimension. The walk that finds them
/// runs only on that path.
pub(super) fn validate_valued_args(
symbols: &SymbolTable,
resolved: &[Expr],
name: &str,
) -> Result<WasmType> {
let dim = decided_over_dims(
symbols,
(args, resolved),
|operand| operand_dim(operand, name),
|dims| shared_dim(dims.iter().flatten().copied(), name),
)?;
/// Whether two resolved operands are the same datum. Operands of different
/// static numeric kinds are a mix, as in an ordering comparison; `EQUAL` and
/// `ASSERT-EQUAL` look at every paired position of a list, `EQ` and `EQL` only
/// at the top level. A runtime operand of statically unknown type is compared
/// at run time.
pub(in crate::compiler) fn same_datum(a: &Expr, b: &Expr, name: &str) -> Result<bool> {
match name {
"EQUAL" | "ASSERT-EQUAL" => refuse_kind_mix(a, b, name)?,
_ => refuse_dim_mix(a, b, name)?,
Ok(a == b)
fn refuse_kind_mix(a: &Expr, b: &Expr, name: &str) -> Result<()> {
match (a, b) {
(Expr::Datum(inner), other) | (other, Expr::Datum(inner)) => {
refuse_kind_mix(inner, other, name)
(Expr::List(left), Expr::List(right)) => left
.zip(right)
.try_for_each(|(l, r)| refuse_kind_mix(l, r, name)),
(Expr::Cons(car_a, cdr_a), Expr::Cons(car_b, cdr_b)) => {
refuse_kind_mix(car_a, car_b, name)?;
refuse_kind_mix(cdr_a, cdr_b, name)
_ => refuse_dim_mix(a, b, name),
/// Push a value onto the WASM stack asserting it is a Commodity.
/// Refuses every other type — commodity comparisons must be homogeneous.
pub(super) fn compile_for_stack_as_commodity(
expr: &Expr,
let ty = compile_for_stack(ctx, emit, symbols, expr)?;
match ty {
WasmType::Commodity => Ok(()),
_ => Err(Error::Compile(format!(
"commodity comparison requires commodity-bearing operand, got {ty}"
))),
#[cfg(test)]
#[path = "shared_tests.rs"]
mod tests;