忽略 ANTLRworks 中的空格

发布于 2024-12-11 19:11:08 字数 755 浏览 7 评论 0原文

我有以下 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:

带有 MismatchedTokenException 的界面图片

来自阅读 ANTLR 网站,以及

Ignore rules: WS
and
{$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:

Picture of the interface with a MismatchedTokenException

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余罪 2024-12-18 19:11:08

我知道您已经找到了答案,但让我解释一下为什么ASSIGNMENT 更改为 assignment 解决了这个问题。

因为以大写字母开头的规则是词法分析器规则(即标记)。并且 {skip();}{$channel=HIDDEN;} 导致词法分析器规则从解析器规则中跳过(或隐藏),而不是从词法分析器规则中跳过(或隐藏)。

这就是为什么ASSIGNMENT(词法分析器规则)不接受任何空格,而赋值(解析器规则)会忽略它们。

I know you already found the answer, but let me explain why changing ASSIGNMENT to assignment 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, and assignment (parser rule) does ignore them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文