Wednesday, August 21, 2002 08:59 PM
Believe it or not, this is "relatively" (albeit non-trivial) easy to do with ANTLR.
First you should start with the excellent Java grammar provided at www.antlr.org. This will read in your Java source files and generate an AST.
Step one is already done for you to a large extent. The real work is to provide a reverse-grammar for C. Think about the structure of C and the TOKENS in the grammar. What you want to accomplish is a mapping of the AST generated by the Java parser to another AST that represents your C program.
You will build a TreeWalker to perform the AST->AST mapping. Then make another TreeWalker to emit the C code or do it in a single step. Since there's no runtime performance requirements (obviously this tool will be run during development not in production) separating the AST translation and emitter into two steps is probably a nice way to carve up the work.
Now make a utility Main class that reads in the Java file and calls the Java parser. Then hand the generated AST to your first TreeWalker. Finally take that output AST and hand it to the emitter along with a file handle. Voila!