[antlr-interest] Tree construction

Marcin Rzeźnicki marcin.rzeznicki at gmail.com
Mon Dec 14 19:16:59 PST 2009


Hi to you all dear antlr-interest members,
I am wondering whether it is possible to specify somehow where AST
nodes should be attached. Let me explain my problem on this short
example.
Let's consider expressions like i += 5. I want to build AST that
breaks this up into simple operation, like STORE and MUL in this case.
In other words, I want my final AST for this case to be like the one
below:
^(STORE i ^(MUL i 5)).
Grammar part which is responsible for parsing these expressions:
expression
  :
  conditionalExpression  ( assignmentOperator expression  )?
  ;

assignmentOperator
  :
  EQUALS
  |  PLUS_EQUALS
  | MINUS_EQUALS
 ...
;

I could not find any clean way to achieve what I wanted. Finally, I
came up with something that works but is utmost ugly:

expression
  :
  ( lhs = conditionalExpression
      -> $lhs )
  (
    op = assignmentOperator[$lhs.tree] rhs = expression
      -> {$op.start.getType() != EQUALS}?
        ^(
          STORE[$op.start] $lhs
          ^( $op $rhs )
         )
      ->
        ^( STORE[$op.start] $lhs $rhs )
  )?
  ;

assignmentOperator[CommonTree leftHand]
  :
  EQUALS
    ->
  | op = PLUS_EQUALS
    ->
      ^( ADD[$op] {$leftHand} )
  | op = MINUS_EQUALS
    ->
      ^( SUB[$op] {$leftHand} )
  ///
  ;

I hope you share my pain :-) If I could move the actual tree
generation to assignmentOperator, it would give me much cleaner result
- but for now, due to facts that I am not knowing right hand side
expression in advance and I am not able to append it to the correct
place in the resulting tree, I think that this is impossible.
So here comes the question. Can you see any better way to achieve the
desired effect? I'll be happy to hear your opinions and share your
experience. Thank you in advance.

-- 
Greetings
Marcin Rzeźnicki


More information about the antlr-interest mailing list