1
//! Structural `EQUAL` helpers. `anyref_equal` compares two boxed values by
2
//! their runtime shape; `pair_equal` walks two lists, comparing the cars with
3
//! it. [`CompileContext::shape_compare`] is the one shape-to-comparison table
4
//! the generated helpers and the identity emitter share.
5

            
6
use super::CompileContext;
7
use crate::ast::WasmType;
8
use crate::error::Result;
9
use wasm_encoder::{AbstractHeapType, BlockType, Function, HeapType, Instruction, ValType};
10

            
11
/// How two values of one reference shape compare once both have it.
12
pub(crate) struct ShapeCompare {
13
    pub shape: u32,
14
    /// The helper comparing the values; `None` when identity is the test.
15
    pub call: Option<u32>,
16
}
17

            
18
const I32_RESULT: BlockType = BlockType::Result(ValType::I32);
19
const I31: HeapType = HeapType::Abstract {
20
    shared: false,
21
    ty: AbstractHeapType::I31,
22
};
23
const EQ: HeapType = HeapType::Abstract {
24
    shared: false,
25
    ty: AbstractHeapType::Eq,
26
};
27

            
28
impl CompileContext {
29
    /// `None` for a type with no reference shape (`I32` rides `i31`, `Bool`
30
    /// is `t` / `nil`).
31
9418172
    pub(crate) fn shape_compare(
32
9418172
        &self,
33
9418172
        ty: WasmType,
34
9418172
        structural: bool,
35
9418172
    ) -> Result<Option<ShapeCompare>> {
36
9418172
        let (shape, call) = match ty {
37
2353966
            WasmType::Ratio => (self.ids.ty_ratio, Some(self.ids.ratio_eq)),
38
2352712
            WasmType::Commodity => (self.ids.ty_commodity, Some(self.ids.commodity_eq)),
39
2353753
            WasmType::StringRef => (self.ids.ty_i8_array, Some(self.ids.string_eq)),
40
2357520
            WasmType::SymbolRef => (self.ids.ty_symbol, Some(self.ids.symbol_eq)),
41
216
            WasmType::PairRef(_) => (self.ids.ty_pair, structural.then_some(self.ids.pair_equal)),
42
            WasmType::EntityRef(kind) => (self.ids.entity_type(kind), None),
43
2
            WasmType::StructRef(_) => (self.ids.ty_struct, None),
44
1
            WasmType::Closure(sig) => (self.closure_sig(sig)?.closure_type_idx, None),
45
2
            WasmType::I32 | WasmType::Bool | WasmType::AnyRef => return Ok(None),
46
        };
47
9418169
        Ok(Some(ShapeCompare { shape, call }))
48
9418172
    }
49

            
50
2352712
    pub(super) fn declare_pair_equal(&mut self) -> Result<()> {
51
2352712
        let (pair, anyref) = (self.pair_ref(), self.anyref());
52
2352712
        self.register_function("pair_equal", &[pair, pair], &[ValType::I32])?;
53
2352712
        self.register_function(
54
2352712
            "anyref_equal",
55
2352712
            &[anyref, anyref, ValType::I32],
56
2352712
            &[ValType::I32],
57
2352712
        )
58
2352712
        .map(drop)
59
2352712
    }
60

            
61
2352712
    pub(super) fn build_pair_equal(&mut self) -> Result<()> {
62
2352712
        self.build_pair_equal_body();
63
2352712
        self.build_anyref_equal_body()
64
2352712
    }
65

            
66
    /// Walks both lists: equal when they end together and every car pair is
67
    /// `anyref_equal` (deep).
68
2352712
    fn build_pair_equal_body(&mut self) {
69
        const A: u32 = 0;
70
        const B: u32 = 1;
71
2352712
        let pair_idx = self.ids.ty_pair;
72
9410848
        let field = |list: u32, field_index: u32, f: &mut Function| {
73
9410848
            f.instruction(&Instruction::LocalGet(list));
74
9410848
            f.instruction(&Instruction::StructGet {
75
9410848
                struct_type_index: pair_idx,
76
9410848
                field_index,
77
9410848
            });
78
9410848
        };
79
2352712
        let mut f = Function::new([]);
80
2352712
        f.instruction(&Instruction::Loop(BlockType::Empty));
81
2352712
        for (this, other) in [(A, B), (B, A)] {
82
4705424
            f.instruction(&Instruction::LocalGet(this));
83
4705424
            f.instruction(&Instruction::RefIsNull);
84
4705424
            f.instruction(&Instruction::If(BlockType::Empty));
85
4705424
            f.instruction(&Instruction::LocalGet(other));
86
4705424
            f.instruction(&Instruction::RefIsNull);
87
4705424
            f.instruction(&Instruction::Return);
88
4705424
            f.instruction(&Instruction::End);
89
        }
90
2352712
        field(A, 0, &mut f);
91
2352712
        field(B, 0, &mut f);
92
2352712
        f.instruction(&Instruction::I32Const(1));
93
2352712
        f.instruction(&Instruction::Call(self.ids.anyref_equal));
94
2352712
        f.instruction(&Instruction::I32Eqz);
95
2352712
        f.instruction(&Instruction::If(BlockType::Empty));
96
2352712
        f.instruction(&Instruction::I32Const(0));
97
2352712
        f.instruction(&Instruction::Return);
98
2352712
        f.instruction(&Instruction::End);
99
2352712
        for list in [A, B] {
100
4705424
            field(list, 1, &mut f);
101
4705424
            f.instruction(&Instruction::LocalSet(list));
102
        }
103
2352712
        f.instruction(&Instruction::Br(0));
104
2352712
        f.instruction(&Instruction::End);
105
2352712
        f.instruction(&Instruction::I32Const(0));
106
2352712
        f.instruction(&Instruction::End);
107
2352712
        self.pending_helpers.push(f);
108
2352712
    }
109

            
110
    /// `(a, b, deep)`: `nil` equals only `nil`; an index compares as `i31`; a
111
    /// shape with a value comparison compares by it; lists compare
112
    /// structurally when `deep`, else by identity; anything else by identity.
113
2352712
    fn build_anyref_equal_body(&mut self) -> Result<()> {
114
        const A: u32 = 0;
115
        const B: u32 = 1;
116
        const DEEP: u32 = 2;
117
2352712
        let mut f = Function::new([]);
118
2352712
        f.instruction(&Instruction::LocalGet(A));
119
2352712
        f.instruction(&Instruction::RefIsNull);
120
2352712
        f.instruction(&Instruction::If(I32_RESULT));
121
2352712
        f.instruction(&Instruction::LocalGet(B));
122
2352712
        f.instruction(&Instruction::RefIsNull);
123
2352712
        f.instruction(&Instruction::Else);
124
2352712
        let mut open = 1;
125
2352712
        open += self.emit_shape_arm(&mut f, I31, |f| {
126
2352712
            for value in [A, B] {
127
4705424
                f.instruction(&Instruction::LocalGet(value));
128
4705424
                f.instruction(&Instruction::RefCastNonNull(I31));
129
4705424
                f.instruction(&Instruction::I31GetS);
130
            }
131
2352712
            f.instruction(&Instruction::I32Eq);
132
2352712
        });
133
2352712
        for ty in [
134
2352712
            WasmType::Ratio,
135
2352712
            WasmType::Commodity,
136
2352712
            WasmType::StringRef,
137
2352712
            WasmType::SymbolRef,
138
2352712
        ] {
139
            if let Some(ShapeCompare {
140
                shape,
141
                call: Some(call),
142
9410848
            }) = self.shape_compare(ty, true)?
143
            {
144
9410848
                open += self.emit_shape_arm(&mut f, HeapType::Concrete(shape), |f| {
145
9410848
                    cast_both(f, shape);
146
9410848
                    f.instruction(&Instruction::Call(call));
147
9410848
                });
148
            }
149
        }
150
2352712
        let pair_idx = self.ids.ty_pair;
151
2352712
        let pair_equal = self.ids.pair_equal;
152
2352712
        open += self.emit_shape_arm(&mut f, HeapType::Concrete(pair_idx), |f| {
153
2352712
            f.instruction(&Instruction::LocalGet(DEEP));
154
2352712
            f.instruction(&Instruction::If(I32_RESULT));
155
2352712
            cast_both(f, pair_idx);
156
2352712
            f.instruction(&Instruction::Call(pair_equal));
157
2352712
            f.instruction(&Instruction::Else);
158
2352712
            cast_both(f, pair_idx);
159
2352712
            f.instruction(&Instruction::RefEq);
160
2352712
            f.instruction(&Instruction::End);
161
2352712
        });
162
2352712
        f.instruction(&Instruction::LocalGet(A));
163
2352712
        f.instruction(&Instruction::RefCastNonNull(EQ));
164
2352712
        f.instruction(&Instruction::LocalGet(B));
165
2352712
        f.instruction(&Instruction::RefCastNullable(EQ));
166
2352712
        f.instruction(&Instruction::RefEq);
167
2352712
        for _ in 0..open {
168
16468984
            f.instruction(&Instruction::End);
169
        }
170
2352712
        f.instruction(&Instruction::End);
171
2352712
        self.pending_helpers.push(f);
172
2352712
        Ok(())
173
2352712
    }
174

            
175
    /// Opens one `if` arm of the cascade: when both values have `shape`,
176
    /// `compare` runs on them (it casts them itself).
177
    /// Returns the number of arms left open for the caller to close.
178
14116272
    fn emit_shape_arm(
179
14116272
        &self,
180
14116272
        f: &mut Function,
181
14116272
        shape: HeapType,
182
14116272
        compare: impl FnOnce(&mut Function),
183
14116272
    ) -> usize {
184
14116272
        for value in [0, 1] {
185
28232544
            f.instruction(&Instruction::LocalGet(value));
186
28232544
            f.instruction(&Instruction::RefTestNonNull(shape));
187
28232544
            f.instruction(&Instruction::If(I32_RESULT));
188
        }
189
14116272
        compare(f);
190
14116272
        f.instruction(&Instruction::Else);
191
14116272
        f.instruction(&Instruction::I32Const(0));
192
14116272
        f.instruction(&Instruction::End);
193
14116272
        f.instruction(&Instruction::Else);
194
14116272
        1
195
14116272
    }
196
}
197

            
198
14116272
fn cast_both(f: &mut Function, shape_idx: u32) {
199
14116272
    for value in [0, 1] {
200
28232544
        f.instruction(&Instruction::LocalGet(value));
201
28232544
        f.instruction(&Instruction::RefCastNonNull(HeapType::Concrete(shape_idx)));
202
    }
203
14116272
}