[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: shift/reduce problem

yuntao wrote:

> I am using sablecc to parse some if statements, the grammar is as follows:
>   if_statement =
>    {if} if general_expression then [true]:statement |
>    {if_else} if general_expression then [true]:statement else statement;
> After run SableCC, I got the following error message:

This grammar is ambiguous. SableCC does not let you parse ambiguous grammars; 
you have to write an equivalent unambiguous grammar.

The trick is to use a "statement_no_if" production, as shown in the examples. 
This is a traditional grammar disambiguation technique, explained in almost 
every book on compilers. Have a little look at a nearby University library for 
such a book.

You can search the mailing-list archive to get my opinion on arbitrarily 
specifying shift and reduce actions. Mainly, I think that few people are aware 
of the real semantics of such specifications. On the other hand, most people 
understand clearly the semantics of an unambiguous grammar.

It is in the development plans of SableCC to eventually have a few 
disambiguation mechanisms for things like operator precedence, but such 
mechanisms will only be added as long as they can be proven not to carry hidden 
traps (as do the equivalent machanisms in Bison/Yacc and similar tools). So, 
SableCC's mechanisms will be different. No "shift here" and "reduce there"...

Have fun!


Etienne M. Gagnon                    http://www.info.uqam.ca/~egagnon/
SableVM:                                       http://www.sablevm.org/
SableCC:                                       http://www.sablecc.org/