1. The phases of a compiler
Since writing a compiler is a nontrivial task, it is a good idea to structure the work. A typical way of doing
this is to split the compilation into several phases with well-defined interfaces.
A common division into phases is described below. There are two phases of compilation.
a. Analysis (Machine Independent/Language Dependent)
b. Synthesis(Machine Dependent/Language independent)
Lexical analysis This is the initial part of reading and analysing the program text: The text is read and
divided into tokens, each of which corresponds to a symbol in the programming language, e.g., a variable
name, keyword or number.
Syntax analysis This phase takes the list of tokens produced by the lexical analysis and arranges these
in a tree-structure (called the syntax tree) that reflects the structure of the program. This phase is often
called parsing.
Semantic Analysis Semantic analysis checks whether the parse tree constructed follows the rules of
language.
Intermediate code generation The program is translated to a simple machine independent intermediate
language.
Code Optimization The next phase does code optimization of the intermediate code. Optimization can be
assumed as something that removes unnecessary code lines, and arranges the sequence of statements in
order to speed up the program execution without wasting resources (CPU, memory).
Code Generation
In this phase, the code generator takes the optimized representation of the intermediate code and maps it
to the target machine language. The code generator translates the intermediate code into a sequence of
(generally) re-locatable machine code.
Symbol Table It is a data-structure maintained throughout all the phases of a compiler. All the identifiers’
names along with their types are stored here. The symbol table makes it easier for the compiler to quickly
search the identifier record and retrieve it. The symbol table is also used for scope management.
Error Handlers:-
It is invoked when a flaw error in the source program is detected.
3. Why learn about compilers?
a) It is considered a topic that you should know in order to be “well-cultured” in computer science.
b) A good craftsman should know his tools, and compilers are important tools for programmers and
computer scientists.
c) The techniques used for constructing a compiler are useful for other purposes as well.
d) There is a good chance that a programmer or computer scientist will need to write a compiler or
interpreter for a domain-specific language.