0
votes

Given the following ANTLR 3 grammar:

statement1 : CHAR_KEYWORD;
statement2 : DIGIT_KEYWORD (COLON_KEYWORD DIGIT_KEYWORD)?;

COLON_KEYWORD : ':';
DIGIT_KEYWORD : '0'..'9';
CHAR_KEYWORD : 'a'..'z' | COLON_KEYWORD;

When parsing the following text:

1

The rule statement2 picks up this text. This is good. However, if one has the following text now:

1:2

The rule statement2 does not pick up this text and gives an error. This is because ":" is matched by CHAR_KEYWORD which is not part of the rule. If one removes the COLON_KEYWORD from the CHAR_KEYWORD, rule statement2 works fine except that rule statement1 does not work as required now. How can this grammar be refactored so that both rules statement1 and statement2 work as expected? Thanks!

1

1 Answers

0
votes

Remove the COLON_KEYWORD alt from CHAR_KEYWORD and instead add it as alt to statement1.

statement1 : CHAR_KEYWORD | COLON_KEYWORD;
statement2 : DIGIT_KEYWORD (COLON_KEYWORD DIGIT_KEYWORD)?;

COLON_KEYWORD : ':';
DIGIT_KEYWORD : '0'..'9';
CHAR_KEYWORD : 'a'..'z';