Top-down parsing: recursive descent and LL(1)
Top-down parsing (recursive descent and LL(1)): definitions, algorithms (FIRST/FOLLOW, predictive table), transformations (left-recursion removal, left-factoring), worked traces for grammar E→T E' etc., common mistakes and exam tips.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Top-down parsing is used in the frontend of compilers (syntax analysis phase) to turn token streams into parse trees or abstract syntax trees. Engineers implement recursive-descent parsers by hand for small languages or use LL(1) parser generators when a grammar is suitable; understanding LL(1) conditions and FIRST/FOLLOW computations is essential to build correct, fast, and debuggable parsers.
Key ideas
Start with the basic building blocks of grammars and parsing.
Grammar: a 4-tuple (V, T, P, S) where V is a finite set of nonterminals, T a finite set of terminals, P a finite set of productions (rules of the form A → α, A ∈ V, α ∈ (V ∪ T)*), and S ∈ V the start symbol. Define each term before use.
Derivation: applying productions to replace nonterminals step by step. A string w ∈ T* is in the language of the grammar if S ⇒* w (zero or more derivation steps).
Nullable (ε-productions): A symbol X is nullable if X ⇒* ε. We must treat ε explicitly in computations.
FIRST(α) for a string α (α ∈ (V ∪ T)) is the set of terminals that can begin strings derived from α, plus ε if α ⇒ ε. This is defined inductively and computed by an algorithm below. By convention, for a terminal a, FIRST(a) = {a}, and FIRST(ε) = {ε}.
FOLLOW(A) for a nonterminal A is the set of terminals that can appear immediately to the right of A in some sentential form, plus $ (end-of-input) if A can occur at the end.
Recursive-descent parser: a collection of mutually recursive procedures, one per nonterminal, that attempt to match the input tokens. It is simple to write when grammar is suitable: no left recursion, ideally LL(1).
LL(1) grammar: a grammar for which a left-to-right, leftmost derivation parser using 1 token lookahead decides the correct production without backtracking. Precisely, a grammar is LL(1) if a predictive parsing table can be constructed with at most one production per table entry.
Predictive parsing table: rows indexed by nonterminals and columns by terminals (plus $). An entry M[A, a] contains a single production A → α if a ∈ FIRST(α) or if ε ∈ FIRST(α) and a ∈ FOLLOW(A). The grammar is LL(1) iff no entry gets two different productions.
Assumptions and necessary transformations:
- A recursive-descent parser cannot handle left recursion (direct or indirect). Remove left recursion by grammar transformation before writing routines.
- Ambiguous grammars are not LL(1) unless disambiguated. Left-factoring is used to transform grammars with common prefixes to be suitable for predictive parsing. For example, if A → αβ1 | αβ2 then factor as A → α A' and A' → β1 | β2 (generalize as needed).
Exact algorithms often asked for:
- Compute FIRST sets by iterating rules until no change: for each production A → X1 X2 ... Xn add FIRST(X1){ε} to FIRST(A); if X1 nullable, add FIRST(X2){ε}, etc.; if all Xi nullable add ε.
- Compute FOLLOW sets by: place $ in FOLLOW(S). For each A → α B β, add FIRST(β){ε} to FOLLOW(B). If β nullable or production ends with B, add FOLLOW(A) to FOLLOW(B). Iterate until fixed point.
What to draw for an exam diagram:
- Draw a predictive parsing table: a grid with nonterminals as rows and terminals plus $ as columns. Fill each cell with the production A → α that belongs there. Draw a separate stack trace: a vertical stack with symbols, arrow indicating next input token, and show actions (expand by production, match token, pop).
Formulas
FIRST(X) — FIRST set of grammar symbol or string X. (No SI units; applies to grammar analysis.)
FOLLOW(A) — FOLLOW set of nonterminal A. (Applies in predictive table construction.)
If A → α and a ∈ FIRST(α) then M[A, a] = A → α — M is predictive parsing table; a is terminal.
If A → α and ε ∈ FIRST(α) and b ∈ FOLLOW(A) then M[A, b] = A → α — handles ε-productions.
Grammar is LL(1) ⇔ ∀A, for any two distinct productions A → α and A → β:
(FIRST(α) ∩ FIRST(β)) = ∅ and (if ε ∈ FIRST(α) then FIRST(β) ∩ FOLLOW(A) = ∅) and (if ε ∈ FIRST(β) then FIRST(α) ∩ FOLLOW(A) = ∅)
(Each symbol: A nonterminal, α,β strings of grammar symbols, FIRST sets and FOLLOW sets as defined. Applies to checking LL(1) property.)
Syntax to remember for recursive-descent (pseudocode pattern):
procedure A(): — top of routine for nonterminal A
lookahead = next token
if lookahead in SELECT(A → α) then match/expand α
else error()
SELECT(A → α) = FIRST(α) ∪ (if ε ∈ FIRST(α) then FOLLOW(A) else ∅).
Worked examples
Example 1: FIRST and FOLLOW and predictive table for a classic expression grammar. Grammar G: E → T E' E' → + T E' | ε T → F T' T' → * F T' | ε F → ( E ) | id
Step 1: Compute FIRST sets (iterative):
- FIRST(id) = {id}
- FIRST('(') = {'('}
- FIRST(F) = {'(', id}
- FIRST(T') = {'*', ε}
- FIRST(T) = FIRST(F) = {'(', id}
- FIRST(E') = {'+', ε}
- FIRST(E) = FIRST(T) = {'(', id} (Explain: e.g. FIRST(T') includes '' because of production T'→'' F T' and ε because of T'→ε.)
Step 2: Compute FOLLOW sets (iterate):
- FOLLOW(E) contains $ (since E is the start symbol)
- From E → T E', FOLLOW(T) includes FIRST(E'){ε} = {'+'}. But T followed by E' which can be ε, so FOLLOW(T) also includes FOLLOW(E) = {$} → FOLLOW(T) = {'+', $}
- For E' → + T E', FOLLOW(T) includes FIRST(E'){ε} = {'+'}; since the trailing E' can derive ε, also add FOLLOW(E') to FOLLOW(T). Continue carefully; final sets:
- FOLLOW(E) = {')', $}
- FOLLOW(E') = {')', $}
- FOLLOW(T) = {'+', ')', $}
- FOLLOW(T') = {'+', ')', $}
- FOLLOW(F) = {'*', '+', ')', $} (Examiners expect step-by-step production scanning; above are final sets.)
Step 3: Predictive table: For each production A→α, for each terminal a in FIRST(α) put that production in M[A,a]; if ε ∈ FIRST(α) put production in M[A,b] for each b ∈ FOLLOW(A). The table has unique entries ⇒ grammar is LL(1).
Example 2: Recursive-descent trace on input id + id * id $ Use the same grammar (it is already LL(1) and not left-recursive). Show call sequence (abbreviated): Tokens: id + id * id $ Call E() E -> T E' Call T() T -> F T' Call F() F -> id (match id) // consume id return to T, now T' Call T'() lookahead = '+'; T' -> ε (since '' not matched) return return to E, now E' Call E'() lookahead = '+'; E' -> + T E' (match '+') match '+' (consume '+') Call T() ... parse id * id similarly, matching '' in T' and returning finally E' -> ε when lookahead is $ End with success and parse tree built. Show stack-style diagram: top-of-stack grows with calls E, T, F etc., tokens consumed as matches.
Example 3 (short): Demonstrate left recursion removal. Given A → A α | β, transform to A → β A' A' → α A' | ε Explain why this removes left recursion and preserves leftmost derivations (show brief derivation equivalence argument). For multiple left-recursive and non-left-recursive alternatives A → A α1 | ... | A αm | β1 | ... | βn, transform to A → β1 A' | ... | βn A' and A' → α1 A' | ... | αm A' | ε. To eliminate indirect left recursion, order nonterminals and substitute earlier definitions into later ones before applying the immediate case.
Common mistakes
- Not adding FOLLOW(S) = $ (start symbol) or wrong end-marker usage.
- Mixing up FIRST(α) and FIRST(A) for productions A → α.
- Failing to left-factor before constructing SELECT sets; this leads to multiple entries in predictive table.
- Trying to write recursive-descent routines without removing left recursion (infinite recursion).
- Incorrectly filling predictive table entries for ε-productions (must use FOLLOW(A)).
- Confusing terminals (like '+' token) with characters: be explicit about token names.
For your exam
Typical question types:
- Definitions and short notes: define FIRST, FOLLOW, LL(1), recursive-descent, left recursion.
- Derivations and algorithms: show algorithm and step-by-step computing FIRST and FOLLOW for given grammar.
- Constructions: build predictive parsing table and show it is LL(1) or not; show how to transform grammar to LL(1) (remove left recursion, left-factor).
- Traces/programming: write recursive-descent routines or show a parser trace on input tokens with stack and input state.
- Proof-style: prove that transformed grammar preserves language (usually for left recursion removal case).
What full-marks answers include:
- Clear definitions (bold or underlined in own notes), explicit notation (which is start symbol, terminals), and stating assumptions.
- Full FIRST and FOLLOW computation with iterations until fixed point (show at least two iterations if nontrivial).
- Correct predictive table (drawn as grid) and justification when entries collide (explain non-LL(1)).
- For recursive-descent, present procedures for each nonterminal and show a short trace on sample input.
Quick check
- What is left recursion and why is it a problem for recursive-descent parsers?
- State the rule that places a production A → α in the predictive parsing table entry M[A, a].
- For grammar S → 'a' S | ε, what are FIRST(S) and FOLLOW(S)?
Answers: 1) Left recursion is when a nonterminal can derive a sentential form beginning with itself (A ⇒+ A α); it causes infinite recursion in naive recursive-descent parsers. 2) Put A → α into M[A,a] if a ∈ FIRST(α); if ε ∈ FIRST(α) also put it for every a ∈ FOLLOW(A). 3) FIRST(S) = {'a', ε}, FOLLOW(S) = {$} (since S is the start symbol; in S → 'a' S, S appears at the end, so no terminal follows it).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?