[antlr-interest] How do I skip a subtree walking in a tree grammar?
Gavin Lambert
antlr at mirality.co.nz
Mon Mar 16 12:13:58 PDT 2009
At 06:34 17/03/2009, Shihwei Li wrote:
>I have a tree grammar to evaluate a boolean expression. What I
>want to do is to implement 'conditional' boolean expression:
>say the expression is 'A and B', then if the evaluation of A is
>already false, I want to skip the evaluation (walking) of B
>subtree. How do I do that?
>
>It seems that I can't insert an action like:
> ^( AND a=bool_exp { if (!a) return false; } b=bool_exp) {
> $value = (a && b); },
>because it messes up the token stream for further tree walking.
You need to specify alternative paths. (NEVER use a return
statement in a grammar action.)
ignore: . | ^(. ignore*);
bool_exp returns [boolean value]
: ^(OR a=bool_exp
( {$a.value}? => ignore { $value = true; }
| b=bool_exp { $value = $b.value; }
))
| ^(AND a=bool_exp
( {$a.value}? => b=bool_exp { $value = $b.value; }
| ignore { $value = false; }
))
;
(You probably don't actually need the references to 'ignore',
since you're ignoring the trailing end of the subtree. But it's
useful in cases where you need to ignore a bit in the middle and
then parse something else afterwards.)
More information about the antlr-interest
mailing list