Best design for generating code from an AST?

Sam Washburn picture Sam Washburn · Feb 4, 2010 · Viewed 6.9k times · Source

I'm working on a pretty complex DSL that I want to compile down into a few high level languages. The whole process has been a learning experience. The compiler is written in java.

I was wondering if anyone knew a best practice for the design of the code generator portion. I currently have everything parsed into an abstract syntax tree.

I was thinking of using a template system, but I haven't researched that direction too far yet as I would like to hear some wisdom first from stack overflow.

Thanks!

Answer

Steven Schlansker picture Steven Schlansker · Feb 4, 2010

When I was doing this back in my programming languages class, we ended up using emitters based on following the visitor pattern. It worked pretty well - makes retargeting it to new output languages pretty easy, as long as your AST matches what you're printing fairly well.