Compiler Design Tutorial
Compiler Design Tutorial
i
Compiler Design
Audience
This tutorial is designed for students interested in learning the basic principles of compilers.
Enthusiastic readers who would like to know more about compilers and those who wish to
design a compiler themselves may start from here.
Prerequisites
This tutorial requires no prior knowledge of compiler design but requires a basic
understanding of at least one programming language such as C, Java, etc. It would be an
additional advantage if you have had prior exposure to Assembly Programming.
i
Compiler Design
Table of Contents
About the Tutorial ········································································································································ i
Audience ······················································································································································ i
Prerequisites ················································································································································ i
Tokens ························································································································································· 8
i
i
Compiler Design
Operations ················································································································································· 11
Notations ··················································································································································· 11
Precedence and Associativity ···················································································································· 12
Derivation ················································································································································· 17
Left-most Derivation ·································································································································· 17
Right-most Derivation ································································································································ 17
Bottom-up Parsing····································································································································· 27
iii
Compiler Design
LR Parser ···················································································································································· 34
LL vs. LR ····················································································································································· 36
Semantics ·················································································································································· 40
Activation Trees········································································································································· 45
Implementation········································································································································· 52
Operations ················································································································································ 53
insert() ······················································································································································· 53
lookup() ······················································································································································ 53
Declarations ·············································································································································· 58
Descriptors ················································································································································ 64
vi
Compiler Design
1. COMPILER DESIGN –
OVERVIEW
Computers are a balanced mix of software and hardware. Hardware is just a piece of
mechanical device and its functions are being controlled by a compatible software.
Hardware understands instructions in the form of electronic charge, which is the counterpart
of binary language in software programming. Binary language has only two alphabets, 0
and 1. To instruct, the hardware codes must be written in binary format, which is simply a
series of 1s and 0s. It would be a difficult and cumbersome task for computer programmers
to write such codes, which is why we have compilers to write such codes.
The high-level language is converted into binary language in various phases. A compiler is
a program that converts high-level language to assembly language. Similarly, an
assembler is a program that converts the assembly language to machine-level language.
Let us first understand how a program, using C compiler, is executed on a host machine.
User writes a program in C language (high-level language).
The C compiler compiles the program and translates it to assembly program
(low-level language).
An assembler then translates the assembly program into machine code (object).
A linker tool is used to link all the parts of the program together for execution
(executable machine code).
A loader loads all of them into memory and then the program is executed.
Before diving straight into the concepts of compilers, we should understand a few other
tools that work closely with compilers.
Preprocessor
A preprocessor, generally considered as a part of compiler, is a tool that produces input for
compilers. It deals with macro-processing, augmentation, file inclusion, language extension,
etc.
Interpreter
An interpreter, like a compiler, translates high-level language into low-level machine language.
The difference lies in the way they read the source code or input. A compiler reads the whole
source code at once, creates tokens, checks semantics, generates intermediate code, executes
the whole program and may involve many passes. In contrast, an interpreter reads a statement
from the input, converts it to an intermediate code, executes it, then takes the next statement in
sequence. If an error occurs, an interpreter stops execution and reports it; whereas a compiler
reads the whole program even if it encounters several errors.
Assembler
An assembler translates assembly language programs into machine code. The output of an
assembler is called an object file, which contains a combination of machine instructions as
well as the data required to place these instructions in memory.
Linker
Linker is a computer program that links and merges various object files together in order to
make an executable file. All these files might have been compiled by separate assemblers.
The major task of a linker is to search and locate referenced module/routines in a program
and to determine the memory location where these codes will be loaded, making the
program instruction to have absolute references.
8
Compiler Design
Loader
Loader is a part of operating system and is responsible for loading executable files into
memory and execute them. It calculates the size of a program (instructions and data) and
creates memory space for it. It initializes various registers to initiate execution.
Cross-compiler
A compiler that runs on platform (A) and is capable of generating executable code for
platform (B) is called a cross-compiler.
Source-to-source Compiler
A compiler that takes the source code of one programming language and translates it into
the source code of another programming language is called a source-to-source compiler.
9
Compiler Design
2. COMPILER DESIGN –
ARCHITECTURE
A compiler can broadly be divided into two phases based on the way they compile.
Analysis Phase
Known as the front-end of the compiler, the analysis phase of the compiler reads the
source program, divides it into core parts, and then checks for lexical, grammar, and syntax
errors. The analysis phase generates an intermediate representation of the source program
and symbol table, which should be fed to the Synthesis phase as input.
Synthesis Phase
Known as the back-end of the compiler, the synthesis phase generates the target program
with the help of intermediate source code representation and symbol table.
A compiler can have many phases and passes.
Pass : A pass refers to the traversal of a compiler through the entire program.
Phase : A phase of a compiler is a distinguishable stage, which takes input from
the previous stage, processes and yields output that can be used as input for the
next stage. A pass can have more than one phase.
10
Compiler Design
The compilation process is a sequence of various phases. Each phase takes input from its
previous stage, has its own representation of source program, and feeds its output to the
next phase of the compiler. Let us understand the phases of a compiler.
11
Compiler Design
Lexical Analysis
The first phase of scanner works as a text scanner. This phase scans the source code as a
stream of characters and converts it into meaningful lexemes. Lexical analyzer represents
these lexemes in the form of tokens as:
<token-name, attribute-value>
Syntax Analysis
The next phase is called the syntax analysis or parsing. It takes the token produced by
lexical analysis as input and generates a parse tree (or syntax tree). In this phase, token
arrangements are checked against the source code grammar, i.e., the parser checks if the
expression made by the tokens is syntactically correct.
Semantic Analysis
Semantic analysis checks whether the parse tree constructed follows the rules of language.
For example, assignment of values is between compatible data types, and adding string to
an integer. Also, the semantic analyzer keeps track of identifiers, their types and
expressions; whether identifiers are declared before use or not, etc. The semantic analyzer
produces an annotated syntax tree as an output.
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. Sequence of
instructions of machine code performs the task as the intermediate code would do.
12
Compiler Design
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.
13
Compiler Design
4. COMPILER DESIGN –
LEXICAL ANALYSIS
Lexical analysis is the first phase of a compiler. It takes the modified source code from
language preprocessors that are written in the form of sentences. The lexical analyzer
breaks these syntaxes into a series of tokens, by removing any whitespace or comments in
the source code.
If the lexical analyzer finds a token invalid, it generates an error. The lexical analyzer works
closely with the syntax analyzer. It reads character streams from the source code, checks
for legal tokens, and passes the data to the syntax analyzer when it demands.
Tokens
Lexemes are said to be a sequence of characters (alphanumeric) in a token. There are some
predefined rules for every lexeme to be identified as a valid token. These rules are defined
by grammar rules, by means of a pattern. A pattern explains what can be a token, and
these patterns are defined by means of regular expressions.
In programming language, keywords, constants, identifiers, strings, numbers, operators,
and punctuations symbols can be considered as tokens.
For example, in C language, the variable declaration line
14
Compiler Design
Specifications of Tokens
Let us understand how the language theory undertakes the following terms:
Alphabets
Any finite set of symbols {0,1} is a set of binary alphabets, {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F} is
a set of Hexadecimal alphabets, {a-z, A-Z} is a set of English language alphabets.
Strings
Any finite sequence of alphabets is called a string. Length of the string is the total number
of occurrence of alphabets, e.g., the length of the string tutorialspoint is 14 and is denoted
by |tutorialspoint| = 14. A string having no alphabets, i.e. a string of zero length is known
as an empty string and is denoted by ε (epsilon).
Special Symbols
A typical high-level language contains the following symbols:-
Assignment =
Preprocessor #
15
Compiler Design
Language
A language is considered as a finite set of strings over some finite set of alphabets.
Computer languages are considered as finite sets, and mathematically set operations can be
performed on them. Finite languages can be described by means of regular expressions.
16
Compiler Design
The lexical analyzer needs to scan and identify only a finite set of valid string/token/lexeme that
belong to the language in hand. It searches for the pattern defined by the language rules.
Regular expressions have the capability to express finite languages by defining a pattern for
finite strings of symbols. The grammar defined by regular expressions is known as regular
grammar. The language defined by regular grammar is known as regular language.
Regular expression is an important notation for specifying patterns. Each pattern matches a
set of strings, so regular expressions serve as names for a set of strings. Programming
language tokens can be described by regular languages. The specification of regular
expressions is an example of a recursive definition. Regular languages are easy to
understand and have efficient implementation.
There are a number of algebraic laws that are obeyed by regular expressions, which can be
used to manipulate regular expressions into equivalent forms.
Operations
The various operations on languages are:
Union of two languages L and M is written
as L U M = {s | s is in L or s is in M}
Concatenation of two languages L and M is written
as LM = {st | s is in L and t is in M}
The Kleene Closure of a language L is written
as L* = Zero or more occurrence of language L.
Notations
If r and s are regular expressions denoting the languages L(r) and L(s), then
Union : (r)|(s) is a regular expression denoting L(r) U L(s)
Concatenation : (r)(s) is a regular expression denoting L(r)L(s)
Kleene closure : (r)* is a regular expression denoting (L(r))*
(r) is a regular expression denoting L(r)
18
Compiler Design
Finite automata is a state machine that takes a string of symbols as input and changes its
state accordingly. Finite automata is a recognizer for regular expressions. When a regular
expression string is fed into finite automata, it changes its state for each literal. If the input
string is successfully processed and the automata reaches its final state, it is accepted, i.e.,
the string just fed was said to be a valid token of the language in hand.
The mathematical model of finite automata consists of:
Finite set of states (Q)
Finite set of input symbols (Σ)
One Start state (q0)
Set of final states (qf)
Transition function (δ)
The transition function (δ) maps the finite set of state (Q) to a finite set of input symbols
(Σ), Q × Σ ➔ Q
19
Compiler Design
int intvalue;
While scanning both lexemes till ‘int’, the lexical analyzer cannot determine whether it is a
keyword int or the initials of identifier int value.
The Longest Match Rule states that the lexeme scanned should be determined based on the
longest match among all the tokens available.
The lexical analyzer also follows rule priority where a reserved word, e.g., a keyword, of a
language is given priority over user input. That is, if the lexical analyzer finds a lexeme that
matches with any existing reserved word, it should generate an error.
20