0% found this document useful (0 votes)
22 views

CD Notes

Compiler design notes

Uploaded by

jayasreepalani02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

CD Notes

Compiler design notes

Uploaded by

jayasreepalani02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

lOMoARcPSD|33982080

CD Unit 2 - detailed notes

Compiler Design (Dr. A.P.J. Abdul Kalam Technical University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Jaya Sree ([email protected])
lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
UNIT 2
BASIC PARSING TECHNIQUES
I. PARSER

Parser is a compiler that is used to break the data into smaller elements coming from
lexical analysis phase.

A parser takes input in the form of sequence of tokens and produces output in the form
of parse tree.

Types of Parser:

Parser is mainly classified into 2 categories: Top-down Parser, and Bottom-up Parser.
These are explained as following below.

1. Top-down Parser:

Top-down parser is the parser which generates parse for the given input string with the
help of grammar productions by expanding the non-terminals i.e. it starts from the start
symbol and ends on the terminals. It uses left most derivation.

Further Top-down parser is classified into 2 types: Recursive descent parser, and Non-
recursive descent parser.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
(i) Recursive descent parser:

It is also known as Brute force parser or the with backtracking parser. It basically
generates the parse tree by using brute force and backtracking.

Backtracking: It means, if one derivation of a production fails, the syntax analyzer


restarts the process using different rules of same production. This technique may
process the input string more than once to determine the right production.

(ii) Non-recursive descent parser:

It is also known as LL(1) parser or predictive parser or without backtracking parser or


dynamic parser. It uses parsing table to generate the parse tree instead of backtracking.

2. Bottom-up Parser:

Bottom-up Parser is the parser which generates the parse tree for the given input string
with the help of grammar productions by compressing the non-terminals i.e. it starts
from non-terminals and ends on the start symbol. It uses reverse of the right most
derivation.

Bottom-up parsing starts from the leaf nodes of a tree and works in upward direction
till it reaches the root node. Here, we start from a sentence and then apply production
rules in reverse manner in order to reach the start symbol. The image given below
depicts the bottom-up parsers available.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Further Bottom-up parser is classified into 3 types: Shift-Reduce Parsing, LR parser,
and Operator precedence parser.
(i) Shift-Reduce Parsing
Shift Reduce parser attempts for the construction of parse in a similar manner
as done in bottom up parsing i.e. the parse tree is constructed from
leaves(bottom) to the root(up).

(ii) LR parser:

LR parser is the bottom-up parser which generates the parse tree for the given string by
using unambiguous grammar. It follows reverse of right most derivation.

LR parser is of 4 types:

(a) LR(0)

(b) SLR(1)

(c) LALR(1)

(d) CLR(1)

(iii) Operator precedence parser:

It generates the parse tree form given grammar and string but the only condition is two
consecutive non-terminals and epsilon never appear in the right-hand side of any
production.

BOTTOM UP PARSING

II. SHIFT REDUCE PARSER

o Shift reduce parsing is a process of reducing a string to the start symbol of a grammar.
o Shift reduce parsing uses a stack to hold the grammar and an input tape to hold the string.

o Sift reduce parsing performs the two actions: shift and reduce. That's why it is known as
shift reduces parsing.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
o At the shift action, the current symbol in the input string is pushed to a stack.
o At each reduction, the symbols will be replaced by the non-terminals. The symbol is the
right side of the production and non-terminal is the left side of the production.
o Data Structures-

Two data structures are required to implement a shift-reduce parser-

• A Stack is required to hold the grammar symbols.


• An Input buffer is required to hold the string to be parsed.

o Working-

• Initially, shift-reduce parser is present in the following configuration where-


➢ Stack contains only the $ symbol.
➢ Input buffer contains the input string with $ at its end.
• The parser works by-
➢ Moving the input symbols on the top of the stack.
➢ Until a handle β appears on the top of the stack.
• The parser keeps on repeating this cycle until-
➢ An error is detected.
➢ Or stack is left with only the start symbol and the input buffer becomes
empty.
• After achieving this configuration,
➢ The parser stops / halts.
➢ It reports the successful completion of parsing.
o Possible Actions-

A shift-reduce parser can possibly make the following four actions-

(i) Shift-
In a shift action, the next symbol is shifted onto the top of the stack.
(ii) Reduce-
In a reduce action, the handle appearing on the stack top is replaced with the appropriate
non-terminal symbol.
(iii) Accept-

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
In an accept action, the parser reports the successful completion of parsing.
(iv) Error-
In this state, the parser becomes confused and is not able to make any decision.
It can neither perform shift action nor reduce action nor accept action.
o EXAMPLES:
1. Consider the following grammar-
E→E–E
E→E*E
E → id

Parse the input string id – id * id using a shift-reduce parser.

Solution:

Stack Input Buffer Parsing Action

$ id – id * id $ Shift

$ id – id * id $ Reduce E → id

$E – id * id $ Shift

$E– id * id $ Shift

$ E – id * id $ Reduce E → id

$E–E * id $ Shift

$E–E* id $ Shift

$ E – E * id $ Reduce E → id

$E–E*E $ Reduce E → E x E

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

$E–E $ Reduce E → E – E

$E $ Accept

Parse Tree:

E - E

id E * E

id id

2. Consider the following grammar-


S → (L) | a
L → L, S | S

Parse the input string (a, (a, a)) using a shift-reduce parser.

Solution:

Stack Input Buffer Parsing Action

$ (a,(a,a))$ Shift

$( a,(a,a))$ Shift

$(a ,(a,a))$ Reduce S → a

$(S ,(a,a))$ Reduce L → S

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

$(L ,(a,a))$ Shift

$(L, (a,a))$ Shift

$(L,( a,a))$ Shift

$(L,(a ,a))$ Reduce S → a

$(L,(S ,a))$ Reduce L → S

$(L,(L ,a))$ Shift

$(L,(L, a))$ Shift

$(L,(L,a ))$ Reduce S → a

$(L,(L,S) ))$ Reduce L → L , S

$(L,(L ))$ Shift

$(L,(L) )$ Reduce S → (L)

$(L,S )$ Reduce L → L , S

$(L )$ Shift

$(L) $ Reduce S → (L)

$S $ Accept

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

Parse Tree:
S

L L

S S S

( a , ( a , a ) )

3. Consider the following grammar-


S → T L;
T → int | float
L → L, id | id

Parse the input string int id, id; using a shift-reduce parser.

Solution:

Stack Input Buffer Parsing Action

$ int id , id ; $ Shift

$ int id , id ; $ Reduce T → int

$T id , id ; $ Shift

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

$ T id , id ; $ Reduce L → id

$TL , id ; $ Shift

$TL, id ; $ Shift

$ T L , id ;$ Reduce L → L , id

$TL ;$ Shift

$TL; $ Reduce S → T L;

$S $ Accept

Parse Tree:
S

T L

Int id , id ;

4. Considering the string “10201”, design a shift-reduce parser for the following
grammar-
S → 0S0 | 1S1 | 2

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Solution:

Stack Input Buffer Parsing Action

$ 10201$ Shift

$1 0201$ Shift

$10 201$ Shift

$102 01$ Reduce S → 2

$10S 01$ Shift

$10S0 1$ Reduce S → 0 S 0

$1S 1$ Shift

$1S1 $ Reduce S → 1 S 1

$S $ Accept

Parse Tree:
S

1 0 2 0 1

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
o Conflicts in Shift Reduce Parsing
There are two types of conflicts occur in shift reduce parser:
(i) Shift/Reduce Conflict
Every SR Parser can reach a configuration knowing the stack and the input
buffer cannot decide whether to shift or to reduce. Shift/Reduce Conflict occur
in a stack that requests both a shift and a reduce action. When such condition
occurs then the condition is known as shift/reduce conflict.

Example:
S → aABe
A → Abc | b
B→d
Input String: abbcde

STACK INPUT BUFFER ACTION


$ abbcde$ Shift

$a bbcde Shift

$ab bcde$ Reduce A→b

$aA bcde$ Shift

$aAb cde$ Error

Here, Parser can’t decide whether to shift ‘c’ or to reduce ‘b’, because if ‘b’ is
reduced to A→b then there will be non-terminal at the top of the stack which can’t
further be reduced. Such Conflicts are known as Shift/Reduce Conflicts.

(ii) Reduce/Reduce Conflict


Every SR Parser can reach a configuration knowing the entire stack and the next
input symbol cannot decide which of the several reductions to make.
Reduce/Reduce Conflict occur in a state that requests two or more different
reduce actions.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Example:
S → aABe | b
A → Abc | b
B→d
Input String: abbcde

STACK INPUT BUFFER ACTION


$ abbcde$ Shift

$a bbcde Shift

$ab bcde$ Error

Here, Parser can’t decide from which production is to be reduced i.e. from S→b or
A→b. Such Conflicts are known as Reduce/Reduce Conflicts.

• To avoid conflict rightmost derivation is used


S → aABe
A → Abc | b
B→d
Input String: abbcde

RMD: S → aABe

aAde (B→d)

aAbcde (A→Abc)

abbcde (A→b)

Now with the help of this RMD we can do the stack representation.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

STACK INPUT BUFFER ACTIONS


$ abbcde$ Shift
$a bbcde$ Shift
$ab bcde$ Reduce A→b
$Aa bcde$ Shift
$aAb cde$ Shift
$aAbc de$ Reduce A→Abc
$Aa de$ Shift
$aAd e$ Reduce B→d
$aAB e$ Shift
$aABe $ Reduce S→aABe
$S $ Accept

Parse Tree:
S

a A B e

A b c d

III. OPERATOR PRECENDENCE PARSER


o A grammar that satisfies the following 2 conditions is called as Operator Precedence
Grammar–
• There exists no production rule which contains ε on its RHS.
• There exists no production rule which contains two non-terminals adjacent to each
other on its RHS.
o A parser that reads and understand an operator precedence grammar is called as Operator
Precedence Parser.
o In operator precedence parsing,

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
• Firstly, we define precedence relations between every pair of terminal symbols.
• Secondly, we construct an operator precedence table.
o Defining Precedence Relations:
The precedence relations are defined using the following rules-
• Rule 1:
➢ If precedence of b is higher than precedence of a, then we define a < b
➢ If precedence of b is same as precedence of a, then we define a = b
➢ If precedence of b is lower than precedence of a, then we define a > b
• Rule 2:
➢ An identifier is always given the higher precedence than any other symbol.
➢ $ symbol is always given the lowest precedence.
• Rule 3:
➢ If two operators have the same precedence, then we go by checking their
associativity.
o Steps for parsing a string:
• Step 1:
Insert the following-
➢ $ symbol at the beginning and ending of the input string.
➢ Precedence operator between every two symbols of the string by referring
the operator precedence table.
• Step 2:
➢ Start scanning the string from LHS in the forward direction until > symbol
is encountered.
➢ Keep a pointer on that location.
• Step 3:
➢ Start scanning the string from RHS in the backward direction until < symbol
is encountered.
➢ Keep a pointer on that location.
• Step 4:
➢ Everything that lies in the middle of < and > forms the handle.
➢ Replace the handle with the head of the respective production.
• Step 5:
➢ Keep repeating the cycle from Step-02 to Step-04 until the start symbol is
reached.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
o Operator Precedence Function:
• Precedence functions perform the mapping of terminal symbols to the integers.
• To decide the precedence relation between symbols, a numerical comparison is
performed.
• It reduces the space complexity to a large extent.

o EXAMPLES:
1. Consider the following grammar-
E → EAE | id
A→+|x

Construct the operator precedence parser and parse the string id + id + id.
Solution:

We convert the given grammar into operator precedence grammar.


The equivalent operator precedence grammar is-

E → E + E | E * E | id

The terminal symbols in the grammar are { id, + , * , $ }


We construct the operator precedence table as-

id + * $

id > > >

+ < > < >

* < > > >

$ < < <

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Stack Representation:

STACK INPUT BUFFER ACTION


$ id+id+id$ Shift
$id +id+id$ Reduce
$ +id+id$ Shift
$+ id+id$ Shift
$+id +id$ Reduce
$+ +id$ Reduce
$ +id$ Shift
$+ id$ Shift
$+id $ Reduce
$+ $ Reduce
$ $ Accept

Parse Tree:

E E

id id id + id

2. Consider the following grammar-


S → (L) | a
L → L, S | S

Construct the operator precedence parser and parse the string (a, (a, a)).

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

Solution:
The terminal symbols in the grammar are { ( , ) , a , , }
We construct the operator precedence table as-

( ) , $
a

a > > > >

( < > > > >

) < > > > >

, < < < > >

$ < < < <

Stack Representation:

STACK INPUT BUFFER ACTION


$ (a,(a, a))$ Shift
$( a,(a, a))$ Shift
$(a ,(a, a))$ Reduce S → a
$(S ,(a, a))$ Reduce L → S
$(L ,(a, a))$ Shift
$(L, (a, a))$ Shift
$(L,( a, a))$ Shift
$(L,(a , a))$ Reduce S → a
$(L,(S , a))$ Reduce L → S

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

$(L,(L , a))$ Shift


$(L,(L, a))$ Shift
$(L,(L, a ))$ Reduce S → a
$(L,(L, S ))$ Reduce L → L, S
$(L,(L ))$ Shift
$(L,(L) )$ Reduce S → (L)
$(L,S )$ Reduce L → L, S
$(L )$ Shift
$(L) $ Reduce S → (L)
$S $ Accept

Parse Tree:
S

L L

S S S

( a , ( a , a ) )

IV. LR (k) PARSING


LR parsing is one type of bottom up parsing. It is used to parse the large class of
grammars.
In the LR parsing, "L" stands for left-to-right scanning of the input.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
"R" stands for constructing a right most derivation in reverse.
"K" is the number of input symbols of the look ahead used to make number of parsing
decision.

LR parsing is divided into four parts: LR (0) parsing, SLR parsing, CLR parsing and LALR
parsing.

V. LR (0) PARSER
Steps to solve LR (0) Parser are:
(i) Augment the given grammar.
Augmented grammar G` will be generated if we add one more production in the
given grammar G. It helps the parser to identify when to stop the parsing and
announce the acceptance of the input.
(ii) Draw canonical collection of LR (0) items.
An LR (0) item is a production G with dot at some position on the right side of the
production.
LR (0) items is useful to indicate that how much of the input has been scanned up
to a given point in the process of parsing.
In the LR (0), we place the reduce node in the entire row.
(iii)Number the Productions.
(iv) Create the Parsing Table.
The Parsing Table consists of two parts:
1. A Parsing Action Function
The Action Table specifies the actions of the parser (e.g., shift or reduce), for
the given parse state and the next token
✓ Rows are State Names;
✓ Columns are Terminals
❖ The LR Parser determines Sm, the state on top of the stack and ai, the Current
Input symbol.
❖ It then consults Action [Sm, ai] which can take one of four values:

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
✓ Shift
✓ Reduce
✓ Accept
✓ Error
❖ If Action [Sm, ai] = Shift S
✓ Where S is a State, then the Parser pushes ai and S on to the Stack.
❖ If Action [Sm, ai] = Reduce A → β,
✓ Then ai and Sm are replaced by A
✓ if S was the state appearing below ai in the Stack, then GOTO [S, A] is
consulted and the state pushed onto the stack.
❖ If Action[ Sm, ai ] = Accept,
✓ Parsing is completed
❖ If Action[ Sm, ai ] = Error,
✓ The Parser discovered an Error.
2. A GOTO function.
The GOTO table specifies which state to put on top of the stack after a reduce
✓Rows are State Names;
✓Columns are Non-Terminals
❖ The GOTO Table is important to find out the next state after every reduction.
❖ The GOTO Table is indexed by a state of the parser and a Non Terminal
(Grammar Symbol) ex : GOTO[S, A]
❖ The GOTO Table simply indicates what the next state of the parser if it has
recognized a certain Non Terminal.
❖ Right Sentential Form is a Sentential Form in a Rightmost Derivation
Example: (S)S , ( (S)S)
❖ Viable Prefix is a sequence of symbols on the parsing stack Example:
✓ (S)S, (S), (S, (,
✓ ((S)S, ((S), ((S , ((, (
(v) Stack Implementation.
(vi) Draw the Parse Tree.
o EXAMPLES:
1. Consider the given grammar

S → AA
A → aA | b
Construct the LR (0) parser and parse the string aabb.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Solution:

Step (i): - Augment the Given Grammar

S`→ S
S → AA
A → aA | b

Step (ii): - Draw Canonical Collection of LR (0) items

S` → •S
S → •AA
A → •aA
A → •b

Step (iii): - Number the Productions

S → AA ------------------ (1)
A → aA ------------------ (2)
A→b ------------------ (3)

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Step (iv): - Create the Parsing Table

Explanation:

o I0 on S is going to I1 so write it as 1.
o I0 on A is going to I2 so write it as 2.
o I2 on A is going to I5 so write it as 5.
o I3 on A is going to I6 so write it as 6.
o I0, I2and I3on a are going to I3 so write it as S3 which means that shift 3.
o I0, I2 and I3 on b are going to I4 so write it as S4 which means that shift 4.
o I4, I5 and I6 all states contain the final item because they contain • in the right most end.
So rate the production as production number with R means reduce.

Step (v): - Stack Implementation

STACK INPUT BUFFER ACTIONS


$0 aabb$ Shift a to stack &
goto state 3
$0a3 abb$ Shift
$0a3a3 bb$ Shift
$0a3a3b4 b$ Reduce A→b
$0a3a3A6 b$ Reduce A→aA
$0a3A6 b$ Reduce A→aA

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

$0A2 b$ Shift
$0A2b4 $ Reduce A→b
$0A2A5 $ Reduce S→AA
$0S1 $ Accept

Step (vi): - Parse Tree

A A

a A b

a A

VI. FIRST AND FOLLOW


First and Follow sets are needed so that the parser can properly apply the needed
production rule at the correct position.

• First Function-
First(α) is a set of terminal symbols that begin in strings derived from α.
➢ Rules for Calculating First Function
▪ Rule-01:
For a production rule X → ∈,

First(X) = {∈}
▪ Rule-02:
For any terminal symbol ‘a’,

First(a) = { a }

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
▪ Rule-03:
For a production rule X → Y1Y2Y3,

Calculating First(X)

If ∈ ∉ First(Y1), then First(X) = First(Y1)


If ∈ ∈ First(Y1), then First(X) = { First(Y1) – ∈ } ∪ First(Y2Y3)

Calculating First(Y2Y3)

If ∈ ∉ First(Y2), then First(Y2Y3) = First(Y2)


If ∈ ∈ First(Y2), then First(Y2Y3) = {First(Y2) – ∈} ∪ First(Y3)

Similarly, we can make expansion for any production rule X →


Y1Y2Y3…...Yn.
• Follow Function-
Follow(α) is a set of terminal symbols that appear immediately to the right of
α.
➢ Rules for Calculating Follow Function-
▪ Rule-01:
For the start symbol S, place $ in Follow(S).
▪ Rule-02:
For any production rule A → αB,

Follow(B) = Follow(A)
▪ Rule-03:
For any production rule A → αBβ,

✓ If ∈ ∉ First(β), then Follow(B) = First(β)


✓ If ∈ ∈ First(β), then Follow(B) = {First(β) – ∈ } ∪ Follow(A)

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
➢ Important Notes-
▪ Note-01:
✓ ∈ may appear in the first function of a non-terminal.
✓ ∈ will never appear in the follow function of a non-
terminal.
▪ Note-02:
✓ Before calculating the first and follow functions, eliminate
Left Recursion from the grammar, if present.
▪ Note-03:
✓ We calculate the follow function of a non-terminal by
looking where it is present on the RHS of a production rule.
o EXAMPLES:
1. Calculate the first and follow functions for the given grammar-

S → aBDh

B → cC

C → bC / ∈

D → EF

E→g/∈

F→f/∈
Solution:

FIRST FOLLOW

S b $

B c {First(D) – ∈} ∪ First(h)={ g , f , h }

C b, ∈ Follow(B) = { g , f , h }

D {First(E) – ∈} ∪ First(F) = { g , f , ∈ } First(h) = { h }

E {g,∈} {First(F) – ∈} ∪ Follow(D)={ f , h }

F {f,∈} Follow(D) = { h }

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
2. Calculate the first and follow functions for the given grammar-
S→A
A → aB / Ad
B→b
C→g

Solution:
We have: -
The given grammar is left recursive.
So, we first remove left recursion from the given grammar.
After eliminating left recursion, we get the following grammar-
S→A
A → aBA’
A’ → dA’ / ∈
B→b
C→g
Now, the first and follow functions are as follows-

FIRST FOLLOW

S First(A) = { a } $

A a Follow(S) = { $ }

A’ d, ∈ Follow(A) = { $ }

B b {First(A’) – ∈} ∪ Follow(A)={d , $}

C g Not Available

3. Calculate the first and follow functions for the given grammar-
S → (L) / a
L → SL’
L’ →, SL’ / ∈

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

Solution:
The first and follow functions are as follows-

FIRST FOLLOW

S (,a { $ } ∪ { First(L’) – ∈ } ∪
Follow(L) ∪ Follow(L’) = { $ , , , ) }

L (,a )

L’ ,,∈ Follow(L) = { ) }

4. Calculate the first and follow functions for the given grammar-
S → AaAb / BbBa
A→∈
B→∈
Solution:
The first and follow functions are as follows-

FIRST FOLLOW

S { First(A) – ∈ } ∪ First(a) ∪ { First(B) $


– ∈ } ∪ First(b) = { a , b }

A ∈ First(a) ∪ First(b) = { a , b }

B ∈ First(b) ∪ First(a) = { a , b }

5. Calculate the first and follow functions for the given grammar-
E→E+T/T
T→T*F/F
F → (E) / id
Solution:
We have: -
The given grammar is left recursive.
So, we first remove left recursion from the given grammar.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
After eliminating left recursion, we get the following grammar-
E → TE’
E’ → + TE’ / ∈
T → FT’
T’ → x FT’ / ∈
F → (E) / id

Now, the first and follow functions are as follows-

FIRST FOLLOW

E First(T) = First(F) = { ( , id } $,)

E’ +, ∈ Follow(E) = { $ , ) }

T First(F) = { ( , id } { First(E’) – ∈ } ∪ Follow(E) ∪


Follow(E’) = { + , $ , ) }

T’ *, ∈ Follow(T) = { + , $ , ) }

F ( , id { First(T’) – ∈ } ∪ Follow(T) ∪
Follow(T’) = { * , + , $ , ) }

6. Calculate the first and follow functions for the given grammar-
S → ACB / CbB / Ba
A → da / BC
B→g/∈
C→h/∈
Solution:
The first and follow functions are as follows-

FIRST FOLLOW

S { First(A) – ∈ } ∪ { First(C) – ∈ } ∪ $
First(B) ∪ First(b) ∪ { First(B) – ∈ } ∪
First(a) = { d , g , h , ∈ , b , a }

A First(d) ∪ { First(B) – ∈ } ∪ First(C) { First(C) – ∈ } ∪ { First(B) – ∈ } ∪


={d,g,h,∈} Follow(S) = { h , g , $ }

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

B g,∈ Follow(S) ∪ First(a) ∪ { First(C) – ∈


} ∪ Follow(A) = { $ , a , h , g }

C h,∈ {First(B) – ∈ } ∪ Follow(S) ∪


First(b) ∪ Follow(A) = {g , $ , b , h }
VII. SLR PARSER
SLR (1) refers to simple LR Parsing. It is same as LR (0) parsing. The only difference
is in the parsing table. To construct SLR (1) parsing table, we use canonical collection
of LR (0) item.
In the SLR (1) parsing, we place the reduce move only in the follow of left hand side.

Various steps involved in the SLR (1) Parsing:


(i) For the given input string write a context free grammar
(ii) Check the ambiguity of the grammar
(iii)Add Augment production in the given grammar
(iv) Create Canonical collection of LR (0) items
(v) Draw a data flow diagram (DFA)
(vi) Construct a SLR (1) parsing table
o EXAMPLES:
1. Consider the given grammar

S → AA
A → aA | b
Construct the SLR (1) parser and parse the string aabb.

Solution:

Step (i): - Augment the Given Grammar

S`→ S
S → AA
A → aA | b

Step (ii): - Draw Canonical Collection of LR (0) items

S` → •S
S → •AA

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
A → •aA
A → •b

Step (iii): - Number the Productions

S → AA ------------------ (1)
A → aA ------------------ (2)
A→b ------------------ (3)
• In the parsing table as like LR (0) parser the entries of SHIFT operation and
NUMBERS will be done as it is but the entries of REDUCE operation will be
done on the basis of FOLLOW of left hand side of that production. Suppose,
the production is B → d so the entry of REDUCE operation will be done in
the FOLLOW (B).

Step (iv): - Create Parsing Table

To create parsing table first calculate FIRST & FOLLOW:

FIRST FOLLOW
S a,b $
A a,b a,b,$

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

STATES ACTION GOTO


a b $ S A
I0 S3 S4 1 2
I1 Accept
I2 S3 S4 5
I3 S3 S4 6
I4 R3 R3 R3
I5 R1
I6 R2 R2 R2

Explanation:

o I0 on S is going to I1 so write it as 1.
o I0 on A is going to I2 so write it as 2.
o I2 on A is going to I5 so write it as 5.
o I3 on A is going to I6 so write it as 6.
o I0, I2and I3on a are going to I3 so write it as S3 which means that shift 3.
o I0, I2 and I3 on b are going to I4 so write it as S4 which means that shift 4.
o I4, I5 and I6 all states contain the final item because they contain • in the right most end.
So rate the production as production number with R means reduce in the follow of that
particular production.

Step (v): - Stack Implementation

STACK INPUT BUFFER ACTIONS


$0 aabb$ Shift a to stack &
goto state 3
$0a3 abb$ Shift
$0a3a3 bb$ Shift
$0a3a3b4 b$ Reduce A→b

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

$0a3a3A6 b$ Reduce A→aA


$0a3A6 b$ Reduce A→aA
$0A2 b$ Shift
$0A2b4 $ Reduce A→b
$0A2A5 $ Reduce S→AA
$0S1 $ Accept

Step (vi): - Parse Tree

A A

a A b

a A

2. Consider the following grammar:


S→E
E→E+T|T
T→T*F|F
F → id

Construct the SLR (1) parser and parse the string id + id * id.
Solution:

Step (i): - Augment the Given Grammar

S` → E
E→E+T
E→T

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
T→T*F
T→F
F → id
Step (ii): - Draw Canonical Collection of SLR (1) items

S` → •E
E → •E + T
E → •T
T → •T * F
T → •F
F → •id

Step (iii): - Number the Productions

E → E + T ------------------ (1)
E→T ------------------ (2)
T → T * F ------------------ (3)
T→F ------------------ (4)
F → id ------------------ (5)

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Step (iv): - Create Parsing Table

To create parsing table first calculate FIRST & FOLLOW:

FIRST FOLLOW
E Id $,+
T Id $,+,*
F Id $,+,*

STATES ACTION GOTO


id + * $ E T F
I0 S4 1 2 3
I1 S5 Accept
I2 R2 S6 R2
I3 R4 R4 R4
I4 R5 R5 R5
I5 S4 7 3
I6 S4 8
I7 R1 S6 R1
I8 R3 R3 R3

Step (v): - Stack Implementation

STACK INPUT BUFFER ACTIONS


$0 id + id * id$ Shift
$0id4 + id * id$ Reduce F→id
$0F3 + id * id$ Reduce T→F
$0T2 + id * id$ Reduce E→T
$0E1 + id * id$ Shift

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

$0E1+5 id * id$ Shift


$0E1+5id4 * id$ Reduce F→id
$0E1+5F3 * id$ Reduce T→F
$0E1+5T7 * id$ Shift
$0E1+5T7*6 id$ Shift
$0E1+5T7*6id4 $ Reduce F → id
$0E1+5T7*6F8 $ Reduce T → T*F
$0E1+5T7 $ Reduce E → E+T
$E1 $ Accept

Step (vi): - Parse Tree

E + T

T T * F

F F id

Id id

VIII. CLR (1) PARSER


CLR refers to canonical lookahead. CLR parsing use the canonical collection of LR
(1) items to build the CLR (1) parsing table. CLR (1) parsing table produces the more
number of states as compare to the SLR (1) parsing.
In the CLR (1), we place the reduce node only in the look-ahead symbols.
Various steps involved in the CLR (1) Parsing:
(i) For the given input string write a context free grammar
(ii) Check the ambiguity of the grammar
(iii)Add Augment production in the given grammar

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
(iv) Create Canonical collection of LR (0) items
(v) Draw a data flow diagram (DFA)
(vi) Construct a CLR (1) parsing table

LR (1) items: LR (1) item is a collection of LR (0) items and a look ahead symbol.

LR (1) item = LR (0) item + look ahead

The look ahead is used to determine that where we place the final item.

The look ahead always add $ symbol for the argument production.

How to find look-ahead?

Suppose we have a grammar:

E → BB

B → cB | d

So first we have to augment a grammar

E’ → E
E → BB
B → cB | d
Now here always $ will be added in the lookahead of augmented grammar

E’ → .E, $
E → .BB, $ (Here we are opening E so the lookahead of
E → BB will be FIRST(E) i.e. $ which is coming
just after .E in E → .E)
B → .cB | .d, c|d

o EXAMPLES:
1. Consider the given grammar:
S → CC
C → cC | d

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Step (i): - Augment the Given Grammar

S’ → S
S → CC
C → cC | d

Step (ii): - Create LR (1) items & lookahead and draw Canonical Collection of LR (1) items

S’ → .S, $
S → .CC, $
C → .cC , c|d
C → .d, c|d

I1 I5
S S’ → S., $ S → CC., $
I0 C I6
I2
S’ → .S, $ C S → C.C, $ c C → c.C, $ C
I9
S → .CC, $ C → .cC, $ C → .cC, $
C → cC., $
C → .cC, c|d C → .d, $ C → .d, $
d
C → .d, c|d c I3
C → d., $ I7
C → c.C, c|d
d C → .cC, c|d C
I4 C → cC., c|d I8
C → d., c|d
C → .d, c|d

Step (iii): - Number the productions


S → .CC ------------------ (1)
C → .Cc ------------------ (2)
C → .d -------------------- (3)

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Step (iv): - Create the Parsing Table

STATES ACTION GOTO


c d $ S C
I0 S3 S4 1 2
I1 Accept
I2 S6 S7 5
I3 S3 S4 8
I4 R3 R3
I5 R1
I6 S6 S7 9
I7 R3
I8 R2 R2
R2

Now the STACK IMPLEMENTATION & PARSE TREE are constructed same as LR (0)
and SLR (1) Parser.

IX. LALR (1) PARSER


LALR refers to the look-ahead LR. To construct the LALR (1) parsing table, we use
the canonical collection of LR (1) items.
In the LALR (1) parsing, the LR (1) items which have same productions but different
look-ahead are combined to form a single set of items
LALR (1) parsing is same as the CLR (1) parsing, only difference in the parsing table.

o EXAMPLES:
1. Consider the given grammar:
S → CC
C → cC | d
Step (i): - Augment the Given Grammar

S’ → S
S → CC
C → cC | d

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

Step (ii): - Create LR (1) items & lookahead and draw Canonical Collection of LR (1) items

S’ → .S, $
S → .CC, $
C → .cC , c|d
C → .d, c|d

I1 I5
S S’ → S., $ S → CC., $
I0 C I6
I2
S’ → .S, $ C S → C.C, $ c C → c.C, $ C
I9
S → .CC, $ C → .cC, $ C → .cC, $
C → cC., $
C → .cC, c|d C → .d, $ C → .d, $
d
C → .d, c|d c I3
C → d., $ I7
C → c.C, c|d
d C → .cC, c|d C
I4 C → cC., c|d I8
C → d., c|d C → .d, c|d

Step (iii): - Number the productions


S → .CC ------------------ (1)
C → .Cc ------------------ (2)
C → .d -------------------- (3)
Step (iv): - Create the Parsing Table

STATES ACTION GOTO


c d $ S C
I0 S3 S4 1 2
I1 Accept
I2 S6 S7 5
I3 S3 S4 8

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

I4 R3 R3
I5 R1
I6 S6 S7 9
I7 R3
I8 R2 R2
R2

Now in the above parsing table, we will see in which state the production is same but the
look-ahead is different. So, we get:
I3 + I6 = I36
I4 + I7 = I47
I8 + I9 = I89
Merge the States in the parsing table also, at the place of Shift function and State Name.
No changes on Reduce function. After merging, remove one row between the two similar
rows.

STATES ACTION GOTO


c d $ S C
I0 S36 S47 1 2
I1 Accept
I2 S36 S47 5
I36 S36 S47 89
I47 R3 R3 R3
I5 R1
I36 S36 S47 89
I47 R3 R3 R3
I89 R2 R2 R2
I89 R2 R2 R2

Now update the canonical collection by merging the look-ahead and construct the new
parsing table.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

I1 I5
S S’ → S., $ S → CC., $
I0 C I36
I2 S

S’ → .S, $ C S → C.C, $ c C → c.C, C


$|c|d I89
S → .CC, $ C → .cC, $
C → .cC, C → cC., $|c|d
C → .cC, c|d C → .d, $ $|c|d
d
C → .d, c|d c I36
C → d., $|c|d I47
C → c.C,
d c|d|$
C
I47 C → cC., c|d|$ I89
C → .cC,
C → d., c|d|$ c|d|$

So the improved DFD is:

I1 I5
S S’ → S., $ S → CC., $
I0 C
I2
S’ → .S, $ C S → C.C, $
S → .CC, $ C → .cC, $
C → .cC, c|d C → .d, $
C → .d, c|d c I36
C → c.C,
d c|d|$
C
I47 C → cC., c|d|$ I89
C → .cC,
C → d., c|d|$ c|d|$

And the updated parsing table is:

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

STATES ACTION GOTO


C d $ S C
I0 S36 S47 1 2
I1 Accept
I2 S36 S47 5
I36 S36 S47 89
I47 R3 R3 R3
I5 R1
I89 R2 R2 R2

Now the STACK IMPLEMENTATION & PARSE TREE are constructed same as LR (0)
and SLR (1) Parser.

X. LEFT RECURSION
o A production of grammar is said to have left recursion if the leftmost variable of its
RHS is same as variable of its LHS.
o A grammar containing a production having left recursion is called as Left Recursive
Grammar.
o Elimination of Left Recursion
Left recursion is eliminated by converting the grammar into a right recursive
grammar.
If we have the left-recursive pair of productions-

A → Aα / β
(Left Recursive Grammar)

where β does not begin with an A.

Then, we can eliminate left recursion by replacing the pair of productions with-

A → βA’
A’ → αA’ / ∈
(Right Recursive Grammar)

This right recursive grammar functions same as left recursive grammar.


o EXAMPLES:

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
1. Consider the following grammar and eliminate left recursion-

A → ABd / Aa / a

B → Be / b
Solution:
The grammar after eliminating left recursion is-

A → aA’
A’ → BdA’ / aA’ / ∈
B → bB’
B’ → eB’ / ∈

2. Consider the following grammar and eliminate left recursion-

E→E+E/ExE/a

Solution:
The grammar after eliminating left recursion is-

E → aA
A → +EA / xEA / ∈

3. Consider the following grammar and eliminate left recursion-

E→E+T/T
T→TxF/F
F → id
Solution:
The grammar after eliminating left recursion is-

E → TE’
E’ → +TE’ / ∈
T → FT’
T’ → xFT’ / ∈
F → id

4. Consider the following grammar and eliminate left recursion-

S → (L) / a
L → L, S / S

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Solution:
The grammar after eliminating left recursion is-

S → (L) / a
L → SL’
L’ →, SL’ / ∈

5. Consider the following grammar and eliminate left recursion-

S → S0S1S / 01
Solution:
The grammar after eliminating left recursion is-

S → 01A
A → 0S1SA / ∈

XI. LEFT FACTORING


o Left factoring is a process by which the grammar with common prefixes is transformed
to make it useful for Top down parsers.
o If RHS of more than one production starts with the same symbol, then such a grammar
is called as Grammar with Common Prefixes.
Example: A → αβ1 / αβ2 / αβ3
o In left factoring,

• We make one production for each common prefixes.


• The common prefix may be a terminal or a non-terminal or a combination of both.
• Rest of the derivation is added by new productions.

The grammar obtained after the process of left factoring is called as Left Factored
Grammar.

o EXAMPLES:
1. Do left factoring in the following grammar-

S → iEtS / iEtSeS / a
E→b

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Solution:
The left factored grammar is-

S → iEtSS’ / a
S’ → eS / ∈
E→b
2. Do left factoring in the following grammar-

A → aAB / aBc / aAc


Solution:
Step-01:
A → aA’
A’ → AB / Bc / Ac

Again, this is a grammar with common prefixes.

Step-02:
A → aA’
A’ → AD / Bc
D→B/c

This is a left factored grammar.

3. Do left factoring in the following grammar-

S → bSSaaS / bSSaSb / bSb / a


Solution:
Step-01:
S → bSS’ / a
S’ → SaaS / SaSb / b

Again, this is a grammar with common prefixes.

Step-02:
S → bSS’ / a
S’ → SaA / b
A → aS / Sb

This is a left factored grammar.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
TOP DOWN PARSING
XII. LL (1) PARSER OR PREDICTIVE PARSER:

o In LL1, first L stands for Left to Right and second L stands for Left-most Derivation.
1 stands for number of Look-ahead token used by parser while parsing a sentence.
o LL (1) parsing is constructed from the grammar which is free from left recursion,
common prefix, and ambiguity.
o LL (1) parser depends on 1 look ahead symbol to predict the production to expand
the parse tree.
o This parser is Non-Recursive.
o Steps to Parse a string using LL (1) or Predictive parser:
(i) Eliminate Left Recursion & Left Factoring.
(ii) Calculate FIRST & FOLLOW of the given grammar.
(iii) Construct the parsing table.
(iv) Stack Implementation
(v) Construct the Parse Tree.
o EXAMPLES:
1. Consider a given grammar:
E → E+T | T
T → T+F | F
F → (E) | id
Parse the string id + id * id using LL (1) parser
Solution:
Step (i): Eliminate Left Recursion
E → TE'
E' → +TE' | ε
T → FT'
T' → *FT' | ε
F → id | (E)
Step (ii): Calculate First & Follow

PRODUCTION FIRST FOLLOW


E → TE'
id, ( $, )
E' → +TE' | ε +, ε $, )
T → FT'
id, ( +, $, )
T' → *FT' | ε
*, ε +, $, )
F → (E) | id
id, ( *, +, $, )

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Step (iii): Construct the Parsing Table
In the parsing table of LL (1) Parser, there is no entry of shift & reduce operation as like
bottom up parser. Instead, the production itself is the entry. The entry is done in the First
of that production and if First of that production contains ε then the entry is done in the
follow of that production.

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)

Step (iv): Stack Implementation

Stack Input Buffer Parsing Action

E$ id + id * id $ E → TE’

TE’$ id + id * id $ T → FT’

FT’E’$ id + id * id $ F → id

id T’E’$ id + id * id $ T’ → ε

E’$ + id * id $ E' → +TE'

+TE’$ + id * id $ T → FT’

FT’E’$ id * id $ F → id

idT’E’$ id * id$ T' → *FT’

*FT’E’$ * id$ F → id

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------

idT’E’ $ id$ T’ → ε

E’$ $ E’ → ε

$ $ Accept

Step (v): Parse Tree

T E’

F T’ + T E’

id ε F T’ ε

id * F T’

id ε

2. Consider a given grammar:


S → iEtS | iEtSeS | a
E→b
Check whether the given grammar is LL (1) grammar or not.

Solution:
Step (i): Eliminate Left Recursion
S → iEtSS’ | a
S’→ Es | ε
E→b
Step (ii): Calculate First & Follow

PRODUCTION FIRST FOLLOW


S → iEtSS’ | a
i, a e, $

S’→ Es | ε e, ε e, $
E→b
b t

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Step (iii): Construct the Parsing Table

a b e i t $
S S→a S → iEtSS’
S’ S → Es S' → ε
S' → ε
E E→b

Since there are two entries in the single block of parsing table so the above grammar
is not LL (1) grammar.

XIII. RECURSIVE DESCENT PARSER

o Recursive-descent parsing is one of the simplest parsing techniques that is used in


practice. Recursive-descent parsers are also called top-down parsers, since they construct
the parse tree top down (rather than bottom up) and uses a set of recursive procedure to
scan its input.
o The parsing method may involve backtracking i.e. making repeated scan of its input.
o Steps for Recursive Descent Parser
• Whenever a Non-terminal expand first time then go with the first alternative and
compare with the given input string.
• If the matching does not occur, then go with the second alternative and compare it
with the given input string
• If the matching again not found, then go with the alternative and so on.
• Moreover, if the matching occurs for at least one alternative then it means that the
input string is parsed successfully.

EXAMPLES:
1. Consider the grammar G
S → cAd
A→ ab | a
Construct a parse tree for the input string w=cad using Recursive Descent Parser.

Input pointer
Step (i): Elaborate the start symbol
S

c A d

descent pointer

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
Now compare the input pointer & descent pointer. If both are matching, then move
forward.
w = cad

Input pointer
Step (ii): Now move descent pointer also and check whether there is terminal or non-
terminal. If there is non-terminal, then elaborate.
S

c A d

a b

descent pointer
Now compare the input pointer & descent pointer. If both are matching, then move
forward.
w = cad

Input pointer

c A d

a b

descent pointer
Now here input pointer & descent pointer are not matching. So, backtracking will be
used.
Step (iii): Backtrack and use another production
w = cad

Input pointer
S

c A d

descent pointer
Now compare input pointer & descent pointer. So, it matched now move forward.

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])


lOMoARcPSD|33982080

Subject: Compiler Design Prachi Jain


Subject Code: KCS 502 Assistant Professor (CSE Dept.)
------------------------------------------------------------------------------------------------------------------------------------------
w = cad

Input pointer
S

c A d

a
descent pointer
Yes, the given string can be parsed and the final parse tree is shown below:

c A d

-------------------------------------------------------------------------------------------------------------------------------------
I. T. S. Engineering College, Greater Noida

Downloaded by Jaya Sree ([email protected])

You might also like