1
//! The lexical constants a lambda reads, which its body binds so that it no
2
//! longer depends on the scope that made it.
3

            
4
use crate::ast::{Expr, LambdaParams};
5
use crate::compiler::special::param_names;
6
use crate::error::{Error, Result};
7
use crate::runtime::SymbolTable;
8

            
9
use super::captures::compute_captures;
10

            
11
/// The lexical constants of the creating scope the lambda reads, bound around
12
/// its body; one it stores to or that holds a runtime value stays free. A
13
/// lambda built while a macro expands is spliced into the caller's code, so
14
/// there a free name the expansion does not bind would resolve in the
15
/// caller's scope.
16
2078315
pub(super) fn close_over_constants(
17
2078315
    symbols: &SymbolTable,
18
2078315
    params: &LambdaParams,
19
2078315
    body: Expr,
20
2078315
) -> Result<Expr> {
21
2078315
    if symbols.is_macro_expansion()
22
196526
        && let Some(name) = foreign_read(symbols, params, &body)?
23
    {
24
2498
        return Err(Error::UndefinedSymbol(name));
25
2075817
    }
26
2075817
    let bindings: Vec<Expr> = read_constants(symbols, params, &body)?
27
        .into_iter()
28
1119007
        .filter(|(_, value)| is_plain(value))
29
1119007
        .map(|(name, value)| Expr::List(vec![Expr::Symbol(name), as_datum(value)]))
30
        .collect();
31
2075817
    Ok(match bindings.is_empty() {
32
956831
        true => body,
33
1118986
        false => Expr::List(vec![Expr::symbol("LET"), Expr::List(bindings), body]),
34
    })
35
2078315
}
36

            
37
/// A free name the body reads that is no global and no variable of the
38
/// expansion: unbound, or a lexical of the caller's scope.
39
196526
fn foreign_read(
40
196526
    symbols: &SymbolTable,
41
196526
    params: &LambdaParams,
42
196526
    body: &Expr,
43
196526
) -> Result<Option<String>> {
44
196526
    let captures = compute_captures(symbols, params, body)?;
45
196526
    Ok(captures
46
196526
        .read_names()
47
194819
        .find(|name| {
48
194819
            !symbols.is_macro_local(name)
49
119315
                && (symbols.lookup(name).is_none() || symbols.is_lexical_variable(name))
50
194819
        })
51
196526
        .map(str::to_string))
52
196526
}
53

            
54
/// A constant that is a raw symbol or list datum, quoted so the binding does
55
/// not evaluate it in the scope the lambda ends up in.
56
1119007
fn as_datum(value: Expr) -> Expr {
57
1119007
    match value {
58
7490
        Expr::Symbol(_) | Expr::List(_) | Expr::Cons(..) => Expr::Quote(Box::new(value)),
59
1111517
        other => other,
60
    }
61
1119007
}
62

            
63
/// Whether the body reads a lexical constant it could not bind.
64
193724
pub(super) fn reads_unbound_constant(
65
193724
    symbols: &SymbolTable,
66
193724
    params: &LambdaParams,
67
193724
    body: &Expr,
68
193724
) -> bool {
69
193724
    read_constants(symbols, params, body).map_or(true, |constants| {
70
193724
        constants.iter().any(|(_, value)| !is_plain(value))
71
193724
    })
72
193724
}
73

            
74
1119033
fn is_plain(value: &Expr) -> bool {
75
1119033
    !value.any_form(Expr::is_runtime_variable)
76
1119033
}
77

            
78
2269541
fn read_constants(
79
2269541
    symbols: &SymbolTable,
80
2269541
    params: &LambdaParams,
81
2269541
    body: &Expr,
82
2269541
) -> Result<Vec<(String, Expr)>> {
83
2269541
    let own: Vec<&str> = param_names(params).collect();
84
2269541
    let named: Vec<(String, Expr)> = symbols
85
2269541
        .lexical_constants()
86
2269541
        .into_iter()
87
1199267
        .filter(|(name, _)| !own.contains(&name.as_str()))
88
13988400
        .filter(|(name, _)| body.any_form(|form| form.as_symbol() == Some(name)))
89
        .collect();
90
2269541
    if named.is_empty() {
91
1142677
        return Ok(named);
92
1126864
    }
93
1126864
    let captures = compute_captures(symbols, params, body)?;
94
1126864
    Ok(named
95
1126864
        .into_iter()
96
1126896
        .filter(|(name, _)| captures.reads(name) && !captures.stores_to(name))
97
        .collect())
98
2269541
}
99

            
100
#[cfg(test)]
101
#[path = "constants_tests.rs"]
102
mod tests;