ANTLR: A análise de números de 2 dígitos numéricos quando outros literais também são possíveis

StackOverflow https://stackoverflow.com/questions/886511

  •  23-08-2019
  •  | 
  •  

Pergunta

Eu estou escrevendo uma gramática para uma linguagem de tamanho moderado, e eu estou tentando implementar literais de tempo do hh:mm:ss formulário.

No entanto, sempre que tento analisar, por exemplo, 12:34:56 como um timeLiteral, eu fico incompatíveis exceções sinal nas dígitos. Alguém sabe o que eu poderia estar fazendo errado?

Aqui estão as regras relevantes como actualmente definidos:

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

timePair
    :   DecimalDigit DecimalDigit
    ;

NumericLiteral
    : DecimalLiteral
    ;

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

fragment DecimalDigit
    : ('0'..'9')
    ;
Foi útil?

Solução

O problema é que o lexer está devorando o DecimalDigit e retornando um NumericLiteral.

O analisador nunca verá DecimalDigits porque é uma regra de fragmento.

Eu recomendaria movendo timeLiteral para o lexer (capitalizar o seu nome). Então você teria algo como

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

number
    :   DecimalLiteral
    ;

TimeLiteral
    :   DecimalDigit DecimalDigit COLON 
        DecimalDigit DecimalDigit COLON
        DecimalDigit DecimalDigit
    ;

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

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

Tenha em mente que o lexer e analisador são completamente independentes. Os determina lexer que tokens serão passados ??para o analisador, então o analisador fica para agrupá-los.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top