Lines
98.53 %
Functions
82.69 %
Branches
100 %
//! The wasm side of `DEFSTRUCT` instances: one `$struct` shape for every
//! layout, so a layout needs no wasm type of its own. An instance is
//! `(serial, layout, values)`; the layout is an immutable `$slots` array
//! `[i31 StructId, $symbol NAME, $symbol :FIELD ...]` shared by its instances.
use std::collections::HashMap;
use wasm_encoder::{
ArrayType, CompositeInnerType, CompositeType, ConstExpr, ExportKind, FieldType, Function,
GlobalType, HeapType, Instruction, RefType, StorageType, SubType, ValType,
};
use super::CompileContext;
use super::registry::bump;
use crate::ast::StructId;
use crate::compiler::emit::FunctionEmitter;
use crate::error::{Error, Result};
use crate::runtime::StructLayout;
/// The wasm global of each layout a compilation has used. A rolled-back trial
/// can reuse an id for another layout, so the layout itself is kept to compare.
pub(super) type LayoutGlobals = HashMap<StructId, (StructLayout, u32)>;
fn non_null(type_idx: u32) -> ValType {
ValType::Ref(RefType {
nullable: false,
heap_type: HeapType::Concrete(type_idx),
})
}
/// The export name of the global holding the session instance `serial`; the
/// host reads it back to see what the unit did to the instance.
#[must_use]
pub fn instance_export_name(serial: u32) -> String {
format!("inst{serial}")
/// The export name of the flag the instance prologue sets once every instance
/// is allocated and filled; the host settles the heap only when it reads 1.
pub const PROLOGUE_DONE_EXPORT: &str = "prologue_done";
fn len_i32(len: usize) -> Result<u32> {
u32::try_from(len).map_err(|_| Error::Compile("struct layout exceeds u32".to_string()))
impl CompileContext {
pub(super) fn register_struct_types(&mut self) -> Result<()> {
let anyref = self.anyref();
let slots = bump(&mut self.type_count, "type")?;
self.types.ty().subtype(&SubType {
is_final: true,
supertype_idxs: Vec::new(),
composite_type: CompositeType {
inner: CompositeInnerType::Array(ArrayType(FieldType {
element_type: StorageType::Val(anyref),
mutable: true,
})),
shared: false,
describes: None,
descriptor: None,
},
});
self.ids.ty_slots = slots;
self.ids.ty_struct =
self.register_struct_type(&[ValType::I32, non_null(slots), non_null(slots)])?;
Ok(())
/// `(ref null $struct)`.
pub fn struct_instance_ref(&self) -> ValType {
nullable: true,
heap_type: HeapType::Concrete(self.ids.ty_struct),
pub(super) fn declare_struct_helpers(&mut self) -> Result<()> {
let slots = non_null(self.ids.ty_slots);
let instance = non_null(self.ids.ty_struct);
self.register_function("struct_new", &[slots, slots, ValType::I32], &[instance])?;
// The host resolves the `$struct` heap type from this result.
self.export_func("struct_new")?;
let nullable = self.struct_instance_ref();
self.register_function("struct_copy", &[nullable, ValType::I32], &[instance])
.map(drop)
pub(super) fn build_struct_helpers(&mut self) {
self.build_struct_new_body();
self.build_struct_copy_body();
/// `struct_new(layout, values, serial)`; the serial is the last argument so
/// the caller reads the counter after evaluating the field values.
fn build_struct_new_body(&mut self) {
let mut f = Function::new([]);
for local in [2, 0, 1] {
f.instruction(&Instruction::LocalGet(local));
f.instruction(&Instruction::StructNew(self.ids.ty_struct));
f.instruction(&Instruction::End);
self.pending_helpers.push(f);
/// `struct_copy(instance, serial)`: a new instance of the same layout over a copy
/// of the values.
fn build_struct_copy_body(&mut self) {
const SOURCE: u32 = 0;
const SERIAL: u32 = 1;
const COPY: u32 = 2;
let (ty_struct, ty_slots) = (self.ids.ty_struct, self.ids.ty_slots);
let field = |f: &mut Function, field_index: u32| {
f.instruction(&Instruction::LocalGet(SOURCE));
f.instruction(&Instruction::StructGet {
struct_type_index: ty_struct,
field_index,
let copy_local = ValType::Ref(RefType {
heap_type: HeapType::Concrete(ty_slots),
let mut f = Function::new([(1, copy_local)]);
field(&mut f, 1);
f.instruction(&Instruction::RefNull(HeapType::ANY));
field(&mut f, 2);
f.instruction(&Instruction::ArrayLen);
f.instruction(&Instruction::ArrayNew(ty_slots));
f.instruction(&Instruction::LocalSet(COPY));
f.instruction(&Instruction::LocalGet(COPY));
f.instruction(&Instruction::I32Const(0));
f.instruction(&Instruction::ArrayCopy {
array_type_index_dst: ty_slots,
array_type_index_src: ty_slots,
f.instruction(&Instruction::RefAsNonNull);
f.instruction(&Instruction::LocalGet(SERIAL));
f.instruction(&Instruction::Call(self.ids.struct_new));
/// The mutable global counting the instances this compilation allocates,
/// allocated on first use so a program with no structure keeps its
/// global indices.
pub(crate) fn struct_serial_global(&mut self) -> Result<u32> {
if let Some(idx) = self.struct_serial {
return Ok(idx);
let idx = self.push_global(
GlobalType {
val_type: ValType::I32,
&ConstExpr::i32_const(
i32::try_from(self.struct_serial_base)
.map_err(|_| Error::Resource("too many struct instances".to_string()))?,
),
)?;
self.struct_serial = Some(idx);
Ok(idx)
/// Starts the instance serial counter past the instances the session holds.
pub(crate) fn set_struct_serial_base(&mut self, base: u32) {
self.struct_serial_base = base;
/// The wasm global of the session instance `serial`.
pub(crate) fn instance_global(&self, serial: u32) -> Result<u32> {
self.instance_globals
.get(&serial)
.copied()
.ok_or_else(|| Error::Compile(format!("internal: instance {serial} has no global")))
/// Declares the exported global of the session instance `serial`, null until
/// the unit prologue allocates it: a constant initializer would make the
/// engine compile every allocation into one start function.
pub(crate) fn alloc_instance_global(&mut self, serial: u32) -> Result<u32> {
let ty = self.struct_instance_ref();
val_type: ty,
&ConstExpr::ref_null(HeapType::Concrete(self.ids.ty_struct)),
self.exports
.export(&instance_export_name(serial), ExportKind::Global, idx);
self.instance_globals.insert(serial, idx);
/// Declares the exported flag the prologue sets when it has finished.
pub(crate) fn alloc_prologue_flag(&mut self) -> Result<u32> {
&ConstExpr::i32_const(0),
.export(PROLOGUE_DONE_EXPORT, ExportKind::Global, idx);
pub(crate) fn set_instances_init(&mut self, func_idx: u32) {
self.instances_init = Some(func_idx);
/// Emits the call that runs the instance prologue, a no-op once it ran.
pub(crate) fn call_instances_init(&self, emit: &mut FunctionEmitter) -> Result<()> {
let func_idx = self
.instances_init
.ok_or_else(|| Error::Compile("internal: the instance prologue is not built".into()))?;
emit.call(func_idx);
/// The global holding `layout`'s `$slots` array, allocated on first use.
pub(crate) fn struct_layout_global(
&mut self,
id: StructId,
layout: &StructLayout,
) -> Result<u32> {
if let Some((known, idx)) = self.struct_layouts.get(&id)
&& known == layout
{
return Ok(*idx);
let init = self.layout_init(id, layout)?;
val_type: non_null(self.ids.ty_slots),
mutable: false,
&init,
self.struct_layouts.insert(id, (layout.clone(), idx));
fn layout_init(&self, id: StructId, layout: &StructLayout) -> Result<ConstExpr> {
let mut code = vec![Instruction::I32Const(
i32::try_from(id.0).map_err(|_| Error::Compile("struct id exceeds i32".to_string()))?,
)];
code.push(Instruction::RefI31);
self.push_name(&mut code, &layout.name)?;
for field in &layout.fields {
self.push_name(&mut code, &format!(":{field}"))?;
code.push(Instruction::ArrayNewFixed {
array_type_index: self.ids.ty_slots,
array_size: len_i32(layout.fields.len() + 2)?,
Ok(ConstExpr::extended(code))
fn push_name(&self, code: &mut Vec<Instruction<'static>>, name: &str) -> Result<()> {
code.extend(
name.bytes()
.map(|byte| Instruction::I32Const(i32::from(byte))),
);
array_type_index: self.ids.ty_i8_array,
array_size: len_i32(name.len())?,
code.push(Instruction::StructNew(self.ids.ty_symbol));