java ANTLR 4 $channel = 隐藏和选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14778570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:21:44  来源:igfitidea点击:

ANTLR 4 $channel = HIDDEN and options

javamigrationantlrantlr4

提问by user2055330

I need help with my ANTLR 4 grammar after deciding to switch to v4 from v3. I am not very experienced with ANTLR so I am really sorry if my question is dumb ;)

在决定从 v3 切换到 v4 后,我需要有关 ANTLR 4 语法的帮助。我对 ANTLR 不是很有经验,所以如果我的问题很愚蠢,我真的很抱歉;)

In v3 I used the following code to detect Java-style comments:

在 v3 中,我使用以下代码来检测 Java 风格的注释:

COMMENT
    :   '//' ~('\n'|'\r')* '\r'? '\n' {$channel=HIDDEN;}
    |   '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;}
    ;

In v4 there are no rule-specific options. The actions (move to hidden channel) are also invalid.

在 v4 中没有特定于规则的选项。动作(移动到隐藏频道)也无效。

Could somebody please give me a hint how to do it in ANTLR v4?

有人可以给我一个提示如何在 ANTLR v4 中做到这一点吗?

回答by Bart Kiers

The v4 equivalent would look like:

v4 等效项如下所示:

COMMENT
    :   ( '//' ~[\r\n]* '\r'? '\n'
        | '/*' .*? '*/'
        ) -> channel(HIDDEN)
    ;

which will put all single- and multi line comment on the HIDDENchannel. However, if you're not doing anything with these HIDDEN-tokens, you could also skipthese tokens, which would look like this:

这会将所有单行和多行评论放在HIDDEN频道上。但是,如果您没有对这些HIDDEN-token做任何事情,您也可以使用skip这些令牌,如下所示:

COMMENT
    :   ( '//' ~[\r\n]* '\r'? '\n'
        | '/*' .*? '*/'
        ) -> skip
    ;

Note that to tell the lexer or parser to match ungreedy, you don't use options {greedy=false;}anymore, but append a ?, similar to many regex implementations.

请注意,要告诉词法分析器或解析器匹配 ungreedy,您不再使用options {greedy=false;},而是附加 a ?,类似于许多正则表达式实现。