Recursive AI

Inspect JavaScript lexical scopes in C#

OneEcma is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Inspect declared names and their scopes without running JavaScript.

Terminal
dotnet add package RecursiveAI.OneEcma

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneEcma.Syntax;
var tree = JsParser.Parse("let value = 1;");
if (tree.HasErrors) return;
foreach (var item in
    tree.Program.Scope.Bindings)
  Console.WriteLine($"{item.Kind} {item.Name}");
Text
Let value

Unzip the example, then dotnet run.

The full program

The full example parses this inline script, then walks Scope.Children with an explicit stack. Three separate scopes declare value.

C#
using RecursiveAI.OneEcma.Syntax;
 
string source = """
let value = 1;
function read(input) {
    let value = input;
    { let value = 3; }
    return value;
}
""";
var result = JsParser.Parse(source);
if (result.HasErrors)
{
    foreach (var error in result.Diagnostics)
        Console.WriteLine(error.Headline);
    return;
}
var pending = new Stack<(Scope Scope, int Depth)>();
pending.Push((result.Program.Scope, 0));
while (pending.TryPop(out var item))
{
    string indent = new(' ', item.Depth * 2);
    Console.WriteLine($"{indent}{item.Scope.Kind} strict={item.Scope.IsStrict}");
    foreach (var binding in item.Scope.Bindings)
        Console.WriteLine($"{indent}  {binding.Kind} {binding.Name}");
    for (int i = item.Scope.Children.Count - 1; i >= 0; i--)
        pending.Push((item.Scope.Children[i], item.Depth + 1));
}
Text
Global strict=False
  Let value
  Function read
  Function strict=False
    Parameter input
    Let value
    Block strict=False
      Let value

If the script has syntax or early errors, the program prints diagnostics and does not inspect the recovered scope tree.

Variations

Inspect module strictness and a direct binding. Lookup searches only the current scope:

C#
using RecursiveAI.OneEcma.Syntax;
 
var result = JsParser.Parse("export const value = 1;",
    new ParseOptions { Goal = ParseGoal.Module });
if (result.HasErrors) throw new Exception("Invalid module");
var scope = result.Program.Scope;
Console.WriteLine($"{scope.Kind} strict={scope.IsStrict}");
Console.WriteLine(scope.Lookup("value")?.Kind);
Text
Module strict=True
Const

The short answer

Call JsParser.Parse, check HasErrors, then inspect result.Program.Scope. Each scope exposes its Bindings, Children, Parent, Kind and IsStrict flag. The parser creates this information while checking early errors; you do not need to run the JavaScript or invoke its functions.

Walk Children to inventory nested declarations. Walk Parent when your analysis needs to search outward for a name. These are different operations: listing declarations is not the same as resolving every identifier use in an expression.

What is JavaScript scope?

A scope is the context in which a name can be referenced; MDN’s scope definition distinguishes global, module, function and block scopes. In this API a Binding describes a declaration, including its name, kind and source span. Its scope records the surrounding declaration context.

The full example has a global value, a function-local value and a block-local value. They share spelling, not identity. Storing bindings in a dictionary keyed only by name across the whole program would collapse those distinct declarations. Retain the scope as part of the identity, or keep a separate name map for each scope.

Scope inspection is useful for declaration outlines, shadowing warnings and source navigation. It does not calculate runtime values. The parser can record a parameter named input without calling read or knowing what a future caller will pass.

How does block scope work in JavaScript?

The nested braces in the full example produce a child Block scope containing its own Let value. The outer function’s value remains a separate binding. That is why the output indents the innermost declaration under a block rather than appending it to the function’s binding list.

To detect shadowing, compare each binding name against declarations in its parent scopes. Do not treat a matching name as a duplicate declaration in the same scope: shadowing and redeclaration are different checks. The parser already reports declaration clashes that are early errors; an application’s shadowing warning is an additional policy decision.

Binding.Span refers to the first declaring identifier. Use it to underline the declaration rather than searching for matching text, which could also occur in strings or comments. As with all parser positions, these spans use UTF-16 source offsets.

What is function scope in JavaScript?

A function scope holds parameters and its top-level body declarations. In the example, read is declared in the global scope, while input and the next value belong to the function scope. The innermost block is a child of that function. Binding.Kind distinguishes a function declaration from a formal parameter or a let binding.

The module variation demonstrates another independent property: modules are strict. Read IsStrict from the scope rather than inferring strictness from indentation or from the presence of a function. Classic scripts can also opt into strict mode.

How do I follow the scope chain in JavaScript?

Scope.Lookup(name) checks declarations directly in that scope. If it returns null, follow Parent and repeat until you find a binding or reach the root. Reference resolution is left to the consumer; the tree does not provide a pre-resolved binding on every identifier.

Keep dynamic features in mind when building tooling. Scopes expose ContainsDirectEval and ContainsWith because those features affect assumptions about name access. A declaration inventory is still useful, but it is not proof of all runtime name behavior. The scope API documentation describes the recorded information.

All oneecma recipes