1
//! Module type handles and `anyref` kind classification for the decoders.
2

            
3
use crate::checked_ref::CheckedAnyRef;
4

            
5
use super::structure::{closure_site, closure_struct};
6

            
7
use 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.
14
4190
pub fn t_singleton(
15
4190
    mut store: impl AsContextMut,
16
4190
    instance: &Instance,
17
4190
) -> wasmtime::Result<Rooted<AnyRef>> {
18
4190
    let found = instance.get_export(&mut store, "t");
19
4190
    t_from_export(&mut store, found)
20
4190
}
21

            
22
539351
fn t_from_export(
23
539351
    mut store: impl AsContextMut,
24
539351
    export: Option<Extern>,
25
539351
) -> wasmtime::Result<Rooted<AnyRef>> {
26
539351
    let global = export
27
539351
        .and_then(Extern::into_global)
28
        .ok_or_else(|| wasmtime::Error::msg("module does not export the `t` global"))?;
29
539351
    match global.get(&mut store) {
30
539351
        Val::AnyRef(Some(t)) => Ok(t),
31
        _ => Err(wasmtime::Error::msg(
32
            "`t` global is not a non-null internal reference",
33
        )),
34
    }
35
539351
}
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.
46
pub 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`].
59
467271
pub fn resolve_type_handles(
60
467271
    mut store: impl AsContextMut,
61
467271
    instance: &Instance,
62
467271
) -> wasmtime::Result<TypeHandles> {
63
7009065
    resolve_with(&mut store, |store, name| instance.get_export(store, name))
64
467271
}
65

            
66
/// [`resolve_type_handles`] for a host function, which sees its calling
67
/// instance's exports only through the `Caller`.
68
67890
pub fn resolve_caller_type_handles<T>(caller: &mut Caller<'_, T>) -> wasmtime::Result<TypeHandles> {
69
1018350
    resolve_with(caller, |caller, name| caller.get_export(name))
70
67890
}
71

            
72
535161
fn resolve_with<S: AsContextMut>(
73
535161
    store: &mut S,
74
535161
    export: impl Fn(&mut S, &str) -> Option<Extern>,
75
535161
) -> wasmtime::Result<TypeHandles> {
76
7492254
    let heap_type = |store: &mut S, name: &str, take_param: bool| {
77
7492254
        let found = export(store, name);
78
7492254
        exported_func_heap_type(&*store, found, name, take_param)
79
7492254
    };
80
535161
    let found = export(store, "t");
81
535161
    let t = t_from_export(&mut *store, found)?;
82
535161
    let ratio = heap_type(store, "ratio_new", false)?;
83
535161
    let commodity = heap_type(store, "commodity_new", false)?;
84
535161
    let pair = heap_type(store, "pair_new", false)?;
85
535161
    let string = heap_type(store, "string_eq", true)?;
86
535161
    let symbol = heap_type(store, "symbol_new", false)?;
87
535161
    let structure = heap_type(store, "struct_new", false)?;
88
535161
    let mut entities = nomiscript::ENTITY_LAYOUTS
89
535161
        .iter()
90
3746127
        .map(|layout| {
91
3746127
            let name = format!("alloc_{}", layout.kind.type_name());
92
3746127
            heap_type(store, &name, false).map(|ty| (layout.kind, ty))
93
3746127
        })
94
        .collect::<wasmtime::Result<Vec<_>>>()?;
95
535161
    entities.push((
96
535161
        nomiscript::EntityKind::Condition,
97
535161
        heap_type(store, "condition_new", false)?,
98
    ));
99
535161
    Ok(TypeHandles {
100
535161
        t,
101
535161
        ratio,
102
535161
        commodity,
103
535161
        pair,
104
535161
        string,
105
535161
        symbol,
106
535161
        structure,
107
535161
        entities,
108
535161
    })
109
535161
}
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.
115
7492254
fn exported_func_heap_type(
116
7492254
    store: impl AsContext,
117
7492254
    export: Option<Extern>,
118
7492254
    name: &str,
119
7492254
    take_param: bool,
120
7492254
) -> wasmtime::Result<HeapType> {
121
7492254
    let func = export
122
7492254
        .and_then(Extern::into_func)
123
        .ok_or_else(|| wasmtime::Error::msg(format!("module does not export `{name}`")))?;
124
7492254
    let ty = func.ty(&store);
125
7492254
    let slot = if take_param {
126
535161
        ty.params().next()
127
    } else {
128
6957093
        ty.results().next()
129
    };
130
7492254
    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
7492254
}
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.
143
pub(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`.
167
7871757
pub(super) fn classify_anyref(
168
7871757
    mut store: impl AsContextMut,
169
7871757
    any: Rooted<AnyRef>,
170
7871757
    handles: &TypeHandles,
171
7871757
) -> wasmtime::Result<AnyRefKind> {
172
7871757
    if Rooted::<AnyRef>::ref_eq(&store, &any, &handles.t)? {
173
259105
        return Ok(AnyRefKind::T);
174
7612652
    }
175
7612652
    if any.is_i31(&mut store)? {
176
5000911
        let i31 = any.checked_i31(&mut store)?;
177
5000911
        return Ok(AnyRefKind::Index(i31.get_i32()));
178
2611741
    }
179
2611741
    if any.matches_ty(&store, &handles.ratio)? {
180
9011
        return Ok(AnyRefKind::Ratio);
181
2602730
    }
182
2602730
    if any.matches_ty(&store, &handles.commodity)? {
183
3060
        return Ok(AnyRefKind::Commodity);
184
2599670
    }
185
2599670
    if any.matches_ty(&store, &handles.string)? {
186
119944
        return Ok(AnyRefKind::StringRef);
187
2479726
    }
188
2479726
    if any.matches_ty(&store, &handles.symbol)? {
189
88761
        return Ok(AnyRefKind::Symbol);
190
2390965
    }
191
2390965
    if any.matches_ty(&store, &handles.pair)? {
192
108355
        return Ok(AnyRefKind::Pair);
193
2282610
    }
194
2282610
    if any.matches_ty(&store, &handles.structure)? {
195
2192816
        return Ok(AnyRefKind::Struct);
196
89794
    }
197
89794
    for (kind, ty) in &handles.entities {
198
712040
        if any.matches_ty(&store, ty)? {
199
3212
            return Ok(AnyRefKind::Entity(*kind));
200
708828
        }
201
    }
202
86582
    let Some(closure) = closure_struct(&mut store, &any)? else {
203
2540
        return Ok(AnyRefKind::Other);
204
    };
205
84042
    Ok(AnyRefKind::Closure(closure_site(&mut store, &closure)?))
206
7871757
}