Lines
88.89 %
Functions
100 %
Branches
//! Which macros the scoped walk may expand: a *template* macro is one whose
//! expansion reads nothing from the environment — a literal, a quoted
//! datum, or a backquote template splicing only its required and rest
//! parameters — so its expansion is the same at every use site and the
//! walk can scan it. Any other macro's expansion is a computation the walk
//! does not run.
use crate::ast::{Expr, LambdaParams};
use crate::compiler::expr::expand_macro;
use crate::error::{Error, Result};
use crate::runtime::{Head, SymbolTable};
/// The parameters and body of `head` when it is a template macro.
pub(crate) fn template_of<'a>(
symbols: &'a SymbolTable,
head: &str,
) -> Option<(&'a LambdaParams, &'a Expr)> {
let Head::Macro(params, body) = symbols.resolve_head(head) else {
return None;
};
let template = match body {
Expr::Quasiquote(template) => template,
Expr::Quote(_) => return Some((params, body)),
literal if is_literal(literal) => return Some((params, body)),
_ => return None,
if !(params.optional.is_empty() && params.key.is_empty() && params.aux.is_empty()) {
}
splices_only_params(params, template).then_some((params, body))
/// Whether every evaluated position of `template` is a bare required or
/// rest parameter: the one shape whose expansion depends on nothing but the
/// use-site arguments.
fn splices_only_params(params: &LambdaParams, template: &Expr) -> bool {
let is_param = |symbol: &str| {
params
.required
.iter()
.chain(params.rest.iter())
.any(|param| param.eq_ignore_ascii_case(symbol))
let mut pending: Vec<&Expr> = vec![template];
while let Some(part) = pending.pop() {
match part {
Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => match inner.as_ref() {
Expr::Symbol(symbol) if is_param(symbol) => {}
_ => return false,
},
Expr::Quasiquote(_) => return false,
Expr::List(items) => pending.extend(items),
Expr::Cons(car, cdr) => pending.extend([car.as_ref(), cdr.as_ref()]),
Expr::Quote(inner) => pending.push(inner),
_ => {}
true
fn is_literal(form: &Expr) -> bool {
matches!(
form,
Expr::Nil | Expr::T | Expr::Number(_) | Expr::String(_) | Expr::Keyword(_)
)
/// The expansion of a use of any user macro `head`, or `None` when expanding
/// it fails. Only a resource error is an `Err`.
pub(crate) fn expand_macro_use(
scratch: &mut SymbolTable,
args: &[Expr],
) -> Result<Option<Expr>> {
let Head::Macro(params, body) = scratch.resolve_head(head) else {
return Ok(None);
let (params, body) = (params.clone(), body.clone());
match expand_macro(scratch, ¶ms, &body, args) {
Ok(expansion) => Ok(Some(expansion)),
Err(Error::Resource(what)) => Err(Error::Resource(what)),
Err(_) => Ok(None),