Sub topic 11
Computing FIRST and FOLLOW
This chapter assumes you can read a context-free grammar, know what a terminal and a nonterminal are, and can write a derivation. It also assumes you are comfortable with set union and set difference. FIRST and FOLLOW feed the LL(1) table in the next chapter and the SLR(1) reduce actions later on.
What the two sets mean
- FIRST(α) is the set of terminals that can begin a string derived from α. If α can derive the empty string, ε is also in FIRST(α).
- FOLLOW(A) is the set of terminals that can appear immediately to the right of the nonterminal A in some sentential form. The end marker
$is a terminal here.
Two facts prevent many mistakes. FOLLOW is defined only for nonterminals, and it never contains ε. FIRST is defined for any string of symbols, and $ never appears in it.
A nonterminal is nullable if it can derive ε. Nullability drives most of the work below.
Rules for FIRST
- For a terminal a, FIRST(a) = {a}.
- If A → ε is a production, add ε to FIRST(A).
- For a production A → Y1 Y2 … Yk, add FIRST(Y1) − {ε} to FIRST(A). If ε is in FIRST(Y1), also add FIRST(Y2) − {ε}, and so on. If every Yi is nullable, add ε to FIRST(A).
Rule 3 also gives FIRST of any string X1…Xn. Scan left to right and stop at the first symbol that is not nullable.
Rules for FOLLOW
- Put
$in FOLLOW(S), where S is the start symbol. - For a production A → αBβ, add FIRST(β) − {ε} to FOLLOW(B).
- For a production A → αB, or A → αBβ where ε is in FIRST(β), add FOLLOW(A) to FOLLOW(B).
Rule 3 is the only place where information flows between FOLLOW sets. The flow goes from the head of the production to a nonterminal at its right end, or to one followed only by nullable symbols.
Worked example
Use the grammar with left recursion already removed:
E -> T E'
E' -> + T E' | ε
T -> F T'
T' -> * F T' | ε
F -> ( E ) | idCompute FIRST from the bottom up:
- FIRST(F) = {(, id}, because both bodies start with a terminal.
- FIRST(T) = FIRST(F) = {(, id}, because F is not nullable, so the scan stops there.
- FIRST(E) = FIRST(T) = {(, id}.
- FIRST(E') = {+, ε} and FIRST(T') = {*, ε}.
Now FOLLOW:
- FOLLOW(E) starts as {$} by rule 1. The body
( E )adds)by rule 2, so FOLLOW(E) = {$, )}. - In
E → T E', E' is at the end. By rule 3, FOLLOW(E') = FOLLOW(E) = {$, )}. - In
E → T E', the string after T is E'. Rule 2 adds FIRST(E') − ε = {+}. E' is nullable, so rule 3 adds FOLLOW(E). The result is FOLLOW(T) = {+, $, )}. - In
T → F T', FOLLOW(T') = FOLLOW(T) = {+, $, )}. - Also in
T → F T', rule 2 gives FIRST(T') − ε = {} for F. T' is nullable, so FOLLOW(T) is added too. The result is FOLLOW(F) = {, +, $, )}.
An arrow from X to Y means every member of X must be copied into Y. Cycles in this graph are why a single pass is not always enough.
Fixed-point algorithm
Apply the rules repeatedly until no set changes. The order does not affect the final answer, only the number of passes. The code below does exactly this.
EPS = "ε"
GRAMMAR = {
"E": [["T", "E'"]],
"E'": [["+", "T", "E'"], []],
"T": [["F", "T'"]],
"T'": [["*", "F", "T'"], []],
"F": [["(", "E", ")"], ["id"]],
}
START = "E"
def first_of_seq(seq, first):
result = set()
for sym in seq:
f = first[sym] if sym in first else {sym}
result |= f - {EPS}
if EPS not in f:
return result
result.add(EPS) # every symbol was nullable, or seq is empty
return result
def compute_first(g):
first = {a: set() for a in g}
changed = True
while changed:
changed = False
for head, bodies in g.items():
for body in bodies:
new = first_of_seq(body, first)
if not new <= first[head]:
first[head] |= new
changed = True
return first
def compute_follow(g, start, first):
follow = {a: set() for a in g}
follow[start].add("$")
changed = True
while changed:
changed = False
for head, bodies in g.items():
for body in bodies:
for i, sym in enumerate(body):
if sym not in g:
continue # terminals have no FOLLOW
rest = first_of_seq(body[i + 1:], first)
new = rest - {EPS}
if EPS in rest:
new |= follow[head]
if not new <= follow[sym]:
follow[sym] |= new
changed = True
return follow
first = compute_first(GRAMMAR)
follow = compute_follow(GRAMMAR, START, first)
for a in GRAMMAR:
print(f"FIRST({a}) = {sorted(first[a])}")
for a in GRAMMAR:
print(f"FOLLOW({a}) = {sorted(follow[a])}")The printed sets match the hand computation above.
Common errors
- Putting ε in a FOLLOW set. A nullable nonterminal can disappear from a derivation, but FOLLOW lists only terminals and
$. - Forgetting
$for the start symbol, or adding it to other sets. Only FOLLOW(S) gets it directly. Other sets receive it through rule 3. - Stopping the FIRST scan too late. Once a symbol is not nullable, later symbols contribute nothing.
- Applying rule 3 when the following symbols are not all nullable. In
A → B c, FOLLOW(A) is not copied into FOLLOW(B), becausecalways intervenes. - Computing FOLLOW from ε-productions themselves. The production
E' → εhas no right-hand-side nonterminal, so it contributes nothing to FOLLOW. - Stopping after one pass when a nonterminal's set depends on one computed later. Check that a full pass changes nothing.
Exercise
For the grammar S -> A B c, A -> a | ε, B -> b | ε, compute FIRST(S), FIRST(A), FIRST(B), FOLLOW(S), FOLLOW(A), and FOLLOW(B).
Show answer
FIRST(A) = {a, ε} and FIRST(B) = {b, ε}. In S -> A B c, A and B are both nullable but c is not, so FIRST(S) = {a, b, c} and S is not nullable. FOLLOW(S) = {$}. For A, the string after it is B c, so FIRST(B c) − ε = {b, c} and FOLLOW(A) = {b, c}. For B, the string after it is c, so FOLLOW(B) = {c}.