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 ;和 ;安迪 |grun AndTest mainRule -tree
line 1:7 mismatched input 'AND' expecting KEY_AND
(mainRule ANDY ; AND ; ANDY)
for And: echo 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
推荐答案
您的语法在匹配 NAME
规则之前将输入AND
"匹配到 >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屋!