[antlr-interest] to stop walking into a subtree
Gary Miller
miller.garym at gmail.com
Tue Apr 5 18:13:19 PDT 2011
Hi Porosh,
One way to do this is to skip the walk of the second operand (op2) is
the tree grammar and call some java code to continue the walk if
necessary. See example (this is sample code and is not expected to
compile as is) below.
Question: Does anyone know and a way this can be done without needing
to create a new TreeNodeStream? Maybe using a predicate to acess the
op2 without changing the position in the TreeNodeStream?
Regards
Gary
Sample code.
@members {
boolean continueBooleanexpression(TreeParser walker, Tree op) throws
RecognitionException {
// Save the current TreeNodeStream
TreeNodeStream tns = walker.getTreeNodeStream();
boolean result =
try {
CommonTreeNodeStream nodes = new CommonTreeNodeStream(op);
nodes.setTokenStream(walker.getTreeNodeStream().getTokenStream());
// Use the same walker so state (scope, member etc.) is preserved.
walker.setTreeNodeStream(nodes);
// Continue the walk
// Probably doesn't return a boolean,
// might need to be something like walker.booleanexpression().result;
result = walker.booleanexpression();
} finally {
// Resort original TreeNodeStream
walker.setTreeNodeStream(tns);
}
return result;
}
}
booleanexpression returns[boolean result]
: ^(AND op1=booleanexpression op2=.)
{
if( $op1 ) {
boolean op2Result = continueBooleanexpression(this, $op2);
if( op2Result ) {
result = true;
} else {
result =false;
}
} else {
result = false;
}
}
;
> booleanexpression returns[boolean result]
> :* ^(AND op1 = booleanexpression op2 = booleanexpression) {if(op1&&op2) result = *> true; else result =false;}
> ;
>
> My question:
> I want to stop walking once I found op1 as false. In that case, I don't need to
> evaluate op2 anymore, the result is false anyway.
>
> Is there any way to implement this?
More information about the antlr-interest
mailing list