Lines
97.89 %
Functions
84.38 %
Branches
100 %
//! A closure factory: a function whose body is a lambda reading the
//! function's own parameters. The lambda outlives the inlined frame that binds
//! them, so each parameter it reads is rebound to a hidden variable of the
//! caller's scope, which the ordinary closure capture then picks up.
use crate::ast::{Expr, LambdaParams, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::special::{
MacroStores, macro_stores, mentions_expanded, param_names, reads_free, unescaped,
};
use crate::error::{Error, Result};
use crate::runtime::{Head, Symbol, SymbolKind, SymbolTable};
use super::eval::eval_value;
use super::lambda_params::compile_and_bind_lambda_params;
/// The lambda `call` returns, closed over the call's argument values, which are
/// bound (their effects emitted) in `symbols`.
pub(in crate::compiler) fn close_factory_call(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
call: &Expr,
) -> Result<Expr> {
let Expr::List(items) = call else {
return Err(not_a_factory());
let [Expr::Symbol(name), args @ ..] = items.as_slice() else {
let Head::Function(params, body) = symbols.resolve_head(name) else {
let (params, body) = (params.clone(), body.clone());
let Some(mut frame) =
compile_and_bind_lambda_params(ctx, emit, symbols, ¶ms, &body, args, Some(name))?
else {
let lambda = eval_value(&mut frame, &body)?;
match lambda {
Expr::Lambda(..) => close_over_params(symbols, &frame, (name, ¶ms), lambda),
_ => Err(not_a_factory()),
}
/// `value`, when it is a lambda reading parameters of `params` free, with each
/// of them rebound to a hidden variable of `symbols` holding its value in
/// `frame`.
pub(in crate::compiler) fn close_over_params(
frame: &SymbolTable,
(factory, params): (&str, &LambdaParams),
value: Expr,
let Expr::Lambda(lambda_params, lambda_body) = &value else {
let names: Vec<String> = param_names(params).map(str::to_string).collect();
return Ok(unescaped(frame, &names, value));
let mut bindings = Vec::new();
for name in param_names(params) {
if defaults_read(symbols, lambda_params, name)? {
return Err(Error::Compile(format!(
"a parameter default of the lambda a function returns reads the \
captured parameter {name}; read it in the body instead"
)));
if reads_free(symbols, &value, name)? {
match macro_stores(symbols, lambda_body, name)? {
MacroStores::Clean => {}
MacroStores::Assigns => {
"the lambda a function returns assigns its parameter {name}; \
a captured parameter is read-only"
MacroStores::Unexpanded(head) => {
"the lambda a function returns uses the macro {head}, \
which could not be expanded here"
let hidden = symbols.hidden_name(factory, name);
let mut variable = Symbol::new(&hidden, SymbolKind::Variable);
if let Some(held) = frame.lookup(name).and_then(Symbol::value) {
variable = variable.with_value(held.clone());
symbols.define(variable);
bindings.push(Expr::List(vec![Expr::symbol(name), Expr::symbol(&hidden)]));
if bindings.is_empty() {
return Ok(value);
let scope = [
Expr::symbol("LET"),
Expr::List(bindings),
lambda_body.as_ref().clone(),
];
Ok(Expr::Lambda(
lambda_params.clone(),
Box::new(Expr::List(scope.into())),
))
/// Whether a default of `params` reads `name` from outside the lambda: a
/// default sees only the parameters bound before it.
fn defaults_read(symbols: &SymbolTable, params: &LambdaParams, name: &str) -> Result<bool> {
let mut bound: Vec<&str> = params.required.iter().map(String::as_str).collect();
let optional = params
.optional
.iter()
.map(|(n, d)| (n.as_str(), d.as_ref()));
if group_reads(symbols, optional, name, &mut bound)? {
return Ok(true);
bound.extend(params.rest.as_deref());
let key = params
.key
.map(|p| (p.name.as_str(), p.default.as_ref()));
if group_reads(symbols, key, name, &mut bound)? {
let aux = params.aux.iter().map(|(n, d)| (n.as_str(), d.as_ref()));
group_reads(symbols, aux, name, &mut bound)
fn group_reads<'a>(
symbols: &SymbolTable,
group: impl Iterator<Item = (&'a str, Option<&'a Expr>)>,
name: &str,
bound: &mut Vec<&'a str>,
) -> Result<bool> {
for (param, default) in group {
if let Some(default) = default
&& !bound.contains(&name)
&& mentions_expanded(symbols, default, name)?
{
bound.push(param);
Ok(false)
/// The hidden variables a closed lambda's capture scope rebinds.
fn hidden_inits(value: &Expr) -> impl Iterator<Item = &str> {
let specs = match value {
Expr::Lambda(_, body) => match body.as_ref() {
Expr::List(scope) => scope.get(1),
_ => None,
},
let specs = match specs {
Some(Expr::List(specs)) => specs.as_slice(),
_ => &[],
specs.iter().filter_map(|spec| match spec {
Expr::List(pair) => match pair.get(1) {
Some(Expr::Symbol(init)) if SymbolTable::is_hidden_name(init) => Some(init.as_str()),
})
/// A function value closed over hidden variables that `symbols` does not hold:
/// evaluating its call built the lambda where nothing could bind them.
pub(in crate::compiler) fn reject_unbound_capture(
value: &Expr,
) -> Result<()> {
match hidden_inits(value).find(|init| symbols.lookup(init).is_none()) {
Some(hidden) => Err(Error::undefined_symbol(hidden)),
None => Ok(()),
/// `value`, or the untyped placeholder when it is a lambda closed over a
/// hidden variable holding a runtime value no local binds.
pub(in crate::compiler) fn unbound_runtime_capture(symbols: &SymbolTable, value: Expr) -> Expr {
let runtime = hidden_inits(&value).any(|init| {
symbols
.lookup(init)
.and_then(Symbol::value)
.is_some_and(Expr::is_wasm_runtime)
});
match runtime {
true => Expr::WasmRuntime(WasmType::AnyRef),
false => value,
fn not_a_factory() -> Error {
Error::Compile("a closure factory call must return a lambda".to_string())
#[cfg(test)]
#[path = "closure_factory_tests.rs"]
mod tests;