[antlr-interest] antlr: beginner question...

John B. Brodie jbb at acm.org
Mon Dec 22 12:51:10 PST 2008


> Started using antlr this weekend...so please bear my lack of understanding
> ( i did buy terence's book and am on page 70... )...
>
> I wrote my first grammar...cut & paste from terence's java grammar...a
> subset just to handle if-else statements...
>
> When I generate java from this ( using antlrworks also ), I get the
> following warnings which I dont understand - can somebody explain...
>
> [14:29:59] warning(200): gwf.g:10:34: Decision can match input such as
> "'else'" using multiple alternatives: 1, 2
> As a result, alternative(s) 2 were disabled for that input
> [14:30:00] warning(200): C:\projects\antlr\gwf\gwf.g:10:34: Decision can
> match input such as "'else'" using multiple alternatives: 1, 2
> As a result, alternative(s) 2 were disabled for that input
>
>
> what are the alternatives ? i cannot figure out how someone can get to
> 'else' without going through just the 2nd alternative of "statement" rule
> below ? I have also attached the complete grammar ( not sure if this
> mailing list allows attachments... )
>

I think this is the classic ambiguity with an if-then-else statement.

Consider a sentence in your language of this form:

if P if Q S1 else S2

where P and Q are some valid boolExpression's and S1 and S2 are valid 
statment's.

Now, to which 'if' does the 'else' to belong?

Your grammar does not specify.

It could be that the "if P" has no else and therefore the else that is present 
belongs to the "if Q" or it could be that the "if Q" has no else and therefore 
the else belongs to the  "if P".

i believe that common practice holds the first interpretation, e.g. an else 
belongs to the last if seen. but your grammar does not specify this.

doesn't java require braces ({}) to surround the then-part and else-part? 
having some bracketing syntax resolves the ambiguity.

if P { if Q { S1 } } else { S2 }

or braxket via an ending keyword (e.g.  if bool s (else s)? fi)

if P if Q S1 fi else S2 fi

(in both of the above the else clearly belongs to the if P).

>
> Grammar:
>
>
> prog
>  : statement+
>  ;
>
>
> statement
>  :  statementExpression ';'
>  | 'if' boolExpression statement (options {k=1;}:'else' statement)?
>  | '{' statement* '}'
>  ;
>
> boolExpression
>  : '(' expression ')'
>  ;
>
> statementExpression
>  :  function '(' expressionList ')'
>  |  Identifier('.' Identifier)* assignmentOperator expression
>  ;
>
> function
>  : 'sendEmail'
>  | 'loadData'
>  | 'loadAllUsers'
>  | 'loadUsersFromRole'
>  ;
>
> expressionList
>     :   expression (',' expression)*
>     ;
>
> ...
> ...

Hope this helps...
---
   -jbb


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20081222/287fe6f8/attachment.html 


More information about the antlr-interest mailing list