Lines
100 %
Functions
96.67 %
Branches
//! The lexical constants a lambda reads, which its body binds so that it no
//! longer depends on the scope that made it.
use crate::ast::{Expr, LambdaParams};
use crate::compiler::special::param_names;
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::captures::compute_captures;
/// The lexical constants of the creating scope the lambda reads, bound around
/// its body; one it stores to or that holds a runtime value stays free. A
/// lambda built while a macro expands is spliced into the caller's code, so
/// there a free name the expansion does not bind would resolve in the
/// caller's scope.
pub(super) fn close_over_constants(
symbols: &SymbolTable,
params: &LambdaParams,
body: Expr,
) -> Result<Expr> {
if symbols.is_macro_expansion()
&& let Some(name) = foreign_read(symbols, params, &body)?
{
return Err(Error::UndefinedSymbol(name));
}
let bindings: Vec<Expr> = read_constants(symbols, params, &body)?
.into_iter()
.filter(|(_, value)| is_plain(value))
.map(|(name, value)| Expr::List(vec![Expr::Symbol(name), as_datum(value)]))
.collect();
Ok(match bindings.is_empty() {
true => body,
false => Expr::List(vec![Expr::symbol("LET"), Expr::List(bindings), body]),
})
/// A free name the body reads that is no global and no variable of the
/// expansion: unbound, or a lexical of the caller's scope.
fn foreign_read(
body: &Expr,
) -> Result<Option<String>> {
let captures = compute_captures(symbols, params, body)?;
Ok(captures
.read_names()
.find(|name| {
!symbols.is_macro_local(name)
&& (symbols.lookup(name).is_none() || symbols.is_lexical_variable(name))
.map(str::to_string))
/// A constant that is a raw symbol or list datum, quoted so the binding does
/// not evaluate it in the scope the lambda ends up in.
fn as_datum(value: Expr) -> Expr {
match value {
Expr::Symbol(_) | Expr::List(_) | Expr::Cons(..) => Expr::Quote(Box::new(value)),
other => other,
/// Whether the body reads a lexical constant it could not bind.
pub(super) fn reads_unbound_constant(
) -> bool {
read_constants(symbols, params, body).map_or(true, |constants| {
constants.iter().any(|(_, value)| !is_plain(value))
fn is_plain(value: &Expr) -> bool {
!value.any_form(Expr::is_runtime_variable)
fn read_constants(
) -> Result<Vec<(String, Expr)>> {
let own: Vec<&str> = param_names(params).collect();
let named: Vec<(String, Expr)> = symbols
.lexical_constants()
.filter(|(name, _)| !own.contains(&name.as_str()))
.filter(|(name, _)| body.any_form(|form| form.as_symbol() == Some(name)))
if named.is_empty() {
return Ok(named);
Ok(named
.filter(|(name, _)| captures.reads(name) && !captures.stores_to(name))
.collect())
#[cfg(test)]
#[path = "constants_tests.rs"]
mod tests;