Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANTLR Decision can match input using multiple alternatives

Tags:

java

antlr

antlr3

I have this simple grammer:

expr: factor;

factor: atom (('*' ^ | '/'^) atom)*;

atom: INT
    | ':' expr;

INT: ('0'..'9')+

when I run it it says :

Decision can match input such as '*' using multiple alternatives 1,2

Decision can match input such as '/' using multiple alternatives 1,2

I can't spot the ambiguity. How are the red arrows pointing ? Any help would be appreciated.

enter image description here

like image 307
John Retallack Avatar asked Oct 31 '11 13:10

John Retallack


1 Answers

Let's say you want to parse the input:

:3*4*:5*6

The parser generated by your grammar could match this input into the following parse trees:

enter image description here

and:

enter image description here

(I omitted the colons to keep the trees more clear)

Note that what you see is just a warning. By specifically instructing ANTLR that (('*' | '/') atom)* needs to be matched greedily, like this:

factor
  :  atom (options{greedy=true;}: ('*'^ | '/'^) atom)*
  ;

the parser "knows" which alternative to take, and no warning is emitted.

EDIT

I tested the grammar with ANTLR 3.3 as follows:

grammar T;

options {
  output=AST;
}

parse
  :  expr EOF!
  ;

expr
  :  factor
  ;

factor
  :  atom (options{greedy=true;}: ('*'^ | '/'^) atom)*
  ;

atom
  :  INT
  |  ':'^ expr
  ;

INT : ('0'..'9')+;

And then from the command line:

java -cp antlr-3.3.jar org.antlr.Tool T.g

which does not produce any warning (or error).

like image 71
Bart Kiers Avatar answered Nov 07 '22 03:11

Bart Kiers