Skip to main content

scripting/runtime/
carry.rs

1//! Reads a finished unit's globals back out of its instance and makes them
2//! the session's values (plan 0014 PERSIST): the values the next unit's
3//! symbol table holds for them.
4
5use nomiscript::{
6    Carried, Expr, Fraction, Number, PROLOGUE_DONE_EXPORT, PairElement, Rebind, StructId,
7    SymbolTable, UnitSlot, WasmType, global_export_name,
8};
9use wasmtime::{AnyRef, AsContextMut, Instance, Rooted, Val};
10
11use crate::checked_ref::CheckedAnyRef;
12
13use super::carry_list::read_list;
14use super::decode::{EvalValue, decode_anyref, decode_commodity};
15use super::heap::{MAX_REACHED, settle_heap};
16use super::structure::{
17    CLOSURE_ENV, CLOSURE_SITE, InstanceMode, holds_unconstant, instance_identity, is_compound_money,
18};
19use super::type_handles::{AnyRefKind, TypeHandles, classify_anyref};
20use super::{EngineError, classify_runtime_error, resolve_type_handles};
21use tracing::warn;
22
23/// How a unit ended, which decides what its globals hold.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum UnitEnd {
26    Returned,
27    /// An uncaught `$nomi_error`: every dynamic binding was unwound.
28    Raised,
29    /// A trap, fuel, epoch or host error: no cleanup ran, so a special bound
30    /// inside the trap holds the binding's value, which `Rebind` undoes.
31    Trapped,
32}
33
34impl UnitEnd {
35    /// The end of a unit whose call failed with `err`.
36    #[must_use]
37    pub fn of_failure(err: &wasmtime::Error) -> Self {
38        match classify_runtime_error(err) {
39            EngineError::ScriptRaised { .. } => Self::Raised,
40            _ => Self::Trapped,
41        }
42    }
43}
44
45/// Takes the unit's manifest and settles each slot it wrote: one none of whose
46/// flags is 1 never got the unit's value and is put back as it was before the
47/// unit, a function or layout keeps the last definition that ran, and a cell
48/// that got a value carries the one its instance holds, or, when the unit
49/// trapped inside a binding of it, the one outside the binding; one only a
50/// DEFVAR of it reached stays declared special and unbound. Never fails the
51/// unit that ran: a cell that cannot be read becomes an opaque global, loud
52/// when a later unit reads it, and the cause is logged. The session heap is
53/// settled only once the unit's instance prologue ran to its end.
54pub fn carry_globals(
55    mut store: impl AsContextMut,
56    instance: &Instance,
57    symbols: &mut SymbolTable,
58    end: UnitEnd,
59) {
60    let slots = symbols.take_unit_slots();
61    let holds_instances = symbols.instances().next().is_some();
62    let handles = match holds_instances || slots.iter().any(|slot| slot.cell.is_some()) {
63        true => resolve_type_handles(&mut store, instance)
64            .inspect_err(|err| warn!(%err, "carrying unit globals: no type handles"))
65            .ok(),
66        false => None,
67    };
68    for slot in slots {
69        match slot.cell {
70            Some(cell) => carry_cell(
71                &mut store,
72                instance,
73                symbols,
74                handles.as_ref(),
75                &slot,
76                cell,
77                end,
78            ),
79            None => {
80                let last = slot
81                    .flags
82                    .iter()
83                    .rposition(|&flag| ran(&mut store, instance, flag));
84                symbols.settle(&slot.name, slot.slot, last);
85            }
86        }
87    }
88    let settles = holds_instances || handles.is_some();
89    if settles && prologue_done(&mut store, instance) {
90        settle_heap(&mut store, instance, symbols, handles.as_ref(), MAX_REACHED);
91    }
92}
93
94/// Settles a cell: its first flag says it holds a value, the later ones that a
95/// DEFVAR of it ran, which declares it special even when nothing bound it.
96fn carry_cell(
97    mut store: impl AsContextMut,
98    instance: &Instance,
99    symbols: &mut SymbolTable,
100    handles: Option<&TypeHandles>,
101    slot: &UnitSlot,
102    (global, ty): (u32, WasmType),
103    end: UnitEnd,
104) {
105    let outer = outer_binding(&mut store, instance, slot.rebind, end);
106    let (bound_flag, declaring) = slot.flags.split_first().unzip();
107    let bound = match outer {
108        Some((_, bound)) => bound,
109        None => bound_flag.is_some_and(|&flag| ran(&mut store, instance, flag)),
110    };
111    let declaring = declaring.unwrap_or_default();
112    let declared = declaring
113        .iter()
114        .any(|&flag| ran(&mut store, instance, flag));
115    match (bound, declared) {
116        (true, _) => {
117            let cell = (outer.map_or(global, |(outer, _)| outer), ty);
118            let carried = match handles {
119                None => opaque("unreadable"),
120                Some(handles) => read_global(&mut store, instance, symbols, cell, handles)
121                    .inspect_err(|err| warn!(%err, name = %slot.name, "carrying unit global"))
122                    .unwrap_or_else(|_| opaque("unreadable")),
123            };
124            symbols.carry(&slot.name, carried);
125            if !declared && !declaring.is_empty() {
126                symbols.restore_declaration(&slot.name, true);
127            }
128        }
129        (false, true) => symbols.declare_unbound(&slot.name),
130        (false, false) => symbols.settle(&slot.name, slot.slot, None),
131    }
132}
133
134/// Puts back every slot a unit wrote when it compiled but never ran: its
135/// instantiation failed, or an interrupt stopped it before its call.
136pub fn carry_not_run(symbols: &mut SymbolTable) {
137    for slot in symbols.take_unit_slots() {
138        symbols.settle(&slot.name, slot.slot, None);
139    }
140}
141
142/// The global holding a rebound special's value outside every binding, and
143/// whether it was bound there, when the unit trapped inside a binding of it.
144fn outer_binding(
145    mut store: impl AsContextMut,
146    instance: &Instance,
147    rebind: Option<Rebind>,
148    end: UnitEnd,
149) -> Option<(u32, bool)> {
150    let rebind = rebind.filter(|_| end == UnitEnd::Trapped)?;
151    let depth = read_i32(&mut store, instance, rebind.depth)?;
152    let bound = read_i32(&mut store, instance, rebind.outer_bound)?;
153    (depth > 0).then_some((rebind.outer, bound == 1))
154}
155
156/// Whether the unit's instance prologue ran to its end: before that the
157/// instance globals are null, and settling would drop every carried instance.
158fn prologue_done(mut store: impl AsContextMut, instance: &Instance) -> bool {
159    instance
160        .get_global(&mut store, PROLOGUE_DONE_EXPORT)
161        .map(|global| global.get(&mut store))
162        .and_then(|value| value.i32())
163        == Some(1)
164}
165
166/// Whether the flag `flag` says its slot got the unit's value; a flag the
167/// instance does not hold counts as set.
168fn ran(store: impl AsContextMut, instance: &Instance, flag: u32) -> bool {
169    read_i32(store, instance, flag).is_none_or(|ran| ran == 1)
170}
171
172fn read_i32(mut store: impl AsContextMut, instance: &Instance, idx: u32) -> Option<i32> {
173    instance
174        .get_global(&mut store, &global_export_name(idx))
175        .map(|global| global.get(&mut store))
176        .and_then(|value| value.i32())
177}
178
179fn read_global(
180    mut store: impl AsContextMut,
181    instance: &Instance,
182    symbols: &SymbolTable,
183    (idx, ty): (u32, WasmType),
184    handles: &TypeHandles,
185) -> wasmtime::Result<Carried> {
186    let export = global_export_name(idx);
187    let val = instance
188        .get_global(&mut store, &export)
189        .ok_or_else(|| wasmtime::Error::msg(format!("module does not export `{export}`")))?
190        .get(&mut store);
191    carried_value(&mut store, (symbols, handles), ty, val)
192}
193
194fn carried_value<S: AsContextMut>(
195    store: &mut S,
196    (symbols, handles): (&SymbolTable, &TypeHandles),
197    ty: WasmType,
198    val: Val,
199) -> wasmtime::Result<Carried> {
200    match (ty, val) {
201        (WasmType::I32, Val::I32(n)) => Ok(constant(EvalValue::I32(n))),
202        (WasmType::Bool, Val::I32(n)) => Ok(constant(truth(n))),
203        (WasmType::Closure(_), Val::AnyRef(Some(any))) => {
204            read_closure(store, (symbols, handles), &any)
205        }
206        (WasmType::Closure(_), _) => Ok(opaque("closure")),
207        (WasmType::Commodity, Val::AnyRef(Some(any))) => Ok(read_money(&mut *store, &any)),
208        (WasmType::EntityRef(_), _) => Ok(opaque("entity")),
209        (WasmType::StructRef(id), Val::AnyRef(Some(any))) => {
210            let (serial, _) = instance_identity(&mut *store, &any)?;
211            Ok(Carried::Constant(Expr::Instance(serial, id)))
212        }
213        (_, Val::AnyRef(None)) => Ok(constant(EvalValue::Nil)),
214        (ty, Val::AnyRef(Some(any))) => Ok(read_ref(&mut *store, (symbols, handles), any, ty)),
215        (ty, _) => Err(wasmtime::Error::msg(format!(
216            "global of type {ty} holds a value of another kind"
217        ))),
218    }
219}
220
221/// A closure as the lambda its source and captured values make; one whose
222/// source was not kept, or that captures a value no constant holds, is opaque.
223pub(super) fn read_closure<S: AsContextMut>(
224    store: &mut S,
225    (symbols, handles): (&SymbolTable, &TypeHandles),
226    any: &Rooted<AnyRef>,
227) -> wasmtime::Result<Carried> {
228    let closure = any.checked_struct(&mut *store)?;
229    let site = closure.field(&mut *store, CLOSURE_SITE)?.i32();
230    let Some(source) = site.and_then(|site| symbols.closure_source(site)) else {
231        return Ok(opaque("closure"));
232    };
233    let env = closure.field(&mut *store, CLOSURE_ENV)?;
234    let mut values = Vec::with_capacity(source.fields().len());
235    for (field, (_, ty)) in source.fields().iter().enumerate() {
236        let Val::AnyRef(Some(env)) = &env else {
237            return Ok(opaque("closure"));
238        };
239        let captured = env.checked_struct(&mut *store)?.field(&mut *store, field)?;
240        match capture_value(store, (symbols, handles), *ty, captured)? {
241            Some(value) => values.push(value),
242            None => return Ok(opaque("closure")),
243        }
244    }
245    Ok(Carried::Constant(source.lambda(values)))
246}
247
248/// The constant a captured variable is carried as; none for one that is not
249/// constant.
250fn capture_value<S: AsContextMut>(
251    store: &mut S,
252    context: (&SymbolTable, &TypeHandles),
253    ty: WasmType,
254    captured: Val,
255) -> wasmtime::Result<Option<Expr>> {
256    Ok(carried_value(store, context, ty, captured)?.into_constant())
257}
258
259fn truth(raw: i32) -> EvalValue {
260    match raw {
261        0 => EvalValue::Nil,
262        _ => EvalValue::T,
263    }
264}
265
266/// Atomic money is a typed constant; compound money has no host form.
267fn read_money(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> Carried {
268    match decode_commodity(&mut store, any) {
269        Ok(value) => constant(value),
270        Err(_) => opaque("money"),
271    }
272}
273
274pub(super) fn read_ref<S: AsContextMut>(
275    store: &mut S,
276    (symbols, handles): (&SymbolTable, &TypeHandles),
277    any: Rooted<AnyRef>,
278    ty: WasmType,
279) -> Carried {
280    match unconstant_kind(&mut *store, &any, ty, handles) {
281        Ok(Some("list")) => {
282            read_list(store, (symbols, handles), &any).unwrap_or_else(|_| opaque("oversized"))
283        }
284        Ok(Some(kind)) => opaque(kind),
285        Ok(None) => decode_anyref(&mut *store, any, ty, handles, InstanceMode::Identity)
286            .map_or_else(|_| opaque("oversized"), constant),
287        Err(_) => opaque("oversized"),
288    }
289}
290
291/// The name of the kind of `any` when a constant cannot hold it, or anything
292/// it holds.
293fn unconstant_kind(
294    mut store: impl AsContextMut,
295    any: &Rooted<AnyRef>,
296    ty: WasmType,
297    handles: &TypeHandles,
298) -> wasmtime::Result<Option<&'static str>> {
299    let (kind, elem) = match ty {
300        WasmType::AnyRef => (
301            classify_anyref(&mut store, *any, handles)?,
302            PairElement::AnyRef,
303        ),
304        WasmType::PairRef(elem) => (AnyRefKind::Pair, elem),
305        _ => return Ok(None),
306    };
307    match kind {
308        AnyRefKind::Commodity => {
309            Ok(is_compound_money(store.as_context_mut(), any)?.then_some("money"))
310        }
311        AnyRefKind::Entity(_) => Ok(Some("entity")),
312        AnyRefKind::Closure(_) | AnyRefKind::Other => Ok(Some("closure")),
313        AnyRefKind::Pair => {
314            let unconstant = holds_unconstant(store.as_context_mut(), *any, elem, handles, 0)?;
315            Ok(unconstant.then_some("list"))
316        }
317        _ => Ok(None),
318    }
319}
320
321pub(super) fn opaque(type_name: &str) -> Carried {
322    Carried::Opaque(type_name.to_string())
323}
324
325fn constant(value: EvalValue) -> Carried {
326    match top_constant(value) {
327        Some(expr) => Carried::Constant(expr),
328        None => opaque("unreadable"),
329    }
330}
331
332/// A global's value as the constant a DEFVAR of it would bind.
333pub(super) fn top_constant(value: EvalValue) -> Option<Expr> {
334    match value {
335        EvalValue::Ratio { numer, denom } => {
336            Some(Expr::Number(Number::Scalar(Fraction::new(numer, denom))))
337        }
338        EvalValue::Symbol(name) => Some(match name.strip_prefix(':') {
339            Some(keyword) => Expr::Keyword(keyword.to_string()),
340            None => Expr::quoted(Expr::Symbol(name)),
341        }),
342        other => member_constant(other).map(|member| match member {
343            Expr::List(_) => Expr::quoted(member),
344            plain => plain,
345        }),
346    }
347}
348
349/// A list member as the constant it was read from.
350fn member_constant(value: EvalValue) -> Option<Expr> {
351    match value {
352        EvalValue::Nil => Some(Expr::Nil),
353        EvalValue::T => Some(Expr::T),
354        EvalValue::I32(n) => Some(Expr::Number(Number::Index(i64::from(n)))),
355        EvalValue::Ratio { numer, denom } => {
356            Some(Expr::Number(Number::Scalar(Fraction::new(numer, denom))))
357        }
358        EvalValue::String(text) => Some(Expr::String(text)),
359        EvalValue::Symbol(name) => Some(match name.strip_prefix(':') {
360            Some(keyword) => Expr::Keyword(keyword.to_string()),
361            None => Expr::Symbol(name),
362        }),
363        EvalValue::List(items) => items
364            .into_iter()
365            .map(member_constant)
366            .collect::<Option<Vec<_>>>()
367            .map(Expr::List),
368        money @ EvalValue::Commodity { .. } => Some(Expr::RuntimeValue(money.into())),
369        EvalValue::Instance { serial, layout } => Some(Expr::Instance(serial, StructId(layout))),
370        EvalValue::Bytes(_)
371        | EvalValue::Closure { .. }
372        | EvalValue::Condition
373        | EvalValue::Opaque
374        | EvalValue::Struct(_) => None,
375    }
376}