Lecture 8
Lecture 8
Lecture 8
LL(1) Parsing
E → TA T → int B | (E)
A→+E|ε B→*T|ε
LL(1) Parser - First sets
● If α is any string of terminals and nonterminals (like the right
side of a production) then FIRST(α) is the set of terminal
symbols that start some string that α produces, plus ε if α can
produce the empty string.
● If α →* tβ, then t ∈ FIRST(α)
● FIRST(α) = {t | α →* tβ} ⋃ {ε | α →* ε}
LL(1) Parser - Follow sets
● If A is a non-terminal symbol, then FOLLOW(A) is the set of
terminal symbols that can come immediately to the right of A in
some sentential form, i.e., the set of terminals such that there
exists a derivation of the form S →* αAtβ
● If A → α →* ε and S →* αAtβ, then t can be consumed as the
next input, if we are at A
● FOLLOW(A)={t | S →* αAtβ}
Computing First Sets
1. If X is a terminal, then FIRST(X) = {X}
2. If X is a non-terminal, then
ε ∈ FIRST(X)
if X → A1 .. An and ε ∈ FIRST(Ai) for all 1 ≤ i ≤ n
FIRST(α) ∈ FIRST(X)
if X → A1 .. Anα and ε ∈ FIRST(Ai) for all 1 ≤ i ≤ n
3. If X → ε then ε ∈ FIRST(X)
Computing First Sets - Example
1. If X is a terminal, then FIRST(X) = {X}
2. If X is a non-terminal, then
ε ∈ FIRST(X) if X → A1 .. An and ε ∈ FIRST(Ai) for all 1 ≤ i ≤ n
FIRST(α) ⊆ FIRST(X) if X → A1 .. Anα and ε ∈ FIRST(Ai) for all 1 ≤ i ≤ n
3. If X → ε then ε ∈ FIRST(X)
FIRST(E) = FIRST(T) =
FIRST(A) = FIRST(B) =
Computing First Sets - Example
1. If X is a terminal, then FIRST(X) = {X}
2. If X is a non-terminal, then
ε ∈ FIRST(X) if X → A1 .. An and ε ∈ FIRST(Ai) for all 1 ≤ i ≤ n
FIRST(α) ⊆ FIRST(X) if X → A1 .. Anα and ε ∈ FIRST(Ai) for all 1 ≤ i ≤ n
3. If X → ε then ε ∈ FIRST(X)
Input Symbol
Non-terminal
int * + ( ) $
B
LL(1) Parsing Table
E → TA A→+E|ε T → int B | (E) B→*T|ε
Input Symbol
Non-terminal
int * + ( ) $
E TA TA
T int B (E)
A +E ε ε
B *T ε ε ε
LL(1) Parsing Example
Stack Input Action
E$ int * int $ TA
int B A $ int $
A$ $ ε
$ $ ACCEPT
LL(1) Parsing Table
S → iEtSS’ | a
S’ → eS | ε Input: i b t i b t a e a
E→b
Input Symbol
Non-terminal
a b e i t $
S a iEtSS’
S’
E
LL(1) Parser
● CFG is not LL(1)
○ If it is ambiguous
○ If it is left-recursive
○ If it is not left-factored
● Most programming languages are not LL(1)!