Skip to main content

nodejs/
slots.rs

1//! Which locals can live in fusevm frame slots instead of the host's scope
2//! chain.
3//!
4//! Every identifier in a node-js program is a name lookup: the compiler emits
5//! `CallBuiltin(GETLOCAL)` with the name as a string constant, and the host pops
6//! it off the VM stack, borrows the thread-local `JsHost`, walks the
7//! `Rc<RefCell<EnvData>>` chain and hashes the name in each scope. An empty
8//! `for (let i = 0; i < 5_000_000; i++) {}` costs four of those round-trips per
9//! iteration — 178 ns against node's 6 ns — and none of them is JIT-able, since
10//! fusevm's block tier declines any region containing a `CallBuiltin`.
11//!
12//! A local that no closure can reach does not need a scope entry at all: it can
13//! live in the frame slot vector fusevm already keeps, addressed by index
14//! (`Op::GetSlot` / `Op::SetSlot`). This module decides which names qualify.
15//! The shape of the analysis follows pythonrs's `fn_slots_allowed` /
16//! `fn_slots`, which does the same job against the same VM.
17//!
18//! The rules are deliberately conservative, because a name that is slotted in
19//! one place and looked up by name in another is a silent wrong answer:
20//!
21//! 1. **A name reachable from another chunk keeps its binding.** A nested
22//!    function, arrow or class body compiles to its own chunk and resolves what
23//!    it captures through the environment chain; a `try` block is likewise its
24//!    own chunk on its own VM frame, so a slot written outside it is invisible
25//!    inside. Every identifier mentioned in either is therefore off the table —
26//!    but only those identifiers, not the whole chunk, so a loop counter still
27//!    gets a slot in a file that also defines a callback. A direct `eval` can
28//!    name anything, so it disables the chunk outright.
29//! 2. **One declaration per name.** Shadowing (`let x` in two sibling blocks) is
30//!    exactly where a flat name→slot table would be wrong, so a name declared
31//!    more than once in the chunk is left alone rather than scope-tracked.
32//! 3. **No read before the declaration, in source order.** This is what keeps
33//!    the temporal dead zone and `var` hoisting behaving as they do today: a
34//!    slot reads as `undefined` before its first write, which is neither node's
35//!    `ReferenceError` for a `let` nor what node-js currently answers. A name
36//!    whose first mention is a read stays on the name path, where those answers
37//!    come from. Source order is a conservative stand-in for execution order —
38//!    a loop can re-enter a block, but it cannot reach a statement the source
39//!    has not introduced yet.
40//! 4. **Simple identifiers only.** Destructuring targets, `delete x`, and
41//!    anything that is not an `Expr::Ident` bind through the host.
42//! 5. **At the top level of a script, `let`/`const` only.** A top-level `var` is
43//!    a property of the global object (`var g = 1; globalThis.g` is `1` on node
44//!    v26.7.0), so it has to stay a real binding.
45
46use crate::ast::{DeclKind, Expr, Param, Prop, Stmt, StmtKind, SwitchCase};
47use rustc_hash::{FxHashMap, FxHashSet};
48
49/// Name → frame slot for one chunk. Empty when the chunk is not eligible.
50pub type SlotTable = FxHashMap<String, u16>;
51
52/// What the compiler needs to know about a chunk's locals.
53#[derive(Default)]
54pub struct Plan {
55    /// The slotted names and their frame indices.
56    pub table: SlotTable,
57    /// Of those, the ones provably holding a Number, so `++`/`--` can be a
58    /// native add instead of a `NUM_STEP` call into the host.
59    pub numeric: FxHashSet<String>,
60    /// Of those, the ones declared `const`. A slotted binding never reaches the
61    /// host's scope chain, so the host's immutable-binding check cannot see it;
62    /// the compiler rejects the assignment instead, which costs nothing at run
63    /// time and is exact (see `Planner::consts`).
64    pub consts: FxHashSet<String>,
65}
66
67/// Is this initializer a literal Number? `-1` reaches the compiler as a unary
68/// negation of `1`, so it counts too.
69fn is_number_literal(e: &Expr) -> bool {
70    match e {
71        Expr::Number(_) => true,
72        Expr::Unary(crate::ast::UnOp::Neg, inner) => matches!(**inner, Expr::Number(_)),
73        _ => false,
74    }
75}
76
77/// Plan the slots for a chunk: `params` are bound into the environment by the
78/// caller before the chunk runs (the compiler emits a prologue that copies each
79/// into its slot), `body` is the statement list about to be compiled, and
80/// `top_level` marks a script/module body, where `var` stays a global.
81pub fn plan(params: &[Param], body: &[Stmt], top_level: bool) -> Plan {
82    if !chunk_is_eligible(body) {
83        return Plan::default();
84    }
85    // Anything a nested chunk can name resolves through the environment, so it
86    // cannot move into this frame's slots.
87    let mut escaping = FxHashSet::default();
88    for s in body {
89        collect_escaping_stmt(s, &mut escaping);
90    }
91    let mut p = Planner {
92        candidates: SlotTable::default(),
93        rejected: escaping,
94        numeric: FxHashSet::default(),
95        consts: FxHashSet::default(),
96        top_level,
97        next: 0,
98        lexical_log: Vec::new(),
99        closed: FxHashSet::default(),
100    };
101    // Parameters are declared and assigned before the first statement runs.
102    // Their incoming type is whatever the caller passed, so they are never in
103    // the numeric set.
104    for name in param_names(params) {
105        p.declare(&name);
106    }
107    for s in body {
108        p.walk_stmt(s);
109    }
110    for name in p.rejected {
111        p.candidates.remove(&name);
112        p.numeric.remove(&name);
113        p.consts.remove(&name);
114    }
115    Plan {
116        table: p.candidates,
117        numeric: p.numeric,
118        consts: p.consts,
119    }
120}
121
122/// The simple identifier parameters, in order. A destructuring or rest pattern
123/// is bound by the body prologue, so it is not seeded here.
124pub fn param_names(params: &[Param]) -> Vec<String> {
125    params
126        .iter()
127        .filter(|p| !p.rest)
128        .filter_map(|p| match &p.pattern {
129            Expr::Ident(n) => Some(n.clone()),
130            _ => None,
131        })
132        .collect()
133}
134
135/// Is this chunk's frame stable enough to hold slots at all? Two things say no
136/// for the whole chunk rather than for one name: a direct `eval`, which can read
137/// or write any binding by a name only known at run time, and a `yield`/`await`
138/// at this chunk's own level, which suspends the frame the slots live in.
139/// (Nested function bodies are their own chunks; what they contain is their
140/// business, and what they NAME is handled per-name by `collect_escaping_*`.)
141fn chunk_is_eligible(body: &[Stmt]) -> bool {
142    !mentions_eval_stmts(body) && body.iter().all(stmt_slot_safe)
143}
144
145/// `eval` named anywhere, at any depth — including inside a nested function,
146/// which can be handed this frame's environment.
147fn mentions_eval_stmts(body: &[Stmt]) -> bool {
148    let mut names = FxHashSet::default();
149    for s in body {
150        collect_all_idents_stmt(s, &mut names);
151    }
152    names.contains("eval")
153}
154
155/// A `try` runs as its own chunk on its own frame; `yield`/`await` suspend the
156/// frame; `delete x` removes a binding a slot does not have.
157fn stmt_slot_safe(s: &Stmt) -> bool {
158    match &s.kind {
159        // A `try` compiles to sub-chunks; the names they touch are handled by
160        // `collect_escaping_stmt`, so the statement itself is no obstacle.
161        StmtKind::Try {
162            block,
163            handler,
164            finalizer,
165        } => {
166            block.iter().all(stmt_slot_safe)
167                && handler
168                    .as_ref()
169                    .map_or(true, |(_, b)| b.iter().all(stmt_slot_safe))
170                && finalizer
171                    .as_ref()
172                    .map_or(true, |b| b.iter().all(stmt_slot_safe))
173        }
174        StmtKind::Expr(e) | StmtKind::Throw(e) => expr_slot_safe(e),
175        StmtKind::Return(e) => e.as_ref().map_or(true, expr_slot_safe),
176        StmtKind::Decl { decls, .. } => decls
177            .iter()
178            .all(|d| d.init.as_ref().map_or(true, expr_slot_safe)),
179        StmtKind::Block(body) => body.iter().all(stmt_slot_safe),
180        StmtKind::If { test, cons, alt } => {
181            expr_slot_safe(test)
182                && stmt_slot_safe(cons)
183                && alt.as_deref().map_or(true, stmt_slot_safe)
184        }
185        StmtKind::While { test, body } | StmtKind::DoWhile { body, test } => {
186            expr_slot_safe(test) && stmt_slot_safe(body)
187        }
188        // A `with` body resolves names against an object chosen at run time, so no
189        // identifier in the chunk can be pinned to a slot.
190        StmtKind::With { .. } => false,
191        StmtKind::For {
192            init,
193            test,
194            update,
195            body,
196        } => {
197            init.as_deref().map_or(true, stmt_slot_safe)
198                && test.as_ref().map_or(true, expr_slot_safe)
199                && update.as_ref().map_or(true, expr_slot_safe)
200                && stmt_slot_safe(body)
201        }
202        StmtKind::ForOf {
203            target,
204            iter,
205            body,
206            is_await,
207            ..
208        } => !*is_await && expr_slot_safe(target) && expr_slot_safe(iter) && stmt_slot_safe(body),
209        StmtKind::ForIn {
210            target,
211            object,
212            body,
213            ..
214        } => expr_slot_safe(target) && expr_slot_safe(object) && stmt_slot_safe(body),
215        StmtKind::Switch { disc, cases } => {
216            expr_slot_safe(disc)
217                && cases.iter().all(|c: &SwitchCase| {
218                    c.test.as_ref().map_or(true, expr_slot_safe)
219                        && c.body.iter().all(stmt_slot_safe)
220                })
221        }
222        StmtKind::Labeled { body, .. } => stmt_slot_safe(body),
223        StmtKind::Break(_) | StmtKind::Continue(_) | StmtKind::Empty => true,
224        // Lowered away by `esm::lower` before any chunk is compiled.
225        StmtKind::Import(_) | StmtKind::Export(_) => false,
226        // A nested function or class body is its own chunk with its own frame:
227        // nothing in it can unsettle this one. What it NAMES is refused per
228        // name by `collect_escaping_stmt`.
229        StmtKind::FuncDecl { .. } | StmtKind::ClassDecl(_) => true,
230    }
231}
232
233fn expr_slot_safe(e: &Expr) -> bool {
234    let all = |xs: &[Expr]| xs.iter().all(expr_slot_safe);
235    match e {
236        Expr::Yield { .. } | Expr::Await(..) => false,
237        // `delete x` is a binding operation a slot cannot express — the NAME is
238        // refused in the walk, the statement holding it is fine.
239        Expr::Unary(_, inner) | Expr::Spread(inner) => expr_slot_safe(inner),
240        Expr::Template { exprs, .. } => all(exprs),
241        Expr::TaggedTemplate { tag, exprs, .. } => expr_slot_safe(tag) && all(exprs),
242        Expr::Array(items) | Expr::Sequence(items) => all(items),
243        Expr::Object(props) => props.iter().all(|p| match p {
244            Prop::KeyValue { key, value, .. } => expr_slot_safe(key) && expr_slot_safe(value),
245            Prop::Spread(x) => expr_slot_safe(x),
246            // An accessor is a nested function: its names escape, it is not a
247            // reason to give up on the chunk.
248            Prop::Accessor { .. } => true,
249        }),
250        Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => expr_slot_safe(l) && expr_slot_safe(r),
251        Expr::Conditional { test, cons, alt } => {
252            expr_slot_safe(test) && expr_slot_safe(cons) && expr_slot_safe(alt)
253        }
254        Expr::Assign { target, value, .. } => expr_slot_safe(target) && expr_slot_safe(value),
255        Expr::Update { target, .. } => expr_slot_safe(target),
256        Expr::Call { func, args, .. }
257        | Expr::New {
258            callee: func, args, ..
259        } => expr_slot_safe(func) && all(args),
260        Expr::Member { object, .. } => expr_slot_safe(object),
261        Expr::Index { object, index, .. } => expr_slot_safe(object) && expr_slot_safe(index),
262        // Its own chunk, its own frame; `collect_escaping_expr` takes the names.
263        Expr::Function { .. } | Expr::Class(_) => true,
264        _ => true,
265    }
266}
267
268struct Planner {
269    candidates: SlotTable,
270    rejected: FxHashSet<String>,
271    /// Slots whose value is provably a JS Number at every point: declared from
272    /// a numeric literal and written afterwards only by `++`/`--`, which on a
273    /// Number yields a Number. `i++` on one of these needs no `NUM_STEP` call
274    /// into the host to do `ToNumeric` and stay BigInt-aware.
275    numeric: FxHashSet<String>,
276    /// Slotted names declared `const`. A slotted name is declared exactly once
277    /// in the chunk (rule 2), is unreachable from any other chunk (rule 1) and
278    /// is a simple identifier (rule 4), so a store to one is UNAMBIGUOUSLY a
279    /// store to that const binding and the compiler can reject it outright.
280    consts: FxHashSet<String>,
281    top_level: bool,
282    next: u16,
283    /// Every `let`/`const` declaration seen so far, in source order, so a
284    /// scope that ends can retire the names it introduced (see `close_scope`).
285    lexical_log: Vec<String>,
286    /// Names whose declaring block has ended. A later mention names an OUTER or
287    /// global binding, never the slot, so the name is given back to the host.
288    closed: FxHashSet<String>,
289}
290
291impl Planner {
292    /// A declaration in source order: the first one claims a slot, a second one
293    /// (rule 2) gives the name back to the host.
294    fn declare(&mut self, name: &str) {
295        if self.rejected.contains(name) {
296            return;
297        }
298        if self.candidates.contains_key(name) {
299            self.reject(name);
300            return;
301        }
302        // fusevm addresses slots with a `u16`; a chunk with more locals than
303        // that keeps the rest on the name path.
304        if self.next == u16::MAX {
305            self.reject(name);
306            return;
307        }
308        self.candidates.insert(name.to_string(), self.next);
309        self.next += 1;
310    }
311
312    fn reject(&mut self, name: &str) {
313        self.rejected.insert(name.to_string());
314    }
315
316    /// A mention of `name` that is not its declaration (rule 3): if the name has
317    /// no slot yet, its first mention is a read, so it never gets one.
318    fn mention(&mut self, name: &str) {
319        if self.closed.contains(name) {
320            self.reject(name);
321        }
322        if !self.candidates.contains_key(name) {
323            self.reject(name);
324        }
325    }
326
327    /// The declaration target of a `let`/`var`/`for`-head binding.
328    fn declare_target(&mut self, target: &Expr, kind: Option<DeclKind>) {
329        self.declare_target_init(target, kind, None)
330    }
331
332    /// As `declare_target`, plus the initializer, which decides whether the
333    /// binding starts out a Number (see `Planner::numeric`).
334    fn declare_target_init(&mut self, target: &Expr, kind: Option<DeclKind>, init: Option<&Expr>) {
335        let Expr::Ident(n) = target else {
336            // A destructuring pattern binds through the host; every name in it
337            // is off the table.
338            self.reject_names_in(target);
339            return;
340        };
341        match kind {
342            // Rule 5: a top-level `var` is a global-object property.
343            Some(DeclKind::Var) if self.top_level => self.reject(n),
344            Some(k) => {
345                self.declare(n);
346                if k != DeclKind::Var {
347                    self.lexical_log.push(n.clone());
348                }
349                if init.is_some_and(is_number_literal) {
350                    self.numeric.insert(n.clone());
351                }
352                if k == DeclKind::Const {
353                    self.consts.insert(n.clone());
354                }
355            }
356            // `for (x of …)` with no declaration keyword assigns an existing
357            // binding — that is a mention, not a declaration.
358            None => self.mention(n),
359        }
360    }
361
362    fn reject_names_in(&mut self, e: &Expr) {
363        let mut names = Vec::new();
364        collect_idents(e, &mut names);
365        for n in names {
366            self.reject(&n);
367        }
368    }
369
370    /// Walk one statement; a statement that opens a lexical scope retires the
371    /// `let`/`const` names it declared once it ends.
372    fn walk_stmt(&mut self, s: &Stmt) {
373        let mark = self.lexical_log.len();
374        self.walk_stmt_inner(s);
375        if matches!(
376            s.kind,
377            StmtKind::Block(_)
378                | StmtKind::For { .. }
379                | StmtKind::ForOf { .. }
380                | StmtKind::ForIn { .. }
381                | StmtKind::Switch { .. }
382        ) {
383            self.closed.extend(self.lexical_log.drain(mark..));
384        }
385    }
386
387    fn walk_stmt_inner(&mut self, s: &Stmt) {
388        match &s.kind {
389            StmtKind::Decl { kind, decls } => {
390                for d in decls {
391                    // The initializer is evaluated BEFORE the binding exists.
392                    if let Some(init) = &d.init {
393                        self.walk_expr(init);
394                    }
395                    match &d.init {
396                        // `let x;` with no initializer leaves the binding
397                        // unassigned, which is exactly the read-before-write
398                        // case slots cannot answer for.
399                        None => self.reject_names_in(&d.target),
400                        Some(init) => self.declare_target_init(&d.target, Some(*kind), Some(init)),
401                    }
402                }
403            }
404            StmtKind::Expr(e) | StmtKind::Throw(e) => self.walk_expr(e),
405            StmtKind::Return(e) => {
406                if let Some(e) = e {
407                    self.walk_expr(e);
408                }
409            }
410            StmtKind::Block(body) => {
411                for s in body {
412                    self.walk_stmt(s);
413                }
414            }
415            StmtKind::If { test, cons, alt } => {
416                self.walk_expr(test);
417                self.walk_stmt(cons);
418                if let Some(alt) = alt {
419                    self.walk_stmt(alt);
420                }
421            }
422            StmtKind::While { test, body } => {
423                self.walk_expr(test);
424                self.walk_stmt(body);
425            }
426            StmtKind::With { object, body } => {
427                self.walk_expr(object);
428                self.walk_stmt(body);
429            }
430            StmtKind::DoWhile { body, test } => {
431                self.walk_stmt(body);
432                self.walk_expr(test);
433            }
434            StmtKind::For {
435                init,
436                test,
437                update,
438                body,
439            } => {
440                if let Some(init) = init {
441                    self.walk_stmt(init);
442                }
443                if let Some(test) = test {
444                    self.walk_expr(test);
445                }
446                self.walk_stmt(body);
447                if let Some(update) = update {
448                    self.walk_expr(update);
449                }
450            }
451            StmtKind::ForOf {
452                decl_kind,
453                target,
454                iter,
455                body,
456                ..
457            } => {
458                self.walk_expr(iter);
459                self.declare_target(target, *decl_kind);
460                self.walk_stmt(body);
461            }
462            StmtKind::ForIn {
463                decl_kind,
464                target,
465                object,
466                body,
467            } => {
468                self.walk_expr(object);
469                self.declare_target(target, *decl_kind);
470                self.walk_stmt(body);
471            }
472            StmtKind::Switch { disc, cases } => {
473                self.walk_expr(disc);
474                for c in cases {
475                    if let Some(t) = &c.test {
476                        self.walk_expr(t);
477                    }
478                    for s in &c.body {
479                        self.walk_stmt(s);
480                    }
481                }
482            }
483            StmtKind::Labeled { body, .. } => self.walk_stmt(body),
484            // Refused by `chunk_is_eligible` before the walk starts.
485            StmtKind::Try { .. } | StmtKind::FuncDecl { .. } | StmtKind::ClassDecl(_) => {}
486            StmtKind::Break(_) | StmtKind::Continue(_) | StmtKind::Empty => {}
487            StmtKind::Import(_) | StmtKind::Export(_) => {}
488        }
489    }
490
491    fn walk_expr(&mut self, e: &Expr) {
492        match e {
493            Expr::Ident(n) => self.mention(n),
494            // An assignment to a name that has no slot yet is a plain store to
495            // whatever binding exists — a mention, not a declaration.
496            Expr::Assign { target, value, .. } => {
497                self.walk_expr(value);
498                match &**target {
499                    // A plain store of an arbitrary value: whatever the slot
500                    // held, it is not provably a Number after this.
501                    Expr::Ident(n) => {
502                        self.numeric.remove(n);
503                        self.mention(n);
504                    }
505                    other => self.walk_expr(other),
506                }
507            }
508            Expr::Update { target, .. } => self.walk_expr(target),
509            // `delete x` asks the host to remove a binding; a slot has none.
510            Expr::Unary(crate::ast::UnOp::Delete, inner) => {
511                if let Expr::Ident(n) = &**inner {
512                    self.reject(n);
513                } else {
514                    self.walk_expr(inner);
515                }
516            }
517            Expr::Unary(_, inner) | Expr::Spread(inner) | Expr::Await(inner, _) => {
518                self.walk_expr(inner)
519            }
520            Expr::Yield { arg: Some(a), .. } => self.walk_expr(a),
521            Expr::Template { exprs, .. } => self.walk_all(exprs),
522            Expr::TaggedTemplate { tag, exprs, .. } => {
523                self.walk_expr(tag);
524                self.walk_all(exprs);
525            }
526            Expr::Array(items) | Expr::Sequence(items) => self.walk_all(items),
527            Expr::Object(props) => {
528                for p in props {
529                    match p {
530                        Prop::KeyValue { key, value, .. } => {
531                            self.walk_expr(key);
532                            self.walk_expr(value);
533                        }
534                        Prop::Spread(x) => self.walk_expr(x),
535                        Prop::Accessor { key, func, .. } => {
536                            self.walk_expr(key);
537                            self.walk_expr(func);
538                        }
539                    }
540                }
541            }
542            Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => {
543                self.walk_expr(l);
544                self.walk_expr(r);
545            }
546            Expr::Conditional { test, cons, alt } => {
547                self.walk_expr(test);
548                self.walk_expr(cons);
549                self.walk_expr(alt);
550            }
551            Expr::Call { func, args, .. }
552            | Expr::New {
553                callee: func, args, ..
554            } => {
555                self.walk_expr(func);
556                self.walk_all(args);
557            }
558            Expr::Member { object, .. } => self.walk_expr(object),
559            Expr::Index { object, index, .. } => {
560                self.walk_expr(object);
561                self.walk_expr(index);
562            }
563            // A nested function or class body is refused by `chunk_is_eligible`,
564            // so anything it names is already out of reach here.
565            Expr::Function { .. } | Expr::Class(_) => {}
566            _ => {}
567        }
568    }
569
570    fn walk_all(&mut self, items: &[Expr]) {
571        for e in items {
572            self.walk_expr(e);
573        }
574    }
575}
576
577// ── names another chunk can reach ────────────────────────────────────────────
578//
579// A nested function, arrow, class body or `try` part compiles to a chunk of its
580// own and resolves every name it uses through the environment chain. Whatever
581// those chunks mention therefore has to stay a real binding — and only that,
582// which is what lets a counting loop keep its slots in a file that also passes
583// a callback to `map`.
584
585fn collect_escaping_stmt(s: &Stmt, out: &mut FxHashSet<String>) {
586    match &s.kind {
587        // The declaration's own name is bound by the hoisting pass, by name.
588        StmtKind::FuncDecl { name, .. } => {
589            out.insert(name.clone());
590            collect_all_idents_stmt(s, out);
591        }
592        StmtKind::ClassDecl(c) => {
593            if let Some(n) = &c.name {
594                out.insert(n.clone());
595            }
596            collect_all_idents_stmt(s, out);
597        }
598        StmtKind::Try {
599            block,
600            handler,
601            finalizer,
602        } => {
603            for st in block {
604                collect_all_idents_stmt(st, out);
605            }
606            if let Some((bind, body)) = handler {
607                if let Some(p) = bind {
608                    collect_all_idents_expr(p, out);
609                }
610                for st in body {
611                    collect_all_idents_stmt(st, out);
612                }
613            }
614            if let Some(body) = finalizer {
615                for st in body {
616                    collect_all_idents_stmt(st, out);
617                }
618            }
619        }
620        StmtKind::Expr(e) | StmtKind::Throw(e) => collect_escaping_expr(e, out),
621        StmtKind::Return(e) => {
622            if let Some(e) = e {
623                collect_escaping_expr(e, out);
624            }
625        }
626        StmtKind::Decl { decls, .. } => {
627            for d in decls {
628                if let Some(init) = &d.init {
629                    collect_escaping_expr(init, out);
630                }
631            }
632        }
633        StmtKind::Block(body) => {
634            for st in body {
635                collect_escaping_stmt(st, out);
636            }
637        }
638        StmtKind::If { test, cons, alt } => {
639            collect_escaping_expr(test, out);
640            collect_escaping_stmt(cons, out);
641            if let Some(alt) = alt {
642                collect_escaping_stmt(alt, out);
643            }
644        }
645        StmtKind::While { test, body } | StmtKind::DoWhile { body, test } => {
646            collect_escaping_expr(test, out);
647            collect_escaping_stmt(body, out);
648        }
649        StmtKind::With { object, body } => {
650            collect_escaping_expr(object, out);
651            collect_escaping_stmt(body, out);
652        }
653        StmtKind::For {
654            init,
655            test,
656            update,
657            body,
658        } => {
659            if let Some(init) = init {
660                collect_escaping_stmt(init, out);
661            }
662            if let Some(test) = test {
663                collect_escaping_expr(test, out);
664            }
665            if let Some(update) = update {
666                collect_escaping_expr(update, out);
667            }
668            collect_escaping_stmt(body, out);
669        }
670        StmtKind::ForOf {
671            target, iter, body, ..
672        } => {
673            collect_escaping_expr(target, out);
674            collect_escaping_expr(iter, out);
675            collect_escaping_stmt(body, out);
676        }
677        StmtKind::ForIn {
678            target,
679            object,
680            body,
681            ..
682        } => {
683            collect_escaping_expr(target, out);
684            collect_escaping_expr(object, out);
685            collect_escaping_stmt(body, out);
686        }
687        StmtKind::Switch { disc, cases } => {
688            collect_escaping_expr(disc, out);
689            for c in cases {
690                if let Some(t) = &c.test {
691                    collect_escaping_expr(t, out);
692                }
693                for st in &c.body {
694                    collect_escaping_stmt(st, out);
695                }
696            }
697        }
698        StmtKind::Labeled { body, .. } => collect_escaping_stmt(body, out),
699        StmtKind::Break(_) | StmtKind::Continue(_) | StmtKind::Empty => {}
700        StmtKind::Import(_) | StmtKind::Export(_) => {}
701    }
702}
703
704fn collect_escaping_expr(e: &Expr, out: &mut FxHashSet<String>) {
705    match e {
706        // Here is the boundary: everything named inside a nested function or
707        // class body is resolved from the environment when that chunk runs.
708        Expr::Function { .. } | Expr::Class(_) => collect_all_idents_expr(e, out),
709        Expr::Ident(_) | Expr::Null | Expr::Undefined | Expr::True | Expr::False => {}
710        Expr::Unary(_, x)
711        | Expr::Spread(x)
712        | Expr::Await(x, _)
713        | Expr::Member { object: x, .. } => collect_escaping_expr(x, out),
714        Expr::Yield { arg: Some(a), .. } => collect_escaping_expr(a, out),
715        Expr::Template { exprs, .. } => exprs.iter().for_each(|x| collect_escaping_expr(x, out)),
716        Expr::TaggedTemplate { tag, exprs, .. } => {
717            collect_escaping_expr(tag, out);
718            exprs.iter().for_each(|x| collect_escaping_expr(x, out));
719        }
720        Expr::Array(items) | Expr::Sequence(items) => {
721            items.iter().for_each(|x| collect_escaping_expr(x, out))
722        }
723        Expr::Object(props) => {
724            for p in props {
725                match p {
726                    Prop::KeyValue { key, value, .. } => {
727                        collect_escaping_expr(key, out);
728                        collect_escaping_expr(value, out);
729                    }
730                    Prop::Spread(x) => collect_escaping_expr(x, out),
731                    Prop::Accessor { key, func, .. } => {
732                        collect_escaping_expr(key, out);
733                        collect_all_idents_expr(func, out);
734                    }
735                }
736            }
737        }
738        Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => {
739            collect_escaping_expr(l, out);
740            collect_escaping_expr(r, out);
741        }
742        Expr::Conditional { test, cons, alt } => {
743            collect_escaping_expr(test, out);
744            collect_escaping_expr(cons, out);
745            collect_escaping_expr(alt, out);
746        }
747        Expr::Assign { target, value, .. } => {
748            collect_escaping_expr(target, out);
749            collect_escaping_expr(value, out);
750        }
751        Expr::Update { target, .. } => collect_escaping_expr(target, out),
752        Expr::Call { func, args, .. }
753        | Expr::New {
754            callee: func, args, ..
755        } => {
756            collect_escaping_expr(func, out);
757            args.iter().for_each(|x| collect_escaping_expr(x, out));
758        }
759        Expr::Index { object, index, .. } => {
760            collect_escaping_expr(object, out);
761            collect_escaping_expr(index, out);
762        }
763        _ => {}
764    }
765}
766
767/// Every identifier anywhere in a statement, nested bodies included.
768fn collect_all_idents_stmt(s: &Stmt, out: &mut FxHashSet<String>) {
769    match &s.kind {
770        StmtKind::FuncDecl { params, body, .. } => {
771            for p in params {
772                collect_all_idents_expr(&p.pattern, out);
773                if let Some(d) = &p.default {
774                    collect_all_idents_expr(d, out);
775                }
776            }
777            body.iter().for_each(|st| collect_all_idents_stmt(st, out));
778        }
779        StmtKind::ClassDecl(c) => collect_class_idents(c, out),
780        StmtKind::Expr(e) | StmtKind::Throw(e) => collect_all_idents_expr(e, out),
781        StmtKind::Return(e) => {
782            if let Some(e) = e {
783                collect_all_idents_expr(e, out);
784            }
785        }
786        StmtKind::Decl { decls, .. } => {
787            for d in decls {
788                collect_all_idents_expr(&d.target, out);
789                if let Some(init) = &d.init {
790                    collect_all_idents_expr(init, out);
791                }
792            }
793        }
794        StmtKind::Block(body) => body.iter().for_each(|st| collect_all_idents_stmt(st, out)),
795        StmtKind::If { test, cons, alt } => {
796            collect_all_idents_expr(test, out);
797            collect_all_idents_stmt(cons, out);
798            if let Some(alt) = alt {
799                collect_all_idents_stmt(alt, out);
800            }
801        }
802        StmtKind::While { test, body } | StmtKind::DoWhile { body, test } => {
803            collect_all_idents_expr(test, out);
804            collect_all_idents_stmt(body, out);
805        }
806        StmtKind::With { object, body } => {
807            collect_all_idents_expr(object, out);
808            collect_all_idents_stmt(body, out);
809        }
810        StmtKind::For {
811            init,
812            test,
813            update,
814            body,
815        } => {
816            if let Some(init) = init {
817                collect_all_idents_stmt(init, out);
818            }
819            if let Some(test) = test {
820                collect_all_idents_expr(test, out);
821            }
822            if let Some(update) = update {
823                collect_all_idents_expr(update, out);
824            }
825            collect_all_idents_stmt(body, out);
826        }
827        StmtKind::ForOf {
828            target, iter, body, ..
829        } => {
830            collect_all_idents_expr(target, out);
831            collect_all_idents_expr(iter, out);
832            collect_all_idents_stmt(body, out);
833        }
834        StmtKind::ForIn {
835            target,
836            object,
837            body,
838            ..
839        } => {
840            collect_all_idents_expr(target, out);
841            collect_all_idents_expr(object, out);
842            collect_all_idents_stmt(body, out);
843        }
844        StmtKind::Switch { disc, cases } => {
845            collect_all_idents_expr(disc, out);
846            for c in cases {
847                if let Some(t) = &c.test {
848                    collect_all_idents_expr(t, out);
849                }
850                c.body
851                    .iter()
852                    .for_each(|st| collect_all_idents_stmt(st, out));
853            }
854        }
855        StmtKind::Labeled { body, .. } => collect_all_idents_stmt(body, out),
856        StmtKind::Try {
857            block,
858            handler,
859            finalizer,
860        } => {
861            block.iter().for_each(|st| collect_all_idents_stmt(st, out));
862            if let Some((bind, body)) = handler {
863                if let Some(p) = bind {
864                    collect_all_idents_expr(p, out);
865                }
866                body.iter().for_each(|st| collect_all_idents_stmt(st, out));
867            }
868            if let Some(body) = finalizer {
869                body.iter().for_each(|st| collect_all_idents_stmt(st, out));
870            }
871        }
872        StmtKind::Break(_) | StmtKind::Continue(_) | StmtKind::Empty => {}
873        StmtKind::Import(_) | StmtKind::Export(_) => {}
874    }
875}
876
877fn collect_class_idents(c: &crate::ast::ClassNode, out: &mut FxHashSet<String>) {
878    if let Some(p) = &c.parent {
879        collect_all_idents_expr(p, out);
880    }
881    for m in &c.members {
882        collect_all_idents_expr(&m.key, out);
883        for p in &m.params {
884            collect_all_idents_expr(&p.pattern, out);
885            if let Some(d) = &p.default {
886                collect_all_idents_expr(d, out);
887            }
888        }
889        m.body
890            .iter()
891            .for_each(|st| collect_all_idents_stmt(st, out));
892        if let Some(init) = &m.field_init {
893            collect_all_idents_expr(init, out);
894        }
895    }
896}
897
898fn collect_all_idents_expr(e: &Expr, out: &mut FxHashSet<String>) {
899    let all = |xs: &[Expr], out: &mut FxHashSet<String>| {
900        xs.iter().for_each(|x| collect_all_idents_expr(x, out))
901    };
902    match e {
903        Expr::Ident(n) => {
904            out.insert(n.clone());
905        }
906        Expr::Class(c) => collect_class_idents(c, out),
907        Expr::Function { params, body, .. } => {
908            for p in params {
909                collect_all_idents_expr(&p.pattern, out);
910                if let Some(d) = &p.default {
911                    collect_all_idents_expr(d, out);
912                }
913            }
914            match body {
915                crate::ast::FnBody::Block(stmts) => {
916                    stmts.iter().for_each(|st| collect_all_idents_stmt(st, out))
917                }
918                crate::ast::FnBody::Expr(x) => collect_all_idents_expr(x, out),
919            }
920        }
921        Expr::Unary(_, x)
922        | Expr::Spread(x)
923        | Expr::Await(x, _)
924        | Expr::Member { object: x, .. } => collect_all_idents_expr(x, out),
925        Expr::Yield { arg: Some(a), .. } => collect_all_idents_expr(a, out),
926        Expr::Template { exprs, .. } => all(exprs, out),
927        Expr::TaggedTemplate { tag, exprs, .. } => {
928            collect_all_idents_expr(tag, out);
929            all(exprs, out);
930        }
931        Expr::Array(items) | Expr::Sequence(items) => all(items, out),
932        Expr::Object(props) => {
933            for p in props {
934                match p {
935                    Prop::KeyValue { key, value, .. } => {
936                        collect_all_idents_expr(key, out);
937                        collect_all_idents_expr(value, out);
938                    }
939                    Prop::Spread(x) => collect_all_idents_expr(x, out),
940                    Prop::Accessor { key, func, .. } => {
941                        collect_all_idents_expr(key, out);
942                        collect_all_idents_expr(func, out);
943                    }
944                }
945            }
946        }
947        Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => {
948            collect_all_idents_expr(l, out);
949            collect_all_idents_expr(r, out);
950        }
951        Expr::Conditional { test, cons, alt } => {
952            collect_all_idents_expr(test, out);
953            collect_all_idents_expr(cons, out);
954            collect_all_idents_expr(alt, out);
955        }
956        Expr::Assign { target, value, .. } => {
957            collect_all_idents_expr(target, out);
958            collect_all_idents_expr(value, out);
959        }
960        Expr::Update { target, .. } => collect_all_idents_expr(target, out),
961        Expr::Call { func, args, .. }
962        | Expr::New {
963            callee: func, args, ..
964        } => {
965            collect_all_idents_expr(func, out);
966            all(args, out);
967        }
968        Expr::Index { object, index, .. } => {
969            collect_all_idents_expr(object, out);
970            collect_all_idents_expr(index, out);
971        }
972        _ => {}
973    }
974}
975
976/// Every identifier appearing in a (possibly destructuring) target expression.
977fn collect_idents(e: &Expr, out: &mut Vec<String>) {
978    match e {
979        Expr::Ident(n) => out.push(n.clone()),
980        Expr::Array(items) | Expr::Sequence(items) => {
981            for x in items {
982                collect_idents(x, out);
983            }
984        }
985        Expr::Object(props) => {
986            for p in props {
987                match p {
988                    Prop::KeyValue { value, .. } => collect_idents(value, out),
989                    Prop::Spread(x) => collect_idents(x, out),
990                    Prop::Accessor { .. } => {}
991                }
992            }
993        }
994        Expr::Spread(inner) => collect_idents(inner, out),
995        Expr::Assign { target, .. } => collect_idents(target, out),
996        _ => {}
997    }
998}
999
1000/// Whether `body` can observe the `arguments` object: it names `arguments`
1001/// anywhere (a nested arrow shares it) or calls a direct `eval`, which can.
1002/// Conservative — a nested ordinary function naming its own `arguments` counts
1003/// — because a false positive only costs the slots and an alias, never an
1004/// answer.
1005pub fn mentions_arguments(body: &[Stmt]) -> bool {
1006    let mut names = FxHashSet::default();
1007    for s in body {
1008        collect_all_idents_stmt(s, &mut names);
1009    }
1010    names.contains("arguments") || names.contains("eval")
1011}