Chapter 11: Code Generation for a Virtual Machine

Overview


In this chapter, we take a final step in program translation by traversing an AST and generating a form of code that is suitable for a virtual machine The construction of an AST (Chapter 7) and its subsequent semantic processing (Chapter 8 and Chapter 9) have developed all of the information that is necessary to translate a source program into some form of interpretable or executable code. The AST serves well for expressing the structure and the meaning of a source program. However, its design is purposefully abstract, and thus independent of any particular architecture specification. Moreover, the AST nicely represents the nested structure of programs written in a modern programming language, while the instructions executed by most architectures are more linear in nature.

In Chapter 5 and Chapter 6, parsing techniques are presented that check an input program's syntax based on a programming language's grammar. While the grammar provides an automatic structure for regulating the parser's activity, the translation of the source program into a suitable AST requires actions that are inserted by hand. In this chapter, code generation is essentially the inverse of the parsing process. A program's AST provides a structure that can be traversed automatically, but the actions required to synthesize code are formulated by hand.