3

I found number of questions related to 'multiple alternatives'in stackoverflow but nothing was much helpful. Here is a part of my g file in antlr3.

statement:
    selection_stmt
    | expression_stmt 
    | compound_stmt
    | iteration_stmt
    | return_stmt
    ;

selection_stmt:
    IF OPENB expression CLOSB statement (ELSE statement)?
    ;

expression:
    (var ASSIGN expression) => assignment 
    | simple_expression
    ;

The problem I'm facing is I get following warning for the phrase ELSE statement above.

(200): Decision can match input such as "ELSE" using multiple alternatives: 1, 2 As a result, alternative(s) 2 were disabled for that input

Can someone explain me what happens here? Thank you.

P.S. When I use a syntactic predicate as ((ELSE)=>ELSE statement)?, warning disappears. I don't get the reason for this too.

Bee
  • 12,251
  • 11
  • 46
  • 73

1 Answers1

5

Bhathiya wrote:

Can someone explain me what happens here? Thank you.

Lets's say your input is:

if (A) if (B) return 1 else return 2

Your grammar is ambiguous: the parser does not "know" how to interpret this. It could do so in two ways (I added braces to emphasize to which if the else block belongs to):

1

if (A) 
{
  if (B)
  {
    return 1
  }
  else
  {
    return 2
  }
}

enter image description here

2

if (A)
{
  if (B)
  {
    return 1
  }
}
else
{
  return 2
}

enter image description here

Bhathiya wrote:

P.S. When I use a syntactic predicate as ((ELSE)=>ELSE statement)?, warning disappears. I don't get the reason for this too.

By adding a predicate before ELSE, you're forcing the parser to choose for option #1 (and the parser does not warn anymore because you're explicitly telling it to choose alternative #1 over #2). Which results in the same as not putting a predicate there, but then ANTLR will warn you about it and mentions it will disregard option #2 and will also choose #1 (the message: "As a result, alternative(s) 2 were disabled for that input").

Now, the answer to your question in the title, "how to remove warning 'multiple alternatives'?", would be to make your grammar unambiguous (or just leave the predicate there, but realize there will never be a parse as shown in option #2!). You can do this by introducing some sort of statement-block-delimiters, like { and }. Or do as Python does it: make the amount of indented white spaces make a distinction to which if an else belongs to. The choice is yours.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • Thank you. Your explanation is great. What I want is the 1st option. – Bee Mar 11 '12 at 13:09
  • Cool, then all you need is the predicate. And you're welcome @Bhathiya. – Bart Kiers Mar 11 '12 at 13:24
  • I have few more questions here (http://stackoverflow.com/questions/9656744/issues-of-error-handling-with-antlr3) Can you please have a look? Thanks. – Bee Mar 11 '12 at 16:35