Sub topic 9
Computing FIRST and FOLLOW
Assume you know context-free grammars, production rules, sets, and ε, which means the empty string. FIRST and FOLLOW sets help a predictive parser choose the correct production using the next input token.
FIRST sets
FIRST(X) contains every terminal that can begin a string derived from X. If X can derive ε, then ε also belongs to FIRST(X).
Consider this grammar:
E -> T E'
E' -> + T E' | ε
T -> F T'
T' -> * F T' | ε
F -> ( E ) | idHere, id, +, *, (, and ) are terminals. E, E', T, T', and F are nonterminals.
Compute FIRST sets by repeatedly applying these rules:
- For a terminal
a,FIRST(a) = {a}. - If
A -> a ..., addatoFIRST(A). - If
A -> B C, addFIRST(B)except ε. IfBcan derive ε, also inspectC. - Add ε to
FIRST(A)when every symbol on the right side can derive ε.
The resulting sets are:
| Nonterminal | FIRST set |
|---|---|
| `E` | `{ (, id }` |
| `E'` | `{ +, ε }` |
| `T` | `{ (, id }` |
| `T'` | `{ *, ε }` |
| `F` | `{ (, id }` |
For example, FIRST(E) equals FIRST(T) because E begins with T. T begins with F, and F begins with either ( or id.
FOLLOW sets
FOLLOW(A) contains terminals that can appear immediately after nonterminal A in some sentential form. Put $ in the start symbol's FOLLOW set. The symbol $ marks the end of input.
Apply these rules repeatedly:
- For
A -> α B β, addFIRST(β)except ε toFOLLOW(B). - If
βcan derive ε, addFOLLOW(A)toFOLLOW(B). - For
A -> α B, addFOLLOW(A)toFOLLOW(B).
For this grammar:
| Nonterminal | FOLLOW set |
|---|---|
| `E` | `{ ), $ }` |
| `E'` | `{ ), $ }` |
| `T` | `{ +, ), $ }` |
| `T'` | `{ +, ), $ }` |
| `F` | `{ *, +, ), $ }` |
The ) enters FOLLOW(E) because of F -> ( E ). The $ enters FOLLOW(E) because E is the start symbol. Since E' appears at the end of E -> T E', FOLLOW(E) flows into FOLLOW(E').
Using FIRST and FOLLOW in LL(1)
For a production A -> α, place it in table entry M[A, a] for every a in FIRST(α). If α derives ε, place the production in M[A, b] for every b in FOLLOW(A).
A grammar is LL(1) when no table cell receives two productions. FIRST chooses productions that begin with input symbols. FOLLOW chooses an ε-production when no explicit symbol is expected.
Exercise
Why is ) in FOLLOW(E) for this grammar?
Show answer
The production F -> ( E ) places ) immediately after E, so ) belongs to FOLLOW(E).