1
//! Decoding nomi-eval's anyref results into [`EvalValue`].
2

            
3
use crate::checked_ref::CheckedAnyRef;
4

            
5
pub use scripting_format::MAX_WIRE_LIST_DEPTH;
6

            
7
use super::structure::{
8
    InstanceMode, decode_closure, decode_dynamic_anyref, decode_entity, decode_pair, decode_struct,
9
};
10
use super::type_handles::TypeHandles;
11
use 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)]
20
pub 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)]
66
pub struct StructView {
67
    pub name: String,
68
    pub fields: Vec<(String, EvalValue)>,
69
}
70

            
71
impl From<EvalValue> for nomiscript::Value {
72
4916033
    fn from(value: EvalValue) -> Self {
73
4916033
        match value {
74
53775
            EvalValue::Nil => nomiscript::Value::Nil,
75
45804
            EvalValue::T => nomiscript::Value::T,
76
3325385
            EvalValue::I32(n) => nomiscript::Value::Number(nomiscript::Number::Index(i64::from(n))),
77
31732
            EvalValue::Ratio { numer, denom } => nomiscript::Value::Number(
78
31732
                nomiscript::Number::Scalar(nomiscript::Fraction::new(numer, denom)),
79
31732
            ),
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
1340
                let raw = ((commodity_hi as u64 as u128) << 64) | (commodity_lo as u64 as u128);
90
1340
                nomiscript::Value::Commodity {
91
1340
                    amount: nomiscript::Fraction::new(numer, denom),
92
1340
                    commodity_id: uuid::Uuid::from_u128(raw),
93
1340
                }
94
            }
95
482460
            EvalValue::String(s) => nomiscript::Value::String(s),
96
477147
            EvalValue::Symbol(s) => nomiscript::Value::Symbol(s),
97
            EvalValue::Struct(view) => nomiscript::Value::Struct {
98
97851
                name: view.name,
99
97851
                fields: view
100
97851
                    .fields
101
97851
                    .into_iter()
102
97851
                    .map(|(key, value)| (key, nomiscript::Value::from(value)))
103
                    .collect(),
104
            },
105
            EvalValue::Closure { site } => nomiscript::Value::Closure(
106
22422
                site.map_or_else(nomiscript::Closure::siteless, |site| {
107
19191
                    nomiscript::Closure::new(site, Vec::new())
108
19191
                }),
109
            ),
110
3611
            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
374506
                nomiscript::vec_to_list(items.into_iter().map(nomiscript::Value::from).collect())
117
            }
118
        }
119
4916033
    }
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).
134
216454
pub fn decode_eval_result(
135
216454
    mut store: impl AsContextMut,
136
216454
    value: Option<Rooted<AnyRef>>,
137
216454
    result_ty: Option<nomiscript::WasmType>,
138
216454
    handles: &TypeHandles,
139
216454
) -> wasmtime::Result<EvalValue> {
140
216454
    let Some(ty) = result_ty else {
141
2152
        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
214302
    let Some(any) = value else {
149
8070
        return match ty {
150
            nomiscript::WasmType::I32 => Err(wasmtime::Error::msg(
151
                "nomi-eval returned null for declared result type i32",
152
            )),
153
8070
            _ => Ok(EvalValue::Nil),
154
        };
155
    };
156
206232
    decode_anyref(&mut store, any, ty, handles, InstanceMode::Wire)
157
216454
}
158

            
159
/// An index result crosses nomi-eval as an `(n, 1)` ratio struct so all 32 bits
160
/// survive the anyref slot.
161
74601
fn decode_index(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> wasmtime::Result<EvalValue> {
162
74601
    let numer = any
163
74601
        .checked_struct(&mut store)?
164
74601
        .field(&mut store, 0)?
165
        .i64()
166
        .ok_or_else(|| wasmtime::Error::msg("index result field 0 (numer) is not i64"))?;
167
74601
    i32::try_from(numer)
168
74601
        .map(EvalValue::I32)
169
        .map_err(|_| wasmtime::Error::msg(format!("index result {numer} exceeds i32")))
170
74601
}
171

            
172
219584
pub(super) fn decode_anyref(
173
219584
    mut store: impl AsContextMut,
174
219584
    any: Rooted<AnyRef>,
175
219584
    ty: nomiscript::WasmType,
176
219584
    handles: &TypeHandles,
177
219584
    mode: InstanceMode,
178
219584
) -> wasmtime::Result<EvalValue> {
179
    use nomiscript::WasmType;
180
219584
    match ty {
181
74601
        WasmType::I32 => decode_index(&mut store, &any),
182
10517
        WasmType::Bool => decode_bool(&mut store, &any, &handles.t),
183
4814
        WasmType::Ratio => decode_ratio(&mut store, &any),
184
490
        WasmType::Commodity => decode_commodity(&mut store, &any),
185
71614
        WasmType::StringRef => decode_string_ref(&mut store, &any),
186
249
        WasmType::SymbolRef => decode_symbol(&mut store, &any),
187
17279
        WasmType::PairRef(elem) => decode_pair(store.as_context_mut(), any, elem, handles, mode, 0),
188
483
        WasmType::EntityRef(kind) => decode_entity(store.as_context_mut(), &any, kind, 0),
189
6
        WasmType::StructRef(_) => decode_struct(store.as_context_mut(), &any, handles, mode, 0),
190
10
        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
39521
        WasmType::AnyRef => decode_dynamic_anyref(store.as_context_mut(), any, handles, mode, 0),
195
    }
196
219584
}
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.
201
10517
fn decode_bool(
202
10517
    store: impl AsContextMut,
203
10517
    any: &Rooted<AnyRef>,
204
10517
    t: &Rooted<AnyRef>,
205
10517
) -> wasmtime::Result<EvalValue> {
206
10517
    if Rooted::<AnyRef>::ref_eq(&store, any, t)? {
207
10517
        Ok(EvalValue::T)
208
    } else {
209
        Err(wasmtime::Error::msg(
210
            "boxed bool result is neither null nor the `t` singleton",
211
        ))
212
    }
213
10517
}
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`).
218
1086874
pub(crate) fn guest_fraction(numer: i64, denom: i64) -> Option<nomiscript::Fraction> {
219
1086874
    (denom > 0).then(|| nomiscript::Fraction::new(numer, denom))
220
1086874
}
221

            
222
59332
pub(super) fn checked_pair(numer: i64, denom: i64, what: &str) -> wasmtime::Result<(i64, i64)> {
223
59332
    guest_fraction(numer, denom)
224
59329
        .map(|_| (numer, denom))
225
3
        .ok_or_else(|| wasmtime::Error::msg(format!("{what} has a non-positive denominator")))
226
59332
}
227

            
228
8007
pub(super) fn decode_ratio(
229
8007
    mut store: impl AsContextMut,
230
8007
    any: &Rooted<AnyRef>,
231
8007
) -> wasmtime::Result<EvalValue> {
232
8007
    let s = any.checked_struct(&mut store)?;
233
8007
    let numer = s
234
8007
        .field(&mut store, 0)?
235
        .i64()
236
        .ok_or_else(|| wasmtime::Error::msg("ratio field 0 (numer) is not i64"))?;
237
8007
    let denom = s
238
8007
        .field(&mut store, 1)?
239
        .i64()
240
        .ok_or_else(|| wasmtime::Error::msg("ratio field 1 (denom) is not i64"))?;
241
8007
    let (numer, denom) = checked_pair(numer, denom, "ratio")?;
242
8004
    Ok(EvalValue::Ratio { numer, denom })
243
8007
}
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.
249
3551
pub(super) fn decode_commodity(
250
3551
    mut store: impl AsContextMut,
251
3551
    any: &Rooted<AnyRef>,
252
3551
) -> wasmtime::Result<EvalValue> {
253
3551
    let s = any.checked_struct(&mut store)?;
254
3551
    let numer = commodity_i64(&mut store, &s, 0)?;
255
3551
    let denom = commodity_i64(&mut store, &s, 1)?;
256
3551
    let (numer, denom) = checked_pair(numer, denom, "commodity amount")?;
257
3551
    match s.field(&mut store, 4)? {
258
        Val::AnyRef(None) => {
259
1265
            let hi = commodity_i64(&mut store, &s, 2)?;
260
1265
            let lo = commodity_i64(&mut store, &s, 3)?;
261
1265
            Ok(EvalValue::Commodity {
262
1265
                numer,
263
1265
                denom,
264
1265
                commodity_hi: hi,
265
1265
                commodity_lo: lo,
266
1265
            })
267
        }
268
        Val::AnyRef(Some(term)) => {
269
2286
            let arr = term.checked_array(&mut store)?;
270
2286
            if arr.len(&mut store)? == 0 {
271
1
                Ok(EvalValue::Ratio { numer, denom })
272
            } else {
273
2285
                Err(wasmtime::Error::msg(
274
2285
                    "compound commodity (e.g. money × money) has no host \
275
2285
                     representation yet",
276
2285
                ))
277
            }
278
        }
279
        _ => Err(wasmtime::Error::msg(
280
            "commodity field 4 (unit term) is not a ref",
281
        )),
282
    }
283
3551
}
284

            
285
9632
fn commodity_i64(
286
9632
    store: impl AsContextMut,
287
9632
    s: &Rooted<wasmtime::StructRef>,
288
9632
    slot: usize,
289
9632
) -> wasmtime::Result<i64> {
290
9632
    s.field(store, slot)?
291
        .i64()
292
        .ok_or_else(|| wasmtime::Error::msg(format!("commodity field {slot} is not i64")))
293
9632
}
294

            
295
238025
pub(super) fn decode_string_ref(
296
238025
    mut store: impl AsContextMut,
297
238025
    any: &Rooted<AnyRef>,
298
238025
) -> wasmtime::Result<EvalValue> {
299
238025
    array_text(&mut store, any).map(EvalValue::String)
300
238025
}
301

            
302
84087
pub(super) fn decode_symbol(
303
84087
    mut store: impl AsContextMut,
304
84087
    any: &Rooted<AnyRef>,
305
84087
) -> wasmtime::Result<EvalValue> {
306
84087
    symbol_name(&mut store, any).map(EvalValue::Symbol)
307
84087
}
308

            
309
/// The name array of the `$symbol` in `any`, as text.
310
277529
pub(super) fn symbol_name(
311
277529
    mut store: impl AsContextMut,
312
277529
    any: &Rooted<AnyRef>,
313
277529
) -> wasmtime::Result<String> {
314
277529
    match any.checked_struct(&mut store)?.field(&mut store, 0)? {
315
277529
        Val::AnyRef(Some(name)) => array_text(&mut store, &name),
316
        _ => Err(wasmtime::Error::msg("symbol name is not a reference")),
317
    }
318
277529
}
319

            
320
515554
fn array_text(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> wasmtime::Result<String> {
321
515554
    let arr = any.checked_array(&mut store)?;
322
515554
    let len = arr.len(&mut store)?;
323
515554
    let mut bytes = Vec::with_capacity(len as usize);
324
515554
    for i in 0..len {
325
68993443
        let v = arr.get(&mut store, i)?;
326
68993443
        let byte = v
327
68993443
            .i32()
328
            .ok_or_else(|| wasmtime::Error::msg("string element is not i32"))?;
329
68993443
        bytes.push(byte as u8);
330
    }
331
515554
    String::from_utf8(bytes).map_err(|err| wasmtime::Error::msg(format!("not valid utf-8: {err}")))
332
515554
}