Lines
100 %
Functions
33.33 %
Branches
//! A list holding closures, carried on as the source that rebuilds it (plan
//! 0014 PERSIST Q4-2): `(LET ((<hidden> <lambda>) …) (LIST <hidden> …))`, each
//! closure member read like a closure global, so the next unit makes its own
//! closures from the source.
use nomiscript::{Carried, Expr, SymbolTable, WasmType};
use wasmtime::{AnyRef, AsContextMut, Rooted, Val};
use crate::checked_ref::CheckedAnyRef;
use super::carry::{opaque, read_closure, read_ref};
use super::structure::check_depth;
use super::type_handles::{AnyRefKind, TypeHandles, classify_anyref};
type Context<'a> = (&'a SymbolTable, &'a TypeHandles);
/// The source of the list `head`; opaque when a member has no source form.
pub(super) fn read_list<S: AsContextMut>(
store: &mut S,
context: Context<'_>,
head: &Rooted<AnyRef>,
) -> wasmtime::Result<Carried> {
let mut closures = Vec::new();
let Some(list) = list_source(store, context, head, &mut closures, 0)? else {
return Ok(opaque("list"));
};
let bindings = closures
.into_iter()
.map(|(name, lambda)| Expr::List(vec![Expr::Symbol(name), lambda]))
.collect();
Ok(Carried::Constant(Expr::List(vec![
Expr::symbol("LET"),
Expr::List(bindings),
list,
])))
}
fn list_source<S: AsContextMut>(
closures: &mut Vec<(String, Expr)>,
depth: usize,
) -> wasmtime::Result<Option<Expr>> {
check_depth(depth)?;
let mut forms = vec![Expr::symbol("LIST")];
let mut cur = Some(head.checked_struct(&mut *store)?);
while let Some(node) = cur {
let car = node.field(&mut *store, 0)?;
let Some(member) = member_source(store, context, car, closures, depth + 1)? else {
return Ok(None);
forms.push(member);
cur = match node.field(&mut *store, 1)? {
Val::AnyRef(Some(next)) => Some(next.checked_struct(&mut *store)?),
_ => None,
Ok(Some(Expr::List(forms)))
fn member_source<S: AsContextMut>(
car: Val,
let Val::AnyRef(Some(car)) = car else {
return Ok(Some(Expr::Nil));
match classify_anyref(&mut *store, car, context.1)? {
AnyRefKind::Closure(_) => {
let Some(lambda) = read_closure(store, context, &car)?.into_constant() else {
let name = context.0.hidden_name("CARRY", &closures.len().to_string());
closures.push((name.clone(), lambda));
Ok(Some(Expr::Symbol(name)))
AnyRefKind::Pair => list_source(store, context, &car, closures, depth),
_ => Ok(read_ref(store, context, car, WasmType::AnyRef).into_constant()),