Three address code explorer
A toy compiler frontend demonstrating various schemes for intermediate code generation, visualising generation of three address code for any given source text.
This follows (with some modifications) the translation schemes as defined in Chapter 6: Intermediate Code Generation in Compilers: Principles, Techniques, and Tools, 2nd edition, Addison-Wesley, 2006 (coloquially called The Dragon Book).
This is the example demonstrated in the screenshot above.
| Source | Three-address code |
|---|---|
int x, y;
if (x + y < 0)
while (y < 0)
y = y + 1;
if (x > 0)
x = x - 1; |
|
The toy language supports the following basic features:
- Variable declarations with array types
- Arithmetic expressions
- Array references
- Assignment statements
- Control flow statements (
if,if-else,while,for) - Short-Circuiting Boolean Expressions
The parsing happens via a Yacc grammar (icg.y).
The basic translation scheme for generating three address code (without fancy techniques like backpatching) is given as a syntax-directed definition, which requires inherited-attributes to pass down labels which occur later in the generated code. Thus, the semantic rules cannot be implemented directly during parsing. They are deferred to a later stage, after the complete parsing happens and generates an abstact syntax tree.
The AST comprises of nodes (tree.h) which are implemented as an hierarchy of classes using C++ object oriented constructs. Each node has a getCode() method which actually implements the semantic rules. The entire code generation process happens via a recursive call on the root node of the AST, which in turn passes the inherited attributes down the tree as required, and generate the IR code. Instead of outputting a string, they construct a structural representation of the generated IR.
Some tests are present in /tests/, which can be run using
./tests/run.sh
For a web demonstration of this application, the entire C++ code is compiled into WebAssembly using Emscripten (em++), which generates web/icg.wasm and a web/icg.js wrapper.
The frontend (web/index.html) allows the user to type any code in the (Monaco) code editor, and invokes the WASM code to translate it into the IR code and displays it.
