nomiscript/compiler/context/
structs.rs1use std::collections::HashMap;
7
8use wasm_encoder::{
9 ArrayType, CompositeInnerType, CompositeType, ConstExpr, ExportKind, FieldType, Function,
10 GlobalType, HeapType, Instruction, RefType, StorageType, SubType, ValType,
11};
12
13use super::CompileContext;
14use super::registry::bump;
15use crate::ast::StructId;
16use crate::compiler::emit::FunctionEmitter;
17use crate::error::{Error, Result};
18use crate::runtime::StructLayout;
19
20pub(super) type LayoutGlobals = HashMap<StructId, (StructLayout, u32)>;
23
24fn non_null(type_idx: u32) -> ValType {
25 ValType::Ref(RefType {
26 nullable: false,
27 heap_type: HeapType::Concrete(type_idx),
28 })
29}
30
31#[must_use]
34pub fn instance_export_name(serial: u32) -> String {
35 format!("inst{serial}")
36}
37
38pub const PROLOGUE_DONE_EXPORT: &str = "prologue_done";
41
42fn len_i32(len: usize) -> Result<u32> {
43 u32::try_from(len).map_err(|_| Error::Compile("struct layout exceeds u32".to_string()))
44}
45
46impl CompileContext {
47 pub(super) fn register_struct_types(&mut self) -> Result<()> {
48 let anyref = self.anyref();
49 let slots = bump(&mut self.type_count, "type")?;
50 self.types.ty().subtype(&SubType {
51 is_final: true,
52 supertype_idxs: Vec::new(),
53 composite_type: CompositeType {
54 inner: CompositeInnerType::Array(ArrayType(FieldType {
55 element_type: StorageType::Val(anyref),
56 mutable: true,
57 })),
58 shared: false,
59 describes: None,
60 descriptor: None,
61 },
62 });
63 self.ids.ty_slots = slots;
64 self.ids.ty_struct =
65 self.register_struct_type(&[ValType::I32, non_null(slots), non_null(slots)])?;
66 Ok(())
67 }
68
69 pub fn struct_instance_ref(&self) -> ValType {
71 ValType::Ref(RefType {
72 nullable: true,
73 heap_type: HeapType::Concrete(self.ids.ty_struct),
74 })
75 }
76
77 pub(super) fn declare_struct_helpers(&mut self) -> Result<()> {
78 let slots = non_null(self.ids.ty_slots);
79 let instance = non_null(self.ids.ty_struct);
80 self.register_function("struct_new", &[slots, slots, ValType::I32], &[instance])?;
81 self.export_func("struct_new")?;
83 let nullable = self.struct_instance_ref();
84 self.register_function("struct_copy", &[nullable, ValType::I32], &[instance])
85 .map(drop)
86 }
87
88 pub(super) fn build_struct_helpers(&mut self) {
89 self.build_struct_new_body();
90 self.build_struct_copy_body();
91 }
92
93 fn build_struct_new_body(&mut self) {
96 let mut f = Function::new([]);
97 for local in [2, 0, 1] {
98 f.instruction(&Instruction::LocalGet(local));
99 }
100 f.instruction(&Instruction::StructNew(self.ids.ty_struct));
101 f.instruction(&Instruction::End);
102 self.pending_helpers.push(f);
103 }
104
105 fn build_struct_copy_body(&mut self) {
108 const SOURCE: u32 = 0;
109 const SERIAL: u32 = 1;
110 const COPY: u32 = 2;
111 let (ty_struct, ty_slots) = (self.ids.ty_struct, self.ids.ty_slots);
112 let field = |f: &mut Function, field_index: u32| {
113 f.instruction(&Instruction::LocalGet(SOURCE));
114 f.instruction(&Instruction::StructGet {
115 struct_type_index: ty_struct,
116 field_index,
117 });
118 };
119 let copy_local = ValType::Ref(RefType {
120 nullable: true,
121 heap_type: HeapType::Concrete(ty_slots),
122 });
123 let mut f = Function::new([(1, copy_local)]);
124 field(&mut f, 1);
125 f.instruction(&Instruction::RefNull(HeapType::ANY));
126 field(&mut f, 2);
127 f.instruction(&Instruction::ArrayLen);
128 f.instruction(&Instruction::ArrayNew(ty_slots));
129 f.instruction(&Instruction::LocalSet(COPY));
130 f.instruction(&Instruction::LocalGet(COPY));
131 f.instruction(&Instruction::I32Const(0));
132 field(&mut f, 2);
133 f.instruction(&Instruction::I32Const(0));
134 field(&mut f, 2);
135 f.instruction(&Instruction::ArrayLen);
136 f.instruction(&Instruction::ArrayCopy {
137 array_type_index_dst: ty_slots,
138 array_type_index_src: ty_slots,
139 });
140 f.instruction(&Instruction::LocalGet(COPY));
141 f.instruction(&Instruction::RefAsNonNull);
142 f.instruction(&Instruction::LocalGet(SERIAL));
143 f.instruction(&Instruction::Call(self.ids.struct_new));
144 f.instruction(&Instruction::End);
145 self.pending_helpers.push(f);
146 }
147
148 pub(crate) fn struct_serial_global(&mut self) -> Result<u32> {
152 if let Some(idx) = self.struct_serial {
153 return Ok(idx);
154 }
155 let idx = self.push_global(
156 GlobalType {
157 val_type: ValType::I32,
158 mutable: true,
159 shared: false,
160 },
161 &ConstExpr::i32_const(
162 i32::try_from(self.struct_serial_base)
163 .map_err(|_| Error::Resource("too many struct instances".to_string()))?,
164 ),
165 )?;
166 self.struct_serial = Some(idx);
167 Ok(idx)
168 }
169
170 pub(crate) fn set_struct_serial_base(&mut self, base: u32) {
172 self.struct_serial_base = base;
173 }
174
175 pub(crate) fn instance_global(&self, serial: u32) -> Result<u32> {
177 self.instance_globals
178 .get(&serial)
179 .copied()
180 .ok_or_else(|| Error::Compile(format!("internal: instance {serial} has no global")))
181 }
182
183 pub(crate) fn alloc_instance_global(&mut self, serial: u32) -> Result<u32> {
187 let ty = self.struct_instance_ref();
188 let idx = self.push_global(
189 GlobalType {
190 val_type: ty,
191 mutable: true,
192 shared: false,
193 },
194 &ConstExpr::ref_null(HeapType::Concrete(self.ids.ty_struct)),
195 )?;
196 self.exports
197 .export(&instance_export_name(serial), ExportKind::Global, idx);
198 self.instance_globals.insert(serial, idx);
199 Ok(idx)
200 }
201
202 pub(crate) fn alloc_prologue_flag(&mut self) -> Result<u32> {
204 let idx = self.push_global(
205 GlobalType {
206 val_type: ValType::I32,
207 mutable: true,
208 shared: false,
209 },
210 &ConstExpr::i32_const(0),
211 )?;
212 self.exports
213 .export(PROLOGUE_DONE_EXPORT, ExportKind::Global, idx);
214 Ok(idx)
215 }
216
217 pub(crate) fn set_instances_init(&mut self, func_idx: u32) {
218 self.instances_init = Some(func_idx);
219 }
220
221 pub(crate) fn call_instances_init(&self, emit: &mut FunctionEmitter) -> Result<()> {
223 let func_idx = self
224 .instances_init
225 .ok_or_else(|| Error::Compile("internal: the instance prologue is not built".into()))?;
226 emit.call(func_idx);
227 Ok(())
228 }
229
230 pub(crate) fn struct_layout_global(
232 &mut self,
233 id: StructId,
234 layout: &StructLayout,
235 ) -> Result<u32> {
236 if let Some((known, idx)) = self.struct_layouts.get(&id)
237 && known == layout
238 {
239 return Ok(*idx);
240 }
241 let init = self.layout_init(id, layout)?;
242 let idx = self.push_global(
243 GlobalType {
244 val_type: non_null(self.ids.ty_slots),
245 mutable: false,
246 shared: false,
247 },
248 &init,
249 )?;
250 self.struct_layouts.insert(id, (layout.clone(), idx));
251 Ok(idx)
252 }
253
254 fn layout_init(&self, id: StructId, layout: &StructLayout) -> Result<ConstExpr> {
255 let mut code = vec![Instruction::I32Const(
256 i32::try_from(id.0).map_err(|_| Error::Compile("struct id exceeds i32".to_string()))?,
257 )];
258 code.push(Instruction::RefI31);
259 self.push_name(&mut code, &layout.name)?;
260 for field in &layout.fields {
261 self.push_name(&mut code, &format!(":{field}"))?;
262 }
263 code.push(Instruction::ArrayNewFixed {
264 array_type_index: self.ids.ty_slots,
265 array_size: len_i32(layout.fields.len() + 2)?,
266 });
267 Ok(ConstExpr::extended(code))
268 }
269
270 fn push_name(&self, code: &mut Vec<Instruction<'static>>, name: &str) -> Result<()> {
271 code.extend(
272 name.bytes()
273 .map(|byte| Instruction::I32Const(i32::from(byte))),
274 );
275 code.push(Instruction::ArrayNewFixed {
276 array_type_index: self.ids.ty_i8_array,
277 array_size: len_i32(name.len())?,
278 });
279 code.push(Instruction::StructNew(self.ids.ty_symbol));
280 Ok(())
281 }
282}