1
//! The key of a binder site: which form binds the variable, and the constants
2
//! and local functions that form references. Eval and codegen compute it here
3
//! from the same form and table, so both name a site alike. It never holds a
4
//! type the fixpoint solves, so widening a home cannot re-key a site.
5

            
6
use std::collections::BTreeSet;
7
use std::hash::{DefaultHasher, Hash, Hasher};
8

            
9
use tracing::trace;
10

            
11
use crate::ast::{Expr, LambdaParams, WasmType};
12
use crate::compiler::expr::classify_stack_type;
13
use crate::compiler::join::fact;
14
use crate::compiler::special::binding::shared::assigned_scope;
15
use crate::runtime::{HomeKey, Symbol, SymbolTable};
16

            
17
#[derive(Clone, Copy, Debug)]
18
pub(crate) enum Surface {
19
    Eval,
20
    Codegen,
21
}
22

            
23
/// The key of each binder of a form, `None` for one no store can reach.
24
pub(crate) type SiteKeys = Vec<Option<HomeKey>>;
25

            
26
/// A binder `binder_keys` keys: its name, whether a DO step stores to it, and
27
/// the forms its stores can come from.
28
pub(crate) type Binder<'a> = (&'a str, bool, Vec<&'a Expr>);
29

            
30
/// The key of each binder of `head` that a store can reach, `None` for the
31
/// rest: an assigned or stepped one that is not a dynamic special, outside a
32
/// macro body (which only evaluates and has no code to give a home).
33
4834679
pub(crate) fn binder_keys<'a>(
34
4834679
    symbols: &SymbolTable,
35
4834679
    surface: Surface,
36
4834679
    (head, args): (&str, &[Expr]),
37
4834679
    binders: impl IntoIterator<Item = Binder<'a>>,
38
4834679
) -> SiteKeys {
39
4834679
    let binders: Vec<Binder> = binders.into_iter().collect();
40
4834679
    let scratch = symbols.scan_scratch();
41
5283792
    let assigned = |(var, stepped, forms): &Binder| {
42
5283792
        !symbols.is_macro_expansion()
43
5068341
            && !symbols.is_dynamic_special(var)
44
5021102
            && (*stepped
45
4612726
                || !matches!(
46
4612726
                    assigned_scope(&scratch, var, forms.iter().copied()),
47
4612726
                    Ok(None)
48
4612726
                ))
49
5283792
    };
50
4834679
    let sites: Vec<bool> = binders.iter().map(assigned).collect();
51
4834679
    if !sites.contains(&true) {
52
4226715
        return vec![None; binders.len()];
53
607964
    }
54
607964
    let (form, names) = form_digest(head, args);
55
607964
    let scope = scope_digest(symbols, &names);
56
607964
    let owner = symbols.function_owner();
57
607964
    binders
58
607964
        .iter()
59
607964
        .zip(sites)
60
887142
        .map(|((var, ..), site)| {
61
887142
            let key = site.then(|| HomeKey::Binder(owner, form, (*var).to_string(), scope))?;
62
752660
            trace!(?surface, ?key, "binder site");
63
752660
            Some(key)
64
887142
        })
65
        .collect()
66
4834679
}
67

            
68
/// The identity of a function body: a global function by its name; a LABELS
69
/// function or a lambda by its source within the function `symbols` compiles.
70
3893866
pub(crate) fn function_owner(symbols: &SymbolTable, callee: Option<&str>, body: &Expr) -> u64 {
71
3893866
    let global = callee.filter(|name| !symbols.lookup(name).is_some_and(Symbol::is_local_function));
72
3893866
    let mut hasher = DefaultHasher::new();
73
3893866
    match global {
74
2247755
        Some(name) => name.hash(&mut hasher),
75
1646111
        None => (
76
1646111
            symbols.function_owner(),
77
1646111
            form_digest(callee.unwrap_or_default(), std::slice::from_ref(body)).0,
78
1646111
        )
79
1646111
            .hash(&mut hasher),
80
    }
81
3893866
    hasher.finish()
82
3893866
}
83

            
84
/// A structural hash of the forms, walked with an explicit stack so a deep
85
/// datum cannot overflow the native one. It reads the source text only, and
86
/// returns the symbols the forms mention.
87
2254718
fn form_digest<'a>(head: &str, forms: &'a [Expr]) -> (u64, BTreeSet<&'a str>) {
88
2254718
    let mut hasher = DefaultHasher::new();
89
2254718
    let mut names = BTreeSet::new();
90
2254718
    head.hash(&mut hasher);
91
2254718
    let mut pending: Vec<&Expr> = forms.iter().rev().collect();
92
56284181
    while let Some(expr) = pending.pop() {
93
54029463
        std::mem::discriminant(expr).hash(&mut hasher);
94
54029463
        match expr {
95
            Expr::Nil
96
            | Expr::T
97
            | Expr::RuntimeValue(_)
98
            | Expr::WasmRuntime(_)
99
            | Expr::WasmLocal(..)
100
            | Expr::WasmGlobal(..)
101
1017921
            | Expr::Instance(..) => {}
102
4365585
            Expr::Number(n) => n.hash(&mut hasher),
103
            Expr::Symbol(text) => {
104
25510641
                names.insert(text.as_str());
105
25510641
                text.hash(&mut hasher);
106
            }
107
88829
            Expr::String(text) | Expr::Keyword(text) => text.hash(&mut hasher),
108
            Expr::Bytes(bytes) => bytes.hash(&mut hasher),
109
            Expr::Cons(car, cdr) => pending.extend([cdr.as_ref(), car.as_ref()]),
110
            Expr::List(items) => {
111
22971377
                items.len().hash(&mut hasher);
112
22971377
                pending.extend(items.iter().rev());
113
            }
114
            Expr::Quote(inner)
115
            | Expr::Datum(inner)
116
            | Expr::Quasiquote(inner)
117
            | Expr::Unquote(inner)
118
72393
            | Expr::UnquoteSplicing(inner) => pending.push(inner),
119
            Expr::Lambda(params, body) => {
120
2717
                hash_param_names(params, &mut hasher);
121
2717
                pending.push(body);
122
2717
                pending.extend(params.defaults().collect::<Vec<_>>().into_iter().rev());
123
            }
124
        }
125
    }
126
2254718
    (hasher.finish(), names)
127
2254718
}
128

            
129
2717
fn hash_param_names(params: &LambdaParams, hasher: &mut DefaultHasher) {
130
2717
    params.required.hash(hasher);
131
2717
    params
132
2717
        .optional
133
2717
        .iter()
134
        .for_each(|(name, _)| name.hash(hasher));
135
2717
    params.rest.hash(hasher);
136
2717
    params
137
2717
        .key
138
2717
        .iter()
139
        .for_each(|param| param.keyword.hash(hasher));
140
2717
    params.aux.iter().for_each(|(name, _)| name.hash(hasher));
141
2717
}
142

            
143
#[derive(Hash)]
144
enum Scope {
145
    Const(Option<WasmType>),
146
    Runtime,
147
    LocalFn(u64),
148
}
149

            
150
/// What a referenced name contributes to the key: a constant by its literal
151
/// type, a local function by its source, anything else (a closure, a local, an
152
/// alias of a global) as runtime.
153
4133814
fn scope_of(symbol: &Symbol) -> Option<Scope> {
154
4133814
    if symbol.is_local_function() {
155
637
        let lambda = symbol.function()?;
156
637
        let (digest, _) = form_digest("", std::slice::from_ref(lambda));
157
637
        return Some(Scope::LocalFn(digest));
158
4133177
    }
159
4133177
    Some(match symbol.value()? {
160
        value
161
473952
            if value.is_wasm_runtime()
162
147794
                || matches!(value, Expr::RuntimeValue(_) | Expr::Lambda(..)) =>
163
        {
164
326170
            Scope::Runtime
165
        }
166
147782
        value => Scope::Const(classify_stack_type(value).map(fact)),
167
    })
168
4133814
}
169

            
170
607964
fn scope_digest(symbols: &SymbolTable, names: &BTreeSet<&str>) -> u64 {
171
607964
    let mut hasher = DefaultHasher::new();
172
607964
    for name in names {
173
5596029
        let scope = symbols
174
5596029
            .lookup(name)
175
4291865
            .filter(|_| !symbols.is_special(name))
176
5596029
            .and_then(scope_of);
177
5596029
        if let Some(scope) = scope {
178
474589
            (name, scope).hash(&mut hasher);
179
5121440
        }
180
    }
181
607964
    hasher.finish()
182
607964
}
183

            
184
#[cfg(test)]
185
#[path = "binder_key_tests.rs"]
186
mod tests;