1
//! Macro-use expansion over a form, binding forms laid out so a name in a
2
//! binding position stays data.
3

            
4
use super::super::setf_scan::code_mapped;
5
use super::shared::labels_names;
6
use crate::ast::{Expr, LambdaParams};
7
use crate::compiler::expr::fold::template::expand_macro_use;
8
use crate::error::Result;
9
use crate::runtime::{Head, SymbolTable, with_sufficient_stack};
10
use std::cell::OnceCell;
11
use std::rc::Rc;
12

            
13
/// What stands for a use [`macro_expanded`] cannot expand, and the names it keeps.
14
pub(super) struct Expander<'a> {
15
    opaque: Option<&'a str>,
16
    /// The LABELS functions in scope: a call of one is not a macro use.
17
    shadowed: Vec<String>,
18
    /// The call heads to rename: a LABELS function of the creating scope to
19
    /// the alias that names it for good.
20
    aliases: Vec<(String, String)>,
21
    /// The head of the first use that could not be expanded, shared by the
22
    /// expanders `shadowing` derives.
23
    unexpanded: Rc<OnceCell<String>>,
24
}
25

            
26
impl<'a> Expander<'a> {
27
17332632
    pub(super) fn any() -> Self {
28
17332632
        Self::with(None)
29
17332632
    }
30

            
31
1170316
    pub(super) fn macro_use(opaque: &'a str) -> Self {
32
1170316
        Self::with(Some(opaque))
33
1170316
    }
34

            
35
18502948
    fn with(opaque: Option<&'a str>) -> Self {
36
18502948
        Expander {
37
18502948
            opaque,
38
18502948
            shadowed: Vec::new(),
39
18502948
            aliases: Vec::new(),
40
18502948
            unexpanded: Rc::default(),
41
18502948
        }
42
18502948
    }
43

            
44
17586
    fn aliasing(aliases: Vec<(String, String)>) -> Self {
45
17586
        Expander {
46
17586
            aliases,
47
17586
            ..Self::any()
48
17586
        }
49
17586
    }
50

            
51
5491880
    pub(super) fn shadowing(&self, names: impl Iterator<Item = String>) -> Self {
52
5491880
        Expander {
53
5491880
            opaque: self.opaque,
54
5491880
            shadowed: self.shadowed.iter().cloned().chain(names).collect(),
55
5491880
            aliases: self.aliases.clone(),
56
5491880
            unexpanded: Rc::clone(&self.unexpanded),
57
5491880
        }
58
5491880
    }
59

            
60
11299500
    pub(super) fn unexpanded(&self) -> Option<&str> {
61
11299500
        self.unexpanded.get().map(String::as_str)
62
11299500
    }
63

            
64
    /// `items` with the function a call or `(function NAME)` names replaced
65
    /// by its alias, unless an inner LABELS rebinds the name.
66
94023014
    fn aliased(&self, mut items: Vec<Expr>) -> Vec<Expr> {
67
94023014
        let at = match items.first() {
68
94022149
            Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("FUNCTION") => 1,
69
94008516
            _ => 0,
70
        };
71
94023014
        if let Some(Expr::Symbol(name)) = items.get(at)
72
94022143
            && !self.shadows(name)
73
93997266
            && let Some((_, alias)) = self.aliases.iter().find(|(from, _)| from == name)
74
        {
75
7933
            items[at] = Expr::symbol(alias);
76
94015081
        }
77
94023014
        items
78
94023014
    }
79

            
80
188244172
    fn shadows(&self, head: &str) -> bool {
81
188244172
        self.shadowed
82
188244172
            .iter()
83
24844764
            .any(|name| name.eq_ignore_ascii_case(head))
84
188244172
    }
85
}
86

            
87
/// `expr` with each user macro use replaced by its expansion, so the scans see
88
/// the stores a macro makes. A use that fails to expand stays as written, or
89
/// becomes the symbol `opaque`; the depth rides the scratch table, which every
90
/// nested expansion clones.
91
295959701
pub(super) fn macro_expanded(symbols: &SymbolTable, expr: &Expr, how: &Expander) -> Result<Expr> {
92
295959701
    with_sufficient_stack(|| match expr {
93
94228167
        Expr::List(elems) => match elems.first() {
94
94227302
            Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("QUOTE") => Ok(expr.clone()),
95
            Some(Expr::Symbol(head))
96
94222029
                if !how.shadows(head) && matches!(symbols.resolve_head(head), Head::Macro(..)) =>
97
            {
98
199880
                let mut scratch = symbols.clone();
99
199880
                scratch.enter_macro_expansion()?;
100
199880
                match expand_macro_use(&mut scratch, head, &elems[1..])? {
101
198161
                    Some(expansion) => macro_expanded(&scratch, &expansion, how),
102
                    None => {
103
1719
                        let _ = how.unexpanded.set(head.clone());
104
1719
                        Ok(how.opaque.map_or_else(|| expr.clone(), Expr::symbol))
105
                    }
106
                }
107
            }
108
94023014
            _ => laid_out(symbols, elems, how).map(|items| Expr::List(how.aliased(items))),
109
        },
110
        Expr::Cons(car, cdr) => Ok(Expr::Cons(
111
            Box::new(macro_expanded(symbols, car, how)?),
112
            Box::new(macro_expanded(symbols, cdr, how)?),
113
        )),
114
        Expr::Lambda(params, body) => Ok(Expr::Lambda(
115
3536
            params_expanded(symbols, params, how)?,
116
3536
            Box::new(macro_expanded(symbols, body, how)?),
117
        )),
118
616
        Expr::Quasiquote(template) => template
119
649
            .map_unquoted(&mut |form| macro_expanded(symbols, form, how))
120
616
            .map(|expanded| Expr::Quasiquote(Box::new(expanded))),
121
201727382
        _ => Ok(expr.clone()),
122
295959701
    })
123
295959701
}
124

            
125
/// `expr` with its macro uses expanded and each call of a LABELS function of
126
/// `symbols` renamed to the alias that outlives the form binding it.
127
9634526
pub(in crate::compiler) fn with_local_calls_aliased(
128
9634526
    symbols: &SymbolTable,
129
9634526
    expr: &Expr,
130
9634526
) -> Result<Expr> {
131
9634526
    let aliases = symbols.local_function_aliases();
132
9634526
    match aliases.is_empty() {
133
9616940
        true => Ok(expr.clone()),
134
17586
        false => macro_expanded(symbols, expr, &Expander::aliasing(aliases)),
135
    }
136
9634526
}
137

            
138
/// `params` with the macro uses of its default forms expanded.
139
5482697
pub(super) fn params_expanded(
140
5482697
    symbols: &SymbolTable,
141
5482697
    params: &LambdaParams,
142
5482697
    how: &Expander,
143
5482697
) -> Result<LambdaParams> {
144
5482697
    let mut params = params.clone();
145
5482697
    for default in params.defaults_mut() {
146
2236754
        *default = macro_expanded(symbols, default, how)?;
147
    }
148
5482697
    Ok(params)
149
5482697
}
150

            
151
/// `elems` with only its operands that are forms expanded; inside a LABELS
152
/// its function names are no macro uses.
153
94023014
fn laid_out(symbols: &SymbolTable, elems: &[Expr], how: &Expander) -> Result<Vec<Expr>> {
154
    let labelled;
155
94023014
    let how = match elems.split_first() {
156
94022149
        Some((Expr::Symbol(head), args)) if head.eq_ignore_ascii_case("LABELS") => {
157
12719
            labelled = how.shadowing(labels_names(args));
158
12719
            &labelled
159
        }
160
94010295
        _ => how,
161
    };
162
269910376
    code_mapped(elems, &mut |form| macro_expanded(symbols, form, how))
163
94023014
}