Antlr v3 & Trees (was: [antlr-interest] if-then-else - Grammar generates faulty parser code)

Monty Zukowski monty at codetransform.com
Thu Apr 22 22:31:40 PDT 2004


On Apr 22, 2004, at 9:26 PM, Terence Parr wrote:

> forRule : #(FOR (expr)? (expr)? (expr)?) ;
>
> ??  Probably not as the grammar is inherently ambiguous.  Position has
> "meaning" in this case.
>
> Is that a good example?

So let's work this through with parser rules and tree parser rules.  We 
could have, instead, left the semicolons:

forRule : "for"^ (expr)? SEMI (expr)? SEMI (expr)? SEMI ;
forRule : #(FOR (expr)? SEMI (expr)? SEMI (expr)? SEMI) ;

This uses more space but is easiest to read.

Or we could have created new imaginary roots:
forRule! : f:"for" (e1:expr )? SEMI (e2:expr)? SEMI (e3:expr)? SEMI
{##=#(f,#([FOR_INIT],e1),#([FOR_TEST],e2),#([FOR_UPDATE],e3));} ;
forRule : #(FOR (#(FOR_INIT expr))? (#(FOR_TEST expr))? (#(FOR_UPDATE 
expr))?) ;

This uses more space than the following but doesn't force us to add 
EMPTY_EXPR to the expr rule.  Not a win for C since other places use 
empty expressions too, but could be relevant to other languages, maybe.

Or, as you did, we could force EMPTY_EXPR in place of the missing expr:
forRule! : f:"for" (e1:expr)? SEMI (e2:expr)? SEMI (e3:expr)? SEMI
{
	if (e1==null) e1=#[EMPTY_EXPR];
	if (e2==null) e2=#[EMPTY_EXPR];
	if (e3==null) e3=#[EMPTY_EXPR];
	##=#(f,e1,e2,e3);
} ;
forRule : #(FOR (expr)? (expr)? (expr)?) ;

This one is easy to read as a tree grammar and uses the least amount of 
space in the tree.

Monty Zukowski

ANTLR & Java Consultant -- http://www.codetransform.com
ANSI C/GCC transformation toolkit -- 
http://www.codetransform.com/gcc.html
Embrace the Decay -- http://www.codetransform.com/EmbraceDecay.html




 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/antlr-interest/

<*> To unsubscribe from this group, send an email to:
     antlr-interest-unsubscribe at yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/
 



More information about the antlr-interest mailing list