问题
I want to replace a token using ANTLR.
I tried with TokenRewriteStream and replace, but it didn't work.
Any suggestions?
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");
}
The lexer finds all occurences of single-line comments, and i want to replace them in the original source too.
EDIT:
This is the grammar:
grammar ANTLRTest;
options {
language = Java;
}
@header {
package main;
}
@lexer::header {
package main;
}
rule: SingleLineComment+;
SingleLineComment
: '//' ~( '\r' | '\n' )* {setText("replacement");}
;
What i want to do is replace all single-line comments in a file, let's say.
回答1:
Rewrite the text inside the lexer:
SingleLineComment
: '//' ~('\r' | '\n')* {setText("replacement");}
;
EDIT
Okay, here's a quick demo how you can filter certain tokens from a language:
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";
}
Now run the demo:
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
which will print:
class Test { /* // don't remove */ String s = "/* don't // remove */ \" \\ me */ as well"; }
(i.e. the single line comments are removed)
来源:https://stackoverflow.com/questions/9878528/replace-token-in-antlr