Lines
97.92 %
Functions
100 %
Branches
//! Macro-use expansion over a form, binding forms laid out so a name in a
//! binding position stays data.
use super::super::setf_scan::code_mapped;
use super::shared::labels_names;
use crate::ast::{Expr, LambdaParams};
use crate::compiler::expr::fold::template::expand_macro_use;
use crate::error::Result;
use crate::runtime::{Head, SymbolTable, with_sufficient_stack};
use std::cell::OnceCell;
use std::rc::Rc;
/// What stands for a use [`macro_expanded`] cannot expand, and the names it keeps.
pub(super) struct Expander<'a> {
opaque: Option<&'a str>,
/// The LABELS functions in scope: a call of one is not a macro use.
shadowed: Vec<String>,
/// The call heads to rename: a LABELS function of the creating scope to
/// the alias that names it for good.
aliases: Vec<(String, String)>,
/// The head of the first use that could not be expanded, shared by the
/// expanders `shadowing` derives.
unexpanded: Rc<OnceCell<String>>,
}
impl<'a> Expander<'a> {
pub(super) fn any() -> Self {
Self::with(None)
pub(super) fn macro_use(opaque: &'a str) -> Self {
Self::with(Some(opaque))
fn with(opaque: Option<&'a str>) -> Self {
Expander {
opaque,
shadowed: Vec::new(),
aliases: Vec::new(),
unexpanded: Rc::default(),
fn aliasing(aliases: Vec<(String, String)>) -> Self {
aliases,
..Self::any()
pub(super) fn shadowing(&self, names: impl Iterator<Item = String>) -> Self {
opaque: self.opaque,
shadowed: self.shadowed.iter().cloned().chain(names).collect(),
aliases: self.aliases.clone(),
unexpanded: Rc::clone(&self.unexpanded),
pub(super) fn unexpanded(&self) -> Option<&str> {
self.unexpanded.get().map(String::as_str)
/// `items` with the function a call or `(function NAME)` names replaced
/// by its alias, unless an inner LABELS rebinds the name.
fn aliased(&self, mut items: Vec<Expr>) -> Vec<Expr> {
let at = match items.first() {
Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("FUNCTION") => 1,
_ => 0,
};
if let Some(Expr::Symbol(name)) = items.get(at)
&& !self.shadows(name)
&& let Some((_, alias)) = self.aliases.iter().find(|(from, _)| from == name)
{
items[at] = Expr::symbol(alias);
items
fn shadows(&self, head: &str) -> bool {
self.shadowed
.iter()
.any(|name| name.eq_ignore_ascii_case(head))
/// `expr` with each user macro use replaced by its expansion, so the scans see
/// the stores a macro makes. A use that fails to expand stays as written, or
/// becomes the symbol `opaque`; the depth rides the scratch table, which every
/// nested expansion clones.
pub(super) fn macro_expanded(symbols: &SymbolTable, expr: &Expr, how: &Expander) -> Result<Expr> {
with_sufficient_stack(|| match expr {
Expr::List(elems) => match elems.first() {
Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("QUOTE") => Ok(expr.clone()),
Some(Expr::Symbol(head))
if !how.shadows(head) && matches!(symbols.resolve_head(head), Head::Macro(..)) =>
let mut scratch = symbols.clone();
scratch.enter_macro_expansion()?;
match expand_macro_use(&mut scratch, head, &elems[1..])? {
Some(expansion) => macro_expanded(&scratch, &expansion, how),
None => {
let _ = how.unexpanded.set(head.clone());
Ok(how.opaque.map_or_else(|| expr.clone(), Expr::symbol))
_ => laid_out(symbols, elems, how).map(|items| Expr::List(how.aliased(items))),
},
Expr::Cons(car, cdr) => Ok(Expr::Cons(
Box::new(macro_expanded(symbols, car, how)?),
Box::new(macro_expanded(symbols, cdr, how)?),
)),
Expr::Lambda(params, body) => Ok(Expr::Lambda(
params_expanded(symbols, params, how)?,
Box::new(macro_expanded(symbols, body, how)?),
Expr::Quasiquote(template) => template
.map_unquoted(&mut |form| macro_expanded(symbols, form, how))
.map(|expanded| Expr::Quasiquote(Box::new(expanded))),
_ => Ok(expr.clone()),
})
/// `expr` with its macro uses expanded and each call of a LABELS function of
/// `symbols` renamed to the alias that outlives the form binding it.
pub(in crate::compiler) fn with_local_calls_aliased(
symbols: &SymbolTable,
expr: &Expr,
) -> Result<Expr> {
let aliases = symbols.local_function_aliases();
match aliases.is_empty() {
true => Ok(expr.clone()),
false => macro_expanded(symbols, expr, &Expander::aliasing(aliases)),
/// `params` with the macro uses of its default forms expanded.
pub(super) fn params_expanded(
params: &LambdaParams,
how: &Expander,
) -> Result<LambdaParams> {
let mut params = params.clone();
for default in params.defaults_mut() {
*default = macro_expanded(symbols, default, how)?;
Ok(params)
/// `elems` with only its operands that are forms expanded; inside a LABELS
/// its function names are no macro uses.
fn laid_out(symbols: &SymbolTable, elems: &[Expr], how: &Expander) -> Result<Vec<Expr>> {
let labelled;
let how = match elems.split_first() {
Some((Expr::Symbol(head), args)) if head.eq_ignore_ascii_case("LABELS") => {
labelled = how.shadowing(labels_names(args));
&labelled
_ => how,
code_mapped(elems, &mut |form| macro_expanded(symbols, form, how))