While working with Esprima JavaScript Parser, which generates an AST in JSON format from JS source code, I noticed that it would be handy if I could register the type of a node (string) and trigger events when this type of node is visited, such as:
ASTFramework.on("Identifier", function(evt){
/*Some code here*/
});
By making some research, it seems that JSHint implements internally such functionality, but is not available from its API. Are there any suggestions on this?
EDIT: What I want to do, is to be able to register events in order to be fired when an AST node is visited. In simple words, a framework that triggers events in specific JSON node visiting would be sufficient for that case.
The closest thing I found searching for AST node traversing was the tool estraverse, which gave me the ability to visit the nodes and check the type in order to make actions:
//Using require from Node.js here to add module.
var estraverse = require("estraverse");
//Rest of code....
estraverse.traverse(astTree, {
enter: function (node) {
if(node.type == "Identifier") {
//Do something
} else if(node.type == "Literal") {
//Do something else, etc
}
}
});
Because estraverse
visits all nodes (probably using DFS), it is pretty easy to specify which types are wanted to be considered for actions, even if they are deeply nested inside others.