令牌中的antlr4混合片段 [英] antlr4 mixed fragments in tokens
问题描述
我观察到一种奇怪的行为,试图使用包含如下语句的语法分析文本:
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 ;
在执行grun期间,我得到了以下信息(这里我们有"AND"并得到一个错误,但是如果我们有"And"则没有):
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):
对于 AND :echo ANDY ; AND ; ANDY | grun AndTest mainRule -tree
line 1:7 mismatched input 'AND' expecting KEY_AND
(mainRule ANDY ; AND ; ANDY)
对于和:echo ANDY ; And ; ANDY | grun AndTest mainRule -tree
(mainRule ANDY ; And ; ANDY)
我的问题:预期在执行期间发生错误,我错过了语法中的某些内容,或者是antlr4中的一种错误?
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?
环境:Windows7x32,Java SE 1.8.0_60-b27,antlr 4.5.1
Environment: Windows7x32, Java SE 1.8.0_60-b27, antlr 4.5.1
推荐答案
您的语法先将输入"AND
"与NAME
规则匹配,然后再将其与KEY_AND
规则匹配.
Your grammar is matching input "AND
" to the NAME
rule before is matches to the KEY_AND
rule.
该错误是预期的. AND
符合NAME
的要求,并且NAME
在之前 KEY_AND
列出.规则的顺序在antlr中很重要.
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.
将KEY_AND
规则移至NAME
上方可解决此错误.
Moving the KEY_AND
rule above NAME
should fix this error.
这篇关于令牌中的antlr4混合片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!