How do I build a source-to-source translator in ANTLR? What is the basic strategy?

Terence Parr

In most general terms, the strategy for building a translator can be summarized as follows:

  1. Parse the input file(s) in the old language, constructing a tree representing the structure of the input and constructing a symbol table (that may have to be saved and used across parses/translations of the files).
  2. Manipulate the tree (intermediate form) in multiple passes using a tree grammar, slowing morphing it towards your target language.
  3. When you think that your intermediate form is very close to the target language, you can do a simple walk of the tree spitting out text again. Each action in the tree-walker grammar does a small bit of the work and you pray that the emergent behavior results in valid output text. ;)