1
//! The syntactic scans the LET and loop binders share: which variables a body
2
//! assigns, and the pair element an accumulator store builds. Both honour
3
//! lexical shadowing and never look inside quoted data.
4

            
5
use crate::ast::{Expr, PairElement, WasmType};
6
use crate::compiler::expr::eval_value;
7
use crate::compiler::native::{literal_pair_element, runtime_cell_slot};
8
use crate::error::Result;
9
use crate::runtime::{Head, Symbol, SymbolTable, with_sufficient_stack};
10

            
11
use super::binding::spec_name;
12

            
13
/// Every `(setf <name> rhs)` in `exprs` whose `<name>` is not rebound by an
14
/// enclosing binder inside `exprs`, first occurrence per name, in source order.
15
831302
pub(in crate::compiler::special) fn collect_setf_targets(
16
831302
    exprs: &[Expr],
17
831302
) -> Vec<(String, Option<Expr>)> {
18
831302
    let mut targets: Vec<(String, Option<Expr>)> = Vec::new();
19
831302
    for_each_setf(exprs, &mut |place, rhs| {
20
278679
        if !targets.iter().any(|(name, _)| name == place) {
21
277611
            targets.push((place.to_string(), rhs.cloned()));
22
1068
        }
23
278679
    });
24
831302
    targets
25
831302
}
26

            
27
/// Every right-hand side `exprs` stores into the variable `name` it sees.
28
63254
pub(in crate::compiler::special) fn setf_rhs_of<'a>(
29
63254
    exprs: &'a [Expr],
30
63254
    name: &str,
31
63254
) -> Vec<&'a Expr> {
32
63254
    let mut out = Vec::new();
33
65599
    for_each_setf(exprs, &mut |place, rhs| {
34
65599
        if place == name
35
61069
            && let Some(rhs) = rhs
36
        {
37
61069
            out.push(rhs);
38
4530
        }
39
65599
    });
40
63254
    out
41
63254
}
42

            
43
/// Whether `exprs` assigns the variable `name` it sees.
44
11138722
pub(in crate::compiler::special) fn assigns(exprs: &[Expr], name: &str) -> bool {
45
11138722
    let mut found = false;
46
11138722
    for_each_setf(exprs, &mut |place, _| found |= place == name);
47
11138722
    found
48
11138722
}
49

            
50
/// Whether the binder form `elems` rebinds `name` for any of its subforms.
51
1272816
pub(in crate::compiler::special) fn binder_rebinds(elems: &[Expr], name: &str) -> bool {
52
1272816
    binder(elems).is_some_and(|(_, specs)| spec_names(specs).any(|bound| bound == name))
53
1272816
}
54

            
55
/// Calls `visit(place, rhs)` for each unshadowed `(setf place rhs)` pair.
56
12033278
fn for_each_setf<'a>(exprs: &'a [Expr], visit: &mut impl FnMut(&'a str, Option<&'a Expr>)) {
57
12033278
    walk_all(exprs, &mut Vec::new(), visit);
58
12033278
}
59

            
60
#[derive(Clone, Copy)]
61
pub(in crate::compiler) enum Binder {
62
    Let,
63
    LetStar,
64
    Do,
65
    DoStar,
66
    Dolist,
67
    Lambda,
68
}
69

            
70
/// The binder `elems` heads and its binding specs.
71
1475921362
pub(in crate::compiler) fn binder(elems: &[Expr]) -> Option<(Binder, &[Expr])> {
72
1475921362
    let kind = match head(elems)?.to_ascii_uppercase().as_str() {
73
235561274
        "LET" => Binder::Let,
74
347748
        "LET*" => Binder::LetStar,
75
2327593
        "DO" => Binder::Do,
76
18227
        "DO*" => Binder::DoStar,
77
1483614
        "DOLIST" => Binder::Dolist,
78
3488923
        "LAMBDA" => Binder::Lambda,
79
1232693027
        _ => return None,
80
    };
81
243227379
    match (kind, elems.get(1)) {
82
1482782
        (Binder::Dolist, Some(spec @ Expr::List(_))) => Some((kind, std::slice::from_ref(spec))),
83
241740645
        (_, Some(specs)) => specs.as_list().map(|specs| (kind, specs)),
84
3952
        _ => None,
85
    }
86
1475921362
}
87

            
88
/// How `elems[index]` holds code: a plain form, a name, a clause whose first
89
/// `keep` parts are names, or a list of such clauses.
90
enum Slot {
91
    Form,
92
    Name,
93
    Clause(usize),
94
    Clauses(usize),
95
}
96

            
97
1382448649
fn slot(elems: &[Expr], index: usize) -> Slot {
98
1382448649
    let Some(Expr::Symbol(head)) = elems.first() else {
99
3437
        return Slot::Form;
100
    };
101
7482116647
    let is = |name: &str| head.eq_ignore_ascii_case(name);
102
1382445212
    let definition = is("DEFUN") || is("DEFMACRO");
103
1382445212
    match (binder(elems), index) {
104
268549
        (Some((Binder::Dolist, _)), 1) => Slot::Clause(1),
105
46032535
        (Some(_), 1) => Slot::Clauses(1),
106
693666
        (Some((Binder::Do | Binder::DoStar, _)), 2) => Slot::Clause(0),
107
1234003307
        (_, 1..) if is("COND") => Slot::Clause(0),
108
1128715465
        (_, 2..) if is("CASE") || is("ECASE") => Slot::Clause(1),
109
1128705742
        (_, 2..) if is("HANDLER-CASE") => Slot::Clause(2),
110
97354014
        (_, 1) if is("LABELS") => Slot::Clauses(2),
111
97302444
        (_, 1) if definition => Slot::Name,
112
155401597
        (_, 2) if definition => Slot::Clauses(1),
113
1327190372
        _ => Slot::Form,
114
    }
115
1382448649
}
116

            
117
impl Slot {
118
    /// The parts of `elem` that run as code.
119
1115460775
    fn forms(self, elem: &Expr) -> Vec<&Expr> {
120
1115460775
        match self {
121
1109323891
            Slot::Form => vec![elem],
122
52249
            Slot::Name => Vec::new(),
123
5975836
            Slot::Clause(keep) => clause_forms(elem, keep).collect(),
124
108799
            Slot::Clauses(keep) => (elem.as_list().unwrap_or_default().iter())
125
68973
                .flat_map(|clause| clause_forms(clause, keep))
126
                .collect(),
127
        }
128
1115460775
    }
129

            
130
    /// `elem` with `f` applied to each part that runs as code.
131
266987874
    fn map(self, elem: &Expr, f: &mut impl FnMut(&Expr) -> Result<Expr>) -> Result<Expr> {
132
266987874
        match (self, elem) {
133
217869918
            (Slot::Form, _) => f(elem),
134
3039353
            (Slot::Clause(keep), _) => clause_mapped(elem, keep, f),
135
45956599
            (Slot::Clauses(keep), Expr::List(clauses)) => clauses
136
45956599
                .iter()
137
46105330
                .map(|clause| clause_mapped(clause, keep, f))
138
                .collect::<Result<_>>()
139
45956599
                .map(Expr::List),
140
122004
            _ => Ok(elem.clone()),
141
        }
142
266987874
    }
143
}
144

            
145
6044809
fn clause_forms(clause: &Expr, keep: usize) -> impl Iterator<Item = &Expr> {
146
6044809
    clause.as_list().unwrap_or_default().iter().skip(keep)
147
6044809
}
148

            
149
/// `clause` with its first `keep` parts as written and `f` applied to the rest.
150
49144683
fn clause_mapped(
151
49144683
    clause: &Expr,
152
49144683
    keep: usize,
153
49144683
    f: &mut impl FnMut(&Expr) -> Result<Expr>,
154
49144683
) -> Result<Expr> {
155
49144683
    let Expr::List(parts) = clause else {
156
247479
        return Ok(clause.clone());
157
    };
158
48897204
    let (kept, forms) = parts.split_at(keep.min(parts.len()));
159
48897204
    (kept.iter().cloned().map(Ok))
160
48897204
        .chain(forms.iter().map(&mut *f))
161
48897204
        .collect::<Result<_>>()
162
48897204
        .map(Expr::List)
163
49144683
}
164

            
165
/// `elems` with `f` applied to each part that runs as code; binding names,
166
/// definition names, CASE keys, handler-case codes and LABELS names stay as written.
167
94023017
pub(in crate::compiler) fn code_mapped(
168
94023017
    elems: &[Expr],
169
94023017
    f: &mut impl FnMut(&Expr) -> Result<Expr>,
170
94023017
) -> Result<Vec<Expr>> {
171
94023017
    (elems.iter().enumerate())
172
266987874
        .map(|(index, elem)| slot(elems, index).map(elem, f))
173
        .collect()
174
94023017
}
175

            
176
/// The forms of `elems` from `from` on that run as code: not binding names,
177
/// CASE keys, handler-case codes or LABELS names.
178
279944826
pub(in crate::compiler) fn forms_from(elems: &[Expr], from: usize) -> impl Iterator<Item = &Expr> {
179
1115460775
    (from..elems.len()).flat_map(move |index| slot(elems, index).forms(&elems[index]))
180
279944826
}
181

            
182
/// The code positions of the form `elems`; a non-symbol head is code too.
183
220848323
pub(in crate::compiler) fn code_forms(elems: &[Expr]) -> impl Iterator<Item = &Expr> {
184
220848323
    forms_from(elems, usize::from(head(elems).is_some()))
185
220848323
}
186

            
187
50406082
fn spec_names(specs: &[Expr]) -> impl Iterator<Item = &str> {
188
50406082
    specs.iter().filter_map(spec_name)
189
50406082
}
190

            
191
/// The forms of a binding spec after its name: an init, then a step.
192
105216889
pub(in crate::compiler) fn spec_forms(spec: &Expr) -> &[Expr] {
193
105216889
    match spec {
194
102774864
        Expr::List(parts) => parts.get(1..).unwrap_or(&[]),
195
2442025
        _ => &[],
196
    }
197
105216889
}
198

            
199
154974514
fn walk<'a>(
200
154974514
    expr: &'a Expr,
201
154974514
    shadowed: &mut Vec<&'a str>,
202
154974514
    visit: &mut impl FnMut(&'a str, Option<&'a Expr>),
203
154974514
) {
204
154974514
    with_sufficient_stack(|| {
205
154974514
        let elems = match expr {
206
73020208
            Expr::List(elems) => elems,
207
            Expr::Quasiquote(template) => {
208
506
                for form in template.unquoted_forms() {
209
544
                    walk(form, shadowed, visit);
210
                }
211
506
                return;
212
            }
213
            Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => {
214
                return walk(inner, shadowed, visit);
215
            }
216
            Expr::Cons(car, cdr) => {
217
                walk(car, shadowed, visit);
218
                return walk(cdr, shadowed, visit);
219
            }
220
81953800
            _ => return,
221
        };
222
73020208
        match head(elems) {
223
73019324
            Some(name) if name.eq_ignore_ascii_case("QUOTE") => return,
224
73012709
            Some(name) if name.eq_ignore_ascii_case("SETF") => {
225
1519425
                for pair in elems[1..].chunks(2) {
226
1521089
                    if let Some(Expr::Symbol(place)) = pair.first()
227
1491137
                        && !shadowed.contains(&place.as_str())
228
                    {
229
1408235
                        visit(place, pair.get(1));
230
112854
                    }
231
                }
232
            }
233
71493284
            Some(name) if name.eq_ignore_ascii_case("DEFPARAMETER") => {
234
2185
                if let Some(Expr::Symbol(place)) = elems.get(1)
235
2185
                    && !shadowed.contains(&place.as_str())
236
                {
237
2173
                    visit(place, elems.get(2));
238
12
                }
239
            }
240
71491983
            _ => {}
241
        }
242
73013593
        let mark = shadowed.len();
243
73013593
        match binder(elems) {
244
            Some((kind, specs)) => {
245
39906532
                for step in binder_steps(kind, specs, elems) {
246
120525346
                    match step {
247
80597744
                        Step::Visit(expr) => walk(expr, shadowed, visit),
248
39927602
                        Step::Shadow(name) => shadowed.push(name),
249
                    }
250
                }
251
            }
252
33107061
            None => walk_all(code_forms(elems), shadowed, visit),
253
        }
254
73013593
        shadowed.truncate(mark);
255
154974514
    });
256
154974514
}
257

            
258
/// One move of a binder walk, in execution order.
259
pub(in crate::compiler) enum Step<'a> {
260
    Visit(&'a Expr),
261
    Shadow(&'a str),
262
}
263

            
264
/// Init forms run in the enclosing scope (a sequential binder's also see the
265
/// names bound before them); steps and the body see every bound name. A
266
/// lambda list is sequential: each default sees the parameters before it.
267
51668104
pub(in crate::compiler) fn binder_steps<'a>(
268
51668104
    kind: Binder,
269
51668104
    specs: &'a [Expr],
270
51668104
    elems: &'a [Expr],
271
51668104
) -> Vec<Step<'a>> {
272
51668104
    let sequential = matches!(kind, Binder::LetStar | Binder::DoStar);
273
51668104
    let mut steps = Vec::new();
274
51668104
    if matches!(kind, Binder::Lambda) {
275
1261586
        for spec in specs {
276
1190018
            steps.extend(spec_forms(spec).iter().map(Step::Visit));
277
1190018
            steps.extend(spec_name(spec).map(Step::Shadow));
278
        }
279
    } else {
280
50406518
        for spec in specs {
281
50632507
            steps.extend(spec_forms(spec).first().map(Step::Visit));
282
50632507
            if sequential {
283
269828
                steps.extend(spec_name(spec).map(Step::Shadow));
284
50362679
            }
285
        }
286
50406518
        if !sequential {
287
50290586
            steps.extend(spec_names(specs).map(Step::Shadow));
288
115932
        }
289
50406518
        for spec in specs {
290
50632507
            steps.extend(
291
50632507
                spec_forms(spec)
292
50632507
                    .get(1..)
293
50632507
                    .unwrap_or(&[])
294
50632507
                    .iter()
295
50632507
                    .map(Step::Visit),
296
50632507
            );
297
        }
298
    }
299
51668104
    steps.extend(forms_from(elems, 2).map(Step::Visit));
300
51668104
    steps
301
51668104
}
302

            
303
45140339
fn walk_all<'a>(
304
45140339
    exprs: impl IntoIterator<Item = &'a Expr>,
305
45140339
    shadowed: &mut Vec<&'a str>,
306
45140339
    visit: &mut impl FnMut(&'a str, Option<&'a Expr>),
307
45140339
) {
308
45140339
    for expr in exprs {
309
74376226
        walk(expr, shadowed, visit);
310
    }
311
45140339
}
312

            
313
1770619749
fn head(elems: &[Expr]) -> Option<&str> {
314
1770619749
    match elems.first() {
315
1770537145
        Some(Expr::Symbol(name)) => Some(name),
316
82604
        _ => None,
317
    }
318
1770619749
}
319

            
320
/// The pair element an accumulator store `expr` builds: the car of a native
321
/// `(cons V acc)` anywhere in it, or the elements of a native `(list …)` that
322
/// is the stored value itself. Quoted data and lambda bodies build nothing;
323
/// branch arms that disagree widen to `AnyRef`, as the branch's own value does.
324
479765
pub(in crate::compiler::special) fn step_pair_element(
325
479765
    expr: &Expr,
326
479765
    symbols: &SymbolTable,
327
479765
) -> Option<PairElement> {
328
479765
    built_element(expr, symbols, true)
329
479765
}
330

            
331
/// `value` says whether `expr` is the stored value rather than a subform of it.
332
1577146
fn built_element(expr: &Expr, symbols: &SymbolTable, value: bool) -> Option<PairElement> {
333
1577146
    let Expr::List(elems) = expr else {
334
750240
        return None;
335
    };
336
826906
    let name = head(elems)?.to_ascii_uppercase();
337
747026
    match name.as_str() {
338
2
        "QUOTE" | "LAMBDA" | "FUNCTION" => None,
339
139586
        "IF" => join(
340
139586
            elems
341
139586
                .iter()
342
139586
                .skip(2)
343
279172
                .map(|arm| built_element(arm, symbols, value)),
344
        ),
345
1665
        "COND" => join(
346
1665
            elems[1..]
347
1665
                .iter()
348
3330
                .filter_map(|clause| match clause {
349
3330
                    Expr::List(parts) => parts.last(),
350
                    _ => None,
351
3330
                })
352
3330
                .map(|arm| built_element(arm, symbols, value)),
353
        ),
354
243867
        "CONS" if elems.len() == 3 && head_is_native("CONS", symbols) => {
355
243866
            resolve_pair_element(&elems[1], symbols).or_else(|| nested(elems, symbols))
356
        }
357
87009
        "LIST" if value && elems.len() > 1 && head_is_native("LIST", symbols) => {
358
86366
            let items = elems[1..]
359
86366
                .iter()
360
86388
                .map(|item| {
361
86388
                    resolve_pair_element(item, symbols).or_else(|| nil_variable_slot(item, symbols))
362
86388
                })
363
                .collect::<Option<Vec<_>>>();
364
86366
            items.and_then(|items| join(items.into_iter().map(Some)))
365
        }
366
275541
        _ => nested(elems, symbols),
367
    }
368
1577146
}
369

            
370
/// A variable that holds nil now (a DO accumulator seed) may hold any list on
371
/// a later step, so its slot is the wide one.
372
10
fn nil_variable_slot(item: &Expr, symbols: &SymbolTable) -> Option<PairElement> {
373
10
    let Expr::Symbol(name) = item else {
374
        return None;
375
    };
376
10
    matches!(symbols.lookup(name)?.value()?, Expr::Nil).then_some(PairElement::AnyRef)
377
10
}
378

            
379
275781
fn nested(elems: &[Expr], symbols: &SymbolTable) -> Option<PairElement> {
380
814879
    elems.iter().find_map(|e| built_element(e, symbols, false))
381
275781
}
382

            
383
/// The one element every known arm agrees on, or `AnyRef` when they differ;
384
/// an arm that builds nothing does not vote.
385
493050
pub(in crate::compiler::special) fn join(
386
493050
    arms: impl Iterator<Item = Option<PairElement>>,
387
493050
) -> Option<PairElement> {
388
493050
    arms.flatten().reduce(|joined, arm| {
389
457
        if joined == arm {
390
216
            joined
391
        } else {
392
241
            PairElement::AnyRef
393
        }
394
457
    })
395
493050
}
396

            
397
656008
fn resolve_pair_element(expr: &Expr, symbols: &SymbolTable) -> Option<PairElement> {
398
656008
    match expr {
399
        Expr::WasmRuntime(ty) | Expr::WasmLocal(_, ty) | Expr::WasmGlobal(_, ty) => {
400
321632
            Some(runtime_cell_slot(*ty))
401
        }
402
7735
        Expr::Number(_) => literal_pair_element(expr),
403
4
        Expr::T => Some(PairElement::Bool),
404
633
        Expr::String(_) => Some(PairElement::StringRef),
405
        Expr::Symbol(name) => {
406
318841
            let value = symbols.lookup(name)?.value()?;
407
318837
            resolve_pair_element(value, symbols)
408
        }
409
7151
        Expr::List(elems) if is_variable_funcall(elems, symbols) => {
410
1458
            evaluated_element(&closure_applied(elems, symbols), symbols)
411
        }
412
        // A native, host-fn or user-function call car: its type is what it
413
        // evaluates to on a clone; a user call runs through the depth-guarded inliner.
414
5693
        Expr::List(elems) if is_pure_native_expr(expr, symbols) || is_user_call(elems, symbols) => {
415
5478
            evaluated_element(expr, symbols)
416
        }
417
227
        _ => None,
418
    }
419
656008
}
420

            
421
6936
fn evaluated_element(call: &Expr, symbols: &SymbolTable) -> Option<PairElement> {
422
6936
    match eval_value(&mut symbols.speculative_clone(), call).ok()? {
423
        Expr::List(_) => None,
424
6917
        other => resolve_pair_element(&other, symbols),
425
    }
426
6936
}
427

            
428
/// `(funcall f …)` of a lambda-valued variable as the application of the
429
/// lambda itself to untyped arguments, as the closure's body is compiled.
430
1458
fn closure_applied(elems: &[Expr], symbols: &SymbolTable) -> Expr {
431
1458
    let callee = elems[1]
432
1458
        .as_symbol()
433
1458
        .and_then(|name| symbols.lookup(name))
434
1458
        .and_then(Symbol::value);
435
1458
    match callee {
436
        Some(lambda @ Expr::Lambda(..)) => {
437
1042
            let mut applied = vec![lambda.clone()];
438
1042
            applied.extend(
439
1042
                elems[2..]
440
1042
                    .iter()
441
208
                    .map(|_| Expr::WasmRuntime(WasmType::AnyRef)),
442
            );
443
1042
            Expr::List(applied)
444
        }
445
416
        _ => Expr::List(elems.to_vec()),
446
    }
447
1458
}
448

            
449
/// `(funcall f …)` of a bound variable with natively pure arguments.
450
7151
fn is_variable_funcall(elems: &[Expr], symbols: &SymbolTable) -> bool {
451
7151
    matches!(elems, [Expr::Symbol(head), Expr::Symbol(callee), args @ ..]
452
4013
        if head.eq_ignore_ascii_case("FUNCALL")
453
1459
            && symbols.lookup(callee).is_some_and(|sym| sym.value().is_some())
454
1458
            && args.iter().all(|arg| is_pure_native_expr(arg, symbols)))
455
7151
}
456

            
457
2950
fn is_user_call(elems: &[Expr], symbols: &SymbolTable) -> bool {
458
2950
    head(elems).is_some_and(|h| matches!(symbols.resolve_head(h), Head::Function(..)))
459
2950
}
460

            
461
/// Whether `expr` is safe to `eval_value` purely for type inference: every
462
/// call head is a native no user definition shadows, and no operand names a
463
/// user function a higher-order native could call.
464
11599
pub(in crate::compiler::special) fn is_pure_native_expr(
465
11599
    expr: &Expr,
466
11599
    symbols: &SymbolTable,
467
11599
) -> bool {
468
11599
    match expr {
469
        Expr::Number(_)
470
        | Expr::T
471
        | Expr::Nil
472
        | Expr::String(_)
473
        | Expr::Bytes(_)
474
        | Expr::Keyword(_)
475
        | Expr::Quote(_)
476
        | Expr::Datum(_)
477
        | Expr::WasmRuntime(_)
478
        | Expr::WasmLocal(_, _)
479
1275
        | Expr::WasmGlobal(_, _) => true,
480
2963
        Expr::Symbol(name) => !names_user_callable(name, symbols),
481
7361
        Expr::List(elems) => match elems.first() {
482
            Some(Expr::Symbol(head)) => {
483
7361
                head_is_native(head, symbols)
484
5698
                    && elems[1..].iter().all(|e| is_pure_native_expr(e, symbols))
485
            }
486
            _ => false,
487
        },
488
        _ => false,
489
    }
490
11599
}
491

            
492
337594
fn head_is_native(head: &str, symbols: &SymbolTable) -> bool {
493
337594
    matches!(symbols.resolve_head(head), Head::Native)
494
337594
}
495

            
496
2965
fn names_user_callable(name: &str, symbols: &SymbolTable) -> bool {
497
2965
    matches!(
498
2965
        symbols.resolve_head(name),
499
        Head::Macro(..) | Head::Function(..)
500
2963
    ) || symbols
501
2963
        .lookup(name)
502
2963
        .is_some_and(|sym| matches!(sym.value(), Some(Expr::Lambda(_, _))))
503
2965
}
504

            
505
#[cfg(test)]
506
#[path = "setf_scan_tests.rs"]
507
mod tests;