Skip to main content

parsec_js/
scope.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Scopes and bindings: which declaration each name in a program refers
5//! to, worked out from the tree alone.
6//!
7//! [`Scopes::analyze`] walks an [`Ast`] once and builds the scopes the
8//! spec's environments would be, from the global or module scope down
9//! through functions, blocks, classes, `catch` clauses, class static
10//! blocks and the implicit function around each class field's
11//! initializer. Each declaration becomes a [`Binding`] in the scope it
12//! lives in: `var` and function declarations hoisted to their function,
13//! with Annex B's function-in-block semantics in sloppy code; `let`,
14//! `const` and `class` in their block. Each IdentifierReference becomes a
15//! [`Reference`], resolved to its binding or left free.
16//!
17//! Nothing runs, so two things the analysis can't see are marked rather
18//! than guessed: a scope that holds a direct `eval` call, or any scope
19//! around one, is [`Scope::dynamic`], since the eval'd code can read and
20//! add names there; and the body of a `with` gets a [`ScopeKind::With`]
21//! scope, dynamic too, since any name in it may be a property of the
22//! object.
23//!
24//! The names declared twice where the spec forbids it come back as
25//! [`Scopes::diagnostics`], with codes `duplicate-declaration` and
26//! `lexical-var-conflict`.
27//!
28//! ```
29//! use parsec_js::scope::{BindingKind, Scopes};
30//! use parsec_js::parse_script;
31//!
32//! let src = "let total = 0; for (const x of items) total += x; console.log(total);";
33//! let ast = parse_script(src).unwrap();
34//! let scopes = Scopes::analyze(&ast, src);
35//! assert_eq!(scopes.free_names(), ["items", "console"]);
36//! let total = scopes.references().iter().find(|r| r.name(&ast, src) == "total").unwrap();
37//! let binding = scopes.binding(total.binding.unwrap());
38//! assert_eq!(binding.kind, BindingKind::Let);
39//! assert!(scopes.diagnostics().is_empty());
40//! ```
41//!
42//! The walk keeps its own stack, so a tree of any depth is analyzed
43//! without touching the thread's.
44
45use std::borrow::Cow;
46use std::collections::{HashMap, HashSet};
47
48use parsec_base::Diagnostic;
49
50use crate::SourceType;
51use crate::ast::{AssignOp, Ast, Class, Function, FunctionKind, List, Node, NodeId, VarKind};
52use crate::text;
53
54/// A scope in [`Scopes`].
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
56pub struct ScopeId(u32);
57
58impl ScopeId {
59    pub const fn index(self) -> usize {
60        self.0 as usize
61    }
62}
63
64/// A binding in [`Scopes`].
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
66pub struct BindingId(u32);
67
68impl BindingId {
69    pub const fn index(self) -> usize {
70        self.0 as usize
71    }
72}
73
74/// What made a scope.
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
76pub enum ScopeKind {
77    /// A script's top level.
78    Global,
79    /// A module's top level.
80    Module,
81    /// A function, arrow or method: its parameters, and its body's
82    /// declarations too unless it has a [`ScopeKind::FunctionBody`].
83    Function,
84    /// A function's body, apart from its parameters, when a parameter has
85    /// a default or a computed key: what the body declares can't be seen
86    /// from the parameters, as the spec's separate environment has it.
87    FunctionBody,
88    /// A block, a `switch`'s cases, a `for` with `let` or `const` in its
89    /// head, or the block Annex B puts around `if (a) function f() {}`.
90    Block,
91    /// A `catch` clause: its parameter and its block's declarations.
92    Catch,
93    /// The body of a `with`, where any name may be the object's.
94    With,
95    /// A class: its own name, its heritage and its computed keys.
96    Class,
97    /// The implicit function a class field's initializer runs in.
98    ClassField,
99    /// A class `static { }` block.
100    StaticBlock,
101}
102
103impl ScopeKind {
104    /// Where `var` declarations land.
105    const fn holds_vars(self) -> bool {
106        matches!(
107            self,
108            ScopeKind::Global
109                | ScopeKind::Module
110                | ScopeKind::Function
111                | ScopeKind::FunctionBody
112                | ScopeKind::StaticBlock
113        )
114    }
115
116    /// Code in it runs later than the code around it, if at all, so
117    /// coming first in the source doesn't put a reference in the TDZ.
118    const fn defers(self) -> bool {
119        matches!(
120            self,
121            ScopeKind::Function | ScopeKind::ClassField | ScopeKind::StaticBlock
122        )
123    }
124}
125
126/// What declared a binding.
127#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
128pub enum BindingKind {
129    Var,
130    Let,
131    Const,
132    /// A function declaration, or in sloppy code, the `var` binding Annex
133    /// B gives a function declared in a block.
134    Function,
135    /// A class declaration's name in the scope around it.
136    Class,
137    Param,
138    CatchParam,
139    Import,
140    /// A function expression's own name, inside it.
141    FunctionName,
142    /// A class's own name, inside it.
143    ClassName,
144    /// The `arguments` object of a function that isn't an arrow, made
145    /// only when something refers to it.
146    Arguments,
147}
148
149/// How a reference uses its name.
150#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
151pub enum Access {
152    Read,
153    Write,
154    /// `x += 1`, `x++`, `x ||= y`.
155    ReadWrite,
156}
157
158/// A scope: what made it, the scope around it, and its bindings.
159#[derive(Clone, Debug)]
160pub struct Scope {
161    pub kind: ScopeKind,
162    pub parent: Option<ScopeId>,
163    /// The node that makes it: the program, a function, a block, a
164    /// `switch`, a `for`, a `catch` clause, a `with`, a class, a
165    /// field, a static block. For the block Annex B puts around
166    /// `if (a) function f() {}`, the function.
167    pub node: NodeId,
168    pub strict: bool,
169    /// A direct `eval` in it or in a scope inside it, or it's a `with`'s
170    /// body: code the analysis can't see may read or declare names here.
171    pub dynamic: bool,
172    arrow: bool,
173    bindings: Vec<BindingId>,
174    names: HashMap<Box<str>, BindingId>,
175}
176
177impl Scope {
178    /// Its bindings, in the order they were declared.
179    pub fn bindings(&self) -> &[BindingId] {
180        &self.bindings
181    }
182}
183
184/// A name declared in a scope.
185#[derive(Clone, Debug)]
186pub struct Binding {
187    pub name: String,
188    pub kind: BindingKind,
189    pub scope: ScopeId,
190    /// The identifier that declares it first; `None` for `arguments`.
191    pub node: Option<NodeId>,
192    /// `let`, `const`, `class`, an import, a catch parameter, or a
193    /// function declared in a block or at a module's top level: the
194    /// names that can't be declared twice.
195    lexical: bool,
196    /// A plain function declaration, not a generator or async: sloppy
197    /// code may declare one twice in a block.
198    plain: bool,
199    /// Where it's initialized: a reference before this, outside a nested
200    /// function, is in its temporal dead zone. 0 for a binding that has
201    /// none.
202    tdz_end: u32,
203}
204
205/// An IdentifierReference, and what it resolved to.
206#[derive(Clone, Copy, Debug, PartialEq, Eq)]
207pub struct Reference {
208    /// The [`Node::Identifier`].
209    pub node: NodeId,
210    /// The scope it's in.
211    pub scope: ScopeId,
212    /// `None` for a free name: a global, or a name nothing declares.
213    pub binding: Option<BindingId>,
214    pub access: Access,
215    /// It refers to a `let`, `const` or `class` binding from before the
216    /// declaration, in the same function: running it would throw.
217    pub tdz: bool,
218}
219
220impl Reference {
221    /// The name it refers to, escapes decoded.
222    pub fn name<'a>(&self, ast: &Ast, src: &'a str) -> Cow<'a, str> {
223        text::ident_name(ast.span(self.node).text(src))
224    }
225}
226
227/// Every scope, binding and reference in a program. See the
228/// [module docs](self).
229#[derive(Clone, Debug)]
230pub struct Scopes {
231    scopes: Vec<Scope>,
232    bindings: Vec<Binding>,
233    references: Vec<Reference>,
234    /// For each node, a reference (`REF | index`) or a declaring
235    /// identifier (a binding's index), or `NONE`.
236    by_node: Vec<u32>,
237    scope_by_node: HashMap<NodeId, ScopeId>,
238    free: Vec<String>,
239    diagnostics: Vec<Diagnostic>,
240}
241
242const NONE: u32 = u32::MAX;
243const REF: u32 = 1 << 31;
244
245impl Scopes {
246    /// Analyzes `ast`, parsed from `src`.
247    pub fn analyze(ast: &Ast, src: &str) -> Scopes {
248        let mut b = Builder {
249            ast,
250            src,
251            s: Scopes {
252                scopes: Vec::new(),
253                bindings: Vec::new(),
254                references: Vec::new(),
255                by_node: vec![NONE; ast.len() + 1],
256                scope_by_node: HashMap::new(),
257                free: Vec::new(),
258                diagnostics: Vec::new(),
259            },
260            cur: ScopeId(0),
261            stack: Vec::new(),
262            buf: Vec::new(),
263            hoisted: HashSet::new(),
264            annex_b: Vec::new(),
265        };
266        b.run();
267        b.s
268    }
269
270    /// The global or module scope.
271    pub fn root(&self) -> ScopeId {
272        ScopeId(0)
273    }
274
275    pub fn scope(&self, id: ScopeId) -> &Scope {
276        &self.scopes[id.index()]
277    }
278
279    /// Every scope, each after the scopes around it.
280    pub fn scopes(&self) -> &[Scope] {
281        &self.scopes
282    }
283
284    pub fn binding(&self, id: BindingId) -> &Binding {
285        &self.bindings[id.index()]
286    }
287
288    pub fn bindings(&self) -> &[Binding] {
289        &self.bindings
290    }
291
292    /// Every reference, in source order.
293    pub fn references(&self) -> &[Reference] {
294        &self.references
295    }
296
297    /// The scope `node` makes, if it makes one.
298    pub fn scope_of(&self, node: NodeId) -> Option<ScopeId> {
299        self.scope_by_node.get(&node).copied()
300    }
301
302    /// The reference `node` is, if it's an IdentifierReference.
303    pub fn reference(&self, node: NodeId) -> Option<&Reference> {
304        match self.by_node.get(node.index()) {
305            Some(&i) if i != NONE && i & REF != 0 => Some(&self.references[(i & !REF) as usize]),
306            _ => None,
307        }
308    }
309
310    /// The binding `node` declares, if it's a binding identifier.
311    pub fn declaration(&self, node: NodeId) -> Option<BindingId> {
312        match self.by_node.get(node.index()) {
313            Some(&i) if i != NONE && i & REF == 0 => Some(BindingId(i)),
314            _ => None,
315        }
316    }
317
318    /// The binding a reference to `name` in `scope` would resolve to.
319    pub fn lookup(&self, mut scope: ScopeId, name: &str) -> Option<BindingId> {
320        loop {
321            let s = self.scope(scope);
322            if let Some(&b) = s.names.get(name) {
323                return Some(b);
324            }
325            scope = s.parent?;
326        }
327    }
328
329    /// The names references use that nothing in the program declares,
330    /// each once, in the order they first appear.
331    pub fn free_names(&self) -> &[String] {
332        &self.free
333    }
334
335    /// Names declared twice, or both lexically and with `var`, where the
336    /// spec makes that an early error.
337    pub fn diagnostics(&self) -> &[Diagnostic] {
338        &self.diagnostics
339    }
340}
341
342/// How a binding pattern's names are declared.
343#[derive(Clone, Copy)]
344struct Decl {
345    kind: BindingKind,
346    tdz_end: u32,
347}
348
349enum Task {
350    Stmt(NodeId),
351    Expr(NodeId),
352    Target(NodeId, Access),
353    Bind(NodeId, Decl),
354    /// Carry on in this scope.
355    Scope(ScopeId),
356}
357
358struct Builder<'a> {
359    ast: &'a Ast,
360    src: &'a str,
361    s: Scopes,
362    cur: ScopeId,
363    stack: Vec<Task>,
364    /// The current node's children, in source order, before they go on
365    /// the stack reversed.
366    buf: Vec<Task>,
367    /// Names a `var` declares in a scope inside each of these, which a
368    /// lexical declaration there would conflict with.
369    hoisted: HashSet<(ScopeId, Box<str>)>,
370    /// Sloppy functions declared in blocks: the block's scope and the
371    /// binding there.
372    annex_b: Vec<(ScopeId, BindingId)>,
373}
374
375impl<'a> Builder<'a> {
376    fn run(&mut self) {
377        let root = self.ast.root();
378        let Node::Program { body, source_type } = *self.ast.node(root) else {
379            unreachable!("the root is a program")
380        };
381        let module = source_type == SourceType::Module;
382        let kind = if module {
383            ScopeKind::Module
384        } else {
385            ScopeKind::Global
386        };
387        let strict = module || self.use_strict(body);
388        self.cur = self.new_scope(kind, root, strict, None);
389        self.push_list(body, Task::Stmt);
390        self.flush();
391        while let Some(task) = self.stack.pop() {
392            match task {
393                Task::Stmt(id) => self.stmt(id),
394                Task::Expr(id) => self.expr(id),
395                Task::Target(id, access) => self.target(id, access),
396                Task::Bind(id, decl) => self.bind(id, decl),
397                Task::Scope(s) => self.cur = s,
398            }
399            self.flush();
400        }
401        self.annex_b();
402        self.resolve();
403    }
404
405    // The walk.
406
407    fn flush(&mut self) {
408        self.stack.extend(self.buf.drain(..).rev());
409    }
410
411    fn push(&mut self, task: Task) {
412        self.buf.push(task);
413    }
414
415    fn push_opt(&mut self, id: Option<NodeId>, f: fn(NodeId) -> Task) {
416        if let Some(id) = id {
417            self.buf.push(f(id));
418        }
419    }
420
421    fn push_list(&mut self, list: List, f: fn(NodeId) -> Task) {
422        for &id in self.ast.get(list) {
423            self.buf.push(f(id));
424        }
425    }
426
427    /// Runs the tasks queued after this in `scope`, then goes back.
428    fn enter(&mut self, scope: ScopeId) {
429        // Queued first, so it runs last.
430        self.stack.push(Task::Scope(self.cur));
431        self.cur = scope;
432    }
433
434    fn node(&self, id: NodeId) -> Node {
435        *self.ast.node(id)
436    }
437
438    fn name(&self, id: NodeId) -> Cow<'a, str> {
439        text::ident_name(self.ast.span(id).text(self.src))
440    }
441
442    fn scope(&self, id: ScopeId) -> &Scope {
443        &self.s.scopes[id.index()]
444    }
445
446    fn new_scope(
447        &mut self,
448        kind: ScopeKind,
449        node: NodeId,
450        strict: bool,
451        parent: Option<ScopeId>,
452    ) -> ScopeId {
453        let id = ScopeId(self.s.scopes.len() as u32);
454        self.s.scopes.push(Scope {
455            kind,
456            parent,
457            node,
458            strict,
459            dynamic: kind == ScopeKind::With,
460            arrow: false,
461            bindings: Vec::new(),
462            names: HashMap::new(),
463        });
464        // The block Annex B puts around a function gives way to the
465        // function's own scope, made after it.
466        self.s.scope_by_node.insert(node, id);
467        id
468    }
469
470    /// A scope inside the current one.
471    fn child(&mut self, kind: ScopeKind, node: NodeId) -> ScopeId {
472        let strict = self.scope(self.cur).strict;
473        self.new_scope(kind, node, strict, Some(self.cur))
474    }
475
476    /// Whether a statement list's directive prologue says "use strict".
477    fn use_strict(&self, list: List) -> bool {
478        for &id in self.ast.get(list) {
479            let Node::Expression {
480                expression,
481                directive: true,
482            } = self.node(id)
483            else {
484                return false;
485            };
486            let span = self.ast.span(expression);
487            if self.src.get(span.start as usize + 1..span.end as usize - 1) == Some("use strict") {
488                return true;
489            }
490        }
491        false
492    }
493
494    fn stmt(&mut self, id: NodeId) {
495        match self.node(id) {
496            Node::Expression { expression, .. } => self.push(Task::Expr(expression)),
497            Node::Block { body } => {
498                let s = self.child(ScopeKind::Block, id);
499                self.enter(s);
500                self.push_list(body, Task::Stmt);
501            }
502            Node::With { object, body } => {
503                self.push(Task::Expr(object));
504                let s = self.child(ScopeKind::With, id);
505                self.push(Task::Scope(s));
506                self.push(Task::Stmt(body));
507                self.push(Task::Scope(self.cur));
508            }
509            Node::Return { argument } => self.push_opt(argument, Task::Expr),
510            Node::Labeled { body, .. } => self.push(Task::Stmt(body)),
511            Node::If {
512                test,
513                consequent,
514                alternate,
515            } => {
516                self.push(Task::Expr(test));
517                self.if_body(consequent);
518                if let Some(alternate) = alternate {
519                    self.if_body(alternate);
520                }
521            }
522            Node::Switch {
523                discriminant,
524                cases,
525            } => {
526                self.push(Task::Expr(discriminant));
527                let s = self.child(ScopeKind::Block, id);
528                self.push(Task::Scope(s));
529                for &case in self.ast.get(cases) {
530                    if let Node::SwitchCase { test, consequent } = self.node(case) {
531                        self.push_opt(test, Task::Expr);
532                        self.push_list(consequent, Task::Stmt);
533                    }
534                }
535                self.push(Task::Scope(self.cur));
536            }
537            Node::Throw { argument } => self.push(Task::Expr(argument)),
538            Node::Try {
539                block,
540                handler,
541                finalizer,
542            } => {
543                self.push(Task::Stmt(block));
544                if let Some(handler) = handler
545                    && let Node::CatchClause { param, body } = self.node(handler)
546                {
547                    let s = self.child(ScopeKind::Catch, handler);
548                    self.push(Task::Scope(s));
549                    if let Some(param) = param {
550                        self.push(Task::Bind(param, decl(BindingKind::CatchParam)));
551                    }
552                    // The block's declarations share the clause's scope,
553                    // where they meet the parameter.
554                    if let Node::Block { body } = self.node(body) {
555                        self.push_list(body, Task::Stmt);
556                    }
557                    self.push(Task::Scope(self.cur));
558                }
559                self.push_opt(finalizer, Task::Stmt);
560            }
561            Node::While { test, body } => {
562                self.push(Task::Expr(test));
563                self.push(Task::Stmt(body));
564            }
565            Node::DoWhile { body, test } => {
566                self.push(Task::Stmt(body));
567                self.push(Task::Expr(test));
568            }
569            Node::For {
570                init,
571                test,
572                update,
573                body,
574            } => {
575                if init.is_some_and(|i| self.lexical_declaration(i)) {
576                    let s = self.child(ScopeKind::Block, id);
577                    self.enter(s);
578                }
579                if let Some(init) = init {
580                    if matches!(self.node(init), Node::VariableDeclaration { .. }) {
581                        self.push(Task::Stmt(init));
582                    } else {
583                        self.push(Task::Expr(init));
584                    }
585                }
586                self.push_opt(test, Task::Expr);
587                self.push_opt(update, Task::Expr);
588                self.push(Task::Stmt(body));
589            }
590            Node::ForIn { left, right, body }
591            | Node::ForOf {
592                left, right, body, ..
593            } => {
594                if let Node::VariableDeclaration { kind, declarations } = self.node(left) {
595                    if kind != VarKind::Var {
596                        let s = self.child(ScopeKind::Block, id);
597                        self.enter(s);
598                    }
599                    // The head's names are in their TDZ until the
600                    // expression after `in` or `of` has run.
601                    let tdz_end = self.ast.span(right).end;
602                    for &d in self.ast.get(declarations) {
603                        if let Node::VariableDeclarator { id: target, init } = self.node(d) {
604                            self.push(Task::Bind(
605                                target,
606                                Decl {
607                                    kind: var_kind(kind),
608                                    tdz_end,
609                                },
610                            ));
611                            self.push_opt(init, Task::Expr);
612                        }
613                    }
614                } else {
615                    self.push(Task::Target(left, Access::Write));
616                }
617                self.push(Task::Expr(right));
618                self.push(Task::Stmt(body));
619            }
620            Node::VariableDeclaration { kind, declarations } => {
621                for &d in self.ast.get(declarations) {
622                    if let Node::VariableDeclarator { id: target, init } = self.node(d) {
623                        let tdz_end = self.ast.span(d).end;
624                        self.push(Task::Bind(
625                            target,
626                            Decl {
627                                kind: var_kind(kind),
628                                tdz_end,
629                            },
630                        ));
631                        self.push_opt(init, Task::Expr);
632                    }
633                }
634            }
635            Node::Function(f) if f.kind == FunctionKind::Declaration => {
636                self.function_declaration(id, f);
637            }
638            Node::Class(c) if c.declaration => self.class(id, c),
639            Node::ExportNamed {
640                declaration,
641                specifiers,
642                source,
643                ..
644            } => {
645                self.push_opt(declaration, Task::Stmt);
646                // `export { a as b }` refers to `a`; with `from`, it
647                // names another module's export.
648                if source.is_none() {
649                    for &spec in self.ast.get(specifiers) {
650                        if let Node::ExportSpecifier { local, .. } = self.node(spec)
651                            && matches!(self.node(local), Node::Identifier)
652                        {
653                            self.push(Task::Expr(local));
654                        }
655                    }
656                }
657            }
658            Node::ExportDefault { declaration } => match self.node(declaration) {
659                Node::Function(f) if f.kind == FunctionKind::Declaration => {
660                    self.push(Task::Stmt(declaration));
661                }
662                Node::Class(c) if c.declaration => self.push(Task::Stmt(declaration)),
663                _ => self.push(Task::Expr(declaration)),
664            },
665            Node::ImportDeclaration { specifiers, .. } => {
666                for &spec in self.ast.get(specifiers) {
667                    let local = match self.node(spec) {
668                        Node::ImportSpecifier { local, .. }
669                        | Node::ImportDefaultSpecifier { local }
670                        | Node::ImportNamespaceSpecifier { local } => local,
671                        _ => continue,
672                    };
673                    self.push(Task::Bind(local, decl(BindingKind::Import)));
674                }
675            }
676            Node::Empty | Node::Debugger | Node::Break { .. } | Node::Continue { .. } => {}
677            Node::ExportAll { .. } => {}
678            _ => self.push(Task::Expr(id)),
679        }
680    }
681
682    /// An `if`'s branch, where sloppy code may have a function
683    /// declaration (B.3.3), which is as if it were in a block of its own.
684    fn if_body(&mut self, id: NodeId) {
685        if let Node::Function(f) = self.node(id)
686            && f.kind == FunctionKind::Declaration
687        {
688            let outer = self.cur;
689            let s = self.child(ScopeKind::Block, id);
690            self.cur = s;
691            self.function_declaration(id, f);
692            self.cur = outer;
693            self.push(Task::Scope(outer));
694            return;
695        }
696        self.push(Task::Stmt(id));
697    }
698
699    fn lexical_declaration(&self, id: NodeId) -> bool {
700        matches!(
701            self.node(id),
702            Node::VariableDeclaration {
703                kind: VarKind::Let | VarKind::Const,
704                ..
705            }
706        )
707    }
708
709    fn expr(&mut self, id: NodeId) {
710        match self.node(id) {
711            Node::Identifier => self.reference(id, Access::Read),
712            Node::Array { elements, .. } => self.push_list(elements, Task::Expr),
713            Node::Object { properties, .. } => {
714                for &p in self.ast.get(properties) {
715                    match self.node(p) {
716                        Node::Property {
717                            key,
718                            value,
719                            computed,
720                            ..
721                        } => {
722                            if computed {
723                                self.push(Task::Expr(key));
724                            }
725                            self.push(Task::Expr(value));
726                        }
727                        _ => self.push(Task::Expr(p)),
728                    }
729                }
730            }
731            Node::Template { expressions, .. } => self.push_list(expressions, Task::Expr),
732            Node::TaggedTemplate { tag, quasi } => {
733                self.push(Task::Expr(tag));
734                self.push(Task::Expr(quasi));
735            }
736            Node::Unary { argument, .. }
737            | Node::Spread { argument }
738            | Node::Await { argument }
739            | Node::Paren {
740                expression: argument,
741            }
742            | Node::Chain {
743                expression: argument,
744            } => self.push(Task::Expr(argument)),
745            Node::Update { argument, .. } => self.push(Task::Target(argument, Access::ReadWrite)),
746            Node::Binary { left, right, .. } | Node::Logical { left, right, .. } => {
747                self.push(Task::Expr(left));
748                self.push(Task::Expr(right));
749            }
750            Node::Assign {
751                operator,
752                left,
753                right,
754            } => {
755                let access = if operator == AssignOp::Assign {
756                    Access::Write
757                } else {
758                    Access::ReadWrite
759                };
760                self.push(Task::Target(left, access));
761                self.push(Task::Expr(right));
762            }
763            Node::Conditional {
764                test,
765                consequent,
766                alternate,
767            } => {
768                self.push(Task::Expr(test));
769                self.push(Task::Expr(consequent));
770                self.push(Task::Expr(alternate));
771            }
772            Node::Call {
773                callee,
774                arguments,
775                optional,
776            } => {
777                let inner = self.ast.unparenthesized(callee);
778                if !optional
779                    && matches!(self.node(inner), Node::Identifier)
780                    && self.name(inner) == "eval"
781                {
782                    self.direct_eval();
783                }
784                self.push(Task::Expr(callee));
785                self.push_list(arguments, Task::Expr);
786            }
787            Node::New { callee, arguments } => {
788                self.push(Task::Expr(callee));
789                self.push_list(arguments, Task::Expr);
790            }
791            Node::Member {
792                object,
793                property,
794                computed,
795                ..
796            } => {
797                self.push(Task::Expr(object));
798                if computed {
799                    self.push(Task::Expr(property));
800                }
801            }
802            Node::Sequence { expressions } => self.push_list(expressions, Task::Expr),
803            Node::Yield { argument, .. } => self.push_opt(argument, Task::Expr),
804            Node::Import { source, options } => {
805                self.push(Task::Expr(source));
806                self.push_opt(options, Task::Expr);
807            }
808            Node::Function(f) => self.function(id, f),
809            Node::Class(c) => self.class(id, c),
810            Node::ObjectPattern { .. }
811            | Node::ArrayPattern { .. }
812            | Node::AssignmentPattern { .. }
813            | Node::Rest { .. } => self.target(id, Access::Write),
814            _ => {}
815        }
816    }
817
818    /// An assignment's target: names in it are written.
819    fn target(&mut self, id: NodeId, access: Access) {
820        match self.node(id) {
821            Node::Identifier => self.reference(id, access),
822            Node::Paren { expression } => self.push(Task::Target(expression, access)),
823            Node::ObjectPattern { properties } => {
824                for &p in self.ast.get(properties) {
825                    match self.node(p) {
826                        Node::Property {
827                            key,
828                            value,
829                            computed,
830                            ..
831                        } => {
832                            if computed {
833                                self.push(Task::Expr(key));
834                            }
835                            self.push(Task::Target(value, Access::Write));
836                        }
837                        Node::Rest { argument } => self.push(Task::Target(argument, Access::Write)),
838                        _ => {}
839                    }
840                }
841            }
842            Node::ArrayPattern { elements } => {
843                for &e in self.ast.get(elements) {
844                    if !matches!(self.node(e), Node::Elision) {
845                        self.push(Task::Target(e, Access::Write));
846                    }
847                }
848            }
849            Node::Rest { argument } => self.push(Task::Target(argument, Access::Write)),
850            Node::AssignmentPattern { left, right } => {
851                self.push(Task::Target(left, Access::Write));
852                self.push(Task::Expr(right));
853            }
854            _ => self.push(Task::Expr(id)),
855        }
856    }
857
858    /// A binding pattern: names in it are declared as `d` says.
859    fn bind(&mut self, id: NodeId, d: Decl) {
860        match self.node(id) {
861            Node::Identifier => self.declare(id, d, true),
862            Node::ObjectPattern { properties } => {
863                for &p in self.ast.get(properties) {
864                    match self.node(p) {
865                        Node::Property {
866                            key,
867                            value,
868                            computed,
869                            ..
870                        } => {
871                            if computed {
872                                self.push(Task::Expr(key));
873                            }
874                            self.push(Task::Bind(value, d));
875                        }
876                        Node::Rest { argument } => self.push(Task::Bind(argument, d)),
877                        _ => {}
878                    }
879                }
880            }
881            Node::ArrayPattern { elements } => {
882                for &e in self.ast.get(elements) {
883                    if !matches!(self.node(e), Node::Elision) {
884                        self.push(Task::Bind(e, d));
885                    }
886                }
887            }
888            Node::Rest { argument } => self.push(Task::Bind(argument, d)),
889            Node::AssignmentPattern { left, right } => {
890                self.push(Task::Bind(left, d));
891                self.push(Task::Expr(right));
892            }
893            _ => {}
894        }
895    }
896
897    fn reference(&mut self, id: NodeId, access: Access) {
898        let index = self.s.references.len() as u32;
899        self.s.references.push(Reference {
900            node: id,
901            scope: self.cur,
902            binding: None,
903            access,
904            tdz: false,
905        });
906        self.s.by_node[id.index()] = REF | index;
907    }
908
909    fn direct_eval(&mut self) {
910        let mut s = Some(self.cur);
911        while let Some(id) = s {
912            let scope = &mut self.s.scopes[id.index()];
913            scope.dynamic = true;
914            s = scope.parent;
915        }
916    }
917
918    fn function_declaration(&mut self, id: NodeId, f: Function) {
919        if let Some(name) = f.id {
920            let kind = self.scope(self.cur).kind;
921            let plain = !f.is_async && !f.generator;
922            if kind.holds_vars() && kind != ScopeKind::Module {
923                self.declare_var(name, BindingKind::Function);
924            } else {
925                let b = self.declare_lexical(name, BindingKind::Function, plain, 0);
926                if let Some(b) = b
927                    && plain
928                    && !self.scope(self.cur).strict
929                    && kind != ScopeKind::Module
930                {
931                    self.annex_b.push((self.cur, b));
932                }
933            }
934        }
935        self.function(id, f);
936    }
937
938    /// A function's scope, its parameters and its body.
939    fn function(&mut self, id: NodeId, f: Function) {
940        let outer = self.cur;
941        let body_list = match self.node(f.body) {
942            Node::Block { body } if !f.expression => Some(body),
943            _ => None,
944        };
945        let strict = self.scope(outer).strict || body_list.is_some_and(|l| self.use_strict(l));
946        let s = self.new_scope(ScopeKind::Function, id, strict, Some(outer));
947        self.s.scopes[s.index()].arrow = f.kind == FunctionKind::Arrow;
948        if f.kind == FunctionKind::Expression
949            && let Some(name) = f.id
950        {
951            self.cur = s;
952            self.declare(name, decl(BindingKind::FunctionName), true);
953            self.cur = outer;
954        }
955        self.push(Task::Scope(s));
956        let params = self.ast.get(f.params);
957        let separate = params.iter().any(|&p| self.has_expression(p));
958        self.push_list(f.params, |p| Task::Bind(p, decl(BindingKind::Param)));
959        match body_list {
960            Some(list) => {
961                if separate {
962                    let b = self.new_scope(ScopeKind::FunctionBody, f.body, strict, Some(s));
963                    self.push(Task::Scope(b));
964                }
965                self.push_list(list, Task::Stmt);
966            }
967            None => self.push(Task::Expr(f.body)),
968        }
969        self.push(Task::Scope(outer));
970    }
971
972    /// Whether a parameter has an expression in it: a default, or a
973    /// computed key.
974    fn has_expression(&self, id: NodeId) -> bool {
975        let mut stack = vec![id];
976        while let Some(id) = stack.pop() {
977            match self.node(id) {
978                Node::AssignmentPattern { .. } => return true,
979                Node::ObjectPattern { properties } => {
980                    for &p in self.ast.get(properties) {
981                        match self.node(p) {
982                            Node::Property { computed: true, .. } => return true,
983                            Node::Property { value, .. } => stack.push(value),
984                            Node::Rest { argument } => stack.push(argument),
985                            _ => {}
986                        }
987                    }
988                }
989                Node::ArrayPattern { elements } => stack.extend(self.ast.get(elements)),
990                Node::Rest { argument } => stack.push(argument),
991                _ => {}
992            }
993        }
994        false
995    }
996
997    fn class(&mut self, id: NodeId, c: Class) {
998        let end = self.ast.span(id).end;
999        if c.declaration
1000            && let Some(name) = c.id
1001        {
1002            self.declare_lexical(name, BindingKind::Class, false, end);
1003        }
1004        let outer = self.cur;
1005        let s = self.new_scope(ScopeKind::Class, id, true, Some(outer));
1006        self.push(Task::Scope(s));
1007        if let Some(name) = c.id {
1008            self.cur = s;
1009            self.declare(
1010                name,
1011                Decl {
1012                    kind: BindingKind::ClassName,
1013                    tdz_end: end,
1014                },
1015                !c.declaration,
1016            );
1017            self.cur = outer;
1018        }
1019        self.push_opt(c.super_class, Task::Expr);
1020        let Node::ClassBody { body } = self.node(c.body) else {
1021            unreachable!("a class has a body")
1022        };
1023        for &element in self.ast.get(body) {
1024            match self.node(element) {
1025                Node::Method {
1026                    key,
1027                    value,
1028                    computed,
1029                    ..
1030                } => {
1031                    if computed {
1032                        self.push(Task::Expr(key));
1033                    }
1034                    self.push(Task::Expr(value));
1035                }
1036                Node::Field {
1037                    key,
1038                    value,
1039                    computed,
1040                    ..
1041                } => {
1042                    if computed {
1043                        self.push(Task::Expr(key));
1044                    }
1045                    if let Some(value) = value {
1046                        let f = self.new_scope(ScopeKind::ClassField, element, true, Some(s));
1047                        self.push(Task::Scope(f));
1048                        self.push(Task::Expr(value));
1049                        self.push(Task::Scope(s));
1050                    }
1051                }
1052                Node::StaticBlock { body } => {
1053                    let b = self.new_scope(ScopeKind::StaticBlock, element, true, Some(s));
1054                    self.push(Task::Scope(b));
1055                    self.push_list(body, Task::Stmt);
1056                    self.push(Task::Scope(s));
1057                }
1058                _ => {}
1059            }
1060        }
1061        self.push(Task::Scope(outer));
1062    }
1063
1064    // Declarations.
1065
1066    /// Declares the identifier `id` as `d` says, in the current scope or,
1067    /// for a `var`, the function's. `map` records `id` as declaring it.
1068    fn declare(&mut self, id: NodeId, d: Decl, map: bool) {
1069        match d.kind {
1070            BindingKind::Var => self.declare_var(id, BindingKind::Var),
1071            BindingKind::Let | BindingKind::Const | BindingKind::Import => {
1072                self.declare_lexical(id, d.kind, false, d.tdz_end);
1073            }
1074            _ => {
1075                let name = self.name(id);
1076                let existing = self.scope(self.cur).names.get(&*name).copied();
1077                match existing {
1078                    // A parameter's name, given twice in sloppy code.
1079                    Some(b)
1080                        if self.s.bindings[b.index()].kind == d.kind
1081                            && d.kind == BindingKind::Param =>
1082                    {
1083                        self.s.by_node[id.index()] = b.0;
1084                    }
1085                    _ => {
1086                        let lexical =
1087                            matches!(d.kind, BindingKind::CatchParam | BindingKind::ClassName);
1088                        let b = self.add(Binding {
1089                            lexical,
1090                            tdz_end: d.tdz_end,
1091                            ..new_binding(self.cur, &name, d.kind, Some(id))
1092                        });
1093                        if map {
1094                            self.s.by_node[id.index()] = b.0;
1095                        }
1096                    }
1097                }
1098            }
1099        }
1100    }
1101
1102    fn add(&mut self, binding: Binding) -> BindingId {
1103        let b = BindingId(self.s.bindings.len() as u32);
1104        let s = &mut self.s.scopes[binding.scope.index()];
1105        s.bindings.push(b);
1106        s.names.insert(binding.name.as_str().into(), b);
1107        self.s.bindings.push(binding);
1108        b
1109    }
1110
1111    /// Whether `scope` is a `catch` clause whose parameter is just a
1112    /// name, which a `var` in its block may declare again (B.3.4).
1113    fn simple_catch(&self, scope: ScopeId) -> bool {
1114        let s = self.scope(scope);
1115        s.kind == ScopeKind::Catch
1116            && matches!(
1117                self.node(s.node),
1118                Node::CatchClause { param: Some(p), .. } if matches!(self.node(p), Node::Identifier)
1119            )
1120    }
1121
1122    fn declare_var(&mut self, id: NodeId, kind: BindingKind) {
1123        let name = self.name(id);
1124        let mut s = self.cur;
1125        loop {
1126            let scope = self.scope(s);
1127            let holds = scope.kind.holds_vars();
1128            if let Some(&b) = scope.names.get(&*name) {
1129                let had = &self.s.bindings[b.index()];
1130                if had.lexical {
1131                    let allowed = had.kind == BindingKind::CatchParam && self.simple_catch(s);
1132                    if !allowed {
1133                        let first = had.node;
1134                        self.conflict("lexical-var-conflict", id, &name, first);
1135                        return;
1136                    }
1137                } else if holds && had.kind != BindingKind::FunctionName {
1138                    self.s.by_node[id.index()] = b.0;
1139                    return;
1140                }
1141            }
1142            if holds {
1143                let b = self.add(new_binding(s, &name, kind, Some(id)));
1144                self.s.by_node[id.index()] = b.0;
1145                return;
1146            }
1147            let parent = scope.parent.expect("a var scope is at the top");
1148            self.hoisted.insert((s, name.as_ref().into()));
1149            s = parent;
1150        }
1151    }
1152
1153    /// Declares a lexical name in the current scope. `None` if it's an
1154    /// error, or a sloppy function declared again.
1155    fn declare_lexical(
1156        &mut self,
1157        id: NodeId,
1158        kind: BindingKind,
1159        plain: bool,
1160        tdz_end: u32,
1161    ) -> Option<BindingId> {
1162        let name = self.name(id);
1163        let s = self.cur;
1164        let scope = self.scope(s);
1165        if let Some(&b) = scope.names.get(&*name) {
1166            let had = &self.s.bindings[b.index()];
1167            if had.kind != BindingKind::FunctionName {
1168                let first = had.node;
1169                if had.lexical {
1170                    let sloppy_functions = kind == BindingKind::Function
1171                        && had.kind == BindingKind::Function
1172                        && plain
1173                        && had.plain
1174                        && !scope.strict;
1175                    if sloppy_functions {
1176                        self.s.by_node[id.index()] = b.0;
1177                        return None;
1178                    }
1179                    self.conflict("duplicate-declaration", id, &name, first);
1180                } else if had.kind == BindingKind::Param {
1181                    self.conflict("duplicate-declaration", id, &name, first);
1182                } else {
1183                    self.conflict("lexical-var-conflict", id, &name, first);
1184                }
1185                return None;
1186            }
1187        }
1188        if self.hoisted.contains(&(s, name.as_ref().into())) {
1189            self.conflict("lexical-var-conflict", id, &name, None);
1190            return None;
1191        }
1192        if scope.kind == ScopeKind::FunctionBody
1193            && let Some(parent) = scope.parent
1194            && let Some(&b) = self.scope(parent).names.get(&*name)
1195            && self.s.bindings[b.index()].kind == BindingKind::Param
1196        {
1197            let first = self.s.bindings[b.index()].node;
1198            self.conflict("duplicate-declaration", id, &name, first);
1199            return None;
1200        }
1201        let b = self.add(Binding {
1202            lexical: true,
1203            plain,
1204            tdz_end,
1205            ..new_binding(s, &name, kind, Some(id))
1206        });
1207        self.s.by_node[id.index()] = b.0;
1208        Some(b)
1209    }
1210
1211    fn conflict(&mut self, code: &'static str, id: NodeId, name: &str, first: Option<NodeId>) {
1212        let message = if code == "duplicate-declaration" {
1213            format!("`{name}` is already declared in this scope")
1214        } else {
1215            format!("`{name}` is declared both with `var` and as a lexical name in this scope")
1216        };
1217        let mut d = Diagnostic::error(code, self.ast.span(id), message);
1218        if let Some(first) = first {
1219            d = d.with_label(self.ast.span(first), "declared here first");
1220        }
1221        self.s.diagnostics.push(d);
1222    }
1223
1224    /// B.3.2: a sloppy function declared in a block is also a `var` in
1225    /// its function, unless a `var` of its name would be an error there
1226    /// or the name is a parameter's.
1227    fn annex_b(&mut self) {
1228        for (block, b) in std::mem::take(&mut self.annex_b) {
1229            let name = self.s.bindings[b.index()].name.clone();
1230            let node = self.s.bindings[b.index()].node;
1231            let mut s = self.scope(block).parent.expect("a block is in a scope");
1232            let target = loop {
1233                let scope = self.scope(s);
1234                if let Some(&had) = scope.names.get(name.as_str()) {
1235                    let had = &self.s.bindings[had.index()];
1236                    let blocks = had.lexical
1237                        && !(had.kind == BindingKind::CatchParam && self.simple_catch(s))
1238                        || had.kind == BindingKind::Param;
1239                    if blocks {
1240                        break None;
1241                    }
1242                }
1243                if scope.kind == ScopeKind::FunctionBody
1244                    && let Some(parent) = scope.parent
1245                    && let Some(&had) = self.scope(parent).names.get(name.as_str())
1246                    && self.s.bindings[had.index()].kind == BindingKind::Param
1247                {
1248                    break None;
1249                }
1250                if scope.kind.holds_vars() {
1251                    break Some(s);
1252                }
1253                s = scope.parent.expect("a var scope is at the top");
1254            };
1255            if let Some(target) = target {
1256                let exists = self
1257                    .scope(target)
1258                    .names
1259                    .get(name.as_str())
1260                    .is_some_and(|&had| {
1261                        self.s.bindings[had.index()].kind != BindingKind::FunctionName
1262                    });
1263                if !exists {
1264                    self.add(Binding {
1265                        plain: true,
1266                        ..new_binding(target, &name, BindingKind::Function, node)
1267                    });
1268                }
1269            }
1270        }
1271    }
1272
1273    // Resolution.
1274
1275    fn resolve(&mut self) {
1276        let mut free: HashSet<String> = HashSet::new();
1277        for i in 0..self.s.references.len() {
1278            let r = self.s.references[i];
1279            let span = self.ast.span(r.node);
1280            let name = text::ident_name(span.text(self.src));
1281            let mut s = r.scope;
1282            let mut deferred = false;
1283            let found = loop {
1284                let scope = self.scope(s);
1285                if let Some(&b) = scope.names.get(&*name) {
1286                    break Some((b, deferred));
1287                }
1288                if name == "arguments" && scope.kind == ScopeKind::Function && !scope.arrow {
1289                    let b = self.add(new_binding(s, "arguments", BindingKind::Arguments, None));
1290                    break Some((b, deferred));
1291                }
1292                deferred |= scope.kind.defers();
1293                match scope.parent {
1294                    Some(p) => s = p,
1295                    None => break None,
1296                }
1297            };
1298            match found {
1299                Some((b, deferred)) => {
1300                    let binding = &self.s.bindings[b.index()];
1301                    let tdz = !deferred && span.start < binding.tdz_end;
1302                    let r = &mut self.s.references[i];
1303                    r.binding = Some(b);
1304                    r.tdz = tdz;
1305                }
1306                None => {
1307                    if !free.contains(&*name) {
1308                        free.insert(name.to_string());
1309                        self.s.free.push(name.into_owned());
1310                    }
1311                }
1312            }
1313        }
1314    }
1315}
1316
1317/// A binding that isn't lexical and has no TDZ.
1318fn new_binding(scope: ScopeId, name: &str, kind: BindingKind, node: Option<NodeId>) -> Binding {
1319    Binding {
1320        name: name.to_string(),
1321        kind,
1322        scope,
1323        node,
1324        lexical: false,
1325        plain: false,
1326        tdz_end: 0,
1327    }
1328}
1329
1330const fn decl(kind: BindingKind) -> Decl {
1331    Decl { kind, tdz_end: 0 }
1332}
1333
1334const fn var_kind(kind: VarKind) -> BindingKind {
1335    match kind {
1336        VarKind::Var => BindingKind::Var,
1337        VarKind::Let => BindingKind::Let,
1338        VarKind::Const => BindingKind::Const,
1339    }
1340}