Calculating First and Follow sets is a fundamental task in compiler design when
working with context-free grammars. Here's a straightforward explanation with
steps and examples:
Definitions
1. First(X): The set of terminals that can appear at the beginning of strings
derived from XXX.
o For a terminal XXX, First(X)={X}\text{First}(X) = \{ X \}First(X)={X}.
o For a non-terminal XXX, recursively compute terminals that can start
productions of XXX.
Follow(X): The set of terminals that can appear immediately to the right of X in
some "sentential form."
Follow(X): The set of terminals that can appear immediately to the right of XXX in
some derivation.
If X is the start symbol, Follow(X) contains $ (end of input).
Look at the grammar rules to see what comes after X.
Example:
S → AB
A → aA | ε
B → bB | ε
2. Steps to Calculate First(X):
1. If X is a terminal, First(X) = {X}.
2. If X → ε, then ε ∈ First(X).
3. For a production X → Y1 Y2 ... Yk:
o Add First(Y1) (except ε) to First(X).
o If Y1 derives ε, then check Y2 and so on.
o If all Y1, Y2, ..., Yk derive ε, then add ε to First(X).
3. Steps to Calculate Follow(X):
1. Add $ to Follow(StartSymbol) (start symbol).
2. For each production A → αBβ:
o Add First(β) (except ε) to Follow(B).
o If β derives ε, add Follow(A) to Follow(B).
3. For a production A → αB, add Follow(A) to Follow(B).
Step 1: Calculate First
1. First(S):
o S → AB
o Look at First(A) and First(B).
2. First(A):
o A → aA ⇒ Add a to First(A).
o A → ε ⇒ Add ε to First(A).
o So, First(A) = {a, ε}.
3. First(B):
o B → bB ⇒ Add b to First(B).
o B → ε ⇒ Add ε to First(B).
o So, First(B) = {b, ε}.
4. First(S):
o S → AB
o Add First(A) - {ε} to First(S). So, First(S) = {a}.
o Since A can derive ε, also add First(B). So, First(S) = {a, b, ε}.
Step 2: Calculate Follow
1. Follow(S):
o Add $ since S is the start symbol. So, Follow(S) = {$}.
2. Follow(A):
First(B) = {b, ε} ⇒ Add {b}.
o S → AB: Add First(B) (except ε) to Follow(A).
o If B derives ε, add Follow(S) to Follow(A).
Follow(S) = {$}.
o So, Follow(A) = {b, $}.
3. Follow(B):
o S → AB: Add Follow(S) to Follow(B).
Follow(S) = {$}.
o So, Follow(B) = {$}.
Final Results:
First(S) = {a, b, ε}
First(A) = {a, ε}
First(B) = {b, ε}
Follow(S) = {$}
Follow(A) = {b, $}
Follow(B) = {$}