1
//! Comparison operands whose type is known only once they are compiled: each
2
//! is compiled exactly once, in source order, and parked in a local (or kept
3
//! as a literal), so the dimension is chosen from the types actually pushed.
4

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

            
12
use super::super::shared::validate_cmp_args;
13
use super::emit::{CmpOperands, emit_runtime_cmp};
14
use super::identity::{IdentityOperands, emit_identity};
15

            
16
enum Slot {
17
    Number(Number),
18
    /// An operand that always raises: it has no value and no dimension.
19
    Raises,
20
    /// A value parked in a local; `folded` is its constant when the
21
    /// evaluator folded the operand.
22
    Local {
23
        local: u32,
24
        ty: WasmType,
25
        folded: Option<Number>,
26
    },
27
}
28

            
29
struct Spilled<'a> {
30
    ctx: &'a mut CompileContext,
31
    emit: &'a mut FunctionEmitter,
32
    symbols: &'a mut SymbolTable,
33
    slots: Vec<Slot>,
34
}
35

            
36
/// Compiles every operand once and classifies it by what it pushed.
37
16874
fn spill(
38
16874
    ctx: &mut CompileContext,
39
16874
    emit: &mut FunctionEmitter,
40
16874
    symbols: &mut SymbolTable,
41
16874
    args: &[Expr],
42
16874
    resolved: &[Expr],
43
16874
) -> Result<(Vec<Slot>, Vec<Expr>)> {
44
16874
    let mut slots = Vec::with_capacity(args.len());
45
16874
    let mut classified = Vec::with_capacity(args.len());
46
16874
    for (arg, value) in args.iter().zip(resolved) {
47
35195
        if let (Expr::Number(n), Expr::Number(_)) = (value, arg) {
48
8900
            slots.push(Slot::Number(*n));
49
8900
            classified.push(value.clone());
50
8900
            continue;
51
26295
        }
52
26295
        if compile_raising(ctx, emit, symbols, arg)? {
53
5071
            slots.push(Slot::Raises);
54
5071
            classified.push(Expr::Number(Number::Index(1)));
55
5071
            continue;
56
21224
        }
57
21224
        let Some((local, ty)) = compile_to_local(ctx, emit, symbols, arg)? else {
58
33
            slots.push(Slot::Raises);
59
33
            classified.push(Expr::Number(Number::Index(1)));
60
33
            continue;
61
        };
62
20540
        let folded = match value {
63
1263
            Expr::Number(n) => Some(*n),
64
19277
            _ => None,
65
        };
66
20540
        slots.push(Slot::Local { local, ty, folded });
67
20540
        classified.push(if value.is_wasm_runtime() {
68
13626
            Expr::WasmRuntime(ty)
69
        } else {
70
6914
            value.clone()
71
        });
72
    }
73
16223
    Ok((slots, classified))
74
16874
}
75

            
76
impl Spilled<'_> {
77
33722
    fn slot(&self, index: usize) -> Result<&Slot> {
78
33722
        self.slots
79
33722
            .get(index)
80
            .ok_or_else(|| Error::Compile(format!("comparison has no operand {index}")))
81
33722
    }
82
}
83

            
84
impl CmpOperands for Spilled<'_> {
85
16376
    fn operand(&mut self, index: usize, target: WasmType) -> Result<()> {
86
16376
        match *self.slot(index)? {
87
            Slot::Number(n)
88
            | Slot::Local {
89
                folded: Some(n), ..
90
7774
            } => push_number(self.ctx, self.emit, n).map(drop),
91
            Slot::Raises => {
92
5272
                self.emit.unreachable();
93
5272
                Ok(())
94
            }
95
            Slot::Local {
96
                local,
97
                ty,
98
                folded: None,
99
3330
            } if ty == target => {
100
3330
                self.emit.local_get(local);
101
3330
                Ok(())
102
            }
103
            Slot::Local { ty, .. } => Err(Error::Compile(format!(
104
                "comparison requires {target} operands, got {ty}"
105
            ))),
106
        }
107
16376
    }
108

            
109
52721
    fn parts(&mut self) -> (&mut CompileContext, &mut FunctionEmitter) {
110
52721
        (self.ctx, self.emit)
111
52721
    }
112
}
113

            
114
impl IdentityOperands for Spilled<'_> {
115
17346
    fn stack(&mut self, index: usize) -> Result<WasmType> {
116
17346
        match *self.slot(index)? {
117
            Slot::Number(n) => {
118
419
                compile_for_stack(self.ctx, self.emit, self.symbols, &Expr::Number(n))
119
            }
120
            Slot::Raises => compile_for_stack(
121
                self.ctx,
122
                self.emit,
123
                self.symbols,
124
                &Expr::Number(Number::Index(1)),
125
            ),
126
            Slot::Local { local, ty, .. } => {
127
16927
                self.emit.local_get(local);
128
16927
                Ok(ty)
129
            }
130
        }
131
17346
    }
132

            
133
208
    fn effect(&mut self, _index: usize) -> Result<()> {
134
208
        Ok(())
135
208
    }
136
}
137

            
138
/// The operands `start` and `start + 1` of a [`Spilled`] chain, as the two
139
/// operands of one comparison.
140
struct Window<'a, 'b> {
141
    spilled: &'a mut Spilled<'b>,
142
    start: usize,
143
}
144

            
145
impl CmpOperands for Window<'_, '_> {
146
16376
    fn operand(&mut self, index: usize, target: WasmType) -> Result<()> {
147
16376
        self.spilled.operand(self.start + index, target)
148
16376
    }
149

            
150
10916
    fn parts(&mut self) -> (&mut CompileContext, &mut FunctionEmitter) {
151
10916
        self.spilled.parts()
152
10916
    }
153
}
154

            
155
/// The comparison `name` of operands `resolved` classified by the evaluator,
156
/// either of which only compiling can type or of which there are more than two:
157
/// every adjacent pair must hold.
158
8023
pub(super) fn compile_spilled_cmp(
159
8023
    ctx: &mut CompileContext,
160
8023
    emit: &mut FunctionEmitter,
161
8023
    symbols: &mut SymbolTable,
162
8023
    args: &[Expr],
163
8023
    resolved: &[Expr],
164
8023
    name: &str,
165
8023
) -> Result<WasmType> {
166
8023
    let (slots, classified) = spill(ctx, emit, symbols, args, resolved)?;
167
7381
    let mut operands = Spilled {
168
7381
        ctx,
169
7381
        emit,
170
7381
        symbols,
171
7381
        slots,
172
7381
    };
173
7381
    let typed: Vec<Expr> = classified
174
7381
        .into_iter()
175
7381
        .zip(&operands.slots)
176
16852
        .filter(|(_, slot)| !matches!(slot, Slot::Raises))
177
        .map(|(operand, _)| operand)
178
        .collect();
179
7381
    let dim = validate_cmp_args(&typed, name)?;
180
6106
    for start in 0..args.len() - 1 {
181
8188
        emit_runtime_cmp(
182
8188
            &mut Window {
183
8188
                spilled: &mut operands,
184
8188
                start,
185
8188
            },
186
8188
            name,
187
8188
            dim,
188
8188
        )?;
189
8188
        if start > 0 {
190
2082
            operands.emit.i32_and();
191
6106
        }
192
    }
193
6106
    Ok(WasmType::Bool)
194
8023
}
195

            
196
/// The identity test of two operands, at least one of which only compiling
197
/// can type.
198
8851
pub(super) fn compile_spilled_identity(
199
8851
    ctx: &mut CompileContext,
200
8851
    emit: &mut FunctionEmitter,
201
8851
    symbols: &mut SymbolTable,
202
8851
    args: &[Expr],
203
8851
    resolved: &[Expr],
204
8851
    structural: bool,
205
8851
) -> Result<WasmType> {
206
8851
    let (slots, classified) = spill(ctx, emit, symbols, args, resolved)?;
207
8842
    let mut operands = Spilled {
208
8842
        ctx,
209
8842
        emit,
210
8842
        symbols,
211
8842
        slots,
212
8842
    };
213
8842
    if operands
214
8842
        .slots
215
8842
        .iter()
216
17678
        .any(|slot| matches!(slot, Slot::Raises))
217
    {
218
28
        operands.emit.i32_const(0);
219
28
        return Ok(WasmType::Bool);
220
8814
    }
221
8814
    emit_identity(&mut operands, &classified[0], &classified[1], structural)
222
8851
}
223

            
224
#[cfg(test)]
225
#[path = "spilled_tests.rs"]
226
mod tests;