Drawtomata / Phases of a compiler, step by step
Phases of a compiler, step by step
Type an assignment such as position = initial + rate * 60 above. Drawtomata passes it through the lexical analyzer, syntax analyzer, semantic analyzer, intermediate code generator, code optimizer and code generator, and shows the output of each, as in figure 1.7 of the Dragon Book.
The six phases
- Lexical analyzer: groups characters into tokens. position, initial and rate become ⟨id, 1⟩, ⟨id, 2⟩, ⟨id, 3⟩, pointing at the symbol table.
- Syntax analyzer: builds the syntax tree; * sits below + because it binds tighter.
- Semantic analyzer: checks types. The variables are float and 60 is an int, so an inttofloat node converts 60.
- Intermediate code generator: writes three-address code with one temporary per operator.
- Code optimizer: folds inttofloat(60) into 60.0 and merges the final copy.
- Code generator: produces machine instructions with registers.
The symbol table is shared by every phase, and errors can be reported by any of them.
Output for position = initial + rate * 60
| Phase | Output |
|---|---|
| Lexical | ⟨id,1⟩ ⟨=⟩ ⟨id,2⟩ ⟨+⟩ ⟨id,3⟩ ⟨*⟩ ⟨60⟩ |
| Intermediate code | t1 = inttofloat(60) t2 = id3 * t1 t3 = id2 + t2 id1 = t3 |
| Optimized code | t1 = id3 * 60.0 id1 = id2 + t1 |
| Target code | LDF R1, id3 MULF R1, R1, #60.0 LDF R2, id2 ADDF R2, R2, R1 STF id1, R2 |
The book uses R2 and R1 the other way round; the instructions are the same. The tool checks that the optimized code and the machine code compute the same values as the three-address code before showing them.