1
//! Host side of the guest ABI: allocating GC refs for the guest and reading its arguments.
2

            
3
use uuid::Uuid;
4

            
5
use super::decode::checked_pair;
6

            
7
use crate::checked_ref::CheckedAnyRef;
8

            
9
use 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.
21
2122
pub async fn alloc_commodity_ref<T>(
22
2122
    caller: &mut Caller<'_, T>,
23
2122
    numer: i64,
24
2122
    denom: i64,
25
2122
    commodity_id: Uuid,
26
2122
) -> wasmtime::Result<Rooted<StructRef>>
27
2122
where
28
2122
    T: Send,
29
2122
{
30
2122
    let commodity_new = caller
31
2122
        .get_export("commodity_new")
32
2121
        .and_then(|e| e.into_func())
33
1
        .ok_or_else(|| {
34
1
            wasmtime::Error::msg(
35
1
                "module missing 'commodity_new' export — host commodity allocation \
36
1
                 requires the nomiscript compiler skeleton's exported commodity_new",
37
1
            )
38
1
        })?;
39
2121
    let (hi, lo) = commodity_id.as_u64_pair();
40
2121
    let mut results = [Val::AnyRef(None)];
41
2121
    commodity_new
42
2121
        .call_async(
43
2121
            caller.as_context_mut(),
44
2121
            &[
45
2121
                Val::I64(numer),
46
2121
                Val::I64(denom),
47
2121
                Val::I64(hi as i64),
48
2121
                Val::I64(lo as i64),
49
2121
            ],
50
2121
            &mut results,
51
2121
        )
52
2121
        .await?;
53
2121
    match &results[0] {
54
2121
        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
2122
}
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`.
68
396269
pub fn alloc_string_ref<T>(
69
396269
    caller: &mut Caller<'_, T>,
70
396269
    bytes: &[u8],
71
396269
) -> wasmtime::Result<Rooted<wasmtime::ArrayRef>> {
72
396269
    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
396269
    let ty = wasmtime::ArrayType::new(&engine, FieldType::new(Mutability::Var, StorageType::I8));
78
396269
    let pre = wasmtime::ArrayRefPre::new(caller.as_context_mut(), ty);
79
70290318
    let vals: Vec<Val> = bytes.iter().map(|b| Val::I32(i32::from(*b))).collect();
80
396269
    wasmtime::ArrayRef::new_fixed(caller.as_context_mut(), &pre, &vals)
81
396269
}
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.
87
3200
pub fn alloc_ratio_ref<T>(
88
3200
    caller: &mut Caller<'_, T>,
89
3200
    numer: i64,
90
3200
    denom: i64,
91
3200
) -> wasmtime::Result<Rooted<StructRef>> {
92
3200
    let engine = caller.engine().clone();
93
3200
    let ty = StructType::new(
94
3200
        &engine,
95
3200
        std::iter::repeat_n(
96
3200
            FieldType::new(Mutability::Const, StorageType::ValType(ValType::I64)),
97
3200
            2,
98
3200
        ),
99
3200
    )?;
100
3200
    let pre = StructRefPre::new(caller.as_context_mut(), ty);
101
3200
    StructRef::new(
102
3200
        caller.as_context_mut(),
103
3200
        &pre,
104
3200
        &[Val::I64(numer), Val::I64(denom)],
105
3200
    )
106
3200
}
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`).
121
44112
pub async fn alloc_entity_via_export<T>(
122
44112
    caller: &mut Caller<'_, T>,
123
44112
    export_name: &str,
124
44112
    args: &[Val],
125
44112
) -> wasmtime::Result<Rooted<StructRef>>
126
44112
where
127
44112
    T: Send,
128
44112
{
129
44112
    let alloc = caller
130
44112
        .get_export(export_name)
131
44112
        .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
44112
    let mut results = [Val::AnyRef(None)];
139
44112
    alloc
140
44112
        .call_async(caller.as_context_mut(), args, &mut results)
141
44112
        .await?;
142
44112
    let new_entity_any = match &results[0] {
143
44112
        Val::AnyRef(any) => *any,
144
        _ => {
145
            return Err(wasmtime::Error::msg(format!(
146
                "{export_name} returned non-anyref Val variant"
147
            )));
148
        }
149
    };
150
44112
    new_entity_any
151
        .ok_or_else(|| {
152
            wasmtime::Error::msg(format!(
153
                "{export_name} returned null when allocating entity"
154
            ))
155
        })?
156
44112
        .checked_struct(caller.as_context_mut())
157
44112
}
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.
165
420628
pub fn read_string_arg<T>(
166
420628
    caller: &mut Caller<'_, T>,
167
420628
    arg: Option<Rooted<wasmtime::ArrayRef>>,
168
420628
) -> wasmtime::Result<Option<String>> {
169
420628
    let Some(arr) = arg else {
170
        return Ok(None);
171
    };
172
420628
    let len = arr.len(caller.as_context_mut())?;
173
420628
    let mut bytes = Vec::with_capacity(len as usize);
174
420628
    for i in 0..len {
175
16762080
        let val = arr.get(caller.as_context_mut(), i)?;
176
16762080
        let byte_i32 = val
177
16762080
            .i32()
178
            .ok_or_else(|| wasmtime::Error::msg("string arg element is not i32"))?;
179
16762080
        bytes.push(byte_i32 as u8);
180
    }
181
420628
    String::from_utf8(bytes)
182
420628
        .map(Some)
183
        .map_err(|err| wasmtime::Error::msg(format!("string arg is not valid UTF-8: {err}")))
184
420628
}
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.
190
323
pub fn read_commodity_arg<T>(
191
323
    caller: &mut Caller<'_, T>,
192
323
    arg: Option<Rooted<StructRef>>,
193
323
) -> wasmtime::Result<Option<(i64, i64, Uuid)>> {
194
323
    let Some(s) = arg else {
195
        return Ok(None);
196
    };
197
1292
    let read_i64 = |c: &mut Caller<'_, T>, idx: usize| -> wasmtime::Result<i64> {
198
1292
        let v = s.field(c.as_context_mut(), idx)?;
199
1292
        v.i64()
200
            .ok_or_else(|| wasmtime::Error::msg(format!("commodity field {idx} is not i64")))
201
1292
    };
202
323
    let (numer, denom) = checked_pair(read_i64(caller, 0)?, read_i64(caller, 1)?, "commodity")?;
203
323
    let hi = read_i64(caller, 2)?;
204
323
    let lo = read_i64(caller, 3)?;
205
323
    let raw = ((hi as u64 as u128) << 64) | (lo as u64 as u128);
206
323
    Ok(Some((numer, denom, Uuid::from_u128(raw))))
207
323
}
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).
213
11718
pub fn read_ratio_arg<T>(
214
11718
    caller: &mut Caller<'_, T>,
215
11718
    arg: Option<Rooted<StructRef>>,
216
11718
) -> wasmtime::Result<Option<(i64, i64)>> {
217
11718
    let Some(s) = arg else {
218
        return Ok(None);
219
    };
220
11718
    let numer = s
221
11718
        .field(caller.as_context_mut(), 0)?
222
        .i64()
223
        .ok_or_else(|| wasmtime::Error::msg("ratio field 0 (numer) is not i64"))?;
224
11718
    let denom = s
225
11718
        .field(caller.as_context_mut(), 1)?
226
        .i64()
227
        .ok_or_else(|| wasmtime::Error::msg("ratio field 1 (denom) is not i64"))?;
228
11718
    checked_pair(numer, denom, "ratio").map(Some)
229
11718
}
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.
237
23436
pub fn read_entity_string_field<T>(
238
23436
    caller: &mut Caller<'_, T>,
239
23436
    arg: Option<Rooted<StructRef>>,
240
23436
    kind: nomiscript::EntityKind,
241
23436
    field_name: &str,
242
23436
) -> wasmtime::Result<Option<String>> {
243
23436
    let Some(s) = arg else {
244
        return Ok(None);
245
    };
246
23436
    read_entity_string_field_ctx(caller.as_context_mut(), s, kind, field_name).map(Some)
247
23436
}
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.
252
23439
pub fn read_entity_string_field_ctx(
253
23439
    mut store: impl AsContextMut,
254
23439
    entity: Rooted<StructRef>,
255
23439
    kind: nomiscript::EntityKind,
256
23439
    field_name: &str,
257
23439
) -> wasmtime::Result<String> {
258
23439
    let layout = nomiscript::entity_layout(kind)
259
        .ok_or_else(|| wasmtime::Error::msg(format!("no entity layout for {kind:?}")))?;
260
23439
    let idx = layout
261
23439
        .fields
262
23439
        .iter()
263
23443
        .position(|f| f.name == field_name && f.kind == nomiscript::EntityFieldKind::String)
264
1
        .ok_or_else(|| {
265
1
            wasmtime::Error::msg(format!(
266
1
                "entity {kind:?} has no String field named '{field_name}'"
267
1
            ))
268
1
        })?;
269
23438
    let arr = match entity.field(store.as_context_mut(), idx)? {
270
23438
        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
23438
    let len = arr.len(store.as_context_mut())?;
278
23438
    let mut bytes = Vec::with_capacity(len as usize);
279
23438
    for i in 0..len {
280
843713
        let byte = arr
281
843713
            .get(store.as_context_mut(), i)?
282
            .i32()
283
            .ok_or_else(|| wasmtime::Error::msg("entity string element is not i32"))?;
284
843713
        bytes.push(byte as u8);
285
    }
286
23438
    String::from_utf8(bytes)
287
        .map_err(|err| wasmtime::Error::msg(format!("entity string field not utf-8: {err}")))
288
23439
}
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)`.
311
49153
pub async fn alloc_pair_chain<T>(
312
49153
    caller: &mut Caller<'_, T>,
313
49153
    items: impl IntoIterator<Item = Option<Rooted<AnyRef>>>,
314
49153
) -> wasmtime::Result<Option<Rooted<StructRef>>>
315
49153
where
316
49153
    T: Send,
317
49153
{
318
49153
    let pair_new = caller
319
49153
        .get_export("pair_new")
320
49152
        .and_then(|e| e.into_func())
321
1
        .ok_or_else(|| {
322
1
            wasmtime::Error::msg(
323
1
                "module missing 'pair_new' export — host pair allocation requires \
324
1
                 the nomiscript compiler skeleton's exported pair_new",
325
1
            )
326
1
        })?;
327

            
328
49152
    let items: Vec<Option<Rooted<AnyRef>>> = items.into_iter().collect();
329
49152
    let mut head: Option<Rooted<StructRef>> = None;
330
49152
    for item in items.into_iter().rev() {
331
196519
        let cdr_any = head.map(|p| p.to_anyref());
332
196519
        let mut results = [Val::AnyRef(None)];
333
196519
        pair_new
334
196519
            .call_async(
335
196519
                caller.as_context_mut(),
336
196519
                &[Val::AnyRef(item), Val::AnyRef(cdr_any)],
337
196519
                &mut results,
338
196519
            )
339
196519
            .await?;
340
196519
        let new_pair_any = match &results[0] {
341
196519
            Val::AnyRef(any) => *any,
342
            _ => {
343
                return Err(wasmtime::Error::msg(
344
                    "pair_new returned non-anyref Val variant",
345
                ));
346
            }
347
        };
348
196519
        head = Some(
349
196519
            new_pair_any
350
                .ok_or_else(|| {
351
                    wasmtime::Error::msg("pair_new returned null when chaining elements")
352
                })?
353
196519
                .checked_struct(caller.as_context_mut())?,
354
        );
355
    }
356
49152
    Ok(head)
357
49153
}