Lecture#16, Chapter 04 (Part II)
Lecture#16, Chapter 04 (Part II)
Syntax Analysis
Part I
Chapter 4
2
Left Factoring
• When a nonterminal has two or more productions
whose right-hand sides start with the same
grammar symbols, the grammar is not LL(1) and
cannot be used for predictive parsing
• Replace productions
A 1 | 2 | … | n |
with
A AR |
AR 1 | 2 | … | n
3
Predictive Parsing
• Eliminate left recursion from grammar
• Left factor the grammar
• Compute FIRST and FOLLOW
• Two variants:
– Recursive (recursive calls)
– Non-recursive (table-driven)
• Wait for definition of LL(1)
4
Repeat above steps until no more elements are added to any First(
) set.
Checking “Yj * ?” essentially amounts to checking whether
belongs to First(Yj)
6
FIRST(a) = {a} if a T
FIRST() = {}
FIRST(A) = A FIRST() for A P
FIRST(X1X2…Xk) =
if for all j = 1, …, i-1 : FIRST(Xj) then
add non- in FIRST(Xi) to FIRST(X1X2…Xk)
if for all j = 1, …, k : FIRST(Xj) then
add to FIRST(X1X2…Xk)
7
S i E t SS’ | a
S’ eS |
E b
Verify that
First(S) = { i, a }
First(S’) = { e, }
First(E) = { b }
8
Example 4
Computing First for: E TE’
E’ + TE’ |
T FT’
T’ * FT’ |
F ( E ) | id
9
FOLLOW(A) =
for all (B A ) P do
add FIRST()\{} to FOLLOW(A)
for all (B A ) P and FIRST() do
add FOLLOW(B) to FOLLOW(A)
for all (B A) P do
add FOLLOW(B) to FOLLOW(A)
if A is the start symbol S then
add $ to FOLLOW(A)
12
Follow(E) = { t }
13
Example 6
Compute Follow for: E TE’
E’ + TE’ |
T FT’
T’ * FT’ |
F ( E ) | id
14
First Follow
E ( id E $)
E’ + E’ $)
T ( id T +$)
T’ * T’ +$)
F ( id F +*$)
15
S’ eS S
First(eS) = {e} First() = {} Follow(S’) = { e, $ }
Example 8
E TE’
E’ + TE’ |
T FT’ Our well-worn example !
T’ * FT’ |
F ( E ) | id
First(E,F,T) = { (, id } Follow(E,E’) = { ), $}
First(E’) = { +, } Follow(F) = { *, +, ), $ }
Table M First(T’) = { *, } Follow(T,T’) = { +, ) , $}