Compiler Design
Grammars, FIRST & FOLLOW
FIRST and FOLLOW sets and the ambiguity test sit underneath every parsing question. Learn the rules once, practise on three or four grammars, and the short calculation questions become free marks.
GATE CSE parsing basics — context-free grammars, derivations and parse trees, ambiguity, FIRST and FOLLOW computation with worked tables, and the parser family overview, with sample questions, flashcards and drills.
Learning outcomes
- Define CFG, derivation, sentential form and parse tree; tell leftmost from rightmost derivations
- Decide whether a grammar is ambiguous and remove ambiguity with precedence/associativity layering
- Compute FIRST and FOLLOW sets for grammars with ε-productions without mistakes
- Place LL(1), LR(0), SLR(1), LALR(1) and CLR(1) in the correct containment hierarchy
Context-free grammars, derivations and parse trees
- A CFG is a 4-tuple G = (V, T, P, S): variables (non-terminals) V, terminals T, productions P of the form A → α, and start symbol S. The parser checks whether the token string can be derived from S and builds the parse tree.
- A derivation step replaces a non-terminal by the right-hand side of one of its productions (⇒). A LEFTMOST derivation always expands the leftmost non-terminal; a RIGHTMOST derivation always expands the rightmost non-terminal.
- A sentential form is any string of terminals and non-terminals derivable from S; a sentence consists of terminals only. A parse tree has the start symbol at the root, non-terminals at internal nodes and the sentence read left to right at the leaves.
- Top-down parsers build a leftmost derivation. Bottom-up (shift-reduce) parsers trace a rightmost derivation in REVERSE. A parse tree corresponds to exactly one leftmost and exactly one rightmost derivation.
- Counting derivation steps: every step applies one production. For S → SS | a deriving a string of n a’s needs (n − 1) uses of S → SS and n uses of S → a, so 2n − 1 steps.
- A grammar is left-recursive if some A ⇒+ Aα. It is right-recursive if A ⇒+ αA. Left-recursion makes top-down parsers loop; right-recursion makes right-associative operators naturally.
- Right-sentential form: any sentential form reached in a rightmost derivation. The HANDLE of a right-sentential form is the substring a shift-reduce parser reduces next. Left-sentential forms are defined the same way for leftmost derivations.
- Counting trick: for E → E op E | id with n operands the tree has n − 1 uses of E → E op E and n uses of E → id, so a derivation has 2n − 1 steps and the tree 2n − 1 internal nodes and n leaves.
- The parse tree forgets the ORDER in which non-terminals were expanded. Several derivations can give one tree (leftmost, rightmost, or mixed order), but exactly one of them is leftmost and exactly one is rightmost — a favourite true/false trap. Ambiguity is about trees, not about the number of derivations.
- The language of a CFG is generated by the start symbol; the parser accepts programs that belong to this language and rejects the rest with a syntax error.
Worked example
Problem. Grammar S → S S | a. Give the number of derivation steps to derive aaa and the number of internal nodes of the parse tree.
Solution. For n = 3 we need n − 1 = 2 applications of S → SS and 3 applications of S → a: 5 steps. Each step creates one internal (non-terminal) node, so the tree has 5 internal nodes and 3 leaves.
Ambiguity
- A grammar is AMBIGUOUS if some string has two or more distinct parse trees (equivalently, two distinct leftmost derivations, or two distinct rightmost derivations).
- E → E + E | E * E | id is ambiguous: id + id * id has two parse trees (one groups + first, the other groups * first). The cause is that precedence and associativity are not encoded.
- Number of parse trees: for E → E op E | id with n operands and n − 1 operators, the number of distinct trees is the Catalan number C(n−1). So id+id+id has 2, id+id*id+id has 5.
- Fix: layer the grammar by precedence. E → E + T | T; T → T * F | F; F → ( E ) | id. Lower precedence operators sit higher in the tree; left recursion gives left associativity, right recursion gives right associativity.
- Dangling else: S → i E t S | i E t S e S | a is ambiguous because “i E t i E t S e S” can attach the else to either if. Compilers resolve it by matching else with the nearest unmatched if.
- Ambiguity is UNDECIDABLE in general (no algorithm can decide whether an arbitrary CFG is ambiguous), but it can be shown by exhibiting one string with two parse trees.
- Inherently ambiguous languages exist: every grammar for the language is ambiguous, e.g. { a^i b^j c^k | i = j or j = k }. Removing ambiguity is not always possible.
- No ambiguous grammar is LL(k) or LR(k) for any k. Yacc can still use an ambiguous grammar together with precedence declarations to resolve shift-reduce conflicts.
- Ambiguity of a GRAMMAR versus a LANGUAGE: S → S S | a is ambiguous, yet the language a⁺ also has the unambiguous grammar S → a S | a. Only inherently ambiguous languages defeat every grammar.
- Associativity comes from the recursion side: E → E − T gives a left-associative minus (a − b − c = (a − b) − c); E → T ^ E gives a right-associative ^ (a ^ b ^ c = a ^ (b ^ c)); a symmetric rule E → E op E gives neither, which is exactly why it is ambiguous.
- Precedence comes from layering: operators with higher precedence are generated LOWER in the grammar, closer to the operands. In E → E + T | T ; T → T * F | F the * sits deeper in the tree than +, so it binds tighter.
- To prove ambiguity in a question, take the shortest string that uses the suspect production twice (id+id+id, aaa, i i a e a) and draw two trees. To argue a grammar is unambiguous, show that for every sentential form the next input symbol fixes the only applicable production.
- Quick ambiguity checks: S → SS | a is ambiguous (aaa = (aa)a or a(aa)); S → aS | b is not; S → aSb | ε is not; a grammar with both left and right recursion on the same non-terminal (A → AA) is usually ambiguous.
Formulas to remember
-
parse trees for n operands (E → E op E | id) = Catalan(n − 1) = C(2(n−1), n−1) / n -
ambiguous ⇒ not LL(k), not LR(k)
| Grammar | Ambiguous? | Reason |
|---|---|---|
| E → E+E | E*E | id | Yes | no precedence / associativity |
| E → E+T | T ; T → T*F | F ; F → (E) | id | No | layered, left associative |
| S → SS | a | Yes | aaa has two trees |
| S → aSb | ε | No | only one way to generate aⁿbⁿ |
| S → iS | iSeS | a | Yes | dangling else |
Worked example
Problem. How many distinct parse trees does id + id * id + id have under E → E + E | E * E | id?
Solution. There are 4 operands and 3 operators, so the count is Catalan(3) = 5 (the operators sit at fixed positions, so each bracketing gives a different tree).
FIRST and FOLLOW — the rules
- FIRST(α) is the set of terminals that can BEGIN a string derived from α; ε ∈ FIRST(α) if α ⇒* ε (α is nullable). FOLLOW(A) is the set of terminals that can appear immediately to the RIGHT of A in some sentential form; $ stands for end of input. FOLLOW never contains ε.
- FIRST rules: (1) if a is a terminal, FIRST(a) = {a}. (2) If A → ε, put ε in FIRST(A). (3) If A → Y1 Y2 … Yk, add FIRST(Y1) − {ε}; if ε ∈ FIRST(Y1) also add FIRST(Y2) − {ε}, and so on; if ALL Yi are nullable, add ε.
- FOLLOW rules: (1) put $ in FOLLOW(S) for the start symbol S. (2) For A → α B β: add FIRST(β) − {ε} to FOLLOW(B). (3) For A → α B, or A → α B β with ε ∈ FIRST(β): add FOLLOW(A) to FOLLOW(B).
- FIRST is computed from the left end of right-hand sides, bottom-up in the grammar; FOLLOW needs the context where the non-terminal is USED. Apply the rules repeatedly until no set changes (fixed point).
- Procedure: first mark nullable non-terminals, then compute FIRST sets for all non-terminals, then FOLLOW sets. Always look at EVERY production whose right-hand side contains the non-terminal when computing its FOLLOW.
- FIRST of a string X1 X2 … Xn: take FIRST(X1) minus ε; continue with X2 only if X1 is nullable, and so on. Include ε only when every Xi is nullable.
- The sets are used to build predictive parse tables: FIRST decides which production to choose on a lookahead; FOLLOW decides when to use an ε-production (and when an SLR parser may reduce).
- Nullable test: A is nullable if A → ε, or A → Y1 … Yk with every Yi nullable. Compute the nullable set first (a small fixed point); it is used by FIRST (continue past nullable symbols) and by FOLLOW (inherit FOLLOW of the head).
- FIRST sets of terminals are singletons; FIRST never contains $. FOLLOW never contains ε but may contain $ and symbols such as ). FIRST(A) and FOLLOW(A) can overlap — with a nullable alternative that overlap is exactly what breaks LL(1).
- Only a symbol at the END of a right-hand side, or one followed only by nullable symbols, inherits FOLLOW of the head. Earlier symbols receive just FIRST of what comes after them.
- Common slips: forgetting $ in FOLLOW(S); adding ε to a FOLLOW set; computing FOLLOW(A) using FIRST of the left side instead of the symbols after A; skipping a nullable symbol that follows.
Formulas to remember
-
A → α B β ⇒ FOLLOW(B) ⊇ FIRST(β) − {ε} -
A → α B or (A → α B β and β ⇒* ε) ⇒ FOLLOW(B) ⊇ FOLLOW(A) -
$ ∈ FOLLOW(start symbol)
Worked example
Problem. Compute FIRST and FOLLOW for S → A B ; A → a | ε ; B → b | ε.
Solution. FIRST(A) = {a, ε}, FIRST(B) = {b, ε}. Both A and B are nullable, so FIRST(S) = {a, b, ε}. FOLLOW(S) = {$}. For S → A B: FOLLOW(A) ⊇ FIRST(B) − ε = {b}, and since B is nullable, FOLLOW(A) ⊇ FOLLOW(S) = {$}, giving FOLLOW(A) = {b, $}. FOLLOW(B) = FOLLOW(S) = {$}.
Worked example — expression grammar FIRST/FOLLOW table
- The standard LL(1) expression grammar: E → T E′; E′ → + T E′ | ε; T → F T′; T′ → * F T′ | ε; F → ( E ) | id. It is the grammar behind most GATE FIRST/FOLLOW and LL(1)-table questions.
- FIRST(F) = { (, id }. T → F T′ starts with F and F is not nullable, so FIRST(T) = FIRST(F) = { (, id }; similarly FIRST(E) = { (, id }. FIRST(E′) = { +, ε }; FIRST(T′) = { *, ε }.
- FOLLOW(E) = { ), $ } (E is the start symbol, and F → ( E ) puts ) after E). Because E → T E′ ends with E′, FOLLOW(E′) = FOLLOW(E) = { ), $ }.
- T appears in E → T E′ followed by E′ (nullable): FOLLOW(T) = (FIRST(E′) − ε) ∪ FOLLOW(E) = { +, ), $ }. T′ ends T → F T′, so FOLLOW(T′) = FOLLOW(T) = { +, ), $ }.
- F appears in T → F T′: FOLLOW(F) = (FIRST(T′) − ε) ∪ FOLLOW(T) = { *, +, ), $ }.
- Notice the pattern: the nullable primed non-terminals (E′, T′) hand their FOLLOW sets back to the non-terminal they came from. This “inheritance” is the step most students miss.
| Non-terminal | FIRST | FOLLOW |
|---|---|---|
| E | { (, id } | { ), $ } |
| E′ | { +, ε } | { ), $ } |
| T | { (, id } | { +, ), $ } |
| T′ | { *, ε } | { +, ), $ } |
| F | { (, id } | { *, +, ), $ } |
Worked example
Problem. For S → A B C ; A → a | ε ; B → b | ε ; C → c, find FOLLOW(A) and FOLLOW(B).
Solution. In S → A B C, FOLLOW(A) ⊇ FIRST(B C) − ε. FIRST(B C) = {b} ∪ FIRST(C) (B is nullable) = {b, c}. So FOLLOW(A) = {b, c}. FOLLOW(B) ⊇ FIRST(C) = {c}, and C is not nullable, so FOLLOW(B) = {c}.
FOLLOW fixed-point walkthrough with nullable symbols
- Grammar: S → A C B | C b b | B a ; A → d a | B C ; B → g | ε ; C → h | ε. Step 0, nullable symbols: B and C (direct ε), then A (A → B C) and S (S → A C B) — all four are nullable.
- Step 1, FIRST: FIRST(B) = {g, ε}; FIRST(C) = {h, ε}; FIRST(A) = {d} ∪ {g} ∪ {h} ∪ {ε} = {d, g, h, ε}; FIRST(S) = FIRST(A C B) ∪ FIRST(C b b) ∪ FIRST(B a) = {d, g, h, ε} ∪ {h, b} ∪ {g, a} = {a, b, d, g, h, ε}.
- Step 2, FOLLOW start: $ ∈ FOLLOW(S). Step 3, scan every production that has a non-terminal on its right-hand side: S → A C B gives FOLLOW(A) ⊇ FIRST(C B) − ε = {h, g} and, because C B is nullable, FOLLOW(S); FOLLOW(C) ⊇ {g} ∪ FOLLOW(S); FOLLOW(B) ⊇ FOLLOW(S).
- S → C b b gives FOLLOW(C) ⊇ {b}. S → B a gives FOLLOW(B) ⊇ {a}. A → B C gives FOLLOW(B) ⊇ FIRST(C) − ε = {h} ∪ FOLLOW(A) (C is nullable) and FOLLOW(C) ⊇ FOLLOW(A). A → d a, B → g | ε and C → h | ε contain no non-terminal, so they add nothing.
- FOLLOW(A) is complete after the first sweep because A appears only in S → A C B. A second sweep copies it into FOLLOW(B) and FOLLOW(C) and then nothing changes: the fixed point is reached.
| Symbol | Nullable | FIRST | FOLLOW |
|---|---|---|---|
| S | yes | { a, b, d, g, h, ε } | { $ } |
| A | yes | { d, g, h, ε } | { g, h, $ } |
| B | yes | { g, ε } | { a, g, h, $ } |
| C | yes | { h, ε } | { b, g, h, $ } |
Worked example
Problem. In the grammar above, find FOLLOW(B).
Solution. Collect the contributions: S → A C B gives FOLLOW(S) = {$}; S → B a gives {a}; A → B C gives FIRST(C) − ε = {h} and, since C is nullable, FOLLOW(A) = {g, h, $}. Union: FOLLOW(B) = {a, g, h, $}.
The parser family and containment hierarchy
- Top-down: recursive descent (with or without backtracking) and LL(1) predictive parsers. Bottom-up: operator-precedence and LR parsers — LR(0), SLR(1), LALR(1), CLR(1) (canonical LR(1)).
- Containment of grammar classes: LR(0) ⊂ SLR(1) ⊂ LALR(1) ⊂ CLR(1) = LR(1), and LL(1) ⊂ LR(1). Every LL(k) grammar is also LR(k); the converse is false.
- Language power: LR(1) parsers recognise exactly the deterministic context-free languages (DCFLs). LL(1) recognises a smaller class. No deterministic parser can handle languages like palindromes (ww^R), which need a non-deterministic PDA.
- LL parsers choose a production from the lookahead before reading the RHS; LR parsers delay the decision until the whole RHS is on the stack, which is why LR is more powerful.
- Languages versus grammars: LL(k) languages form a proper subset of the deterministic CFLs, while LR(k) for any k ≥ 1 accepts exactly the DCFLs, so LR(1) is enough in theory. The GRAMMAR classes LR(0), SLR(1), LALR(1) and CLR(1) differ, but all four describe DCFLs.
- Decision order for “which parser can handle this grammar?”: test LR(0), then SLR(1), then LALR(1), then CLR(1); the first one that is conflict-free is the answer. If none works, the grammar is not LR(1) (usually it is ambiguous).
- Parser generators: Yacc/Bison generate LALR(1) tables; ANTLR is LL(*). Hand-written compilers often use recursive descent for the easy error reporting.
- Syntax error handling modes: panic mode (skip tokens until a synchronizing token), phrase-level recovery (local correction), error productions, and global correction.
| Parser | Direction | Derivation traced | Lookahead used for decisions |
|---|---|---|---|
| LL(1) | top-down | leftmost | 1 token (FIRST / FOLLOW) |
| LR(0) | bottom-up | rightmost in reverse | none |
| SLR(1) | bottom-up | rightmost in reverse | FOLLOW of the LHS |
| LALR(1) | bottom-up | rightmost in reverse | merged LR(1) lookaheads |
| CLR(1) | bottom-up | rightmost in reverse | exact LR(1) lookaheads |
Worked example
Problem. True or false: every SLR(1) grammar is LALR(1) and every LALR(1) grammar is LR(1).
Solution. True. The containment chain LR(0) ⊂ SLR(1) ⊂ LALR(1) ⊂ LR(1) holds, so each class is contained in the next.
Exam tips
- For FIRST, read left to right and stop at the first non-nullable symbol; for FOLLOW, look at every place the symbol appears on a right-hand side.
- Never put ε in FOLLOW; always put $ in FOLLOW of the start symbol.
- When a symbol is followed by a nullable string, FOLLOW also inherits FOLLOW of the left-hand side.
- Number of parse trees for E → E op E | id with n operands is Catalan(n − 1).
- Ambiguous ⇒ not LL(k) and not LR(k). Memorise LR(0) ⊂ SLR ⊂ LALR ⊂ CLR and LL(1) ⊂ CLR.
10 GATE-style MCQs for Grammars, FIRST & FOLLOW with full explanations. Attempt each question before revealing the answer.
For the grammar S → A B ; A → a | ε ; B → b | ε, FOLLOW(A) is:
Show answer & explanation
Answer: B
FIRST(B) − ε = {b} is added; because B is nullable, FOLLOW(S) = {$} is also added. FOLLOW(A) = {b, $}.
For the same grammar S → A B ; A → a | ε ; B → b | ε, FIRST(S) is:
Show answer & explanation
Answer: B
FIRST(S) = (FIRST(A) − ε) ∪ (FIRST(B) − ε) and since both are nullable, ε is included: {a, b, ε}.
The number of distinct parse trees for the string id + id * id + id under the grammar E → E + E | E * E | id is:
Show answer & explanation
Answer: D
Four operands with three binary operators give Catalan(3) = 5 bracketings, and each is a different tree.
Which one of the following is TRUE about an ambiguous grammar?
Show answer & explanation
Answer: C
LR(k) and LL(k) grammars are unambiguous by definition. An ambiguous grammar may still generate an unambiguous language, so D is false.
The number of steps in a derivation of aaa from S → S S | a is:
Show answer & explanation
Answer: C
2 uses of S → SS and 3 uses of S → a: 2n − 1 = 5 steps for n = 3.
Which one of the following grammars is ambiguous?
Show answer & explanation
Answer: C
aaa has the two trees (aa)a and a(aa) in S → SS | a. The others generate each string in exactly one way.
Which statement about FIRST and FOLLOW sets is FALSE?
Show answer & explanation
Answer: B
FOLLOW sets contain only terminals and $; ε appears only in FIRST sets.
The dangling-else grammar S → i S | i S e S | a produces how many parse trees for the string i i a e a ?
Show answer & explanation
Answer: B
The else can match the inner i (i (i a e a)) or the outer i ((i i a) e a), giving exactly two parse trees.
For S → a S b | ε the set FOLLOW(S) is:
Show answer & explanation
Answer: D
S is the start symbol, so $ ∈ FOLLOW(S); in a S b the symbol b follows S. FOLLOW(S) = {b, $}.
Which of the following correctly orders the grammar classes by inclusion?
Show answer & explanation
Answer: B
More lookahead precision means more power: LR(0) ⊂ SLR(1) ⊂ LALR(1) ⊂ CLR(1).
Extra page-specific practice beyond the GATE samples. Attempt all 8, then reveal answers to check your reasoning.
For S → ( S ) S | ε the set FOLLOW(S) is:
Show answer & explanation
Answer: B) {), $}
S is the start symbol ($); in ( S ) S the symbol ) follows the first S; the last S inherits FOLLOW(S).
For S → A B | c ; A → a A | ε ; B → b B | d, FIRST(S) is:
Show answer & explanation
Answer: B) {a, b, c, d}
FIRST(B) = {b, d}. FIRST(A B) = {a} ∪ FIRST(B) = {a, b, d} because A is nullable. Then FIRST(S) = {a, b, d} ∪ {c} = {a, b, c, d}.
How many parse trees does id + id + id have under E → E + E | id?
Show answer & explanation
Answer: B) 2
Catalan(2) = 2: (id+id)+id and id+(id+id).
Which transformation makes the grammar E → E + E | E * E | id unambiguous with * binding tighter than +?
Show answer & explanation
Answer: A) E → E + T | T ; T → T * F | F ; F → id
Layering by precedence (E for +, T for *, F for operands) removes ambiguity and gives left associativity.
Which language needs a non-deterministic PDA and therefore cannot be parsed by any LR(k) parser?
Show answer & explanation
Answer: B) { w wᴿ | w ∈ {a,b}* }
Even palindromes without a middle marker are CFL but not deterministic CFL, so no LR(k) grammar exists for them.
If A → α B β with β nullable, which statement is correct?
Show answer & explanation
Answer: B) FOLLOW(A) ⊆ FOLLOW(B)
Whatever can follow A can also follow B because β can vanish.
Which statement is TRUE?
Show answer & explanation
Answer: B) A parse tree has exactly one leftmost and one rightmost derivation
Each parse tree fixes both. A sentence may have several trees if the grammar is ambiguous, and ambiguity is undecidable.
For S → A B ; A → a | ε ; B → b, FOLLOW(A) equals:
Show answer & explanation
Answer: B) {b}
FIRST(B) = {b} and B is not nullable, so nothing more is inherited from FOLLOW(S).
Topic FAQs
How do I know if a grammar is ambiguous in the exam?
Look for a string that can be parsed in two ways: a symmetric production such as E → E + E or S → S S, an unmatched-if pattern, or two different productions that can both start the same prefix. One string with two parse trees (or two leftmost derivations) proves ambiguity.
Can FOLLOW(A) be empty?
No in a reduced grammar with end marker: every reachable non-terminal has at least one follower or $ after it. FOLLOW of the start symbol always contains $.
Why does FOLLOW need ε-handling but not contain ε?
If the symbols after B can all vanish (derive ε), then whatever follows A also follows B, so FOLLOW(A) is added to FOLLOW(B). FOLLOW itself consists of terminals and $, never ε.
Is every unambiguous grammar LL(1) or LR(1)?
No. Unambiguity is necessary but not sufficient. A grammar can be unambiguous and still be left-recursive or need more than one lookahead, so it fails the LL(1) conditions; many unambiguous grammars also are not LR(1).
Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.