简体   繁体   中英

ANTLR Decision can match input using multiple alternatives

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.

在此输入图像描述

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:

在此输入图像描述

and:

在此输入图像描述

(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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM