### ScopeTracker Initialization Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Examples of initializing ScopeTracker, showing both single-pass (memory-efficient) and multi-pass (scope preservation) configurations. ```typescript // Single-pass (discards exited scopes, saves memory) new ScopeTracker() // Multi-pass (preserves all scopes) new ScopeTracker({ preserveExitedScopes: true }) ``` -------------------------------- ### Install oxc-walker and oxc-parser Source: https://github.com/oxc-project/oxc-walker/blob/main/README.md Install the necessary packages using npm or pnpm. oxc-parser is an optional peer dependency. ```sh # npm npm install oxc-walker oxc-parser # pnpm pnpm install oxc-walker oxc-parser ``` -------------------------------- ### Walk Function Usage Example Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Demonstrates how to use the walk function with custom enter and leave callbacks for AST traversal. ```typescript import { walk } from "oxc-walker"; const options: WalkOptions = { enter(node, parent, ctx) { console.log(`Entering ${node.type}`); }, leave(node, parent, ctx) { console.log(`Leaving ${node.type}`); }, }; walk(ast.program, options); ``` -------------------------------- ### parseAndWalk Usage Example Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Demonstrates how to use `parseAndWalk` with custom parser options and a specific `parseSync` implementation. It logs the type of each node entered during the walk. ```typescript import { parseAndWalk } from "oxc-walker"; import { parseSync } from "rolldown/utils"; const result = parseAndWalk("const x = 1", "example.js", { parseSync, parseOptions: { sourceType: "module", strictMode: true, }, enter(node) { console.log(node.type); }, }); ``` -------------------------------- ### WalkerLeave Example Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Example of a WalkerLeave callback that logs when traversal of a BlockStatement node is completed. ```typescript walk(ast.program, { leave(node, parent, ctx) { if (node.type === "BlockStatement") { console.log("Finished traversing block"); } }, }); ``` -------------------------------- ### Parse and walk with custom parseSync implementation Source: https://github.com/oxc-project/oxc-walker/blob/main/README.md Provide an explicit `parseSync` implementation, such as from `rolldown/utils`, to `parseAndWalk` if `oxc-parser` is not installed. ```ts import { parseSync } from "rolldown/utils"; import { parseAndWalk } from "oxc-walker"; parseAndWalk("const x = 1", "example.js", { parseSync, enter(node) { // ... }, }); ``` -------------------------------- ### Walker Context Methods Example Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Demonstrates using skip, remove, and replace methods within enter and leave callbacks to control AST traversal and modification. ```typescript walk(ast.program, { enter(node) { if (node.type === "FunctionDeclaration") { // Traverse the function but not its children this.skip(); } }, leave(node) { if (node.type === "BlockStatement") { // Remove all blocks this.remove(); } }, }); ``` -------------------------------- ### Checking for ScopeTrackerCatchParam Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Example of how to check if a declaration is a catch parameter and log its start position. ```typescript if (decl instanceof ScopeTrackerCatchParam) { console.log("Catch parameter at", decl.start); } ``` -------------------------------- ### Using walk() with ScopeTracker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/walk.md Shows how to integrate `walk()` with `ScopeTracker` to track variable declarations and references. This example finds references to a variable 'x' and logs the location of its declaration. ```typescript import { parseSync } from "oxc-parser"; import { walk, ScopeTracker } from "oxc-walker"; const ast = parseSync("example.js", "const x = 1; function foo() { console.log(x) }"); const scopeTracker = new ScopeTracker(); walk(ast.program, { scopeTracker, enter(node) { if (node.type === "Identifier" && node.name === "x") { const declaration = scopeTracker.getDeclaration("x"); if (declaration) { console.log("Found reference to x declared at", declaration.start); } } }, }); ``` -------------------------------- ### ScopeTracker Usage Examples Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Demonstrates how to instantiate the ScopeTracker. The default tracker discards exited scopes, while enabling `preserveExitedScopes` retains them for multi-pass analysis. ```typescript import { ScopeTracker } from "oxc-walker"; // Default: exited scopes are discarded const tracker1 = new ScopeTracker(); // Preserve scopes for multi-pass analysis const tracker2 = new ScopeTracker({ preserveExitedScopes: true }); ``` -------------------------------- ### Checking for ScopeTrackerIdentifier Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Example of how to check if a declaration is an identifier and log its start position. ```typescript if (decl instanceof ScopeTrackerIdentifier) { console.log("Class or identifier at", decl.start); } ``` -------------------------------- ### WalkerEnter Example Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Example of a WalkerEnter callback that logs when a VariableDeclarator node is encountered during traversal. ```typescript parseAndWalk("const x = 1", "example.js", (node, parent, ctx) => { if (node.type === "VariableDeclarator") { console.log("Found variable"); } }); ``` -------------------------------- ### WalkerCallbackContext Example Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Illustrates accessing context properties like key and index within walker callbacks. ```typescript walk(ast.program, { enter(node, parent, ctx) { console.log(`key: ${ctx.key}, index: ${ctx.index}`); if (ctx.index !== null) { console.log(`Node is at index ${ctx.index} in an array`); } }, }); ``` -------------------------------- ### Walk a parsed AST with oxc-walker Source: https://github.com/oxc-project/oxc-walker/blob/main/README.md Walk a pre-parsed AST using the `walk` function. Ensure `oxc-parser` is installed or a custom `parseSync` implementation is provided. ```ts import { parseSync } from "oxc-parser"; import { walk } from "oxc-walker"; const ast = parseSync("example.js", "const x = 1"); walk(ast.program, { enter(node, parent, ctx) { // ... }, }); ``` -------------------------------- ### Pattern: Scope Tracking Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md An example of using ScopeTracker to find declarations associated with identifier references. ```typescript const tracker = new ScopeTracker(); walk(ast.program, { scopeTracker: tracker, enter(node) { if (node.type === "Identifier") { const decl = tracker.getDeclaration(node.name); if (decl) { console.log("Reference to", decl.type); } } }, }); ``` -------------------------------- ### ScopeTrackerFunction Example Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/scope-tracker-nodes.md Shows how to find a named function declaration using ScopeTracker.getDeclaration(). It verifies if the declaration is a ScopeTrackerFunction and logs the number of parameters it has. ```typescript import { parseAndWalk, ScopeTracker, ScopeTrackerFunction } from "oxc-walker"; const tracker = new ScopeTracker(); parseAndWalk("function foo() { return 42; }", "example.js", { scopeTracker: tracker, enter(node) { if (node.type === "Identifier" && node.name === "foo") { const decl = tracker.getDeclaration("foo"); if (decl instanceof ScopeTrackerFunction) { console.log("Function foo has", decl.node.params.length, "parameters"); } } }, }); ``` -------------------------------- ### AST Transformation with `this.replace()` Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/configuration.md Shows how to transform an AST during traversal using `this.replace()`. This example simplifies a `CallExpression` by replacing it with its callee. ```typescript import { walk } from "oxc-walker"; walk(ast.program, { enter(node, parent, ctx) { if (node.type === "CallExpression") { this.replace(node.callee); // Simplify AST } }, }); ``` -------------------------------- ### Import Core oxc-walker Functions and Types Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/INDEX.md Import the primary functions and types for AST traversal and scope analysis from the oxc-walker package. Ensure you have the package installed. ```typescript import { walk, parseAndWalk, isBindingIdentifier, getUndeclaredIdentifiersInFunction, ScopeTracker, ScopeTrackerVariable, ScopeTrackerFunction, ScopeTrackerFunctionParam, ScopeTrackerIdentifier, ScopeTrackerImport, ScopeTrackerCatchParam, } from "oxc-walker"; ``` -------------------------------- ### ScopeTrackerVariable Example Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/scope-tracker-nodes.md Demonstrates how to retrieve and identify a variable declaration using ScopeTracker.getDeclaration(). It checks if the declaration is an instance of ScopeTrackerVariable and logs its kind and position. ```typescript import { parseAndWalk, ScopeTracker, ScopeTrackerVariable } from "oxc-walker"; const tracker = new ScopeTracker(); parseAndWalk("const x = 1", "example.js", { scopeTracker: tracker, enter(node) { if (node.type === "Identifier" && node.name === "x") { const decl = tracker.getDeclaration("x"); if (decl instanceof ScopeTrackerVariable) { console.log("Variable x declared with kind:", decl.variableNode.kind); // "const" console.log("Position:", decl.start, "to", decl.end); } } }, }); ``` -------------------------------- ### Checking Declaration Scope with isUnderScope Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/scope-tracker-nodes.md Provides an example of how to use the `isUnderScope` method to determine if a declaration exists within a specific scope. This is useful for scope resolution and analysis. ```typescript const decl = tracker.getDeclaration("x"); if (decl?.isUnderScope("0")) { console.log("x is declared inside the first child scope"); } ``` -------------------------------- ### walk(input, options) Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Walk an AST by providing an entry point (Program or Node) and optional configuration options. ```APIDOC ## walk(input, options) ### Description Walk an Abstract Syntax Tree (AST) starting from a given node or program. ### Method Signature ```typescript walk(input: Program | Node, options: Partial): void ``` ### Parameters * `input` (Program | Node) - The starting point for the AST traversal. * `options` (Partial) - Optional configuration for the walker, including `enter`, `leave`, and `scopeTracker`. ### Example ```javascript walk(ast.program, { enter(node, parent, ctx) { /* ... */ }, leave(node, parent, ctx) { /* ... */ }, scopeTracker: tracker, }); ``` ``` -------------------------------- ### walk(ast, options) Source: https://github.com/oxc-project/oxc-walker/blob/main/README.md Walks an Abstract Syntax Tree (AST) using provided enter and/or leave callbacks. It supports options for scope tracking and allows control over the traversal process. ```APIDOC ## walk(ast, options) Walk an AST. ```ts // options interface WalkOptions { /** * The function to be called when entering a node. */ enter?: (node: Node, parent: Node | null, ctx: CallbackContext) => void; /** * The function to be called when leaving a node. */ leave?: (node: Node, parent: Node | null, ctx: CallbackContext) => void; /** * The instance of `ScopeTracker` to use for tracking declarations and references. */ scopeTracker?: ScopeTracker; } interface CallbackContext { /** * The key of the current node within its parent node object, if applicable. */ key: string | number | symbol | null | undefined; /** * The zero-based index of the current node within its parent's children array, if applicable. */ index: number | null; /** * The full Abstract Syntax Tree (AST) that is being walked, starting from the root node. */ ast: Program | Node; } ``` ### Control Flow #### `this.skip()` When called inside an `enter` callback, prevents the node's children from being walked. It is not available in `leave`. #### `this.replace(newNode)` Replaces the current node with `newNode`. When called inside `enter`, the **new node's children** will be walked. The leave callback will still be called with the original node. > ⚠️ When a `ScopeTracker` is provided, calling `this.replace()` will not update its declarations. #### `this.remove()` Removes the current node from its parent. When called inside `enter`, the removed node's children will not be walked. _This has a higher precedence than `this.replace()`, so if both are called, the node will be removed._ > ⚠️ When a `ScopeTracker` is provided, calling `this.remove()` will not update its declarations. ``` -------------------------------- ### Basic AST Traversal with walk() Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/walk.md Demonstrates basic traversal of an AST using the walk() function. Callbacks are provided for entering and leaving each node to log their types. ```typescript import { parseSync } from "oxc-parser"; import { walk } from "oxc-walker"; const ast = parseSync("example.js", "const x = 1; console.log(x)"); walk(ast.program, { enter(node) { console.log(`Entering ${node.type}`); }, leave(node) { console.log(`Leaving ${node.type}`); }, }); ``` -------------------------------- ### Checking for ScopeTrackerImport Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Example of how to check if a declaration is an import and access its source value. ```typescript if (decl instanceof ScopeTrackerImport) { console.log(decl.importNode.source.value); // module path } ``` -------------------------------- ### parseAndWalk with Full Options Form (Enter and Leave) Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/parseAndWalk.md Utilize the options form to provide both enter and leave callbacks for detailed AST traversal. This is useful for tracking node entry and exit, managing state, or performing complex analyses. ```typescript import { parseAndWalk } from "oxc-walker"; const nodeStack = []; const result = parseAndWalk("const x = 1", "example.js", { enter(node) { console.log(`→ ${node.type}`); nodeStack.push(node); }, leave(node) { console.log(`← ${node.type}`); nodeStack.pop(); }, }); ``` -------------------------------- ### Walker enter Callback Methods Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Demonstrates methods available within the `enter` callback for AST traversal control. ```typescript walk(ast.program, { enter(node, parent, ctx) { this.skip(); // Prevent children from being walked this.replace(newNode); // Replace node; new children are walked this.remove(); // Remove node; children not walked }, }); ``` -------------------------------- ### Optimized Parser Selection Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/configuration.md Shows how to optimize parser selection by pre-importing `parseSync` and passing it directly to `parseAndWalk`. This avoids runtime lookup overhead. ```typescript import { parseSync } from "oxc-parser"; import { parseAndWalk } from "oxc-walker"; export function analyze(code: string, filename: string) { return parseAndWalk(code, filename, { parseSync, // Pre-imported, no lookup enter(node) { // ... }, }); } ``` -------------------------------- ### ScopeTracker: Get Current Scope Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Obtain the identifier for the current scope being tracked. This is useful for understanding the nesting level of declarations. ```typescript const scope = tracker.getCurrentScope(); console.log(scope); // "", "0", "0-1", etc. ``` -------------------------------- ### walk() Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/walk.md Walks a parsed Abstract Syntax Tree (AST) and invokes callbacks when entering and leaving nodes. It provides mechanisms to skip, replace, or remove nodes during traversal. ```APIDOC ## walk() ### Description Walks a parsed Abstract Syntax Tree (AST) and invokes callbacks when entering and leaving nodes. It provides mechanisms to skip, replace, or remove nodes during traversal. ### Signature ```typescript function walk(input: Program | Node, options: Partial): void ``` ### Parameters #### `input` - **Type**: `Program | Node` - **Required**: Yes - **Description**: The AST to walk. Typically the `program` property from a `ParseResult` obtained via `parseSync()`. #### `options` - **Type**: `Partial` - **Required**: Yes - **Description**: Configuration object containing callback functions and optional scope tracker. ##### `options.enter` - **Type**: `WalkerEnter` - **Required**: No - **Description**: Callback invoked when entering each node. Receives `(node, parent, ctx)` and can use `this.skip()`, `this.replace()`, or `this.remove()`. ##### `options.leave` - **Type**: `WalkerLeave` - **Required**: No - **Description**: Callback invoked when leaving each node. Receives `(node, parent, ctx)` and can use `this.replace()` or `this.remove()`. ##### `options.scopeTracker` - **Type**: `ScopeTracker` - **Required**: No - **Description**: Optional instance of `ScopeTracker` to track variable declarations and references during traversal. ### Return Type `void` — No return value. The walk operates with side effects through callbacks. ### Callback Context (`ctx`) The context object passed to callbacks contains: - **key**: `string | number | symbol | null | undefined` - The property key of the current node within its parent object, or null if not applicable. - **index**: `number | null` - The zero-based index of the current node within its parent's array, or null if the node is not part of an array. - **ast**: `Program | Node` - The root AST node being walked. ### This Context in Callbacks #### In `enter` callback: - `this.skip()` — Prevents traversal of child nodes. Not available in `leave` callbacks. - `this.replace(newNode)` — Replaces the current node. Children of the new node will be traversed. - `this.remove()` — Removes the current node from the AST. Children are not traversed. #### In `leave` callback: - `this.replace(newNode)` — Replaces the current node after children have been visited. - `this.remove()` — Removes the current node from the AST. ### Notes - `this.replace()` has lower precedence than `this.remove()`. If both are called, removal wins. - When a `ScopeTracker` is provided, `this.replace()` and `this.remove()` do not update the tracker's declaration records. - The walker always traverses all child nodes when a `ScopeTracker` is active, even if `this.skip()` is called in `enter`. ### Usage Examples #### Basic Tree Traversal ```typescript import { parseSync } from "oxc-parser"; import { walk } from "oxc-walker"; const ast = parseSync("example.js", "const x = 1; console.log(x)"); walk(ast.program, { enter(node) { console.log(`Entering ${node.type}`); }, leave(node) { console.log(`Leaving ${node.type}`); }, }); ``` #### Collecting Variable Names ```typescript import { parseSync } from "oxc-parser"; import { walk } from "oxc-walker"; const ast = parseSync("example.js", "const x = 1; const y = 2;"); const vars = []; walk(ast.program, { enter(node) { if (node.type === "VariableDeclarator" && node.id.type === "Identifier") { vars.push(node.id.name); } }, }); console.log(vars); // ['x', 'y'] ``` #### Skipping Subtrees ```typescript walk(ast.program, { enter(node) { if (node.type === "FunctionDeclaration") { console.log(`Found function: ${node.id.name}`); this.skip(); // Don't traverse function body } }, }); ``` #### Modifying the AST ```typescript walk(ast.program, { enter(node, parent, ctx) { // Remove all console.log calls if ( node.type === "CallExpression" && node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "console" && node.callee.property.type === "Identifier" && node.callee.property.name === "log" ) { this.remove(); } }, }); ``` #### Using with ScopeTracker ```typescript import { parseSync } from "oxc-parser"; import { walk, ScopeTracker } from "oxc-walker"; const ast = parseSync("example.js", "const x = 1; function foo() { console.log(x) }"); const scopeTracker = new ScopeTracker(); walk(ast.program, { scopeTracker, enter(node) { if (node.type === "Identifier" && node.name === "x") { const declaration = scopeTracker.getDeclaration("x"); if (declaration) { console.log("Found reference to x declared at", declaration.start); } } }, }); ``` ``` -------------------------------- ### Initialize and Freeze ScopeTracker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/ScopeTracker.md Demonstrates initializing ScopeTracker and using freeze() to prepare for multi-pass analysis. Call freeze() after the first pass to prevent modifications during the second pass. ```typescript const scopeTracker = new ScopeTracker({ preserveExitedScopes: true }); // First pass: collect all declarations parseAndWalk( `function foo() { console.log(a) }; const a = 1`, "example.js", { scopeTracker } ); // Prepare for second pass scopeTracker.freeze(); // Second pass: analyze with complete scope information parseAndWalk(code, "example.js", { scopeTracker, enter(node) { if (node.type === "Identifier") { const decl = scopeTracker.getDeclaration(node.name); // decl is available even though function references a before its declaration } }, }); ``` -------------------------------- ### Tracking Function Parameters with ScopeTracker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/scope-tracker-nodes.md Demonstrates how to use ScopeTracker to identify and retrieve information about function parameters. This is useful for analyzing function signatures and parameter usage. ```typescript import { parseAndWalk, ScopeTracker, ScopeTrackerFunctionParam } from "oxc-walker"; const tracker = new ScopeTracker(); parseAndWalk("function foo(x, y) { return x + y; }", "example.js", { scopeTracker: tracker, enter(node) { if (node.type === "Identifier" && node.name === "x") { const decl = tracker.getDeclaration("x"); if (decl instanceof ScopeTrackerFunctionParam) { console.log("Parameter x of function", decl.fnNode.id?.name); } } }, }); ``` -------------------------------- ### Get Undeclared Identifiers in Function Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Retrieve a list of all identifiers used within a function that are not declared within that function's scope. ```typescript const undeclared = getUndeclaredIdentifiersInFunction(node); console.log(undeclared); // ['console', 'externalVar'] ``` -------------------------------- ### parseAndWalk(source, filename, callback, options?) Source: https://github.com/oxc-project/oxc-walker/blob/main/README.md Parses source code using oxc-parser, then walks the resulting AST. It accepts a callback function or options object for controlling the walk. ```APIDOC ## parseAndWalk(source, filename, callback, options?) Parse the source code using `oxc-parser`, walk the resulting AST and return the `ParseResult`. Overloads: - `parseAndWalk(code, filename, enter)` - `parseAndWalk(code, filename, options)` ```ts interface ParseAndWalkOptions { /** * The function to be called when entering a node. */ enter?: (node: Node, parent: Node | null, ctx: CallbackContext) => void; /** * The function to be called when leaving a node. */ leave?: (node: Node, parent: Node | null, ctx: CallbackContext) => void; /** * The instance of `ScopeTracker` to use for tracking declarations and references. */ scopeTracker?: ScopeTracker; /** * The options for `oxc-parser` to use when parsing the code. */ parseOptions?: ParserOptions; } ``` ``` -------------------------------- ### parseAndWalk(code, sourceFilename, callback | options) Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Parse source code and walk the resulting AST in a single step, with options for custom parsing and traversal callbacks. ```APIDOC ## parseAndWalk(code, sourceFilename, callback | options) ### Description Parses the provided code and traverses the resulting Abstract Syntax Tree (AST) in one operation. It supports both a simple callback for node processing and a more detailed options object for advanced configurations. ### Method Signature ```typescript parseAndWalk(code: string, filename: string, callback: WalkerEnter): ParseResult; parseAndWalk(code: string, filename: string, options: Partial): ParseResult; ``` ### Parameters * `code` (string) - The source code to parse and walk. * `filename` (string) - The name of the source file. * `callback` (WalkerEnter) - A function to be called for each node during the walk (simple form). * `options` (Partial) - An object for advanced configuration, including `parseSync`, `parseOptions`, `enter`, `leave`, and `scopeTracker`. ### Example ```javascript // Simple form parseAndWalk("const x = 1", "example.js", (node) => { console.log(node.type); }); // Full form const result = parseAndWalk("const x = 1", "example.js", { parseSync: customParser, parseOptions: { lang: "ts" }, enter(node) { /* ... */ }, leave(node) { /* ... */ }, scopeTracker: tracker, }); ``` ``` -------------------------------- ### Transform Specific Node Types Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/README.md Modify the AST during traversal by replacing nodes. This example shows how to replace `CallExpression` nodes with a transformed version. ```typescript walk(ast.program, { enter(node, parent, ctx) { if (node.type === "CallExpression") { this.replace(createOptimizedVersion(node)); } }, }); ``` -------------------------------- ### Importing Helper Functions from oxc-walker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/helper-functions.md Shows how to import key helper functions like getUndeclaredIdentifiersInFunction and parseAndWalk directly from the 'oxc-walker' package. ```typescript export { isBindingIdentifier, getUndeclaredIdentifiersInFunction, } from "./scope-tracker"; ``` ```typescript import { isBindingIdentifier, getUndeclaredIdentifiersInFunction, parseAndWalk, ScopeTracker, } from "oxc-walker"; ``` -------------------------------- ### Walk AST with Options Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Use the walk function to traverse an Abstract Syntax Tree (AST). You can provide options to customize the traversal, such as defining enter and leave callbacks for nodes, and integrating a scope tracker. ```typescript walk(ast.program, { enter(node, parent, ctx) { /* ... */ }, leave(node, parent, ctx) { /* ... */ }, scopeTracker: tracker, }); ``` -------------------------------- ### ScopeTracker: Get Declaration Details Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Retrieve specific declaration information for an identifier using getDeclaration. This can return details about variables, functions, or other declared entities. ```typescript const decl = tracker.getDeclaration("x"); if (decl instanceof ScopeTrackerVariable) { console.log("x is a variable at", decl.start); } else if (decl instanceof ScopeTrackerFunction) { console.log("x is a function"); } else if (decl) { console.log("x is a", decl.type); } else { console.log("x is undeclared"); } ``` -------------------------------- ### Initialize ScopeTracker (Default) Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/README.md Instantiate `ScopeTracker` for single-pass analysis. This is the default behavior and suitable for most use cases. ```typescript // Single-pass analysis (default) const tracker = new ScopeTracker(); ``` -------------------------------- ### WalkOptions Interface Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Defines the configuration options for the walk function, including enter and leave callbacks, and an optional scope tracker. ```typescript interface WalkOptions extends Partial<_WalkOptions> { /** * The function to be called when entering a node. */ enter: WalkerEnter; /** * The function to be called when leaving a node. */ leave: WalkerLeave; } interface _WalkOptions { /** * The instance of `ScopeTracker` to use for tracking declarations and references. * @see ScopeTracker * @default undefined */ scopeTracker: ScopeTracker; } ``` -------------------------------- ### Parse Options for parseAndWalk Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Illustrates configuration options for `parseAndWalk`, including language, source type, strict mode, and custom parsers. ```typescript parseAndWalk(code, "example.ts", { parseOptions: { lang: "ts", // Auto-detect from filename or specify sourceType: "module", // "script" | "module" (default: "module") strictMode: true, // Enable strict mode }, parseSync: customParser, // Override parser }); ``` -------------------------------- ### AST Transformation with oxc-walker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/README.md Modify an AST during traversal using `this.skip()` to skip nodes or `this.remove()` to remove them. This example skips function declarations and removes console.log calls. ```typescript import { parseAndWalk } from "oxc-walker"; parseAndWalk("const x = 1; console.log(x);", "example.js", { enter(node) { // Skip function bodies if (node.type === "FunctionDeclaration") { this.skip(); } // Remove all console.log calls if ( node.type === "CallExpression" && node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "console" ) { this.remove(); } }, }); ``` -------------------------------- ### ScopeTracker Constructor Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/ScopeTracker.md Initializes a new instance of the ScopeTracker. It can optionally accept configuration options to customize its behavior, such as preserving exited scopes. ```APIDOC ## Constructor ```typescript constructor(options?: ScopeTrackerOptions) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | `ScopeTrackerOptions` | No | `{}` | Configuration object. | | options.preserveExitedScopes | `boolean` | No | `false` | If true, exited scopes are kept in memory for multi-pass analysis. | ``` -------------------------------- ### Modifying AST with walk() using this.remove() Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/walk.md Demonstrates how to modify the AST during traversal by removing specific nodes. This example removes all `console.log` calls from the AST using `this.remove()` in the `enter` callback. ```typescript walk(ast.program, { enter(node, parent, ctx) { // Remove all console.log calls if ( node.type === "CallExpression" && node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "console" && node.callee.property.type === "Identifier" && node.callee.property.name === "log" ) { this.remove(); } }, }); ``` -------------------------------- ### Basic AST Traversal with oxc-walker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/README.md Use `parseAndWalk` to traverse an AST and execute enter/leave callbacks for each node. This is useful for simple analysis or logging. ```typescript import { parseAndWalk } from "oxc-walker"; parseAndWalk("const x = 1; console.log(x)", "example.js", { enter(node) { console.log(`Entering ${node.type}`); }, leave(node) { console.log(`Leaving ${node.type}`); }, }); ``` -------------------------------- ### Configure Walk Options with ScopeTracker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/README.md Pass an optional `ScopeTracker` instance to the `walk` function's options. This allows integrating scope tracking into your AST traversal. ```typescript walk(ast.program, { enter(node) { /* ... */ }, leave(node) { /* ... */ }, scopeTracker: optionalTracker, }); ``` -------------------------------- ### Get Current Scope Key Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/ScopeTracker.md Use `getCurrentScope` to retrieve the unique string key representing the current scope during AST traversal. This key reflects the scope's position in the hierarchy. ```typescript const scopeTracker = new ScopeTracker(); parseAndWalk("function foo() { const x = 1 }", "example.js", { scopeTracker, enter(node) { console.log(scopeTracker.getCurrentScope()); // "" (global) // "0" (function foo parameters) // "0-0" (function foo body) }, }); ``` -------------------------------- ### Import All at Once Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/module-exports.md Imports all available functions and types from the 'oxc-walker' package in a single statement. ```typescript import { walk, parseAndWalk, ScopeTracker, isBindingIdentifier, getUndeclaredIdentifiersInFunction, } from "oxc-walker"; ``` -------------------------------- ### Skipping Subtrees during AST Traversal Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/walk.md Shows how to prevent the walker from descending into child nodes of a specific node type using `this.skip()` within the `enter` callback. This example skips the body of function declarations. ```typescript walk(ast.program, { enter(node) { if (node.type === "FunctionDeclaration") { console.log(`Found function: ${node.id.name}`); this.skip(); // Don't traverse function body } }, }); ``` -------------------------------- ### Parse and walk directly with oxc-walker Source: https://github.com/oxc-project/oxc-walker/blob/main/README.md Use `parseAndWalk` to parse source code and traverse its AST in a single step. A callback function is provided for node visitation. ```js import { parseAndWalk } from "oxc-walker"; parseAndWalk("const x = 1", "example.js", (node, parent, ctx) => { // ... }); ``` -------------------------------- ### parseAndWalk with Simple Callback Form Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/parseAndWalk.md Use this form to pass an enter callback directly for basic AST traversal. It's suitable for simple analysis tasks where only node entry needs to be processed. ```typescript import { parseAndWalk } from "oxc-walker"; const result = parseAndWalk("const x = 1; console.log(x)", "example.js", (node) => { if (node.type === "VariableDeclarator") { console.log(`Declared: ${node.id.name}`); } }); console.log(result.program); // Access the parsed AST ``` -------------------------------- ### TypeScript Parsing Configuration Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/configuration.md Configures `parseAndWalk` to parse TypeScript code by setting `parseOptions.lang` to 'ts'. Demonstrates basic node type logging during traversal. ```typescript import { parseAndWalk } from "oxc-walker"; const result = parseAndWalk("const x: number = 1", "example.ts", { parseOptions: { lang: "ts" }, enter(node) { console.log(node.type); }, }); ``` -------------------------------- ### parseAndWalk() Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/module-exports.md Parses source code and walks the resulting AST in a single operation. This is an efficient way to process code without needing separate parsing and walking steps. ```APIDOC ## parseAndWalk() ### Description Parses source code and walks the resulting AST in a single operation. ### Signatures ```typescript function parseAndWalk(code: string, sourceFilename: string, callback: WalkerEnter): ParseResult; function parseAndWalk(code: string, sourceFilename: string, options: Partial): ParseResult; ``` ### Parameters * **code** (string) - The source code to parse and walk. * **sourceFilename** (string) - The name of the source file. * **callback** (WalkerEnter) - The enter callback function. * **options** (Partial) - Optional configuration for parsing and walking. ``` -------------------------------- ### Tracking Catch Clause Parameters with ScopeTracker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/scope-tracker-nodes.md Illustrates how to use ScopeTracker to identify and retrieve information about parameters declared in catch clauses. This is useful for error handling analysis. ```typescript import { parseAndWalk, ScopeTracker, ScopeTrackerCatchParam } from "oxc-walker"; const tracker = new ScopeTracker(); parseAndWalk("try { } catch (e) { console.log(e) }", "example.js", { scopeTracker: tracker, enter(node) { if (node.type === "Identifier" && node.name === "e") { const decl = tracker.getDeclaration("e"); if (decl instanceof ScopeTrackerCatchParam) { console.log("Catch parameter e declared at", decl.start); } } }, }); ``` -------------------------------- ### Walker leave Callback Methods Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-quick-reference.md Demonstrates methods available within the `leave` callback for AST traversal control. ```typescript walk(ast.program, { leave(node, parent, ctx) { this.replace(newNode); // Replace after children walked this.remove(); // Remove node }, }); ``` -------------------------------- ### Import All Types from Oxc Walker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Import all available types from the main 'oxc-walker' package. This includes types for walk options, callback contexts, enter/leave functions, and scope tracking. ```typescript import type { WalkOptions, WalkerCallbackContext, WalkerEnter, WalkerLeave, WalkerThisContextEnter, WalkerThisContextLeave, ScopeTrackerOptions, ScopeTrackerNode, } from "oxc-walker"; ``` -------------------------------- ### Main Module Exports Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/module-exports.md Exports from the main entry point (src/index.ts), including functions for identifier analysis, scope tracking classes, walker types, and parsing utilities. ```typescript // src/index.ts export { getUndeclaredIdentifiersInFunction, isBindingIdentifier, ScopeTrackerFunctionParam, ScopeTrackerFunction, ScopeTrackerVariable, ScopeTrackerIdentifier, ScopeTrackerImport, ScopeTrackerCatchParam, ScopeTracker, } from "./scope-tracker"; export type { ScopeTrackerOptions, ScopeTrackerNode, } from "./scope-tracker"; export type { WalkerThisContextEnter, WalkerThisContextLeave, WalkerCallbackContext, WalkerEnter, WalkerLeave, } from "./walker/base"; export type { WalkOptions } from "./walker/sync"; export { parseAndWalk, walk } from "./walk"; export type { Identifier } from "./walk"; ``` -------------------------------- ### ParseAndWalkOptions Interface Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Configuration options for the `parseAndWalk` function, extending `WalkOptions`. It includes settings for the parser and the parsing function itself. ```typescript interface ParseAndWalkOptions extends WalkOptions { /** * The options for `oxc-parser` to use when parsing the code. */ parseOptions: ParserOptions; /** * The `parseSync` implementation to use. Defaults to `parseSync` from `oxc-parser`, * falling back to `rolldown/utils` if `oxc-parser` is not installed. * * Provide this explicitly to avoid the runtime lookup or to use a different * compatible parser (e.g. `import { parseSync } from "rolldown/utils"`). */ parseSync: ParseSync; } ``` -------------------------------- ### Import Primary Exports from oxc-walker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/module-exports.md Import various functions, classes, and types from the main package entry point. ```typescript import { // Functions walk, parseAndWalk, isBindingIdentifier, getUndeclaredIdentifiersInFunction, // Classes ScopeTracker, ScopeTrackerVariable, ScopeTrackerFunction, ScopeTrackerFunctionParam, ScopeTrackerIdentifier, ScopeTrackerImport, ScopeTrackerCatchParam, // Types WalkOptions, WalkerCallbackContext, WalkerEnter, WalkerLeave, WalkerThisContextEnter, WalkerThisContextLeave, ScopeTrackerOptions, ScopeTrackerNode, Identifier, } from "oxc-walker"; ``` -------------------------------- ### Basic Scope Tracking with Oxc-Walker Source: https://github.com/oxc-project/oxc-walker/blob/main/README.md Demonstrates how to use ScopeTracker to find the declaration of a variable 'x' when it's referenced within a function call. Requires importing parseAndWalk and ScopeTracker. ```typescript import { parseAndWalk, ScopeTracker } from "oxc-walker"; const scopeTracker = new ScopeTracker(); parseAndWalk("const x = 1; function foo() { console.log(x) }", "example.js", { scopeTracker, enter(node, parent) { if (node.type === "Identifier" && node.name === "x" && parent?.type === "CallExpression") { const declaration = scopeTracker.getDeclaration(node.name); console.log(declaration); // ScopeTrackerVariable } }, }); ``` -------------------------------- ### Multi-Pass Analysis with ScopeTracker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/configuration.md Illustrates a multi-pass analysis strategy. The first pass collects declarations, `freeze()` is called, and the second pass analyzes with complete scope information. Requires `preserveExitedScopes: true`. ```typescript import { parseAndWalk, ScopeTracker } from "oxc-walker"; const tracker = new ScopeTracker({ preserveExitedScopes: true }); // Pass 1: collect declarations parseAndWalk(code, "example.js", { scopeTracker: tracker }); tracker.freeze(); // Pass 2: analyze with complete scope info parseAndWalk(code, "example.js", { scopeTracker: tracker }); ``` -------------------------------- ### ScopeTracker Source: https://github.com/oxc-project/oxc-walker/blob/main/README.md A utility for tracking scopes and declarations during AST traversal, designed for use with the `walk` function. ```APIDOC ### ScopeTracker A utility to track scopes and declarations while walking an AST. It is designed to be used with the `walk` function from this library. ```ts interface ScopeTrackerOptions { /** * If true, the scope tracker will preserve exited scopes in memory. * @default false */ preserveExitedScopes?: boolean; } ``` ``` -------------------------------- ### Configure Parse Options for parseAndWalk Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/README.md Customize parsing behavior within `parseAndWalk` by providing `parseOptions`. This allows specifying language, strict mode, or a custom parser. ```typescript parseAndWalk(code, "example.ts", { parseOptions: { lang: "ts", strictMode: true }, parseSync: customParser, enter(node) { /* ... */ }, }); ``` -------------------------------- ### Single-Pass Analysis with ScopeTracker Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/configuration.md Demonstrates a single-pass analysis using `parseAndWalk` with a `ScopeTracker`. This pattern is suitable for tasks that can be completed in one traversal. ```typescript import { parseAndWalk, ScopeTracker } from "oxc-walker"; parseAndWalk(code, "example.js", { scopeTracker: new ScopeTracker(), enter(node) { // Query during traversal }, }); ``` -------------------------------- ### ScopeTracker Default Configuration Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/configuration.md Instantiate ScopeTracker without options to use default behavior, discarding scopes after exit. This is suitable for single-pass analysis. ```typescript import { ScopeTracker } from "oxc-walker"; const tracker = new ScopeTracker(); // Scopes are discarded when exited to save memory ``` -------------------------------- ### Peer Dependencies Configuration Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/module-exports.md Defines optional peer dependencies for oxc-parser and rolldown, specifying version requirements and marking them as optional. ```json { "peerDependencies": { "oxc-parser": ">=0.98.0", "rolldown": ">=1.0.0" }, "peerDependenciesMeta": { "oxc-parser": { "optional": true }, "rolldown": { "optional": true } } } ``` -------------------------------- ### parseAndWalk with Custom Parser Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/parseAndWalk.md Integrate a custom parser function, such as one from 'rolldown/utils', into parseAndWalk. This allows using alternative parsing implementations or pre-configured parsers. ```typescript import { parseAndWalk } from "oxc-walker"; import { parseSync } from "rolldown/utils"; const result = parseAndWalk("const x = 1", "example.js", { parseSync, enter(node) { console.log(node.type); }, }); ``` -------------------------------- ### Multi-Pass Scope Analysis with Oxc-Walker Source: https://github.com/oxc-project/oxc-walker/blob/main/README.md Illustrates a two-pass approach for scope analysis using ScopeTracker, first collecting hoisted declarations and then analyzing references. This is useful for accurately resolving variables declared after their first use. Requires importing parseAndWalk, ScopeTracker, and walk. ```typescript import { parseAndWalk, ScopeTracker, walk } from "oxc-walker"; const code = ` function foo() { console.log(a) } const a = 1 `; const scopeTracker = new ScopeTracker({ preserveExitedScopes: true, }); // pre-pass to collect hoisted declarations const { program } = parseAndWalk(code, "example.js", { scopeTracker, }); // freeze the scope tracker to prevent further modifications // and prepare it for second pass scopeTracker.freeze(); // main pass to analyze references walk(program, { scopeTracker, enter(node) { if (node.type === "CallExpression" && node.callee.type === "MemberExpression" /* ... */) { const declaration = scopeTracker.getDeclaration("a"); console.log(declaration); // ScopeTrackerVariable; would be `null` without the pre-pass } }, }); ``` -------------------------------- ### getCurrentScope(): string Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/api-reference/ScopeTracker.md Returns the unique string key representing the current scope. This key follows a hierarchical format indicating the scope's position in the AST. ```APIDOC ## getCurrentScope(): string Returns the key of the current scope. ```typescript getCurrentScope(): string ``` **Returns:** `string` — The scope key (e.g., `""`, `"0"`, `"0-1-2"`). **Example:** ```typescript const scopeTracker = new ScopeTracker(); parseAndWalk("function foo() { const x = 1 }", "example.js", { scopeTracker, enter(node) { console.log(scopeTracker.getCurrentScope()); // "" (global) // "0" (function foo parameters) // "0-0" (function foo body) }, }); ``` ``` -------------------------------- ### Type-Safe Walker Callback Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/README.md Demonstrates how to use TypeScript types for AST nodes and walker context. This ensures type safety when implementing custom traversal logic. ```typescript import type { Node } from "oxc-parser"; import type { WalkerCallbackContext } from "oxc-walker"; function analyze(node: Node, parent: Node | null, ctx: WalkerCallbackContext) { console.log(`At index ${ctx.index} within parent property ${String(ctx.key)}`); } ``` -------------------------------- ### Walk Function Basic Usage Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/configuration.md Use the walk function with `enter` and `leave` callbacks to traverse an AST. An optional `scopeTracker` can be provided for declaration and reference tracking. ```typescript import { walk } from "oxc-walker"; walk(ast.program, { enter(node) { console.log(`Entering ${node.type}`); }, leave(node) { console.log(`Leaving ${node.type}`); }, scopeTracker: optionalTracker, }); ``` -------------------------------- ### ScopeTracker with parseAndWalk Usage Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/types.md Shows how to integrate ScopeTracker with parseAndWalk to retrieve declarations for identifiers during traversal. It logs the type of the found declaration. ```typescript import { parseAndWalk, ScopeTracker } from "oxc-walker"; const tracker = new ScopeTracker(); parseAndWalk(code, "example.js", { scopeTracker: tracker, enter(node) { if (node.type === "Identifier") { const decl: ScopeTrackerNode | null = tracker.getDeclaration(node.name); if (decl) { console.log(`Found ${decl.type}`); } } }, }); ``` -------------------------------- ### Initialize ScopeTracker (Preserve Exited Scopes) Source: https://github.com/oxc-project/oxc-walker/blob/main/_autodocs/README.md Instantiate `ScopeTracker` with `preserveExitedScopes: true` for multi-pass analysis. This option retains scope information even after a scope has been exited, which can be useful for certain advanced analysis scenarios. ```typescript // Multi-pass analysis with scope preservation const tracker = new ScopeTracker({ preserveExitedScopes: true }); ```