[antlr-interest] Expression grammars and *non*-ambiguities

John B. Brodie jbb at acm.org
Fri Aug 17 12:18:52 PDT 2012


Greetings!

On 08/17/2012 02:56 PM, Andrew Gacek wrote:
> I have investigated this a bit more. The following grammar is flagged
> as ambiguous by ANTLR, but the resulting parser seems to make the
> correct decisions. Is there a sensible way to rewrite the grammar to
> remove the ambiguity?

this apparently valid sentence has an ambiguous parse under your grammar:

1 * if 2 then 3 else 4 * 5

it could be 1 * (if 2 then 3 else (4*5))
or 1 * ((if 2 then 3 else 4) * 5)

fix by adding a closing keyword to your if construct
atom : ..... | 'if' expr 'then' expr 'else' expr 'fi'

or muck with the precedence of the if-then-else operator

Hope this helps
    -jbb

>
> expr: term;
>
> term: factor ('+' factor)*;
>
> factor: atom ('*' atom)*;
>
> atom
> : INT
> | '(' expr ')'
> | 'if' expr 'then' expr 'else' expr
> ;
>
> INT: ('0'..'9')+;
>
> -Andrew
>



More information about the antlr-interest mailing list