[antlr-interest] Flattening my expression tree.

keith smillie keith.smillie at gmail.com
Thu May 13 05:04:53 PDT 2010


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


More information about the antlr-interest mailing list