1
//! The walk of the store scan over the unit's text (see [`super`]).
2

            
3
use std::collections::HashSet;
4

            
5
use crate::ast::{Expr, LambdaParams};
6
use crate::compiler::CompileMode;
7
use crate::compiler::special::setf_scan::{
8
    Binder, Step, binder, binder_steps, code_forms, spec_forms,
9
};
10
use crate::compiler::special::{binding, labels_shadowed};
11
use crate::error::{Error, Result};
12
use crate::runtime::{Head, SymbolTable, is_list_source, with_sufficient_stack};
13

            
14
use super::super::template::expand_macro_use;
15
use super::StoreScan;
16
use crate::compiler::special::expand_macro_places;
17

            
18
/// The function every script unit compiles in, whether or not its text names
19
/// it; an eval unit never compiles one.
20
const SHOULD_APPLY: &str = "SHOULD-APPLY";
21

            
22
/// Walks `unit` and every function body it reaches.
23
2352359
pub(super) fn walk(symbols: &SymbolTable, unit: &[Expr], mode: CompileMode) -> Result<StoreScan> {
24
2352359
    let mut walker = Walker {
25
2352359
        scratch: symbols.scan_scratch(),
26
2352359
        scan: StoreScan::default(),
27
2352359
        shadowed: Vec::new(),
28
2352359
        visited: HashSet::new(),
29
2352359
        pending: Vec::new(),
30
2352359
        visited_opaque: HashSet::new(),
31
2352359
        opaque_depth: 0,
32
2352359
        macro_depth: 0,
33
2352359
    };
34
2352359
    for form in unit {
35
3113294
        walker.visit(form)?;
36
    }
37
2341931
    if mode == CompileMode::Script {
38
1607027
        walker.name(SHOULD_APPLY);
39
734904
    }
40
2341931
    walker.drain()?;
41
2341931
    walker.scan.named = walker.visited.into_iter().collect();
42
2341931
    Ok(walker.scan)
43
2352359
}
44

            
45
/// The scan's state: the scratch table the unit's DEFMACROs register in,
46
/// the findings, and the lexical names in scope — a store to one of those
47
/// is a store to a local, not to a global.
48
struct Walker {
49
    scratch: SymbolTable,
50
    scan: StoreScan,
51
    shadowed: Vec<String>,
52
    /// The earlier-unit functions already walked.
53
    visited: HashSet<String>,
54
    /// The earlier-unit functions queued to be walked.
55
    pending: Vec<(String, bool)>,
56
    /// The earlier-unit functions queued from inside an unreadable macro text.
57
    visited_opaque: HashSet<String>,
58
    /// How many unreadable macro texts the walk is inside.
59
    opaque_depth: usize,
60
    /// How many DEFMACRO bodies the walk is inside.
61
    macro_depth: usize,
62
}
63

            
64
impl Walker {
65
1350531586
    fn visit(&mut self, expr: &Expr) -> Result<()> {
66
1350531586
        with_sufficient_stack(|| {
67
1350531586
            match expr {
68
5914316
                Expr::Symbol(name) if name.eq_ignore_ascii_case("SETF") => {
69
4902
                    self.scan.possibly_storing = true;
70
                }
71
5909414
                Expr::Symbol(name) => self.name(name),
72
190745879
                Expr::List(elems) => self.list(elems)?,
73
247482
                Expr::Quote(inner) | Expr::Datum(inner) => self.datum(inner)?,
74
                Expr::Quasiquote(_) => {
75
810358
                    self.datum(expr)?;
76
810358
                    for form in expr.unquoted_forms() {
77
                        self.visit(form)?;
78
                    }
79
                }
80
416
                Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => self.visit(inner)?,
81
                Expr::Cons(car, cdr) => {
82
3
                    self.visit(car)?;
83
3
                    self.visit(cdr)?;
84
                }
85
                Expr::Lambda(params, body) => {
86
176218639
                    let mark = self.shadowed.len();
87
176218639
                    self.shadowed.extend(params.required.iter().cloned());
88
176218639
                    let visited = self.parsed_sections(params).and_then(|()| self.visit(body));
89
176218639
                    self.shadowed.truncate(mark);
90
176218639
                    visited?;
91
                }
92
976594493
                _ => {}
93
            }
94
1349576210
            Ok(())
95
1350531586
        })
96
1350531586
    }
97

            
98
1424745
    fn function_name(&mut self, args: &[Expr]) {
99
1424745
        if let Some(Expr::Symbol(name)) = args.first() {
100
1424531
            self.scan.functions.push(name.clone());
101
214
        }
102
1424745
    }
103

            
104
    /// Quoted data: its symbols are names of the unit, but nothing in it is
105
    /// code, so no macro use in it is expanded.
106
5627247
    fn datum(&mut self, expr: &Expr) -> Result<()> {
107
5627247
        match expr {
108
            Expr::Symbol(name) => {
109
1388850
                if self.opaque_depth > 0 {
110
4721
                    self.scan.opaque_names.insert(name.to_ascii_uppercase());
111
1384129
                }
112
1388850
                self.visit(expr)
113
            }
114
3753946
            Expr::List(items) => items.iter().try_for_each(|item| self.datum(item)),
115
            Expr::Cons(car, cdr) => {
116
1664
                self.datum(car)?;
117
1664
                self.datum(cdr)
118
            }
119
812133
            Expr::Quote(inner) | Expr::Datum(inner) | Expr::Quasiquote(inner) => self.datum(inner),
120
1957067
            _ => Ok(()),
121
        }
122
5627247
    }
123

            
124
    /// A symbol of the text: a global an earlier unit left a value for, and
125
    /// an earlier-unit function whose body the unit now runs, queued so its
126
    /// stores and bindings are the unit's own.
127
194360802
    fn name(&mut self, name: &str) {
128
194360802
        let name = name.to_ascii_uppercase();
129
194360802
        let opaque = self.opaque_depth > 0;
130
194360802
        if self.visited.insert(name.clone()) || (opaque && self.visited_opaque.insert(name.clone()))
131
        {
132
184453987
            self.pending.push((name, opaque));
133
9906815
        }
134
194360802
    }
135

            
136
    /// Walks the queued function bodies, each of which may queue more: a
137
    /// worklist, so a long chain of functions costs no native stack.
138
2341931
    fn drain(&mut self) -> Result<()> {
139
186713055
        while let Some((name, opaque)) = self.pending.pop() {
140
184371124
            let Some(body) = self.code_of(&name) else {
141
8156020
                continue;
142
            };
143
176215104
            self.shadowed.clear();
144
176215104
            self.opaque_depth += usize::from(opaque);
145
176215104
            let walked = self.visit(&body);
146
176215104
            self.opaque_depth -= usize::from(opaque);
147
176215104
            walked?;
148
        }
149
2341931
        Ok(())
150
2341931
    }
151

            
152
    /// The code the unit runs when it names `name`: an earlier unit's function
153
    /// body, or the lambda or list-of-closures source it left in the global,
154
    /// whose own names the unit then names too.
155
184371124
    fn code_of(&self, name: &str) -> Option<Expr> {
156
184371124
        let function = self.scratch.lookup(name).and_then(|s| s.function());
157
184371124
        match function {
158
176174734
            Some(body @ Expr::Lambda(..)) => Some(body.clone()),
159
8196390
            _ => self
160
8196390
                .scratch
161
8196390
                .constant_global(name)
162
453916
                .filter(|value| matches!(value, Expr::Lambda(..)) || is_list_source(value)),
163
        }
164
184371124
    }
165

            
166
    /// A `SETF` pair: a store to a global, a literal one typing its cell.
167
549604
    fn store(&mut self, pair: &[Expr]) {
168
549604
        place(&mut self.scan, &self.shadowed, pair);
169
549604
        if let Some(Expr::Symbol(name)) = pair.first()
170
526927
            && !self.shadowed.contains(name)
171
        {
172
411637
            self.scan.note_writer(name, pair.get(1));
173
137967
        }
174
549604
    }
175

            
176
    /// The `SETF` arguments with each macro place expanded; a place that
177
    /// cannot expand at scan time may store anywhere.
178
548772
    fn macro_places(&mut self, args: &[Expr]) -> Result<Vec<Expr>> {
179
548772
        match expand_macro_places(&self.scratch, args) {
180
548772
            Ok(expanded) => Ok(expanded),
181
            Err(err @ Error::Resource(_)) => Err(err),
182
            Err(_) => {
183
                self.scan.possibly_storing = true;
184
                Ok(args.to_vec())
185
            }
186
        }
187
548772
    }
188

            
189
190840615
    fn all<'a>(&mut self, exprs: impl IntoIterator<Item = &'a Expr>) -> Result<()> {
190
990958101
        exprs.into_iter().try_for_each(|expr| self.visit(expr))
191
190840615
    }
192

            
193
    /// Visits `forms` with `names` in scope.
194
53464
    fn scoped(&mut self, names: Vec<String>, forms: &[Expr]) -> Result<()> {
195
53464
        let mark = self.shadowed.len();
196
53464
        self.shadowed.extend(names);
197
53464
        let visited = self.all(forms);
198
53464
        self.shadowed.truncate(mark);
199
53464
        visited
200
53464
    }
201

            
202
190745879
    fn list(&mut self, elems: &[Expr]) -> Result<()> {
203
190745879
        let Some(Expr::Symbol(head)) = elems.first() else {
204
4539
            return self.all(elems);
205
        };
206
190741340
        let args = &elems[1..];
207
190741340
        match head.to_ascii_uppercase().as_str() {
208
            "SETF" => {
209
548772
                let args = self.macro_places(args)?;
210
548772
                for pair in args.chunks(2) {
211
549604
                    self.store(pair);
212
                }
213
548772
                self.all(&args)
214
            }
215
            "DEFVAR" | "DEFPARAMETER" => {
216
301020
                if let Some(Expr::Symbol(name)) = args.first()
217
301020
                    && self.opaque_depth + self.macro_depth == 0
218
                {
219
300598
                    self.scan.defined.push(name.clone());
220
300598
                    self.scan.note_writer(name, args.get(1));
221
422
                }
222
301020
                self.all(args)
223
            }
224
            "DEFMACRO" => {
225
860338
                self.function_name(args);
226
                // Registered on the scratch so a template use below expands;
227
                // a malformed definition is the compiler's to reject when it
228
                // compiles the form.
229
860338
                if let Err(Error::Resource(what)) =
230
860338
                    crate::compiler::special::call(&mut self.scratch, "DEFMACRO", args)
231
                {
232
                    return Err(Error::Resource(what));
233
860338
                }
234
860338
                self.macro_depth += 1;
235
860338
                let walked = self.definition(args);
236
860338
                self.macro_depth -= 1;
237
860338
                walked
238
            }
239
            "DEFUN" => {
240
564407
                self.function_name(args);
241
564407
                self.definition(args)
242
            }
243
            "DEFSTRUCT" => {
244
65974
                if let Some(name) = args.first().and_then(Expr::as_symbol) {
245
65971
                    let names = crate::compiler::special::struct_function_names(name, &args[1..]);
246
65971
                    self.scan.functions.extend(names);
247
65971
                    self.scan.functions.push(name.to_string());
248
3
                }
249
65974
                Ok(())
250
            }
251
225383
            "LAMBDA" => self.definition_body(args),
252
974312
            "LET" | "LET*" | "DO" | "DO*" => match binder(elems) {
253
972850
                Some((kind, specs)) => self.binder(kind, specs, elems),
254
1462
                None => self.all(args),
255
            },
256
            "HANDLER-CASE" => {
257
76558
                let vars = args.iter().skip(1).filter_map(clause_var);
258
77188
                vars.for_each(|var| self.note_bound(var));
259
76558
                self.all(code_forms(elems))
260
            }
261
            "LABELS" => {
262
27637
                let defs = args.first().and_then(Expr::as_list).unwrap_or_default();
263
27637
                for def in defs {
264
                    let params =
265
28273
                        (spec_forms(def).first().and_then(Expr::as_list)).unwrap_or_default();
266
28273
                    params
267
28273
                        .iter()
268
28273
                        .filter_map(spec_name)
269
21688
                        .for_each(|var| self.note_bound(var));
270
                }
271
27637
                let local = labels_shadowed(&self.scratch, elems);
272
27637
                let outer = std::mem::replace(&mut self.scratch, local);
273
27637
                let walked = self.all(code_forms(elems));
274
27637
                self.scratch = outer;
275
27637
                walked
276
            }
277
            "CATCH-EACH" => {
278
11682
                if let Some(Expr::Symbol(var)) = args.get(1) {
279
11679
                    self.note_bound(var.clone());
280
3
                }
281
11682
                self.all(args)
282
            }
283
54091
            "DOLIST" => match args.split_first() {
284
                Some((Expr::List(spec), body)) => {
285
53464
                    self.all(spec.get(1..).unwrap_or_default())?;
286
53464
                    let var: Vec<String> = spec.first().and_then(spec_name).into_iter().collect();
287
53464
                    var.iter().cloned().for_each(|name| self.note_bound(name));
288
53464
                    self.scoped(var, body)
289
                }
290
627
                _ => self.all(args),
291
            },
292
            _ => {
293
187031166
                if matches!(self.scratch.resolve_head(head), Head::Macro(..)) {
294
186805
                    self.macro_use(head, args)
295
                } else {
296
186844361
                    self.name(head);
297
186844361
                    self.all(code_forms(elems))
298
                }
299
            }
300
        }
301
190745879
    }
302

            
303
    /// `(defun name (params) body…)` / `(defmacro name (params) body…)`.
304
1424745
    fn definition(&mut self, args: &[Expr]) -> Result<()> {
305
1424745
        self.definition_body(args.get(1..).unwrap_or_default())
306
1424745
    }
307

            
308
    /// `(params body…)`: each default form sees the parameters before it,
309
    /// the body sees them all.
310
1650128
    fn definition_body(&mut self, args: &[Expr]) -> Result<()> {
311
1650128
        let Some((params, body)) = args.split_first() else {
312
416
            return Ok(());
313
        };
314
1649712
        let mark = self.shadowed.len();
315
1649712
        let visited = self.list_params(params).and_then(|()| self.all(body));
316
1649712
        self.shadowed.truncate(mark);
317
1649712
        visited
318
1650128
    }
319

            
320
1649712
    fn list_params(&mut self, params: &Expr) -> Result<()> {
321
1649712
        let Expr::List(items) = params else {
322
479852
            return Ok(());
323
        };
324
1169860
        for item in items {
325
1257862
            self.all(spec_forms(item))?;
326
1257862
            if let Some(name) = spec_name(item).filter(|name| !name.starts_with('&')) {
327
1228671
                self.note_bound(name.clone());
328
1228671
                self.shadowed.push(name);
329
29191
            }
330
        }
331
1169860
        Ok(())
332
1649712
    }
333

            
334
176218639
    fn parsed_sections(&mut self, params: &LambdaParams) -> Result<()> {
335
176218639
        for (name, default) in params.defaulted() {
336
177840
            default.iter().try_for_each(|form| self.visit(form))?;
337
177840
            self.note_bound(name.to_string());
338
177840
            self.shadowed.push(name.to_string());
339
        }
340
176218639
        for name in params.required.iter().chain(&params.rest) {
341
202208
            self.note_bound(name.clone());
342
        }
343
176218639
        self.shadowed.extend(params.rest.iter().cloned());
344
176218639
        Ok(())
345
176218639
    }
346

            
347
    /// A LET / LET* / DO / DO* form, walked as `binder_steps` orders it.
348
972850
    fn binder(&mut self, kind: Binder, specs: &[Expr], elems: &[Expr]) -> Result<()> {
349
972850
        self.note_rebound(specs);
350
972850
        let mark = self.shadowed.len();
351
        let visited =
352
972850
            binder_steps(kind, specs, elems)
353
972850
                .into_iter()
354
3468099
                .try_for_each(|step| match step {
355
2365327
                    Step::Visit(expr) => self.visit(expr),
356
                    Step::Shadow(name) => {
357
1102772
                        self.shadowed.push(name.to_string());
358
1102772
                        Ok(())
359
                    }
360
3468099
                });
361
972850
        self.shadowed.truncate(mark);
362
972850
        visited
363
972850
    }
364

            
365
2876547
    fn note_bound(&mut self, name: String) {
366
2876547
        self.scan.rebound.insert(name);
367
2876547
    }
368

            
369
972850
    fn note_rebound(&mut self, specs: &[Expr]) {
370
972850
        specs
371
972850
            .iter()
372
972850
            .filter_map(spec_name)
373
1103812
            .for_each(|name| self.note_bound(name));
374
972850
    }
375

            
376
    /// The text of a macro whose use cannot expand at scan time, read as the
377
    /// unit's own: the names it mentions, quoted ones included, and the stores.
378
9455
    fn opaque_body(&mut self, head: &str) -> Result<()> {
379
9455
        let Head::Macro(_, body) = self.scratch.resolve_head(head) else {
380
            return Ok(());
381
        };
382
9455
        let body = body.clone();
383
9455
        self.opaque_depth += 1;
384
9455
        let walked = self.visit(&body);
385
9455
        self.opaque_depth -= 1;
386
9455
        walked
387
9455
    }
388

            
389
    /// Every symbol of the arguments of an unreadable macro use.
390
9455
    fn opaque_args(&mut self, args: &[Expr]) {
391
9455
        for arg in args {
392
3594
            let mut found = Vec::new();
393
3594
            symbols_of(arg, &mut found);
394
3594
            self.scan.opaque_names.extend(found);
395
        }
396
9455
    }
397

            
398
    /// A macro's expansion is scanned in place of the use, which already
399
    /// contains every argument it keeps (scanning the arguments too would walk
400
    /// a nested macro argument twice per level). A use that cannot expand at
401
    /// scan time is opaque: its macro's text and its arguments are scanned as
402
    /// text of the unit.
403
186805
    fn macro_use(&mut self, head: &str, args: &[Expr]) -> Result<()> {
404
186805
        self.scratch.enter_macro_expansion()?;
405
186597
        let walked = match expand_macro_use(&mut self.scratch, head, args) {
406
166922
            Ok(Some(expansion)) => self.visit(&expansion),
407
            Ok(None) => {
408
9455
                self.scan.opaque_uses += 1;
409
9455
                self.opaque_body(head)?;
410
9455
                self.opaque_args(args);
411
9455
                self.all(args)
412
            }
413
10220
            Err(err) => Err(err),
414
        };
415
186597
        self.scratch.exit_macro_expansion()?;
416
186597
        walked
417
186805
    }
418
}
419

            
420
4673
fn symbols_of(expr: &Expr, found: &mut Vec<String>) {
421
4673
    with_sufficient_stack(|| match expr {
422
858
        Expr::Symbol(name) => found.push(name.to_ascii_uppercase()),
423
1079
        Expr::List(items) => items.iter().for_each(|item| symbols_of(item, found)),
424
        Expr::Cons(car, cdr) => {
425
            symbols_of(car, found);
426
            symbols_of(cdr, found);
427
        }
428
        Expr::Quote(inner)
429
        | Expr::Datum(inner)
430
        | Expr::Quasiquote(inner)
431
        | Expr::Unquote(inner)
432
        | Expr::UnquoteSplicing(inner) => symbols_of(inner, found),
433
3384
        _ => {}
434
4673
    })
435
4673
}
436

            
437
/// The condition variable of a HANDLER-CASE clause `(code (var) form…)`.
438
77194
fn clause_var(clause: &Expr) -> Option<String> {
439
77194
    match clause {
440
77191
        Expr::List(parts) => match parts.get(1) {
441
77188
            Some(Expr::List(var)) => var.first().and_then(spec_name),
442
3
            _ => None,
443
        },
444
3
        _ => None,
445
    }
446
77194
}
447

            
448
2514255
fn spec_name(spec: &Expr) -> Option<String> {
449
2514255
    binding::spec_name(spec).map(str::to_string)
450
2514255
}
451

            
452
/// A `SETF` pair: a bare-symbol place is a store to that name; a struct
453
/// accessor place `(accessor sym …)` rebinds `sym` (see `set_place`); any
454
/// other place is one the scan cannot resolve.
455
549604
fn place(scan: &mut StoreScan, shadowed: &[String], pair: &[Expr]) {
456
549604
    let (name, direct) = match pair.first() {
457
526927
        Some(Expr::Symbol(name)) => (Some(name), true),
458
22677
        Some(Expr::List(parts)) => match parts.get(1) {
459
19346
            Some(Expr::Symbol(target)) => (Some(target), false),
460
3331
            _ => (None, false),
461
        },
462
        _ => (None, false),
463
    };
464
549604
    match name {
465
546273
        Some(name) if shadowed.iter().any(|local| local == name) => {}
466
        Some(name) => {
467
418711
            scan.stored.insert(name.clone());
468
418711
            if direct {
469
411637
                scan.direct.insert(name.clone());
470
7074
            }
471
        }
472
3331
        None => scan.possibly_storing = true,
473
    }
474
549604
}