Expand description
Scopes and bindings: which declaration each name in a program refers to, worked out from the tree alone.
Scopes::analyze walks an Ast once and builds the scopes the
spec’s environments would be, from the global or module scope down
through functions, blocks, classes, catch clauses, class static
blocks and the implicit function around each class field’s
initializer. Each declaration becomes a Binding in the scope it
lives in: var and function declarations hoisted to their function,
with Annex B’s function-in-block semantics in sloppy code; let,
const and class in their block. Each IdentifierReference becomes a
Reference, resolved to its binding or left free.
Nothing runs, so two things the analysis can’t see are marked rather
than guessed: a scope that holds a direct eval call, or any scope
around one, is Scope::dynamic, since the eval’d code can read and
add names there; and the body of a with gets a ScopeKind::With
scope, dynamic too, since any name in it may be a property of the
object.
The names declared twice where the spec forbids it come back as
Scopes::diagnostics, with codes duplicate-declaration and
lexical-var-conflict.
use parsec_js::scope::{BindingKind, Scopes};
use parsec_js::parse_script;
let src = "let total = 0; for (const x of items) total += x; console.log(total);";
let ast = parse_script(src).unwrap();
let scopes = Scopes::analyze(&ast, src);
assert_eq!(scopes.free_names(), ["items", "console"]);
let total = scopes.references().iter().find(|r| r.name(&ast, src) == "total").unwrap();
let binding = scopes.binding(total.binding.unwrap());
assert_eq!(binding.kind, BindingKind::Let);
assert!(scopes.diagnostics().is_empty());The walk keeps its own stack, so a tree of any depth is analyzed without touching the thread’s.
Structs§
- Binding
- A name declared in a scope.
- Binding
Id - A binding in
Scopes. - Reference
- An IdentifierReference, and what it resolved to.
- Scope
- A scope: what made it, the scope around it, and its bindings.
- ScopeId
- A scope in
Scopes. - Scopes
- Every scope, binding and reference in a program. See the module docs.
Enums§
- Access
- How a reference uses its name.
- Binding
Kind - What declared a binding.
- Scope
Kind - What made a scope.