Lines
94.26 %
Functions
66.53 %
Branches
100 %
//! Reads a finished unit's globals back out of its instance and makes them
//! the session's values (plan 0014 PERSIST): the values the next unit's
//! symbol table holds for them.
use nomiscript::{
Carried, Expr, Fraction, Number, PROLOGUE_DONE_EXPORT, PairElement, Rebind, StructId,
SymbolTable, UnitSlot, WasmType, global_export_name,
};
use wasmtime::{AnyRef, AsContextMut, Instance, Rooted, Val};
use crate::checked_ref::CheckedAnyRef;
use super::carry_list::read_list;
use super::decode::{EvalValue, decode_anyref, decode_commodity};
use super::heap::{MAX_REACHED, settle_heap};
use super::structure::{
CLOSURE_ENV, CLOSURE_SITE, InstanceMode, holds_unconstant, instance_identity, is_compound_money,
use super::type_handles::{AnyRefKind, TypeHandles, classify_anyref};
use super::{EngineError, classify_runtime_error, resolve_type_handles};
use tracing::warn;
/// How a unit ended, which decides what its globals hold.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnitEnd {
Returned,
/// An uncaught `$nomi_error`: every dynamic binding was unwound.
Raised,
/// A trap, fuel, epoch or host error: no cleanup ran, so a special bound
/// inside the trap holds the binding's value, which `Rebind` undoes.
Trapped,
}
impl UnitEnd {
/// The end of a unit whose call failed with `err`.
#[must_use]
pub fn of_failure(err: &wasmtime::Error) -> Self {
match classify_runtime_error(err) {
EngineError::ScriptRaised { .. } => Self::Raised,
_ => Self::Trapped,
/// Takes the unit's manifest and settles each slot it wrote: one none of whose
/// flags is 1 never got the unit's value and is put back as it was before the
/// unit, a function or layout keeps the last definition that ran, and a cell
/// that got a value carries the one its instance holds, or, when the unit
/// trapped inside a binding of it, the one outside the binding; one only a
/// DEFVAR of it reached stays declared special and unbound. Never fails the
/// unit that ran: a cell that cannot be read becomes an opaque global, loud
/// when a later unit reads it, and the cause is logged. The session heap is
/// settled only once the unit's instance prologue ran to its end.
pub fn carry_globals(
mut store: impl AsContextMut,
instance: &Instance,
symbols: &mut SymbolTable,
end: UnitEnd,
) {
let slots = symbols.take_unit_slots();
let holds_instances = symbols.instances().next().is_some();
let handles = match holds_instances || slots.iter().any(|slot| slot.cell.is_some()) {
true => resolve_type_handles(&mut store, instance)
.inspect_err(|err| warn!(%err, "carrying unit globals: no type handles"))
.ok(),
false => None,
for slot in slots {
match slot.cell {
Some(cell) => carry_cell(
&mut store,
instance,
symbols,
handles.as_ref(),
&slot,
cell,
end,
),
None => {
let last = slot
.flags
.iter()
.rposition(|&flag| ran(&mut store, instance, flag));
symbols.settle(&slot.name, slot.slot, last);
let settles = holds_instances || handles.is_some();
if settles && prologue_done(&mut store, instance) {
settle_heap(&mut store, instance, symbols, handles.as_ref(), MAX_REACHED);
/// Settles a cell: its first flag says it holds a value, the later ones that a
/// DEFVAR of it ran, which declares it special even when nothing bound it.
fn carry_cell(
handles: Option<&TypeHandles>,
slot: &UnitSlot,
(global, ty): (u32, WasmType),
let outer = outer_binding(&mut store, instance, slot.rebind, end);
let (bound_flag, declaring) = slot.flags.split_first().unzip();
let bound = match outer {
Some((_, bound)) => bound,
None => bound_flag.is_some_and(|&flag| ran(&mut store, instance, flag)),
let declaring = declaring.unwrap_or_default();
let declared = declaring
.any(|&flag| ran(&mut store, instance, flag));
match (bound, declared) {
(true, _) => {
let cell = (outer.map_or(global, |(outer, _)| outer), ty);
let carried = match handles {
None => opaque("unreadable"),
Some(handles) => read_global(&mut store, instance, symbols, cell, handles)
.inspect_err(|err| warn!(%err, name = %slot.name, "carrying unit global"))
.unwrap_or_else(|_| opaque("unreadable")),
symbols.carry(&slot.name, carried);
if !declared && !declaring.is_empty() {
symbols.restore_declaration(&slot.name, true);
(false, true) => symbols.declare_unbound(&slot.name),
(false, false) => symbols.settle(&slot.name, slot.slot, None),
/// Puts back every slot a unit wrote when it compiled but never ran: its
/// instantiation failed, or an interrupt stopped it before its call.
pub fn carry_not_run(symbols: &mut SymbolTable) {
for slot in symbols.take_unit_slots() {
symbols.settle(&slot.name, slot.slot, None);
/// The global holding a rebound special's value outside every binding, and
/// whether it was bound there, when the unit trapped inside a binding of it.
fn outer_binding(
rebind: Option<Rebind>,
) -> Option<(u32, bool)> {
let rebind = rebind.filter(|_| end == UnitEnd::Trapped)?;
let depth = read_i32(&mut store, instance, rebind.depth)?;
let bound = read_i32(&mut store, instance, rebind.outer_bound)?;
(depth > 0).then_some((rebind.outer, bound == 1))
/// Whether the unit's instance prologue ran to its end: before that the
/// instance globals are null, and settling would drop every carried instance.
fn prologue_done(mut store: impl AsContextMut, instance: &Instance) -> bool {
instance
.get_global(&mut store, PROLOGUE_DONE_EXPORT)
.map(|global| global.get(&mut store))
.and_then(|value| value.i32())
== Some(1)
/// Whether the flag `flag` says its slot got the unit's value; a flag the
/// instance does not hold counts as set.
fn ran(store: impl AsContextMut, instance: &Instance, flag: u32) -> bool {
read_i32(store, instance, flag).is_none_or(|ran| ran == 1)
fn read_i32(mut store: impl AsContextMut, instance: &Instance, idx: u32) -> Option<i32> {
.get_global(&mut store, &global_export_name(idx))
fn read_global(
symbols: &SymbolTable,
(idx, ty): (u32, WasmType),
handles: &TypeHandles,
) -> wasmtime::Result<Carried> {
let export = global_export_name(idx);
let val = instance
.get_global(&mut store, &export)
.ok_or_else(|| wasmtime::Error::msg(format!("module does not export `{export}`")))?
.get(&mut store);
carried_value(&mut store, (symbols, handles), ty, val)
fn carried_value<S: AsContextMut>(
store: &mut S,
(symbols, handles): (&SymbolTable, &TypeHandles),
ty: WasmType,
val: Val,
match (ty, val) {
(WasmType::I32, Val::I32(n)) => Ok(constant(EvalValue::I32(n))),
(WasmType::Bool, Val::I32(n)) => Ok(constant(truth(n))),
(WasmType::Closure(_), Val::AnyRef(Some(any))) => {
read_closure(store, (symbols, handles), &any)
(WasmType::Closure(_), _) => Ok(opaque("closure")),
(WasmType::Commodity, Val::AnyRef(Some(any))) => Ok(read_money(&mut *store, &any)),
(WasmType::EntityRef(_), _) => Ok(opaque("entity")),
(WasmType::StructRef(id), Val::AnyRef(Some(any))) => {
let (serial, _) = instance_identity(&mut *store, &any)?;
Ok(Carried::Constant(Expr::Instance(serial, id)))
(_, Val::AnyRef(None)) => Ok(constant(EvalValue::Nil)),
(ty, Val::AnyRef(Some(any))) => Ok(read_ref(&mut *store, (symbols, handles), any, ty)),
(ty, _) => Err(wasmtime::Error::msg(format!(
"global of type {ty} holds a value of another kind"
))),
/// A closure as the lambda its source and captured values make; one whose
/// source was not kept, or that captures a value no constant holds, is opaque.
pub(super) fn read_closure<S: AsContextMut>(
any: &Rooted<AnyRef>,
let closure = any.checked_struct(&mut *store)?;
let site = closure.field(&mut *store, CLOSURE_SITE)?.i32();
let Some(source) = site.and_then(|site| symbols.closure_source(site)) else {
return Ok(opaque("closure"));
let env = closure.field(&mut *store, CLOSURE_ENV)?;
let mut values = Vec::with_capacity(source.fields().len());
for (field, (_, ty)) in source.fields().iter().enumerate() {
let Val::AnyRef(Some(env)) = &env else {
let captured = env.checked_struct(&mut *store)?.field(&mut *store, field)?;
match capture_value(store, (symbols, handles), *ty, captured)? {
Some(value) => values.push(value),
None => return Ok(opaque("closure")),
Ok(Carried::Constant(source.lambda(values)))
/// The constant a captured variable is carried as; none for one that is not
/// constant.
fn capture_value<S: AsContextMut>(
context: (&SymbolTable, &TypeHandles),
captured: Val,
) -> wasmtime::Result<Option<Expr>> {
Ok(carried_value(store, context, ty, captured)?.into_constant())
fn truth(raw: i32) -> EvalValue {
match raw {
0 => EvalValue::Nil,
_ => EvalValue::T,
/// Atomic money is a typed constant; compound money has no host form.
fn read_money(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> Carried {
match decode_commodity(&mut store, any) {
Ok(value) => constant(value),
Err(_) => opaque("money"),
pub(super) fn read_ref<S: AsContextMut>(
any: Rooted<AnyRef>,
) -> Carried {
match unconstant_kind(&mut *store, &any, ty, handles) {
Ok(Some("list")) => {
read_list(store, (symbols, handles), &any).unwrap_or_else(|_| opaque("oversized"))
Ok(Some(kind)) => opaque(kind),
Ok(None) => decode_anyref(&mut *store, any, ty, handles, InstanceMode::Identity)
.map_or_else(|_| opaque("oversized"), constant),
Err(_) => opaque("oversized"),
/// The name of the kind of `any` when a constant cannot hold it, or anything
/// it holds.
fn unconstant_kind(
) -> wasmtime::Result<Option<&'static str>> {
let (kind, elem) = match ty {
WasmType::AnyRef => (
classify_anyref(&mut store, *any, handles)?,
PairElement::AnyRef,
WasmType::PairRef(elem) => (AnyRefKind::Pair, elem),
_ => return Ok(None),
match kind {
AnyRefKind::Commodity => {
Ok(is_compound_money(store.as_context_mut(), any)?.then_some("money"))
AnyRefKind::Entity(_) => Ok(Some("entity")),
AnyRefKind::Closure(_) | AnyRefKind::Other => Ok(Some("closure")),
AnyRefKind::Pair => {
let unconstant = holds_unconstant(store.as_context_mut(), *any, elem, handles, 0)?;
Ok(unconstant.then_some("list"))
_ => Ok(None),
pub(super) fn opaque(type_name: &str) -> Carried {
Carried::Opaque(type_name.to_string())
fn constant(value: EvalValue) -> Carried {
match top_constant(value) {
Some(expr) => Carried::Constant(expr),
/// A global's value as the constant a DEFVAR of it would bind.
pub(super) fn top_constant(value: EvalValue) -> Option<Expr> {
match value {
EvalValue::Ratio { numer, denom } => {
Some(Expr::Number(Number::Scalar(Fraction::new(numer, denom))))
EvalValue::Symbol(name) => Some(match name.strip_prefix(':') {
Some(keyword) => Expr::Keyword(keyword.to_string()),
None => Expr::quoted(Expr::Symbol(name)),
}),
other => member_constant(other).map(|member| match member {
Expr::List(_) => Expr::quoted(member),
plain => plain,
/// A list member as the constant it was read from.
fn member_constant(value: EvalValue) -> Option<Expr> {
EvalValue::Nil => Some(Expr::Nil),
EvalValue::T => Some(Expr::T),
EvalValue::I32(n) => Some(Expr::Number(Number::Index(i64::from(n)))),
EvalValue::String(text) => Some(Expr::String(text)),
None => Expr::Symbol(name),
EvalValue::List(items) => items
.into_iter()
.map(member_constant)
.collect::<Option<Vec<_>>>()
.map(Expr::List),
money @ EvalValue::Commodity { .. } => Some(Expr::RuntimeValue(money.into())),
EvalValue::Instance { serial, layout } => Some(Expr::Instance(serial, StructId(layout))),
EvalValue::Bytes(_)
| EvalValue::Closure { .. }
| EvalValue::Condition
| EvalValue::Opaque
| EvalValue::Struct(_) => None,