[antlr-interest] add a tree visitor?

Andy Tripp antlr at jazillian.com
Tue Oct 28 08:15:03 PDT 2008


Terence Parr wrote:
> Howdy, as part of my tree grammar filter mode, I need an external tree  
> visitor. It's just a depth first walk that triggers a pattern match  
> for each node as it walks back up the tree. I might as well make it a  
> generic action, which means I need an interface in Java. [java doesn't  
> have function pointers...sigh]
> 
>      public interface TreeVisitorAction {
>          public void visit(Object t);
>      }
> 
> Then the depth first recursive walk can trigger a generic action after  
> visiting the children, us, doing a bottom-up walk:
> 
>     public static void visit(CommonTree t, TreeVisitorAction action) {
>          if ( t.getChildCount()>0 ) {
>              List children = t.getChildren();
>              for (int i=0; i<children.size(); i++) {
>                  CommonTree child = (CommonTree)children.get(i);
>                  filter(child, action);
>              }
>          }
>          action.visit(t);
>      }
> 
> Is this a reasonable bit of code to insert in the main distribution?   
> C and other languages can use function pointers to perform the true  
> intent of the interface.

Yep, that's the Visitor design pattern...seems like a good thing to add.
The TreeVisitorAction method is usually called "accept()", though.
And the Java 1.5 foreach and generics would make the code cleaner.

Andy


More information about the antlr-interest mailing list