问题
I observe a strange behavior, trying to parse a text using a grammar that contains a statements like the following:
fragment A : ('a'|'A') ;
fragment D : ('d'|'D') ;
fragment N : ('n'|'N') ;
KEY_AND : A N D;
I created a simple grammar to produce the issue I experience:
grammar AndTest;
mainRule: NAME SEP KEY_AND SEP NAME;
NAME: ('A'..'Z')+ ;
SEP: ';' ;
fragment A : ('a'|'A') ;
fragment D : ('d'|'D') ;
fragment N : ('n'|'N') ;
KEY_AND : A N D;
WS: [ \r\t\n]+ -> skip ;
During grun execution I have got the following (here we have 'AND' and get an error, but if we have 'And' then we don't):
for AND: echo ANDY ; AND ; ANDY | grun AndTest mainRule -tree
line 1:7 mismatched input 'AND' expecting KEY_AND
(mainRule ANDY ; AND ; ANDY)
for And: echo ANDY ; And ; ANDY | grun AndTest mainRule -tree
(mainRule ANDY ; And ; ANDY)
My question: The error occurred during execution is expected and I missed something in my grammar, or it is a kind of bug in antlr4?
Environment: Windows7x32, Java SE 1.8.0_60-b27, antlr 4.5.1
回答1:
Your grammar is matching input "AND" to the NAME rule before is matches to the KEY_AND rule.
The error is expected. AND meets the requirements for NAME and NAME is listed before KEY_AND. The order of rules is important in antlr.
Moving the KEY_AND rule above NAME should fix this error.
来源:https://stackoverflow.com/questions/33420586/antlr4-mixed-fragments-in-tokens