忽略 ANTLRworks 中的空格
我有以下 ANTLR 语法:
grammar mygrammar;
ASSIGNMENT
: ID '=' INT
;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
INT : '0'..'9'+
;
WS : ( ' '
| '\t'
| '\r'
| '\n'
) {$channel=HIDDEN;}
;
只有 ASSIGNMENT 规则实际上是我的,其余的都是 ANTLRWorks 1.4.3 添加的默认值。
当我在解释器中尝试语法时,诸如“a=5”之类的字符串成功,但诸如“b[space]=[space]6”之类的字符串失败:由于空格,我收到 MismatchedTokenException:
来自阅读 ANTLR 网站,以及
Ignore rules: WSand
{$channel=HIDDEN}text/grammar rule, it seems the whitespace should be ignored, however this is not the case.
我做错了什么?
I have the following ANTLR grammar:
grammar mygrammar;
ASSIGNMENT
: ID '=' INT
;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
INT : '0'..'9'+
;
WS : ( ' '
| '\t'
| '\r'
| '\n'
) {$channel=HIDDEN;}
;
Only the ASSIGNMENT rule is actually mine, the rest are defaults added by ANTLRWorks 1.4.3.
When I come to try the grammar in the interpreter, strings such as "a=5" succeed, but strings such as "b[space]=[space]6" fail: I get a MismatchedTokenException because of the spaces:
From reading the ANTLR website, and the
Ignore rules: WS
and
{$channel=HIDDEN}
text/grammar rule, it seems the whitespace should be ignored, however this is not the case.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道您已经找到了答案,但让我解释一下为什么将
ASSIGNMENT
更改为assignment
解决了这个问题。因为以大写字母开头的规则是词法分析器规则(即标记)。并且
{skip();}
或{$channel=HIDDEN;}
导致词法分析器规则从解析器规则中跳过(或隐藏),而不是从词法分析器规则中跳过(或隐藏)。这就是为什么
ASSIGNMENT
(词法分析器规则)不接受任何空格,而赋值
(解析器规则)会忽略它们。I know you already found the answer, but let me explain why changing
ASSIGNMENT
toassignment
solved it.Because rules that start with a capital, are lexer rules (i.e. tokens). And
{skip();}
or{$channel=HIDDEN;}
cause lexer rules to be skipped (or hidden) from parser rules, not from lexer rules.That is why
ASSIGNMENT
(lexer rule) didn't accept any white spaces, andassignment
(parser rule) does ignore them.