Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

parsing - Antlr v3 error with parser/lexer rules

I am having problems with my Antlr grammar. I'm trying to write a parser rule for 'typedident' which can accept the following inputs:

'int a' or 'char a'

The variable name 'a' is from my lexer rule 'IDENT' which is defined as follows:

IDENT : (('a'..'z'|'A'..'Z') | '_') (('a'..'z'|'A'..'Z')|('0'..'9')| '_')*;

My 'typedident' parser rule is as follows:

typedident : (INT|CHAR) IDENT;

INT and CHAR having been defined as tokens.

The problem I'm having is that when I test 'typedident' the variable name has to be more than one character. For example:

'int a' isn't accepted while 'int ab' is accepted.

The outputed error I get is:

"MismatchedTokenException: mismatched input 'a' expecting '$'"

Any idea why I'm getting this error? I'm fairly new to Antlr so apologies if the error is trivial.

EDIT

I literally just got it working, and I don't know why. I also had two other lexer rules defined as follows:

ALPH : ('a'..'z'|'A'..'Z'); 
DIGIT : ('0'..'9'); 

I realised these weren't being used at all so I deleted them and everything now works fine! My guess why this works is because ALPH and DIGIT were overriding my other Lexer rules:

NUMBER : ('0'..'9')+; 
CHARACTER : ''' (~('
' | '
' |''')) '''; 

Does anyone know if this is the case? I'm curious as to why this problem has now been solved.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

'int a' isn't accepted while 'int ab' is accepted. ... My guess why this works is because ALPH and DIGIT were overriding ...

Yes, it appears ALPH was defined before the IDENT rule, in which case single letters were tokenized as ALPH tokens. If IDENT was defined before ALPH, it should all go okay (in your case).

To summarize how ANTLR's lexer rules work:

  • lexer rules match as much characters as possible (greedy);
  • if 2 (or more) lexer rules match the same input, the rule defined first will "win".

You must realize that the lexer does not produce tokens based on what the parser (at that time) needs. The lexer operates independently from the parser.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...