views:

241

answers:

2

So, here is a piece of code using CodeModel that generates java code:

    JCodeModel cm = new JCodeModel();
    JDefinedClass dc = cm._class("foo.Bar");
    JMethod m = dc.method(0, int.class, "foo"); 
    m.body()._return(JExpr.lit(5));
    File f = new File("C:/target/classes");
    f.mkdirs();
    cm.build(f);

This code generates a .java file:

package foo;
public class Bar {

       int foo() {
        return  5;
    }
}

However, I DO NOT want CodeModel to create a new java file for me. I do have a .java file already and would like to add a few lines of code to a method inside it. So, I would like the API to modify the java file directly/ create a modified copy of it. Is there a way to doing this?

+2  A: 

You're really going to need a full parse of the code you want to modify to ensure you insert code into the correct location. I'd have thought your best bet would be to make use of an existing parse tool that allows code to be rewritten, rather than to try and do something by hand.

The Eclipse IDE does something like this to support code refactoring. This article might be helpful.

Richard Miskin
A: 

What you want is a program transformation system. This is a tool that parses your source file, and can apply transformations to modify it, an regenerates source code with the modifications.

A source-to-source transformation system accepts rules of the form of:

lhs -> rhs  if cond

where the lhs and rhs are souce patterns for valid fragments of the language and the cond checks that the rule is safe to apply. (Consider " ?x/?x -> 1 if ?x~=0"; you need the condition to verify that the division is valid).

One such tool is our DMS Software Reengineering Toolkit. DMS has full C, C++, C#, Java, COBOL, Python, PHP and ECMAScript front end parsers (as as many lesser known languages) and can apply such rules directly. DMS also provides symbol table construction and control and data flow analysis, as these are often useful in defining a cond for complex rules.

Ira Baxter
@Ira thanks. I am however looking at using open source stuff, not commercial ones.
Jay
Well, you can try TXL http://www.txl.ca or Stratego http://www.strategoxt.org, which are also program transformation systems that have source-to-source rewrite rules. What they don't have, that I beleive is fundamentally necessary to transformation of procedural langauges, is the symbol table and flow analysis tools. We've found these to be indispensable to doing reliable, large scale program transformation. You can try implementing these yourself in the OSS tools, but its a lot of work. YMMV.
Ira Baxter