1
//! Which LET bindings live in a shared cell: a name that its scope both
2
//! assigns and mentions free inside a lambda. The scan is syntactic over the
3
//! scope; a lambda it misses (macro-built) stays a copy, which the captured
4
//! store guards turn into a compile error.
5

            
6
use super::super::setf_scan::{assigns, spec_forms};
7
use super::expansion::{Expander, macro_expanded, params_expanded};
8
use super::spec_name;
9
use crate::ast::{Expr, LambdaParams, WasmType};
10
use crate::compiler::expr::fold::walk::is_lambda_literal;
11
use crate::compiler::special::compute_captures;
12
use crate::error::Result;
13
use crate::runtime::{Head, Symbol, SymbolKind, SymbolTable, with_sufficient_stack};
14

            
15
/// A value holding a lambda that reads a runtime binding of the LET being
16
/// left cannot leave it: the binder's local is gone, so it is an untyped
17
/// runtime value the enclosing form compiles in place.
18
1611314
pub(in crate::compiler) fn unescaped(symbols: &SymbolTable, names: &[String], value: Expr) -> Expr {
19
18357076
    let escapes = value.any_form(|form| match form {
20
        Expr::Lambda(params, body) => {
21
37541
            compute_captures(symbols, params, body).map_or(true, |captures| {
22
37541
                captures.iter().any(|captured| {
23
13197
                    SymbolTable::is_hidden_name(captured)
24
13197
                        || names.iter().any(|name| name == captured)
25
13197
                })
26
37541
            })
27
        }
28
18319535
        _ => false,
29
18357076
    });
30
1611314
    match escapes {
31
13104
        true => Expr::WasmRuntime(WasmType::AnyRef),
32
1598210
        false => value,
33
    }
34
1611314
}
35

            
36
2492097
pub(in crate::compiler) fn needs_cell(
37
2492097
    symbols: &SymbolTable,
38
2492097
    name: &str,
39
2492097
    scope: &[Expr],
40
2492097
) -> Result<bool> {
41
2492097
    needs_cell_stepped(symbols, name, false, scope)
42
2492097
}
43

            
44
/// [`needs_cell`] for a loop variable, which a step form also assigns.
45
2709271
pub(in crate::compiler::special) fn needs_cell_stepped<'a>(
46
2709271
    symbols: &SymbolTable,
47
2709271
    name: &str,
48
2709271
    stepped: bool,
49
2709271
    scope: impl IntoIterator<Item = &'a Expr>,
50
2709271
) -> Result<bool> {
51
2709271
    let (scope, unexpanded) = macro_expanded_scope(symbols, scope)?;
52
    Ok(
53
2709271
        (stepped || assigns_or_opaque(&scope, unexpanded.is_some(), name))
54
983179
            && scope.iter().any(|form| captured_in_lambda(form, name)),
55
    )
56
2709271
}
57

            
58
/// What a body's macro uses, once expanded, do to a variable.
59
pub(in crate::compiler) enum MacroStores {
60
    Clean,
61
    Assigns,
62
    /// The first macro use that could not be expanded: it may assign any name.
63
    Unexpanded(String),
64
}
65

            
66
1025442
pub(in crate::compiler) fn macro_stores(
67
1025442
    symbols: &SymbolTable,
68
1025442
    body: &Expr,
69
1025442
    name: &str,
70
1025442
) -> Result<MacroStores> {
71
1025442
    let (scope, unexpanded) = macro_expanded_scope(symbols, std::slice::from_ref(body))?;
72
1025442
    Ok(match unexpanded {
73
1
        Some(head) => MacroStores::Unexpanded(head),
74
1025441
        None if assigns(&scope, name) => MacroStores::Assigns,
75
1025189
        None => MacroStores::Clean,
76
    })
77
1025442
}
78

            
79
/// Whether `body`, with its macro uses expanded, assigns `name` or holds a
80
/// macro use that could not be expanded.
81
4395
pub(in crate::compiler) fn assigns_through_macros(
82
4395
    symbols: &SymbolTable,
83
4395
    body: &Expr,
84
4395
    name: &str,
85
4395
) -> Result<bool> {
86
4395
    Ok(!matches!(
87
4395
        macro_stores(symbols, body, name)?,
88
        MacroStores::Clean
89
    ))
90
4395
}
91

            
92
/// What binding `at` of a LET / LET* sees: the body, and for LET* the inits
93
/// after it.
94
4759211
pub(super) fn star_scope<'a>(
95
4759211
    bindings: &'a [(String, Option<Expr>)],
96
4759211
    at: usize,
97
4759211
    body: &'a [Expr],
98
4759211
    sequential: bool,
99
4759211
) -> Vec<&'a Expr> {
100
4759211
    let later_inits = bindings[at + 1..]
101
4759211
        .iter()
102
        .filter(|_| sequential)
103
3726920
        .filter_map(|(_, init)| init.as_ref());
104
4759211
    later_inits.chain(body).collect()
105
4759211
}
106

            
107
/// `scope` with its macro uses expanded when it assigns `name` (or holds an
108
/// opaque macro use), `None` when it does not. The one test of whether a
109
/// binder is a mutated local, for codegen, eval and the binder site alike.
110
7564131
pub(in crate::compiler) fn assigned_scope<'a>(
111
7564131
    symbols: &SymbolTable,
112
7564131
    name: &str,
113
7564131
    scope: impl IntoIterator<Item = &'a Expr>,
114
7564131
) -> Result<Option<Vec<Expr>>> {
115
7564131
    let (scope, unexpanded) = macro_expanded_scope(symbols, scope)?;
116
7564131
    Ok(assigns_or_opaque(&scope, unexpanded.is_some(), name).then_some(scope))
117
7564131
}
118

            
119
/// Whether the expanded `scope` assigns `name`, or holds a macro use that was
120
/// not expanded (an opaque one may store to any variable a closure captures).
121
10069036
fn assigns_or_opaque(scope: &[Expr], opaque: bool, name: &str) -> bool {
122
10069036
    assigns(scope, name) || (opaque && scope.iter().any(|form| captured_in_lambda(form, name)))
123
10069036
}
124

            
125
/// `scope` with each user macro use replaced by its expansion, and the head of
126
/// the first use that could not be expanded.
127
11299500
fn macro_expanded_scope<'a>(
128
11299500
    symbols: &SymbolTable,
129
11299500
    scope: impl IntoIterator<Item = &'a Expr>,
130
11299500
) -> Result<(Vec<Expr>, Option<String>)> {
131
11299500
    let how = Expander::any();
132
11299500
    let forms = scope
133
11299500
        .into_iter()
134
16406777
        .map(|form| macro_expanded(symbols, form, &how))
135
        .collect::<Result<_>>()?;
136
11299500
    Ok((forms, how.unexpanded().map(str::to_string)))
137
11299500
}
138

            
139
/// `symbols` where each function a LABELS form defines hides a macro of the
140
/// same name, in the definitions and the body alike.
141
28146
pub(in crate::compiler) fn labels_shadowed(symbols: &SymbolTable, elems: &[Expr]) -> SymbolTable {
142
28146
    let mut local = symbols.clone();
143
28146
    for name in labels_names(elems.get(1..).unwrap_or_default()) {
144
28776
        local.define(Symbol::new(name, SymbolKind::Function).local_function());
145
    }
146
28146
    local
147
28146
}
148

            
149
/// `expr` with every user macro use replaced by its expansion.
150
184972
pub(in crate::compiler) fn fully_macro_expanded(
151
184972
    symbols: &SymbolTable,
152
184972
    expr: &Expr,
153
184972
) -> Result<Expr> {
154
184972
    macro_expanded(symbols, expr, &Expander::any())
155
184972
}
156

            
157
/// A function's parameter defaults and body with the macros in force now
158
/// expanded, as Common Lisp compiles it: a later definition of a macro, or of
159
/// a function named `name`, does not change them.
160
5479161
pub(in crate::compiler) fn expanded_function(
161
5479161
    symbols: &SymbolTable,
162
5479161
    name: Option<&str>,
163
5479161
    params: &LambdaParams,
164
5479161
    body: &Expr,
165
5479161
) -> Result<(LambdaParams, Expr)> {
166
5479161
    let how = Expander::any().shadowing(name.map(str::to_string).into_iter());
167
    Ok((
168
5479161
        params_expanded(symbols, params, &how)?,
169
5479161
        macro_expanded(symbols, body, &how)?,
170
    ))
171
5479161
}
172

            
173
7710351
fn captured_in_lambda(expr: &Expr, name: &str) -> bool {
174
7710351
    with_sufficient_stack(|| match expr {
175
        Expr::Lambda(params, body) => {
176
            (!binds(params, name) && mentions(body, name))
177
                || defaults(params).any(|default| mentions(default, name))
178
        }
179
2491888
        Expr::List(elems) => match elems.first() {
180
2344436
            Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("QUOTE") => false,
181
2343803
            Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("LAMBDA") => {
182
121500
                let specs = elems.get(1).and_then(Expr::as_list).unwrap_or_default();
183
121500
                (!specs.iter().any(|spec| spec_name(spec) == Some(name))
184
121331
                    && elems.iter().skip(2).any(|form| mentions(form, name)))
185
12888
                    || specs
186
12888
                        .iter()
187
10814
                        .any(|spec| spec_forms(spec).iter().any(|form| mentions(form, name)))
188
            }
189
6620970
            _ => elems.iter().any(|elem| captured_in_lambda(elem, name)),
190
        },
191
        Expr::Cons(car, cdr) => captured_in_lambda(car, name) || captured_in_lambda(cdr, name),
192
12
        Expr::Quasiquote(template) => template
193
12
            .unquoted_forms()
194
12
            .into_iter()
195
27
            .any(|form| captured_in_lambda(form, name)),
196
        Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => captured_in_lambda(inner, name),
197
5218451
        _ => false,
198
7710351
    })
199
7710351
}
200

            
201
/// Whether `call` calls a user function whose body builds a lambda reading one
202
/// of the function's own parameters free: the closure outlives the inlined
203
/// frame that binds them, so only compiling the call can capture them.
204
1448158
pub(in crate::compiler) fn is_closure_factory_call(
205
1448158
    symbols: &SymbolTable,
206
1448158
    call: &Expr,
207
1448158
) -> Result<bool> {
208
1448158
    let Expr::List(items) = call else {
209
1100637
        return Ok(false);
210
    };
211
347521
    let Some(Expr::Symbol(head)) = items.first() else {
212
        return Ok(false);
213
    };
214
347521
    let Head::Function(params, body) = symbols.resolve_head(head) else {
215
220331
        return Ok(false);
216
    };
217
127190
    if !is_lambda_literal(symbols, body) {
218
18582
        return Ok(false);
219
108608
    }
220
108608
    for name in param_names(params) {
221
104890
        let how = Expander::macro_use(name);
222
104890
        if captured_in_lambda(&macro_expanded(symbols, body, &how)?, name) {
223
102763
            return Ok(true);
224
2127
        }
225
    }
226
5845
    Ok(false)
227
1448158
}
228

            
229
8539869
pub(in crate::compiler) fn param_names(params: &LambdaParams) -> impl Iterator<Item = &str> {
230
8539869
    params
231
8539869
        .required
232
8539869
        .iter()
233
8539869
        .chain(params.rest.iter())
234
8539869
        .chain(params.optional.iter().map(|(name, _)| name))
235
8539869
        .chain(params.key.iter().map(|param| &param.name))
236
8539869
        .chain(params.aux.iter().map(|(name, _)| name))
237
8539869
        .map(String::as_str)
238
8539869
}
239

            
240
1065667
fn binds(params: &LambdaParams, name: &str) -> bool {
241
1065667
    param_names(params).any(|param| param == name)
242
1065667
}
243

            
244
/// Whether `function` reads `name` free: in its body or a parameter default.
245
/// A macro use is read through its expansion; one that fails to expand reads
246
/// everything.
247
1065667
pub(crate) fn reads_free(symbols: &SymbolTable, function: &Expr, name: &str) -> Result<bool> {
248
1065667
    let Expr::Lambda(params, body) = function else {
249
        return mentions_expanded(symbols, function, name);
250
    };
251
1065667
    if binds(params, name) {
252
1255
        return Ok(false);
253
1064412
    }
254
1064412
    for form in std::iter::once(body.as_ref()).chain(defaults(params)) {
255
1064626
        if mentions_expanded(symbols, form, name)? {
256
1026742
            return Ok(true);
257
37884
        }
258
    }
259
37670
    Ok(false)
260
1065667
}
261

            
262
/// Whether `function`, with its macro uses expanded, assigns `name` free.
263
656
pub(crate) fn stores_free(symbols: &SymbolTable, function: &Expr, name: &str) -> Result<bool> {
264
656
    let body = match function {
265
656
        Expr::Lambda(_, body) => body.as_ref(),
266
        other => other,
267
    };
268
656
    let (scope, _) = macro_expanded_scope(symbols, std::slice::from_ref(body))?;
269
656
    Ok(assigns(&scope, name))
270
656
}
271

            
272
/// Whether `form` mentions `name` once its macro uses are expanded; an
273
/// unexpandable use mentions every name.
274
1065426
pub(in crate::compiler) fn mentions_expanded(
275
1065426
    symbols: &SymbolTable,
276
1065426
    form: &Expr,
277
1065426
    name: &str,
278
1065426
) -> Result<bool> {
279
1065426
    let how = Expander::macro_use(name);
280
1065426
    Ok(mentions(&macro_expanded(symbols, form, &how)?, name))
281
1065426
}
282

            
283
/// Whether the macro-expanded `body` uses the parameter `name` as a function:
284
/// a call head, an operand of FUNCALL/APPLY, or an argument of any other call.
285
/// A test or a value of a special form is data.
286
351413
pub(in crate::compiler) fn used_as_function(
287
351413
    symbols: &SymbolTable,
288
351413
    body: &Expr,
289
351413
    name: &str,
290
351413
) -> Result<bool> {
291
351413
    let expanded = macro_expanded(symbols, body, &Expander::any())?;
292
351413
    Ok(calls_with(symbols, &expanded, name))
293
351413
}
294

            
295
1772872
fn calls_with(symbols: &SymbolTable, expr: &Expr, name: &str) -> bool {
296
1772872
    with_sufficient_stack(|| match expr {
297
1262917
        Expr::List(elems) => match elems.split_first() {
298
1092335
            Some((Expr::Symbol(head), _)) if head.eq_ignore_ascii_case("QUOTE") => false,
299
            Some((Expr::Symbol(head), args)) => {
300
1035984
                let is_name = |arg: &Expr| matches!(arg, Expr::Symbol(symbol) if symbol == name);
301
1092334
                let operand = if matches!(symbols.resolve_head(head), Head::SpecialForm) {
302
354195
                    ["FUNCALL", "APPLY"]
303
354195
                        .iter()
304
703356
                        .any(|form| head.eq_ignore_ascii_case(form))
305
                } else {
306
738139
                    true
307
                };
308
1092334
                head == name
309
1090634
                    || (operand && args.iter().any(is_name))
310
1199617
                    || args.iter().any(|arg| calls_with(symbols, arg, name))
311
            }
312
221830
            _ => elems.iter().any(|elem| calls_with(symbols, elem, name)),
313
        },
314
        Expr::Cons(car, cdr) => calls_with(symbols, car, name) || calls_with(symbols, cdr, name),
315
12
        Expr::Quasiquote(template) => template
316
12
            .unquoted_forms()
317
12
            .into_iter()
318
12
            .any(|form| calls_with(symbols, form, name)),
319
        Expr::Lambda(params, body) => !binds(params, name) && calls_with(symbols, body, name),
320
509943
        _ => false,
321
1772872
    })
322
1772872
}
323

            
324
1064412
fn defaults(params: &LambdaParams) -> impl Iterator<Item = &Expr> {
325
1064412
    params.defaults()
326
1064412
}
327

            
328
22419312
pub(in crate::compiler) fn mentions(expr: &Expr, name: &str) -> bool {
329
22419312
    with_sufficient_stack(|| match expr {
330
5510291
        Expr::Symbol(symbol) => symbol == name,
331
6271432
        Expr::List(elems) => match elems.first() {
332
4489676
            Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("QUOTE") => false,
333
            Some(Expr::Symbol(head))
334
4489661
                if head.eq_ignore_ascii_case("LABELS") && defines(elems, name) =>
335
            {
336
21
                false
337
            }
338
            Some(Expr::Symbol(head))
339
4489640
                if head.eq_ignore_ascii_case("BLOCK")
340
4489635
                    || head.eq_ignore_ascii_case("RETURN-FROM") =>
341
            {
342
218
                elems.iter().skip(2).any(|elem| mentions(elem, name))
343
            }
344
10467913
            _ => elems.iter().any(|elem| mentions(elem, name)),
345
        },
346
        Expr::Cons(car, cdr) => mentions(car, name) || mentions(cdr, name),
347
42
        Expr::Quasiquote(template) => template
348
42
            .unquoted_forms()
349
42
            .into_iter()
350
37
            .any(|form| mentions(form, name)),
351
        Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => mentions(inner, name),
352
        Expr::Lambda(params, body) => !binds(params, name) && mentions(body, name),
353
10637547
        _ => false,
354
22419312
    })
355
22419312
}
356

            
357
/// The names the LABELS operands `args` define.
358
42590
pub(super) fn labels_names(args: &[Expr]) -> impl Iterator<Item = String> {
359
42590
    let clauses = args.first().and_then(Expr::as_list).unwrap_or_default();
360
42590
    clauses
361
42590
        .iter()
362
43232
        .filter_map(|clause| clause.as_list()?.first()?.as_symbol().map(str::to_string))
363
42590
}
364

            
365
/// Whether the LABELS form `elems` defines a function `name`.
366
53
fn defines(elems: &[Expr], name: &str) -> bool {
367
53
    labels_names(elems.get(1..).unwrap_or_default()).any(|fname| fname.eq_ignore_ascii_case(name))
368
53
}