ast-traverse.js
Simple but flexible AST traversal with pre and post visitors.
Works in node and browsers.
Usage
var ast = require("esprima").parse("f(1, x) + 2");
var traverse = require("ast-traverse");
traverse(ast, {pre: function(node, parent, prop, idx) {
console.log(node.type + (parent ? " from parent " + parent.type +
" via " + prop + (idx !== undefined ? "[" + idx + "]" : "") : ""));
}});
console.log();
var indent = 0;
traverse(ast, {
pre: function(node) {
console.log(Array(indent + 1).join(" ") + node.type);
indent += 4;
},
post: function() {
indent -= 4;
}
});
console.log();
traverse(ast, {
pre: function(node) {
console.log(node.type);
},
skipProperty: function(prop, node) {
return prop === "parent" || prop === "expression";
}
});
Installation
Node
Install using npm
npm install ast-traverse
var traverse = require("ast-traverse");
Browser
Clone the repo and include it in a script tag
git clone https://github.com/olov/ast-traverse.git
<script src="ast-traverse/ast-traverse.js"></script>