Lines
92.26 %
Functions
60.83 %
Branches
100 %
//! Reads the session's struct instances back out of a finished unit
//! (rstruct S5): every instance reachable from an exported global is decoded
//! once, memoised by serial, so cycles and sharing terminate.
use std::collections::{BTreeMap, HashSet};
use std::hash::{BuildHasherDefault, Hasher};
use nomiscript::{Expr, Found, StructId, StructInstance, SymbolTable};
use tracing::warn;
use wasmtime::{AnyRef, AsContextMut, Extern, Instance, Rooted, StructRef, Val};
use crate::checked_ref::CheckedAnyRef;
use super::carry::top_constant;
use super::structure::{InstanceMode, decode_dynamic_anyref, instance_identity, value_slots};
use super::type_handles::{AnyRefKind, TypeHandles, classify_anyref};
/// The ceiling on the objects one unit's read visits: what it has not visited by
/// then is unreadable, loud in a later unit rather than half read.
pub(super) const MAX_REACHED: usize = 1 << 24;
type Reached = BTreeMap<u32, Rooted<AnyRef>>;
/// Replaces the session heap with the instances the unit left: everything its
/// exported globals reach, with the fields each now holds.
pub(super) fn settle_heap(
mut store: impl AsContextMut,
instance: &Instance,
symbols: &mut SymbolTable,
handles: Option<&TypeHandles>,
ceiling: usize,
) {
let Some(handles) = handles else {
symbols.settle_instances(Found::new(), 0);
return;
};
let roots = roots(&mut store, instance);
let reached = reach(&mut store, roots, handles, ceiling)
.inspect_err(|err| warn!(%err, "reading the unit's struct instances"))
.unwrap_or_default();
let next_serial = reached.keys().next_back().map_or(0, |last| last + 1);
let found = reached
.iter()
.map(|(serial, any)| (*serial, read_instance(&mut store, any, handles)))
.collect();
symbols.settle_instances(found, next_serial);
}
fn roots(mut store: impl AsContextMut, instance: &Instance) -> Vec<Rooted<AnyRef>> {
let globals: Vec<_> = instance
.exports(&mut store)
.map(wasmtime::Export::into_extern)
.filter_map(Extern::into_global)
globals
.into_iter()
.filter_map(|global| match global.get(&mut store) {
Val::AnyRef(Some(any)) => Some(any),
_ => None,
})
.collect()
/// Spreads a collector reference, a `u32` slot, over the hash table.
#[derive(Default)]
struct SlotHash(u64);
impl Hasher for SlotHash {
fn write(&mut self, bytes: &[u8]) {
self.0 = bytes
.fold(self.0, |hash, byte| hash.rotate_left(8) ^ u64::from(*byte));
fn write_u32(&mut self, slot: u32) {
self.0 = u64::from(slot).wrapping_mul(0x9E37_79B9_7F4A_7C15);
fn finish(&self) -> u64 {
self.0
/// The heap objects already visited, by their collector slot: a cycle and a
/// shared list are each walked once.
struct Visited {
seen: HashSet<u32, BuildHasherDefault<SlotHash>>,
impl Visited {
/// Records `any`; `false` when its object was visited before.
fn first_visit(
&mut self,
any: Rooted<AnyRef>,
) -> wasmtime::Result<bool> {
Ok(self.seen.insert(any.to_raw(&mut store)?))
fn is_full(&self, ceiling: usize) -> bool {
self.seen.len() > ceiling
/// The instances reachable from `roots` through list cells, instance fields
/// and closure environments, by serial. Each object is visited once; past the
/// ceiling the instances not yet reached are left out.
fn reach(
roots: Vec<Rooted<AnyRef>>,
handles: &TypeHandles,
) -> wasmtime::Result<Reached> {
let mut reached = Reached::new();
let mut pending = roots;
let mut visited = Visited::default();
while let Some(any) = pending.pop() {
if visited.is_full(ceiling) {
warn!("the unit's heap exceeds the read ceiling");
break;
match classify_anyref(&mut store, any, handles)? {
AnyRefKind::Pair => chain(&mut store, any, &mut visited, &mut pending, ceiling)?,
AnyRefKind::Struct if visited.first_visit(&mut store, any)? => {
let (serial, _) = instance_identity(&mut store, &any)?;
reached.insert(serial, any);
values(&mut store, &any, &mut pending)?;
AnyRefKind::Closure(_)
| AnyRefKind::Other
| AnyRefKind::Entity(nomiscript::EntityKind::Condition)
if visited.first_visit(&mut store, any)? =>
{
if let Some(object) = any.as_struct(&store)? {
children(&mut store, &object, &mut pending)?;
_ => {}
Ok(reached)
/// Walks a `$pair` chain along its cdrs, leaving each car that is not an
/// immediate for the caller; stops at the first cell visited before.
fn chain(
head: Rooted<AnyRef>,
visited: &mut Visited,
pending: &mut Vec<Rooted<AnyRef>>,
) -> wasmtime::Result<()> {
let mut next = Some(head);
while let Some(any) = next.filter(|_| !visited.is_full(ceiling)) {
if !visited.first_visit(&mut store, any)? {
let cell = any.checked_struct(&mut store)?;
if let Val::AnyRef(Some(car)) = cell.field(&mut store, 0)?
&& !car.is_i31(&store)?
pending.push(car);
next = match cell.field(&mut store, 1)? {
Val::AnyRef(Some(cdr)) => Some(cdr),
Ok(())
fn children(
object: &Rooted<StructRef>,
let fields = object.ty(&store)?.fields().len();
for field in 0..fields {
if let Val::AnyRef(Some(child)) = object.field(&mut store, field)? {
pending.push(child);
fn values(
any: &Rooted<AnyRef>,
let slots = value_slots(&mut store, any)?;
for value in slots {
if let Val::AnyRef(Some(child)) = value {
/// The instance as the constants its fields hold now; `None` when a field holds
/// what no constant holds, or cannot be decoded within the datum bound.
fn read_instance(
) -> Option<StructInstance> {
let (_, layout) = instance_identity(&mut store, any).ok()?;
let fields = value_slots(&mut store, any)
.ok()?
.map(|value| field_constant(&mut store, value, handles))
.collect::<Option<Vec<_>>>()?;
Some(StructInstance {
layout: StructId(layout),
fields,
fn field_constant(mut store: impl AsContextMut, value: Val, handles: &TypeHandles) -> Option<Expr> {
match value {
Val::AnyRef(None) => Some(Expr::Nil),
Val::AnyRef(Some(any)) => {
let decoded = decode_dynamic_anyref(
store.as_context_mut(),
any,
handles,
InstanceMode::Identity,
0,
)
.ok()?;
top_constant(decoded)