[antlr-interest] ast for pre/postfix expressions

David Holroyd dave at badgers-in-foil.co.uk
Thu Mar 27 06:07:42 PDT 2008


On Thu, Mar 27, 2008 at 10:07:21AM +0100, Felix Dorner wrote:
> I am currently creating AST's for pre and postfix expressions, like in Java:
> 
> a++
> ++a
> 
> my current grammar looks like that:
> 
> prefixExpression
>    :    prefixOp^?  postfixExpression;
> 
> postfixExpression
>    :    primaryExpression (('++'|'--')^)?;
> 
> The problem is that this creates identical trees for the two examples 
> above. Since this is the first time I really work with AST construction 
> I am not sure how to solve this problem. Should I just introduce two 
> imaginary tokens PRE and POST, and change the grammar to this:
> 
> prefixExpression
>    :    prefixOp postfixExpression -> ^(PRE prefixOp postfixExpression)
>    |    postfixExpression
>    ;
> 
> postfixExpression
>    :    primaryExpression ('++') -> ^(POST primaryExpression '++')
>    |    ...
>    |    primaryExpression
> 
> 
>  A secondary question is: Is it possible to singularize alternatives 
> using '?'  for each of the above rules? How would the rewrites look?

If it helps, I have a grammar where I've structured it a bit like this,

  unaryExpression
	:	in=INC unaryExpression -> ^(PRE_INC[$in] unaryExpression)
	|	de=DEC unaryExpression -> ^(PRE_DEC[$de] unaryExpression)
	|	...
	|	postfixExpression
	;

  postfixExpression
	:	(primaryExpression -> primaryExpression)
		( ... )*
		( 	in=INC -> ^(POST_INC[$in] $postfixExpression)
	 	|	de=DEC -> ^(POST_DEC[$de] $postfixExpression)
		)?


PRE_INC, PRE_DEC, POST_INC and POST_DEC are imaginary token types.


ta,
dave

-- 
http://david.holroyd.me.uk/


More information about the antlr-interest mailing list