Unit 2 - Session 11
Unit 2 - Session 11
COMPILER DESIGN
UNIT 2
SESSION 11
Topics that will be covered in this Session
Predictive Parsers
• The first L in LL(1) stands for scanning the input from left to right
• The 1 stands for using one input symbol of lookahead at each step to make parsing action
decisions
Steps in Constructing Predictive Parsers
3. Compute the functions FIRST and FOLLLOW for all the non-terminals in the grammar
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
There is no need for left factoring in this grammar as there are no common prefixes
Constructing Predictive Parsing Table – Example 1 – cont..
Now the grammar is
E → T E′
E′ → + T E′ | ε
T → F T′
T′ → * F T′ | ε
F → ( E ) | id
E → T E′
E′ → + T E′
E′ → ε
T → F T′
T′ → * F T′
T′ → ε
F→(E)
F → id
Example 2
Construct predictive parsing table for the grammar given below:
S→(L)|a
L→L,S|S
S→(L)|a
L → ( L ) L′ | a L′
L′ → , S L′ | ε
There is no need for left factoring in this grammar as there are no common prefixes
Example 2 – cont..
Now the grammar is
S→(L)|a
L → ( L ) L′ | a L′
L′ → , S L′ | ε
FIRST(S) = { ( , a } FOLLOW(S) = { $ , , , ) }
FIRST(L) = { ( , a } FOLLOW(L) = { ) }
FIRST(L′) = { , , ε } FOLLOW(L′) = { ) }
Example 2 – cont..
Step 4 : Construct predictive parsing table
S→(L)
S→a
L → ( L ) L′
L → a L′
( ) a , $
L′ → , S L′
S S→(L) S→a
L′ → ε
L L → ( L ) L′ L → a L′
L′ L′ → ε L′ → , S L′
Example 3
Construct predictive parsing table for the grammar given below:
S → iEtSS′ | a
S′ → eS | ε
E→b
There is no need for left factoring in this grammar as there are no common prefixes
FIRST(S) = { i , a } FOLLOW(S) = { $ , e }
FIRST(S′) = { e , ε } FOLLOW(S′) = { $ , e }
FIRST(E) = { b } FOLLOW(E) = { t }
Example 3
The grammar is Step 4 : Construct predictive parsing table
S′ → eS FIRST(E) = { b } FOLLOW(E) = { t }
S′ → ε i t a b e $
E→b S S → iEtSS′ S→a
S′ S′ → eS S′ → ε
S′ → ε
E E→b
In the parsing table, the entry for M[S′,e] contains two productions. This is
because the grammar is ambiguous. Hence, the grammar is not LL(1)
PREDICTIVE PARSERS
LL(1) GRAMMARS
LL(1) Grammars
• The class of LL(1) grammars is rich enough to cover most programming constructs
• Care should be taken in writing suitable grammar for the source language
• A grammar G is LL(1) if and only if whenever A → | β are two distinct productions of G, the
following conditions hold:
3. If then does not derive any string beginning with a terminal in FOLLOW(A).
Likewise, if then β does not derive any string beginning with a terminal in
FOLLOW(A).
• The first two conditions are equivalent to the statement that FIRST() and FIRST(β) are disjoint
sets
• The third condition is equivalent to stating that if ε is in FIRST(β), then FIRST() and FOLLOW(A)
are disjoint sets, and likewise if ε is in FIRST()