Top-down parsing
Top-down parsing: how to analyse a sentence from the start symbol downward using recursive-descent and predictive (LL(1)) methods, FIRST/FOLLOW sets and table-driven parsing.
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 compilers and language tools to check if source code follows a grammar and to build parse trees used for translation and optimisation. Engineers use recursive-descent parsers for simple languages and predictive (LL(1)) parsers where a fast table-driven parser is needed (for front-end syntax analysis). It connects to other topics like Programming language grammars, Lexical analysis, Bottom-up parsing and Syntax-directed translation.
Key ideas
A derivation is a sequence of rule applications replacing a nonterminal with the right side of one of its productions. A leftmost derivation always replaces the leftmost nonterminal at each step. A parse tree is a tree representation of a derivation: root labelled S, internal nodes nonterminals, leaves terminals or ε (empty string). To draw a parse tree for a derivation, draw S at top, expand children according to the production used at each step; label each internal node with the nonterminal and label each child node with the symbol in the production's right-hand side.
Top-down parsing attempts to construct a leftmost derivation from the start symbol to the input string, expanding nonterminals to match the next input tokens. Two practical implementations: recursive-descent parser (a set of mutually recursive functions, each for a nonterminal) and predictive parser (table-driven, stack-based).
A grammar is LL(1) if left-to-right scan of input, producing a leftmost derivation, requires at most 1 lookahead token to decide which production to use. LL(1) grammars permit a predictive parsing table with no conflicts. Equivalently, for each nonterminal A, for all distinct productions A → αi and A → αj (i ≠ j), FIRST(αi) ∩ FIRST(αj) = ∅; and if ε ∈ FIRST(αi) then FIRST(αj) ∩ FOLLOW(A) = ∅ for all j ≠ i.
Define ε as the empty string (the production A → ε means A can derive nothing). When computing sets below, ε is treated specially.
FIRST(α) for a string α (sequence of terminals/nonterminals) is the set of terminals that can begin strings derived from α; include ε in FIRST(α) iff α ⇒* ε. Exact constructive rules universities expect:
- If X is a terminal, FIRST(X) = {X}.
- If X is ε, FIRST(X) = {ε}.
- If X is a nonterminal and X → Y1 Y2 ... Yk are productions, then add all non-ε symbols of FIRST(Y1) to FIRST(X); if FIRST(Y1) contains ε, then add FIRST(Y2), and so on; if all FIRST(Yi) contain ε, add ε to FIRST(X). Compute FIRST sets iteratively until no change.
FOLLOW(A) for a nonterminal A is the set of terminals that can appear immediately to the right of A in some sentential form; formally, b ∈ FOLLOW(A) if S ⇒* α A b β for some α, β. Rule-based computation (standard university algorithm):
- Place end-of-input marker $ in FOLLOW(S) (S start symbol).
- For each production A → α B β, add FIRST(β) \ {ε} to FOLLOW(B).
- If A → α B or A → α B β where FIRST(β) contains ε, add FOLLOW(A) to FOLLOW(B). Iterate until stable.
Predictive parser table construction (exact rule): For each production A → α,
- For each terminal a in FIRST(α), put A → α into TABLE[A, a].
- If ε ∈ FIRST(α), then for each b in FOLLOW(A) put A → α into TABLE[A, b].
- If any TABLE entry receives two different productions, the grammar is not LL(1). Describe what to draw: draw the table as rows labelled by nonterminals and columns labelled by terminals plus $. Fill a cell with the production or blank; conflicts are cells with multiple productions.
Predictive parsing algorithm (stack method): Start with stack containing [S, $], input has tokens followed by $; repeat: let X = top(stack) and a = current input token. If X is terminal: if X == a then pop and advance input else error. If X is nonterminal: consult TABLE[X, a]; if entry is A → α, pop X and push the symbols of α in order so the leftmost symbol becomes the new top (skip ε); else error. Accept when stack is [$] and input token is $.
Left recursion: A production A → A α | β is left-recursive. Left recursion must be eliminated for most top-down parsers. Standard elimination for immediate left recursion A → A α1 | A α2 | ... | β1 | β2 | ... where βi do not start with A: replace with A → β1 A' | β2 A' | ... and A' → α1 A' | α2 A' | ... | ε. To remove indirect left recursion across nonterminals A1, A2, ..., An: for i = 1 to n, for each j = 1 to i−1, replace any production Ai → Aj γ by all productions Aj → δ, yielding Ai → δ γ for each δ; then eliminate any immediate left recursion on Ai.
Left factoring: If productions A → α β1 | α β2 | ... share common prefix α, replace with A → α A' and A' → β1 | β2 | ... to make predictive choice possible with 1 token.
Assumptions: terminals and nonterminals are disjoint; grammar finite; input tokens are available via lexer.
Formulas
FIRST(X) — the set of terminals that begin strings derived from symbol or string X; includes ε if X ⇒* ε. Applies when X ∈ (N ∪ Σ ∪ {ε})*.
FOLLOW(A) — the set of terminals that can immediately follow nonterminal A in some sentential form; includes $ for end marker if start symbol. Applies for A ∈ N.
TABLE[A, a] = A → α if a ∈ FIRST(α) — predictive table rule when α does not derive ε.
TABLE[A, b] = A → α if ε ∈ FIRST(α) and b ∈ FOLLOW(A) — table entry for ε-productions.
Predictive parser stack action pseudocode syntax to remember:
while stack.top ≠ $:
X = stack.top; a = input.current
if X is terminal:
if X == a: pop; advance input
else error
else if TABLE[X, a] = X → Y1 Y2 ... Yk:
pop X; push Y1 Y2 ... Yk (skip ε)
else error
accept if stack.top == $ and input.current == $
Worked examples
Example 1 — standard expression grammar (build FIRST, FOLLOW, table, parse): Grammar (terminals: id, +, *, (, ), $; nonterminals: E, E', T, T', F; start: E): 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() = {}, FIRST(() = {(}, FIRST()) = {)}
- FIRST(F): from F → ( E ) add '('; from F → id add 'id' → FIRST(F) = {(, id}
- FIRST(T'): productions T' → * F T' | ε: FIRST(T') = {*, ε}
- FIRST(T): T → F T' → FIRST(F) plus if F ⇒* ε (it doesn't), so FIRST(T) = FIRST(F) = {(, id}
- FIRST(E'): E' → + T E' | ε → FIRST(E') = {+, ε}
- FIRST(E) = FIRST(T) = {(, id}
Step 2: Compute FOLLOW sets (iterative): start with FOLLOW(E) contains $.
- From E → T E' add FIRST(E') \ {ε} = {+} to FOLLOW(T). If E' can be ε (yes), add FOLLOW(E) to FOLLOW(T) (so $ goes to FOLLOW(T)).
- From T → F T' add FIRST(T') \ {ε} = {*} to FOLLOW(F). If T' can be ε, add FOLLOW(T) to FOLLOW(F).
- From productions with E' and T' apply rules similarly. Final sets (computed stepwise): FOLLOW(E) = {), $} FOLLOW(E') = {), $} FOLLOW(T) = {+, ), $} FOLLOW(T') = {+, ), $} FOLLOW(F) = {*, +, ), $}
Step 3: Build predictive table. Example entry: for E → T E' put this production in TABLE[E, a] for each a ∈ FIRST(T E') = FIRST(T) = {(, id}. Similarly E' → + T E' goes into TABLE[E', '+']; E' → ε goes into TABLE[E', b] for each b ∈ FOLLOW(E') = {), $}. Describe table to draw: rows E,E',T,T',F; columns 'id','(', '+','*',')','$'; fill each cell with production or blank. Check that no cell has more than one entry — grammar is LL(1).
Step 4: Parse input id + id * id $ Show stack trace (columns: step, stack (top left), input, action):
- Stack: [E,$] Input: [id + id * id $] Action: expand E → T E' (push E' then T)
- Stack: [T E', $] Input: [id + ...] Action: expand T → F T'
- Stack: [F T' E', $] Input: [id + ...] Action: expand F → id
- Stack: [id T' E', $] Input: [id + ...] Action: match id: pop id, advance input
- Stack: [T' E', $] Input: [+ id * id $] Action: TABLE[T', '+'] uses ε so pop T'
- Stack: [E', $] Input: [+ id * id $] Action: TABLE[E', '+'] → + T E' ; push E', T, +
- Stack: [+, T, E', $] Input: [+ id * id $] Action: match +
- Stack: [T, E', $] Input: [id * id $] Action: T → F T'
- Stack: [F T' E', $] Input: [id * id $] Action: F → id, match id ...
- After matching id, Stack [T' E',$] Input: [* id $] Action: TABLE[T', '*'] → * F T' ... continue similarly: after finishing, accept. Final result: input accepted and parse tree can be drawn following expansions. Bold final: input accepted.
Example 2 — left recursion elimination and left factoring:
- Given A → A α | β where β does not start with A, transform to: A → β A' A' → α A' | ε Show worked transformation: A → A a | b becomes A → b A' A' → a A' | ε
- Left factoring example: A → a b | a c d becomes A → a A' A' → b | c d Explain when to apply: when two or more productions for A begin with same prefix so a single lookahead token cannot decide.
Common mistakes
- Incorrectly treating ε: adding ε to FIRST of a terminal or forgetting to remove ε when using FIRST(α) \ {ε}.
- Pushing production symbols in wrong order (should push rightmost first so leftmost appears on top).
- Declaring grammar LL(1) without checking table conflicts (two different productions in a single TABLE cell).
- Not eliminating indirect left recursion (A → B α and B → A β) before trying recursive-descent.
- Mixing terminals and token names: be consistent with lexer token names (e.g., id, number) when computing FIRST/FOLLOW and table.
For your exam
- Short notes: explain recursive-descent vs predictive parsing, when to use each, pros and cons (predictive parsers are table-driven and faster; recursive-descent is easy to write but needs grammar adjusted).
- Derivations: compute FIRST and FOLLOW sets step-by-step; show iteration until no changes and list intermediate updates.
- Construction: build predictive parsing table and show it as a matrix. A full-marks answer must show each table cell filled according to rules and point out conflicts if any.
- Tracing: parse a given input with the table-driven stack algorithm; show a clear stack/input/action table and the final parse tree or accept/reject decision.
- Transformations: remove left recursion and perform left factoring with exact transformed grammar; explain why transformation preserves language (sketch proof by showing how derivations correspond).
A full-marks answer always labels terminals and nonterminals, shows all FIRST/FOLLOW steps, shows table entries with explanation, and includes a stack trace (or parse-tree) for an example input.
Quick check
- Define FIRST(α) in one line.
- What change do you make to a grammar production A → A α | β to eliminate immediate left recursion?
- In the predictive parsing table rule, when do you use FOLLOW(A) to place a production A → α into TABLE[A, b]?
Answers: 1) FIRST(α) is the set of terminals that can begin strings derived from α, including ε if α ⇒* ε. 2) Replace with A → β A' and A' → α A' | ε. 3) Use FOLLOW(A) when ε ∈ FIRST(α): put A → α in TABLE[A, b] for each b ∈ FOLLOW(A).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?