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

Jim Idle jimi at temporal-wave.com
Fri Aug 17 12:17:57 PDT 2012


The issue is that your trailing expression in the if has no terminator to
indicate the end of the if statement.

If you had something like:

'if' expr 'then' expr 'else' expr 'end'

Then it will go away. The correct decision is made, but it is difficult to
make ANTLR not issue the warning. If you cannot change the language, it
might be better to just document that the clause causes a warning and
leave it at that.

You could try playing with k=1 and so on - that might make the warning go
away and you could add single token predicates. Also, don't use literals
in the parser, they will confuse you later.

grammar jim;

tu	: expr EOF
	;
	
expr: term;

term: factor ((PLUS)=>PLUS factor)*
	;

factor: atom ((MUL)=>MUL atom)*;

atom
: INT
	| '(' expr ')'
	| 'if' expr 'then' expr 'else' expr
	;

INT: ('0'..'9')+;
MUL : '*';
PLUS : '+';


Jim


> -----Original Message-----
> From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-
> bounces at antlr.org] On Behalf Of Andrew Gacek
> Sent: Friday, August 17, 2012 11:56 AM
> To: antlr-interest
> Subject: Re: [antlr-interest] Expression grammars and *non*-ambiguities
>
> 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?
>
> expr: term;
>
> term: factor ('+' factor)*;
>
> factor: atom ('*' atom)*;
>
> atom
> : INT
> | '(' expr ')'
> | 'if' expr 'then' expr 'else' expr
> ;
>
> INT: ('0'..'9')+;
>
> -Andrew
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-
> email-address


More information about the antlr-interest mailing list