[antlr-interest] expression tree question

Don Caton dcaton at shorelinesoftware.com
Fri Jan 14 06:15:52 PST 2005


Thomas:

You need separate rules for operators at difference precedence levels.  Only
group operators in the same rule that share the same precedence level.  Ex:

  expression:            addingExpression;
  addingExpression:      multiplyingExpression ( ( ADD^ | SUBT^ )
multiplyingExpression );
  multiplyingExpression: primaryExpression ( ( MULT^ | DIV^ )
primaryExpression );
  primaryExpression:     literal | ID | whatever...

You don't really need the expression rule, I just do it because it serves as
a sort of "entry point" into the expression rules, which are usually
non-trivial.

The presence levels go higher the deeper you get into the rules.  IOW, the
primaryExpression rule has the highest presence, followed by the
multiplication operators, and the addition operators have the lowest
presence.

Within the rule, ADD and SUBT for example have equal precedence.

Don

 

> -----Original Message-----
> From: antlr-interest-bounces at antlr.org 
> [mailto:antlr-interest-bounces at antlr.org] On Behalf Of Thomas Rolfs
> Sent: Friday, January 14, 2005 1:22 AM
> To: ANTLR Interest
> Subject: [antlr-interest] expression tree question
> 
> 
> This is a very simplified version of my expression grammar.
> 
> atom
>   : ...
>   ;
> 
> relationalExpression
>   : atmo ((EQUALS^|NOT_EQUALS^|GT^|GTE^|LESS^|LTE^) atom)*
>   ;
> 
> expression
>   : relationalExpression ((AND^|OR^) relationalExpression)*
>   ;
> 
> 
> The expression:
> 
>  1 and 2 and 3 and 4
> 
> creates the tree:
> 
>  <and <and < and 1 2 > 3 > 4 >
> 
> but I would like to have:
> 
>  < and 1 < and 2 < and 3 < and 4>>>>
>  
> What is the best way to do this?
> 
> I can get the desired tree by changing the rule to:
> 
> expression
>   : relationalExpression ((AND^|OR^) expression)*
>   ;
> 
> but I'm guessing that operator precedence will be broken.
> 
> Thanks in advance.
> --
> Thomas Rolfs
> 
> 




More information about the antlr-interest mailing list