1
//! The wasm side of `DEFSTRUCT` instances: one `$struct` shape for every
2
//! layout, so a layout needs no wasm type of its own. An instance is
3
//! `(serial, layout, values)`; the layout is an immutable `$slots` array
4
//! `[i31 StructId, $symbol NAME, $symbol :FIELD ...]` shared by its instances.
5

            
6
use std::collections::HashMap;
7

            
8
use wasm_encoder::{
9
    ArrayType, CompositeInnerType, CompositeType, ConstExpr, ExportKind, FieldType, Function,
10
    GlobalType, HeapType, Instruction, RefType, StorageType, SubType, ValType,
11
};
12

            
13
use super::CompileContext;
14
use super::registry::bump;
15
use crate::ast::StructId;
16
use crate::compiler::emit::FunctionEmitter;
17
use crate::error::{Error, Result};
18
use crate::runtime::StructLayout;
19

            
20
/// The wasm global of each layout a compilation has used. A rolled-back trial
21
/// can reuse an id for another layout, so the layout itself is kept to compare.
22
pub(super) type LayoutGlobals = HashMap<StructId, (StructLayout, u32)>;
23

            
24
9561818
fn non_null(type_idx: u32) -> ValType {
25
9561818
    ValType::Ref(RefType {
26
9561818
        nullable: false,
27
9561818
        heap_type: HeapType::Concrete(type_idx),
28
9561818
    })
29
9561818
}
30

            
31
/// The export name of the global holding the session instance `serial`; the
32
/// host reads it back to see what the unit did to the instance.
33
#[must_use]
34
1941497
pub fn instance_export_name(serial: u32) -> String {
35
1941497
    format!("inst{serial}")
36
1941497
}
37

            
38
/// The export name of the flag the instance prologue sets once every instance
39
/// is allocated and filled; the host settles the heap only when it reads 1.
40
pub const PROLOGUE_DONE_EXPORT: &str = "prologue_done";
41

            
42
456861
fn len_i32(len: usize) -> Result<u32> {
43
456861
    u32::try_from(len).map_err(|_| Error::Compile("struct layout exceeds u32".to_string()))
44
456861
}
45

            
46
impl CompileContext {
47
2352713
    pub(super) fn register_struct_types(&mut self) -> Result<()> {
48
2352713
        let anyref = self.anyref();
49
2352713
        let slots = bump(&mut self.type_count, "type")?;
50
2352713
        self.types.ty().subtype(&SubType {
51
2352713
            is_final: true,
52
2352713
            supertype_idxs: Vec::new(),
53
2352713
            composite_type: CompositeType {
54
2352713
                inner: CompositeInnerType::Array(ArrayType(FieldType {
55
2352713
                    element_type: StorageType::Val(anyref),
56
2352713
                    mutable: true,
57
2352713
                })),
58
2352713
                shared: false,
59
2352713
                describes: None,
60
2352713
                descriptor: None,
61
2352713
            },
62
2352713
        });
63
2352713
        self.ids.ty_slots = slots;
64
2352713
        self.ids.ty_struct =
65
2352713
            self.register_struct_type(&[ValType::I32, non_null(slots), non_null(slots)])?;
66
2352713
        Ok(())
67
2352713
    }
68

            
69
    /// `(ref null $struct)`.
70
4710439
    pub fn struct_instance_ref(&self) -> ValType {
71
4710439
        ValType::Ref(RefType {
72
4710439
            nullable: true,
73
4710439
            heap_type: HeapType::Concrete(self.ids.ty_struct),
74
4710439
        })
75
4710439
    }
76

            
77
2352712
    pub(super) fn declare_struct_helpers(&mut self) -> Result<()> {
78
2352712
        let slots = non_null(self.ids.ty_slots);
79
2352712
        let instance = non_null(self.ids.ty_struct);
80
2352712
        self.register_function("struct_new", &[slots, slots, ValType::I32], &[instance])?;
81
        // The host resolves the `$struct` heap type from this result.
82
2352712
        self.export_func("struct_new")?;
83
2352712
        let nullable = self.struct_instance_ref();
84
2352712
        self.register_function("struct_copy", &[nullable, ValType::I32], &[instance])
85
2352712
            .map(drop)
86
2352712
    }
87

            
88
2352712
    pub(super) fn build_struct_helpers(&mut self) {
89
2352712
        self.build_struct_new_body();
90
2352712
        self.build_struct_copy_body();
91
2352712
    }
92

            
93
    /// `struct_new(layout, values, serial)`; the serial is the last argument so
94
    /// the caller reads the counter after evaluating the field values.
95
2352712
    fn build_struct_new_body(&mut self) {
96
2352712
        let mut f = Function::new([]);
97
2352712
        for local in [2, 0, 1] {
98
7058136
            f.instruction(&Instruction::LocalGet(local));
99
        }
100
2352712
        f.instruction(&Instruction::StructNew(self.ids.ty_struct));
101
2352712
        f.instruction(&Instruction::End);
102
2352712
        self.pending_helpers.push(f);
103
2352712
    }
104

            
105
    /// `struct_copy(instance, serial)`: a new instance of the same layout over a copy
106
    /// of the values.
107
2352712
    fn build_struct_copy_body(&mut self) {
108
        const SOURCE: u32 = 0;
109
        const SERIAL: u32 = 1;
110
        const COPY: u32 = 2;
111
2352712
        let (ty_struct, ty_slots) = (self.ids.ty_struct, self.ids.ty_slots);
112
9410848
        let field = |f: &mut Function, field_index: u32| {
113
9410848
            f.instruction(&Instruction::LocalGet(SOURCE));
114
9410848
            f.instruction(&Instruction::StructGet {
115
9410848
                struct_type_index: ty_struct,
116
9410848
                field_index,
117
9410848
            });
118
9410848
        };
119
2352712
        let copy_local = ValType::Ref(RefType {
120
2352712
            nullable: true,
121
2352712
            heap_type: HeapType::Concrete(ty_slots),
122
2352712
        });
123
2352712
        let mut f = Function::new([(1, copy_local)]);
124
2352712
        field(&mut f, 1);
125
2352712
        f.instruction(&Instruction::RefNull(HeapType::ANY));
126
2352712
        field(&mut f, 2);
127
2352712
        f.instruction(&Instruction::ArrayLen);
128
2352712
        f.instruction(&Instruction::ArrayNew(ty_slots));
129
2352712
        f.instruction(&Instruction::LocalSet(COPY));
130
2352712
        f.instruction(&Instruction::LocalGet(COPY));
131
2352712
        f.instruction(&Instruction::I32Const(0));
132
2352712
        field(&mut f, 2);
133
2352712
        f.instruction(&Instruction::I32Const(0));
134
2352712
        field(&mut f, 2);
135
2352712
        f.instruction(&Instruction::ArrayLen);
136
2352712
        f.instruction(&Instruction::ArrayCopy {
137
2352712
            array_type_index_dst: ty_slots,
138
2352712
            array_type_index_src: ty_slots,
139
2352712
        });
140
2352712
        f.instruction(&Instruction::LocalGet(COPY));
141
2352712
        f.instruction(&Instruction::RefAsNonNull);
142
2352712
        f.instruction(&Instruction::LocalGet(SERIAL));
143
2352712
        f.instruction(&Instruction::Call(self.ids.struct_new));
144
2352712
        f.instruction(&Instruction::End);
145
2352712
        self.pending_helpers.push(f);
146
2352712
    }
147

            
148
    /// The mutable global counting the instances this compilation allocates,
149
    /// allocated on first use so a program with no structure keeps its
150
    /// global indices.
151
98952
    pub(crate) fn struct_serial_global(&mut self) -> Result<u32> {
152
98952
        if let Some(idx) = self.struct_serial {
153
15621
            return Ok(idx);
154
83331
        }
155
83331
        let idx = self.push_global(
156
83331
            GlobalType {
157
83331
                val_type: ValType::I32,
158
83331
                mutable: true,
159
83331
                shared: false,
160
83331
            },
161
83331
            &ConstExpr::i32_const(
162
83331
                i32::try_from(self.struct_serial_base)
163
                    .map_err(|_| Error::Resource("too many struct instances".to_string()))?,
164
            ),
165
        )?;
166
83331
        self.struct_serial = Some(idx);
167
83331
        Ok(idx)
168
98952
    }
169

            
170
    /// Starts the instance serial counter past the instances the session holds.
171
2341606
    pub(crate) fn set_struct_serial_base(&mut self, base: u32) {
172
2341606
        self.struct_serial_base = base;
173
2341606
    }
174

            
175
    /// The wasm global of the session instance `serial`.
176
2115386
    pub(crate) fn instance_global(&self, serial: u32) -> Result<u32> {
177
2115386
        self.instance_globals
178
2115386
            .get(&serial)
179
2115386
            .copied()
180
1
            .ok_or_else(|| Error::Compile(format!("internal: instance {serial} has no global")))
181
2115386
    }
182

            
183
    /// Declares the exported global of the session instance `serial`, null until
184
    /// the unit prologue allocates it: a constant initializer would make the
185
    /// engine compile every allocation into one start function.
186
1941494
    pub(crate) fn alloc_instance_global(&mut self, serial: u32) -> Result<u32> {
187
1941494
        let ty = self.struct_instance_ref();
188
1941494
        let idx = self.push_global(
189
1941494
            GlobalType {
190
1941494
                val_type: ty,
191
1941494
                mutable: true,
192
1941494
                shared: false,
193
1941494
            },
194
1941494
            &ConstExpr::ref_null(HeapType::Concrete(self.ids.ty_struct)),
195
1941494
        )?;
196
1941494
        self.exports
197
1941494
            .export(&instance_export_name(serial), ExportKind::Global, idx);
198
1941494
        self.instance_globals.insert(serial, idx);
199
1941494
        Ok(idx)
200
1941494
    }
201

            
202
    /// Declares the exported flag the prologue sets when it has finished.
203
2341606
    pub(crate) fn alloc_prologue_flag(&mut self) -> Result<u32> {
204
2341606
        let idx = self.push_global(
205
2341606
            GlobalType {
206
2341606
                val_type: ValType::I32,
207
2341606
                mutable: true,
208
2341606
                shared: false,
209
2341606
            },
210
2341606
            &ConstExpr::i32_const(0),
211
2341606
        )?;
212
2341606
        self.exports
213
2341606
            .export(PROLOGUE_DONE_EXPORT, ExportKind::Global, idx);
214
2341606
        Ok(idx)
215
2341606
    }
216

            
217
2341398
    pub(crate) fn set_instances_init(&mut self, func_idx: u32) {
218
2341398
        self.instances_init = Some(func_idx);
219
2341398
    }
220

            
221
    /// Emits the call that runs the instance prologue, a no-op once it ran.
222
2355552
    pub(crate) fn call_instances_init(&self, emit: &mut FunctionEmitter) -> Result<()> {
223
2355552
        let func_idx = self
224
2355552
            .instances_init
225
            .ok_or_else(|| Error::Compile("internal: the instance prologue is not built".into()))?;
226
2355552
        emit.call(func_idx);
227
2355552
        Ok(())
228
2355552
    }
229

            
230
    /// The global holding `layout`'s `$slots` array, allocated on first use.
231
2101178
    pub(crate) fn struct_layout_global(
232
2101178
        &mut self,
233
2101178
        id: StructId,
234
2101178
        layout: &StructLayout,
235
2101178
    ) -> Result<u32> {
236
2101178
        if let Some((known, idx)) = self.struct_layouts.get(&id)
237
1950211
            && known == layout
238
        {
239
1950210
            return Ok(*idx);
240
150968
        }
241
150968
        let init = self.layout_init(id, layout)?;
242
150968
        let idx = self.push_global(
243
150968
            GlobalType {
244
150968
                val_type: non_null(self.ids.ty_slots),
245
150968
                mutable: false,
246
150968
                shared: false,
247
150968
            },
248
150968
            &init,
249
150968
        )?;
250
150968
        self.struct_layouts.insert(id, (layout.clone(), idx));
251
150968
        Ok(idx)
252
2101178
    }
253

            
254
150968
    fn layout_init(&self, id: StructId, layout: &StructLayout) -> Result<ConstExpr> {
255
150968
        let mut code = vec![Instruction::I32Const(
256
150968
            i32::try_from(id.0).map_err(|_| Error::Compile("struct id exceeds i32".to_string()))?,
257
        )];
258
150968
        code.push(Instruction::RefI31);
259
150968
        self.push_name(&mut code, &layout.name)?;
260
150968
        for field in &layout.fields {
261
154925
            self.push_name(&mut code, &format!(":{field}"))?;
262
        }
263
150968
        code.push(Instruction::ArrayNewFixed {
264
150968
            array_type_index: self.ids.ty_slots,
265
150968
            array_size: len_i32(layout.fields.len() + 2)?,
266
        });
267
150968
        Ok(ConstExpr::extended(code))
268
150968
    }
269

            
270
305893
    fn push_name(&self, code: &mut Vec<Instruction<'static>>, name: &str) -> Result<()> {
271
305893
        code.extend(
272
305893
            name.bytes()
273
675467
                .map(|byte| Instruction::I32Const(i32::from(byte))),
274
        );
275
305893
        code.push(Instruction::ArrayNewFixed {
276
305893
            array_type_index: self.ids.ty_i8_array,
277
305893
            array_size: len_i32(name.len())?,
278
        });
279
305893
        code.push(Instruction::StructNew(self.ids.ty_symbol));
280
305893
        Ok(())
281
305893
    }
282
}