1
//! The `EQ?` / `EQL` / `EQUAL` / `EQUAL?` identity emitter. The caller
2
//! classifies its two operands (a constant as its literal, a runtime value as
3
//! `WasmRuntime`) and supplies them through [`IdentityOperands`]; this module alone decides which
4
//! identity test the pair needs and emits it. Every route evaluates both
5
//! operands exactly once, in source order, even when the answer is static.
6

            
7
mod anyref;
8

            
9
use crate::ast::{Expr, WasmType};
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::{NilRepr, classify_stack_type, nil_repr};
12
use crate::compiler::native::nullable::require_non_null;
13
use crate::error::{Error, Result};
14

            
15
use super::super::shared::{same_datum, validate_cmp_args};
16
use super::emit::{CmpOperands, emit_runtime_cmp};
17
use anyref::try_emit_anyref_identity;
18

            
19
/// How a pipeline emits the two operands of an identity test.
20
pub(in crate::compiler) trait IdentityOperands: CmpOperands {
21
    /// Emits operand `index` for its value, returning its stack type.
22
    fn stack(&mut self, index: usize) -> Result<WasmType>;
23
    /// Emits operand `index` for its effects only.
24
    fn effect(&mut self, index: usize) -> Result<()>;
25
}
26

            
27
/// Emits the identity test of two operands classified as `a` and `b`,
28
/// leaving a `Bool` on the stack.
29
50306
pub(in crate::compiler) fn emit_identity(
30
50306
    ops: &mut impl IdentityOperands,
31
50306
    a: &Expr,
32
50306
    b: &Expr,
33
50306
    structural: bool,
34
50306
) -> Result<WasmType> {
35
50306
    if !a.is_wasm_runtime() && !b.is_wasm_runtime() {
36
12735
        return emit_static(ops, same_datum(a, b, identity_name(structural))?);
37
37571
    }
38
37571
    if let Some((known_is_t, known_is_first)) = t_or_nil_identity_operand(a, b) {
39
1891
        return emit_t_nil_identity(ops, known_is_t, known_is_first);
40
35680
    }
41
35680
    if is_t_nil_vs_never_nil(a, b) {
42
4396
        return emit_static(ops, false);
43
31284
    }
44
    // AnyRef can box any type, so it must route before the disjoint-type
45
    // check below.
46
31284
    if let Some(ty) = try_emit_anyref_identity(ops, a, b, structural)? {
47
9027
        return Ok(ty);
48
22257
    }
49
22257
    if let (Some(WasmType::PairRef(_)), Some(WasmType::PairRef(_))) =
50
22257
        (classify_stack_type(a), classify_stack_type(b))
51
    {
52
247
        return emit_pair_identity(ops, structural);
53
22010
    }
54
22010
    if let (Some(WasmType::StructRef(_)), Some(WasmType::StructRef(_))) =
55
22010
        (classify_stack_type(a), classify_stack_type(b))
56
    {
57
4166
        return emit_struct_identity(ops);
58
17844
    }
59
17844
    if let (Some(ty_a), Some(ty_b)) = (classify_stack_type(a), classify_stack_type(b))
60
17844
        && ty_a != ty_b
61
8810
        && (is_nilable(ty_a) || is_nilable(ty_b))
62
    {
63
8765
        return emit_cross_type_nil_identity(ops, ty_a, ty_b);
64
9079
    }
65
9079
    match (is_symbol_typed(a), is_symbol_typed(b)) {
66
1299
        (true, true) => return emit_symbol_equal(ops),
67
        (true, false) | (false, true) => return emit_static(ops, false),
68
7780
        (false, false) => {}
69
    }
70
7780
    match (is_string_typed(a), is_string_typed(b)) {
71
1664
        (true, true) => emit_string_equal(ops),
72
        (true, false) | (false, true) => emit_static(ops, false),
73
6116
        (false, false) if is_bool_typed(a) && is_bool_typed(b) => emit_runtime_bool_equal(ops),
74
        (false, false) => {
75
2992
            let dim = validate_cmp_args(&[a.clone(), b.clone()], identity_name(structural))?;
76
2947
            emit_runtime_cmp(ops, "=", dim)
77
        }
78
    }
79
50306
}
80

            
81
16359
pub(super) fn identity_name(structural: bool) -> &'static str {
82
16359
    if structural { "EQUAL" } else { "EQL" }
83
16359
}
84

            
85
/// Two structure instances: the same object, by `ref.eq`. `EQUAL` is `EQ`
86
/// for a structure.
87
4166
fn emit_struct_identity(ops: &mut impl IdentityOperands) -> Result<WasmType> {
88
4166
    ops.stack(0)?;
89
4166
    ops.stack(1)?;
90
4166
    ops.emit().ref_eq();
91
4166
    Ok(WasmType::Bool)
92
4166
}
93

            
94
/// Two lists: the same object, or both `nil` (the null `$pair`), by
95
/// `ref.eq` of the emitted references; `EQUAL` compares them structurally.
96
/// Their element annotations are compile-time types, not part of the object
97
/// (0011 S17 / ISS-007).
98
247
fn emit_pair_identity(ops: &mut impl IdentityOperands, structural: bool) -> Result<WasmType> {
99
247
    ops.stack(0)?;
100
247
    ops.stack(1)?;
101
247
    if structural {
102
238
        let pair_equal = ops.ctx().ids.pair_equal;
103
238
        ops.emit().call(pair_equal);
104
    } else {
105
9
        ops.emit().ref_eq();
106
    }
107
247
    Ok(WasmType::Bool)
108
247
}
109

            
110
/// Both operands for effect, then the statically known answer.
111
17089
fn emit_static(ops: &mut impl IdentityOperands, holds: bool) -> Result<WasmType> {
112
17089
    ops.effect(0)?;
113
17089
    ops.effect(1)?;
114
16875
    ops.emit().i32_const(i32::from(holds));
115
16875
    Ok(WasmType::Bool)
116
17089
}
117

            
118
9240
fn is_bool_typed(expr: &Expr) -> bool {
119
9240
    expr.wasm_type() == Some(WasmType::Bool)
120
9240
}
121

            
122
15560
fn is_string_typed(expr: &Expr) -> bool {
123
15560
    matches!(expr, Expr::String(_)) || expr.wasm_type() == Some(WasmType::StringRef)
124
15560
}
125

            
126
18158
fn is_symbol_typed(expr: &Expr) -> bool {
127
18158
    classify_stack_type(expr) == Some(WasmType::SymbolRef)
128
18158
}
129

            
130
16393
fn is_nilable(ty: WasmType) -> bool {
131
16393
    matches!(nil_repr(&ty), NilRepr::I32Zero | NilRepr::Null)
132
16393
}
133

            
134
143152
fn known_t_or_nil(expr: &Expr) -> Option<bool> {
135
143152
    match expr {
136
4620
        Expr::T => Some(true),
137
6063
        Expr::Nil => Some(false),
138
132469
        _ => None,
139
    }
140
143152
}
141

            
142
/// When one side is the constant `t`/`nil` and the other a runtime value
143
/// that can itself be `t`/`nil`: whether the known side is `t`, and whether
144
/// it is the first operand.
145
37571
fn t_or_nil_identity_operand(a: &Expr, b: &Expr) -> Option<(bool, bool)> {
146
6287
    let nilable = |other: &Expr| other.wasm_type().is_some_and(is_nilable);
147
37571
    match (known_t_or_nil(a), known_t_or_nil(b)) {
148
4606
        (Some(is_t), _) if nilable(b) => Some((is_t, true)),
149
1681
        (_, Some(is_t)) if nilable(a) => Some((is_t, false)),
150
35680
        _ => None,
151
    }
152
37571
}
153

            
154
/// `t`/`nil` against a runtime value of a type that is never `t`/`nil`
155
/// (Index, Ratio, Commodity, Closure): statically `nil`.
156
35680
fn is_t_nil_vs_never_nil(a: &Expr, b: &Expr) -> bool {
157
4396
    let never_nil = |e: &Expr| {
158
4396
        e.wasm_type()
159
4396
            .is_some_and(|ty| matches!(nil_repr(&ty), NilRepr::Never))
160
4396
    };
161
35680
    (known_t_or_nil(a).is_some() && never_nil(b)) || (known_t_or_nil(b).is_some() && never_nil(a))
162
35680
}
163

            
164
/// Tests the runtime side against `t` (when `known_is_t`) or `nil`: a
165
/// `Bool`'s raw i32 is its "is t" flag; a reference's `nil` is null and its
166
/// `t` the `$t` singleton.
167
1891
fn emit_t_nil_identity(
168
1891
    ops: &mut impl IdentityOperands,
169
1891
    known_is_t: bool,
170
1891
    known_is_first: bool,
171
1891
) -> Result<WasmType> {
172
1891
    let ty = if known_is_first {
173
1256
        ops.effect(0)?;
174
1256
        ops.stack(1)?
175
    } else {
176
635
        let ty = ops.stack(0)?;
177
631
        let local = ops.ctx().alloc_local(ty)?;
178
631
        ops.emit().local_set(local);
179
631
        ops.effect(1)?;
180
631
        ops.emit().local_get(local);
181
631
        ty
182
    };
183
1883
    let (ctx, emit) = ops.parts();
184
1883
    match nil_repr(&ty) {
185
1464
        NilRepr::I32Zero if !known_is_t => emit.i32_eqz(),
186
1042
        NilRepr::I32Zero => {}
187
419
        NilRepr::Null if known_is_t => {
188
208
            emit.ref_cast_eq();
189
208
            emit.global_get(ctx.ids.global_t);
190
208
            emit.ref_eq();
191
        }
192
211
        NilRepr::Null => emit.ref_is_null(),
193
        NilRepr::Never => {
194
            return Err(Error::Compile(format!(
195
                "internal: {ty} is never nil, routed as a t/nil identity test"
196
            )));
197
        }
198
    }
199
1883
    Ok(WasmType::Bool)
200
1891
}
201

            
202
/// Two runtime operands of different, disjoint types (neither `AnyRef`),
203
/// at least one nilable: equal only when both are `nil`.
204
8765
fn emit_cross_type_nil_identity(
205
8765
    ops: &mut impl IdentityOperands,
206
8765
    ty_a: WasmType,
207
8765
    ty_b: WasmType,
208
8765
) -> Result<WasmType> {
209
8765
    let local_a = ops.ctx().alloc_local(ty_a)?;
210
8765
    ops.stack(0)?;
211
8763
    ops.emit().local_set(local_a);
212
8763
    let local_b = ops.ctx().alloc_local(ty_b)?;
213
8763
    ops.stack(1)?;
214
8757
    let emit = ops.emit();
215
8757
    emit.local_set(local_b);
216
8757
    emit_is_nil_flag(emit, local_a, ty_a);
217
8757
    emit_is_nil_flag(emit, local_b, ty_b);
218
8757
    emit.i32_and();
219
8757
    Ok(WasmType::Bool)
220
8765
}
221

            
222
/// Pushes `1` (nil) / `0` (not nil) for the value in `local` of type `ty`.
223
17514
fn emit_is_nil_flag(emit: &mut FunctionEmitter, local: u32, ty: WasmType) {
224
17514
    emit.local_get(local);
225
17514
    match nil_repr(&ty) {
226
7077
        NilRepr::I32Zero => emit.i32_eqz(),
227
8761
        NilRepr::Null => emit.ref_is_null(),
228
        NilRepr::Never => {
229
1676
            emit.drop_value();
230
1676
            emit.i32_const(0);
231
        }
232
    }
233
17514
}
234

            
235
/// Two strings: both evaluated into locals before either is null-checked,
236
/// then compared bytewise by `string_eq`.
237
1664
fn emit_string_equal(ops: &mut impl IdentityOperands) -> Result<WasmType> {
238
1664
    let local_a = string_operand(ops, 0)?;
239
1664
    let local_b = string_operand(ops, 1)?;
240
1664
    let (ctx, emit) = ops.parts();
241
1664
    for local in [local_a, local_b] {
242
3328
        emit.local_get(local);
243
3328
        require_non_null(ctx, emit, WasmType::StringRef, ctx.ids.nil_string)?;
244
3328
        emit.local_set(local);
245
    }
246
1664
    emit.local_get(local_a);
247
1664
    emit.local_get(local_b);
248
1664
    emit.call(ctx.ids.string_eq);
249
1664
    Ok(WasmType::Bool)
250
1664
}
251

            
252
/// Two symbols compare by name; a nil symbol equals only another nil.
253
1299
fn emit_symbol_equal(ops: &mut impl IdentityOperands) -> Result<WasmType> {
254
1299
    for index in 0..2 {
255
2598
        let ty = ops.stack(index)?;
256
2598
        if ty != WasmType::SymbolRef {
257
            return Err(Error::Compile(format!(
258
                "EQUAL: symbol comparison requires symbol operands, got {ty}"
259
            )));
260
2598
        }
261
    }
262
1299
    let (ctx, emit) = ops.parts();
263
1299
    emit.call(ctx.ids.symbol_eq);
264
1299
    Ok(WasmType::Bool)
265
1299
}
266

            
267
3328
fn string_operand(ops: &mut impl IdentityOperands, index: usize) -> Result<u32> {
268
3328
    let ty = ops.stack(index)?;
269
3328
    if ty != WasmType::StringRef {
270
        return Err(Error::Compile(format!(
271
            "EQUAL: string comparison requires string operands, got {ty}"
272
        )));
273
3328
    }
274
3328
    let local = ops.ctx().alloc_local(ty)?;
275
3328
    ops.emit().local_set(local);
276
3328
    Ok(local)
277
3328
}
278

            
279
/// Two runtime `Bool`s: raw i32 equality.
280
3124
fn emit_runtime_bool_equal(ops: &mut impl IdentityOperands) -> Result<WasmType> {
281
3124
    let local_a = ops.ctx().alloc_local(WasmType::Bool)?;
282
3124
    ops.stack(0)?;
283
3122
    ops.emit().local_set(local_a);
284
3122
    ops.stack(1)?;
285
3122
    let emit = ops.emit();
286
3122
    emit.local_get(local_a);
287
3122
    emit.i32_eq();
288
3122
    Ok(WasmType::Bool)
289
3124
}