Lines
93.43 %
Functions
49.81 %
Branches
100 %
//! Walks `$pair` chains and typed entity structs into structured
//! [`EvalValue`] lists.
use crate::checked_ref::CheckedAnyRef;
use super::decode::{
EvalValue, MAX_WIRE_LIST_DEPTH, StructView, decode_commodity, decode_ratio, decode_string_ref,
decode_symbol, symbol_name,
};
use super::type_handles::{AnyRefKind, TypeHandles, classify_anyref};
use wasmtime::{AnyRef, ArrayRef, AsContextMut, Rooted, StoreContextMut, StructRef, Val};
/// Fields of the struct every closure value is: its code, its environment and
/// the site of its source.
const CLOSURE_CODE: usize = 0;
pub(super) const CLOSURE_ENV: usize = 1;
pub(super) const CLOSURE_SITE: usize = 2;
const INSTANCE_LAYOUT: usize = 1;
pub(super) const INSTANCE_VALUES: usize = 2;
const DEPTH_PLACEHOLDER: &str = "#<...>";
const LAYOUT_ID_SLOT: u32 = 0;
const LAYOUT_NAME_SLOT: u32 = 1;
const LAYOUT_FIELDS_AT: u32 = 2;
/// How a walk decodes: instances as their identity (carry, heap), or as their
/// name and fields with a placeholder at the depth cap (the log) or an error
/// there (`Wire`: results sent to a client).
#[derive(Clone, Copy)]
pub(super) enum InstanceMode {
Identity,
Contents,
Wire,
}
// The walkers recur into each other, so the store parameter is the concrete
// `StoreContextMut<'_, T>`: `impl AsContextMut` would add a `&mut` wrapper
// type per level and blow the compiler's generic recursion limit.
/// Walks a `$pair` chain into a list, decoding each car per `elem`. `depth`
/// is the number of lists enclosing this one, entities included; it runs after
/// guest execution on the host stack, so it is bounded by [`MAX_WIRE_LIST_DEPTH`].
pub(super) fn decode_pair<T>(
store: StoreContextMut<'_, T>,
head: Rooted<AnyRef>,
elem: nomiscript::PairElement,
handles: &TypeHandles,
mode: InstanceMode,
depth: usize,
) -> wasmtime::Result<EvalValue> {
if let Some(capped) = guard_depth(mode, depth)? {
return Ok(capped);
decode_cars(store, head, elem, handles, mode, depth + 1).map(EvalValue::List)
/// Decodes each car of the `$pair` chain `head` at `depth`, as separate values
/// rather than one list: the chain is a call's argument list, not a datum.
pub(super) fn decode_cars<T>(
mut store: StoreContextMut<'_, T>,
) -> wasmtime::Result<Vec<EvalValue>> {
let mut items = Vec::new();
let mut cur = Some(head.checked_struct(&mut store)?);
while let Some(node) = cur {
let car = node.field(&mut store, 0)?;
items.push(decode_car(
store.as_context_mut(),
car,
elem,
handles,
mode,
depth,
)?);
cur = match node.field(&mut store, 1)? {
Val::AnyRef(Some(next)) => Some(next.checked_struct(&mut store)?),
_ => None,
Ok(items)
pub(super) fn check_depth(depth: usize) -> wasmtime::Result<()> {
if depth >= MAX_WIRE_LIST_DEPTH {
return Err(wasmtime::Error::msg(format!(
"anyref decode: nested list exceeds the {MAX_WIRE_LIST_DEPTH}-level depth limit"
)));
Ok(())
/// The placeholder a printed walk writes at the depth cap, as the result
/// serializer does; an identity walk fails there instead.
fn guard_depth(mode: InstanceMode, depth: usize) -> wasmtime::Result<Option<EvalValue>> {
match mode {
InstanceMode::Contents if depth >= MAX_WIRE_LIST_DEPTH => {
Ok(Some(EvalValue::Symbol(DEPTH_PLACEHOLDER.to_string())))
_ => check_depth(depth).map(|()| None),
fn decode_car<T>(
car: Val,
use nomiscript::PairElement;
let any = match car {
Val::AnyRef(Some(any)) => any,
Val::AnyRef(None) => return Ok(EvalValue::Nil),
_ => return Err(wasmtime::Error::msg("pair car is not anyref")),
match elem {
PairElement::I32 => Ok(EvalValue::I32(any.checked_i31(&mut store)?.get_i32())),
// ADR-0033: a bool car is `ref.null` (nil) / the `$t` singleton (t).
PairElement::Bool => Ok(bool_value(Rooted::<AnyRef>::ref_eq(
&store, &any, &handles.t,
)?)),
PairElement::Ratio => decode_ratio(&mut store, &any),
PairElement::Commodity => decode_commodity(&mut store, &any),
PairElement::StringRef => decode_string_ref(&mut store, &any),
PairElement::Symbol => decode_symbol(&mut store, &any),
PairElement::Entity(kind) => decode_entity(store, &any, kind, depth),
PairElement::Struct(_) => decode_struct(store, &any, handles, mode, depth),
PairElement::AnyRef | PairElement::Closure(_) => {
decode_dynamic_anyref(store, any, handles, mode, depth)
/// Whether the `$pair` chain `head` holds, at any depth, a car that has no
/// constant form: an entity, money or a kind the host does not classify.
pub(super) fn holds_unconstant<T>(
) -> wasmtime::Result<bool> {
check_depth(depth)?;
if let Val::AnyRef(Some(car)) = node.field(&mut store, 0)?
&& car_is_unconstant(store.as_context_mut(), car, elem, handles, depth + 1)?
{
return Ok(true);
Ok(false)
fn car_is_unconstant<T>(
car: Rooted<AnyRef>,
PairElement::Commodity => is_compound_money(store, &car),
PairElement::Entity(_) | PairElement::Closure(_) => Ok(true),
PairElement::AnyRef => match classify_anyref(&mut store, car, handles)? {
AnyRefKind::Commodity => is_compound_money(store, &car),
AnyRefKind::Entity(_) | AnyRefKind::Closure(_) | AnyRefKind::Other => Ok(true),
AnyRefKind::Pair => holds_unconstant(store, car, PairElement::AnyRef, handles, depth),
_ => Ok(false),
},
/// Whether the money struct `car` has a non-empty unit term: money with no
/// host form, where an atomic or dimensionless one is a constant.
pub(super) fn is_compound_money<T>(
car: &Rooted<AnyRef>,
let money = car.checked_struct(&mut store)?;
match money.field(&mut store, 4)? {
Val::AnyRef(Some(term)) => Ok(term.checked_array(&mut store)?.len(&store)? > 0),
fn bool_value(is_t: bool) -> EvalValue {
if is_t { EvalValue::T } else { EvalValue::Nil }
/// Decodes a heterogeneous anyref (a result or a `$pair` car) by the kind
/// [`classify_anyref`] reports, reusing the per-kind decoder a fixed type uses.
/// Null is handled by the caller.
pub(super) fn decode_dynamic_anyref<T>(
any: Rooted<AnyRef>,
match classify_anyref(&mut store, any, handles)? {
AnyRefKind::T => Ok(EvalValue::T),
AnyRefKind::Index(n) => Ok(EvalValue::I32(n)),
AnyRefKind::Ratio => decode_ratio(&mut store, &any),
AnyRefKind::Commodity => decode_commodity(&mut store, &any),
AnyRefKind::StringRef => decode_string_ref(&mut store, &any),
AnyRefKind::Symbol => decode_symbol(&mut store, &any),
AnyRefKind::Pair => decode_pair(
store,
any,
nomiscript::PairElement::AnyRef,
),
AnyRefKind::Entity(kind) => decode_entity(store, &any, kind, depth),
AnyRefKind::Struct => decode_struct(store, &any, handles, mode, depth),
AnyRefKind::Closure(site) => Ok(EvalValue::Closure { site }),
AnyRefKind::Other => Ok(EvalValue::Opaque),
pub(super) fn decode_struct<T>(
any: &Rooted<AnyRef>,
InstanceMode::Identity => decode_instance(&mut store, any),
InstanceMode::Contents | InstanceMode::Wire => {
decode_struct_view(store, any, handles, mode, depth)
fn decode_struct_view<T>(
let (name, keys) = layout_names(&mut store, any)?;
let slots = value_slots(&mut store, any)?;
let fields = keys
.into_iter()
.zip(slots)
.map(|(key, slot)| {
decode_car(
slot,
depth + 1,
)
.map(|value| (key, value))
})
.collect::<wasmtime::Result<Vec<_>>>()?;
Ok(EvalValue::Struct(Box::new(StructView { name, fields })))
/// The identity of a `DEFSTRUCT` instance: its serial and the `StructId` its
/// layout array holds in slot 0.
fn decode_instance(
mut store: impl AsContextMut,
let (serial, layout) = instance_identity(&mut store, any)?;
Ok(EvalValue::Instance { serial, layout })
pub(super) fn instance_identity(
) -> wasmtime::Result<(u32, u32)> {
let serial = any
.checked_struct(&mut store)?
.field(&mut store, 0)?
.i32()
.and_then(|serial| u32::try_from(serial).ok())
.ok_or_else(|| wasmtime::Error::msg("instance serial is not a u32"))?;
let layout = instance_layout(&mut store, any)?;
let Val::AnyRef(Some(id)) = layout.get(&mut store, LAYOUT_ID_SLOT)? else {
return Err(wasmtime::Error::msg("layout id is not a reference"));
Ok((serial, id.checked_i31(&mut store)?.get_u32()))
fn instance_layout(
) -> wasmtime::Result<Rooted<ArrayRef>> {
let Val::AnyRef(Some(layout)) = any
.field(&mut store, INSTANCE_LAYOUT)?
else {
return Err(wasmtime::Error::msg("instance layout is not a reference"));
layout.checked_array(&mut store)
/// The struct name and each field name (without its keyword colon) from the
/// layout array an instance holds.
fn layout_names(
) -> wasmtime::Result<(String, Vec<String>)> {
let len = layout.len(&store)?;
let mut symbol_at = |slot: u32| -> wasmtime::Result<String> {
match layout.get(&mut store, slot)? {
Val::AnyRef(Some(symbol)) => symbol_name(&mut store, &symbol),
_ => Err(wasmtime::Error::msg("layout name is not a reference")),
let name = symbol_at(LAYOUT_NAME_SLOT)?;
let keys = (LAYOUT_FIELDS_AT..len)
.map(|slot| symbol_at(slot).map(|key| key.trim_start_matches(':').to_string()))
.collect::<wasmtime::Result<_>>()?;
Ok((name, keys))
pub(super) fn value_slots(
) -> wasmtime::Result<Vec<Val>> {
let Val::AnyRef(Some(array)) = any
.field(&mut store, INSTANCE_VALUES)?
return Err(wasmtime::Error::msg("instance values are not a reference"));
let array = array.checked_array(&mut store)?;
(0..array.len(&store)?)
.map(|slot| array.get(&mut store, slot))
.collect()
/// Decodes an entity struct into `(:label :field value ...)`, reading each
/// field at its `struct.get` slot per [`nomiscript::entity_layout`].
pub(super) fn decode_entity<T>(
kind: nomiscript::EntityKind,
let entity = any.checked_struct(&mut store)?;
let Some(layout) = nomiscript::entity_layout(kind) else {
return Ok(layoutless_entity(kind));
let mut items = Vec::with_capacity(1 + 2 * layout.fields.len());
items.push(keyword(layout.label));
for (slot, field) in layout.fields.iter().enumerate() {
items.push(keyword(field.name));
let value = decode_field(store.as_context_mut(), &entity, slot, field.kind)?;
items.push(value);
Ok(EvalValue::List(items))
fn layoutless_entity(kind: nomiscript::EntityKind) -> EvalValue {
match kind {
nomiscript::EntityKind::Condition => EvalValue::Condition,
other => EvalValue::List(vec![keyword(&format!("{other:?}"))]),
/// The closure struct in `any`; a closure is the one struct whose first
/// field is a function reference.
pub(super) fn closure_struct(
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
if !any.is_struct(&store)? {
return Ok(None);
let closure = any.checked_struct(&mut store)?;
let Ok(Val::FuncRef(_)) = closure.field(&mut store, CLOSURE_CODE) else {
Ok(Some(closure))
/// The site of a closure's source, `None` when the source cannot be carried.
pub(super) fn closure_site(
closure: &Rooted<StructRef>,
) -> wasmtime::Result<Option<u32>> {
let site = closure
.field(&mut store, CLOSURE_SITE)?
.and_then(|site| u32::try_from(site).ok());
Ok(site)
pub(super) fn decode_closure(
let closure = closure_struct(&mut store, any)?
.ok_or_else(|| wasmtime::Error::msg("the value is not a closure"))?;
let site = closure_site(&mut store, &closure)?;
Ok(EvalValue::Closure { site })
fn keyword(name: &str) -> EvalValue {
EvalValue::Symbol(format!(":{name}"))
fn decode_field<T>(
entity: &Rooted<StructRef>,
slot: usize,
kind: nomiscript::EntityFieldKind,
use nomiscript::EntityFieldKind;
let raw = entity.field(&mut store, slot)?;
EntityFieldKind::String => match raw {
Val::AnyRef(Some(a)) => decode_string_ref(&mut store, &a),
_ => Ok(EvalValue::String(String::new())),
EntityFieldKind::Ratio => match raw {
Val::AnyRef(Some(a)) => decode_ratio(&mut store, &a),
_ => Ok(EvalValue::Ratio { numer: 0, denom: 1 }),
EntityFieldKind::I32 => raw
.map(EvalValue::I32)
.ok_or_else(|| field_error(slot, "i32")),
// ADR-0033 Phase 5: 0 = unknown, 1 = Some(false), 2 = Some(true).
EntityFieldKind::TriBool => match raw.i32() {
Some(2) => Ok(EvalValue::T),
Some(1) => Ok(EvalValue::Nil),
Some(_) => Ok(keyword("unknown")),
None => Err(field_error(slot, "i32")),
fn field_error(slot: usize, expected: &str) -> wasmtime::Error {
wasmtime::Error::msg(format!("entity field {slot} is not {expected}"))