[antlr-interest] add a tree visitor?
Terence Parr
parrt at cs.usfca.edu
Thu Oct 23 18:12:40 PDT 2008
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.
Such a plain "visit every node" visitor is not particularly useful
unless the triggered action does something interesting. In my case, I
tell it to try to match one of the tree patterns:
public static void filter(CommonTree t) {
filter(t, new TreeVisitorAction() {
public void visit(Object t) { match((CommonTree)t); }
});
}
where match(t) creates a tree parser and tries to match that subtree
to one of the patterns.
Ter
More information about the antlr-interest
mailing list