2. 2
LL(1) Grammar
A grammar G is LL(1) if it is not left recursive and for each
collection of productions
A 1 | 2 | … | n
for nonterminal A the following holds:
1. FIRST(i) FIRST(j) = for all i j
2. if i * then
2.a. j * for all i j
2.b. FIRST(j) FOLLOW(A) =
for all i j
3. 3
the first L stands for scanning the input from left
to right,
the second L stands for producing a leftmost
derivation,
and the 1 stands for using one input symbol of
looka head at each step to make parsing action
decision.
4. 4
Non-LL(1) Examples
Grammar Not LL(1) because:
S S a | a Left recursive
S a S | a FIRST(a S) FIRST(a)
S a R |
R S | For R: S * and *
S a R a
R S |
For R:
FIRST(S) FOLLOW(R)
5. 5
Non-Recursive Predictive Parsing:
Table-Driven Parsing
Given an LL(1) grammar G = (N, T, P, S)
construct a table M[A,a] for A N, a T and
use a driver program with a stack
Predictive parsing
program (driver)
Parsing table
M
a + b $
X
Y
Z
$
stack
input
output
6. 6
Constructing an LL(1) Predictive
Parsing Table
for each production A do
for each a FIRST() do
add A to M[A,a]
enddo
if FIRST() then
for each b FOLLOW(A) do
add A to M[A,b]
enddo
endif
enddo
Mark each undefined entry in M error
7. 7
Example Table
E T ER
ER + T ER |
T F TR
TR * F TR |
F ( E ) | id
A
FIRST(
)
FOLLOW(
A)
E T ER ( id $ )
ER + T
ER
+
$ )
ER
T F TR ( id + $ )
TR * F
TR
*
+ $ )
TR
F ( E ) ( * + $ )
F id Id * + $ )
8. Parsing Table
8
id + * ( ) $
E
E T
ER
E
T ER
E
R
ER +
T ER
ER
ER
T
T F
TR
T
F TR
T
TR
TR *
F T
TR TR
9. 9
LL(1) Grammars are Unambiguous
Ambiguous grammar
S i E t S SR | a
SR e S |
E b
a b e i t $
S S a S i E t S SR
SR
SR
SR e S
SR
E E b
A
FIRST(
)
FOLLOW
(A)
S i E t S
SR
i
e $
S a a
SR e S e
e $
SR
E b b t
Error: duplicate table entry
11. Contd..
11
These reductions, in fact, trace out the following right-most
derivation in reverse:
S ⇒ aABe
⇒ aAde
⇒ aAbcde
⇒ abbcde
12. 12
Left Recursion Removal
Rewrite rules to avoid left recursion
S->Sx | y
becomes
S-> yS’
and
S’ -> xS’ |
(Note: x and y can be arbitrary strings)
13. 13
Review LL(1) Grammars
Compute First and Follow sets
Build the parsing table
If x is in First(A), then M[A,x] = A->xZ (the rule that
put x in First(A)
If is in First(A) and x is in Follow(A), then M[A,x]
= A->
If each cell has no more than 1 rule, grammar
is LL(1).
Notas do Editor
More general algorithm for left recursion removal in 4.2 (pp 159-160 of Loudon)