Traverser module 🌀oniguruma-parser/traverser
September 22, 2025 · View on GitHub
Provides a traversal and transformation API (using the vistor pattern) for OnigurumaAst objects created by this library.
Contents
Import
import {traverse} from 'oniguruma-parser/traverser';
Details
The traverse function takes three arguments:
root: Usually anOnigurumaAst, but can also be a midpoint in an AST.visitor: An object with node types as keys, and functions as values. These visitor node type functions can transform the AST in-place.state: Optional. Any non-primitive value, ornull. It's passed to all of the visitor's node type functions as their second argument.
The root argument is returned. It might have been modified by the visitor's node type functions.
Note: The full description of the
traversefunction's types is complex. Refer totraverse.tsif needed.
The visitor's keys can be any node type (ex: CapturingGroup) or '*'. Their values can be either functions that accept arguments path and state, or objects with enter and/or exit methods (that offer more control over when the functions run during traversal).
The path argument contains a variety of properties (node, parent, etc.) and methods (remove, replaceWith, etc.).
For example, to add a parent property to every node:
import {toOnigurumaAst} from 'oniguruma-parser';
import {traverse} from 'oniguruma-parser/traverser';
const ast = toOnigurumaAst('^.');
traverse(ast, {
'*'({node, parent}) {
node.parent = parent;
},
});
Or, to swap all a and . nodes:
import {toOnigurumaAst} from 'oniguruma-parser';
import {createCharacter, createCharacterSet} from 'oniguruma-parser/parser';
import {traverse} from 'oniguruma-parser/traverser';
const charCode = 'a'.codePointAt(0);
const ast = toOnigurumaAst('a.');
traverse(ast, {
Character({node, replaceWith}) {
if (node.value === charCode) {
replaceWith(createCharacterSet('dot'));
}
},
CharacterSet({node, replaceWith}) {
if (node.kind === 'dot') {
replaceWith(createCharacter(charCode));
}
},
});
Note:
NodeType() {…}is shorthand forNodeType: {enter() {…}}.
Note: For additional examples, check out the optimizer's list of optimization transforms.
Node types
*: Specific to the traverser; used to visit any node typeAbsenceFunctionAlternativeAssertionBackreferenceCapturingGroupCharacterCharacterClassCharacterClassRangeCharacterSetDirectiveFlagsGroupLookaroundAssertionNamedCalloutQuantifierRegex: The root nodeSubroutine
Many node types are subdivided by other properties; especially kind. Types for each node type are defined in the parser module.
Path
Note: Refer to
traverse.tsfor more details.
Properties
nodeparentkeycontainerroot
Methods
removeremoveAllNextSiblingsremoveAllPrevSiblingsreplaceWithreplaceWithMultipleskip
About
Created by Steven Levithan and contributors.
If you want to support this project, I'd love your help by contributing improvements (guide), sharing it with others, or sponsoring ongoing development.
MIT License.