[antlr-interest] Translating from one language to another

Mark Wright markwright at internode.on.net
Tue Jul 22 09:55:23 PDT 2008


Of course the ANTLR book is essential.

The syntax directed translation approach (generate code from the
AST) would be easy if you are lucky that your generated code is
in a very similar structure to the source language.

This article by Andy is brilliant:

http://jazillian.com/articles/treewalkers.html

In my situation, which is different to yours, I thought
my AST was not in the right form to generate the code using
string template, Andy's article just reinforced this for me, which
really helped.

I think string template is great.  What I did was I generated
a completely new tree with all the information I need in the
right places to generate the code, then used string template to
generate it.  So basically, I used Andy's approach (I manually
walked the AST looking for stuff for the new tree which I entered
into some data structures), manually walked parts of the symbol table
(while looking up more stuff in the  symbol table and other data
structures), generated a new tree, and used string template.

If AST is not in the right format to generate the code, then
one approach is to figure out some way to transform and
augment it, possibly with new subtrees, or generate a new tree.

On Tue, 22 Jul 2008 11:38:15 -0400
Andy Tripp <antlr at jazillian.com> wrote:

> A "quick and dirty" alternative approach to StringTemplate is
> to write some code that just walks your AST, printing out code.
> This: http://www.jazillian.com/antlr/emitter.html
> just walks a Java AST and prints Java code.
> 
> David Tauzell wrote:
> > I'd like to translate from language A to java.  I've written a
> > grammar that parses language A and generates an AST.   The language
> > is mostly like java, except there are a few cases where I'll need
> > to change the input.  For example, something like:
> > 
> >     a.b.c.d = foo
> > 
> > will be converted to
> > 
> >     a.get("b").get("c").get("d").setValue(foo)
> > 
> > Other stuff like:
> > 
> >    if( foo == "bar") {
> >       ...
> >    }
> > 
> > can stay like it is.
> > 
> > I'm not sure what is the best way to proceed.  Should I somehow use 
> > StringTemplate?  Should I walk the AST and generate output? Is this 
> > question to vague? Do I just need to buy the ANTLR book and learn
> > more about ANTLR?
> > 
> > Thanks,
> >     Dave
> > 
> > 
> 


-- 


More information about the antlr-interest mailing list