Lines
91.87 %
Functions
71.5 %
Branches
100 %
//! Module type handles and `anyref` kind classification for the decoders.
use crate::checked_ref::CheckedAnyRef;
use super::structure::{closure_site, closure_struct};
use wasmtime::{AnyRef, AsContext, AsContextMut, Caller, Extern, HeapType, Instance, Rooted, Val};
/// Resolves the compiler-emitted `t` singleton export (ADR-0033: the `$t`
/// module global, an empty-struct instance identified by reference equality)
/// so the host can recognise it when decoding an `AnyRef` result or list
/// cell. Every module the compiler emits exports it, so a missing export is a
/// structured error, not a silent fallback.
pub fn t_singleton(
mut store: impl AsContextMut,
instance: &Instance,
) -> wasmtime::Result<Rooted<AnyRef>> {
let found = instance.get_export(&mut store, "t");
t_from_export(&mut store, found)
}
fn t_from_export(
export: Option<Extern>,
let global = export
.and_then(Extern::into_global)
.ok_or_else(|| wasmtime::Error::msg("module does not export the `t` global"))?;
match global.get(&mut store) {
Val::AnyRef(Some(t)) => Ok(t),
_ => Err(wasmtime::Error::msg(
"`t` global is not a non-null internal reference",
)),
/// Module type handles for classifying a heterogeneous `anyref` result or
/// `$pair` car by structural kind (ADR-0033 Phase 6), once the null / `$t` /
/// i31 kinds Phase 3 already covers are ruled out. WasmGC struct/array types
/// are structural, so the host can't name "the ratio type"; instead it reads
/// the `HeapType` off an export whose signature already carries it — no
/// value is ever taken through any of these exports host-side, only their
/// declared shape. `ratio_new` / `commodity_new` / `pair_new` / `string_eq` / `symbol_new`
/// and one `alloc_<kind>` per [`nomiscript::EntityKind`] with a field layout
/// are exported by every module regardless of program content.
pub struct TypeHandles {
pub(super) t: Rooted<AnyRef>,
pub(super) ratio: HeapType,
pub(super) commodity: HeapType,
pub(super) pair: HeapType,
pub(super) string: HeapType,
pub(super) symbol: HeapType,
pub(super) structure: HeapType,
pub(super) entities: Vec<(nomiscript::EntityKind, HeapType)>,
/// Resolves [`TypeHandles`] from `instance`'s exports. Call once per eval
/// call, alongside (in place of) [`t_singleton`].
pub fn resolve_type_handles(
) -> wasmtime::Result<TypeHandles> {
resolve_with(&mut store, |store, name| instance.get_export(store, name))
/// [`resolve_type_handles`] for a host function, which sees its calling
/// instance's exports only through the `Caller`.
pub fn resolve_caller_type_handles<T>(caller: &mut Caller<'_, T>) -> wasmtime::Result<TypeHandles> {
resolve_with(caller, |caller, name| caller.get_export(name))
fn resolve_with<S: AsContextMut>(
store: &mut S,
export: impl Fn(&mut S, &str) -> Option<Extern>,
let heap_type = |store: &mut S, name: &str, take_param: bool| {
let found = export(store, name);
exported_func_heap_type(&*store, found, name, take_param)
};
let found = export(store, "t");
let t = t_from_export(&mut *store, found)?;
let ratio = heap_type(store, "ratio_new", false)?;
let commodity = heap_type(store, "commodity_new", false)?;
let pair = heap_type(store, "pair_new", false)?;
let string = heap_type(store, "string_eq", true)?;
let symbol = heap_type(store, "symbol_new", false)?;
let structure = heap_type(store, "struct_new", false)?;
let mut entities = nomiscript::ENTITY_LAYOUTS
.iter()
.map(|layout| {
let name = format!("alloc_{}", layout.kind.type_name());
heap_type(store, &name, false).map(|ty| (layout.kind, ty))
})
.collect::<wasmtime::Result<Vec<_>>>()?;
entities.push((
nomiscript::EntityKind::Condition,
heap_type(store, "condition_new", false)?,
));
Ok(TypeHandles {
t,
ratio,
commodity,
pair,
string,
symbol,
structure,
entities,
/// The `HeapType` of `name`'s single reference-typed result (`take_param =
/// false`) or param (`take_param = true`). A missing export or a
/// non-reference-typed slot is a structured error — every name this module
/// queries is unconditionally exported by the compiler.
fn exported_func_heap_type(
store: impl AsContext,
name: &str,
take_param: bool,
) -> wasmtime::Result<HeapType> {
let func = export
.and_then(Extern::into_func)
.ok_or_else(|| wasmtime::Error::msg(format!("module does not export `{name}`")))?;
let ty = func.ty(&store);
let slot = if take_param {
ty.params().next()
} else {
ty.results().next()
slot.and_then(|v| v.as_ref().map(|r| r.heap_type().clone()))
.ok_or_else(|| {
let side = if take_param { "param" } else { "result" };
wasmtime::Error::msg(format!("`{name}` has no reference-typed {side}"))
/// The `AnyRef` kinds the host recognises in a heterogeneous cell/result
/// (ADR-0033 Phase 6): the `$t` singleton and an i31-boxed index by
/// identity/kind alone (Phase 3), the struct/array kinds a module export's
/// signature identifies via [`TypeHandles`] (Phase 6), a closure by its
/// function-reference field, or `Other` — a kind this host build doesn't
/// classify, which keeps the `<anyref>` placeholder rather than erroring.
pub(super) enum AnyRefKind {
T,
Index(i32),
Ratio,
Commodity,
StringRef,
Symbol,
/// A nested `$pair` chain. Its own element type is not recoverable at
/// runtime (`PairElement` is a compile-time-only tag), so a caller walks
/// it with `PairElement::AnyRef`, classifying each of ITS cars in turn.
Pair,
Entity(nomiscript::EntityKind),
/// A `DEFSTRUCT` instance.
Struct,
/// A closure, by the site of its source.
Closure(Option<u32>),
Other,
/// Classifies a non-null `anyref` value: `t` by reference identity against
/// the module's `$t` singleton (ADR-0033 — never by type test, since WasmGC
/// struct types are structural and an empty struct type is not unique), an
/// i31 as an index, else a `matches_ty` test against each of `handles`'
/// struct/array kinds in turn, else `Other`.
pub(super) fn classify_anyref(
any: Rooted<AnyRef>,
handles: &TypeHandles,
) -> wasmtime::Result<AnyRefKind> {
if Rooted::<AnyRef>::ref_eq(&store, &any, &handles.t)? {
return Ok(AnyRefKind::T);
if any.is_i31(&mut store)? {
let i31 = any.checked_i31(&mut store)?;
return Ok(AnyRefKind::Index(i31.get_i32()));
if any.matches_ty(&store, &handles.ratio)? {
return Ok(AnyRefKind::Ratio);
if any.matches_ty(&store, &handles.commodity)? {
return Ok(AnyRefKind::Commodity);
if any.matches_ty(&store, &handles.string)? {
return Ok(AnyRefKind::StringRef);
if any.matches_ty(&store, &handles.symbol)? {
return Ok(AnyRefKind::Symbol);
if any.matches_ty(&store, &handles.pair)? {
return Ok(AnyRefKind::Pair);
if any.matches_ty(&store, &handles.structure)? {
return Ok(AnyRefKind::Struct);
for (kind, ty) in &handles.entities {
if any.matches_ty(&store, ty)? {
return Ok(AnyRefKind::Entity(*kind));
let Some(closure) = closure_struct(&mut store, &any)? else {
return Ok(AnyRefKind::Other);
Ok(AnyRefKind::Closure(closure_site(&mut store, &closure)?))