简体   繁体   中英

ANTLR 4.5: line 1:22 mismatched input 'randomly' expecting DIRECTION

The following grammar does not work properly with Antlr4.5 and Java 1.8.45 (IDE: IntelliJ Ultimate 14.1.4):

grammar PlayerAIShots;
file : row row EOF ;
row : START (randomshot)? SPACE direction Dot (LineBreak | EOF);

randomshot: RANDOM ;
direction : DIRECTION ;

RANDOM : 'randomly' ;
DIRECTION : ('to the left'|'to the right'|'central') ;
START : 'The opponent shoots' ;
SPACE : ' ' ;
Dot : '.' ;

// line break
LineBreak : '\r'?'\n' | '\r';

WS : [\t\r\n]+ -> skip ; // skip tabs, newlines

Letting the generated lexer and parser being evaluated results to:

line 1:22 mismatched input 'randomly' expecting DIRECTION

In the used data (text file) the second line was properly processed, but as in the above stated error message not the first one. Here is the text file being used:

The opponent shoots randomly to the left.
The opponent shoots to the right. 

Removing those SPACE within the definition of "row" the error does not occur. Why?

First line of your input is wrong. You didn't specify that you require space between START and randomshot like this

row : START (SPACE randomshot)? SPACE direction Dot (LineBreak | EOF);

When you remove 'SPACE' from 'row' definition you will get even more errors

line 1:19 extraneous input ' ' expecting {'randomly', DIRECTION}
line 1:28 extraneous input ' ' expecting DIRECTION
line 2:19 extraneous input ' ' expecting {'randomly', DIRECTION}

经过几次尝试,这才真正符合期望的行为:

row : START SPACE (RANDOM)? (SPACE)? direction Dot (LineBreak | EOF);

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