2

我正在为中等大小的语言编写语法,并且正在尝试实现形式的时间文字hh:mm:ss

但是,每当我尝试解析时,例如,12:34:56timeLiteral都会在数字上得到不匹配的令牌异常。有谁知道我可能做错了什么?

以下是当前定义的相关规则:

timeLiteral
    :   timePair COLON timePair COLON timePair -> ^(TIMELIT timePair*)
    ;

timePair
    :   DecimalDigit DecimalDigit
    ;

NumericLiteral
    : DecimalLiteral
    ;

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

fragment DecimalDigit
    : ('0'..'9')
    ;
4

1 回答 1

4

The problem is that the lexer is gobbling the DecimalDigit and returning a NumericLiteral.

The parser will never see DecimalDigits because it is a fragment rule.

I would recommend moving timeLiteral into the lexer (capitalize its name). So you'd 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 gets to group them.

于 2009-05-20T13:37:23.147 回答