Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a code snippet to method body with JDT/AST

I'm trying to generate Java source code with JDT/AST. I now have MethodDeclaration and want to add a code snippet (from another source) to the method body. The code snippet can contain any Java code, even syntactically invalid code. I just can't find the way to do this.

With JCodeModel you would use JBlock#directStatement(String s) method.

Is there a way to do this with JDT/AST?

like image 510
Morrandir Avatar asked Dec 10 '12 12:12

Morrandir


2 Answers

Since you have a well-formed tree for the rest of the application, and you want to insert non-well-formed text at a particular place, you pretty much can't do it with the standard tree node insertion mechanisms.

What matters is that you produce text for the valid program text with the fragment inserted in at at the right place. Somewhere in there must be a piece of logic that prints the AST as text. What you need to do is to ask that the AST be printed as text, and catch it in the middle of that process, at the precise point necessary, to insert your arbitrary text.

Our DMS Software Reengineering Toolkit has enter/exit print-node hooks in its prettyprinter to allow this kind of thing to happen.

If such things don't exist in JDT/AST, you can try to modify its prettyprinter to give you that hook. Alternatively, you might consider modifying JDT/AST by adding a another tree node type that isn't part of the standard set, that simply holds arbitrary text but acts like a method node. Presumably each node controls what is printed; then you could define the prettyprinting for that tree node, to cause it to output its text.

A final really hacky solution: insert a perfectly valid AST where the arbitrary text will go, containing somewhere a bogus identifier with a unique name, e.g., ZZZ. Then, print the AST to a string, and post-process the string to replace the bogus trees containing the unique name with the actual user text.

like image 70
Ira Baxter Avatar answered Nov 13 '22 01:11

Ira Baxter


You first need to parse the code snippet into an AST. You can use the ASTParser API for this purpose.

It is possible to get the compilation problems of a compilation unit (See CompilationUnit.getProblems()).

There are a couple of ways to modify Java code using JDT. I'd suggest that you consider the ASTRewrite API for modifying the body of a method.

like image 3
reprogrammer Avatar answered Nov 13 '22 00:11

reprogrammer