Skip to main content

scripting/runtime/
type_handles.rs

1//! Module type handles and `anyref` kind classification for the decoders.
2
3use crate::checked_ref::CheckedAnyRef;
4
5use super::structure::{closure_site, closure_struct};
6
7use wasmtime::{AnyRef, AsContext, AsContextMut, Caller, Extern, HeapType, Instance, Rooted, Val};
8
9/// Resolves the compiler-emitted `t` singleton export (ADR-0033: the `$t`
10/// module global, an empty-struct instance identified by reference equality)
11/// so the host can recognise it when decoding an `AnyRef` result or list
12/// cell. Every module the compiler emits exports it, so a missing export is a
13/// structured error, not a silent fallback.
14pub fn t_singleton(
15    mut store: impl AsContextMut,
16    instance: &Instance,
17) -> wasmtime::Result<Rooted<AnyRef>> {
18    let found = instance.get_export(&mut store, "t");
19    t_from_export(&mut store, found)
20}
21
22fn t_from_export(
23    mut store: impl AsContextMut,
24    export: Option<Extern>,
25) -> wasmtime::Result<Rooted<AnyRef>> {
26    let global = export
27        .and_then(Extern::into_global)
28        .ok_or_else(|| wasmtime::Error::msg("module does not export the `t` global"))?;
29    match global.get(&mut store) {
30        Val::AnyRef(Some(t)) => Ok(t),
31        _ => Err(wasmtime::Error::msg(
32            "`t` global is not a non-null internal reference",
33        )),
34    }
35}
36
37/// Module type handles for classifying a heterogeneous `anyref` result or
38/// `$pair` car by structural kind (ADR-0033 Phase 6), once the null / `$t` /
39/// i31 kinds Phase 3 already covers are ruled out. WasmGC struct/array types
40/// are structural, so the host can't name "the ratio type"; instead it reads
41/// the `HeapType` off an export whose signature already carries it — no
42/// value is ever taken through any of these exports host-side, only their
43/// declared shape. `ratio_new` / `commodity_new` / `pair_new` / `string_eq` / `symbol_new`
44/// and one `alloc_<kind>` per [`nomiscript::EntityKind`] with a field layout
45/// are exported by every module regardless of program content.
46pub struct TypeHandles {
47    pub(super) t: Rooted<AnyRef>,
48    pub(super) ratio: HeapType,
49    pub(super) commodity: HeapType,
50    pub(super) pair: HeapType,
51    pub(super) string: HeapType,
52    pub(super) symbol: HeapType,
53    pub(super) structure: HeapType,
54    pub(super) entities: Vec<(nomiscript::EntityKind, HeapType)>,
55}
56
57/// Resolves [`TypeHandles`] from `instance`'s exports. Call once per eval
58/// call, alongside (in place of) [`t_singleton`].
59pub fn resolve_type_handles(
60    mut store: impl AsContextMut,
61    instance: &Instance,
62) -> wasmtime::Result<TypeHandles> {
63    resolve_with(&mut store, |store, name| instance.get_export(store, name))
64}
65
66/// [`resolve_type_handles`] for a host function, which sees its calling
67/// instance's exports only through the `Caller`.
68pub fn resolve_caller_type_handles<T>(caller: &mut Caller<'_, T>) -> wasmtime::Result<TypeHandles> {
69    resolve_with(caller, |caller, name| caller.get_export(name))
70}
71
72fn resolve_with<S: AsContextMut>(
73    store: &mut S,
74    export: impl Fn(&mut S, &str) -> Option<Extern>,
75) -> wasmtime::Result<TypeHandles> {
76    let heap_type = |store: &mut S, name: &str, take_param: bool| {
77        let found = export(store, name);
78        exported_func_heap_type(&*store, found, name, take_param)
79    };
80    let found = export(store, "t");
81    let t = t_from_export(&mut *store, found)?;
82    let ratio = heap_type(store, "ratio_new", false)?;
83    let commodity = heap_type(store, "commodity_new", false)?;
84    let pair = heap_type(store, "pair_new", false)?;
85    let string = heap_type(store, "string_eq", true)?;
86    let symbol = heap_type(store, "symbol_new", false)?;
87    let structure = heap_type(store, "struct_new", false)?;
88    let mut entities = nomiscript::ENTITY_LAYOUTS
89        .iter()
90        .map(|layout| {
91            let name = format!("alloc_{}", layout.kind.type_name());
92            heap_type(store, &name, false).map(|ty| (layout.kind, ty))
93        })
94        .collect::<wasmtime::Result<Vec<_>>>()?;
95    entities.push((
96        nomiscript::EntityKind::Condition,
97        heap_type(store, "condition_new", false)?,
98    ));
99    Ok(TypeHandles {
100        t,
101        ratio,
102        commodity,
103        pair,
104        string,
105        symbol,
106        structure,
107        entities,
108    })
109}
110
111/// The `HeapType` of `name`'s single reference-typed result (`take_param =
112/// false`) or param (`take_param = true`). A missing export or a
113/// non-reference-typed slot is a structured error — every name this module
114/// queries is unconditionally exported by the compiler.
115fn exported_func_heap_type(
116    store: impl AsContext,
117    export: Option<Extern>,
118    name: &str,
119    take_param: bool,
120) -> wasmtime::Result<HeapType> {
121    let func = export
122        .and_then(Extern::into_func)
123        .ok_or_else(|| wasmtime::Error::msg(format!("module does not export `{name}`")))?;
124    let ty = func.ty(&store);
125    let slot = if take_param {
126        ty.params().next()
127    } else {
128        ty.results().next()
129    };
130    slot.and_then(|v| v.as_ref().map(|r| r.heap_type().clone()))
131        .ok_or_else(|| {
132            let side = if take_param { "param" } else { "result" };
133            wasmtime::Error::msg(format!("`{name}` has no reference-typed {side}"))
134        })
135}
136
137/// The `AnyRef` kinds the host recognises in a heterogeneous cell/result
138/// (ADR-0033 Phase 6): the `$t` singleton and an i31-boxed index by
139/// identity/kind alone (Phase 3), the struct/array kinds a module export's
140/// signature identifies via [`TypeHandles`] (Phase 6), a closure by its
141/// function-reference field, or `Other` — a kind this host build doesn't
142/// classify, which keeps the `<anyref>` placeholder rather than erroring.
143pub(super) enum AnyRefKind {
144    T,
145    Index(i32),
146    Ratio,
147    Commodity,
148    StringRef,
149    Symbol,
150    /// A nested `$pair` chain. Its own element type is not recoverable at
151    /// runtime (`PairElement` is a compile-time-only tag), so a caller walks
152    /// it with `PairElement::AnyRef`, classifying each of ITS cars in turn.
153    Pair,
154    Entity(nomiscript::EntityKind),
155    /// A `DEFSTRUCT` instance.
156    Struct,
157    /// A closure, by the site of its source.
158    Closure(Option<u32>),
159    Other,
160}
161
162/// Classifies a non-null `anyref` value: `t` by reference identity against
163/// the module's `$t` singleton (ADR-0033 — never by type test, since WasmGC
164/// struct types are structural and an empty struct type is not unique), an
165/// i31 as an index, else a `matches_ty` test against each of `handles`'
166/// struct/array kinds in turn, else `Other`.
167pub(super) fn classify_anyref(
168    mut store: impl AsContextMut,
169    any: Rooted<AnyRef>,
170    handles: &TypeHandles,
171) -> wasmtime::Result<AnyRefKind> {
172    if Rooted::<AnyRef>::ref_eq(&store, &any, &handles.t)? {
173        return Ok(AnyRefKind::T);
174    }
175    if any.is_i31(&mut store)? {
176        let i31 = any.checked_i31(&mut store)?;
177        return Ok(AnyRefKind::Index(i31.get_i32()));
178    }
179    if any.matches_ty(&store, &handles.ratio)? {
180        return Ok(AnyRefKind::Ratio);
181    }
182    if any.matches_ty(&store, &handles.commodity)? {
183        return Ok(AnyRefKind::Commodity);
184    }
185    if any.matches_ty(&store, &handles.string)? {
186        return Ok(AnyRefKind::StringRef);
187    }
188    if any.matches_ty(&store, &handles.symbol)? {
189        return Ok(AnyRefKind::Symbol);
190    }
191    if any.matches_ty(&store, &handles.pair)? {
192        return Ok(AnyRefKind::Pair);
193    }
194    if any.matches_ty(&store, &handles.structure)? {
195        return Ok(AnyRefKind::Struct);
196    }
197    for (kind, ty) in &handles.entities {
198        if any.matches_ty(&store, ty)? {
199            return Ok(AnyRefKind::Entity(*kind));
200        }
201    }
202    let Some(closure) = closure_struct(&mut store, &any)? else {
203        return Ok(AnyRefKind::Other);
204    };
205    Ok(AnyRefKind::Closure(closure_site(&mut store, &closure)?))
206}