在ANTLR中替换令牌

时间:2012-03-26 19:35:38

标签: antlr antlr3

我想使用ANTLR替换令牌。

我尝试使用TokenRewriteStream并替换,但它没有用。

有什么建议吗?

  ANTLRStringStream in = new ANTLRStringStream(source);
  MyLexer lexer = new MyLexer(in);
  TokenRewriteStream tokens = new TokenRewriteStream(lexer);
  for(Object obj : tokens.getTokens()) {
     CommonToken token = (CommonToken)obj;  
     tokens.replace(token, "replacement");
  }

词法分析器找到所有单行注释的出现,我也想在原始源中替换它们。

编辑:

这是语法:

grammar ANTLRTest;

options {
  language = Java;
}

@header {
  package main;
}

@lexer::header {
  package main;
}

rule: SingleLineComment+;

SingleLineComment
  :  '//' ~( '\r' | '\n' )* {setText("replacement");}
    ;

我想要做的是替换文件中的所有单行注释,比如说。

1 个答案:

答案 0 :(得分:4)

重写词法分析器中的文字:

SingleLineComment
 : '//' ~('\r' | '\n')* {setText("replacement");}
 ;

修改

好的,这里有一个快速演示如何从语言中过滤某些令牌:

SingleCommentStrip.g

grammar SingleCommentStrip;

parse returns [String str]
@init{StringBuilder builder = new StringBuilder();}
 : (t=. {builder.append($t.text);})* EOF {$str = builder.toString();}
 ;

SingleLineComment
 : '//' ~('\r' | '\n')* {skip();}
 ;

MultiLineComment
 : '/*' .* '*/'
 ;

StringLiteral
 : '"' ('\\' . | ~('"' | '\\' | '\r' | '\n'))* '"'
 ;

AnyOtherChar
 : .
 ;

Main.java

import org.antlr.runtime.*;

public class Main {
  public static void main(String[] args) throws Exception {
    SingleCommentStripLexer lexer = new SingleCommentStripLexer(new ANTLRFileStream("Test.java"));
    SingleCommentStripParser parser = new SingleCommentStripParser(new CommonTokenStream(lexer));
    String adjusted = parser.parse();
    System.out.println(adjusted);
  }
}

Test.java

// COMMENT
class Test {
  /*
  // don't remove
  */
  // COMMENT AS WELL
  String s = "/* don't // remove */ \" \\ me */ as well";
}

现在运行演示:

java -cp antlr-3.3.jar org.antlr.Tool SingleCommentStrip.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main

将打印:


class Test {
  /*
  // don't remove
  */

  String s = "/* don't // remove */ \" \\ me */ as well";
}

(即删除单行注释)