1
//! The runtime comparison emitter: once the operands' shared dimension is
2
//! known, the one implementation of which instructions each operator emits.
3
//! The caller supplies only its operands, through [`CmpOperands`].
4

            
5
use crate::ast::{Expr, WasmType};
6
use crate::compiler::context::CompileContext;
7
use crate::compiler::emit::FunctionEmitter;
8
use crate::compiler::expr::{compile_for_effect, compile_for_stack, compile_for_stack_as};
9
use crate::error::{Error, Result};
10
use crate::runtime::SymbolTable;
11

            
12
use super::super::shared::compile_for_stack_as_commodity;
13
use super::identity::IdentityOperands;
14

            
15
/// How a pipeline emits the operands of a runtime comparison.
16
pub(in crate::compiler) trait CmpOperands {
17
    /// Emits operand `index` coerced to `target`.
18
    fn operand(&mut self, index: usize, target: WasmType) -> Result<()>;
19
    fn parts(&mut self) -> (&mut CompileContext, &mut FunctionEmitter);
20

            
21
68005
    fn ctx(&mut self) -> &mut CompileContext {
22
68005
        self.parts().0
23
68005
    }
24

            
25
2652888
    fn emit(&mut self) -> &mut FunctionEmitter {
26
2652888
        self.parts().1
27
2652888
    }
28
}
29

            
30
/// Emits a two-operand runtime comparison `name` at dimension `dim` (as
31
/// `validate_cmp_args` classified it). Operands are evaluated in source
32
/// order; `>` and `<=` park both in locals and compare them reversed.
33
2579079
pub(in crate::compiler) fn emit_runtime_cmp(
34
2579079
    operands: &mut impl CmpOperands,
35
2579079
    name: &str,
36
2579079
    dim: WasmType,
37
2579079
) -> Result<WasmType> {
38
2579079
    match dim {
39
        WasmType::I32 => {
40
2561683
            operands.operand(0, WasmType::I32)?;
41
2561591
            operands.operand(1, WasmType::I32)?;
42
2561576
            let emit = operands.emit();
43
2561576
            match name {
44
278835
                "=" => emit.i32_eq(),
45
418
                "/=" => emit.i32_ne(),
46
14771
                "<" => emit.i32_lt_s(),
47
2222907
                ">" => emit.i32_gt_s(),
48
1666
                "<=" => emit.i32_le_s(),
49
42979
                ">=" => emit.i32_ge_s(),
50
                other => return Err(unknown(other)),
51
            }
52
        }
53
17396
        WasmType::Ratio | WasmType::Commodity => ordered(operands, name, dim)?,
54
        WasmType::Bool
55
        | WasmType::PairRef(_)
56
        | WasmType::StringRef
57
        | WasmType::SymbolRef
58
        | WasmType::EntityRef(_)
59
        | WasmType::StructRef(_)
60
        | WasmType::Closure(_)
61
        | WasmType::AnyRef => {
62
            return Err(Error::Compile(format!(
63
                "cannot compare cons cells with {name}"
64
            )));
65
        }
66
    }
67
2578971
    Ok(WasmType::Bool)
68
2579079
}
69

            
70
/// A scalar or money comparison through its `*_lt` / `*_eq` helpers.
71
17396
fn ordered(operands: &mut impl CmpOperands, name: &str, dim: WasmType) -> Result<()> {
72
17396
    let ids = &operands.ctx().ids;
73
17396
    let (lt, eq) = if dim == WasmType::Commodity {
74
208
        (ids.commodity_lt, ids.commodity_eq)
75
    } else {
76
17188
        (ids.ratio_lt, ids.ratio_eq)
77
    };
78
17396
    match name {
79
3150
        ">" => reversed(operands, dim, lt),
80
        "<=" => {
81
1459
            reversed(operands, dim, lt)?;
82
1459
            operands.emit().i32_eqz();
83
1459
            Ok(())
84
        }
85
        "=" | "<" | "/=" | ">=" => {
86
12787
            operands.operand(0, dim)?;
87
12787
            operands.operand(1, dim)?;
88
12787
            let emit = operands.emit();
89
12787
            match name {
90
8557
                "=" => emit.call(eq),
91
3604
                "<" => emit.call(lt),
92
                "/=" => {
93
210
                    emit.call(eq);
94
210
                    emit.i32_eqz();
95
                }
96
                _ => {
97
416
                    emit.call(lt);
98
416
                    emit.i32_eqz();
99
                }
100
            }
101
12787
            Ok(())
102
        }
103
        other => Err(unknown(other)),
104
    }
105
17396
}
106

            
107
/// `b < a` with both operands evaluated in source order into locals.
108
4609
fn reversed(operands: &mut impl CmpOperands, dim: WasmType, lt: u32) -> Result<()> {
109
4609
    operands.operand(0, dim)?;
110
4608
    let local_a = operands.ctx().alloc_local(dim)?;
111
4608
    operands.emit().local_set(local_a);
112
4608
    operands.operand(1, dim)?;
113
4608
    let local_b = operands.ctx().alloc_local(dim)?;
114
4608
    let emit = operands.emit();
115
4608
    emit.local_set(local_b);
116
4608
    emit.local_get(local_b);
117
4608
    emit.local_get(local_a);
118
4608
    emit.call(lt);
119
4608
    Ok(())
120
4609
}
121

            
122
fn unknown(name: &str) -> Error {
123
    Error::Compile(format!("no runtime comparison for operator '{name}'"))
124
}
125

            
126
/// Source-expression operands, compiled in place.
127
pub(super) struct ExprOperands<'a> {
128
    pub(super) ctx: &'a mut CompileContext,
129
    pub(super) emit: &'a mut FunctionEmitter,
130
    pub(super) symbols: &'a mut SymbolTable,
131
    pub(super) args: &'a [Expr],
132
}
133

            
134
impl<'a> ExprOperands<'a> {
135
5218671
    fn arg(&self, index: usize) -> Result<&'a Expr> {
136
5218671
        self.args
137
5218671
            .get(index)
138
            .ok_or_else(|| Error::Compile(format!("comparison has no operand {index}")))
139
5218671
    }
140
}
141

            
142
impl CmpOperands for ExprOperands<'_> {
143
5141689
    fn operand(&mut self, index: usize, target: WasmType) -> Result<()> {
144
5141689
        let arg = self.arg(index)?;
145
5141689
        match target {
146
            WasmType::Commodity => {
147
416
                compile_for_stack_as_commodity(self.ctx, self.emit, self.symbols, arg)
148
            }
149
5141273
            _ => compile_for_stack_as(self.ctx, self.emit, self.symbols, arg, target),
150
        }
151
5141689
    }
152

            
153
2682045
    fn parts(&mut self) -> (&mut CompileContext, &mut FunctionEmitter) {
154
2682045
        (self.ctx, self.emit)
155
2682045
    }
156
}
157

            
158
impl IdentityOperands for ExprOperands<'_> {
159
41125
    fn stack(&mut self, index: usize) -> Result<WasmType> {
160
41125
        let arg = self.arg(index)?;
161
41125
        compile_for_stack(self.ctx, self.emit, self.symbols, arg)
162
41125
    }
163

            
164
35857
    fn effect(&mut self, index: usize) -> Result<()> {
165
35857
        let arg = self.arg(index)?;
166
35857
        compile_for_effect(self.ctx, self.emit, self.symbols, arg)
167
35857
    }
168
}