Tom Copeland's Recent Posts

RSS Feeds

« A JavaCC/JJTree bug fixed | Main | JavaCC/JJTree file generation bug fix »

Better JJTree Visitors

JavaCC comes with a built in tree builder, JJTree.  One of the nice bits about JJTree is that it will generate a visitor implementation so you can easily traverse the abstract syntax tree.  However, the interface that JJTree generates looks like this:

public interface FooVisitor {
  public Object visit(SimpleNode node, Object data);
  public Object visit(ASTBar node, Object data);
}

Since that second parameter is an Object, you're always downcasting if you want to use it.  For example, if you're passing around a Map, you'll need to do something like this in your visitor:

public class MyVisitor extends MyVisitorAdapter {
  public Object visit(ASTBar node, Object data) {
    Map myMap = (Map)data;
    // do stuff with the Map
  }
}

But thanks to Paul Cager, JJTree has a new VISITOR_DATA_TYPE option.  Just set it like this:

options {
  VISITOR=true;
  MULTI=true;
  VISITOR_DATA_TYPE="java.util.Map";
}

With this option in place, the generated visitor interface looks like this:

public interface FooVisitor {
  public Object visit(SimpleNode node, java.util.Map data);
  public Object visit(ASTBar node, java.util.Map data);
}

And now your visitor implementation can look like this - no cast necessary!

public class MyVisitor extends MyVisitorAdapter {
  public Object visit(ASTBar node, java.util.Map data) {
    // do stuff with the Map
  }
}

Note that you'll want to declare a fully-qualified type, otherwise you'll need to go back and fill in the import statements.  So it's more readable, more type-safe, and it probably yields a small runtime performance improvement due to the eliminated cast.  You can grab a javacc.jar built from CVS here if you want to give it a whirl.  Props to Paul for this and his other recent bug fixes!

Using JavaCC or JJTree?  Get the JavaCC book!

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00d83451d3c069e200e55088b9088834

Listed below are links to weblogs that reference Better JJTree Visitors:

Comments

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been saved. Comments are moderated and will not appear until approved by the author. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

Comments are moderated, and will not appear until the author has approved them.