Scope and Binding Resolver - Problem
Implement a lexical scoping resolver that resolves variable references to their declarations across nested scopes.
Given an Abstract Syntax Tree (AST) representing a program with variable declarations and references, your task is to:
- Track variable declarations in different scopes
- Resolve each variable reference to its corresponding declaration
- Handle nested scopes where inner scopes can shadow outer scopes
- Return a mapping of variable references to their declaration locations
The AST is represented as a tree structure where each node has a type, optional name (for variables), and optional children list.
Node Types:
"program"- Root of the AST"block"- Creates a new scope"declaration"- Variable declaration (hasname)"reference"- Variable reference (hasname)
Input & Output
Example 1 — Basic Nested Scopes
$
Input:
ast = {"type":"program","children":[{"type":"declaration","name":"x"},{"type":"block","children":[{"type":"declaration","name":"y"},{"type":"reference","name":"x"}]}]}
›
Output:
{"[1,1]":[0]}
💡 Note:
Program has declaration 'x' at [0]. Inside block, reference 'x' at [1,1] resolves to outer declaration at [0].
Example 2 — Variable Shadowing
$
Input:
ast = {"type":"program","children":[{"type":"declaration","name":"x"},{"type":"block","children":[{"type":"declaration","name":"x"},{"type":"reference","name":"x"}]}]}
›
Output:
{"[1,1]":[1,0]}
💡 Note:
Inner declaration 'x' at [1,0] shadows outer 'x'. Reference 'x' at [1,1] resolves to inner declaration [1,0].
Example 3 — Multiple References
$
Input:
ast = {"type":"program","children":[{"type":"declaration","name":"a"},{"type":"reference","name":"a"},{"type":"block","children":[{"type":"reference","name":"a"}]}]}
›
Output:
{"[1]":[0],"[2,0]":[0]}
💡 Note:
Both references to 'a' (at [1] and [2,0]) resolve to the same declaration at [0].
Constraints
- 1 ≤ number of AST nodes ≤ 1000
- 1 ≤ variable name length ≤ 50
- 1 ≤ nesting depth ≤ 20
- Variable names contain only letters and numbers
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code