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.
Rewrite the text inside the lexer:
EDIT
Okay, here’s a quick demo how you can filter certain tokens from a language:
SingleCommentStrip.g
Main.java
Test.java
Now run the demo:
which will print:
class Test { /* // don't remove */ String s = "/* don't // remove */ \" \\ me */ as well"; }(i.e. the single line comments are removed)