Skip to main content

nodejs/
capture.rs

1//! Does a piece of a program hold on to the scope it runs in?
2//!
3//! Two lowerings in `compiler.rs` exist only to serve code that captures an
4//! environment, and both cost a heap allocation every time control passes them:
5//!
6//! * a `for (let i = …)` head is re-bound per iteration (ForBodyEvaluation's
7//!   CreatePerIterationEnvironment), so a closure made in one pass keeps that
8//!   pass's value — `COPY_SCOPE` clones the whole scope on every iteration;
9//! * a `{ … }` block opens a scope for its lexical declarations.
10//!
11//! When nothing in the subtree can make a closure, the per-iteration copy is
12//! unobservable: no one can ever hold a reference to the iteration's bindings,
13//! so one binding mutated in place gives the same answers. A profile of
14//! `for (let i = 0; i < 5_000_000; i++) s += i % 7;` spent 17% of its samples in
15//! `copy_scope` and the `EnvData` allocate/free traffic under it, for copies
16//! that nothing could observe.
17//!
18//! This module answers the question conservatively: it says "captures" for
19//! anything that makes a function, a class (its methods are functions), or a
20//! direct `eval` (which can both make closures and declare into the caller's
21//! scope). Every match here is exhaustive — a new AST node has to be classified
22//! deliberately rather than defaulting into the fast path.
23
24use crate::ast::{Expr, Prop, Stmt, StmtKind, SwitchCase};
25
26/// True if evaluating `s` can create something that outlives it holding the
27/// current scope.
28pub fn stmt_captures(s: &Stmt) -> bool {
29    match &s.kind {
30        // A function or class body is exactly the thing that captures.
31        StmtKind::FuncDecl { .. } | StmtKind::ClassDecl(_) => true,
32
33        StmtKind::Expr(e) | StmtKind::Throw(e) => expr_captures(e),
34        StmtKind::Return(e) => e.as_ref().is_some_and(expr_captures),
35        StmtKind::Decl { decls, .. } => decls
36            .iter()
37            .any(|d| expr_captures(&d.target) || d.init.as_ref().is_some_and(expr_captures)),
38        StmtKind::Block(body) => body.iter().any(stmt_captures),
39        StmtKind::If { test, cons, alt } => {
40            expr_captures(test) || stmt_captures(cons) || alt.as_deref().is_some_and(stmt_captures)
41        }
42        StmtKind::While { test, body } | StmtKind::DoWhile { body, test } => {
43            expr_captures(test) || stmt_captures(body)
44        }
45        StmtKind::With { object, body } => expr_captures(object) || stmt_captures(body),
46        StmtKind::For {
47            init,
48            test,
49            update,
50            body,
51        } => {
52            init.as_deref().is_some_and(stmt_captures)
53                || test.as_ref().is_some_and(expr_captures)
54                || update.as_ref().is_some_and(expr_captures)
55                || stmt_captures(body)
56        }
57        StmtKind::ForOf {
58            target, iter, body, ..
59        } => expr_captures(target) || expr_captures(iter) || stmt_captures(body),
60        StmtKind::ForIn {
61            target,
62            object,
63            body,
64            ..
65        } => expr_captures(target) || expr_captures(object) || stmt_captures(body),
66        StmtKind::Switch { disc, cases } => expr_captures(disc) || cases.iter().any(case_captures),
67        StmtKind::Labeled { body, .. } => stmt_captures(body),
68        StmtKind::Try {
69            block,
70            handler,
71            finalizer,
72        } => {
73            block.iter().any(stmt_captures)
74                || handler.as_ref().is_some_and(|(param, body)| {
75                    param.as_ref().is_some_and(expr_captures) || body.iter().any(stmt_captures)
76                })
77                || finalizer
78                    .as_ref()
79                    .is_some_and(|body| body.iter().any(stmt_captures))
80        }
81        StmtKind::Break(_) | StmtKind::Continue(_) | StmtKind::Empty => false,
82        // Module declarations never reach a compiled body: `esm::lower` replaces
83        // them before compilation. Classified as capturing, the safe answer.
84        StmtKind::Import(_) | StmtKind::Export(_) => true,
85    }
86}
87
88fn case_captures(c: &SwitchCase) -> bool {
89    c.test.as_ref().is_some_and(expr_captures) || c.body.iter().any(stmt_captures)
90}
91
92/// True if evaluating `e` can create something that outlives it holding the
93/// current scope.
94pub fn expr_captures(e: &Expr) -> bool {
95    match e {
96        // The three that capture.
97        Expr::Function { .. } | Expr::Class(_) => true,
98        // Direct `eval` sees — and can close over, or declare into — the scope
99        // it is called from, so a scope it can reach must stay a real scope.
100        // Any other use of the name (`const f = eval;`) is caught here too:
101        // the check is on the identifier, not on the call shape.
102        Expr::Ident(n) => n == "eval",
103
104        Expr::Null
105        | Expr::Undefined
106        | Expr::Hole
107        | Expr::True
108        | Expr::False
109        | Expr::Number(_)
110        | Expr::BigInt(_)
111        | Expr::Regex(_, _)
112        | Expr::Str(_)
113        | Expr::This
114        | Expr::Super
115        | Expr::NewTarget => false,
116
117        Expr::Template { exprs, .. } => exprs.iter().any(expr_captures),
118        Expr::TaggedTemplate { tag, exprs, .. } => {
119            expr_captures(tag) || exprs.iter().any(expr_captures)
120        }
121        Expr::Yield { arg, .. } => arg.as_deref().is_some_and(expr_captures),
122        Expr::Await(inner, _) | Expr::Spread(inner) | Expr::Unary(_, inner) => expr_captures(inner),
123        Expr::Array(items) | Expr::Sequence(items) => items.iter().any(expr_captures),
124        Expr::Object(props) => props.iter().any(prop_captures),
125        Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => expr_captures(l) || expr_captures(r),
126        Expr::Conditional { test, cons, alt } => {
127            expr_captures(test) || expr_captures(cons) || expr_captures(alt)
128        }
129        Expr::Assign { target, value, .. } => expr_captures(target) || expr_captures(value),
130        Expr::Update { target, .. } => expr_captures(target),
131        Expr::Call { func, args, .. }
132        | Expr::New {
133            callee: func, args, ..
134        } => expr_captures(func) || args.iter().any(expr_captures),
135        Expr::Member { object, .. } => expr_captures(object),
136        Expr::Index { object, index, .. } => expr_captures(object) || expr_captures(index),
137    }
138}
139
140fn prop_captures(p: &Prop) -> bool {
141    match p {
142        Prop::KeyValue { key, value, .. } => expr_captures(key) || expr_captures(value),
143        Prop::Spread(e) => expr_captures(e),
144        // An accessor's `func` is an `Expr::Function`, so this arm is `true`;
145        // it is spelled out rather than assumed.
146        Prop::Accessor { key, func, .. } => expr_captures(key) || expr_captures(func),
147    }
148}
149
150/// Does this statement list declare anything that needs a block scope of its
151/// own? `let` / `const` / `class` / a hoisted `function` bind into the block;
152/// `var` does not (it lands in the enclosing function's base env). A block that
153/// binds nothing needs no scope at all, so `{ …; }` inside a hot loop stops
154/// allocating and freeing an `EnvData` per pass.
155///
156/// Direct `eval` forces a scope: `eval("let x = 1")` declares into the running
157/// block, and with no block open that binding would escape to the function.
158pub fn block_needs_scope(body: &[Stmt]) -> bool {
159    body.iter().any(|s| match &s.kind {
160        StmtKind::Decl { kind, .. } => !matches!(kind, crate::ast::DeclKind::Var),
161        StmtKind::FuncDecl { .. } | StmtKind::ClassDecl(_) => true,
162        // Only a DIRECT `eval` in this block's own statements can declare into
163        // it; a nested block or function has its own scope to declare into.
164        StmtKind::Expr(e) => mentions_eval(e),
165        _ => false,
166    })
167}
168
169/// `eval` named anywhere in this expression (see [`block_needs_scope`]).
170fn mentions_eval(e: &Expr) -> bool {
171    match e {
172        Expr::Ident(n) => n == "eval",
173        Expr::Call { func, args, .. }
174        | Expr::New {
175            callee: func, args, ..
176        } => mentions_eval(func) || args.iter().any(mentions_eval),
177        Expr::Assign { target, value, .. } => mentions_eval(target) || mentions_eval(value),
178        Expr::Sequence(items) => items.iter().any(mentions_eval),
179        Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => mentions_eval(l) || mentions_eval(r),
180        Expr::Conditional { test, cons, alt } => {
181            mentions_eval(test) || mentions_eval(cons) || mentions_eval(alt)
182        }
183        Expr::Unary(_, inner) | Expr::Await(inner, _) | Expr::Spread(inner) => mentions_eval(inner),
184        _ => false,
185    }
186}