1
//! The one scoped syntactic walk over a form (0014 Stage 2, ISS-053). It
2
//! carries the binder stack as it descends, expands template macros with
3
//! the evaluator's own `expand_macro`, skips quoted data, and hands every
4
//! node in code position to a [`Visit`]or that answers one question.
5
//!
6
//! Every walk errs the same way: a node the visitor cannot classify is
7
//! [`Step::Found`], the answer that ends the walk with `true`.
8

            
9
use std::borrow::Cow;
10

            
11
use crate::ast::Expr;
12
use crate::compiler::expr::expand_macro;
13
use crate::compiler::special::binding::spec_name;
14
use crate::compiler::special::labels_shadowed;
15
use crate::compiler::special::setf_scan::{code_forms, spec_forms};
16
use crate::error::Result;
17
use crate::runtime::{Head, SymbolTable};
18

            
19
use super::template::template_of;
20

            
21
/// What the visitor wants done with a node.
22
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
23
pub(crate) enum Step {
24
    /// Walk the node's subforms.
25
    Descend,
26
    /// Leave the node's subforms unvisited.
27
    Skip,
28
    /// The question is answered: the walk ends with `true`.
29
    Found,
30
}
31

            
32
/// A node in code position, classified against the live table.
33
pub(crate) enum Node<'a> {
34
    /// A symbol read that no binder inside the form bounds.
35
    Free(&'a str),
36
    /// A special form call; `elems` is the whole form.
37
    Special(&'a str, &'a [Expr]),
38
    /// A native or operator call no user definition shadows.
39
    Native(&'a str),
40
    /// A call of a user function, a closure value, or an unknown name.
41
    Call,
42
    /// A macro use whose expansion is not a template, so it is not scanned.
43
    OpaqueMacro,
44
    /// A `LAMBDA` / `FUNCTION` form in a body's non-tail position.
45
    DiscardedLambda,
46
    /// A self-evaluating literal or quoted datum.
47
    Datum,
48
    /// Anything else: a quasiquote in code position, a cons, a placeholder.
49
    Other,
50
}
51

            
52
/// The binders in scope at a node.
53
#[derive(Default)]
54
pub(crate) struct Scope {
55
    vars: Vec<String>,
56
    blocks: Vec<String>,
57
}
58

            
59
impl Scope {
60
10124527
    pub(crate) fn binds_var(&self, name: &str) -> bool {
61
10124527
        self.vars.iter().any(|v| v.eq_ignore_ascii_case(name))
62
10124527
    }
63
}
64

            
65
pub(crate) trait Visit {
66
    fn visit(&mut self, env: &SymbolTable, scope: &Scope, node: Node<'_>) -> Step;
67

            
68
    /// Whether an `IF` with a literal test walks only its live branch.
69
28909
    fn prunes_dead_branches(&self) -> bool {
70
28909
        false
71
28909
    }
72
}
73

            
74
/// Walks `forms` as a body (all but the last for effect) in a fresh scope
75
/// whose variables are `bound`; `true` once the visitor answers [`Step::Found`].
76
18987236
pub(crate) fn walk_body<V: Visit>(
77
18987236
    symbols: &SymbolTable,
78
18987236
    bound: &[&str],
79
18987236
    forms: &[Expr],
80
18987236
    visitor: &mut V,
81
18987236
) -> Result<bool> {
82
18987236
    let mut env = Cow::Borrowed(symbols);
83
    let mut scope = Scope {
84
18987236
        vars: bound.iter().map(|name| (*name).to_string()).collect(),
85
18987236
        blocks: Vec::new(),
86
    };
87
18987236
    body(&mut env, &mut scope, forms, visitor)
88
18987236
}
89

            
90
type Env<'a> = Cow<'a, SymbolTable>;
91

            
92
19947868
fn body<V: Visit>(
93
19947868
    env: &mut Env<'_>,
94
19947868
    scope: &mut Scope,
95
19947868
    forms: &[Expr],
96
19947868
    visitor: &mut V,
97
19947868
) -> Result<bool> {
98
19947868
    let Some((tail, init)) = forms.split_last() else {
99
251562
        return Ok(false);
100
    };
101
19696306
    for form in init {
102
213579
        if is_lambda_literal(env, form) {
103
835
            if visitor.visit(env, scope, Node::DiscardedLambda) == Step::Found {
104
                return Ok(true);
105
835
            }
106
835
            continue;
107
212744
        }
108
212744
        if walk(env, scope, form, visitor)? {
109
127980
            return Ok(true);
110
84764
        }
111
    }
112
19568326
    walk(env, scope, tail, visitor)
113
19947868
}
114

            
115
9132146
fn all<'a, V: Visit>(
116
9132146
    env: &mut Env<'_>,
117
9132146
    scope: &mut Scope,
118
9132146
    forms: impl IntoIterator<Item = &'a Expr>,
119
9132146
    visitor: &mut V,
120
9132146
) -> Result<bool> {
121
9132146
    for form in forms {
122
853083085
        if walk(env, scope, form, visitor)? {
123
3256556
            return Ok(true);
124
849826529
        }
125
    }
126
5875590
    Ok(false)
127
9132146
}
128

            
129
873844816
fn walk<V: Visit>(
130
873844816
    env: &mut Env<'_>,
131
873844816
    scope: &mut Scope,
132
873844816
    form: &Expr,
133
873844816
    visitor: &mut V,
134
873844816
) -> Result<bool> {
135
873844816
    let step = match form {
136
        Expr::Nil
137
        | Expr::T
138
        | Expr::Number(_)
139
        | Expr::String(_)
140
        | Expr::Bytes(_)
141
        | Expr::Keyword(_)
142
        | Expr::Quote(_)
143
847752972
        | Expr::Datum(_) => visitor.visit(env, scope, Node::Datum),
144
10124527
        Expr::Symbol(name) if scope.binds_var(name) => Step::Skip,
145
7844937
        Expr::Symbol(name) => visitor.visit(env, scope, Node::Free(name)),
146
14789694
        Expr::List(elems) if elems.is_empty() => visitor.visit(env, scope, Node::Datum),
147
14789694
        Expr::List(elems) => return call(env, scope, elems, visitor),
148
        Expr::Quasiquote(template) => {
149
253
            return match visitor.visit(env, scope, Node::Other) {
150
229
                Step::Descend => walk_unquoted(env, scope, template, visitor),
151
                Step::Skip => Ok(false),
152
24
                Step::Found => Ok(true),
153
            };
154
        }
155
        Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => {
156
            return match visitor.visit(env, scope, Node::Other) {
157
                Step::Descend => walk(env, scope, inner, visitor),
158
                Step::Skip => Ok(false),
159
                Step::Found => Ok(true),
160
            };
161
        }
162
1177370
        _ => visitor.visit(env, scope, Node::Other),
163
    };
164
859054869
    Ok(step == Step::Found)
165
873844816
}
166

            
167
229
fn walk_unquoted<V: Visit>(
168
229
    env: &mut Env<'_>,
169
229
    scope: &mut Scope,
170
229
    template: &Expr,
171
229
    visitor: &mut V,
172
229
) -> Result<bool> {
173
229
    for form in template.unquoted_forms() {
174
228
        if walk(env, scope, form, visitor)? {
175
20
            return Ok(true);
176
208
        }
177
    }
178
209
    Ok(false)
179
229
}
180

            
181
14789694
fn call<V: Visit>(
182
14789694
    env: &mut Env<'_>,
183
14789694
    scope: &mut Scope,
184
14789694
    elems: &[Expr],
185
14789694
    visitor: &mut V,
186
14789694
) -> Result<bool> {
187
14789694
    let Some(Expr::Symbol(head)) = elems.first() else {
188
8897
        return match visitor.visit(env, scope, Node::Call) {
189
6760
            Step::Found => Ok(true),
190
            Step::Skip => Ok(false),
191
2137
            Step::Descend => all(env, scope, elems, visitor),
192
        };
193
    };
194
14780797
    let resolved = env.resolve_head(head);
195
14780797
    let is_special = matches!(resolved, Head::SpecialForm);
196
14780797
    let node = match resolved {
197
213765
        Head::Macro(..) => return macro_use(env, scope, head, elems, visitor),
198
4366925
        Head::SpecialForm => Node::Special(head, elems),
199
9818010
        Head::Native => Node::Native(head),
200
382097
        _ => Node::Call,
201
    };
202
14567032
    match visitor.visit(env, scope, node) {
203
5398020
        Step::Found => Ok(true),
204
177137
        Step::Skip => Ok(false),
205
8991875
        Step::Descend if is_special => special(env, scope, head, elems, visitor),
206
        // The type name of `(the TYPE form)` is not evaluated.
207
6729752
        Step::Descend if head.eq_ignore_ascii_case("THE") => {
208
19352
            all(env, scope, elems.get(2..).unwrap_or_default(), visitor)
209
        }
210
6710400
        Step::Descend => all(env, scope, &elems[1..], visitor),
211
    }
212
14789694
}
213

            
214
/// A template macro's expansion is walked in place of the use; any other
215
/// macro use is opaque to the walk.
216
213765
fn macro_use<V: Visit>(
217
213765
    env: &mut Env<'_>,
218
213765
    scope: &mut Scope,
219
213765
    head: &str,
220
213765
    elems: &[Expr],
221
213765
    visitor: &mut V,
222
213765
) -> Result<bool> {
223
213765
    let args = &elems[1..];
224
213765
    let Some((params, body)) = template_of(env, head) else {
225
81486
        return Ok(visitor.visit(env, scope, Node::OpaqueMacro) == Step::Found);
226
    };
227
132279
    let (params, body) = (params.clone(), body.clone());
228
132279
    let table = env.to_mut();
229
132279
    table.enter_macro_expansion()?;
230
132279
    let expansion = expand_macro(table, &params, &body, args).and_then(|expansion| {
231
132279
        table.charge_work(crate::compiler::datum::cost(&expansion)?)?;
232
132279
        Ok(expansion)
233
132279
    });
234
132279
    let found = expansion.and_then(|code| walk(env, scope, &code, visitor));
235
132279
    env.to_mut().exit_macro_expansion()?;
236
132279
    found
237
213765
}
238

            
239
/// The subforms of a special form, with its binders pushed around the forms
240
/// they scope.
241
2262123
fn special<V: Visit>(
242
2262123
    env: &mut Env<'_>,
243
2262123
    scope: &mut Scope,
244
2262123
    head: &str,
245
2262123
    elems: &[Expr],
246
2262123
    visitor: &mut V,
247
2262123
) -> Result<bool> {
248
2262123
    let rest = &elems[1..];
249
2262123
    match head.to_ascii_uppercase().as_str() {
250
11216
        "QUOTE" => Ok(false),
251
520385
        "IF" if visitor.prunes_dead_branches() => match rest.split_first() {
252
491475
            Some((test, branches)) if is_literal(test) => {
253
5879
                let live = usize::from(test.is_nil());
254
5879
                all(
255
5879
                    env,
256
5879
                    scope,
257
5879
                    branches.get(live..=live).unwrap_or_default(),
258
5879
                    visitor,
259
5879
                )
260
            }
261
485597
            _ => all(env, scope, rest, visitor),
262
        },
263
338175
        "PROGN" => body(env, scope, rest, visitor),
264
140092
        "LET" | "LET*" => let_form(env, scope, head.eq_ignore_ascii_case("LET*"), rest, visitor),
265
195409
        "DOLIST" => dolist(env, scope, rest, visitor),
266
394474
        "DO" | "DO*" => do_form(env, scope, head.eq_ignore_ascii_case("DO*"), rest, visitor),
267
20434
        "LAMBDA" => lambda(env, scope, rest, visitor),
268
509
        "LABELS" => all(
269
509
            &mut Cow::Owned(labels_shadowed(env, elems)),
270
509
            scope,
271
509
            code_forms(elems),
272
509
            visitor,
273
509
        ),
274
44149
        "BLOCK" => match rest.split_first() {
275
            Some((Expr::Symbol(name), forms)) => {
276
44145
                scope.blocks.push(name.clone());
277
44145
                let found = body(env, scope, forms, visitor);
278
44145
                scope.blocks.pop();
279
44145
                found
280
            }
281
4
            _ => all(env, scope, rest, visitor),
282
        },
283
626189
        _ => all(env, scope, code_forms(elems), visitor),
284
    }
285
2262123
}
286

            
287
140092
fn let_form<V: Visit>(
288
140092
    env: &mut Env<'_>,
289
140092
    scope: &mut Scope,
290
140092
    sequential: bool,
291
140092
    rest: &[Expr],
292
140092
    visitor: &mut V,
293
140092
) -> Result<bool> {
294
140092
    let Some((specs, forms)) = rest
295
140092
        .split_first()
296
140090
        .and_then(|(specs, forms)| Some((specs.as_list()?, forms)))
297
    else {
298
2
        return all(env, scope, rest, visitor);
299
    };
300
140090
    let mark = scope.vars.len();
301
140090
    let mut found = false;
302
140090
    for spec in specs {
303
133706
        found = all(env, scope, spec_forms(spec), visitor)?;
304
133706
        if found {
305
86450
            break;
306
47256
        }
307
47256
        if sequential && let Some(name) = spec_name(spec) {
308
5785
            scope.vars.push(name.to_string());
309
41471
        }
310
    }
311
140090
    if !found {
312
53640
        if !sequential {
313
46910
            scope
314
46910
                .vars
315
46910
                .extend(specs.iter().filter_map(spec_name).map(str::to_string));
316
6730
        }
317
53640
        found = body(env, scope, forms, visitor)?;
318
86450
    }
319
140090
    scope.vars.truncate(mark);
320
140090
    Ok(found)
321
140092
}
322

            
323
195409
fn dolist<V: Visit>(
324
195409
    env: &mut Env<'_>,
325
195409
    scope: &mut Scope,
326
195409
    rest: &[Expr],
327
195409
    visitor: &mut V,
328
195409
) -> Result<bool> {
329
195409
    let Some((Expr::List(spec), forms)) = rest.split_first() else {
330
837
        return all(env, scope, rest, visitor);
331
    };
332
194572
    let (Some(Expr::Symbol(var)), Some(list)) = (spec.first(), spec.get(1)) else {
333
211
        return all(env, scope, rest, visitor);
334
    };
335
194361
    if walk(env, scope, list, visitor)? {
336
34235
        return Ok(true);
337
160126
    }
338
160126
    scope.vars.push(var.clone());
339
160126
    let found = body(env, scope, forms, visitor);
340
160126
    scope.vars.pop();
341
160126
    if found? {
342
42383
        return Ok(true);
343
117743
    }
344
117743
    all(env, scope, spec.get(2..).unwrap_or_default(), visitor)
345
195409
}
346

            
347
394474
fn do_form<V: Visit>(
348
394474
    env: &mut Env<'_>,
349
394474
    scope: &mut Scope,
350
394474
    sequential: bool,
351
394474
    rest: &[Expr],
352
394474
    visitor: &mut V,
353
394474
) -> Result<bool> {
354
394474
    let Some((specs, tail)) = rest
355
394474
        .split_first()
356
393642
        .and_then(|(specs, tail)| Some((specs.as_list()?, tail)))
357
    else {
358
835
        return all(env, scope, rest, visitor);
359
    };
360
393639
    let mark = scope.vars.len();
361
393639
    let mut found = false;
362
393639
    for spec in specs {
363
664966
        found = all(
364
664966
            env,
365
664966
            scope,
366
664966
            spec_forms(spec).get(..1).unwrap_or_default(),
367
664966
            visitor,
368
664966
        )?;
369
664966
        if found {
370
214
            break;
371
664752
        }
372
664752
        if sequential && let Some(name) = spec_name(spec) {
373
21266
            scope.vars.push(name.to_string());
374
643486
        }
375
    }
376
393639
    if !found {
377
393425
        if !sequential {
378
382179
            scope
379
382179
                .vars
380
382179
                .extend(specs.iter().filter_map(spec_name).map(str::to_string));
381
11246
        }
382
393425
        let steps: Vec<&Expr> = specs
383
393425
            .iter()
384
664538
            .filter_map(|spec| spec_forms(spec).get(1))
385
            .collect();
386
653793
        found = steps.iter().try_fold(false, |found, step| {
387
653793
            Ok(found || walk(env, scope, step, visitor)?)
388
653793
        })?;
389
393425
        found = found
390
354267
            || match tail.split_first() {
391
                Some((Expr::List(end), forms)) => {
392
353628
                    all(env, scope, end, visitor)? || body(env, scope, forms, visitor)?
393
                }
394
639
                _ => all(env, scope, tail, visitor)?,
395
            };
396
214
    }
397
393639
    scope.vars.truncate(mark);
398
393639
    Ok(found)
399
394474
}
400

            
401
20434
fn lambda<V: Visit>(
402
20434
    env: &mut Env<'_>,
403
20434
    scope: &mut Scope,
404
20434
    rest: &[Expr],
405
20434
    visitor: &mut V,
406
20434
) -> Result<bool> {
407
20434
    let Some((Expr::List(params), forms)) = rest.split_first() else {
408
9512
        return all(env, scope, rest, visitor);
409
    };
410
10922
    let mark = scope.vars.len();
411
10922
    scope
412
10922
        .vars
413
10922
        .extend(params.iter().filter_map(spec_name).map(str::to_string));
414
10922
    let found = body(env, scope, forms, visitor);
415
10922
    scope.vars.truncate(mark);
416
10922
    found
417
20434
}
418

            
419
721078
pub(crate) fn is_literal(form: &Expr) -> bool {
420
721078
    matches!(
421
721078
        form,
422
        Expr::Nil | Expr::T | Expr::Number(_) | Expr::String(_) | Expr::Keyword(_)
423
    )
424
721078
}
425

            
426
/// A `(lambda …)` or `(function (lambda …))` list: the lambda a head spells
427
/// out, as opposed to one a call or a name produces.
428
1440352
pub(crate) fn is_lambda_head(symbols: &SymbolTable, form: &Expr) -> bool {
429
1440352
    let Expr::List(elems) = form else {
430
771539
        return false;
431
    };
432
668813
    match elems.as_slice() {
433
76446
        [head, inner] if is_special_head(symbols, head, "FUNCTION") => {
434
23302
            matches!(inner, Expr::List(_)) && is_lambda_head(symbols, inner)
435
        }
436
645511
        [head, ..] => is_special_head(symbols, head, "LAMBDA"),
437
        [] => false,
438
    }
439
1440352
}
440

            
441
721957
fn is_special_head(symbols: &SymbolTable, head: &Expr, name: &str) -> bool {
442
721957
    matches!(head, Expr::Symbol(head) if head.eq_ignore_ascii_case(name)
443
609343
        && matches!(symbols.resolve_head(head), Head::SpecialForm))
444
721957
}
445

            
446
/// A `lambda` / `function` form or a lambda value, whose body does not run
447
/// where it is created.
448
1847450
pub(crate) fn is_lambda_literal(symbols: &SymbolTable, form: &Expr) -> bool {
449
1847450
    matches!(form, Expr::Lambda(..))
450
1847450
        || matches!(
451
1847450
            form,
452
583198
            Expr::List(elems) if matches!(
453
583198
                elems.first(),
454
581103
                Some(Expr::Symbol(head)) if (head.eq_ignore_ascii_case("LAMBDA")
455
415976
                    || head.eq_ignore_ascii_case("FUNCTION"))
456
166443
                    && matches!(symbols.resolve_head(head), Head::SpecialForm)
457
            )
458
        )
459
1847450
}