1
//! An eval result as its whole GC value graph, flattened in pre-order: every
2
//! struct field and array element, down to the scalars. It keeps what the
3
//! host's rendering (`decode_eval_result`) loses — a list of 1 and 2 against
4
//! the string "(1 2)", an i31 index against a ratio, an entity's pair fields.
5
//! The walk is iterative and bounded, so a deep or huge value neither
6
//! overflows the host stack nor runs away.
7

            
8
use scripting::host::ExecutionState;
9
use wasmtime::{AnyRef, Rooted, Store, Val};
10

            
11
/// Far beyond any snippet's value.
12
const MAX_NODES: usize = 1 << 16;
13

            
14
#[derive(Clone, Debug, PartialEq, Eq)]
15
pub(super) enum Node {
16
    Null,
17
    /// The module's `$t` singleton, told apart by identity.
18
    T,
19
    I31(i32),
20
    I32(i32),
21
    I64(i64),
22
    F32(u32),
23
    F64(u64),
24
    /// A funcref, by whether it is null: a function's identity is its index.
25
    Func(bool),
26
    /// A struct with this many fields, which follow.
27
    Struct(usize),
28
    /// An array with this many elements, which follow.
29
    Array(u32),
30
    Opaque(&'static str),
31
}
32

            
33
/// `root`'s graph, telling `t` apart by identity.
34
4191
pub(super) fn observe(
35
4191
    store: &mut Store<ExecutionState>,
36
4191
    t: &Rooted<AnyRef>,
37
4191
    root: Option<Rooted<AnyRef>>,
38
4191
) -> Result<Vec<Node>, String> {
39
4191
    let mut nodes = Vec::new();
40
4191
    let mut pending = vec![Val::AnyRef(root)];
41
348222
    while let Some(val) = pending.pop() {
42
344036
        let room = MAX_NODES.saturating_sub(nodes.len() + pending.len() + 1);
43
344036
        nodes.push(node(store, t, val, room, &mut pending).map_err(|err| err.to_string())?);
44
    }
45
4186
    Ok(nodes)
46
4191
}
47

            
48
/// `val`'s node; a struct's fields or an array's elements go on `pending`,
49
/// last first, so they pop in order, and only if at most `room` of them.
50
344036
fn node(
51
344036
    store: &mut Store<ExecutionState>,
52
344036
    t: &Rooted<AnyRef>,
53
344036
    val: Val,
54
344036
    room: usize,
55
344036
    pending: &mut Vec<Val>,
56
344036
) -> wasmtime::Result<Node> {
57
344036
    Ok(match val {
58
67956
        Val::I32(n) => Node::I32(n),
59
4610
        Val::I64(n) => Node::I64(n),
60
        Val::F32(bits) => Node::F32(bits),
61
        Val::F64(bits) => Node::F64(bits),
62
30
        Val::FuncRef(func) => Node::Func(func.is_some()),
63
1639
        Val::AnyRef(None) => Node::Null,
64
269801
        Val::AnyRef(Some(any)) => reference(store, t, &any, room, pending)?,
65
        Val::V128(_) => Node::Opaque("v128"),
66
        Val::ExternRef(_) => Node::Opaque("externref"),
67
        Val::ExnRef(_) => Node::Opaque("exnref"),
68
        Val::ContRef(_) => Node::Opaque("contref"),
69
    })
70
344036
}
71

            
72
269801
fn reference(
73
269801
    store: &mut Store<ExecutionState>,
74
269801
    t: &Rooted<AnyRef>,
75
269801
    any: &Rooted<AnyRef>,
76
269801
    room: usize,
77
269801
    pending: &mut Vec<Val>,
78
269801
) -> wasmtime::Result<Node> {
79
269801
    if Rooted::<AnyRef>::ref_eq(&*store, any, t)? {
80
409
        return Ok(Node::T);
81
269392
    }
82
269392
    if let Some(i31) = any.as_i31(&*store)? {
83
132733
        return Ok(Node::I31(i31.get_i32()));
84
136659
    }
85
136659
    if let Some(record) = any.as_struct(&*store)? {
86
136055
        let count = record.ty(&*store)?.fields().count();
87
136055
        fits("a struct", count, room)?;
88
136051
        let fields: Vec<Val> = record.fields(&mut *store)?.collect();
89
136051
        pending.extend(fields.into_iter().rev());
90
136051
        return Ok(Node::Struct(count));
91
604
    }
92
604
    if let Some(array) = any.as_array(&*store)? {
93
604
        let len = array.len(&*store)?;
94
604
        fits("an array", usize::try_from(len)?, room)?;
95
603
        let elems: Vec<Val> = array.elems(&mut *store)?.collect();
96
603
        pending.extend(elems.into_iter().rev());
97
603
        return Ok(Node::Array(len));
98
    }
99
    Ok(Node::Opaque("anyref"))
100
269801
}
101

            
102
/// Refuses children that would take the value past [`MAX_NODES`].
103
136659
fn fits(what: &str, children: usize, room: usize) -> wasmtime::Result<()> {
104
136659
    if children > room {
105
5
        return Err(wasmtime::Error::msg(format!(
106
5
            "{what} of {children} children exceeds the {MAX_NODES}-node budget"
107
5
        )));
108
136654
    }
109
136654
    Ok(())
110
136659
}