CD Unit 2
CD Unit 2
UNIT-2
by
V VEERA RASAD
Asst. Prof., Department of CSE
Aditya College of Engineering
token
Source Lexical Parse tree Rest of Front Intermediate
Analyzer Parser End
program representation
getNext
Token
Symbol
table
4
Syntax Analyzer or Parser takes the input from a
Lexical Analyzer in the form of token streams.
The Parser analyzes the source code (token stream)
against the production rules to detect any errors in
the code.
The output of this phase is a parse tree
Parser accomplishes two tasks, i.e., parsing the
code, looking for errors and generating a Parse tree
as the output of the phase.
Parsers are expected to Parse the whole code even
if some errors exist in the program.
Parsers use error recovering strategies
backtracking
LR Parser is of 4 types:
(a) LR(0)
(b) SLR(1)
(c) LALR(1)
(d) CLR(1)
Derivation
E→E*E
E→E+E*E
E → id + E * E
E → id + id * E
E → id + id * id
compiler construction.
No method can detect and remove
Top-down parsers start parsing from the Start symbol, which in itself is non-
terminal.
Example:
(1) A => Aα | β
It is an example of immediate left recursion, where A is any non-terminal
symbol and α represents a string of non-terminals.
(2) S => Aα | β
A => Sd
It is an example of indirect-left recursion.
33
Computing Follow
• To compute Follow(A) for all nonterminals A, apply following
rules until nothing can be added to any follow set:
1. If A is the starting symbol of given grammar, then add $ to
FOLLOW(A)
2. If there is a grammar rule, A-> αBβ(β‡ ɛ) then
FOLLOW(B) = FIRST(β) {doesn’t contain ɛ string}
FOLLOW(B) = FIRST(β)-{ɛ} + FOLLOW(A)
3. If there is a grammar rule, A->αB then
FOLLOW(B) = FOLLOW(A)
34
Example of First and
Follow Sets
E -> TE’
E’ -> +TE’ |
Ɛ
T -> FT’
T’ -> *FT’ | Ɛ
F -> (E) | id
35
E -> TE’ FIRST(E) = FIRST(T)
E’ -> +TE’ | Ɛ FIRST(E’) = {+, Ɛ}
T -> FT’ FIRST(T) = FIRST(F)
T’ -> *FT’ | Ɛ FIRST(T’) = {*, Ɛ}
F -> (E) | id FIRST(F) = {(,id}
grammar, G
Construct the Predictive Parsing Table
Check if the given input string can be
46
Parsing action for input string
id+(id*id)
STACK INPUT ACTION
$E id+(id*id)$ ETE’
$E’T id+(id*id)$ TFT’
$E’T’F id+(id*id)$ Fid
$E’T’id id+(id*id)$ pop id
$E’T’ +(id*id)$ T’ Ɛ
$E’ +(id*id)$ E’+TE’
$E’T+ +(id*id)$ POP +
$E’T (id*id)$ TFT’
$E’T’F (id*id)$ F(E)
Procedure T’()
begin
if input_symbol = ‘*’ then
begin
ADVANCE();
F();
T’();
end
end