简体   繁体   中英

antlr4 mismatched input 'a' expecting NAME

I have simplified the code where errors happened:

grammar simperr;
var
  : VAR_IDS NAME EQU NAME SPLIT
  ;
VAR_IDS : ('var'|'let')+;
LETTER : [a-zA-Z$_];
NUM : [0-9];
NAME : LETTER (LETTER|NUM)*;
EQU : '=';
SPLIT : ';';
WS : [ \t\n\r]+ -> skip;

and I get this:

var a=ijf;
enter   var, LT(1)=var
consume [@0,0:2='var',<1>,1:0] rule var
line 1:4 mismatched input 'a' expecting NAME
exit    var, LT(1)=<EOF>

I've tried so many ways but none of them would work.Can somebody help me?

If you print the token stream for your input (by adding -tokens as an argument to grun ), you'll see that the a is recognized as a LETTER , not a WORD . This happens because both LETTER and WORD produce a match of the same length (ie both match a ) and LETTER comes first in the grammar (this is known as the maximum munch rule).

So you can fix your issue by moving the LETTER rule after the word rule, but since you never actually want to produce a LETTER token in any situation, the better solution would be to tell ANTLR this by marking the rule as a fragment .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM