1
//! Which macros the scoped walk may expand: a *template* macro is one whose
2
//! expansion reads nothing from the environment — a literal, a quoted
3
//! datum, or a backquote template splicing only its required and rest
4
//! parameters — so its expansion is the same at every use site and the
5
//! walk can scan it. Any other macro's expansion is a computation the walk
6
//! does not run.
7

            
8
use crate::ast::{Expr, LambdaParams};
9
use crate::compiler::expr::expand_macro;
10
use crate::error::{Error, Result};
11
use crate::runtime::{Head, SymbolTable};
12

            
13
/// The parameters and body of `head` when it is a template macro.
14
213765
pub(crate) fn template_of<'a>(
15
213765
    symbols: &'a SymbolTable,
16
213765
    head: &str,
17
213765
) -> Option<(&'a LambdaParams, &'a Expr)> {
18
213765
    let Head::Macro(params, body) = symbols.resolve_head(head) else {
19
        return None;
20
    };
21
213765
    let template = match body {
22
116022
        Expr::Quasiquote(template) => template,
23
1277
        Expr::Quote(_) => return Some((params, body)),
24
96466
        literal if is_literal(literal) => return Some((params, body)),
25
81485
        _ => return None,
26
    };
27
116022
    if !(params.optional.is_empty() && params.key.is_empty() && params.aux.is_empty()) {
28
        return None;
29
116022
    }
30
116022
    splices_only_params(params, template).then_some((params, body))
31
213765
}
32

            
33
/// Whether every evaluated position of `template` is a bare required or
34
/// rest parameter: the one shape whose expansion depends on nothing but the
35
/// use-site arguments.
36
116022
fn splices_only_params(params: &LambdaParams, template: &Expr) -> bool {
37
223475
    let is_param = |symbol: &str| {
38
223475
        params
39
223475
            .required
40
223475
            .iter()
41
223475
            .chain(params.rest.iter())
42
331996
            .any(|param| param.eq_ignore_ascii_case(symbol))
43
223475
    };
44
116022
    let mut pending: Vec<&Expr> = vec![template];
45
902123
    while let Some(part) = pending.pop() {
46
786102
        match part {
47
223475
            Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => match inner.as_ref() {
48
223475
                Expr::Symbol(symbol) if is_param(symbol) => {}
49
1
                _ => return false,
50
            },
51
            Expr::Quasiquote(_) => return false,
52
223853
            Expr::List(items) => pending.extend(items),
53
            Expr::Cons(car, cdr) => pending.extend([car.as_ref(), cdr.as_ref()]),
54
            Expr::Quote(inner) => pending.push(inner),
55
338774
            _ => {}
56
        }
57
    }
58
116021
    true
59
116022
}
60

            
61
96466
fn is_literal(form: &Expr) -> bool {
62
96466
    matches!(
63
96466
        form,
64
        Expr::Nil | Expr::T | Expr::Number(_) | Expr::String(_) | Expr::Keyword(_)
65
    )
66
96466
}
67

            
68
/// The expansion of a use of any user macro `head`, or `None` when expanding
69
/// it fails. Only a resource error is an `Err`.
70
391099
pub(crate) fn expand_macro_use(
71
391099
    scratch: &mut SymbolTable,
72
391099
    head: &str,
73
391099
    args: &[Expr],
74
391099
) -> Result<Option<Expr>> {
75
391099
    let Head::Macro(params, body) = scratch.resolve_head(head) else {
76
        return Ok(None);
77
    };
78
391099
    let (params, body) = (params.clone(), body.clone());
79
391099
    match expand_macro(scratch, &params, &body, args) {
80
369702
        Ok(expansion) => Ok(Some(expansion)),
81
10220
        Err(Error::Resource(what)) => Err(Error::Resource(what)),
82
11177
        Err(_) => Ok(None),
83
    }
84
391099
}