Lines
94.02 %
Functions
81.82 %
Branches
100 %
//! The unit prologue of the session's struct instances (rstruct S5): each is
//! allocated into an exported global holding nil fields, then every field
//! takes its carried constant, all in bounded helper functions. All are
//! allocated first, so a cycle resolves. The unit's cells are seeded after
//! them in the same guarded run, so SHOULD-APPLY sees them as `process` does.
use wasm_encoder::BlockType;
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::fold::stores::StoreScan;
use crate::compiler::native::push_constant_arm;
use crate::error::{Error, Result};
use crate::runtime::{StructInstance, SymbolTable};
use super::cells::{adopt_closures, allocate_cells};
pub(in crate::compiler) fn allocate_instances(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
scan: &StoreScan,
) -> Result<()> {
ctx.set_struct_serial_base(symbols.next_serial());
let heap: Vec<(u32, StructInstance)> = symbols
.instances()
.map(|(serial, instance)| (serial, instance.clone()))
.collect();
let homes = heap
.iter()
.map(|(serial, instance)| declare_instance(ctx, symbols, *serial, instance))
.collect::<Result<Vec<_>>>()?;
let mut steps = Vec::new();
for (index, chunk) in homes.chunks(INSTANCES_PER_FUNCTION).enumerate() {
let name = format!("__instance_alloc_{index}");
steps.push(in_helper(ctx, &name, |ctx, helper| {
chunk
.try_for_each(|home| allocate_instance(ctx, helper, home))
})?);
}
for (index, chunk) in heap.chunks(INSTANCES_PER_FUNCTION).enumerate() {
let name = format!("__instance_fill_{index}");
chunk.iter().try_for_each(|(serial, instance)| {
fill_instance(ctx, helper, symbols, *serial, instance)
})
let done = ctx.alloc_prologue_flag()?;
steps.push(in_helper(ctx, "__cells_init", |ctx, helper| {
allocate_cells(ctx, helper, symbols, scan)?;
adopt_closures(ctx, helper, symbols, scan)
let init = in_helper(ctx, "__instances_init", |_, helper| {
emit_guarded_steps(helper, done, &steps)
})?;
ctx.set_instances_init(init);
ctx.call_instances_init(emit)
/// Runs `steps` unless the flag `done` says they ran, then raises the flag, so
/// a trap partway leaves it down and the carried heap untouched.
fn emit_guarded_steps(helper: &mut FunctionEmitter, done: u32, steps: &[u32]) -> Result<()> {
helper.global_get(done);
helper.i32_eqz();
helper.if_block(BlockType::Empty);
steps.iter().for_each(|&step| helper.call(step));
helper.i32_const(1);
helper.global_set(done);
helper.block_end()
/// The engine compiles a function in time superlinear in its size, so the
/// prologue rides bounded functions called in order.
const INSTANCES_PER_FUNCTION: usize = 256;
/// Emits `body` into a fresh helper function and returns its index.
fn in_helper(
name: &str,
body: impl FnOnce(&mut CompileContext, &mut FunctionEmitter) -> Result<()>,
) -> Result<u32> {
let func_idx = ctx.register_function(name, &[], &[])?;
let slot = ctx.reserve_helper();
let snapshot = ctx.take_local_pool(0);
let mut helper = FunctionEmitter::new();
let emitted = body(ctx, &mut helper);
let locals = ctx.build_helper_locals(0);
ctx.restore_local_pool(snapshot);
emitted?;
let locals = locals?;
ctx.fill_helper(slot, helper.finish(&locals)?)?;
Ok(func_idx)
/// A session instance's global and the layout it is allocated from.
struct Home {
serial: u32,
global: u32,
layout_global: u32,
size: usize,
fn declare_instance(
symbols: &SymbolTable,
instance: &StructInstance,
) -> Result<Home> {
let layout = symbols
.struct_layout(instance.layout)
.ok_or_else(|| Error::Compile(format!("instance {serial} has no struct layout")))?;
let layout_global = ctx.struct_layout_global(instance.layout, layout)?;
let global = ctx.alloc_instance_global(serial)?;
Ok(Home {
serial,
global,
layout_global,
size: layout.fields.len(),
fn allocate_instance(ctx: &CompileContext, emit: &mut FunctionEmitter, home: &Home) -> Result<()> {
let serial = i32::try_from(home.serial)
.map_err(|_| Error::Resource("too many struct instances".to_string()))?;
let size = i32::try_from(home.size)
.map_err(|_| Error::Compile("struct layout exceeds i32".to_string()))?;
emit.i32_const(serial);
emit.global_get(home.layout_global);
emit.i32_const(size);
emit.array_new_default(ctx.ids.ty_slots);
emit.struct_new(ctx.ids.ty_struct);
emit.global_set(home.global);
Ok(())
fn fill_instance(
let global = ctx.instance_global(serial)?;
for (slot, value) in (0..).zip(&instance.fields) {
emit.global_get(global);
emit.struct_get(ctx.ids.ty_struct, 2);
emit.i32_const(slot);
let arm = push_constant_arm(ctx, emit, symbols, value)?;
emit.array_set(ctx.ids.ty_slots);
symbols.note_field_store(instance.layout, u16::try_from(slot).map_err(too_many)?, arm);
fn too_many(_: std::num::TryFromIntError) -> Error {
Error::Compile("struct layout exceeds u16 fields".to_string())
#[cfg(test)]
#[path = "instances_tests.rs"]
mod tests;