1
//! Whether a form calls a function that does not outlive its unit.
2

            
3
use super::super::setf_scan::code_forms;
4
use super::shared::labels_names;
5
use crate::ast::Expr;
6
use crate::runtime::SymbolTable;
7

            
8
/// Whether the macro-expanded `body` calls, or takes with FUNCTION, a LABELS
9
/// function of the enclosing code or a user macro that could not be expanded.
10
/// A name in a variable position or in quoted data is no call.
11
194986
pub(in crate::compiler) fn calls_form_bound(symbols: &SymbolTable, body: &Expr) -> bool {
12
194986
    calls(symbols, body, &[])
13
194986
}
14

            
15
483851
fn calls(symbols: &SymbolTable, expr: &Expr, defined: &[String]) -> bool {
16
483851
    match expr {
17
169548
        Expr::List(elems) => list_calls(symbols, elems, defined),
18
        Expr::Cons(car, cdr) => calls(symbols, car, defined) || calls(symbols, cdr, defined),
19
1456
        Expr::Lambda(_, body) => calls(symbols, body, defined),
20
        Expr::Quasiquote(template) => template
21
            .unquoted_forms()
22
            .into_iter()
23
            .any(|form| calls(symbols, form, defined)),
24
312847
        _ => false,
25
    }
26
483851
}
27

            
28
169548
fn list_calls(symbols: &SymbolTable, elems: &[Expr], defined: &[String]) -> bool {
29
169548
    let Some((Expr::Symbol(head), args)) = elems.split_first() else {
30
        return elems.iter().any(|elem| calls(symbols, elem, defined));
31
    };
32
171836
    let bound = |name: &str| {
33
171836
        symbols.is_form_bound(name) && !defined.iter().any(|d| d.eq_ignore_ascii_case(name))
34
171836
    };
35
169548
    if head.eq_ignore_ascii_case("QUOTE") {
36
1
        return false;
37
169547
    }
38
169547
    if bound(head) {
39
1257
        return true;
40
168290
    }
41
168290
    if head.eq_ignore_ascii_case("FUNCTION") {
42
2289
        return match args.first() {
43
2289
            Some(Expr::Symbol(name)) => bound(name),
44
            Some(other) => calls(symbols, other, defined),
45
            None => false,
46
        };
47
166001
    }
48
166001
    if head.eq_ignore_ascii_case("LABELS") {
49
1672
        let inner: Vec<String> = defined.iter().cloned().chain(labels_names(args)).collect();
50
3347
        return code_forms(elems).any(|form| calls(symbols, form, &inner));
51
164329
    }
52
284062
    code_forms(elems).any(|form| calls(symbols, form, defined))
53
169548
}
54

            
55
#[cfg(test)]
56
#[path = "form_bound_tests.rs"]
57
mod tests;