Skip to content
Advertisement

How to get from parse tree to Java class file

I am working on a command-line tool with the following functionality:

  1. Parse modified .java files using an extended ANTLR4 Java9 grammar. The syntax in the files is Java, with one modification to the method declaration which includes a purpose, like in this example: public void {marketing} sendEmail() {}
  2. Collect and remove all purposes using a visitor. Collection and analysis of the purposes is the main functionality of the program.
  3. Compile and execute the Java files where the purposes are removed.

I am searching for the simplest and most effective way to achieve step 3. It is out of the scope of my project to build a full compiler, I would prefer to exploit the Java compiler and run javac if possible. I have considered the following approaches, but none seem optimal:

Any input is much appreciated.

Advertisement

Answer

You could use TokenStreamRewriter to get the source code without the purpose node (or accomplish many other rewriting tasks). Here’s an example from an application where I conditionally add a top level LIMIT clause to a MySQL query:

JavaScript

What is this code doing:

  • Line 017: the input is parsed to get a parse tree. If you have done that already, you can pass in the parse tree, of course, instead of parsing again.
  • Line 022 prepares a new TokenStreamRewriter instance with your token stream.
  • Line 023 uses ANTLR4’s XPATH feature to get all nodes of a specific context type. This is where you can retrieve all your purpose contexts in one go. This would also be a solution for your point 2).
  • The following lines only check if a new LIMIT clause must be added at all. Not so interesting for you.
  • Line 046 is the place where you manipulate the token stream. In this case something is added, but you can also replace or remove nodes.
  • Line 052 contains probably what you are most interested in: it returns the original text of the input, but with all the rewrite actions applied.

With this code you can create a temporary java file for compilation. And it could be used to execute two actions from your list at the same time (collect the purposes and remove them).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement