[antlr-interest] conditional tree rewrite

Gavin Lambert antlr at mirality.co.nz
Fri Sep 18 16:32:07 PDT 2009


At 00:50 19/09/2009, Marco Trudel wrote:
 >Or do you only mean in expression trees like the one I mentioned 

 >from "ART_EXPRESSION -> ART_ASSIGNMENT_EXPRESSION -> ... ->
 >ART_CONSTANT -> 0" for a constant? If so, than that's exactly my 

 >question: how to do the tree rewrite to only get "ART_EXPRESSION 

 >-> ART_CONSTANT -> 0"? I don't see a way to insert the imaginary 

 >tokens like e.g. "ART_LOGICAL_OR_EXPRESSION" only if it's a
 >logical or expression for this rule:
 >
 >logical_or_expression
 >	: logical_and_expression ('||' logical_and_expression)*
 >	;
 >
 >Because it's not a logical_or_expression if the parenthesis part 
is
 >not found.

logical_or_expression
   : logical_and_expression ('||'^ logical_and_expression)*
   ;

This is the best option; it will use the operator itself as the 
tree root, and only generate a subtree if the operator is 
present.  And it will generate nested trees appropriately.

It's slightly better if you use a named token rather than a 
literal:

LOGICAL_OR: '||';
logical_or_expression
   : logical_and_expression (LOGICAL_OR^ logical_and_expression)*
   ;

Finally, if you really want to do the rewrite "manually", you can:

logical_or_expression
   : (logical_and_expression -> logical_and_expression)
     ('||' b=logical_and_expression -> ^('||' 
$logical_or_expression $b))*
   ;

You can use this final pattern to use an imaginary token as the 
root rather than using the operator, if you really want to do 
that.  But it seems a bit silly when the operator is usually a 
good enough identifier all by itself.



More information about the antlr-interest mailing list