FIRST and FOLLOW Sets for a Given CFG
We compute FIRST and FOLLOW sets for the context-free grammar:
Key supporting definitions/rules we use: epsilon-handling in FIRST computation and end-marker propagation in FOLLOW computation. A nonterminal can have in its FIRST set if it can derive the empty string. For FOLLOW, the start symbol’s FOLLOW includes the end marker $$$.
We’ll compute systematically:
- FIRST sets for
- FOLLOW sets for and show the intermediate reasoning using the standard grammar rules.
FIRST and FOLLOW Sets (Theory + Examples)
Step 1 — Compute FIRST sets
- 1Step 1
From , we have
- 2Step 2
Since , and is a terminal, the strings derived from always begin with ; thus
- 3Step 3
From , we get
- 4Step 4
From , we get
- 5Step 5
Because , we combine: start with , and if can be , also include , and if both can be , include . Here: , , and both can be , so is included. Therefore
- 6Step 6
Since , the first symbol is terminal , so
FIRST sets (final)
epsilon-aware results:
| Nonterminal | FIRST set |
|---|---|
Step 2 — Compute FOLLOW sets
- 1Step 1
Because is the start symbol, we include the end marker: \\in\text{FOLLOW}(S)\text{FOLLOW}(S)={$}.$
- 2Step 2
In , after comes , so add to . Since , add Also, because can derive , add to . Thus
- 3Step 3
In , after comes terminal , so add to . Thus . So
- 4Step 4
In , is at the end of the right-hand side, so add to . Therefore
- 5Step 5
In , the second is at the end, so add to itself (no new information). The production also doesn’t add terminals directly.
- 6Step 6
In , after comes , so add to . Here , so . Since , also add to . We already have , so . Hence
- 7Step 7
In , is at the end, so add to . Therefore
- 8Step 8
Now that , it forces . Those values already propagate consistently into and via . No additional terminals appear.
FOLLOW sets (final)
End marker propagation and epsilon-aware propagation yield:
| Nonterminal | FOLLOW set |
|---|---|
| \}$ | |
Pro Tip: Epsilon changes what follows
When you process and , you must also add into . This is exactly why enters and .
Pro Tip to avoid a common mistake
Do not add itself into FOLLOW sets. FOLLOW contains terminals (and \$$ for start), not \epsilon\text{FIRST}(\cdot)\setminus{\epsilon}$ when adding to FOLLOW.
What you should do (recap roadmap)
Compute FIRST
Phase AStart from productions with terminals and , then build outward (e.g., , , first)."
Compute FOLLOW
Phase BInitialize FOLLOW() with $$$, then scan each production right-to-left with FIRST(remaining) logic."
Close under propagation
Phase CRepeat until sets stop growing; epsilon-driven dependencies should already be satisfied."
Knowledge Check
In the grammar , which terminals are added to FOLLOW(B) from FIRST(D) when forming FOLLOW(B)?