Parsing ANTLR获取注释文本以进行附加处理

Parsing ANTLR获取注释文本以进行附加处理,parsing,comments,antlr,lexer,Parsing,Comments,Antlr,Lexer,在实验性语言开发中,需要获取注释文本以进行进一步处理 在令牌级别,这不起作用 COMMENT : comm = ('/*' ~'*' .* '*/') { System.out.println($comm.text); } ; 试图添加语句和/或表达式,但也未分析所需的语法 x = myFunction(x1, /* comment x1 */ x2, /* comment x2 */ x3) 更新:使用ANTLR 3.

在实验性语言开发中,需要获取注释文本以进行进一步处理

在令牌级别,这不起作用

COMMENT      : comm = ('/*' ~'*' .* '*/')  { System.out.println($comm.text); } ;
试图添加语句和/或表达式,但也未分析所需的语法

x = myFunction(x1, /* comment x1 */
               x2, /* comment x2 */
               x3)

更新:使用ANTLR 3.1.3。

发现这种工作方法虽然不完全适合将语句/表达式与注释相关联

@lexer::members {   
    public static final int COMMENTS = 2;
}
因此评论偏离了编号通道

COMMENT      : '/*' ~'*' .* '*/' {$channel=COMMENTS;} ;
那么

NetworkLexer lexer = new NetworkLexer(sourceStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);

Parser parser = new Parser(tokenStream);
parser.prog();

用行号获取注释文本,请考虑此java代码

for (Object tk: tokenStream.getTokens()) {
  CommonToken ctk = (CommonToken) tk;
  if (ctk.getChannel() == 2) {
    if (ctk.getText() != null && ctk.getText().trim().isEmpty() == false) {
      System.out.println(String.format("tk channel %s line %s text %s"), 
                               ctk.getChannel(), ctk.getLine(), ctk.getText());
  }
}