
84 An Introduction to Compiler Construction in a Java World
1. Follow(S) contains #, that is, the terminator follows the start symbol.
2. If there is a rule Y ::= αXβ in P , follow(X) contains first(β) − {}.
3. If there is a rule Y ::= αXβ in P and either β = or first(β) contains , follow(X)
contains follow(Y ).
This definition suggests a straightforward algorithm.
Algorithm 3.4 Compute follow(X) for all non-terminals X in a Grammar G
Input: a context-free grammar G = (N, T, S, P )
Output: follow(X) for all non-terminals X in G
follow(S) ← {#}
for each non-terminal X ∈ S do
follow(X) ← {}
end for
repeat
for each rule Y ::= X
1
X
2
. . . X
n
∈ P do
for each non-terminal ...