Lines
89.19 %
Functions
100 %
Branches
//! The host-anyref lambda boundary: the wire values a host-invoked body
//! receives as anyref and returns as anyref.
use crate::ast::WasmType;
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::emit_box_anyref;
use crate::error::{Error, Result};
/// Emits the wasm to convert an `anyref` on the stack to the declared
/// user-visible type: a reference `ref.cast`s to its concrete type, an i31-boxed
/// index or bool unboxes to its i32. The variable keeps the element's own
/// dimension — no int ↔ ratio ↔ commodity bridging (ADR-0014).
pub(super) fn emit_anyref_to_typed_downcast(
ctx: &CompileContext,
helper: &mut FunctionEmitter,
ty: WasmType,
) -> Result<()> {
match ty {
WasmType::Ratio => helper.ref_cast(ctx.ids.ty_ratio),
WasmType::Commodity => helper.ref_cast(ctx.ids.ty_commodity),
// `PairRef` / `StringRef` / `EntityRef` cells can legitimately be nil
// (ADR-0033 Phase 5): a nullable cast keeps that nil rather than
// trapping the engine — mirrors `emit_pair_car_downcast`. The
// `TYPE-ERROR` null check runs later, only when a consumer
// dereferences the value.
WasmType::PairRef(_) => helper.ref_cast_nullable(ctx.ids.ty_pair),
WasmType::StringRef => helper.ref_cast_nullable(ctx.ids.ty_i8_array),
WasmType::SymbolRef => helper.ref_cast_nullable(ctx.ids.ty_symbol),
WasmType::EntityRef(kind) => helper.ref_cast_nullable(ctx.ids.entity_type(kind)),
WasmType::StructRef(_) => helper.ref_cast_nullable(ctx.ids.ty_struct),
WasmType::I32 => {
helper.ref_cast_i31();
helper.i31_get_s();
}
// A bool item is `ref.null` (nil) / the `$t` singleton (t), never an
// i31 (ADR-0033) — unboxing is "is it non-null?", mirroring
// `emit_pair_car_downcast`'s `PairElement::Bool` arm.
WasmType::Bool => {
helper.ref_is_null();
helper.i32_eqz();
WasmType::AnyRef => {}
WasmType::Closure(sig) => helper.ref_cast_nullable(ctx.closure_sig(sig)?.closure_type_idx),
Ok(())
/// Wraps the body's typed result as the anyref the host fn receives: an index
/// through the range-checked `box_index`, a bool as nil-null / i31 1, a
/// reference as itself. A body that diverged left a polymorphic stack, which
/// the same boxing satisfies.
pub(super) fn promote_result_to_anyref(
WasmType::AnyRef => Ok(()),
WasmType::I32 | WasmType::Bool => {
emit_box_anyref(ctx, helper, ty);
WasmType::Ratio
| WasmType::Commodity
| WasmType::PairRef(_)
| WasmType::StringRef
| WasmType::SymbolRef
| WasmType::EntityRef(_)
| WasmType::StructRef(_) => {
// Refs widen to anyref freely (subtyping); no instruction needed.
let _ = ctx;
let _ = helper;
WasmType::Closure(_) => Err(Error::Compile(format!(
"host-anyref calling convention cannot widen body return type {ty} to anyref"
))),