ANTLR:解析2位数时,其它数字文字也是可能的
-
23-08-2019 - |
题
我正在写一个语法为中等大小的语言,我想实现形式hh:mm:ss
的时间文字。
然而,每当我试图解析,例如,12:34:56
作为timeLiteral
,我得到的数字不匹配的令牌例外。有谁知道我可能是做错了?
下面是按当前定义的相关规则:
timeLiteral
: timePair COLON timePair COLON timePair -> ^(TIMELIT timePair*)
;
timePair
: DecimalDigit DecimalDigit
;
NumericLiteral
: DecimalLiteral
;
fragment DecimalLiteral
: DecimalDigit+ ('.' DecimalDigit+)?
;
fragment DecimalDigit
: ('0'..'9')
;
解决方案
的问题是,词法分析器被吞噬的DecimalDigit并返回一个NumericLiteral。
分析器不会看到DecimalDigits因为它是一个片段的规则。
我建议移动timeLiteral到词法分析器(利用它的名字)。所以,你必须像
timeLiteral
: TimeLiteral -> ^(TIMELIT TimeLiteral*)
;
number
: DecimalLiteral
;
TimeLiteral
: DecimalDigit DecimalDigit COLON
DecimalDigit DecimalDigit COLON
DecimalDigit DecimalDigit
;
DecimalLiteral
: DecimalDigit+ ('.' DecimalDigit+)?
;
fragment DecimalDigit
: ('0'..'9')
;
记请的是,词法分析器和解析器是完全独立的。词法分析器确定哪些令牌将被传递给分析器,然后解析器到达他们组。
不隶属于 StackOverflow