Skip to main content

4.1 FIRST and FOLLOW Sets: Mathematical Formulations & Computation Algorithms

📚Module 01FIRST and FOLLOW Sets: Formulations & Computation⏱️5 min read
🎯High-Yield For:Semester Exams • GATE CSE • Technical Interviews

💡 Core Intuition: The 3-Second Mental Model​

🍳 The Everyday Analogy: The Forward Radar and The Trailing Shadow​

Imagine standing at a train terminal deciding which track an incoming express train will arrive on:

  1. FIRST(α)\text{FIRST}(\alpha) (The Forward Radar): You look down the track through a telescope. What color headlights could possibly appear first around the bend? If you see a green light, you know instantly it is the Northern Express. FIRST(α)\text{FIRST}(\alpha) is the set of all terminal characters that can appear as the very first symbol in any string derived from α\alpha.
  2. FOLLOW(A)\text{FOLLOW}(A) (The Trailing Shadow): Suppose a train car is completely transparent or empty (ϵ\epsilon). You look past it to see what car is coupled immediately behind it! FOLLOW(A)\text{FOLLOW}(A) is the set of all terminal symbols that can legally appear immediately to the right of non-terminal AA across all valid sentences in the language.

💻 Bridging to Computer Science: Predictive Lookahead Routing via FIRST and FOLLOW​

In top-down predictive parsing, when the parser encounters a non-terminal AA on top of its stack and observes an incoming lookahead token aa, it must choose which production rule to expand without backtracking:

  • If a∈FIRST(α)a \in \text{FIRST}(\alpha), the parser confidently expands A→αA \to \alpha.
  • If α\alpha can derive the empty string (ϵ∈FIRST(α)\epsilon \in \text{FIRST}(\alpha)), the non-terminal AA effectively disappears! The parser then consults FOLLOW(A)\text{FOLLOW}(A): if a∈FOLLOW(A)a \in \text{FOLLOW}(A), the parser applies the derivation A→ϵA \to \epsilon.

🏗️ Architectural Foundations & Lookahead Mechanics​

Architecture Flow

The Predictive Lookahead Routing Pipeline

How top-down parsers use FIRST and FOLLOW sets to resolve deterministic production choices

📥Input

Lookahead Token (a)

Next unconsumed terminal symbol from the lexical token stream.

→
Queries
🔦Rule 1

FIRST(α) Inspection

If a ∈ FIRST(α), select production A → α deterministically.

→
Nullable?
👥Rule 2

FOLLOW(A) Fallback

If ε ∈ FIRST(α) and a ∈ FOLLOW(A), apply reduction A → ε.

→
Resolves
🎯Table

Deterministic Slot M[A, a]

Exact production rule populated in the LL(1) parsing table.

⚖️ FIRST vs FOLLOW: Conceptual Duals​

FIRST vs FOLLOW: Conceptual Duals

Contrasting leading terminal sets against trailing context sets

Leading Symbols

FIRST(α)

🔦
Dominant Architecture / DomainDefined for Terminals, Non-Terminals, and Strings
  • •The set of terminals that can begin strings derived from α.
  • •Calculated for both terminals (T) and non-terminals (V).
  • •Can contain the empty string symbol ε if α can derive ε.
  • •Never contains the input end-marker `$` under normal circumstances.
"What terminal symbol does this grammatical construct start with?"
Trailing Symbols

FOLLOW(A)

👥
Dominant Architecture / DomainDefined ONLY for Non-Terminals (V)
  • •The set of terminals that can appear immediately to the right of A.
  • •Calculated STRICTLY for non-terminals (never for terminals).
  • •CANNOT EVER contain ε under any circumstances.
  • •Always contains the input end-marker `$` for the start symbol S.
"What terminal can legally follow this construct when it finishes or disappears?"

📐 Formal Mathematical Definitions & Inductive Algorithms​

🔦 The FIRST Function​

For any grammar symbol X∈(V∪Σ)X \in (V \cup \Sigma) or string of symbols α∈(V∪Σ)∗\alpha \in (V \cup \Sigma)^*:

📖Formal Definition: The FIRST Functiondefinition
FIRST(α)={a∈Σ∣α⇒∗aβ for some string β}∪{ϵ∣α⇒∗ϵ}\text{FIRST}(\alpha) = \{ a \in \Sigma \mid \alpha \Rightarrow^* a \beta \text{ for some string } \beta \} \cup \{ \epsilon \mid \alpha \Rightarrow^* \epsilon \}

Inductive Rules to Compute FIRST:​

  1. If XX is a Terminal: FIRST(X)={X}\text{FIRST}(X) = \{ X \}
  2. If X→ϵX \to \epsilon is a Production: ϵ∈FIRST(X)\epsilon \in \text{FIRST}(X)
  3. If X→Y1Y2…YkX \to Y_1 Y_2 \dots Y_k is a Production:
    • Add FIRST(Y1)∖{ϵ}\text{FIRST}(Y_1) \setminus \{\epsilon\} to FIRST(X)\text{FIRST}(X).
    • If ϵ∈FIRST(Y1)\epsilon \in \text{FIRST}(Y_1), also add FIRST(Y2)∖{ϵ}\text{FIRST}(Y_2) \setminus \{\epsilon\} to FIRST(X)\text{FIRST}(X).
    • Continue in order: for any i≤ki \le k, if ϵ∈FIRST(Yj)\epsilon \in \text{FIRST}(Y_j) for all 1≤j<i1 \le j < i, add FIRST(Yi)∖{ϵ}\text{FIRST}(Y_i) \setminus \{\epsilon\} to FIRST(X)\text{FIRST}(X).
    • If ϵ∈FIRST(Yj)\epsilon \in \text{FIRST}(Y_j) for all 1≤j≤k1 \le j \le k, then add ϵ\epsilon to FIRST(X)\text{FIRST}(X) (meaning XX is completely nullable).

👥 The FOLLOW Function​

For any non-terminal A∈VA \in V:

📖Formal Definition: The FOLLOW Functiondefinition
FOLLOW(A)={a∈Σ∣S⇒∗αAaβ for some α,β∈(V∪Σ)∗}∪{$∣S⇒∗αA}\text{FOLLOW}(A) = \{ a \in \Sigma \mid S \Rightarrow^* \alpha A a \beta \text{ for some } \alpha, \beta \in (V \cup \Sigma)^* \} \cup \{ \$ \mid S \Rightarrow^* \alpha A \}

Inductive Rules to Compute FOLLOW:​

  1. Start Symbol Rule: $∈FOLLOW(S)where S is the start symbol of the grammar.\$ \in \text{FOLLOW}(S) \quad \text{where } S \text{ is the start symbol of the grammar.}
  2. Direct Successor Rule: If there is a production of the form B→αAβB \to \alpha A \beta: (FIRST(β)∖{ϵ})⊆FOLLOW(A)\big( \text{FIRST}(\beta) \setminus \{\epsilon\} \big) \subseteq \text{FOLLOW}(A) (Whatever begins β\beta immediately follows AA).
  3. Transmission / Nullable Suffix Rule: If there is a production of the form:
    • B→αAB \to \alpha A, OR
    • B→αAβB \to \alpha A \beta where ϵ∈FIRST(β)\epsilon \in \text{FIRST}(\beta) (i.e. β⇒∗ϵ\beta \Rightarrow^* \epsilon): FOLLOW(B)⊆FOLLOW(A)\text{FOLLOW}(B) \subseteq \text{FOLLOW}(A) (Since β\beta disappears or AA is the final symbol of the rule, whatever can trail BB also legally trails AA).

Cardinal Rule: ϵ\epsilon is NEVER an element of any FOLLOW\text{FOLLOW} set! FOLLOW\text{FOLLOW} sets consist strictly of input terminals and $ (the input end-marker).


🏭 Real-World Production Context: How Industry Builds This​

In industrial compiler engines (such as recursive-descent parsers in GCC, Clang, and Roslyn):

When a recursive-descent parser encounters a syntax error while executing the parsing function for non-terminal AA, it initiates Panic-Mode Error Recovery:

  • The parser does not crash. Instead, it enters a token-skipping loop until it encounters a token in FOLLOW(A)\text{FOLLOW}(A).
  • It then cleanly returns from function parse_A(), popping AA from the virtual call stack and allowing the parent grammar rule to resume parsing the remainder of the file.

Automated parser tools compute FIRST\text{FIRST} and FOLLOW\text{FOLLOW} sets across the entire grammar during compilation:

  • If FIRST(α)∩FIRST(β)≠∅\text{FIRST}(\alpha) \cap \text{FIRST}(\beta) \neq \emptyset, the generator immediately flags a First/First Conflict.
  • If ϵ∈FIRST(α)\epsilon \in \text{FIRST}(\alpha) and FIRST(α)∩FOLLOW(A)≠∅\text{FIRST}(\alpha) \cap \text{FOLLOW}(A) \neq \emptyset, the generator flags a First/Follow Conflict.

📐 Numerical Applications & Worked Examples​

Example 1: The Canonical Arithmetic Expression Grammar​

Compute the complete FIRST\text{FIRST} and FOLLOW\text{FOLLOW} sets for the unambiguous arithmetic expression grammar:

E→TE′E′→+TE′∣ϵT→FT′T′→∗FT′∣ϵF→(E)∣id\begin{aligned} E &\to T E' \\ E' &\to + T E' \mid \epsilon \\ T &\to F T' \\ T' &\to * F T' \mid \epsilon \\ F &\to ( E ) \mid \text{id} \end{aligned}

Step-by-Step Analytical Solution:

Step 1: Compute FIRST Sets (Bottom-Up Evaluation)

  • For F→(E)∣idF \to ( E ) \mid \text{id}:
    • Leading terminals are '(' and 'id'.
    • FIRST(F)={(,id}\text{FIRST}(F) = \{ (, \text{id} \}
  • For T′→∗FT′∣ϵT' \to * F T' \mid \epsilon:
    • Leading terminal is '*', plus ϵ\epsilon.
    • FIRST(T′)={∗,ϵ}\text{FIRST}(T') = \{ *, \epsilon \}
  • For T→FT′T \to F T':
    • Begins with FF. Since ϵ∉FIRST(F)\epsilon \notin \text{FIRST}(F), FIRST(T)=FIRST(F)={(,id}\text{FIRST}(T) = \text{FIRST}(F) = \{ (, \text{id} \}.
  • For E′→+TE′∣ϵE' \to + T E' \mid \epsilon:
    • Leading terminal is '+', plus ϵ\epsilon.
    • FIRST(E′)={+,ϵ}\text{FIRST}(E') = \{ +, \epsilon \}
  • For E→TE′E \to T E':
    • Begins with TT. Since ϵ∉FIRST(T)\epsilon \notin \text{FIRST}(T), FIRST(E)=FIRST(T)={(,id}\text{FIRST}(E) = \text{FIRST}(T) = \{ (, \text{id} \}.

Step 2: Compute FOLLOW Sets

  • Start Symbol: Add $ to FOLLOW(E)\text{FOLLOW}(E):
FOLLOW(E)={$}\text{FOLLOW}(E) = \{ \$ \}
  • Inspect occurrences of EE:
    • In F→(E)F \to ( E ): Followed by ')'. Add ')' to FOLLOW(E)\text{FOLLOW}(E):
FOLLOW(E)={),$}\text{FOLLOW}(E) = \{ ), \$ \}
  • Inspect occurrences of E′E':
    • In E→TE′E \to T E': E′E' is at the end:
FOLLOW(E′)=FOLLOW(E)={),$}\text{FOLLOW}(E') = \text{FOLLOW}(E) = \{ ), \$ \}
  • In E′→+TE′E' \to + T E': Adds FOLLOW(E′)\text{FOLLOW}(E') to itself (no new tokens):
FOLLOW(E′)={),$}\text{FOLLOW}(E') = \{ ), \$ \}
  • Inspect occurrences of TT:
    • In E→TE′E \to T E': Followed by E′E'. Add FIRST(E′)∖{ϵ}={+}\text{FIRST}(E') \setminus \{\epsilon\} = \{ + \}.
    • Since ϵ∈FIRST(E′)\epsilon \in \text{FIRST}(E'), also add FOLLOW(E)\text{FOLLOW}(E):
FOLLOW(T)={+,),$}\text{FOLLOW}(T) = \{ +, ), \$ \}
  • Inspect occurrences of T′T':
    • In T→FT′T \to F T': T′T' is at the end:
FOLLOW(T′)=FOLLOW(T)={+,),$}\text{FOLLOW}(T') = \text{FOLLOW}(T) = \{ +, ), \$ \}
  • Inspect occurrences of FF:
    • In T→FT′T \to F T': Followed by T′T'. Add FIRST(T′)∖{ϵ}={∗}\text{FIRST}(T') \setminus \{\epsilon\} = \{ * \}.
    • Since ϵ∈FIRST(T′)\epsilon \in \text{FIRST}(T'), also add FOLLOW(T)\text{FOLLOW}(T):
FOLLOW(F)={∗,+,),$}\text{FOLLOW}(F) = \{ *, +, ), \$ \}

Consolidated Sets:​

Non-TerminalFIRST SetFOLLOW Set
E(, id), $
E'+, ε), $
T(, id+, ), $
T'*, ε+, ), $
F(, id*, +, ), $

Example 2: Multi-Symbol Epsilon Cascades and Follow Propagation​

Compute the FIRST\text{FIRST} and FOLLOW\text{FOLLOW} sets for the following grammar featuring multi-symbol epsilon cascades:

S→aBDhB→cCC→b∣ϵD→EFE→g∣ϵF→f∣ϵ\begin{aligned} S &\to a B D h \\ B &\to c C \\ C &\to b \mid \epsilon \\ D &\to E F \\ E &\to g \mid \epsilon \\ F &\to f \mid \epsilon \end{aligned}

Step-by-Step Analytical Solution:

Step 1: Compute FIRST Sets

  • FIRST(C)={b,ϵ}\text{FIRST}(C) = \{ b, \epsilon \}
  • FIRST(B)={c}\text{FIRST}(B) = \{ c \} (begins with terminal cc)
  • FIRST(E)={g,ϵ}\text{FIRST}(E) = \{ g, \epsilon \}
  • FIRST(F)={f,ϵ}\text{FIRST}(F) = \{ f, \epsilon \}
  • For D→EFD \to E F:
    • Add FIRST(E)∖{ϵ}={g}\text{FIRST}(E) \setminus \{\epsilon\} = \{ g \}.
    • Since ϵ∈FIRST(E)\epsilon \in \text{FIRST}(E), add FIRST(F)∖{ϵ}={f}\text{FIRST}(F) \setminus \{\epsilon\} = \{ f \}.
    • Since both EE and FF derive ϵ\epsilon, add ϵ\epsilon.
    • FIRST(D)={g,f,ϵ}\text{FIRST}(D) = \{ g, f, \epsilon \}.
  • For S→aBDhS \to a B D h:
    • Begins with terminal a  ⟹  FIRST(S)={a}a \implies \text{FIRST}(S) = \{ a \}.

Step 2: Compute FOLLOW Sets

  • Start Symbol: Add $ to FOLLOW(S)\text{FOLLOW}(S):
FOLLOW(S)={$}\text{FOLLOW}(S) = \{ \$ \}
  • For non-terminal BB in S→aBDhS \to a B D h:
    • Followed by DhD h.
    • FIRST(Dh)∖{ϵ}=(FIRST(D)∖{ϵ})∪FIRST(h)={g,f,h}\text{FIRST}(D h) \setminus \{\epsilon\} = (\text{FIRST}(D) \setminus \{\epsilon\}) \cup \text{FIRST}(h) = \{ g, f, h \}.
    • FOLLOW(B)={g,f,h}\text{FOLLOW}(B) = \{ g, f, h \}.
  • For non-terminal CC in B→cCB \to c C:
    • CC is at the very end of B→cCB \to c C.
    • FOLLOW(C)=FOLLOW(B)={g,f,h}\text{FOLLOW}(C) = \text{FOLLOW}(B) = \{ g, f, h \}.
  • For non-terminal DD in S→aBDhS \to a B D h:
    • Followed by terminal h  ⟹  FOLLOW(D)={h}h \implies \text{FOLLOW}(D) = \{ h \}.
  • For non-terminal EE in D→EFD \to E F:
    • Followed by FF. Add FIRST(F)∖{ϵ}={f}\text{FIRST}(F) \setminus \{\epsilon\} = \{ f \}.
    • Since ϵ∈FIRST(F)\epsilon \in \text{FIRST}(F), add FOLLOW(D)={h}\text{FOLLOW}(D) = \{ h \}.
    • FOLLOW(E)={f,h}\text{FOLLOW}(E) = \{ f, h \}.
  • For non-terminal FF in D→EFD \to E F:
    • FF is at the end of D→EFD \to E F.
    • FOLLOW(F)=FOLLOW(D)={h}\text{FOLLOW}(F) = \text{FOLLOW}(D) = \{ h \}.

Final Table of Sets:​

Non-TerminalFIRST SetFOLLOW Set
Sa$
Bcg, f, h
Cb, εg, f, h
Dg, f, εh
Eg, εf, h
Ff, εh

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions

Question 1: "Can the empty string symbol ε ever be a member of a FOLLOW set?"
Key Focus Points:

  • Strict Rule: ϵ\epsilon can NEVER belong to any FOLLOW\text{FOLLOW} set under any circumstances.
  • Physical Meaning: FOLLOW(A)\text{FOLLOW}(A) represents the set of concrete terminal tokens that can physically appear after AA on the input tape. The empty string is an absence of characters, not a physical character on the input stream.

Question 2: "Can FIRST be computed for terminal symbols? Can FOLLOW be computed for terminal symbols?"
Key Focus Points:

  • FIRST: Defined for both terminals and non-terminals: for any terminal aa, FIRST(a)={a}\text{FIRST}(a) = \{ a \}.
  • FOLLOW: Defined strictly for non-terminals (VV). The mathematical concept of FOLLOW(a)\text{FOLLOW}(a) for a terminal aa is undefined in compiler syntax theory.
Common Interview Traps: Architectural Trade-Offs

Trap 1: Forgetting to add $ to FOLLOW of the start symbol.
Answer: Fatal calculation bug. The input stream always ends with the end-marker $. The start symbol SS derives the entire sentence; therefore, $ is universally in FOLLOW(S)\text{FOLLOW}(S). Forgetting $ corrupts all dependent FOLLOW sets.

Trap 2: Propagating ε into FOLLOW when applying Rule 2.
Answer: Follow sets never receive ε. When computing FOLLOW(A)\text{FOLLOW}(A) from B→αAβB \to \alpha A \beta, we take FIRST(β)∖{ϵ}\text{FIRST}(\beta) \setminus \{\epsilon\}. If β\beta is nullable, we invoke Rule 3 and add FOLLOW(B)\text{FOLLOW}(B), but ϵ\epsilon itself is stripped.


💬

Discussion & Doubts