1
//! Runtime codegen for the comparison shape. Each per-op
2
//! `compile_*_to_stack` routes through one of three helpers:
3
//! `compile_cmp_to_stack` (forward operand order, dispatched by
4
//! name), `compile_cmp_to_stack_reversed` (`>` ≡ swap-and-`<`),
5
//! or the per-op explicit form (`<=` / `>=` need an `i32_eqz` over
6
//! the strict comparator since `ratio_le` / `commodity_le` don't
7
//! exist).
8

            
9
use crate::ast::{Expr, Fraction, WasmType};
10
use crate::compiler::context::CompileContext;
11
use crate::compiler::emit::FunctionEmitter;
12
use crate::compiler::expr::{always_raises, is_untyped, probe_value};
13
use crate::error::{Error, Result};
14
use crate::runtime::SymbolTable;
15

            
16
use super::super::shared::{
17
    compile_args_for_effect, extract_numbers, resolve_all, validate_cmp_args,
18
};
19
use super::emit::{ExprOperands, emit_runtime_cmp};
20
use super::identity::{emit_identity, identity_name};
21
use super::spilled::{compile_spilled_cmp, compile_spilled_identity};
22

            
23
332930
pub(in crate::compiler::native::comparison) fn compile_eq_to_stack(
24
332930
    ctx: &mut CompileContext,
25
332930
    emit: &mut FunctionEmitter,
26
332930
    symbols: &mut SymbolTable,
27
332930
    args: &[Expr],
28
332930
) -> Result<WasmType> {
29
332930
    compile_cmp_to_stack(ctx, emit, symbols, args, "=", |a, b| a == b)
30
332930
}
31

            
32
/// `EQL` / `EQUAL` / `EQ?` / `EQUAL?` — generic structural equality. Unlike the
33
/// numeric `=` (`compile_eq_to_stack`), this also compares strings: a runtime
34
/// `account-name` against a literal lowers to the shared `string_eq` byte
35
/// comparison. The result is a `Bool` truth value (Nil/Bool serialization), so
36
/// it composes inside `and` / `if` and as a value-position result.
37
34731
pub(in crate::compiler::native::comparison) fn compile_eql_to_stack(
38
34731
    ctx: &mut CompileContext,
39
34731
    emit: &mut FunctionEmitter,
40
34731
    symbols: &mut SymbolTable,
41
34731
    args: &[Expr],
42
34731
) -> Result<WasmType> {
43
34731
    compile_identity_to_stack(ctx, emit, symbols, args, false)
44
34731
}
45

            
46
16204
pub(in crate::compiler::native::comparison) fn compile_equal_to_stack(
47
16204
    ctx: &mut CompileContext,
48
16204
    emit: &mut FunctionEmitter,
49
16204
    symbols: &mut SymbolTable,
50
16204
    args: &[Expr],
51
16204
) -> Result<WasmType> {
52
16204
    compile_identity_to_stack(ctx, emit, symbols, args, true)
53
16204
}
54

            
55
50935
fn compile_identity_to_stack(
56
50935
    ctx: &mut CompileContext,
57
50935
    emit: &mut FunctionEmitter,
58
50935
    symbols: &mut SymbolTable,
59
50935
    args: &[Expr],
60
50935
    structural: bool,
61
50935
) -> Result<WasmType> {
62
50935
    if args.len() != 2 {
63
632
        return Err(Error::Arity {
64
632
            name: identity_name(structural).to_string(),
65
632
            expected: 2,
66
632
            actual: args.len(),
67
632
        });
68
50303
    }
69
    // One disposable clone, probed in order: `b` must classify against the
70
    // compile-time effects of `a` (a `setf`, a `defvar`).
71
50303
    let mut probe = symbols.clone();
72
50303
    let a = probe_value(&mut probe, &args[0])?;
73
50297
    let b = probe_value(&mut probe, &args[1])?;
74
50293
    let resolved = [a, b];
75
50293
    if is_spilled(symbols, args, &resolved)? {
76
8801
        return compile_spilled_identity(ctx, emit, symbols, args, &resolved, structural);
77
41492
    }
78
41492
    let identity = emit_identity(
79
41492
        &mut ExprOperands {
80
41492
            ctx,
81
41492
            emit,
82
41492
            symbols,
83
41492
            args,
84
41492
        },
85
41492
        &resolved[0],
86
41492
        &resolved[1],
87
41492
        structural,
88
41492
    );
89
41492
    match identity {
90
        Err(mix @ Error::Dimension(_)) => {
91
50
            compile_spilled_identity(ctx, emit, symbols, args, &resolved, structural)
92
                .map_err(|_| mix)
93
        }
94
41442
        other => other,
95
    }
96
50935
}
97

            
98
635
pub(in crate::compiler::native::comparison) fn compile_neq_to_stack(
99
635
    ctx: &mut CompileContext,
100
635
    emit: &mut FunctionEmitter,
101
635
    symbols: &mut SymbolTable,
102
635
    args: &[Expr],
103
635
) -> Result<WasmType> {
104
635
    if args.is_empty() {
105
        return Err(Error::Compile(
106
            "/= requires at least 1 argument".to_string(),
107
        ));
108
635
    }
109
635
    let resolved = resolve_all(symbols, args)?;
110
634
    if let Some(nums) = extract_numbers(&resolved, "/=")? {
111
8
        let result = (0..nums.len()).all(|i| (i + 1..nums.len()).all(|j| nums[i] != nums[j]));
112
4
        compile_args_for_effect(ctx, emit, symbols, args)?;
113
4
        emit.i32_const(i32::from(result));
114
4
        return Ok(WasmType::Bool);
115
630
    }
116
630
    compile_runtime_cmp(ctx, emit, symbols, args, &resolved, "/=")
117
635
}
118

            
119
25303
pub(in crate::compiler::native::comparison) fn compile_lt_to_stack(
120
25303
    ctx: &mut CompileContext,
121
25303
    emit: &mut FunctionEmitter,
122
25303
    symbols: &mut SymbolTable,
123
25303
    args: &[Expr],
124
25303
) -> Result<WasmType> {
125
25303
    compile_cmp_to_stack(ctx, emit, symbols, args, "<", |a, b| a < b)
126
25303
}
127

            
128
2242322
pub(in crate::compiler::native::comparison) fn compile_gt_to_stack(
129
2242322
    ctx: &mut CompileContext,
130
2242322
    emit: &mut FunctionEmitter,
131
2242322
    symbols: &mut SymbolTable,
132
2242322
    args: &[Expr],
133
2242322
) -> Result<WasmType> {
134
    // a > b ≡ b < a
135
2242322
    compile_cmp_to_stack_reversed(ctx, emit, symbols, args, ">", |a, b| a > b)
136
2242322
}
137

            
138
16654
pub(in crate::compiler::native::comparison) fn compile_le_to_stack(
139
16654
    ctx: &mut CompileContext,
140
16654
    emit: &mut FunctionEmitter,
141
16654
    symbols: &mut SymbolTable,
142
16654
    args: &[Expr],
143
16654
) -> Result<WasmType> {
144
16654
    if args.len() != 2 {
145
2
        return Err(Error::Compile(
146
2
            "<= requires exactly 2 arguments for runtime comparison".to_string(),
147
2
        ));
148
16652
    }
149
16652
    let resolved = resolve_all(symbols, args)?;
150
16651
    if let Some(nums) = extract_numbers(&resolved, "<=")? {
151
13522
        let result = nums[0] <= nums[1];
152
13522
        compile_args_for_effect(ctx, emit, symbols, args)?;
153
13522
        emit.i32_const(i32::from(result));
154
13522
        return Ok(WasmType::Bool);
155
3129
    }
156
3129
    compile_runtime_cmp(ctx, emit, symbols, args, &resolved, "<=")
157
16654
}
158

            
159
43402
pub(in crate::compiler::native::comparison) fn compile_ge_to_stack(
160
43402
    ctx: &mut CompileContext,
161
43402
    emit: &mut FunctionEmitter,
162
43402
    symbols: &mut SymbolTable,
163
43402
    args: &[Expr],
164
43402
) -> Result<WasmType> {
165
43402
    if args.len() != 2 {
166
        return Err(Error::Compile(
167
            ">= requires exactly 2 arguments for runtime comparison".to_string(),
168
        ));
169
43402
    }
170
43402
    let resolved = resolve_all(symbols, args)?;
171
43401
    if let Some(nums) = extract_numbers(&resolved, ">=")? {
172
2
        let result = nums[0] >= nums[1];
173
2
        compile_args_for_effect(ctx, emit, symbols, args)?;
174
2
        emit.i32_const(i32::from(result));
175
2
        return Ok(WasmType::Bool);
176
43399
    }
177
43399
    compile_runtime_cmp(ctx, emit, symbols, args, &resolved, ">=")
178
43402
}
179

            
180
8371
pub(in crate::compiler::native::comparison) fn compile_cmp_to_stack_by_name(
181
8371
    ctx: &mut CompileContext,
182
8371
    emit: &mut FunctionEmitter,
183
8371
    symbols: &mut SymbolTable,
184
8371
    args: &[Expr],
185
8371
    name: &str,
186
8371
    const_cmp: fn(&Fraction, &Fraction) -> bool,
187
8371
) -> Result<WasmType> {
188
8371
    match name {
189
6040
        "=" => compile_eq_to_stack(ctx, emit, symbols, args),
190
1282
        "<" => compile_lt_to_stack(ctx, emit, symbols, args),
191
211
        ">" => compile_gt_to_stack(ctx, emit, symbols, args),
192
419
        "<=" => compile_le_to_stack(ctx, emit, symbols, args),
193
419
        ">=" => compile_ge_to_stack(ctx, emit, symbols, args),
194
        _ => compile_cmp_to_stack(ctx, emit, symbols, args, name, const_cmp),
195
    }
196
8371
}
197

            
198
/// The runtime comparison of two operands.
199
2577858
fn compile_runtime_cmp(
200
2577858
    ctx: &mut CompileContext,
201
2577858
    emit: &mut FunctionEmitter,
202
2577858
    symbols: &mut SymbolTable,
203
2577858
    args: &[Expr],
204
2577858
    resolved: &[Expr],
205
2577858
    name: &str,
206
2577858
) -> Result<WasmType> {
207
2577858
    let chained = args.len() > 2 && name != "/=";
208
2577858
    if chained || (args.len() == 2 && is_spilled(symbols, args, resolved)?) {
209
6942
        return compile_spilled_cmp(ctx, emit, symbols, args, resolved, name);
210
2570916
    }
211
2570916
    let dim = match runtime_cmp_dim(args, resolved, name) {
212
        // A raising operand has no dimension; only compiling it shows that.
213
        Err(mix @ Error::Dimension(_)) => {
214
1081
            return compile_spilled_cmp(ctx, emit, symbols, args, resolved, name).map_err(|_| mix);
215
        }
216
2569835
        dim => dim?,
217
    };
218
2567944
    emit_runtime_cmp(
219
2567944
        &mut ExprOperands {
220
2567944
            ctx,
221
2567944
            emit,
222
2567944
            symbols,
223
2567944
            args,
224
2567944
        },
225
2567944
        name,
226
2567944
        dim,
227
2567944
    )
228
2577858
}
229

            
230
2626467
fn is_spilled(symbols: &SymbolTable, args: &[Expr], resolved: &[Expr]) -> Result<bool> {
231
2626467
    if resolved.iter().any(is_untyped) {
232
13822
        return Ok(true);
233
2612645
    }
234
2612645
    for arg in args {
235
5225284
        if always_raises(symbols, arg)? {
236
241
            return Ok(true);
237
5225043
        }
238
    }
239
2612404
    Ok(false)
240
2626467
}
241

            
242
2570916
fn runtime_cmp_dim(args: &[Expr], resolved: &[Expr], name: &str) -> Result<WasmType> {
243
2570916
    if args.len() != 2 {
244
4
        return Err(Error::Compile(format!(
245
4
            "{name} with runtime args requires exactly 2 arguments"
246
4
        )));
247
2570912
    }
248
2570912
    validate_cmp_args(resolved, name)
249
2570916
}
250

            
251
358233
fn compile_cmp_to_stack(
252
358233
    ctx: &mut CompileContext,
253
358233
    emit: &mut FunctionEmitter,
254
358233
    symbols: &mut SymbolTable,
255
358233
    args: &[Expr],
256
358233
    name: &str,
257
358233
    const_cmp: fn(&Fraction, &Fraction) -> bool,
258
358233
) -> Result<WasmType> {
259
358233
    if args.is_empty() {
260
423
        return Err(Error::Compile(format!(
261
423
            "{name} requires at least 1 argument"
262
423
        )));
263
357810
    }
264
357810
    let resolved = resolve_all(symbols, args)?;
265
357805
    if let Some(nums) = extract_numbers(&resolved, name)? {
266
53021
        let result = nums.windows(2).all(|w| const_cmp(&w[0], &w[1]));
267
53019
        compile_args_for_effect(ctx, emit, symbols, args)?;
268
53019
        emit.i32_const(i32::from(result));
269
53019
        return Ok(WasmType::Bool);
270
304781
    }
271
304781
    compile_runtime_cmp(ctx, emit, symbols, args, &resolved, name)
272
358233
}
273

            
274
2242322
fn compile_cmp_to_stack_reversed(
275
2242322
    ctx: &mut CompileContext,
276
2242322
    emit: &mut FunctionEmitter,
277
2242322
    symbols: &mut SymbolTable,
278
2242322
    args: &[Expr],
279
2242322
    name: &str,
280
2242322
    const_cmp: fn(&Fraction, &Fraction) -> bool,
281
2242322
) -> Result<WasmType> {
282
2242322
    if args.is_empty() {
283
        return Err(Error::Compile(format!(
284
            "{name} requires at least 1 argument"
285
        )));
286
2242322
    }
287
2242322
    let resolved = resolve_all(symbols, args)?;
288
2242321
    if let Some(nums) = extract_numbers(&resolved, name)? {
289
16404
        let result = nums.windows(2).all(|w| const_cmp(&w[0], &w[1]));
290
16402
        compile_args_for_effect(ctx, emit, symbols, args)?;
291
16402
        emit.i32_const(i32::from(result));
292
16402
        return Ok(WasmType::Bool);
293
2225919
    }
294
2225919
    compile_runtime_cmp(ctx, emit, symbols, args, &resolved, name)
295
2242322
}