1
//! Reads the session's struct instances back out of a finished unit
2
//! (rstruct S5): every instance reachable from an exported global is decoded
3
//! once, memoised by serial, so cycles and sharing terminate.
4

            
5
use std::collections::{BTreeMap, HashSet};
6
use std::hash::{BuildHasherDefault, Hasher};
7

            
8
use nomiscript::{Expr, Found, StructId, StructInstance, SymbolTable};
9
use tracing::warn;
10
use wasmtime::{AnyRef, AsContextMut, Extern, Instance, Rooted, StructRef, Val};
11

            
12
use crate::checked_ref::CheckedAnyRef;
13

            
14
use super::carry::top_constant;
15
use super::structure::{InstanceMode, decode_dynamic_anyref, instance_identity, value_slots};
16
use super::type_handles::{AnyRefKind, TypeHandles, classify_anyref};
17

            
18
/// The ceiling on the objects one unit's read visits: what it has not visited by
19
/// then is unreadable, loud in a later unit rather than half read.
20
pub(super) const MAX_REACHED: usize = 1 << 24;
21

            
22
type Reached = BTreeMap<u32, Rooted<AnyRef>>;
23

            
24
/// Replaces the session heap with the instances the unit left: everything its
25
/// exported globals reach, with the fields each now holds.
26
250812
pub(super) fn settle_heap(
27
250812
    mut store: impl AsContextMut,
28
250812
    instance: &Instance,
29
250812
    symbols: &mut SymbolTable,
30
250812
    handles: Option<&TypeHandles>,
31
250812
    ceiling: usize,
32
250812
) {
33
250812
    let Some(handles) = handles else {
34
        symbols.settle_instances(Found::new(), 0);
35
        return;
36
    };
37
250812
    let roots = roots(&mut store, instance);
38
250812
    let reached = reach(&mut store, roots, handles, ceiling)
39
        .inspect_err(|err| warn!(%err, "reading the unit's struct instances"))
40
        .unwrap_or_default();
41
250812
    let next_serial = reached.keys().next_back().map_or(0, |last| last + 1);
42
250812
    let found = reached
43
250812
        .iter()
44
1933091
        .map(|(serial, any)| (*serial, read_instance(&mut store, any, handles)))
45
        .collect();
46
250812
    symbols.settle_instances(found, next_serial);
47
250812
}
48

            
49
250812
fn roots(mut store: impl AsContextMut, instance: &Instance) -> Vec<Rooted<AnyRef>> {
50
250812
    let globals: Vec<_> = instance
51
250812
        .exports(&mut store)
52
250812
        .map(wasmtime::Export::into_extern)
53
250812
        .filter_map(Extern::into_global)
54
250812
        .collect();
55
250812
    globals
56
250812
        .into_iter()
57
2183401
        .filter_map(|global| match global.get(&mut store) {
58
1284926
            Val::AnyRef(Some(any)) => Some(any),
59
898475
            _ => None,
60
2183401
        })
61
        .collect()
62
250812
}
63

            
64
/// Spreads a collector reference, a `u32` slot, over the hash table.
65
#[derive(Default)]
66
struct SlotHash(u64);
67

            
68
impl Hasher for SlotHash {
69
    fn write(&mut self, bytes: &[u8]) {
70
        self.0 = bytes
71
            .iter()
72
            .fold(self.0, |hash, byte| hash.rotate_left(8) ^ u64::from(*byte));
73
    }
74

            
75
301599173
    fn write_u32(&mut self, slot: u32) {
76
301599173
        self.0 = u64::from(slot).wrapping_mul(0x9E37_79B9_7F4A_7C15);
77
301599173
    }
78

            
79
301599173
    fn finish(&self) -> u64 {
80
301599173
        self.0
81
301599173
    }
82
}
83

            
84
/// The heap objects already visited, by their collector slot: a cycle and a
85
/// shared list are each walked once.
86
#[derive(Default)]
87
struct Visited {
88
    seen: HashSet<u32, BuildHasherDefault<SlotHash>>,
89
}
90

            
91
impl Visited {
92
    /// Records `any`; `false` when its object was visited before.
93
71965441
    fn first_visit(
94
71965441
        &mut self,
95
71965441
        mut store: impl AsContextMut,
96
71965441
        any: Rooted<AnyRef>,
97
71965441
    ) -> wasmtime::Result<bool> {
98
71965441
        Ok(self.seen.insert(any.to_raw(&mut store)?))
99
71965441
    }
100

            
101
122497268
    fn is_full(&self, ceiling: usize) -> bool {
102
122497268
        self.seen.len() > ceiling
103
122497268
    }
104
}
105

            
106
/// The instances reachable from `roots` through list cells, instance fields
107
/// and closure environments, by serial. Each object is visited once; past the
108
/// ceiling the instances not yet reached are left out.
109
250812
fn reach(
110
250812
    mut store: impl AsContextMut,
111
250812
    roots: Vec<Rooted<AnyRef>>,
112
250812
    handles: &TypeHandles,
113
250812
    ceiling: usize,
114
250812
) -> wasmtime::Result<Reached> {
115
250812
    let mut reached = Reached::new();
116
250812
    let mut pending = roots;
117
250812
    let mut visited = Visited::default();
118
4415880
    while let Some(any) = pending.pop() {
119
4165069
        if visited.is_full(ceiling) {
120
1
            warn!("the unit's heap exceeds the read ceiling");
121
1
            break;
122
4165068
        }
123
4165068
        match classify_anyref(&mut store, any, handles)? {
124
17148
            AnyRefKind::Pair => chain(&mut store, any, &mut visited, &mut pending, ceiling)?,
125
1974493
            AnyRefKind::Struct if visited.first_visit(&mut store, any)? => {
126
1933091
                let (serial, _) = instance_identity(&mut store, &any)?;
127
1933091
                reached.insert(serial, any);
128
1933091
                values(&mut store, &any, &mut pending)?;
129
            }
130
            AnyRefKind::Closure(_)
131
            | AnyRefKind::Other
132
            | AnyRefKind::Entity(nomiscript::EntityKind::Condition)
133
                if visited.first_visit(&mut store, any)? =>
134
            {
135
42012
                if let Some(object) = any.as_struct(&store)? {
136
42012
                    children(&mut store, &object, &mut pending)?;
137
                }
138
            }
139
2172817
            _ => {}
140
        }
141
    }
142
250812
    Ok(reached)
143
250812
}
144

            
145
/// Walks a `$pair` chain along its cdrs, leaving each car that is not an
146
/// immediate for the caller; stops at the first cell visited before.
147
17148
fn chain(
148
17148
    mut store: impl AsContextMut,
149
17148
    head: Rooted<AnyRef>,
150
17148
    visited: &mut Visited,
151
17148
    pending: &mut Vec<Rooted<AnyRef>>,
152
17148
    ceiling: usize,
153
17148
) -> wasmtime::Result<()> {
154
17148
    let mut next = Some(head);
155
69965622
    while let Some(any) = next.filter(|_| !visited.is_full(ceiling)) {
156
69948474
        if !visited.first_visit(&mut store, any)? {
157
            break;
158
69948474
        }
159
69948474
        let cell = any.checked_struct(&mut store)?;
160
69948474
        if let Val::AnyRef(Some(car)) = cell.field(&mut store, 0)?
161
69948244
            && !car.is_i31(&store)?
162
        {
163
943703
            pending.push(car);
164
69004771
        }
165
69948474
        next = match cell.field(&mut store, 1)? {
166
69931327
            Val::AnyRef(Some(cdr)) => Some(cdr),
167
17147
            _ => None,
168
        };
169
    }
170
17148
    Ok(())
171
17148
}
172

            
173
42012
fn children(
174
42012
    mut store: impl AsContextMut,
175
42012
    object: &Rooted<StructRef>,
176
42012
    pending: &mut Vec<Rooted<AnyRef>>,
177
42012
) -> wasmtime::Result<()> {
178
42012
    let fields = object.ty(&store)?.fields().len();
179
42012
    for field in 0..fields {
180
160428
        if let Val::AnyRef(Some(child)) = object.field(&mut store, field)? {
181
3351
            pending.push(child);
182
157077
        }
183
    }
184
42012
    Ok(())
185
42012
}
186

            
187
1933091
fn values(
188
1933091
    mut store: impl AsContextMut,
189
1933091
    any: &Rooted<AnyRef>,
190
1933091
    pending: &mut Vec<Rooted<AnyRef>>,
191
1933091
) -> wasmtime::Result<()> {
192
1933091
    let slots = value_slots(&mut store, any)?;
193
1933091
    for value in slots {
194
1934126
        if let Val::AnyRef(Some(child)) = value {
195
1933089
            pending.push(child);
196
1037
        }
197
    }
198
1933091
    Ok(())
199
1933091
}
200

            
201
/// The instance as the constants its fields hold now; `None` when a field holds
202
/// what no constant holds, or cannot be decoded within the datum bound.
203
1933091
fn read_instance(
204
1933091
    mut store: impl AsContextMut,
205
1933091
    any: &Rooted<AnyRef>,
206
1933091
    handles: &TypeHandles,
207
1933091
) -> Option<StructInstance> {
208
1933091
    let (_, layout) = instance_identity(&mut store, any).ok()?;
209
1933091
    let fields = value_slots(&mut store, any)
210
1933091
        .ok()?
211
        .into_iter()
212
1934126
        .map(|value| field_constant(&mut store, value, handles))
213
232
        .collect::<Option<Vec<_>>>()?;
214
1932859
    Some(StructInstance {
215
1932859
        layout: StructId(layout),
216
1932859
        fields,
217
1932859
    })
218
1933091
}
219

            
220
1934126
fn field_constant(mut store: impl AsContextMut, value: Val, handles: &TypeHandles) -> Option<Expr> {
221
1934126
    match value {
222
1037
        Val::AnyRef(None) => Some(Expr::Nil),
223
        Val::AnyRef(Some(any)) => {
224
1933089
            let decoded = decode_dynamic_anyref(
225
1933089
                store.as_context_mut(),
226
1933089
                any,
227
1933089
                handles,
228
1933089
                InstanceMode::Identity,
229
1933089
                0,
230
1933089
            )
231
1933089
            .ok()?;
232
1933089
            top_constant(decoded)
233
        }
234
        _ => None,
235
    }
236
1934126
}