0
votes

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?

2

2 Answers

1
votes

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}
0
votes

After several tries that is what really matched desired behaviour:

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