Introduction

A predictive parser must decide which production to apply by looking only at the next input token. A bottom-up SLR parser must decide whether to reduce by looking at the same token. Both decisions are made with two families of sets computed from the grammar alone: FIRST, the terminals that can begin a string derived from a symbol, and FOLLOW, the terminals that can appear immediately after a nonterminal in some sentential form.

Computing these sets correctly is mechanical, but every step has a trap: ε\varepsilon in FIRST, the end marker in FOLLOW, chains of nullable symbols, and the difference between "can begin" and "can follow". This note gives the definitions, the fixed-point algorithms, and fully worked grammars.

Prerequisites

Core concepts

End-marker convention used in all Compiler Design notes. The input is followed by the end marker $\text{\textdollar}, a terminal that occurs nowhere else. ε\varepsilon may appear in FIRST sets but never in FOLLOW sets; $\text{\textdollar} may appear in FOLLOW sets but never in FIRST sets of a grammar symbol.

SetDefinition
FIRST(α)\text{FIRST}(\alpha)All terminals aa with α⇒∗aβ\alpha \Rightarrow^{*} a\beta for some β\beta, plus ε\varepsilon if α⇒∗ε\alpha \Rightarrow^{*} \varepsilon
FOLLOW(A)\text{FOLLOW}(A)All terminals aa with S⇒∗αAaβS \Rightarrow^{*} \alpha A a \beta for some α,β\alpha, \beta, plus $\text{\textdollar} if AA can be the last symbol of a sentential form
NullableXX is nullable if X⇒∗εX \Rightarrow^{*} \varepsilon, that is, ε∈FIRST(X)\varepsilon \in \text{FIRST}(X)

FIRST is defined for any string of grammar symbols; FOLLOW only for nonterminals.

Algorithms

Nullable symbols first

Text
NULLABLE(G)
    N <- {A : A -> eps is a production}
    repeat
        for each production A -> Y1 ... Yk with every Yi in N (no terminal in the body)
            add A to N
    until N does not change

A body that contains a terminal is never nullable. Computing the nullable set first makes the FIRST and FOLLOW passes easier to do by hand, because "is YiY_i nullable?" is then a lookup.

FIRST of a single symbol

Text
FIRST-SETS(G)
    for each terminal a: FIRST(a) <- {a}
    for each nonterminal A: FIRST(A) <- {}
    repeat
        for each production A -> Y1 Y2 ... Yk
            add FIRST-OF-STRING(Y1 Y2 ... Yk) to FIRST(A)
    until no set changes
    return FIRST

FIRST-OF-STRING(Y1 Y2 ... Yk)
    result <- {}
    for i <- 1 to k
        add FIRST(Yi) - {eps} to result
        if eps not in FIRST(Yi) then return result
    add eps to result          (every Yi is nullable, or k = 0)
    return result

The rule in words: take FIRST of the first symbol without ε\varepsilon; if that symbol is nullable, also take FIRST of the next one; continue while symbols are nullable; add ε\varepsilon only if all of them are nullable. A production A→εA \to \varepsilon puts ε\varepsilon into FIRST(A)\text{FIRST}(A).

FOLLOW

Text
FOLLOW-SETS(G, S)
    FOLLOW(S) <- {$}; every other FOLLOW(A) <- {}
    repeat
        for each production A -> alpha B beta, for each nonterminal occurrence B
            add FIRST-OF-STRING(beta) - {eps} to FOLLOW(B)
            if eps in FIRST-OF-STRING(beta)     (beta nullable or empty)
                add FOLLOW(A) to FOLLOW(B)
    until no set changes

Both algorithms are fixed-point iterations: sets only grow and are bounded by the number of terminals, so they terminate. With nn nonterminals, tt terminals and total production length ℓ\ell, a FIRST pass costs O(ℓ⋅t)O(\ell\cdot t) set work. A FOLLOW pass also has that bound if suffix FIRST/nullable sets are cached or computed in a linear right-to-left suffix pass; a literal implementation rescanning every suffix costs O(t∑p∣body⁡(p)∣2)O(t\sum_p |\operatorname{body}(p)|^2) per pass and at most n(t+1)+1n(t+1) + 1 passes are needed (each pass but the last adds at least one element), a polynomial bound; small grammars settle in two or three passes.

Direction of the FOLLOW rule. When β\beta is nullable, FOLLOW of the head AA flows into FOLLOW of the body symbol BB, never the other way. In A→αBA \to \alpha B, whatever follows AA can follow BB, because BB ends whatever AA derives.

Worked examples

The expression grammar

Text
E  -> T E'
E' -> + T E' | eps
T  -> F T'
T' -> * F T' | eps
F  -> ( E ) | id

FIRST. FF begins with ( or id. T→FT′T \to F T' and FF is not nullable, so FIRST(T)=FIRST(F)\text{FIRST}(T) = \text{FIRST}(F); likewise FIRST(E)=FIRST(T)\text{FIRST}(E) = \text{FIRST}(T).

FOLLOW. Start with $∈FOLLOW(E)\text{\textdollar} \in \text{FOLLOW}(E). From F→(E)F \to ( E ), ) is in FOLLOW(E)\text{FOLLOW}(E). From E→TE′E \to T E', FOLLOW(E) flows into FOLLOW(E'), and FIRST(E′)−{ε}={+}\text{FIRST}(E') - \{\varepsilon\} = \{+\} goes into FOLLOW(T); since E′E' is nullable, FOLLOW(E) also flows into FOLLOW(T). Similarly at the next level, * and FOLLOW(T) go into FOLLOW(F).

NonterminalFIRSTFOLLOW
EE(, id), $\text{\textdollar}
E′E'+, ε\varepsilon), $\text{\textdollar}
TT(, id+, ), $\text{\textdollar}
T′T'*, ε\varepsilon+, ), $\text{\textdollar}
FF(, id*, +, ), $\text{\textdollar}

Check the pattern: FOLLOW grows as one moves down the precedence levels, because a lower-level nonterminal can be followed by every operator of the levels above it.

Nullable chains

Text
S -> A B c | B d
A -> a A | eps
B -> b | eps
  • FIRST(A)={a,ε}\text{FIRST}(A) = \{a, \varepsilon\}, FIRST(B)={b,ε}\text{FIRST}(B) = \{b, \varepsilon\}.
  • FIRST(ABc)\text{FIRST}(A B c): aa from AA; AA nullable, so bb from BB; BB nullable, so cc. Result {a,b,c}\{a, b, c\}, and no ε\varepsilon because cc is not nullable.
  • FIRST(Bd)={b,d}\text{FIRST}(B d) = \{b, d\}, so FIRST(S)={a,b,c,d}\text{FIRST}(S) = \{a, b, c, d\}.
  • FOLLOW(S)={$}\text{FOLLOW}(S) = \{\text{\textdollar}\}. FOLLOW(A)=FIRST(Bc)={b,c}\text{FOLLOW}(A) = \text{FIRST}(B c) = \{b, c\} (and A→aAA \to a A adds FOLLOW(A) to itself, nothing new). FOLLOW(B)={c}∪{d}={c,d}\text{FOLLOW}(B) = \{c\} \cup \{d\} = \{c, d\}.

Both alternatives of SS can begin with bb, so this grammar is not LL(1): on input b the parser cannot choose between S→ABcS \to A B c and S→BdS \to B d.

A conflict that appears only through FOLLOW

Text
S -> X Y Z
X -> x | eps
Y -> y X | eps
Z -> z | X
NonterminalFIRSTFOLLOW
SSx, y, z, ε\varepsilon$\text{\textdollar}
XXx, ε\varepsilonx, y, z, $\text{\textdollar}
YYy, ε\varepsilonx, z, $\text{\textdollar}
ZZx, z, ε\varepsilon$\text{\textdollar}

How x enters FOLLOW(X): there are two independent routes.

  • Directly from S→XYZS \to X Y Z. What follows XX there is YZY Z. YY is nullable, so FIRST(YZ)−{ε}={y}∪FIRST(Z)−{ε}={x,y,z}\text{FIRST}(Y Z) - \{\varepsilon\} = \{y\} \cup \text{FIRST}(Z) - \{\varepsilon\} = \{x, y, z\} goes into FOLLOW(X). x is in FIRST(Z) because of Z→XZ \to X.
  • Through Y→yXY \to y X. XX ends this body, so FOLLOW(Y) flows into FOLLOW(X), and FOLLOW(Y) contains FIRST(Z) minus epsilon, which contains x.

Either route alone puts x into FOLLOW(X). Now X→xX \to x and X→εX \to \varepsilon both apply on lookahead x, an LL(1) conflict that no pair of FIRST sets reveals. SS is nullable (all three symbols are), so ε∈FIRST(S)\varepsilon \in \text{FIRST}(S), and $\text{\textdollar} enters FOLLOW(X) three ways: from S→XYZS \to X Y Z itself (since YZY Z is nullable), through Z→XZ \to X, and through Y→yXY \to y X.

FOLLOW sets that feed each other

Text
P -> S d S
S -> a B | eps
B -> b S | c
NonterminalFIRSTFOLLOW
PPa, d$\text{\textdollar}
SSa, ε\varepsilond, $\text{\textdollar}
BBb, cd, $\text{\textdollar}
  • FIRST(P)\text{FIRST}(P) contains d because the first SS is nullable; it does not contain ε\varepsilon because d is a terminal.
  • In P→SdSP \to S d S the first SS gets d and the last SS gets FOLLOW(P)={$}\text{FOLLOW}(P) = \{\text{\textdollar}\}.
  • S→aBS \to a B sends FOLLOW(S) into FOLLOW(B), and B→bSB \to b S sends FOLLOW(B) back into FOLLOW(S). Mutual inclusion forces FOLLOW(S)=FOLLOW(B)\text{FOLLOW}(S) = \text{FOLLOW}(B); the iteration still stops, because sets only grow.
  • The number of passes depends on the order of productions. Processing P,S,BP, S, B gives the final sets in one pass and a second pass confirms. Processing B,S,PB, S, P needs three passes: FOLLOW(S) is filled in pass 1 (from PP), FOLLOW(B) only in pass 2 (from S→aBS \to a B), and pass 3 confirms. The result is the same.
  • The grammar is LL(1): SS's alternatives are chosen by a versus FOLLOW(S)={d,$}\text{FOLLOW}(S) = \{d, \text{\textdollar}\}, and BB's by b versus c.

FIRST and FOLLOW of a left-recursive grammar

The sets are defined for any grammar, including the left-recursive expression grammar used for LR parsing:

Text
E -> E + T | T
T -> T * F | F
F -> ( E ) | id

FIRST(E)=FIRST(T)=FIRST(F)={(,id}\text{FIRST}(E) = \text{FIRST}(T) = \text{FIRST}(F) = \{(, id\}. FOLLOW(E)={+,),$}\text{FOLLOW}(E) = \{+, ), \text{\textdollar}\}, FOLLOW(T)=FOLLOW(F)={+,∗,),$}\text{FOLLOW}(T) = \text{FOLLOW}(F) = \{+, *, ), \text{\textdollar}\}. Here + follows EE itself (from E→E+TE \to E + T), unlike the left-factored grammar above, where + follows TT but not EE. The left-recursive grammar cannot be used for LL(1) parsing (see the note Grammar Transformations for Parsing), but these FOLLOW sets are exactly what an SLR(1) table needs.

Small facts worth memorising

  • S→aSb∣εS \to a S b \mid \varepsilon: FIRST(S)={a,ε}\text{FIRST}(S) = \{a, \varepsilon\}, FOLLOW(S)={b,$}\text{FOLLOW}(S) = \{b, \text{\textdollar}\}.
  • S→AaAb∣BbBaS \to A a A b \mid B b B a, A→εA \to \varepsilon, B→εB \to \varepsilon: FIRST(S)={a,b}\text{FIRST}(S) = \{a, b\}, FOLLOW(A)=FOLLOW(B)={a,b}\text{FOLLOW}(A) = \text{FOLLOW}(B) = \{a, b\}. Equal FOLLOW sets matter for SLR parsing; see the note LR(0) and SLR(1) Parsing.

Important properties and observations

  • ε∈FIRST(A)\varepsilon \in \text{FIRST}(A) if and only if AA is nullable. ε\varepsilon is never in a FOLLOW set; $\text{\textdollar} is never in a FIRST set of a grammar symbol.
  • $∈FOLLOW(S)\text{\textdollar} \in \text{FOLLOW}(S) always, and $∈FOLLOW(A)\text{\textdollar} \in \text{FOLLOW}(A) whenever AA can end a sentential form (it appears last in a body whose head has $\text{\textdollar} in FOLLOW, possibly followed by nullable symbols).
  • FOLLOW sets depend on the whole grammar, FIRST sets only on the productions reachable from the symbol. Adding a production anywhere can enlarge FOLLOW sets elsewhere.
  • A nonterminal on the right of its own body. In A→αAA \to \alpha A, the rule "add FOLLOW(A) to FOLLOW(A)" is harmless. In A→αAβA \to \alpha A \beta, FIRST(β\beta) minus epsilon goes into FOLLOW(A); when β\beta is nullable, the usual FOLLOW(head) contribution also applies.
  • FIRST of a string stops at the first terminal. In FIRST(A a B)\text{FIRST}(A\, a\, B), nothing from BB can appear and ε\varepsilon cannot appear.
  • Mutual inclusion gives equal sets. If FOLLOW(A)⊆FOLLOW(B)\text{FOLLOW}(A) \subseteq \text{FOLLOW}(B) and FOLLOW(B)⊆FOLLOW(A)\text{FOLLOW}(B) \subseteq \text{FOLLOW}(A), the two sets are equal.
  • Use of the sets. LL(1) table: FIRST of each body, and FOLLOW of the head for nullable bodies. SLR(1) table: FOLLOW of the head decides where to reduce. Operator-precedence and LR(1) parsing use other information.

Common misconceptions.

  • "FIRST(XYXY) is FIRST(XX) ∪\cup FIRST(YY)." Only when XX is nullable, and then without XX's ε\varepsilon.
  • "FOLLOW(BB) in A→αBβA \to \alpha B \beta is FIRST(β\beta)." Without ε\varepsilon, and plus FOLLOW(AA) when β\beta is nullable.
  • "If A→εA \to \varepsilon is a production, ε\varepsilon goes into FOLLOW(AA)." Never; it goes into FIRST(AA).
  • "A terminal enters FOLLOW(BB) only from the symbol right after BB." It also comes from symbols further right when the ones in between are nullable, as x enters FOLLOW(X) from FIRST(Z) across the nullable YY.
  • "FOLLOW sets that include each other make the algorithm loop forever." The sets are bounded by the terminals and only grow, so the passes stop.

GATE examination perspective

  • Compute FIRST and FOLLOW for a given grammar. Work in passes until nothing changes; most errors come from stopping after one pass when a FOLLOW set feeds another FOLLOW set.
  • Option elimination. Any option with ε\varepsilon in a FOLLOW set or $\text{\textdollar} in a FIRST set is wrong.
  • Hidden flows through nullable symbols. As in the S→XYZS \to X Y Z example, a terminal can enter FOLLOW through two or three links of nullable symbols.
  • LL(1) decision. Two alternatives with overlapping FIRST sets, or a nullable alternative whose head's FOLLOW overlaps another alternative's FIRST, make a conflict. See the note Top-Down Parsing and LL(1).
  • SLR reductions. "On which lookaheads does state II reduce by A→αA \to \alpha?" The answer is FOLLOW(A)\text{FOLLOW}(A).
  • Left-recursive grammars. FIRST and FOLLOW can be asked of E→E+T∣TE \to E + T \mid T directly; compute them without removing the recursion.
  • Every occurrence counts. A nonterminal that occurs twice in one body (SS in P→SdSP \to S d S) collects from both occurrences.

Summary

Sources

  1. A. V. Aho, M. S. Lam, R. Sethi, J. D. Ullman, Compilers: Principles, Techniques, and Tools, 2nd ed., Pearson Addison-Wesley, 2007: Section 4.4.2 (FIRST and FOLLOW), Section 4.4.3 (LL(1) grammars), Section 4.6.4 (constructing SLR-parsing tables).

Next steps