Search code examples
javaantlrantlr4code-translationprogram-transformation

Inserting extra lines of code using Antlr4


The target is to insert codes to monitor the entry and exit of Java synchronized block.

i.e.

enteringSync();
synchronized(lockObj){
enteredSync();

   ...

leavingSync();
}
leftSync();

My original thought was to implement the enter/exit listener methods (which add subtrees around the Java synchronizd block), then to print out the resultant AST. Now I realized that antlr4 doesn't seem to support tree modification, what alternatives should I consider?


Solution

  • The best solution is to use the token stream rewrite engine rather than manipulating the parse tree. Book as an example; http://amzn.com/1934356999. Here is a code snippet that inserts serialization identifiers into class bodies.

    public class InsertSerialIDListener extends JavaBaseListener {
        TokenStreamRewriter rewriter;
        public InsertSerialIDListener(TokenStream tokens) {
            rewriter = new TokenStreamRewriter(tokens);
        }
        @Override
        public void enterClassBody(JavaParser.ClassBodyContext ctx) {
            String field = "\n\tpublic static final long serialVersionUID = 1L;";       
            rewriter.insertAfter(ctx.start, field);
        }
    }