antlr @members

转自StackOverflow,原问题 https://stackoverflow.com/questions/6005898/antlr-members-and-lexer

 

问题内容:

 

i have problem with @members rule in ANTLR. I want overwrite default error handling, so i read http://www.antlr.org/wiki/display/ANTLR3/Error+reporting+and+recovery and write this simple code for my grammar:

@members {
   def displayRecognitionError(self, tokenNames, e):
      print 'Test'
}

I have no @lexer::members or @parser::members in my grammar. Code (python runtime) from this rule is included only in parser file, not in lexer. It is a bug? I think it is,

@members should add content to both - lexer and parser according to documentation. I use Python runtime, 3.1.3.

Btw. is stackoverflow inline code work's for Opera?

 

最佳回答:

 

 

In a combined grammar file, @members is a short-hand for @parser::members.

// combined grammar
grammar Foo;

@members {
  // only parser members here, equivalent to: @parser::members { ... }
}

@lexer::members {
  // lexer members
}

When you use separate lexer- and/or parser grammars, then @members is enough:

parser grammar Foo;

@members {
  // parser members
}

or

lexer grammar Foo;

@members {
  // lexer members
}

Galmi wrote:

Btw. is stackoverflow inline code work's for Opera?

I guess so, but questions about SO itself can be asked on SO-Meta.

 

总结:

简单来说就是在antlr 语法文件或者词法文件中加入 @members {} 块,用IDEA antlr插件生成parser 或者 lexer 文件时,@members 内包裹的内容会原封不动拷贝到生成的文件中;

如果语法和词法定义在同一个文件中,那么 @members等同于 @parser::members,如果想要指定,需要写为:

 

@parser::members 或 @lexer::members

 

如果语法、词法是分开两个文件定义的,需要添加 members 直接写为 @members 即可。

那么在语法g4文件中的 @members 内容拷贝到 parser中,词法g4文件中的 @members 内容拷贝到 lexer 中;

 

目前有一个问题是,比如@members中写了 python 代码,生成语言选择的却是 Java,这样做的话生成的.java文件中因为混有Python代码,直接无法编译,

所以 @members 如果要写特定语言的话,会丧失通用性,建议通过g4文件名来区分是生成什么语言使用的。

posted @ 2021-03-02 19:50  Joynic  阅读(274)  评论(0编辑  收藏  举报