1
//! Walks `$pair` chains and typed entity structs into structured
2
//! [`EvalValue`] lists.
3

            
4
use crate::checked_ref::CheckedAnyRef;
5

            
6
use super::decode::{
7
    EvalValue, MAX_WIRE_LIST_DEPTH, StructView, decode_commodity, decode_ratio, decode_string_ref,
8
    decode_symbol, symbol_name,
9
};
10
use super::type_handles::{AnyRefKind, TypeHandles, classify_anyref};
11
use wasmtime::{AnyRef, ArrayRef, AsContextMut, Rooted, StoreContextMut, StructRef, Val};
12

            
13
/// Fields of the struct every closure value is: its code, its environment and
14
/// the site of its source.
15
const CLOSURE_CODE: usize = 0;
16
pub(super) const CLOSURE_ENV: usize = 1;
17
pub(super) const CLOSURE_SITE: usize = 2;
18
const INSTANCE_LAYOUT: usize = 1;
19
pub(super) const INSTANCE_VALUES: usize = 2;
20
const DEPTH_PLACEHOLDER: &str = "#<...>";
21
const LAYOUT_ID_SLOT: u32 = 0;
22
const LAYOUT_NAME_SLOT: u32 = 1;
23
const LAYOUT_FIELDS_AT: u32 = 2;
24

            
25
/// How a walk decodes: instances as their identity (carry, heap), or as their
26
/// name and fields with a placeholder at the depth cap (the log) or an error
27
/// there (`Wire`: results sent to a client).
28
#[derive(Clone, Copy)]
29
pub(super) enum InstanceMode {
30
    Identity,
31
    Contents,
32
    Wire,
33
}
34

            
35
// The walkers recur into each other, so the store parameter is the concrete
36
// `StoreContextMut<'_, T>`: `impl AsContextMut` would add a `&mut` wrapper
37
// type per level and blow the compiler's generic recursion limit.
38

            
39
/// Walks a `$pair` chain into a list, decoding each car per `elem`. `depth`
40
/// is the number of lists enclosing this one, entities included; it runs after
41
/// guest execution on the host stack, so it is bounded by [`MAX_WIRE_LIST_DEPTH`].
42
108057
pub(super) fn decode_pair<T>(
43
108057
    store: StoreContextMut<'_, T>,
44
108057
    head: Rooted<AnyRef>,
45
108057
    elem: nomiscript::PairElement,
46
108057
    handles: &TypeHandles,
47
108057
    mode: InstanceMode,
48
108057
    depth: usize,
49
108057
) -> wasmtime::Result<EvalValue> {
50
108057
    if let Some(capped) = guard_depth(mode, depth)? {
51
382
        return Ok(capped);
52
107672
    }
53
107672
    decode_cars(store, head, elem, handles, mode, depth + 1).map(EvalValue::List)
54
108057
}
55

            
56
/// Decodes each car of the `$pair` chain `head` at `depth`, as separate values
57
/// rather than one list: the chain is a call's argument list, not a datum.
58
166015
pub(super) fn decode_cars<T>(
59
166015
    mut store: StoreContextMut<'_, T>,
60
166015
    head: Rooted<AnyRef>,
61
166015
    elem: nomiscript::PairElement,
62
166015
    handles: &TypeHandles,
63
166015
    mode: InstanceMode,
64
166015
    depth: usize,
65
166015
) -> wasmtime::Result<Vec<EvalValue>> {
66
166015
    let mut items = Vec::new();
67
166015
    let mut cur = Some(head.checked_struct(&mut store)?);
68
116058374
    while let Some(node) = cur {
69
115895648
        let car = node.field(&mut store, 0)?;
70
115895648
        items.push(decode_car(
71
115895648
            store.as_context_mut(),
72
115895648
            car,
73
115895648
            elem,
74
115895648
            handles,
75
115895648
            mode,
76
115895648
            depth,
77
115895648
        )?);
78
115892359
        cur = match node.field(&mut store, 1)? {
79
115729633
            Val::AnyRef(Some(next)) => Some(next.checked_struct(&mut store)?),
80
162726
            _ => None,
81
        };
82
    }
83
162726
    Ok(items)
84
166015
}
85

            
86
463031
pub(super) fn check_depth(depth: usize) -> wasmtime::Result<()> {
87
463031
    if depth >= MAX_WIRE_LIST_DEPTH {
88
571
        return Err(wasmtime::Error::msg(format!(
89
571
            "anyref decode: nested list exceeds the {MAX_WIRE_LIST_DEPTH}-level depth limit"
90
571
        )));
91
462460
    }
92
462460
    Ok(())
93
463031
}
94

            
95
/// The placeholder a printed walk writes at the depth cap, as the result
96
/// serializer does; an identity walk fails there instead.
97
395176
fn guard_depth(mode: InstanceMode, depth: usize) -> wasmtime::Result<Option<EvalValue>> {
98
395176
    match mode {
99
213759
        InstanceMode::Contents if depth >= MAX_WIRE_LIST_DEPTH => {
100
1900
            Ok(Some(EvalValue::Symbol(DEPTH_PLACEHOLDER.to_string())))
101
        }
102
393276
        _ => check_depth(depth).map(|()| None),
103
    }
104
395176
}
105

            
106
115992369
fn decode_car<T>(
107
115992369
    mut store: StoreContextMut<'_, T>,
108
115992369
    car: Val,
109
115992369
    elem: nomiscript::PairElement,
110
115992369
    handles: &TypeHandles,
111
115992369
    mode: InstanceMode,
112
115992369
    depth: usize,
113
115992369
) -> wasmtime::Result<EvalValue> {
114
    use nomiscript::PairElement;
115
115992369
    let any = match car {
116
115984278
        Val::AnyRef(Some(any)) => any,
117
8091
        Val::AnyRef(None) => return Ok(EvalValue::Nil),
118
        _ => return Err(wasmtime::Error::msg("pair car is not anyref")),
119
    };
120
115984278
    match elem {
121
114017707
        PairElement::I32 => Ok(EvalValue::I32(any.checked_i31(&mut store)?.get_i32())),
122
        // ADR-0033: a bool car is `ref.null` (nil) / the `$t` singleton (t).
123
13
        PairElement::Bool => Ok(bool_value(Rooted::<AnyRef>::ref_eq(
124
13
            &store, &any, &handles.t,
125
13
        )?)),
126
33
        PairElement::Ratio => decode_ratio(&mut store, &any),
127
10
        PairElement::Commodity => decode_commodity(&mut store, &any),
128
23523
        PairElement::StringRef => decode_string_ref(&mut store, &any),
129
1623
        PairElement::Symbol => decode_symbol(&mut store, &any),
130
12485
        PairElement::Entity(kind) => decode_entity(store, &any, kind, depth),
131
1521142
        PairElement::Struct(_) => decode_struct(store, &any, handles, mode, depth),
132
        PairElement::AnyRef | PairElement::Closure(_) => {
133
407742
            decode_dynamic_anyref(store, any, handles, mode, depth)
134
        }
135
    }
136
115992369
}
137

            
138
/// Whether the `$pair` chain `head` holds, at any depth, a car that has no
139
/// constant form: an entity, money or a kind the host does not classify.
140
16802
pub(super) fn holds_unconstant<T>(
141
16802
    mut store: StoreContextMut<'_, T>,
142
16802
    head: Rooted<AnyRef>,
143
16802
    elem: nomiscript::PairElement,
144
16802
    handles: &TypeHandles,
145
16802
    depth: usize,
146
16802
) -> wasmtime::Result<bool> {
147
16802
    check_depth(depth)?;
148
16802
    let mut cur = Some(head.checked_struct(&mut store)?);
149
69948587
    while let Some(node) = cur {
150
69944209
        if let Val::AnyRef(Some(car)) = node.field(&mut store, 0)?
151
69944209
            && car_is_unconstant(store.as_context_mut(), car, elem, handles, depth + 1)?
152
        {
153
12424
            return Ok(true);
154
69931785
        }
155
69931785
        cur = match node.field(&mut store, 1)? {
156
69927407
            Val::AnyRef(Some(next)) => Some(next.checked_struct(&mut store)?),
157
4378
            _ => None,
158
        };
159
    }
160
4378
    Ok(false)
161
16802
}
162

            
163
69944209
fn car_is_unconstant<T>(
164
69944209
    mut store: StoreContextMut<'_, T>,
165
69944209
    car: Rooted<AnyRef>,
166
69944209
    elem: nomiscript::PairElement,
167
69944209
    handles: &TypeHandles,
168
69944209
    depth: usize,
169
69944209
) -> wasmtime::Result<bool> {
170
    use nomiscript::PairElement;
171
69944209
    match elem {
172
5
        PairElement::Commodity => is_compound_money(store, &car),
173
4026
        PairElement::Entity(_) | PairElement::Closure(_) => Ok(true),
174
18790
        PairElement::AnyRef => match classify_anyref(&mut store, car, handles)? {
175
            AnyRefKind::Commodity => is_compound_money(store, &car),
176
7362
            AnyRefKind::Entity(_) | AnyRefKind::Closure(_) | AnyRefKind::Other => Ok(true),
177
1035
            AnyRefKind::Pair => holds_unconstant(store, car, PairElement::AnyRef, handles, depth),
178
10393
            _ => Ok(false),
179
        },
180
69921388
        _ => Ok(false),
181
    }
182
69944209
}
183

            
184
/// Whether the money struct `car` has a non-empty unit term: money with no
185
/// host form, where an atomic or dimensionless one is a constant.
186
7
pub(super) fn is_compound_money<T>(
187
7
    mut store: StoreContextMut<'_, T>,
188
7
    car: &Rooted<AnyRef>,
189
7
) -> wasmtime::Result<bool> {
190
7
    let money = car.checked_struct(&mut store)?;
191
7
    match money.field(&mut store, 4)? {
192
2
        Val::AnyRef(Some(term)) => Ok(term.checked_array(&mut store)?.len(&store)? > 0),
193
5
        _ => Ok(false),
194
    }
195
7
}
196

            
197
2470
fn bool_value(is_t: bool) -> EvalValue {
198
2470
    if is_t { EvalValue::T } else { EvalValue::Nil }
199
2470
}
200

            
201
/// Decodes a heterogeneous anyref (a result or a `$pair` car) by the kind
202
/// [`classify_anyref`] reports, reusing the per-kind decoder a fixed type uses.
203
/// Null is handled by the caller.
204
3653424
pub(super) fn decode_dynamic_anyref<T>(
205
3653424
    mut store: StoreContextMut<'_, T>,
206
3653424
    any: Rooted<AnyRef>,
207
3653424
    handles: &TypeHandles,
208
3653424
    mode: InstanceMode,
209
3653424
    depth: usize,
210
3653424
) -> wasmtime::Result<EvalValue> {
211
3653424
    match classify_anyref(&mut store, any, handles)? {
212
8294
        AnyRefKind::T => Ok(EvalValue::T),
213
3124822
        AnyRefKind::Index(n) => Ok(EvalValue::I32(n)),
214
2680
        AnyRefKind::Ratio => decode_ratio(&mut store, &any),
215
3044
        AnyRefKind::Commodity => decode_commodity(&mut store, &any),
216
109709
        AnyRefKind::StringRef => decode_string_ref(&mut store, &any),
217
82213
        AnyRefKind::Symbol => decode_symbol(&mut store, &any),
218
88001
        AnyRefKind::Pair => decode_pair(
219
88001
            store,
220
88001
            any,
221
88001
            nomiscript::PairElement::AnyRef,
222
88001
            handles,
223
88001
            mode,
224
88001
            depth,
225
88001
        ),
226
3212
        AnyRefKind::Entity(kind) => decode_entity(store, &any, kind, depth),
227
213191
        AnyRefKind::Struct => decode_struct(store, &any, handles, mode, depth),
228
18258
        AnyRefKind::Closure(site) => Ok(EvalValue::Closure { site }),
229
        AnyRefKind::Other => Ok(EvalValue::Opaque),
230
    }
231
3653424
}
232

            
233
1734339
pub(super) fn decode_struct<T>(
234
1734339
    mut store: StoreContextMut<'_, T>,
235
1734339
    any: &Rooted<AnyRef>,
236
1734339
    handles: &TypeHandles,
237
1734339
    mode: InstanceMode,
238
1734339
    depth: usize,
239
1734339
) -> wasmtime::Result<EvalValue> {
240
1734339
    match mode {
241
1636478
        InstanceMode::Identity => decode_instance(&mut store, any),
242
        InstanceMode::Contents | InstanceMode::Wire => {
243
97861
            decode_struct_view(store, any, handles, mode, depth)
244
        }
245
    }
246
1734339
}
247

            
248
97861
fn decode_struct_view<T>(
249
97861
    mut store: StoreContextMut<'_, T>,
250
97861
    any: &Rooted<AnyRef>,
251
97861
    handles: &TypeHandles,
252
97861
    mode: InstanceMode,
253
97861
    depth: usize,
254
97861
) -> wasmtime::Result<EvalValue> {
255
97861
    if let Some(capped) = guard_depth(mode, depth)? {
256
1140
        return Ok(capped);
257
96721
    }
258
96721
    let (name, keys) = layout_names(&mut store, any)?;
259
96721
    let slots = value_slots(&mut store, any)?;
260
96721
    let fields = keys
261
96721
        .into_iter()
262
96721
        .zip(slots)
263
96721
        .map(|(key, slot)| {
264
96721
            decode_car(
265
96721
                store.as_context_mut(),
266
96721
                slot,
267
96721
                nomiscript::PairElement::AnyRef,
268
96721
                handles,
269
96721
                mode,
270
96721
                depth + 1,
271
96721
            )
272
96721
            .map(|value| (key, value))
273
96721
        })
274
        .collect::<wasmtime::Result<Vec<_>>>()?;
275
96721
    Ok(EvalValue::Struct(Box::new(StructView { name, fields })))
276
97861
}
277

            
278
/// The identity of a `DEFSTRUCT` instance: its serial and the `StructId` its
279
/// layout array holds in slot 0.
280
1636478
fn decode_instance(
281
1636478
    mut store: impl AsContextMut,
282
1636478
    any: &Rooted<AnyRef>,
283
1636478
) -> wasmtime::Result<EvalValue> {
284
1636478
    let (serial, layout) = instance_identity(&mut store, any)?;
285
1636478
    Ok(EvalValue::Instance { serial, layout })
286
1636478
}
287

            
288
5513143
pub(super) fn instance_identity(
289
5513143
    mut store: impl AsContextMut,
290
5513143
    any: &Rooted<AnyRef>,
291
5513143
) -> wasmtime::Result<(u32, u32)> {
292
5513143
    let serial = any
293
5513143
        .checked_struct(&mut store)?
294
5513143
        .field(&mut store, 0)?
295
        .i32()
296
5513143
        .and_then(|serial| u32::try_from(serial).ok())
297
        .ok_or_else(|| wasmtime::Error::msg("instance serial is not a u32"))?;
298
5513143
    let layout = instance_layout(&mut store, any)?;
299
5513143
    let Val::AnyRef(Some(id)) = layout.get(&mut store, LAYOUT_ID_SLOT)? else {
300
        return Err(wasmtime::Error::msg("layout id is not a reference"));
301
    };
302
5513143
    Ok((serial, id.checked_i31(&mut store)?.get_u32()))
303
5513143
}
304

            
305
5609864
fn instance_layout(
306
5609864
    mut store: impl AsContextMut,
307
5609864
    any: &Rooted<AnyRef>,
308
5609864
) -> wasmtime::Result<Rooted<ArrayRef>> {
309
5609864
    let Val::AnyRef(Some(layout)) = any
310
5609864
        .checked_struct(&mut store)?
311
5609864
        .field(&mut store, INSTANCE_LAYOUT)?
312
    else {
313
        return Err(wasmtime::Error::msg("instance layout is not a reference"));
314
    };
315
5609864
    layout.checked_array(&mut store)
316
5609864
}
317

            
318
/// The struct name and each field name (without its keyword colon) from the
319
/// layout array an instance holds.
320
96721
fn layout_names(
321
96721
    mut store: impl AsContextMut,
322
96721
    any: &Rooted<AnyRef>,
323
96721
) -> wasmtime::Result<(String, Vec<String>)> {
324
96721
    let layout = instance_layout(&mut store, any)?;
325
96721
    let len = layout.len(&store)?;
326
193442
    let mut symbol_at = |slot: u32| -> wasmtime::Result<String> {
327
193442
        match layout.get(&mut store, slot)? {
328
193442
            Val::AnyRef(Some(symbol)) => symbol_name(&mut store, &symbol),
329
            _ => Err(wasmtime::Error::msg("layout name is not a reference")),
330
        }
331
193442
    };
332
96721
    let name = symbol_at(LAYOUT_NAME_SLOT)?;
333
96721
    let keys = (LAYOUT_FIELDS_AT..len)
334
96721
        .map(|slot| symbol_at(slot).map(|key| key.trim_start_matches(':').to_string()))
335
        .collect::<wasmtime::Result<_>>()?;
336
96721
    Ok((name, keys))
337
96721
}
338

            
339
3962903
pub(super) fn value_slots(
340
3962903
    mut store: impl AsContextMut,
341
3962903
    any: &Rooted<AnyRef>,
342
3962903
) -> wasmtime::Result<Vec<Val>> {
343
3962903
    let Val::AnyRef(Some(array)) = any
344
3962903
        .checked_struct(&mut store)?
345
3962903
        .field(&mut store, INSTANCE_VALUES)?
346
    else {
347
        return Err(wasmtime::Error::msg("instance values are not a reference"));
348
    };
349
3962903
    let array = array.checked_array(&mut store)?;
350
3962903
    (0..array.len(&store)?)
351
3964973
        .map(|slot| array.get(&mut store, slot))
352
        .collect()
353
3962903
}
354

            
355
/// Decodes an entity struct into `(:label :field value ...)`, reading each
356
/// field at its `struct.get` slot per [`nomiscript::entity_layout`].
357
16181
pub(super) fn decode_entity<T>(
358
16181
    mut store: StoreContextMut<'_, T>,
359
16181
    any: &Rooted<AnyRef>,
360
16181
    kind: nomiscript::EntityKind,
361
16181
    depth: usize,
362
16181
) -> wasmtime::Result<EvalValue> {
363
16181
    check_depth(depth)?;
364
16180
    let entity = any.checked_struct(&mut store)?;
365
16180
    let Some(layout) = nomiscript::entity_layout(kind) else {
366
2287
        return Ok(layoutless_entity(kind));
367
    };
368
13893
    let mut items = Vec::with_capacity(1 + 2 * layout.fields.len());
369
13893
    items.push(keyword(layout.label));
370
13893
    for (slot, field) in layout.fields.iter().enumerate() {
371
56220
        items.push(keyword(field.name));
372
56220
        let value = decode_field(store.as_context_mut(), &entity, slot, field.kind)?;
373
56220
        items.push(value);
374
    }
375
13893
    Ok(EvalValue::List(items))
376
16181
}
377

            
378
3610
fn layoutless_entity(kind: nomiscript::EntityKind) -> EvalValue {
379
3610
    match kind {
380
3610
        nomiscript::EntityKind::Condition => EvalValue::Condition,
381
        other => EvalValue::List(vec![keyword(&format!("{other:?}"))]),
382
    }
383
3610
}
384

            
385
/// The closure struct in `any`; a closure is the one struct whose first
386
/// field is a function reference.
387
86592
pub(super) fn closure_struct(
388
86592
    mut store: impl AsContextMut,
389
86592
    any: &Rooted<AnyRef>,
390
86592
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
391
86592
    if !any.is_struct(&store)? {
392
        return Ok(None);
393
86592
    }
394
86592
    let closure = any.checked_struct(&mut store)?;
395
86592
    let Ok(Val::FuncRef(_)) = closure.field(&mut store, CLOSURE_CODE) else {
396
2540
        return Ok(None);
397
    };
398
84052
    Ok(Some(closure))
399
86592
}
400

            
401
/// The site of a closure's source, `None` when the source cannot be carried.
402
84052
pub(super) fn closure_site(
403
84052
    mut store: impl AsContextMut,
404
84052
    closure: &Rooted<StructRef>,
405
84052
) -> wasmtime::Result<Option<u32>> {
406
84052
    let site = closure
407
84052
        .field(&mut store, CLOSURE_SITE)?
408
        .i32()
409
84052
        .and_then(|site| u32::try_from(site).ok());
410
84052
    Ok(site)
411
84052
}
412

            
413
10
pub(super) fn decode_closure(
414
10
    mut store: impl AsContextMut,
415
10
    any: &Rooted<AnyRef>,
416
10
) -> wasmtime::Result<EvalValue> {
417
10
    let closure = closure_struct(&mut store, any)?
418
        .ok_or_else(|| wasmtime::Error::msg("the value is not a closure"))?;
419
10
    let site = closure_site(&mut store, &closure)?;
420
10
    Ok(EvalValue::Closure { site })
421
10
}
422

            
423
84613
fn keyword(name: &str) -> EvalValue {
424
84613
    EvalValue::Symbol(format!(":{name}"))
425
84613
}
426

            
427
56220
fn decode_field<T>(
428
56220
    mut store: StoreContextMut<'_, T>,
429
56220
    entity: &Rooted<StructRef>,
430
56220
    slot: usize,
431
56220
    kind: nomiscript::EntityFieldKind,
432
56220
) -> wasmtime::Result<EvalValue> {
433
    use nomiscript::EntityFieldKind;
434
56220
    let raw = entity.field(&mut store, slot)?;
435
56220
    match kind {
436
55260
        EntityFieldKind::String => match raw {
437
33179
            Val::AnyRef(Some(a)) => decode_string_ref(&mut store, &a),
438
22081
            _ => Ok(EvalValue::String(String::new())),
439
        },
440
480
        EntityFieldKind::Ratio => match raw {
441
480
            Val::AnyRef(Some(a)) => decode_ratio(&mut store, &a),
442
            _ => Ok(EvalValue::Ratio { numer: 0, denom: 1 }),
443
        },
444
        EntityFieldKind::I32 => raw
445
            .i32()
446
            .map(EvalValue::I32)
447
            .ok_or_else(|| field_error(slot, "i32")),
448
        // ADR-0033 Phase 5: 0 = unknown, 1 = Some(false), 2 = Some(true).
449
480
        EntityFieldKind::TriBool => match raw.i32() {
450
160
            Some(2) => Ok(EvalValue::T),
451
160
            Some(1) => Ok(EvalValue::Nil),
452
160
            Some(_) => Ok(keyword("unknown")),
453
            None => Err(field_error(slot, "i32")),
454
        },
455
    }
456
56220
}
457

            
458
fn field_error(slot: usize, expected: &str) -> wasmtime::Error {
459
    wasmtime::Error::msg(format!("entity field {slot} is not {expected}"))
460
}