Skip to main content

scripting/runtime/
abi.rs

1//! Host side of the guest ABI: allocating GC refs for the guest and reading its arguments.
2
3use uuid::Uuid;
4
5use super::decode::checked_pair;
6
7use crate::checked_ref::CheckedAnyRef;
8
9use wasmtime::{
10    AnyRef, AsContextMut, Caller, FieldType, Mutability, Rooted, StorageType, StructRef,
11    StructRefPre, StructType, Val, ValType,
12};
13
14/// Allocates an ATOMIC `$commodity` value by re-entering the guest's exported
15/// `commodity_new` with the four i64 components (numer, denom, commodity_hi,
16/// commodity_lo). Since ADR-0028 E0 the `$commodity` struct carries a 5th
17/// `(ref null $unit_term)` field; the host must NOT construct that ref-bearing
18/// struct itself, so it delegates to the guest helper (which sets the term to
19/// null = atomic) — the same re-entry pattern as `alloc_pair_chain` / the
20/// entity allocators. Async because it calls back into the wasm instance.
21pub async fn alloc_commodity_ref<T>(
22    caller: &mut Caller<'_, T>,
23    numer: i64,
24    denom: i64,
25    commodity_id: Uuid,
26) -> wasmtime::Result<Rooted<StructRef>>
27where
28    T: Send,
29{
30    let commodity_new = caller
31        .get_export("commodity_new")
32        .and_then(|e| e.into_func())
33        .ok_or_else(|| {
34            wasmtime::Error::msg(
35                "module missing 'commodity_new' export — host commodity allocation \
36                 requires the nomiscript compiler skeleton's exported commodity_new",
37            )
38        })?;
39    let (hi, lo) = commodity_id.as_u64_pair();
40    let mut results = [Val::AnyRef(None)];
41    commodity_new
42        .call_async(
43            caller.as_context_mut(),
44            &[
45                Val::I64(numer),
46                Val::I64(denom),
47                Val::I64(hi as i64),
48                Val::I64(lo as i64),
49            ],
50            &mut results,
51        )
52        .await?;
53    match &results[0] {
54        Val::AnyRef(Some(any)) => any.checked_struct(caller.as_context_mut()),
55        Val::AnyRef(None) => Err(wasmtime::Error::msg("commodity_new returned null")),
56        _ => Err(wasmtime::Error::msg(
57            "commodity_new returned non-anyref Val variant",
58        )),
59    }
60}
61
62/// Allocates a `$i8_array` wasm array holding `bytes` and returns a rooted
63/// reference. Single allocation; callers can format UUID/name payloads into
64/// a reused `Vec<u8>` and ship the bytes without an intermediate `String`.
65/// Engine canonicalizes the i8 array type so the host-side allocation
66/// matches the guest's `(array i8)` declaration in
67/// `CompileContext::new_skeleton`.
68pub fn alloc_string_ref<T>(
69    caller: &mut Caller<'_, T>,
70    bytes: &[u8],
71) -> wasmtime::Result<Rooted<wasmtime::ArrayRef>> {
72    let engine = caller.engine().clone();
73    // Mutability must match the compiler's `register_type("i8_array")` field
74    // declaration (mutable: true) — engine canonicalization compares the
75    // mutability bit, so a `Const` array type would fail the guest's
76    // `ref.cast (ref $i8_array)` even though the storage type matches.
77    let ty = wasmtime::ArrayType::new(&engine, FieldType::new(Mutability::Var, StorageType::I8));
78    let pre = wasmtime::ArrayRefPre::new(caller.as_context_mut(), ty);
79    let vals: Vec<Val> = bytes.iter().map(|b| Val::I32(i32::from(*b))).collect();
80    wasmtime::ArrayRef::new_fixed(caller.as_context_mut(), &pre, &vals)
81}
82
83/// Allocates a `$ratio` wasm struct (2 i64 fields: numer, denom). Mirrors
84/// `alloc_commodity_ref` for the Ratio numeric stratum — used when a host
85/// fn returns a typed Ratio without going through the synthesized
86/// `ratio_new` wrap.
87pub fn alloc_ratio_ref<T>(
88    caller: &mut Caller<'_, T>,
89    numer: i64,
90    denom: i64,
91) -> wasmtime::Result<Rooted<StructRef>> {
92    let engine = caller.engine().clone();
93    let ty = StructType::new(
94        &engine,
95        std::iter::repeat_n(
96            FieldType::new(Mutability::Const, StorageType::ValType(ValType::I64)),
97            2,
98        ),
99    )?;
100    let pre = StructRefPre::new(caller.as_context_mut(), ty);
101    StructRef::new(
102        caller.as_context_mut(),
103        &pre,
104        &[Val::I64(numer), Val::I64(denom)],
105    )
106}
107
108/// Allocates an entity wasm struct (`$account`, `$commodity_entity`, etc) by
109/// re-entering the module's exported `alloc_<kind>` function. The host can't
110/// freshly construct an entity `StructType` via `StructType::new` — fields
111/// like `(ref null $i8_array)` reference concrete type indices that engine
112/// canonicalization compares by identity, so any abstract `anyref`-typed
113/// fresh declaration produces a structurally distinct (and uncastable) type.
114/// Re-entry through the guest's own allocator (registered in
115/// `CompileContext::register_entity_allocators`) sidesteps the issue: each
116/// call returns a struct ref of the exact `$<kind>` type the subsequent
117/// `ref.cast (ref $<kind>)` in the consuming form accepts.
118///
119/// Args are passed in declaration order matching the entity's struct
120/// field layout (see `CompileContext::new_skeleton`).
121pub async fn alloc_entity_via_export<T>(
122    caller: &mut Caller<'_, T>,
123    export_name: &str,
124    args: &[Val],
125) -> wasmtime::Result<Rooted<StructRef>>
126where
127    T: Send,
128{
129    let alloc = caller
130        .get_export(export_name)
131        .and_then(|e| e.into_func())
132        .ok_or_else(|| {
133            wasmtime::Error::msg(format!(
134                "module missing '{export_name}' export — host entity allocation requires \
135                 the nomiscript compiler skeleton's exported alloc_<kind> function"
136            ))
137        })?;
138    let mut results = [Val::AnyRef(None)];
139    alloc
140        .call_async(caller.as_context_mut(), args, &mut results)
141        .await?;
142    let new_entity_any = match &results[0] {
143        Val::AnyRef(any) => *any,
144        _ => {
145            return Err(wasmtime::Error::msg(format!(
146                "{export_name} returned non-anyref Val variant"
147            )));
148        }
149    };
150    new_entity_any
151        .ok_or_else(|| {
152            wasmtime::Error::msg(format!(
153                "{export_name} returned null when allocating entity"
154            ))
155        })?
156        .checked_struct(caller.as_context_mut())
157}
158
159/// Reads a `$i8_array` arg ref into a Rust `String`. `None` is returned for
160/// null refs (the wasm-level `(ref null $i8_array)` param's null state). The
161/// underlying byte storage is i8 (mutable per `register_type("i8_array")`),
162/// so each element is read via `array.get_u` semantics and assembled into a
163/// `Vec<u8>` then UTF-8 validated. Non-UTF-8 bytes surface as a structured
164/// trap rather than a silent replacement.
165pub fn read_string_arg<T>(
166    caller: &mut Caller<'_, T>,
167    arg: Option<Rooted<wasmtime::ArrayRef>>,
168) -> wasmtime::Result<Option<String>> {
169    let Some(arr) = arg else {
170        return Ok(None);
171    };
172    let len = arr.len(caller.as_context_mut())?;
173    let mut bytes = Vec::with_capacity(len as usize);
174    for i in 0..len {
175        let val = arr.get(caller.as_context_mut(), i)?;
176        let byte_i32 = val
177            .i32()
178            .ok_or_else(|| wasmtime::Error::msg("string arg element is not i32"))?;
179        bytes.push(byte_i32 as u8);
180    }
181    String::from_utf8(bytes)
182        .map(Some)
183        .map_err(|err| wasmtime::Error::msg(format!("string arg is not valid UTF-8: {err}")))
184}
185
186/// Reads a `$commodity` arg ref into its (numer, denom, commodity_id)
187/// components. Mirrors `read_string_arg` for the Commodity numeric stratum:
188/// fields 0-1 are numer/denom, fields 2-3 are the UUID halves. `None`
189/// returns for a null ref; bad shape surfaces as a structured trap.
190pub fn read_commodity_arg<T>(
191    caller: &mut Caller<'_, T>,
192    arg: Option<Rooted<StructRef>>,
193) -> wasmtime::Result<Option<(i64, i64, Uuid)>> {
194    let Some(s) = arg else {
195        return Ok(None);
196    };
197    let read_i64 = |c: &mut Caller<'_, T>, idx: usize| -> wasmtime::Result<i64> {
198        let v = s.field(c.as_context_mut(), idx)?;
199        v.i64()
200            .ok_or_else(|| wasmtime::Error::msg(format!("commodity field {idx} is not i64")))
201    };
202    let (numer, denom) = checked_pair(read_i64(caller, 0)?, read_i64(caller, 1)?, "commodity")?;
203    let hi = read_i64(caller, 2)?;
204    let lo = read_i64(caller, 3)?;
205    let raw = ((hi as u64 as u128) << 64) | (lo as u64 as u128);
206    Ok(Some((numer, denom, Uuid::from_u128(raw))))
207}
208
209/// Reads a `$ratio` arg ref into its `(numer, denom)` components. `None`
210/// returns for a null ref; a non-positive denominator is a structured trap.
211/// Mirrors `read_commodity_arg` for the
212/// dimensionless Scalar stratum (a `draft-split` amount).
213pub fn read_ratio_arg<T>(
214    caller: &mut Caller<'_, T>,
215    arg: Option<Rooted<StructRef>>,
216) -> wasmtime::Result<Option<(i64, i64)>> {
217    let Some(s) = arg else {
218        return Ok(None);
219    };
220    let numer = s
221        .field(caller.as_context_mut(), 0)?
222        .i64()
223        .ok_or_else(|| wasmtime::Error::msg("ratio field 0 (numer) is not i64"))?;
224    let denom = s
225        .field(caller.as_context_mut(), 1)?
226        .i64()
227        .ok_or_else(|| wasmtime::Error::msg("ratio field 1 (denom) is not i64"))?;
228    checked_pair(numer, denom, "ratio").map(Some)
229}
230
231/// Reads a named String field from an entity struct arg, resolving the field's
232/// slot index from [`nomiscript::entity_layout`](fn@nomiscript::entity_layout) (the single source of struct
233/// slot order). `None` returns for a null ref. Errors if the kind has no
234/// layout, the named field is absent or non-String, or the slot is not an
235/// `$i8_array`. This is how the draft natives read e.g. an account's `id`
236/// (slot 0) from a `(get-account …)` entity ref passed as an argument.
237pub fn read_entity_string_field<T>(
238    caller: &mut Caller<'_, T>,
239    arg: Option<Rooted<StructRef>>,
240    kind: nomiscript::EntityKind,
241    field_name: &str,
242) -> wasmtime::Result<Option<String>> {
243    let Some(s) = arg else {
244        return Ok(None);
245    };
246    read_entity_string_field_ctx(caller.as_context_mut(), s, kind, field_name).map(Some)
247}
248
249/// Context-based core of [`read_entity_string_field`], split out so it is
250/// unit-testable without a `Caller` (tests hold a bare `Store`). Resolves the
251/// field's slot from the entity layout and reads it as an `$i8_array` string.
252pub fn read_entity_string_field_ctx(
253    mut store: impl AsContextMut,
254    entity: Rooted<StructRef>,
255    kind: nomiscript::EntityKind,
256    field_name: &str,
257) -> wasmtime::Result<String> {
258    let layout = nomiscript::entity_layout(kind)
259        .ok_or_else(|| wasmtime::Error::msg(format!("no entity layout for {kind:?}")))?;
260    let idx = layout
261        .fields
262        .iter()
263        .position(|f| f.name == field_name && f.kind == nomiscript::EntityFieldKind::String)
264        .ok_or_else(|| {
265            wasmtime::Error::msg(format!(
266                "entity {kind:?} has no String field named '{field_name}'"
267            ))
268        })?;
269    let arr = match entity.field(store.as_context_mut(), idx)? {
270        Val::AnyRef(Some(any)) => any.checked_array(store.as_context_mut())?,
271        _ => {
272            return Err(wasmtime::Error::msg(format!(
273                "entity {kind:?} field '{field_name}' (slot {idx}) is not an i8_array"
274            )));
275        }
276    };
277    let len = arr.len(store.as_context_mut())?;
278    let mut bytes = Vec::with_capacity(len as usize);
279    for i in 0..len {
280        let byte = arr
281            .get(store.as_context_mut(), i)?
282            .i32()
283            .ok_or_else(|| wasmtime::Error::msg("entity string element is not i32"))?;
284        bytes.push(byte as u8);
285    }
286    String::from_utf8(bytes)
287        .map_err(|err| wasmtime::Error::msg(format!("entity string field not utf-8: {err}")))
288}
289
290/// Folds an iterator of GC-ref elements into a `$pair` chain by re-entering
291/// the wasm module via its exported `pair_new` function. Returns the chain
292/// head, or `None` if the iterator is empty.
293///
294/// `$pair` is the self-recursive cell type (`{anyref car, ref null $pair
295/// cdr}`) declared by `CompileContext::new_skeleton`. The host can't freshly
296/// construct that StructType via `StructType::new` — the cdr field references
297/// the type itself, which `StructType::new` doesn't model. Instead this
298/// helper reaches into the module's own type system: `pair_new` is already
299/// emitted by the compiler skeleton as `register_function("pair_new", ...)`
300/// which adds it to the export table, so the host fn body can pull it from
301/// `Caller::get_export` and invoke it per element. Each call produces a
302/// `Rooted<StructRef>` of the exact `$pair` type that subsequent `ref.cast
303/// (ref null $pair)` operations in the guest accept.
304///
305/// Items are folded right-to-left so the first element of the iterator
306/// ends up at the chain head — `[a, b, c]` → `(a . (b . (c . nil)))`. An
307/// element is `Option`-nullable: `None` builds a `nil` car (ADR-0033: a
308/// list consumer accepts an `AnyRef` cell that may be nil), not a dropped
309/// element — `catch_each::build_ok_cell` relies on this to keep `(ok nil)`
310/// a two-element list rather than nil-punning it to `(ok)`.
311pub async fn alloc_pair_chain<T>(
312    caller: &mut Caller<'_, T>,
313    items: impl IntoIterator<Item = Option<Rooted<AnyRef>>>,
314) -> wasmtime::Result<Option<Rooted<StructRef>>>
315where
316    T: Send,
317{
318    let pair_new = caller
319        .get_export("pair_new")
320        .and_then(|e| e.into_func())
321        .ok_or_else(|| {
322            wasmtime::Error::msg(
323                "module missing 'pair_new' export — host pair allocation requires \
324                 the nomiscript compiler skeleton's exported pair_new",
325            )
326        })?;
327
328    let items: Vec<Option<Rooted<AnyRef>>> = items.into_iter().collect();
329    let mut head: Option<Rooted<StructRef>> = None;
330    for item in items.into_iter().rev() {
331        let cdr_any = head.map(|p| p.to_anyref());
332        let mut results = [Val::AnyRef(None)];
333        pair_new
334            .call_async(
335                caller.as_context_mut(),
336                &[Val::AnyRef(item), Val::AnyRef(cdr_any)],
337                &mut results,
338            )
339            .await?;
340        let new_pair_any = match &results[0] {
341            Val::AnyRef(any) => *any,
342            _ => {
343                return Err(wasmtime::Error::msg(
344                    "pair_new returned non-anyref Val variant",
345                ));
346            }
347        };
348        head = Some(
349            new_pair_any
350                .ok_or_else(|| {
351                    wasmtime::Error::msg("pair_new returned null when chaining elements")
352                })?
353                .checked_struct(caller.as_context_mut())?,
354        );
355    }
356    Ok(head)
357}