[antlr-interest] Flattening my expression tree.

Jim Idle jimi at temporal-wave.com
Thu May 13 06:27:28 PDT 2010


Rather than use rewrite operators, use the operators themselves. The names of the rules are really parse points (and so they appear in the parse tree)and not AST node points. So:



expression
   : assignmentExpression
   -> ^(EXPRESSION assignmentExpression)
   ;

assignmentExpression
   : listConcatExpression (ASSIGN^ listConcatExpression )*
   ;

And so on...

Jim

> -----Original Message-----
> From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-
> bounces at antlr.org] On Behalf Of keith smillie
> Sent: Thursday, May 13, 2010 5:05 AM
> To: antlr-interest at antlr.org
> Subject: [antlr-interest] Flattening my expression tree.
> 
> Hi All,
> 
> I have a simple grammar which describes expressions. Everything seems
> fine
> but the resulting tree is very verbose and I was wondering if someone
> could
> suggest how to flatten it.
> 
> The expression part of the grammar looks something like this, with the
> expressions nested in order of precedence.
> 
> expression
>   : assignmentExpression
>   -> ^(EXPRESSION assignmentExpression)
>   ;
> 
>  assignmentExpression
>   : x+=listConcatExpression (ASSIGN x+=listConcatExpression )*
>   -> ^(ASSIGNMENT_EXPRESSION $x+)
>   ;
> 
> listConcatExpression
>   : x+=logicalExpression (COLON x+=logicalExpression)*
>   -> ^(LIST_EXPRESSION $x+)
>   ;
> 
> logicalExpression
>   : x+=relationalExpression (o1=logicalOperators
> x+=relationalExpression)*
> 
>   -> ^(LOGICAL_EXPRESSION $o1* $x+)
>   ;
> 
> If I parse an expression such as: '1 + 2' I get the following tree
> which
> seems far too verbose.
> 
> ASSIGNMENT_EXPRESSION
>         LIST_EXPRESSION
>                 LOGICAL_EXPRESSION
>                         RELATIONAL_EXPRESSION
>                                 ADDITION_EXPRESSION
>                                         +
>                                         MULTIPLY_EXPRESSION
>                                                 UNARY_EXPRESSION
> 
> SUBSCRIPT_EXPRESSION
> 
>                                                                 NUMBER
> 
> 1
>                                         MULTIPLY_EXPRESSION
>                                                 UNARY_EXPRESSION
> 
> SUBSCRIPT_EXPRESSION
> 
>                                                                 NUMBER
> 
> 2
> 
> I would like the resulting tree to be flattened into something like the
> following. Has anyone got any suggestions?
> 
> ADDITION_EXPRESSION
>         +
>         NUMBER
>                 1
>         NUMBER
>                 2
> 
> Regards, Keith
> 
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-
> email-address





More information about the antlr-interest mailing list