1
//! Lowering of the struct natives. The operand's static type decides: a
2
//! `StructRef` of the layout needs only a null check, an `AnyRef` is tested
3
//! against the layout at run time, anything else is a compile error.
4

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

            
7
use super::{COPY, NEW, P, REF, SET, expect_arity, layout_of, slot_of, stored_type};
8
use crate::ast::{Expr, PairElement, StructId, WasmType};
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::compile_for_stack;
12
use crate::compiler::native::{emit_pair_car_downcast, push_anyref_arm};
13
use crate::compiler::special::control::error_form::push_string_literal;
14
use crate::error::{Error, Result, with_article};
15
use crate::runtime::{StructLayout, SymbolTable};
16

            
17
/// What an operand's static type says about a layout.
18
#[derive(Clone, Copy, PartialEq)]
19
enum Operand {
20
    Exact,
21
    Dynamic,
22
    Other,
23
}
24

            
25
impl Operand {
26
65935
    fn of(ty: WasmType, id: StructId) -> Self {
27
65935
        match ty {
28
58414
            WasmType::StructRef(found) if found == id => Self::Exact,
29
1263
            WasmType::AnyRef => Self::Dynamic,
30
7092
            _ => Self::Other,
31
        }
32
65935
    }
33
}
34

            
35
/// An operand compiled and parked in a local, with the layout it is read as.
36
struct Target {
37
    id: StructId,
38
    local: u32,
39
    kind: Operand,
40
    layout_global: u32,
41
    layout: StructLayout,
42
}
43

            
44
/// Compiles the operand of the function `who` and parks it; an operand that
45
/// cannot be an instance of the layout is a compile error naming `who`.
46
61976
fn target(
47
61976
    ctx: &mut CompileContext,
48
61976
    emit: &mut FunctionEmitter,
49
61976
    symbols: &mut SymbolTable,
50
61976
    who: &str,
51
61976
    (id, layout): (StructId, StructLayout),
52
61976
    operand: &Expr,
53
61976
) -> Result<Target> {
54
61976
    let ty = compile_for_stack(ctx, emit, symbols, operand)?;
55
61976
    let local = ctx.alloc_local(ty)?;
56
61976
    emit.local_set(local);
57
61976
    let kind = Operand::of(ty, id);
58
61976
    if kind == Operand::Other {
59
4801
        emit.reject_if_live(Error::Compile(format!(
60
4801
            "{who}: expected a {}, got {}",
61
4801
            layout.name,
62
4801
            with_article(ty)
63
4801
        )))?;
64
57175
    }
65
    Ok(Target {
66
57187
        id,
67
57187
        local,
68
57187
        kind,
69
57187
        layout_global: ctx.struct_layout_global(id, &layout)?,
70
57187
        layout,
71
    })
72
61976
}
73

            
74
57175
fn throw_type_error(
75
57175
    ctx: &mut CompileContext,
76
57175
    emit: &mut FunctionEmitter,
77
57175
    message: &str,
78
57175
) -> Result<()> {
79
57175
    push_string_literal(ctx, emit, "TYPE-ERROR")?;
80
57175
    push_string_literal(ctx, emit, message)?;
81
57175
    emit.ref_null_any();
82
57175
    emit.struct_new(ctx.condition_type_idx());
83
57175
    emit.throw(ctx.nomi_error_tag()?);
84
57175
    Ok(())
85
57175
}
86

            
87
/// Leaves an i32 on the stack: whether the parked operand is an instance of
88
/// the layout.
89
61134
fn instance_test(ctx: &CompileContext, emit: &mut FunctionEmitter, target: &Target) -> Result<()> {
90
61134
    emit.local_get(target.local);
91
61134
    match target.kind {
92
        Operand::Exact => {
93
57580
            emit.ref_is_null();
94
57580
            emit.i32_eqz();
95
        }
96
        Operand::Dynamic => {
97
1263
            emit.ref_test_non_null(HeapType::Concrete(ctx.ids.ty_struct));
98
1263
            emit.if_block(BlockType::Result(ValType::I32));
99
1263
            emit.local_get(target.local);
100
1263
            emit.ref_cast(ctx.ids.ty_struct);
101
1263
            emit.struct_get(ctx.ids.ty_struct, 1);
102
1263
            emit.global_get(target.layout_global);
103
1263
            emit.ref_eq();
104
1263
            emit.else_block();
105
1263
            emit.i32_const(0);
106
1263
            emit.block_end()?;
107
        }
108
        Operand::Other => {
109
2291
            emit.drop_value();
110
2291
            emit.i32_const(0);
111
        }
112
    }
113
61134
    Ok(())
114
61134
}
115

            
116
/// Throws a `TYPE-ERROR` unless the parked operand is an instance.
117
57175
fn require_instance(
118
57175
    ctx: &mut CompileContext,
119
57175
    emit: &mut FunctionEmitter,
120
57175
    target: &Target,
121
57175
    accessor: &str,
122
57175
) -> Result<()> {
123
57175
    instance_test(ctx, emit, target)?;
124
57175
    emit.i32_eqz();
125
57175
    emit.if_block(BlockType::Empty);
126
57175
    let message = format!("{accessor}: expected a {}", target.layout.name);
127
57175
    throw_type_error(ctx, emit, &message)?;
128
57175
    emit.block_end()
129
57175
}
130

            
131
/// Pushes the parked instance's `$slots` of values.
132
56547
fn push_values(ctx: &CompileContext, emit: &mut FunctionEmitter, target: &Target) {
133
56547
    emit.local_get(target.local);
134
56547
    emit.ref_cast(ctx.ids.ty_struct);
135
56547
    emit.struct_get(ctx.ids.ty_struct, 2);
136
56547
}
137

            
138
98536
pub(super) fn new(
139
98536
    ctx: &mut CompileContext,
140
98536
    emit: &mut FunctionEmitter,
141
98536
    symbols: &mut SymbolTable,
142
98536
    args: &[Expr],
143
98536
) -> Result<WasmType> {
144
98536
    let first = args.first().ok_or_else(|| Error::Arity {
145
1
        name: NEW.to_string(),
146
1
        expected: 1,
147
1
        actual: 0,
148
1
    })?;
149
98535
    let (id, layout) = layout_of(symbols, NEW, first)?;
150
98533
    expect_arity(NEW, args, 1 + layout.fields.len())?;
151
98532
    let global = ctx.struct_layout_global(id, &layout)?;
152
98532
    emit.global_get(global);
153
98532
    let size = u16::try_from(layout.fields.len())
154
        .map_err(|_| Error::Compile(format!("{NEW}: too many fields")))?;
155
98532
    for (idx, value) in (0..size).zip(&args[1..]) {
156
101654
        let arm = push_anyref_arm(ctx, emit, symbols, value)?;
157
101446
        if emit.is_reachable() {
158
101446
            symbols.note_field_store(id, idx, arm);
159
        }
160
    }
161
98324
    emit.array_new_fixed(ctx.ids.ty_slots, u32::from(size));
162
98324
    emit_with_next_serial(ctx, emit, ctx.ids.struct_new)?;
163
98324
    Ok(WasmType::StructRef(id))
164
98536
}
165

            
166
3960
pub(super) fn predicate(
167
3960
    ctx: &mut CompileContext,
168
3960
    emit: &mut FunctionEmitter,
169
3960
    symbols: &mut SymbolTable,
170
3960
    args: &[Expr],
171
3960
) -> Result<WasmType> {
172
3960
    expect_arity(P, args, 2)?;
173
3959
    let (id, layout) = layout_of(symbols, P, &args[1])?;
174
3959
    let ty = compile_for_stack(ctx, emit, symbols, &args[0])?;
175
3959
    let local = ctx.alloc_local(ty)?;
176
3959
    emit.local_set(local);
177
    let target = Target {
178
3959
        id,
179
3959
        local,
180
3959
        kind: Operand::of(ty, id),
181
3959
        layout_global: ctx.struct_layout_global(id, &layout)?,
182
3959
        layout,
183
    };
184
3959
    instance_test(ctx, emit, &target)?;
185
3959
    Ok(WasmType::Bool)
186
3960
}
187

            
188
39847
pub(super) fn read(
189
39847
    ctx: &mut CompileContext,
190
39847
    emit: &mut FunctionEmitter,
191
39847
    symbols: &mut SymbolTable,
192
39847
    args: &[Expr],
193
39847
) -> Result<WasmType> {
194
39847
    expect_arity(REF, args, 3)?;
195
39846
    let (id, layout) = layout_of(symbols, REF, &args[1])?;
196
39846
    let slot = slot_of(REF, &args[2], &layout)?;
197
39845
    let who = accessor(&layout, slot);
198
39845
    let target = target(ctx, emit, symbols, &who, (id, layout), &args[0])?;
199
35891
    let ty = symbols.field_type(target.id, slot);
200
35891
    if !emit.is_reachable() {
201
4
        return Ok(ty);
202
35887
    }
203
35887
    require_instance(ctx, emit, &target, &who)?;
204
35887
    push_values(ctx, emit, &target);
205
35887
    emit.i32_const(i32::from(slot));
206
35887
    emit.array_get(ctx.ids.ty_slots);
207
35887
    unbox(ctx, emit, ty)?;
208
35887
    Ok(ty)
209
39847
}
210

            
211
21499
pub(super) fn write(
212
21499
    ctx: &mut CompileContext,
213
21499
    emit: &mut FunctionEmitter,
214
21499
    symbols: &mut SymbolTable,
215
21499
    args: &[Expr],
216
21499
) -> Result<WasmType> {
217
21499
    expect_arity(SET, args, 4)?;
218
21498
    let (id, layout) = layout_of(symbols, SET, &args[1])?;
219
21498
    let slot = slot_of(SET, &args[2], &layout)?;
220
21498
    let setter = format!("(SETF {})", accessor(&layout, slot));
221
21498
    let target = target(ctx, emit, symbols, &setter, (id, layout), &args[0])?;
222
20664
    if !emit.is_reachable() {
223
4
        return Ok(WasmType::AnyRef);
224
20660
    }
225
20660
    let arm = push_anyref_arm(ctx, emit, symbols, &args[3])?;
226
20660
    let result = stored_type(arm);
227
20660
    if emit.is_reachable() {
228
20658
        symbols.note_field_store(target.id, slot, arm);
229
2
    }
230
20660
    let value = ctx.alloc_local(WasmType::AnyRef)?;
231
20660
    emit.local_set(value);
232
20660
    require_instance(ctx, emit, &target, &setter)?;
233
20660
    push_values(ctx, emit, &target);
234
20660
    emit.i32_const(i32::from(slot));
235
20660
    emit.local_get(value);
236
20660
    emit.array_set(ctx.ids.ty_slots);
237
20660
    emit.local_get(value);
238
20660
    unbox(ctx, emit, result)?;
239
20660
    Ok(result)
240
21499
}
241

            
242
634
pub(super) fn copy(
243
634
    ctx: &mut CompileContext,
244
634
    emit: &mut FunctionEmitter,
245
634
    symbols: &mut SymbolTable,
246
634
    args: &[Expr],
247
634
) -> Result<WasmType> {
248
634
    expect_arity(COPY, args, 2)?;
249
633
    let found = layout_of(symbols, COPY, &args[1])?;
250
633
    let copier = format!("COPY-{}", found.1.name);
251
633
    let target = target(ctx, emit, symbols, &copier, found, &args[0])?;
252
632
    if !emit.is_reachable() {
253
4
        return Ok(WasmType::StructRef(target.id));
254
628
    }
255
628
    require_instance(ctx, emit, &target, &copier)?;
256
628
    emit.local_get(target.local);
257
628
    emit.ref_cast_nullable(ctx.ids.ty_struct);
258
628
    emit_with_next_serial(ctx, emit, ctx.ids.struct_copy)?;
259
628
    Ok(WasmType::StructRef(target.id))
260
634
}
261

            
262
/// Calls the allocating helper `func` with the next serial as its last
263
/// argument and advances the counter.
264
98952
fn emit_with_next_serial(
265
98952
    ctx: &mut CompileContext,
266
98952
    emit: &mut FunctionEmitter,
267
98952
    func: u32,
268
98952
) -> Result<()> {
269
98952
    let serial = ctx.struct_serial_global()?;
270
98952
    emit.global_get(serial);
271
98952
    emit.call(func);
272
98952
    emit.global_get(serial);
273
98952
    emit.i32_const(1);
274
98952
    emit.i32_add();
275
98952
    emit.global_set(serial);
276
98952
    Ok(())
277
98952
}
278

            
279
61343
fn accessor(layout: &StructLayout, slot: u16) -> String {
280
61343
    let field = layout
281
61343
        .fields
282
61343
        .get(usize::from(slot))
283
61343
        .map_or("", String::as_str);
284
61343
    format!("{}-{field}", layout.name)
285
61343
}
286

            
287
/// Casts the `anyref` a slot read to the type its home settled on.
288
56547
fn unbox(ctx: &CompileContext, emit: &mut FunctionEmitter, ty: WasmType) -> Result<()> {
289
56547
    match (ty, PairElement::from_wasm_type(ty)) {
290
2
        (WasmType::PairRef(_), _) => emit.ref_cast_nullable(ctx.ids.ty_pair),
291
56545
        (_, Some(elem)) => emit_pair_car_downcast(ctx, emit, elem)?,
292
        (_, None) => {}
293
    }
294
56547
    Ok(())
295
56547
}