1
//! Identity against an `AnyRef` operand. `AnyRef` is the ADR-0025 widen
2
//! target and can box a value of any other type, so it is never a disjoint
3
//! stratum: the test discriminates the boxed value's runtime shape.
4

            
5
use wasm_encoder::{BlockType, ValType};
6

            
7
use crate::ast::{Expr, WasmType};
8
use crate::compiler::context::CompileContext;
9
use crate::compiler::emit::FunctionEmitter;
10
use crate::compiler::expr::{NilRepr, classify_stack_type, emit_box_anyref, nil_repr};
11
use crate::error::{Error, Result};
12

            
13
use super::IdentityOperands;
14
use crate::compiler::context::ShapeCompare;
15

            
16
/// Emits the test when exactly one operand classifies as `AnyRef`;
17
/// `Ok(None)` otherwise. `classify_stack_type` also types a literal
18
/// operand, which `Expr::wasm_type` would miss.
19
31284
pub(super) fn try_emit_anyref_identity(
20
31284
    ops: &mut impl IdentityOperands,
21
31284
    a: &Expr,
22
31284
    b: &Expr,
23
31284
    structural: bool,
24
31284
) -> Result<Option<WasmType>> {
25
31284
    match (classify_stack_type(a), classify_stack_type(b)) {
26
        (Some(WasmType::AnyRef), Some(WasmType::AnyRef)) => {
27
27
            emit_anyref_vs_anyref(ops, structural).map(Some)
28
        }
29
624
        (Some(WasmType::Bool), Some(WasmType::AnyRef)) => emit_bool_anyref(ops, true).map(Some),
30
208
        (Some(WasmType::AnyRef), Some(WasmType::Bool)) => emit_bool_anyref(ops, false).map(Some),
31
2503
        (Some(ty), Some(WasmType::AnyRef)) if ty != WasmType::AnyRef => {
32
2503
            emit_concrete_vs_anyref(ops, true, structural).map(Some)
33
        }
34
5665
        (Some(WasmType::AnyRef), Some(ty)) if ty != WasmType::AnyRef => {
35
5665
            emit_concrete_vs_anyref(ops, false, structural).map(Some)
36
        }
37
22257
        _ => Ok(None),
38
    }
39
31284
}
40

            
41
/// A `Bool` against an `AnyRef`: boxing the `Bool` yields the canonical
42
/// `$t` / null an `AnyRef` holds for it, so `ref.eq` is the whole test.
43
832
fn emit_bool_anyref(ops: &mut impl IdentityOperands, bool_is_first: bool) -> Result<WasmType> {
44
832
    if bool_is_first {
45
624
        ops.stack(0)?;
46
624
        box_bool(ops);
47
624
        ops.stack(1)?;
48
624
        ops.emit().ref_cast_eq();
49
    } else {
50
208
        ops.stack(0)?;
51
208
        let anyref_local = ops.ctx().alloc_local(WasmType::AnyRef)?;
52
208
        ops.emit().local_set(anyref_local);
53
208
        ops.stack(1)?;
54
208
        box_bool(ops);
55
208
        let emit = ops.emit();
56
208
        emit.local_get(anyref_local);
57
208
        emit.ref_cast_eq();
58
    }
59
832
    ops.emit().ref_eq();
60
832
    Ok(WasmType::Bool)
61
832
}
62

            
63
832
fn box_bool(ops: &mut impl IdentityOperands) {
64
832
    let (ctx, emit) = ops.parts();
65
832
    emit_box_anyref(ctx, emit, WasmType::Bool);
66
832
    emit.ref_cast_eq();
67
832
}
68

            
69
/// A concrete-typed operand against an `AnyRef`: equal when the `AnyRef`
70
/// holds the same shape and an equal value. The concrete local is sized from
71
/// the type the operand actually lowers to, never from its classification,
72
/// which can differ (a `SETF` coercing its right-hand side).
73
8168
fn emit_concrete_vs_anyref(
74
8168
    ops: &mut impl IdentityOperands,
75
8168
    concrete_is_first: bool,
76
8168
    structural: bool,
77
8168
) -> Result<WasmType> {
78
8168
    let first = operand_local(ops, 0, concrete_is_first)?;
79
8168
    let second = operand_local(ops, 1, !concrete_is_first)?;
80
8168
    let ((concrete_local, concrete_ty), (anyref_local, _)) = if concrete_is_first {
81
2503
        (first, second)
82
    } else {
83
5665
        (second, first)
84
    };
85
8168
    let (ctx, emit) = ops.parts();
86
8168
    let locals = Locals {
87
8168
        concrete: concrete_local,
88
8168
        concrete_ty,
89
8168
        anyref: anyref_local,
90
8168
        structural,
91
8168
    };
92
8168
    match nil_repr(&concrete_ty) {
93
2104
        NilRepr::Never => emit_never_nil_vs_anyref(ctx, emit, locals),
94
6064
        NilRepr::Null => emit_nilable_vs_anyref(ctx, emit, locals),
95
        NilRepr::I32Zero => Err(Error::Compile(
96
            "internal: a Bool against AnyRef must use the boxed identity test".to_string(),
97
        )),
98
    }
99
8168
}
100

            
101
/// Emits operand `index` into a fresh local typed as it lowers (the
102
/// concrete side) or as `AnyRef`.
103
16336
fn operand_local(
104
16336
    ops: &mut impl IdentityOperands,
105
16336
    index: usize,
106
16336
    concrete: bool,
107
16336
) -> Result<(u32, WasmType)> {
108
16336
    let lowered = ops.stack(index)?;
109
16336
    let ty = if concrete { lowered } else { WasmType::AnyRef };
110
16336
    let local = ops.ctx().alloc_local(ty)?;
111
16336
    ops.emit().local_set(local);
112
16336
    Ok((local, ty))
113
16336
}
114

            
115
#[derive(Clone, Copy)]
116
struct Locals {
117
    concrete: u32,
118
    concrete_ty: WasmType,
119
    anyref: u32,
120
    structural: bool,
121
}
122

            
123
/// The concrete side is never nil: a null `AnyRef` is `nil` (checked first,
124
/// since `ratio_eq` / `commodity_eq` trap on null), otherwise shape test and
125
/// value compare.
126
8168
fn emit_never_nil_vs_anyref(
127
8168
    ctx: &mut CompileContext,
128
8168
    emit: &mut FunctionEmitter,
129
8168
    locals: Locals,
130
8168
) -> Result<WasmType> {
131
8168
    emit.local_get(locals.anyref);
132
8168
    emit.ref_is_null();
133
8168
    emit.if_block(BlockType::Result(ValType::I32));
134
8168
    emit.i32_const(0);
135
8168
    emit.else_block();
136
8168
    emit_type_test_and_compare(ctx, emit, locals)?;
137
8168
    emit.block_end()?;
138
8168
    Ok(WasmType::Bool)
139
8168
}
140

            
141
/// The concrete side may be nil: then equal exactly when the `AnyRef` is
142
/// nil too; otherwise as for a never-nil side.
143
6064
fn emit_nilable_vs_anyref(
144
6064
    ctx: &mut CompileContext,
145
6064
    emit: &mut FunctionEmitter,
146
6064
    locals: Locals,
147
6064
) -> Result<WasmType> {
148
6064
    emit.local_get(locals.concrete);
149
6064
    emit.ref_is_null();
150
6064
    emit.if_block(BlockType::Result(ValType::I32));
151
6064
    emit.local_get(locals.anyref);
152
6064
    emit.ref_is_null();
153
6064
    emit.else_block();
154
6064
    emit_never_nil_vs_anyref(ctx, emit, locals)?;
155
6064
    emit.block_end()?;
156
6064
    Ok(WasmType::Bool)
157
6064
}
158

            
159
/// Two `AnyRef`s: equal by their runtime shapes; lists deeply when
160
/// `structural`.
161
27
fn emit_anyref_vs_anyref(ops: &mut impl IdentityOperands, structural: bool) -> Result<WasmType> {
162
27
    ops.stack(0)?;
163
27
    ops.stack(1)?;
164
27
    let (ctx, emit) = ops.parts();
165
27
    emit.i32_const(i32::from(structural));
166
27
    emit.call(ctx.ids.anyref_equal);
167
27
    Ok(WasmType::Bool)
168
27
}
169

            
170
/// `ref.test`s the non-null `AnyRef` against the concrete type's
171
/// representation and compares values on a match; `nil` otherwise. An index
172
/// is boxed as `i31ref`, so it has its own test.
173
8168
fn emit_type_test_and_compare(
174
8168
    ctx: &mut CompileContext,
175
8168
    emit: &mut FunctionEmitter,
176
8168
    locals: Locals,
177
8168
) -> Result<()> {
178
8168
    let i32_result = BlockType::Result(ValType::I32);
179
8168
    if locals.concrete_ty == WasmType::I32 {
180
850
        emit.local_get(locals.anyref);
181
850
        emit.ref_test_i31();
182
850
        emit.if_block(i32_result);
183
850
        emit.local_get(locals.anyref);
184
850
        emit.ref_cast_i31();
185
850
        emit.i31_get_s();
186
850
        emit.local_get(locals.concrete);
187
850
        emit.i32_eq();
188
850
        emit.else_block();
189
850
        emit.i32_const(0);
190
850
        emit.block_end()?;
191
850
        return Ok(());
192
7318
    }
193
    let Some(ShapeCompare { shape, call }) =
194
7318
        ctx.shape_compare(locals.concrete_ty, locals.structural)?
195
    else {
196
        return Err(Error::Compile(format!(
197
            "internal: {} has no reference shape test against AnyRef",
198
            locals.concrete_ty
199
        )));
200
    };
201
7318
    let type_idx = shape;
202
7318
    emit.local_get(locals.anyref);
203
7318
    emit.ref_test(type_idx);
204
7318
    emit.if_block(i32_result);
205
7318
    emit.local_get(locals.anyref);
206
7318
    emit.ref_cast_nullable(type_idx);
207
7318
    emit.local_get(locals.concrete);
208
7318
    match call {
209
7108
        Some(fn_idx) => emit.call(fn_idx),
210
210
        None => emit.ref_eq(),
211
    }
212
7318
    emit.else_block();
213
7318
    emit.i32_const(0);
214
7318
    emit.block_end()?;
215
7318
    Ok(())
216
8168
}