Search code examples
javaparsingabstract-syntax-treeeclipse-jdttree-traversal

In Eclipse JDT Java parser, is it possible to traverse the AST node by node without the using of visitors?


The standard way to access information on Nodes through the Eclipse JDT API is with Visitor's pattern. For example:

unit.accept(new MyVisitorAdapter<Object>() {
  @Override public void visit(MethodCallExpr node, Object arg) {
    System.out.println("found method call: " + node.toString());
  }
}, null);

In this case, to visit a node I need to specify what type of node I'm interested (MethodCallExpr for this case). But, to proceed to access node information in a generic way, I should override all the visit() method, potentially enumerating every kind of node available in the Eclipse JDT API. A full example of where it is done is found here.

In this context, although not exactly in the same domain of Code Coverage, I would like to have control over the traversal done by the Eclipse JDT Java Parser. I would like to walk through the AST nodes, potentially passing by all of them, selecting what I want, but without to restrict to a type, as shown in the code above. Is it possible? Is there a standard way to do that through the Eclipse JDT API?


Solution

  • If you don't care about node types, override any of ASTVisitor.preVisit(ASTNode), ASTVisitor.preVisit2(ASTNode), ASTVisitor.postVisit(ASTNode).