Traverse and mutate the AST with Handlebars.Visitor
masterThe Handlebars.Visitor class allows you to traverse the AST. By extending it, you can override specific node handler methods to inspect or modify the tree.
Non-mutation mode
In the default mode, you override methods (like PartialStatement) to perform actions as the visitor traverses the tree. The visitor maintains a parents array containing the current node's ancestors, with the most recent parent listed first.
Mutation mode
By setting the mutating field to true, you can modify the AST during traversal. Handler methods in mutation mode return:
- A valid AST node: Replaces the current node with the returned node.
false: Removes the current node from the tree.undefined: Leaves the node unchanged.
When implementing mutation mode, use the acceptKey, acceptRequired, and acceptArray helpers to manage conditional overwrites and sanity checks.
var Visitor = Handlebars.Visitor;
function ImportScanner() {
this.partials = [];
}
ImportScanner.prototype = new Visitor();
// Override specific node handlers
ImportScanner.prototype.PartialStatement = function (partial) {
this.partials.push({ request: partial.name.original });
// Call the prototype to continue traversal
Visitor.prototype.PartialStatement.call(this, partial);
};
var scanner = new ImportScanner();
scanner.accept(ast);