Compiler Design Tutorial

Phases of a compiler: lexical analysis, parsing (LL and LR), syntax-directed translation, intermediate code, optimization and code generation.

A compiler translates a program written in a high-level source language into an equivalent program in a target language (usually machine code), and reports errors along the way.

Compiler vs Interpreter

CompilerInterpreter
Translates the whole program at onceTranslates and executes statement by statement
Produces an object/executable fileNo object file
Faster executionSlower execution, easier debugging
C, C++Python, JavaScript (classic)

Phases of a Compiler

Source programcharactersLexical analyzertokensSyntax analyzersyntax treeSemantic analyzerannotated treeIntermediate code generatorintermediate codeCode optimizeroptimized codeCode generatortarget codeTarget programSymbol tablemanagerErrorhandlerfront endback end
Phases of a compiler (dashed lines: every phase uses the symbol table and error handler)

Take the statement position = initial + rate * 60:

Text
Lexical analysis    → id1 = id2 + id3 * 60          (tokens)
Syntax analysis     →        =
                           /   \
                        id1     +
                              /   \
                           id2     *
                                 /   \
                              id3     60
Semantic analysis   → inttofloat(60) inserted (rate is float)
Intermediate code   → t1 = inttofloat(60)
                      t2 = id3 * t1
                      t3 = id2 + t2
                      id1 = t3
Code optimization   → t1 = id3 * 60.0
                      id1 = id2 + t1
Code generation     → LDF R2, id3
                      MULF R2, R2, #60.0
                      LDF R1, id2
                      ADDF R1, R1, R2
                      STF id1, R1

The symbol table manager and error handler interact with every phase. The first four phases form the front end (source-language dependent); optimization and code generation form the back end (target-machine dependent).

Compiler Construction Tools

Scanner generators (Lex/Flex), parser generators (Yacc/Bison), syntax-directed translation engines, data-flow analysis engines and code-generator generators.

Track your progress through the Compiler Design course