Parsing ANTLR:在也可以使用其他数字文字时解析2位数字

Parsing ANTLR:在也可以使用其他数字文字时解析2位数字,parsing,antlr,antlrworks,Parsing,Antlr,Antlrworks,我正在为一种中等规模的语言编写语法,并尝试实现形式为hh:mm:ss的时间文本 但是,每当我尝试将12:34:56解析为timeLiteral时,就会在数字上出现不匹配的令牌异常。有人知道我可能做错了什么吗 以下是当前定义的相关规则: timeLiteral : timePair COLON timePair COLON timePair -> ^(TIMELIT timePair*) ; timePair : DecimalDigit DecimalDi

我正在为一种中等规模的语言编写语法,并尝试实现形式为
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')
    ;

问题是lexer正在吞食小数并返回NumericLiteral

解析器永远不会看到小数位数,因为它是一个片段规则

我建议将timeLiteral移至lexer(大写其名称)。所以你会有

timeLiteral
    :   TimeLiteral -> ^(TIMELIT TimeLiteral*)
    ;

number
    :   DecimalLiteral
    ;

TimeLiteral
    :   DecimalDigit DecimalDigit COLON 
        DecimalDigit DecimalDigit COLON
        DecimalDigit DecimalDigit
    ;

DecimalLiteral
    :   DecimalDigit+ ('.' DecimalDigit+)?
    ;

fragment DecimalDigit
    :   ('0'..'9')
    ;
请记住,lexer和parser是完全独立的。lexer确定哪些令牌将被传递给解析器,然后解析器将它们分组