Reputation: 1771
I am writing a file parser with ANTLR4
. The file can have a number of blocks, which all begin and end with a (BEGIN | END) keyword. Here is a very simple example:
grammar test;
BEGIN: 'BEGIN';
END: 'END';
HEADER:'HEADER';
BODY: 'BODY';
file: block+;
ID: [A-Za-z];
NUM: [0-9];
block:
| BEGIN HEAD statement* END HEAD
| BEGIN BODY statement* END BODY
;
statement: ID '=' NUM;
The error thats get thrown is error(153): test.g4:8:0: rule file contains a closure with at least one alternative that can match an empty string
, what I don't understand, since file
has at least one empty block, with the begin-end style. Anyone sees what I am missing here?
Upvotes: 1
Views: 1448
Reputation: 370445
block
can match the empty string because there's nothing between the colon and the first |
. Then in file
, you use block+
. This causes the error because you're applying +
to something that can match the empty string, which could lead to an infinite looo that doesn't consume any input.
To fix this problem, just remove the first |
in block
.
Upvotes: 2