2

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?

314314314
  • 249
  • 1
  • 10
  • I later realized that ANTLR4 allows modification of tree. One can add and delete children of a ParseRuleContext. But as the ANTLR Guy has said, rewriting token stream appears to be a better option. – 314314314 Jun 05 '14 at 08:02
  • I found this answer a bit astonishing. If the goal is to manipulate code, what's the point of building trees if it isn't useful to manipulate them? This goes to show that one needs life beyond mere parsing (see my bio). To see how to do this with "trees" (but not ANTLR4), see my paper on inserting any kind of probes into code (the example is for test coverage) at semanticdesigns.com/Company/Publications/TestCoverage.pdf – Ira Baxter Jun 14 '14 at 17:11

1 Answers1

4

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);
    }
}
Terence Parr
  • 5,912
  • 26
  • 32