Fog Creek Software
Discussion Board




ANTLR and Java

Does anyone here have any experience with antlr?  I'm trying to auto generate some code (no need to get into the evils of code generation...) and am able to parse the java code, and alter the AST nodes to my liking.  However, I cannot figure out how to convert the AST nodes back into java source code.

blah
Monday, April 05, 2004

Can you walk the tree and generate the Java code representation of each node?

e.g.: with a tree like (for-loop (expr (= i 0)) (expr (<= i n)) (expr (inc i)) (expr (block ...))) you'd have:

string for_loop(node* init, node* pred, node* inc, node* body)
{
  return "for (" + expression(init) + "; " + expression(pred) + "; " + expression(inc) + ")\n\t\t" + expression(body);
}

I've read a bit about ANTLR and heard some talks, but I use my own CFG parser generator.

Kalani
Monday, April 05, 2004

That's what I had started to do, but can't shake the feeling that there must be some automatic way to do this.  I somehow doubt I'm the first person to need to do this.  Thanks for the response though.

blah
Monday, April 05, 2004

ANTLR has a tree-parser that might help with this (http://www.antlr.org/doc/sor.html).  A Prolog-style rule engine might be helpful here.  I'm working on something like that for my CFG parser generator, actually.  You should be able to say something like:

(for-loop x? y? z? body?) => (concat "for (" (reduce x?) "; " (reduce y?) "; " (reduce z?) ")\n\t\t" (reduce body?))

(= x? y?) => (concat (reduce x?) " = " (reduce y?) ";")

etc...

Kalani
Monday, April 05, 2004

ANTLR generates parsers and tree-walkers.

For code generation, you are on your own.

ANTLR is public-domain, so you can look at their code generators for Java and C++.

David Jones
Tuesday, April 06, 2004

*  Recent Topics

*  Fog Creek Home