Skip to main content

scripting/runtime/
decode.rs

1//! Decoding nomi-eval's anyref results into [`EvalValue`].
2
3use crate::checked_ref::CheckedAnyRef;
4
5pub use scripting_format::MAX_WIRE_LIST_DEPTH;
6
7use super::structure::{
8    InstanceMode, decode_closure, decode_dynamic_anyref, decode_entity, decode_pair, decode_struct,
9};
10use super::type_handles::TypeHandles;
11use wasmtime::{AnyRef, AsContextMut, Rooted, Val};
12
13/// Final value captured by an eval-mode module via the `nomi_capture_*` host
14/// fns. Mirrors the subset of [`nomiscript::WasmType`] variants the compiler
15/// emits as terminal stack types, plus a `Bytes` variant for native fns that
16/// marshal compound data (server-command results via `scripting-format`,
17/// chart SVGs, exported files, etc.). Cons/Vector/Closure/Struct still wait
18/// for the GC migration.
19#[derive(Debug, Clone, PartialEq)]
20pub enum EvalValue {
21    Nil,
22    T,
23    I32(i32),
24    Ratio {
25        numer: i64,
26        denom: i64,
27    },
28    /// Commodity-bearing amount: rational + originating commodity uuid.
29    /// Distinct from `Ratio` so cross-strata arithmetic is rejected by
30    /// the compiler before any wire round-trip. Wire form via
31    /// `format_value`: `(:commodity <ratio> :id "<uuid>")`.
32    Commodity {
33        numer: i64,
34        denom: i64,
35        commodity_hi: i64,
36        commodity_lo: i64,
37    },
38    String(String),
39    Bytes(Vec<u8>),
40    /// A list; an entity is `[Symbol(":label"), Symbol(":field"), value, ...]`.
41    List(Vec<EvalValue>),
42    /// A bare symbol, keywords carrying their leading colon.
43    Symbol(String),
44    /// A `DEFSTRUCT` instance: its identity, which the host reads separately.
45    Instance {
46        serial: u32,
47        layout: u32,
48    },
49    /// A `DEFSTRUCT` instance read into its name and fields, as a print shows
50    /// it; each key is the field name without its keyword colon.
51    Struct(Box<StructView>),
52    /// A closure, printed by the site of its source; a closure whose source
53    /// cannot be carried has none.
54    Closure {
55        site: Option<u32>,
56    },
57    /// A caught condition, printed without its fields.
58    Condition,
59    /// A heap value the host cannot classify.
60    Opaque,
61}
62
63/// The name and fields of a `DEFSTRUCT` instance; boxed in [`EvalValue`] so
64/// the error types carrying a value stay small.
65#[derive(Debug, Clone, PartialEq)]
66pub struct StructView {
67    pub name: String,
68    pub fields: Vec<(String, EvalValue)>,
69}
70
71impl From<EvalValue> for nomiscript::Value {
72    fn from(value: EvalValue) -> Self {
73        match value {
74            EvalValue::Nil => nomiscript::Value::Nil,
75            EvalValue::T => nomiscript::Value::T,
76            EvalValue::I32(n) => nomiscript::Value::Number(nomiscript::Number::Index(i64::from(n))),
77            EvalValue::Ratio { numer, denom } => nomiscript::Value::Number(
78                nomiscript::Number::Scalar(nomiscript::Fraction::new(numer, denom)),
79            ),
80            EvalValue::Commodity {
81                numer,
82                denom,
83                commodity_hi,
84                commodity_lo,
85            } => {
86                // Reassemble the 16-byte uuid from the wasm-side (hi, lo)
87                // i64 pair. Both halves get cast to u64 first so negative
88                // i64 patterns don't sign-extend into bogus high bits.
89                let raw = ((commodity_hi as u64 as u128) << 64) | (commodity_lo as u64 as u128);
90                nomiscript::Value::Commodity {
91                    amount: nomiscript::Fraction::new(numer, denom),
92                    commodity_id: uuid::Uuid::from_u128(raw),
93                }
94            }
95            EvalValue::String(s) => nomiscript::Value::String(s),
96            EvalValue::Symbol(s) => nomiscript::Value::Symbol(s),
97            EvalValue::Struct(view) => nomiscript::Value::Struct {
98                name: view.name,
99                fields: view
100                    .fields
101                    .into_iter()
102                    .map(|(key, value)| (key, nomiscript::Value::from(value)))
103                    .collect(),
104            },
105            EvalValue::Closure { site } => nomiscript::Value::Closure(
106                site.map_or_else(nomiscript::Closure::siteless, |site| {
107                    nomiscript::Closure::new(site, Vec::new())
108                }),
109            ),
110            EvalValue::Condition => nomiscript::Value::Condition,
111            EvalValue::Opaque | EvalValue::Instance { .. } => {
112                nomiscript::Value::String("<anyref>".into())
113            }
114            EvalValue::Bytes(b) => nomiscript::Value::Bytes(b),
115            EvalValue::List(items) => {
116                nomiscript::vec_to_list(items.into_iter().map(nomiscript::Value::from).collect())
117            }
118        }
119    }
120}
121
122/// Decodes nomi-eval's anyref return value into an [`EvalValue`] using
123/// the compile-time-known result type. `None` for the result_ty means
124/// the form was empty / definition-only and the host should see
125/// [`EvalValue::Nil`]. Numeric types (`I32`, `Ratio`, `Commodity`) and
126/// `StringRef` decode directly. `PairRef` walks the chain, decoding
127/// each car per its declared element type. `EntityRef` returns a
128/// placeholder until a downstream consumer needs the structured
129/// shape host-side. Takes any `AsContextMut` so it works with both
130/// `&mut Store<T>` (sync test paths) and `&mut Caller<'_, T>` (async
131/// host fn paths). `handles` resolves the module's `$t` singleton and
132/// struct/array type handles (see [`super::type_handles::resolve_type_handles`]), needed to
133/// classify a heterogeneous `AnyRef` result by identity/kind (ADR-0033).
134pub fn decode_eval_result(
135    mut store: impl AsContextMut,
136    value: Option<Rooted<AnyRef>>,
137    result_ty: Option<nomiscript::WasmType>,
138    handles: &TypeHandles,
139) -> wasmtime::Result<EvalValue> {
140    let Some(ty) = result_ty else {
141        return Ok(EvalValue::Nil);
142    };
143    // Reference-typed results can legitimately be null: empty
144    // `pair<…>` from `list-accounts`, `Option<Rooted<…>>` returns
145    // surfacing not-found / missing-string cases. Surface those as
146    // `Nil` so consumers see an empty-shaped value rather than a
147    // trap. Primitive (I32) returns can't be null and stay strict.
148    let Some(any) = value else {
149        return match ty {
150            nomiscript::WasmType::I32 => Err(wasmtime::Error::msg(
151                "nomi-eval returned null for declared result type i32",
152            )),
153            _ => Ok(EvalValue::Nil),
154        };
155    };
156    decode_anyref(&mut store, any, ty, handles, InstanceMode::Wire)
157}
158
159/// An index result crosses nomi-eval as an `(n, 1)` ratio struct so all 32 bits
160/// survive the anyref slot.
161fn decode_index(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> wasmtime::Result<EvalValue> {
162    let numer = any
163        .checked_struct(&mut store)?
164        .field(&mut store, 0)?
165        .i64()
166        .ok_or_else(|| wasmtime::Error::msg("index result field 0 (numer) is not i64"))?;
167    i32::try_from(numer)
168        .map(EvalValue::I32)
169        .map_err(|_| wasmtime::Error::msg(format!("index result {numer} exceeds i32")))
170}
171
172pub(super) fn decode_anyref(
173    mut store: impl AsContextMut,
174    any: Rooted<AnyRef>,
175    ty: nomiscript::WasmType,
176    handles: &TypeHandles,
177    mode: InstanceMode,
178) -> wasmtime::Result<EvalValue> {
179    use nomiscript::WasmType;
180    match ty {
181        WasmType::I32 => decode_index(&mut store, &any),
182        WasmType::Bool => decode_bool(&mut store, &any, &handles.t),
183        WasmType::Ratio => decode_ratio(&mut store, &any),
184        WasmType::Commodity => decode_commodity(&mut store, &any),
185        WasmType::StringRef => decode_string_ref(&mut store, &any),
186        WasmType::SymbolRef => decode_symbol(&mut store, &any),
187        WasmType::PairRef(elem) => decode_pair(store.as_context_mut(), any, elem, handles, mode, 0),
188        WasmType::EntityRef(kind) => decode_entity(store.as_context_mut(), &any, kind, 0),
189        WasmType::StructRef(_) => decode_struct(store.as_context_mut(), &any, handles, mode, 0),
190        WasmType::Closure(_) => decode_closure(store.as_context_mut(), &any),
191        // Heterogeneous payload (catch-each result cells, `and`/`or`
192        // results, etc.) — classified and decoded by
193        // `decode_dynamic_anyref` (ADR-0033 Phase 6).
194        WasmType::AnyRef => decode_dynamic_anyref(store.as_context_mut(), any, handles, mode, 0),
195    }
196}
197
198/// ADR-0033: `box_bool`'s boxed form is `ref.null` (nil — already handled by
199/// the caller's top-level null check, so `any` here is never that case) /
200/// the `$t` singleton (t), never an i31.
201fn decode_bool(
202    store: impl AsContextMut,
203    any: &Rooted<AnyRef>,
204    t: &Rooted<AnyRef>,
205) -> wasmtime::Result<EvalValue> {
206    if Rooted::<AnyRef>::ref_eq(&store, any, t)? {
207        Ok(EvalValue::T)
208    } else {
209        Err(wasmtime::Error::msg(
210            "boxed bool result is neither null nor the `t` singleton",
211        ))
212    }
213}
214
215/// The one place a guest-written numerator/denominator pair becomes a
216/// [`nomiscript::Fraction`]. Compiled code keeps the denominator positive; any
217/// other is `None`, since normalising its sign can overflow (`i64::MIN`).
218pub(crate) fn guest_fraction(numer: i64, denom: i64) -> Option<nomiscript::Fraction> {
219    (denom > 0).then(|| nomiscript::Fraction::new(numer, denom))
220}
221
222pub(super) fn checked_pair(numer: i64, denom: i64, what: &str) -> wasmtime::Result<(i64, i64)> {
223    guest_fraction(numer, denom)
224        .map(|_| (numer, denom))
225        .ok_or_else(|| wasmtime::Error::msg(format!("{what} has a non-positive denominator")))
226}
227
228pub(super) fn decode_ratio(
229    mut store: impl AsContextMut,
230    any: &Rooted<AnyRef>,
231) -> wasmtime::Result<EvalValue> {
232    let s = any.checked_struct(&mut store)?;
233    let numer = s
234        .field(&mut store, 0)?
235        .i64()
236        .ok_or_else(|| wasmtime::Error::msg("ratio field 0 (numer) is not i64"))?;
237    let denom = s
238        .field(&mut store, 1)?
239        .i64()
240        .ok_or_else(|| wasmtime::Error::msg("ratio field 1 (denom) is not i64"))?;
241    let (numer, denom) = checked_pair(numer, denom, "ratio")?;
242    Ok(EvalValue::Ratio { numer, denom })
243}
244
245/// Field 4 is the unit term (ADR-0028). Null ⇒ ATOMIC single-currency money
246/// (id in fields 2-3). An empty term ⇒ DIMENSIONLESS (money ÷ money, same
247/// currency) and decodes as a plain Number. A non-empty (compound) term —
248/// e.g. money×money — has no host wire form yet.
249pub(super) fn decode_commodity(
250    mut store: impl AsContextMut,
251    any: &Rooted<AnyRef>,
252) -> wasmtime::Result<EvalValue> {
253    let s = any.checked_struct(&mut store)?;
254    let numer = commodity_i64(&mut store, &s, 0)?;
255    let denom = commodity_i64(&mut store, &s, 1)?;
256    let (numer, denom) = checked_pair(numer, denom, "commodity amount")?;
257    match s.field(&mut store, 4)? {
258        Val::AnyRef(None) => {
259            let hi = commodity_i64(&mut store, &s, 2)?;
260            let lo = commodity_i64(&mut store, &s, 3)?;
261            Ok(EvalValue::Commodity {
262                numer,
263                denom,
264                commodity_hi: hi,
265                commodity_lo: lo,
266            })
267        }
268        Val::AnyRef(Some(term)) => {
269            let arr = term.checked_array(&mut store)?;
270            if arr.len(&mut store)? == 0 {
271                Ok(EvalValue::Ratio { numer, denom })
272            } else {
273                Err(wasmtime::Error::msg(
274                    "compound commodity (e.g. money × money) has no host \
275                     representation yet",
276                ))
277            }
278        }
279        _ => Err(wasmtime::Error::msg(
280            "commodity field 4 (unit term) is not a ref",
281        )),
282    }
283}
284
285fn commodity_i64(
286    store: impl AsContextMut,
287    s: &Rooted<wasmtime::StructRef>,
288    slot: usize,
289) -> wasmtime::Result<i64> {
290    s.field(store, slot)?
291        .i64()
292        .ok_or_else(|| wasmtime::Error::msg(format!("commodity field {slot} is not i64")))
293}
294
295pub(super) fn decode_string_ref(
296    mut store: impl AsContextMut,
297    any: &Rooted<AnyRef>,
298) -> wasmtime::Result<EvalValue> {
299    array_text(&mut store, any).map(EvalValue::String)
300}
301
302pub(super) fn decode_symbol(
303    mut store: impl AsContextMut,
304    any: &Rooted<AnyRef>,
305) -> wasmtime::Result<EvalValue> {
306    symbol_name(&mut store, any).map(EvalValue::Symbol)
307}
308
309/// The name array of the `$symbol` in `any`, as text.
310pub(super) fn symbol_name(
311    mut store: impl AsContextMut,
312    any: &Rooted<AnyRef>,
313) -> wasmtime::Result<String> {
314    match any.checked_struct(&mut store)?.field(&mut store, 0)? {
315        Val::AnyRef(Some(name)) => array_text(&mut store, &name),
316        _ => Err(wasmtime::Error::msg("symbol name is not a reference")),
317    }
318}
319
320fn array_text(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> wasmtime::Result<String> {
321    let arr = any.checked_array(&mut store)?;
322    let len = arr.len(&mut store)?;
323    let mut bytes = Vec::with_capacity(len as usize);
324    for i in 0..len {
325        let v = arr.get(&mut store, i)?;
326        let byte = v
327            .i32()
328            .ok_or_else(|| wasmtime::Error::msg("string element is not i32"))?;
329        bytes.push(byte as u8);
330    }
331    String::from_utf8(bytes).map_err(|err| wasmtime::Error::msg(format!("not valid utf-8: {err}")))
332}