Lines
98.66 %
Functions
90.63 %
Branches
100 %
//! Lowering of the struct natives. The operand's static type decides: a
//! `StructRef` of the layout needs only a null check, an `AnyRef` is tested
//! against the layout at run time, anything else is a compile error.
use wasm_encoder::{BlockType, HeapType, ValType};
use super::{COPY, NEW, P, REF, SET, expect_arity, layout_of, slot_of, stored_type};
use crate::ast::{Expr, PairElement, StructId, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::compile_for_stack;
use crate::compiler::native::{emit_pair_car_downcast, push_anyref_arm};
use crate::compiler::special::control::error_form::push_string_literal;
use crate::error::{Error, Result, with_article};
use crate::runtime::{StructLayout, SymbolTable};
/// What an operand's static type says about a layout.
#[derive(Clone, Copy, PartialEq)]
enum Operand {
Exact,
Dynamic,
Other,
}
impl Operand {
fn of(ty: WasmType, id: StructId) -> Self {
match ty {
WasmType::StructRef(found) if found == id => Self::Exact,
WasmType::AnyRef => Self::Dynamic,
_ => Self::Other,
/// An operand compiled and parked in a local, with the layout it is read as.
struct Target {
id: StructId,
local: u32,
kind: Operand,
layout_global: u32,
layout: StructLayout,
/// Compiles the operand of the function `who` and parks it; an operand that
/// cannot be an instance of the layout is a compile error naming `who`.
fn target(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
who: &str,
(id, layout): (StructId, StructLayout),
operand: &Expr,
) -> Result<Target> {
let ty = compile_for_stack(ctx, emit, symbols, operand)?;
let local = ctx.alloc_local(ty)?;
emit.local_set(local);
let kind = Operand::of(ty, id);
if kind == Operand::Other {
emit.reject_if_live(Error::Compile(format!(
"{who}: expected a {}, got {}",
layout.name,
with_article(ty)
)))?;
Ok(Target {
id,
local,
kind,
layout_global: ctx.struct_layout_global(id, &layout)?,
layout,
})
fn throw_type_error(
message: &str,
) -> Result<()> {
push_string_literal(ctx, emit, "TYPE-ERROR")?;
push_string_literal(ctx, emit, message)?;
emit.ref_null_any();
emit.struct_new(ctx.condition_type_idx());
emit.throw(ctx.nomi_error_tag()?);
Ok(())
/// Leaves an i32 on the stack: whether the parked operand is an instance of
/// the layout.
fn instance_test(ctx: &CompileContext, emit: &mut FunctionEmitter, target: &Target) -> Result<()> {
emit.local_get(target.local);
match target.kind {
Operand::Exact => {
emit.ref_is_null();
emit.i32_eqz();
Operand::Dynamic => {
emit.ref_test_non_null(HeapType::Concrete(ctx.ids.ty_struct));
emit.if_block(BlockType::Result(ValType::I32));
emit.ref_cast(ctx.ids.ty_struct);
emit.struct_get(ctx.ids.ty_struct, 1);
emit.global_get(target.layout_global);
emit.ref_eq();
emit.else_block();
emit.i32_const(0);
emit.block_end()?;
Operand::Other => {
emit.drop_value();
/// Throws a `TYPE-ERROR` unless the parked operand is an instance.
fn require_instance(
target: &Target,
accessor: &str,
instance_test(ctx, emit, target)?;
emit.if_block(BlockType::Empty);
let message = format!("{accessor}: expected a {}", target.layout.name);
throw_type_error(ctx, emit, &message)?;
emit.block_end()
/// Pushes the parked instance's `$slots` of values.
fn push_values(ctx: &CompileContext, emit: &mut FunctionEmitter, target: &Target) {
emit.struct_get(ctx.ids.ty_struct, 2);
pub(super) fn new(
args: &[Expr],
) -> Result<WasmType> {
let first = args.first().ok_or_else(|| Error::Arity {
name: NEW.to_string(),
expected: 1,
actual: 0,
})?;
let (id, layout) = layout_of(symbols, NEW, first)?;
expect_arity(NEW, args, 1 + layout.fields.len())?;
let global = ctx.struct_layout_global(id, &layout)?;
emit.global_get(global);
let size = u16::try_from(layout.fields.len())
.map_err(|_| Error::Compile(format!("{NEW}: too many fields")))?;
for (idx, value) in (0..size).zip(&args[1..]) {
let arm = push_anyref_arm(ctx, emit, symbols, value)?;
if emit.is_reachable() {
symbols.note_field_store(id, idx, arm);
emit.array_new_fixed(ctx.ids.ty_slots, u32::from(size));
emit_with_next_serial(ctx, emit, ctx.ids.struct_new)?;
Ok(WasmType::StructRef(id))
pub(super) fn predicate(
expect_arity(P, args, 2)?;
let (id, layout) = layout_of(symbols, P, &args[1])?;
let ty = compile_for_stack(ctx, emit, symbols, &args[0])?;
let target = Target {
kind: Operand::of(ty, id),
};
instance_test(ctx, emit, &target)?;
Ok(WasmType::Bool)
pub(super) fn read(
expect_arity(REF, args, 3)?;
let (id, layout) = layout_of(symbols, REF, &args[1])?;
let slot = slot_of(REF, &args[2], &layout)?;
let who = accessor(&layout, slot);
let target = target(ctx, emit, symbols, &who, (id, layout), &args[0])?;
let ty = symbols.field_type(target.id, slot);
if !emit.is_reachable() {
return Ok(ty);
require_instance(ctx, emit, &target, &who)?;
push_values(ctx, emit, &target);
emit.i32_const(i32::from(slot));
emit.array_get(ctx.ids.ty_slots);
unbox(ctx, emit, ty)?;
Ok(ty)
pub(super) fn write(
expect_arity(SET, args, 4)?;
let (id, layout) = layout_of(symbols, SET, &args[1])?;
let slot = slot_of(SET, &args[2], &layout)?;
let setter = format!("(SETF {})", accessor(&layout, slot));
let target = target(ctx, emit, symbols, &setter, (id, layout), &args[0])?;
return Ok(WasmType::AnyRef);
let arm = push_anyref_arm(ctx, emit, symbols, &args[3])?;
let result = stored_type(arm);
symbols.note_field_store(target.id, slot, arm);
let value = ctx.alloc_local(WasmType::AnyRef)?;
emit.local_set(value);
require_instance(ctx, emit, &target, &setter)?;
emit.local_get(value);
emit.array_set(ctx.ids.ty_slots);
unbox(ctx, emit, result)?;
Ok(result)
pub(super) fn copy(
expect_arity(COPY, args, 2)?;
let found = layout_of(symbols, COPY, &args[1])?;
let copier = format!("COPY-{}", found.1.name);
let target = target(ctx, emit, symbols, &copier, found, &args[0])?;
return Ok(WasmType::StructRef(target.id));
require_instance(ctx, emit, &target, &copier)?;
emit.ref_cast_nullable(ctx.ids.ty_struct);
emit_with_next_serial(ctx, emit, ctx.ids.struct_copy)?;
Ok(WasmType::StructRef(target.id))
/// Calls the allocating helper `func` with the next serial as its last
/// argument and advances the counter.
fn emit_with_next_serial(
func: u32,
let serial = ctx.struct_serial_global()?;
emit.global_get(serial);
emit.call(func);
emit.i32_const(1);
emit.i32_add();
emit.global_set(serial);
fn accessor(layout: &StructLayout, slot: u16) -> String {
let field = layout
.fields
.get(usize::from(slot))
.map_or("", String::as_str);
format!("{}-{field}", layout.name)
/// Casts the `anyref` a slot read to the type its home settled on.
fn unbox(ctx: &CompileContext, emit: &mut FunctionEmitter, ty: WasmType) -> Result<()> {
match (ty, PairElement::from_wasm_type(ty)) {
(WasmType::PairRef(_), _) => emit.ref_cast_nullable(ctx.ids.ty_pair),
(_, Some(elem)) => emit_pair_car_downcast(ctx, emit, elem)?,
(_, None) => {}