System Programming & Compiler Design Syllabus
System Programming & Compiler Design Syllabus
Code: CSPC-402
By
Dr K P Sharma
Course
Program outcomes
Outcomes
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CSPC-402
CO 1 M M H
CO 2 H H M
CO 3 M L
CO 4 M L L 2
TOPICS TO BE COVERED
▪ Introduction to Language Processor: Overview, fundamentals of language
processing and symbol tables
▪ Assemblers and Macros: Pass structure of assemblers, design of two pass
assemblers using any hypothetical computer, design of macro processors
▪ Linker and Loaders: Relocation and linking operation, design of linker,
absolute and relocating loaders
▪ Compiler structure: analysis-synthesis model of compilation, various phases of
a compiler, tool based approach to compiler construction.
▪ Lexical analysis: interface with input, parser and symbol table, token, lexeme
and patterns. Difficulties in lexical analysis, Error reporting. Implementation.
Regular definition, Transition diagrams, LEX.
▪ Syntax analysis: CFGs, ambiguity, associativity, precedence, top down parsing,
recursive descent parsing, transformation on the grammars, predictive parsing,
bottom up parsing, operator precedence grammars, LR parsers (SLR, LALR,
LR), YACC.
▪ Syntax directed definitions: inherited and synthesized attributes, dependency
graph, evaluation order, bottom up and top down evaluation of attributes, L- and
S-attributed definitions. 3
TOPICS TO BE COVERED
▪ Type checking: type system, type expressions, structural and name equivalence of types,
type conversion, overloaded functions and operators, polymorphic functions.
▪ Run time system: storage organization, activation tree, activation record, parameter
passing, symbol table, dynamic storage allocation.
▪ Intermediate code generation: intermediate representations, translation of declarations,
assignments, control flow, boolean expressions and procedure calls. Implementation
issues.
▪ Code generation and instruction selection: issues, basic blocks and flow graphs,
register allocation, code generation, dag representation of programs, code generation from
dags, peep hole optimization, code generator generators, specifications of machine.
▪ TEXT BOOKS, AND/OR REFERENCE MATERIAL:
▪ D M Dhamdhere, System Programming, TMH, 1st ed., 2012
▪ V. Aho, R. Sethi, and J. D. Ullman. Compilers: Principles, Techniques and Tools ,
Addison-Wesley, 1988.
▪ Fischer and R. LeBlanc. Crafting a Compiler , Benjamin Cummings, 1991..
▪ C. Holub. Compiler Design in C , Prentice-Hall Inc., 1993.
▪ Appel. Modern Compiler Implementation in C: Basic Design , Cambridge Press.
▪ Fraser and Hanson. A Retargetable C Compiler: Design and Implementation ,
4
Addison-Wesley.
Basic questions before start the Compiler
▪ What are different level of programming languages ?
▪ What is the role of translator ?
▪ What are different types of translator ?
▪ Why we need to study Compiler ?
▪ In which language, the code of first compiler was written ?
▪ Which language use compiler, which use interpreter, and which
used both ?
▪ How to design Compiler ?
▪ Difference between compiler and interpreter
5
6
Machine Language
▪ The machine-level language is a language that consists of a set of
instructions that are in the binary form 0 or 1.
▪ As we know that computers can understand only machine instructions,
which are in binary digits, i.e., 0 and 1.
▪ Creating a program in a machine-level language is a very difficult task as
it is not easy for the programmers to write the program in machine
instructions.
▪ It is error-prone as it is not easy to understand, and its maintenance is
also very high.
▪ A machine-level language is not portable, so if we write a program in one
computer will no longer be valid in another computer.
▪ The different processor architectures use different machine codes, for
example, a PowerPC processor contains RISC architecture, which
requires different code than intel x86 processor, which has a CISC
architecture.
7
Assembly Languages
▪ The assembly language contains some human-readable commands
such as mov, add, sub, etc.
▪ The problems which we were facing in machine-level language are
reduced to some extent by using an extended form of
machine-level language known as assembly language.
▪ Computers can only understand the machine-level instructions, so
we require a translator that converts the assembly code into
machine code.
▪ The translator used for translating the code is known as an
assembler.
▪ The assembly code is not faster than machine code because the
assembly language comes above the machine language in the
hierarchy.
8
High Level Languages
▪ The high-level language is a programming language that allows a
programmer to write the programs which are independent of a
particular type of computer.
▪ The high-level languages are considered as high-level because
they are closer to human languages than machine-level languages.
▪ A high-level language gets away from all the constraints of a
particular machine.
▪ A compiler is required to translate a high-level language into a
low-level language.
9
FORTRAN
▪ FORTRAN was first HLL written by John Backus and IBM in 1957.
▪ The original Fortran compiler was written entirely in assembly language.
▪ The first compiler had a huge impact on the programming languages and
computer science.
▪ The whole new field of compiler design was started
▪ More than half the programmers were using Fortran by 1958
▪ Led to enormous amount of theoretical work (lexical analysis, parsing,
optimization, structured programming, code generation, error recovery
etc.)
10
Translators
• Compilers
• Interpreters
• Assemblers
Two ways for doing that: compile the program or interpret the
program
Compilers:
• A compiler is a computer program that translates a program in a
source language into an equivalent program in a target language.
or
• Compilers: Translate a source (human-writable) program to an
executable (machine-readable) program.
• Object code is a portion of machine code that has not yet been
linked into a complete program.
• Machine code is binary (1's and 0's) code that can be executed
directly by the CPU.
Interpreters:
• An interpreter is a computer program that translates and
executes instructions written in a computer programming
language line-by-line, unit by unit etc.,
23
▪ Compiler is part of program development environment
▪ The other typical components of this environment are editor,
assembler, linker, loader, debugger, profiler etc.
▪ The compiler (and all other tools) must support each other for easy
program development
24
Difference between Compiler and Interpreters
25
COMPILERS
▪ A compiler is a system software takes a program written in a
source language and translates it into an equivalent program in a
target language.
error messages
▪ As an important part of translation process, the compiler report to
its user the presence of error in the source program.
26
Abstract view
Source Machine
code Compiler code
errors
▪ Recognizes legal (and illegal) programs
▪ Generate correct code
▪ Manage storage of all variables and code
▪ Agreement on format for object code
Types of Compiler
Compilers are sometimes classified as
1. Single-pass
2. Two Pass Compilers or Multi-pass
▪ debugging or optimizing, depending on how they have been
constructed or what function they are supposed to perform.
▪ If we combine or group all the phases of compiler design in
a single module known as single pass compiler.
▪ In single pass Compiler source code directly transforms into
machine code. For example, Pascal language.
▪ Single pass compiler is faster and smaller than the multi pass
compiler
28
Continue..
▪ As a disadvantage of single pass compiler is that it is less
efficient in comparison with two pass or multi-pass compiler.
29
Continue..
▪ In first pass, included phases are as Lexical analyzer, syntax analyzer,
semantic analyzer, intermediate code generator are work as front end.
▪ Analytic part means all phases analyze the High level language and
convert them three address code.
▪ First pass is platform independent because the output of first pass is
as three address code which is useful for every system and
requirement is to change the code optimization and code generator
phase which are comes to the second pass.
30
▪ A multi-pass Compiler is a type of compiler that processes
the source code or abstract syntax tree of a program multiple
times.
▪ It divided a large program into multiple small programs and
process them.
▪ It develops multiple intermediate codes.
▪ All of these multi-pass take the output of the previous phase as an
input. So it requires less memory. It is also known as 'Wide
Compiler'.
31
Tasks of Compiler
▪ Breaks up the source program into pieces and impose grammatical
structure on them
▪ Allows you to construct the desired target program from the
intermediate representation and also create the symbol table
▪ Compiles source code and detects errors in it
▪ Manage storage of all variables and codes.
▪ Support for separate compilation
▪ Read, analyze the entire program, and translate to semantically
equivalent
▪ Translating the source code into object code depending upon the
type of machine
32
Other Applications
▪ In addition to the development of a compiler, the techniques
used in compiler design can be applicable to many problems in
computer science.
• Techniques used in a lexical analyzer can be used in text editors,
information retrieval system, and pattern recognition programs.
• Techniques used in a parser can be used in a query processing system such
as SQL.
• Most of the techniques used in compiler design can be used in Natural
Language Processing (NLP) systems.
33
Practical applications
▪ Greedy algorithms - register allocation
▪ Graph algorithms - dead code elimination,
register allocation
▪ Dynamic programming - instruction selection
▪ Optimization techniques – instruction scheduling
▪ Finite automata – lexical analysis
▪ Pushdown automata – parsing
▪ Complex data structure – symbol table, data dependence graph
▪ Computer architecture – machine code generator
34
Analysis of the source program
▪ There are two major parts of a compiler: Analysis and Synthesis
▪ In analysis phase, an intermediate representation is created from
the given source program.
• Lexical Analyzer, Syntax Analyzer and Semantic Analyzer are the parts of this phase.
▪ In synthesis phase, the equivalent target program is created from
this intermediate representation.
• Intermediate Code Generator, Code Generator, and Code Optimizer are the parts of this phase.
35
Phases of A Compiler
36
37
38
Phases of Compiler
▪ 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.
39
Phases of Compiler
▪ 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.
▪ Intermediate Code Generation
▪ After semantic analysis the compiler generates an intermediate
code of the source code for the target machine. It represents a
program for some abstract machine. It is in between the high-level
language and the machine language. This intermediate code should
be generated in such a way that it makes it easier to be translated
40
into the target machine code.
Phases of Compiler
▪ 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.
41
Phases of Compiler
▪ Symbol Table
▪ It is a data-structure maintained throughout all the phases of a
compiler. All the identifier's 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.
42
43
Compiler Construction Tools
▪ Scanner Generators − These generators create the lexical analysis. The
fundamental lexical analysis is produced by Finite Automata which takes input
in the form of regular expressions.
▪ Example − LEX is a scanner generator provided by UNIX systems.
▪ Parser Generators − This software produces syntax analysis which takes input
in the form of the syntax of a programming language depends on context-free
grammar. Example YACC
▪ Syntax Directed Translation Engines − These make a set of routines that walk
the parse tree. The basic concept is that one or more translations are related to
each node of the parse tree, and each translation is represented because of
translation at its neighbour nodes in the tree.
▪ Data Flow Engines − It can generate an optimized code. These tools are used in
code optimization.
▪ Automatic Code Generators − These generators take input in the form of
intermediate code and convert it into machine language.
44
Token, Pattern and Lexeme
▪ Token: Token is a sequence of characters that can be treated as a
single logical entity. Typical tokens
are,
▪ 1) Identifiers 2) keywords 3) operators 4) special symbols
5)constants
▪ Pattern: A set of strings in the input for which the same token is
produced as output. This set of strings is described by a rule called
a pattern associated with the token.
▪ Lexeme: A lexeme is a sequence of characters in the source
program that is matched by the pattern for a token.
45
46
Lexical Analyzer
▪ Lexical Analysis is the first phase of compiler also known as scanner.
▪ Its main task is to read the input characters and produce as output a sequence of
tokens that the parser use for syntax analysis.
▪ It converts the High level input program into a sequence of Tokens.
▪ Lexical Analysis can be implemented with the Deterministic finite Automata
Example of token:
Keywords; Examples-for, while, if etc.
Identifier; Examples-Variable name, function name etc.
Operators; Examples '+', '++', '-' etc.
Separators; Examples ',' ';' etc
Example of Non-Tokens:
Comments, preprocessor directive, macros, blanks, tabs, newline etc
47
Lexical analyzer
token
Source To semantic
Lexical Analyzer Parser
program analysis
getNextToken
Symbol
table
The role of lexical analyzer
▪ Its main task is to read the input characters and produce as output a sequence
of tokens that the parser uses for syntax analysis.
▪ Removes white spaces and comments from the source program which are in
the form of blank, tab, and newline characters.
▪ Correlates error messages with the source program
▪ In some compiler Lexical Analyzer is in charge of making a copy of the
source program with error message marked in it
▪ Helps you to expands the macros if it is found in the source program
▪ Read input characters from the source program
Why to separate Lexical analysis and parsing
1. Simplicity of design
2. Improving compiler efficiency
3. Enhancing compiler portability
Tokens, Patterns and Lexemes
▪ A token is a pair a token name and an optional token value
▪ A pattern is a description of the form that the lexemes of a token
may take
▪ A lexeme is a sequence of characters in the source program that
matches the pattern for a token
Example
i n t i , j ; i = i + 1 ; j = j + 1 ;
fp
Continue..
▪ Initially both the pointers point to the first character of the input string as
shown in fig
▪ The forward ptr moves ahead to search for end of lexeme.
▪ As soon as the blank space is encountered, it indicates end of lexeme.
▪ In the example as soon as ptr (fp) encounters a blank space the lexeme
“int” is identified.
▪ The fp will be moved ahead at white space, when fp encounters white
space, it ignore and moves ahead. then both the begin ptr(bp) and forward
ptr(fp) are set at next token.
▪ The input character is thus read from secondary storage, but reading in this
way from secondary storage is costly.
▪ Hence buffering technique is used.
▪ When referring to computer memory, the input buffer is a location that
holds all incoming information before it continues to the CPU for
processing.
▪ A block of data is first read into a buffer, and then scaned by lexical
analyzer.
▪ There are two methods used in this context: One Buffer Scheme, and Two
Buffer Scheme.
One Buffer Scheme
▪ In this scheme, only one buffer is used to store the input string
▪ But the problem with this scheme is that if lexeme is very long then it
crosses the buffer boundary,
▪ To scan rest of the lexeme the buffer has to be refilled, that makes
overwriting the first of lexeme.
Disadvantage:
▪ Example:
letter_ -> A | B | … | Z | a | b | … | Z | _
digit -> 0 | 1 | … | 9
id -> letter_ (letter_ | digit)*
Extensions
▪ One or more instances: (r)+
▪ Zero of one instances: r?
▪ Character classes: [abc]
▪ Example:
• letter_ -> [A-Za-z_]
• digit -> [0-9]
• id -> letter_(letter|digit)*
Recognition of tokens
▪ Starting point is the language grammar to understand the tokens:
stmt -> if expr then stmt
| if expr then stmt else stmt
|Ɛ
expr -> term relop term
| term
term -> id
| number
Recognition of tokens (cont.)
▪ The next step is to formalize the patterns:
digit -> [0-9]
Digits -> digit+
number -> digit(.digits)? (E[+-]? Digit)?
letter -> [A-Za-z_]
id -> letter (letter|digit)*
If -> if
Then -> then
Else -> else
Relop -> < | > | <= | >= | = | <>
▪ We also need to handle whitespaces:
ws -> (blank | tab | newline)+
Transition diagrams
▪ Transition diagram for relop
Transition diagrams (cont.)
▪ Transition diagram for reserved words and identifiers
Transition diagrams (cont.)
▪ Transition diagram for unsigned numbers
Transition diagrams (cont.)
▪ Transition diagram for whitespace
Finite Automata
▪ Regular expressions = specification
▪ Finite automata = implementation
78
Finite Automata
▪ Transition
s1 →a s2
▪ Is read
In state s1 on input “a” go to state s2
▪ If end of input
• If in accepting state => accept, othewise => reject
▪ If no transition possible => reject
79
Finite Automata State Graphs
▪ A state
• An accepting state
a
• A transition
80
A Simple Example
81
Another Simple Example
82
And Another Example
▪ Alphabet {0,1}
▪ What language does this recognize?
1 0
0 0
1
1
83
And Another Example
▪ Alphabet still { 0, 1 }
1
84
Epsilon Moves
85
Deterministic and Nondeterministic
Automata
▪ Deterministic Finite Automata (DFA)
• One transition per input per state
• No ε-moves
▪ Nondeterministic Finite Automata (NFA)
• Can have multiple transitions for one input in a given state
• Can have ε-moves
▪ Finite automata have finite memory
• Need only to encode the current state
86
Execution of Finite Automata
▪ A DFA can take only one path through the state graph
• Completely determined by input
87
Acceptance of NFAs
▪ An NFA can get into multiple states
1
0 1
• Input: 1 0 1
88
NFA vs. DFA (1)
▪ NFAs and DFAs recognize the same set of languages (regular
languages)
89
NFA vs. DFA (2)
▪ For a given language the NFA can be simpler than the DFA
1
0 0
NFA
0
1 0
0 0
DFA
1
1
▪ High-level sketch
NFA
Regular
expressions DFA
Lexical Table-driven
Specification Implementation of DFA
91
Regular Expressions to NFA (1)
▪ For each kind of rexp, define an NFA
• Notation: NFA for rexp A
• For ε
ε
• For input a
a
92
Regular Expressions to NFA (2)
▪ For AB
A ε
B
• For A | B
B ε
ε
ε
ε A
93
Regular Expressions to NFA (3)
▪ For A*
ε
A
ε
94
Example of RegExp -> NFA conversion
▪ Consider the regular expression
(1 | 0)*1
▪ The NFA is
ε C 1 E ε
A B 1
ε 0 G H ε I J
ε D F ε
ε
95
Next
NFA
Regular
expressions DFA
Lexical Table-driven
Specification Implementation of DFA
96
NFA to DFA. The Trick
▪ Simulate the NFA
▪ Each state of resulting DFA
= a non-empty subset of states of the NFA
▪ Start state
= the set of NFA states reachable through ε-moves from NFA start state
▪ Add a transition S →a S’ to DFA iff
• S’ is the set of NFA states reachable from the states in S after seeing the input
a
• considering ε-moves as well
97
NFA -> DFA Example
ε
ε C 1 E ε
A B 1
ε 0 G H ε I J
ε D F ε
ε
0
0 FGABCDHI
ABCDHI 0 1
1
1 EJGABCDHI
98
NFA to DFA. Remark
▪ An NFA may be in many states at any time
99
Implementation
▪ A DFA can be implemented by a 2D table T
• One dimension is “states”
• Other dimension is “input symbols”
• For every transition Si →a Sk define T[i,a] = k
▪ DFA “execution”
• If in state Si and input a, read T[i,a] = k and skip to state Sk
• Very efficient
100
Table Implementation of a DFA
0
0 T
S 0 1
1
1 U
0 1
S T U
T T U
U T U
101
Implementation (Cont.)
▪ NFA -> DFA conversion is at the heart of tools such as flex or jflex
▪ In practice, flex-like tools trade off speed for space in the choice of
NFA and DFA representations
102
Lexical Analyzer Generator - Lex
[Link].c C [Link]
compiler
declarations
%%
translation rules Pattern {Action}
%%
auxiliary functions
Example
%{
Int installID() {/* funtion to install the
/* definitions of manifest constants
lexeme, whose first character is
LT, LE, EQ, NE, GT, GE, pointed to by yytext, and whose
IF, THEN, ELSE, ID, NUMBER, RELOP */ length is yyleng, into the symbol table
%} and return a pointer thereto */
}
/* regular definitions
delim [ \t\n] Int installNum() { /* similar to installID,
ws {delim}+ but puts numerical constants into a
letter [A-Za-z] separate table */
digit [0-9] }
id {letter}({letter}|{digit})*
number {digit}+(\.{digit}+)?(E[+-]?{digit}+)?
%%
{ws} {/* no action and no return */}
if {return(IF);}
then {return(THEN);}
else {return(ELSE);}
{id} {yylval = (int) installID(); return(ID); }
{number} {yylval = (int) installNum(); return(NUMBER);}
…
Lex patterns
1. Single Character 4. Repetition Operators
a → matches character a * → zero or more times
110
Continue..
▪ Count number of tokens :
int main() // 4 tokens
{ // 1
int a = 10, b = 20; // 9 tokens
printf("sum is :%d", a+b); // 9 tokens
return 0; // 3 tokens
} //1 token
111
112
Answer is 41
113
Symbol Table
int a, b, c;
float i;
1 a integer
2 b integer
3 c integer
114
Bootstrapping
▪ Bootstrapping is widely used in the compilation development.
▪ Bootstrapping is used to produce a self-hosting compiler.
Self-hosting compiler is a type of compiler that can compile its
own source code.
▪ Bootstrap compiler is used to compile the compiler and then
you can use this compiled compiler to compile everything else
as well as future versions of itself.
▪ A compiler can be characterized by three languages:
• Source Language
• Target Language
• Implementation Language
115
Bootstrapping
▪ The T- diagram shows a compiler SCIT for Source S, Target T,
implemented in I.
116
Bootstrapping
▪ Suppose we have a new language L, which we want to make available on several
machines say A and B.
▪ Follow some steps to produce a new language L for machine A:
▪ 1. Create a compiler SCAA for subset, S of the desired language, L using language
"A" and that compiler runs on machine A. Here the language S can have only
some core features of L and A can be the machine language or Assembly
language for Machine A.
▪ 2. Now, we can say that we are now available language S on machine A and now
we can code a program for compiler of language L in S for machine A i.e. Create
a compiler LCSA for language L written in a subset of L.
▪ 3. Compile LCSA using the compiler SCAA to obtain LCAA. LCAA is a compiler for
language L, which runs on machine A and produces code for machine A.
S
L
CS A CA A L
CA A 117
Bootstrapping
L
C LB L
CA A L
CA B
119
Lex: A Lexical analyzer generator
▪ Lex is a computer program that generates lexical analyzers.
▪ Lex is commonly used with the yacc parser generator.
▪ Lex has a language for describing regular expression.
▪ It generate a pattern matcher for the regular expression
specifications provided to it as input.
▪ The input notation for the Lex tool is referred to as the Lex
language and tool itself is Lex compiler.
▪ Lexical analyzer is prepared by creating a program lex.l in the Lex
language. Then, lex.l is run through the Lex compiler to produce a
C program [Link].c.
▪ [Link].c is run through the C compiler to produce an object
program [Link], which is the lexical analyzer that transforms an
input stream into a sequence of tokens.
120
Continue..
121
How to install lex and Yacc
▪ Ubuntu does not come installed with a lex and yacc compiler to do so
install it first by
1. Opening the terminal
2. type - sudo apt-get install flex
3. enter your password
after installation of flex finishes
4. type - sudo apt-get install bison
5. enter your pasword.
Congratualtions Lex and Yacc have been installed on your system.
Command to run Lex
for compiling a lex program
1. write the lex program in a file and save it as file.l (where file is the name
of the file).
2. open the terminal and navigate to the directory where you have saved the
file.l
3. type: lex file.l
4. then type: cc [Link].c -ll
5. then type - ./[Link]
Your lex progam will be running now
Continue..
Lex Specification
A Lex program consists of three parts:
{ definitions } – opitional
{ rules } – essential
{ user subroutines } - essential
Commands to create a LA
lex file.l creates a C program [Link].c
type cc [Link].c –ll produce [Link]
[Link] is lexical analyzer that create token from input
▪ Definitions include declarations of variables, constants, and
regular definitions
125
Continue..
Rules are statements of the form
▪ p1 {action1}
▪ p2 {action2}
▪…
▪ pn {actionn}
▪ where pi is regular expression and actioni describes what action the
lexical analyzer should take when pattern pi matches a lexeme.
Actions are written in C code.
▪ User subroutines are auxiliary procedures needed by the actions.
These can be compiled separately and loaded with the lexical
analyzer.
126
127
COUSINS OF COMPILER
1. Preprocessor
2. Assembler
3. Loader and Link-editor
Minimization of DFA
129
Syntax Analysis
Outline
▪ Role of parser
▪ Context free grammars
▪ Top down parsing
▪ Bottom up parsing
▪ Parser generators
The role of parser
token
Source Lexical Parse tree Rest of Front Intermediate
Parser
program Analyzer End representation
getNext
Token
Symbol
table
The role of parser
▪ The parser obtains a string of tokens from the lexical analyzer and
verifies that the string can be the grammar for the source language.
▪ It detects and reports any syntax errors and produces a parse tree
from which intermediate code can be generated.
▪ Recognize sentences in a language.
▪ Discover the structure of a document/program.
▪ The above tree is used later to guide translation
▪ Model using context free grammars
▪ Recognize using Push down automata/Table Driven Parsers
133
Limitations of regular languages
▪ How to describe language syntax precisely and conveniently. Can
regular expressions be used?
▪ Many languages are not regular, for example, string of balanced
parentheses – ((((…)))) – { (i ) i | i ≥ 0 } – There is no regular
expression for this language
▪ A finite automata may repeat states, however, it cannot remember
the number of times it has been to a particular state
▪ A more powerful language is needed to describe a valid string of
tokens
134
Syntax definition or Grammars
▪ Noam Chomsky gave a mathematical model of grammar in 1956
which is effective for writing computer languages.
▪ A grammar G can be formally written as a 4-tuple (N, T, S, P)
where
• N or VN is a set of variables or non-terminal symbols
• T or Σ is a set of Terminal symbols
• S is a special variable called the Start symbol, S ∈ N
• P is Production rules for Terminals and Non-terminals.
A production rule has the form 𝛼 → 𝛽, where 𝛼 and 𝛽 are strings
on 𝑉𝑁 ∪ Σ and least one symbol of 𝛼 belongs to VN.
135
Grammar
▪ Example
▪ Grammar G1: ({S, A, B}, {a, b}, S, {S →AB, A →a, B →b})
Here,
• S, A, and B are Non-terminal symbols;
• a and b are Terminal symbols
• S is the Start symbol, S ∈ N
• Productions, P : S →AB, A →a, B →b
136
Derivations from a Grammar
▪ Derivations mean replacing a given string’s non-terminal by the
right-hand side of the production rule.
▪ Strings may be derived from other strings using the productions in
a grammar. If a grammar G has a production α → β, we can say
that x α y derives x β y in G. This derivation is written as:
137
Types of Derivation
There are two types of derivations which are as follows −
▪Leftmost Derivation
A derivation A⇒*w is known as leftmost derivation if we use a
production only to the leftmost variable at each step. Here, * means
0, 1, 2,………..n number of derivations.
▪Rightmost Derivation
A derivation A⇒*w is the rightmost derivation if we use
production to the rightmost variable at each step. It is also
called Canonical Derivation.
138
Derivation Examples
▪ Example1 − Let G be a CFG with productions.
S → AA
A → αB
B → b
B → ε
▪ Find Leftmost and Rightmost derivation for string abab
139
Types of Grammars or Chomsky Hierarchy
▪ According to Noam Chomsky, there are four types of grammars:
Type 0, Type 1, Type 2, and Type 3. The following table shows
how they differ from each other:
140
Chomsky Hierarchy
141
142
Context free grammars
▪ Definition − A context-free grammar (CFG) consisting of a
finite set of grammar rules is a quadruple (N, T, P, S) where
• N is a set of non-terminal symbols.
• T is a set of terminals where N ∩ T = NULL.
• P is a set of rules, P: N → (N ∪ T)*, i.e., the left-hand side of
the production rule P does have any right context or left
context.
• S is the start symbol.
Context free grammars
▪ Example
▪ The grammar ({S, F}, {0, 1}, P, S), P: S → 00S | 11F, F → 00F | ε
144
Generation of Derivation Tree
▪ Example
Let a CFG {N,T,P,S} be
N = {S}, T = {a, b}, Starting symbol = S, P = S → SS | aSb | ε
One derivation from the above CFG is “abaabb”
S → SS → aSbS → abS → abaSb → abaaSbb → abaabb
145
Context free grammars
E -> E + T | T
T -> T * F | F
F -> (E) | id
E -> TE’
E’ -> +TE’ | Ɛ
T -> FT’
T’ -> *FT’ | Ɛ
F -> (E) | id
Top Down Parsing
Introduction
E E E E E E
E -> TE’ lm lm lm lm lm
E’ -> +TE’ | Ɛ T E’ T E’ T E’ T E’ T E’
T -> FT’
F T’ F T’ F T’ F T’ + T E’
T’ -> *FT’ | Ɛ
F -> (E) | id id id Ɛ id Ɛ
Recursive descent parsing
▪ Consists of a set of procedures, one for each nonterminal
▪ Execution begins with the procedure for start symbol
▪ A typical procedure for a non-terminal
void A() {
choose an A-production, A->X1X2..Xk
for (i=1 to k) {
if (Xi is a nonterminal
call procedure Xi();
else if (Xi equals the current input symbol a)
advance the input to the next symbol;
else /* an error has occurred */
}
}
Recursive descent parsing (cont)
▪ General recursive descent may require backtracking
▪ The previous code needs to be modified to allow backtracking
▪ In general form it cant choose an A-production easily.
▪ So we need to try all alternatives
▪ If one failed the input pointer needs to be reset and another
alternative should be tried
▪ Recursive descent parsers cant be used for left-recursive grammars
Example
S->cAd
A->ab | a Input: cad
S S S
c A d c A d c A d
a b a
158
Left recursion
• A top down parser with production
A → A α may loop forever
A→β R
R→αR|ε
159
Parse tree corresponding Parse tree corresponding
to a left recursive to the modified grammar
grammar
A A
A R
A R
β α α β α Є
transforms to
S Aa | b
A Ac | Sd | Є
S → Aa → Sda
– Starting from the first rule and replacing all the occurrences of the first
non terminal symbol
163
Removal of left recursion due to
many productions …
• After the first step (substitute S by its rhs in the rules) the
grammar becomes
S Aa | b
A Ac | Aad | bd | Є
S Aa | b
A bdA' | A'
A' cA' | adA' | Є
164
Left recursion elimination (cont.)
▪ There are cases like following
• S -> Aa | b
• A -> Ac | Sd | ɛ
▪ Left recursion elimination algorithm:
• Arrange the nonterminals in some order A1,A2,…,An.
• For (each i from 1 to n) {
• For (each j from 1 to i-1) {
– Replace each production of the form Ai-> Aj γ by the production Ai
-> δ1 γ | δ2 γ | … |δk γ where Aj-> δ1 | δ2 | … |δk are
all current Aj productions
– }
– Eliminate left recursion among the Ai-productions
•}
Left factoring
• In top-down parsing when it is not clear which production to choose
for expansion of a symbol
defer the decision till we have seen enough input.
β2
• Therefore A α β1 | α β2
transforms to A αA’
A’ β1 | β2
166
Left factoring
▪ Left factoring is a grammar transformation that is useful for
producing a grammar suitable for predictive or top-down parsing.
▪ Consider following grammar:
• Stmt -> if expr then stmt else stmt
• | if expr then stmt
▪ On seeing input if it is not clear for the parser which production to
use
▪ We can easily perform left factoring:
• If we have A->αβ1 | αβ2 then we replace it with
• A -> αA’
• A’ -> β1 | β2
Left factoring (cont.)
▪ Algorithm
• For each non-terminal A, find the longest prefix α common to two or more
of its alternatives. If α<> ɛ, then replace all of A-productions A->αβ1
|αβ2 | … | αβn | γ by
• A -> αA’ | γ
• A’ -> β1 |β2 | … | βn
▪ Example:
• S -> I E t S | i E t S e S | a
• E -> b
Dangling else problem again
Dangling else problem can be handled by left factoring
can be transformed to
169
First and Follow
▪ FIRST(X) for a grammar symbol X is the set of terminals that
begin the strings derivable from X.
▪ Rules to compute FIRST set:
▪ If x is a terminal, then FIRST(x) = { ‘x’ }
▪ If x-> Є, is a production rule, then add Є to FIRST(x).
▪ If X->Y1 Y2 Y3….Yn is a production,
• FIRST(X) = FIRST(Y1)
• If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U {
FIRST(Y2) }
• If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X).
Calculate first for following Grammars
Production Rules of Grammar
E -> TE’
E’ -> +T E’|Є
T -> F T’
T’ -> *F T’ | Є
F -> (E) | id
171
Production Rules of Grammar
E -> TE’
E’ -> +T E’|Є
T -> F T’
T’ -> *F T’ | Є
F -> (E) | id
FIRST sets
FIRST(E) = FIRST(T) = { ( , id }
FIRST(E’) = { +, Є }
FIRST(T) = FIRST(F) = { ( , id }
FIRST(T’) = { *, Є }
FIRST(F) = { ( , id }
172
(1) S → aBDh
B → cC
C → bC / ∈
D → EF
E→g/∈
F→f/∈
173
Production Rules of Grammar
S -> ACB | Cbb | Ba
A -> da | BC
B -> g | Є
C -> h | Є
174
Production Rules of Grammar
S -> ACB | Cbb | Ba
A -> da | BC
B -> g | Є
C -> h | Є
FIRST sets
FIRST(S) = FIRST(ACB) U FIRST(Cbb) U FIRST(Ba)
= { d, g, h, b, a, Є}
FIRST(A) = { d } U FIRST(BC)
= { d, g, h, Є }
FIRST(B) = { g , Є }
FIRST(C) = { h , Є }
175
S→A
A → aB / Ad
B→b
C→g
E→E+T/T
T→TxF/F
F → (E) / id
176
Computing follow
▪ To compute FOLLOW(A) for all nonterminals A, apply following
rules until nothing can be added to any follow set:
1. Place $ in Follow(S) where S is the start symbol
2. If there is a production A-> αBβ then everything in First(β) except ɛ is
in Follow(B).
3. If there is a production A-> αB or a production A->αBβ where
First(β) contains ɛ, then everything in Follow(A) is in Follow(B)
1. Example!
178
Example
• Consider grammar for arithmetic expressions
E E+T|T
T T*F|F F ( E ) | id
E T E’
E’ + T E’ | Є
T F T’
T’ * F T’ | Є F ( E ) | id
179
Predictive parsers
• A non recursive top down parsing method
stack
E T E’
E' +T E' | Є
T F T'
T' * F T' | Є
F ( E ) | id
Parse table for the grammar
id + * ( ) $
E E TE’ E TE’
E’ E’ +TE’ E’ Є E’ Є
T T FT’ T FT’
T’ T’ Є T’ *FT’ T’ Є T’ Є
F F id F (E)
• Assume that '$' is a special token that is at the bottom of the stack and terminates
the input string
if X = a = $ then halt
if X = a ≠ $ then pop(x) and ip++
if X is a non terminal
$E’T’F id + id * id $ expand by F id
$E’T’ + id * id $ expand by T’
Є
$E’ + id * id $ expand by E’
+TE’
$E’T+ + id * id $ pop + and ip++
S -> iEtSS’ | a
S’ -> eS | Ɛ
E -> b
Input Symbol
Non -
terminal a b e i t $
S S -> a S -> iEtSS’
S’ S’ -> Ɛ S’ -> Ɛ
S’ -> eS
E E -> b
Practice Assignment
• Construct LL(1) parse table for the expression grammar
bexpr bexpr or bterm | bterm
bterm bterm and bfactor | bfactor
bfactor not bfactor | ( bexpr ) | true | false
• Steps to be followed
– Remove left recursion
– Compute first sets
– Compute follow sets
– Construct the parse table
Error handling
• Stop at the first error and print a message
– Compiler writer friendly
– But not user friendly
– Error productions
– Global correction
193
Panic mode
• Simplest and the most popular method
194
Panic mode
…
• Consider following code
begin
a = b + c; x = p r ; h = x < 0;
end;
195
Phrase level recovery
• Make local correction to the input
196
Error productions
• Add erroneous constructs as productions in the grammar
197
Global corrections
• Considering the program as a whole find a correct
“nearby” program
198
Error Recovery in LL(1)
parser
• Error occurs when a parse table entry M[A,a] is empty
200
Non-recursive predicting parsing
a + b $
Predictive
parsing output
stack X
Y program
Z
$
Parsing
Table
M
Predictive parsing algorithm
Set ip point to the first symbol of w;
Set X to the top stack symbol;
While (X<>$) { /* stack is not empty */
if (X is a) pop the stack and advance ip;
else if (X is a terminal) error();
else if (M[X,a] is an error entry) error();
else if (M[X,a] = X->Y1Y2..Yk) {
output the production X->Y1Y2..Yk;
pop the stack;
push Yk,…,Y2,Y1 on to the stack with Y1 on top;
}
set X to the top stack symbol;
}
Example
▪ id+id*id$
id id F id T*F
id F id
id
Shift-reduce parser
▪ The general idea is to shift some symbols of input to the stack until
a reduction can be applied
▪ At each reduction step, a specific substring matching the body of a
production is replaced by the nonterminal at the head of the
production
▪ The key decisions during bottom-up parsing are about when to
reduce and about what production to apply
▪ A reduction is a reverse of a step in a derivation
▪ The goal of a bottom-up parser is to construct a derivation in
reverse:
• E=>T=>T*F=>T*id=>F*id=>id*id
Handle pruning
▪ Basic operations:
• Shift
• Reduce
Stack Input Action
• Accept $ id*id$ shift
• Error $id *id$ reduce by F->id
▪ Example: id*id $F *id$ reduce by
$T *id$ shift
T->F
$T* id$ shift
$T*id $ reduce by F->id
$T*F $ reduce by
$T $ reduce by E->T
T->T*F
$E $ accept
Handle will appear on top of the stack
S S
A
B
B A
α β γ z α γ z
y x y
Stack Input Stack Input
$αβγ yz$ $αγ xyz$
$αβB yz$ $αBxy z$
$αβBy z$
Conflicts during shit reduce parsing
▪ Two kind of conflicts
• Shift/reduce conflict
• Reduce/reduce conflict
▪ Example:
Stack Input
… if expr then stmt else …$
LR Parsing
▪ The most prevalent type of bottom-up parsers
▪ LR(k), mostly interested on parsers with k<=1
▪ Why LR parsers?
• Table driven
• Can be constructed to recognize all programming language constructs
• Most general non-backtracking shift-reduce parsing method
• Can detect a syntactic error as soon as it is possible to do so
• Class of grammars for which we can construct LR parsers are superset of
those which we can construct LL parsers
States of an LR parser
▪ States represent set of items
▪ An LR(0) item of G is a production of G with the dot at some
position of the body:
• For A->XYZ we have following items
• A->.XYZ
• A->[Link]
• A->XY.Z
• A->XYZ.
• In a state having A->.XYZ we hope to see a string derivable from XYZ next
on the input.
• What about A->[Link]?
Constructing canonical LR(0) item sets
▪ Augmented grammar:
• G with addition of a production: S’->S
▪ Closure of item sets:
• If I is a set of items, closure(I) is a set of items constructed from I by the
following rules:
• Add every item in I to closure(I)
• If A->α.Bβ is in closure(I) and B->γ is a production then add the item
B->.γ to clsoure(I).
▪ Example: I0=closure({[E’->.E]}
E’->E E’->.E
E -> E + T | T E->.E+T
T -> T * F | F E->.T
T->.T*F
F -> (E) | id T->.F
F->.(E)
F->.id
Constructing canonical LR(0) item sets
(cont.)
E E->E.+T
I0=closure({[E’->.E]}
E’->.E I2
E->.E+T T
E’->T.
E->.T T->T.*F
T->.T*F I4
T->.F ( F->(.E)
F->.(E) E->.E+T
E->.T
F->.id T->.T*F
T->.F
F->.(E)
F->.id
Closure algorithm
SetOfItems CLOSURE(I) {
J=I;
repeat
for (each item A-> α.Bβ in J)
for (each prodcution B->γ of G)
if (B->.γ is not in J)
add B->.γ to J;
until no more items are added to J on one round;
return J;
GOTO algorithm
SetOfItems GOTO(I,X) {
J=empty;
if (A-> α.X β is in I)
add CLOSURE(A-> αX. β ) to J;
return J;
}
Canonical LR(0) items
Void items(G’) {
C= CLOSURE({[S’->.S]});
repeat
for (each set of items I in C)
for (each grammar symbol X)
if (GOTO(I,X) is not empty and not in C)
add GOTO(I,X) to C;
until no new set of items are added to C on a round;
}
E’->E
E -> E + T | T
Example
acc
T -> T * F | F
F -> (E) | id
$ I6 I9
E->E+.T
I1
+ T->.T*F T E->E+T.
E’->E. T->.F
T->T.*F
E E->E.+T
F->.(E)
F->.id
I0=closure({[E’->.E]} I2
E’->.E T I7
F I10
E->.E+T E’->T. * T->T*.F
F->.(E) T->T*F.
E->.T T->T.*F id F->.id
T->.T*F id
T->.F I5
F->.(E)
F->.id ( F->id. +
I4
F->(.E)
I8 I11
E->.E+T
E->.T
E E->E.+T )
T->.T*F F->(E.) F->(E).
T->.F
F->.(E)
F->.id
I3
T>F.
Use of LR(0) automaton
▪ Example: id*id
INPUT a1 … ai … an $
Action
=
Shift 6
2 Reduce R->L
More powerful LR parsers
▪ Canonical-LR or just LR method
• Use lookahead symbols for items: LR(1) items
• Results in a large collection of items
▪ LALR: lookaheads are introduced in LR(0) items
Canonical LR(1) items
▪ In LR(1) items each item is in the form: [A->α.β,a]
▪ An LR(1) item [A->α.β,a] is valid for a viable prefix γ if there is a
derivation S=>δAw=>δαβw, where
• Γ= δα
• Either a is the first symbol of w, or w is ε and a is $
*
▪ Example: rm
• S->BB
• B->aB|b
*
S=>aaBab=>aaaBab
rm
Item [B->a.B,a] is valid for γ=aaa
and w=ab
Constructing LR(1) sets of items
SetOfItems Closure(I) {
repeat
for (each item [A->α.Bβ,a] in I)
for (each production B->γ in G’)
for (each terminal b in First(βa))
add [B->.γ, b] to set I;
until no more items are added to I;
return I;
}
SetOfItems Goto(I,X) {
initialize J to be the empty set;
for (each item [A->α.Xβ,a] in I)
add item [A->αX.β,a] to set J;
return closure(J);
}
void items(G’){
initialize C to Closure({[S’->.S,$]});
repeat
for (each set of items I in C)
for (each grammar symbol X)
if (Goto(I,X) is not empty and not in C)
add Goto(I,X) to C;
until no new sets of items are added to C;
}
Example
S’->S
S->CC
C->cC
C->d
Canonical LR(1) parsing table
▪ Method
• Construct C={I0,I1, … , In}, the collection of LR(1) items for G’
• State i is constructed from state Ii:
• If [A->α.aβ, b] is in Ii and Goto(Ii,a)=Ij, then set
ACTION[i,a] to “shift j”
• If [A->α., a] is in Ii, then set ACTION[i,a] to “reduce A->α”
• If {S’->.S,$] is in Ii, then set ACTION[I,$] to “Accept”
• If any conflicts appears then we say that the grammar is not LR(1).
• If GOTO(Ii,A) = Ij then GOTO[i,A]=j
• All entries not defined by above rules are made “error”
• The initial state of the parser is the one constructed from the set of items
containing [S’->.S,$]
Example
S’->S
S->CC
C->cC
C->d
LALR Parsing Table
I4
C->d. , c/d
I47
C->d. , c/d/$
I7
C->d. , $
E->E*E 0 S3 S2 1
E->(E) 1 S4 S5 Acc
E->id 2 S3 S2 6
3 R4 R4 R4 R4
4 S3 S2 7
5 S3 S2 8
I0: E’->.E I1: E’->E. I2: E->(.E)
E->.E+E E->E.+E E->.E+E 6 S4 S5
E->.E*E E->E.*E E->.E*E 7 R1 S5 R1 R1
E->.(E) E->.(E)
E->.id E->.id 8 R2 R2 R2 R2