ANTLR: parsing two-digit numbers when other numeric literals are possible
I am writing a grammar for a moderate sized language and I am trying to implement temporary form literals hh:mm:ss
.
However, whenever I try to parse, like 12:34:56
how timeLiteral
, I get inappropriate token exceptions on the numbers. Does anyone know what I might be doing wrong?
The following are the relevant rules:
timeLiteral
: timePair COLON timePair COLON timePair -> ^(TIMELIT timePair*)
;
timePair
: DecimalDigit DecimalDigit
;
NumericLiteral
: DecimalLiteral
;
fragment DecimalLiteral
: DecimalDigit+ ('.' DecimalDigit+)?
;
fragment DecimalDigit
: ('0'..'9')
;
a source to share
The problem is that the lexer is consuming the DecimalDigit and returning a NumericLiteral.
The parser will never see DecimalDigits because it is a fragment rule.
I would recommend moving the timeLiteral to lexer (capital letters of its name). This way you will have something like
timeLiteral
: TimeLiteral -> ^(TIMELIT TimeLiteral*)
;
number
: DecimalLiteral
;
TimeLiteral
: DecimalDigit DecimalDigit COLON
DecimalDigit DecimalDigit COLON
DecimalDigit DecimalDigit
;
DecimalLiteral
: DecimalDigit+ ('.' DecimalDigit+)?
;
fragment DecimalDigit
: ('0'..'9')
;
Keep in mind that the lexer and parser are completely independent. The lexer determines which tokens will be passed to the parser, then the parser will group them.
a source to share