1
//! Free-variable analysis for lambda bodies.
2
//!
3
//! Tier 1.5 of the error-processing model rewrites defuns and lambdas
4
//! to emit as real wasm functions instead of inline templates. A real
5
//! wasm function only sees its own params + globals + table imports,
6
//! so any binding the body references that lives in the surrounding
7
//! lexical scope must travel in via a closure environment struct.
8
//! [`compute_captures`] picks out exactly those names; subsequent
9
//! slices use the result to shape the env-struct (#34) and to emit the
10
//! body fn (#29).
11
//!
12
//! What counts as a capture: a name `n` referenced in the body where
13
//! the in-scope `SymbolTable` resolves `n` to a runtime binding
14
//! (`Expr::WasmRuntime` / `Expr::WasmLocal`) and `n` is **not** rebound
15
//! by an enclosing form inside the body (the lambda's own params, or
16
//! a nested LET / LET* / LAMBDA / LABELS / DOLIST / DO / DO*).
17
//! Constants, builtins, special forms, and globally-defined defuns
18
//! don't need capture — they remain reachable from the wasm function
19
//! via the same global symbol table the call-site sees.
20
//!
21
//! The pass is purely structural: it walks `Expr` and never emits
22
//! wasm. Body code is not modified — captures are just enumerated for
23
//! later phases.
24

            
25
mod follow;
26
#[cfg(test)]
27
mod tests;
28

            
29
use crate::ast::{Expr, LambdaParams};
30
use crate::compiler::special::binding::spec_name;
31
use crate::compiler::special::param_names;
32
use crate::compiler::special::setf_scan::{Step, binder, binder_steps, forms_from, spec_forms};
33
use crate::error::{Error, Result};
34
use crate::runtime::{SymbolTable, with_sufficient_stack};
35
use follow::{follow_designator, follow_function, follow_macro, local_function_key};
36

            
37
/// Ordered set of captured names. Insertion-order is preserved so the
38
/// env-struct field layout is deterministic — the body emitter and
39
/// the call-site env-construction phase walk the same order.
40
#[derive(Debug, Default)]
41
pub struct CaptureSet {
42
    names: Vec<String>,
43
    /// Free names the body reads, in or out of the table's runtime bindings.
44
    read: Vec<String>,
45
    /// Free names the body reads that the table holds no symbol for.
46
    unbound: Vec<String>,
47
    /// Free names the body (or a user function it calls) `SETF`s.
48
    stored: Vec<String>,
49
    /// A macro use whose expansion the walk cannot read: it may store to any
50
    /// captured name.
51
    opaque_store: bool,
52
    /// User functions already followed, and how deep the walk is in them.
53
    followed: Vec<String>,
54
    depth: usize,
55
    /// The first reason the walk could not follow the body to the end.
56
    refused: Option<Error>,
57
}
58

            
59
impl CaptureSet {
60
61650
    pub fn insert(&mut self, name: &str) {
61
61650
        if !self.names.iter().any(|n| n == name) {
62
42815
            self.names.push(name.to_string());
63
18835
        }
64
61650
    }
65

            
66
638373
    pub fn iter(&self) -> impl Iterator<Item = &str> {
67
638373
        self.names.iter().map(String::as_str)
68
638373
    }
69

            
70
8749193
    fn note_read(&mut self, name: &str) {
71
13966050
        if !self.read.iter().any(|n| n == name) {
72
3997021
            self.read.push(name.to_string());
73
4752172
        }
74
8749193
    }
75

            
76
10672
    fn note_unbound(&mut self, name: &str) {
77
16750
        if !self.unbound.iter().any(|n| n == name) {
78
7070
            self.unbound.push(name.to_string());
79
3602
        }
80
10672
    }
81

            
82
    /// The free names the body reads, bound by the table or not.
83
196526
    pub fn read_names(&self) -> impl Iterator<Item = &str> {
84
196526
        self.read.iter().chain(&self.unbound).map(String::as_str)
85
196526
    }
86

            
87
    /// Whether the body reads the free name `name`, quoted data aside.
88
    #[must_use]
89
1129398
    pub fn reads(&self, name: &str) -> bool {
90
2167838
        self.read.iter().any(|n| n == name)
91
1129398
    }
92

            
93
    /// Whether the body may store to the free name `name`.
94
    #[must_use]
95
1145627
    pub fn stores_to(&self, name: &str) -> bool {
96
1145627
        self.opaque_store || self.stored.iter().any(|stored| stored == name)
97
1145627
    }
98

            
99
    /// The captured names the body stores to; a store to a name that has no
100
    /// shared cell would land in the closure's copy.
101
300523
    pub fn stored_captures(&self) -> impl Iterator<Item = &str> {
102
300523
        self.iter().filter(|name| self.stores_to(name))
103
300523
    }
104

            
105
    /// The user functions the body reaches, through the bodies it follows.
106
263423
    pub fn followed_functions(&self) -> impl Iterator<Item = &str> {
107
263423
        self.followed.iter().map(String::as_str)
108
263423
    }
109

            
110
833
    fn refuse(&mut self, error: Error) {
111
833
        self.refused.get_or_insert(error);
112
833
    }
113

            
114
    #[cfg(test)]
115
    #[must_use]
116
12
    pub fn len(&self) -> usize {
117
12
        self.names.len()
118
12
    }
119

            
120
    #[cfg(test)]
121
    #[must_use]
122
9
    pub fn contains(&self, name: &str) -> bool {
123
9
        self.names.iter().any(|n| n == name)
124
9
    }
125
}
126

            
127
/// Compute the set of free variables in `body` that aren't bound by
128
/// `params` and that resolve to a runtime binding in `symbols`.
129
1663573
pub fn compute_captures(
130
1663573
    symbols: &SymbolTable,
131
1663573
    params: &LambdaParams,
132
1663573
    body: &Expr,
133
1663573
) -> Result<CaptureSet> {
134
1663573
    let mut captures = CaptureSet::default();
135
1663573
    let bound: Vec<String> = param_names(params).map(str::to_string).collect();
136
1663573
    walk(symbols, &bound, body, &mut captures);
137
1663573
    captures.refused.take().map_or(Ok(captures), Err)
138
1663573
}
139

            
140
44431474
fn walk(symbols: &SymbolTable, bound: &[String], expr: &Expr, captures: &mut CaptureSet) {
141
44431474
    with_sufficient_stack(|| match expr {
142
14863975
        Expr::Symbol(name) => visit_symbol(symbols, bound, name, captures),
143
18215429
        Expr::List(elems) => walk_list(symbols, bound, elems, captures),
144
        Expr::Cons(car, cdr) => {
145
            walk(symbols, bound, car, captures);
146
            walk(symbols, bound, cdr, captures);
147
        }
148
        Expr::Quote(inner) | Expr::Datum(inner) => {
149
13582
            follow::follow_value(symbols, bound, inner, captures);
150
        }
151
        Expr::Quasiquote(template) => {
152
76
            for form in template.unquoted_forms() {
153
76
                walk(symbols, bound, form, captures);
154
            }
155
        }
156
        Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => {
157
            walk(symbols, bound, inner, captures);
158
        }
159
3329
        Expr::Lambda(params, body) => walk_lambda(symbols, bound, params, body, captures),
160
11335083
        _ => {
161
11335083
            // Atoms (Nil, Bool, Number, String, Keyword, Bytes,
162
11335083
            // RuntimeValue, WasmRuntime, WasmLocal) carry no symbol
163
11335083
            // references that could be captures.
164
11335083
        }
165
44431474
    })
166
44431474
}
167

            
168
14863975
fn visit_symbol(symbols: &SymbolTable, bound: &[String], name: &str, captures: &mut CaptureSet) {
169
98746713
    if bound.iter().any(|n| n == name) {
170
6104110
        return;
171
8759865
    }
172
8759865
    let Some(sym) = symbols.lookup(name) else {
173
10672
        captures.note_unbound(name);
174
10672
        return;
175
    };
176
8749193
    captures.note_read(name);
177
8749193
    match sym.value() {
178
61650
        Some(Expr::WasmRuntime(_) | Expr::WasmLocal(_, _)) => captures.insert(name),
179
1267865
        Some(value) => follow::follow_value(symbols, bound, value, captures),
180
7419678
        None => {}
181
    }
182
14863975
}
183

            
184
18215429
fn walk_list(symbols: &SymbolTable, bound: &[String], elems: &[Expr], captures: &mut CaptureSet) {
185
18215429
    let head = elems
186
18215429
        .first()
187
18215429
        .and_then(Expr::as_symbol)
188
18215429
        .map(str::to_uppercase);
189
18215429
    match (head.as_deref(), binder(elems)) {
190
6
        (Some("QUOTE"), _) => elems
191
6
            .get(1)
192
6
            .into_iter()
193
6
            .for_each(|inner| follow::follow_value(symbols, bound, inner, captures)),
194
1698
        (Some("LABELS"), _) => walk_labels(symbols, bound, elems, captures),
195
        (_, Some((kind, specs))) => {
196
10788722
            replay(symbols, bound, binder_steps(kind, specs, elems), captures)
197
        }
198
        (head, None) => {
199
7425003
            match head {
200
18285
                Some("SETF") => record_stores(bound, &elems[1..], captures),
201
4825
                Some("FUNCTION") => follow_designator(symbols, bound, elems.get(1), captures),
202
7401893
                _ => {}
203
            }
204
7425003
            walk_all(symbols, bound, forms_from(elems, 0), captures);
205
7425003
            if let Some(name) = head {
206
7425003
                follow_function(symbols, bound, name, captures);
207
7425003
                follow_macro(symbols, bound, name, &elems[1..], captures);
208
            }
209
        }
210
    }
211
18215429
}
212

            
213
7428399
fn walk_all<'a>(
214
7428399
    symbols: &SymbolTable,
215
7428399
    bound: &[String],
216
7428399
    exprs: impl IntoIterator<Item = &'a Expr>,
217
7428399
    captures: &mut CaptureSet,
218
7428399
) {
219
7428399
    for expr in exprs {
220
21059562
        walk(symbols, bound, expr, captures);
221
    }
222
7428399
}
223

            
224
/// A binder's steps in execution order: each name is in scope for the steps after it.
225
10788722
fn replay(symbols: &SymbolTable, bound: &[String], steps: Vec<Step>, captures: &mut CaptureSet) {
226
10788722
    let mut scope = bound.to_vec();
227
10788722
    for step in steps {
228
31303308
        match step {
229
20512438
            Step::Visit(expr) => walk(symbols, &scope, expr, captures),
230
10790870
            Step::Shadow(name) => scope.push(name.to_string()),
231
        }
232
    }
233
10788722
}
234

            
235
18285
fn record_stores(bound: &[String], args: &[Expr], captures: &mut CaptureSet) {
236
18285
    for pair in args.chunks(2) {
237
18285
        if let Some(Expr::Symbol(name)) = pair.first()
238
12668
            && !bound.iter().any(|b| b == name)
239
        {
240
12229
            captures.stored.push(name.clone());
241
6056
        }
242
    }
243
18285
}
244

            
245
/// A lambda's body and parameter defaults, walked with its parameters in scope.
246
1190753
pub(super) fn walk_lambda(
247
1190753
    symbols: &SymbolTable,
248
1190753
    bound: &[String],
249
1190753
    params: &LambdaParams,
250
1190753
    body: &Expr,
251
1190753
    captures: &mut CaptureSet,
252
1190753
) {
253
1190753
    let mut scope = bound.to_vec();
254
1190753
    scope.extend(param_names(params).map(str::to_string));
255
1190753
    walk(symbols, &scope, body, captures);
256
1190753
    for default in params.defaults() {
257
453
        walk(symbols, &scope, default, captures);
258
    }
259
1190753
}
260

            
261
1698
fn walk_labels(symbols: &SymbolTable, bound: &[String], elems: &[Expr], captures: &mut CaptureSet) {
262
1698
    let defs = elems.get(1).and_then(Expr::as_list).unwrap_or_default();
263
1698
    let mut scope = bound.to_vec();
264
1698
    for name in defs.iter().filter_map(spec_name) {
265
1698
        scope.push(name.to_string());
266
1698
        scope.push(local_function_key(name));
267
    }
268
1698
    for def in defs {
269
1698
        let params = spec_forms(def).first().and_then(Expr::as_list);
270
1698
        let mut def_scope = scope.clone();
271
1698
        def_scope.extend(
272
1698
            params
273
1698
                .unwrap_or_default()
274
1698
                .iter()
275
1698
                .filter_map(spec_name)
276
1698
                .map(str::to_string),
277
1698
        );
278
1698
        walk_all(
279
1698
            symbols,
280
1698
            &def_scope,
281
1698
            forms_from(def.as_list().unwrap_or_default(), 2),
282
1698
            captures,
283
1698
        );
284
    }
285
1698
    walk_all(symbols, &scope, forms_from(elems, 2), captures);
286
1698
}