IAE Academy

GATE CS

Parsing

Top-down and bottom-up parsers

Parsing turns a stream of tokens into a parse tree by following a context-free grammar, either top-down (LL, building a leftmost derivation) or bottom-up (LR, building a rightmost derivation in reverse). For GATE you must be able to compute FIRST and FOLLOW sets, build LL(1) tables and LR(0), SLR(1), LR(1) and LALR(1) item sets and tables, spot conflicts, place a grammar in the class hierarchy, and count the moves a parser makes on a string.

13 previous-year questions · 12 solved · 5 practice questions

Grammars, derivations and ambiguity

A context-free grammar has terminals, nonterminals, a start symbol and productions of the form . Convention: the start symbol is the left side of the first production unless stated, is the empty string, $ is the end-of-input marker, FIRST and FOLLOW sets are sets of terminals (FIRST may also contain ), and an LR item writes the dot as .

A leftmost derivation always expands the leftmost nonterminal; a rightmost derivation always expands the rightmost one. A top-down parser traces a leftmost derivation. A bottom-up parser traces a rightmost derivation in reverse. A parse tree does not record the order of expansion, so one parse tree corresponds to exactly one leftmost and exactly one rightmost derivation.

A grammar is ambiguous if some string has two different parse trees (equivalently, two leftmost derivations, or two rightmost derivations). An ambiguous grammar is never LL(k) and never LR(k) for any k; put the other way, every LL(k) and every LR(k) grammar is unambiguous. The converse fails: is unambiguous but is not LR(k) for any k, because its language (odd-length palindromes) is not deterministic. Ambiguity is a property of the grammar, not the language: some ambiguous grammars have an equivalent unambiguous grammar, and some languages are inherently ambiguous.

Dangling else. In , the string if E then if E then other else other has two parse trees, one attaching else to the inner if and one to the outer. The usual rule attaches else to the nearest unmatched then. In an LR parser this is a shift-reduce conflict on else, resolved in favour of shift. For top-down parsing the grammar is first left-factored to , ; since else is in FOLLOW(), the cell holds both -productions, and keeping gives the nearest-then rule. The grammar is still not LL(1); the parser simply resolves the conflict by choice.

EXAM TIP

Ambiguity is undecidable in general, but one string with two parse trees proves it. A table or item-set conflict proves only that the grammar is not in that class (LL(1), SLR(1), …), not that it is ambiguous.

Preparing a grammar for top-down parsing

A predictive top-down parser loops forever on left recursion () and cannot choose between productions that start with a common prefix. Both are removed by rewriting the grammar. The rewritten grammar generates the same language but has a different parse tree shape.

REMOVING IMMEDIATE LEFT RECURSION

Conditions: no starts with , and no is . is a new nonterminal. The new grammar has alternatives in total: for and for .

LEFT FACTORING

Applies when two or more alternatives of share a nonempty prefix (take the longest one); is a new nonterminal, and an empty becomes . Repeat until no two alternatives of any nonterminal share a prefix.

Removing indirect left recursion

  1. Order the nonterminals .

  2. For to : for each , replace every production by , where are the current productions of .

  3. Then remove the immediate left recursion of using the formula above.

  4. The algorithm is guaranteed to work on a grammar with no cycles () and no -productions; remove those first if present.

EXAM TIP

Removing left recursion and left factoring are necessary for LL(1) but not sufficient: the result can still fail the LL(1) test. Bottom-up parsers have no trouble with left recursion; on a long list, left recursion keeps an LR parser's stack shallow, while right recursion makes the stack grow with the length of the list.

FIRST and FOLLOW sets

is the set of terminals that can begin a string derived from , plus if . is the set of terminals that can appear immediately to the right of in some sentential form derived from the start symbol, plus $ if can be the rightmost symbol of such a sentential form. FOLLOW never contains and is defined only for nonterminals.

Computing FIRST

  1. For a terminal : .

  2. For a production : add to .

  3. For a production : add to ; if , also add , and so on.

  4. Add to from this production only if every can derive .

  5. FIRST of a string is computed the same way.

  6. Repeat over all productions until no set changes.

Computing FOLLOW

  1. Put $ in for the start symbol .

  2. For a production : add to .

  3. For a production , or with : add all of to .

  4. Repeat until no set changes.

WORKED EXAMPLE

Grammar (start symbol ): , , . Compute FIRST and FOLLOW for every nonterminal.

Solution
  1. FIRST() = and FIRST() = , since each has an -alternative.

  2. FIRST(): start with FIRST() minus = ; is nullable, so add FIRST() minus = ; is nullable too, so add FIRST() = . So FIRST() = with no , because is a terminal.

  3. FOLLOW() = {$} (start symbol, and appears on no right side).

  4. FOLLOW(): in the string after is , with FIRST() = . In the symbol is last, so add FOLLOW() to itself (no change). So FOLLOW() = .

  5. FOLLOW(): the string after in is , giving ; adds FOLLOW() to itself. So FOLLOW() = .

Answer: FIRST: S = {a, b, c}, A = {a, ε}, B = {b, ε}. FOLLOW: S = {$}, A = {b, c}, B = {c}.

The sets from the worked example

Nonterminal

FIRST

FOLLOW

{$}

EXAM TIP

Keep a separate list of nullable nonterminals first. The usual slips are stopping at a nullable symbol instead of continuing past it, and putting into a FOLLOW set.

LL(1) grammars and predictive parsing

An LL(1) parser reads the input Left to right, builds a Leftmost derivation, and uses 1 symbol of lookahead. A predictive parser keeps a stack of grammar symbols (start symbol on top of $) and a table with a row per nonterminal and a column per terminal plus $. If the top is a terminal it must match the input; if it is a nonterminal and the lookahead is , it pops and pushes the right side of so that its leftmost symbol ends on top (that is, in reverse order). It accepts when the stack top and the input are both $. An empty entry is a syntax error. A recursive-descent parser (one procedure per nonterminal) that picks each production from one lookahead symbol, with no backtracking, implements the same idea.

Building the LL(1) table

  1. For each production and each terminal , put in .

  2. If , put in for every , including $.

  3. Every cell left empty is an error entry.

  4. A cell holding two or more productions is a conflict, and the grammar is not LL(1).

LL(1) CONDITION

Also at most one alternative of may derive . The condition holds for every nonterminal exactly when no cell of the LL(1) table has two entries.

LL(1) table for $S \to ABc$, $A \to aA \mid \varepsilon$, $B \to bB \mid \varepsilon$

$

error

error

error

error

No cell has two entries, so this grammar is LL(1). The entries under and come from FOLLOW() = , and under comes from FOLLOW() = .

EXAM TIP

A grammar is not LL(1) if it is ambiguous, left recursive (in a nonterminal that is reachable and derives some terminal string), or has two alternatives of one nonterminal with a common first terminal. Check nullable alternatives against FOLLOW: for with the entry gets both productions, which is the classic hidden conflict.

Bottom-up parsing: shift-reduce, LR(0) and SLR(1)

A bottom-up parser reduces the input to the start symbol. A handle of a right-sentential form is the right side of a production, at a particular position, whose replacement by the production's left side gives the previous right-sentential form of a rightmost derivation. Reducing handles one after another is called handle pruning. A shift-reduce parser has a stack and four moves: shift the next input symbol, reduce a handle on top of the stack, accept and error. The stack contents are always a viable prefix: a prefix of a right-sentential form that does not extend past the right end of its handle. The set of viable prefixes is a regular language, and the LR(0) automaton built below is a DFA that recognises it.

Two conflicts can arise. A shift-reduce conflict: the parser cannot tell whether to shift or to reduce. A reduce-reduce conflict: two different reductions are possible. Shift-shift conflicts cannot occur, because shifting a given symbol leads to one state.

An LR(0) item is a production with a dot marking how much of the right side has been seen, written . A production whose right side has symbols gives items; for the only item is . The grammar is augmented with a new start production , and reaching with $ as the next input means accept.

Building the LR(0) automaton (canonical collection)

  1. Closure(): start with the items of . While some item is present, add for every production of .

  2. Goto(, ): move the dot over in every item of of the form , then take the closure.

  3. Start with = closure of . Repeatedly apply Goto for every grammar symbol until no new set appears. Each set is a state.

  4. Action table, LR(0): if is in a state, shift on terminal . If a completed item (other than ) is in a state, reduce by it in every terminal column, including $. gives accept under $. The goto table holds transitions on nonterminals.

  5. SLR(1): the same automaton, but reduce by only on terminals in .

WORKED EXAMPLE

Augmented grammar: , . Build the LR(0) states, say whether the grammar is LR(0), and count the moves the parser makes on ((x)).

Solution
  1. : , , .

  2. Goto(, ) = : . Goto(, () = : , , . Goto(, x) = : .

  3. Goto(, ) = : . Goto(, () = and Goto(, x) = .

  4. Goto(, )) = : . No further sets appear, so there are 6 states.

  5. The only states with a completed item are (accept), and , each holding that single item. No state mixes a completed item with another item, so there is no conflict: the grammar is LR(0).

  6. Moves on ((x)): shift (, shift (, shift x, reduce , shift ), reduce , shift ), reduce , then accept. That is 5 shifts and 3 reductions: 8 moves before accept.

Answer: 6 states; the grammar is LR(0); the parse takes 5 shifts and 3 reductions (8 moves), then accept.

MOVES OF A DETERMINISTIC PARSER

Applies to LL(1) and LR parsers on an accepted string of tokens whose parse tree has internal nodes, not counting the augmented start . In LL, counts the matches and the expansions; in LR, counts the shifts and the reductions. A node for an -production counts in . Accept, and the final match of $, are not counted unless the question says so.

EXAM TIP

Conflicts in an LR(0) state: together with is a shift-reduce conflict, and two completed items are a reduce-reduce conflict. SLR(1) removes the shift-reduce conflict when , and removes the reduce-reduce conflict between and when .

Canonical LR(1) and LALR(1)

An LR(1) item pairs an LR(0) item with a lookahead terminal (or $): the parser may reduce by only if the next input symbol is . This is more precise than FOLLOW(), which merges every context in which appears. Convention: several lookaheads for one item are written as .

LR(1) CLOSURE

If is empty or nullable, itself is among the new lookaheads. The initial item is with lookahead $. Goto works exactly as in LR(0), carrying the lookaheads along unchanged. Reduce by only on the item's own lookahead.

Building LALR(1)

  1. Build the canonical LR(1) collection.

  2. Find states with identical cores (the same LR(0) items, ignoring lookaheads) and merge each group into one state, taking the union of the lookaheads item by item.

  3. The merged cores are exactly the states of the LR(0) automaton, so LALR(1) has as many states as LR(0). Build the action table as for LR(1), reducing on the merged lookaheads.

What merging can and cannot do. Merging can never create a shift-reduce conflict: the shift items depend only on the core, so a merged state with a shift-reduce conflict on means one of the original states already held the same reduce item with lookahead and the same shift item. Merging can create reduce-reduce conflicts, because two states may reduce by different productions with different lookaheads, and the union makes those lookaheads overlap. On an erroneous input an LALR(1) parser may make some extra reductions before it reports the error, but it never shifts an input symbol beyond the point where the canonical LR(1) parser would report it.

WORKED EXAMPLE

Grammar: , , . Show that it is LR(1) but not LALR(1).

Solution
  1. After shifting a, the closure contains (from ) and (from ). After shifting c the state is . The lookaheads differ, so there is no conflict.

  2. After shifting b, the closure has (from ) and (from ). After c the state is . Again no conflict, and no other state has a conflict, so the grammar is LR(1).

  3. The two states after c have the same core , so LALR merges them into .

  4. On d or e the merged state can reduce by or by : a reduce-reduce conflict.

Answer: The grammar is LR(1) but not LALR(1). It is not SLR(1) either, since FOLLOW() = FOLLOW() = .

Comparing parsers, and operator precedence

GRAMMAR-CLASS HIERARCHY

Each inclusion is proper. A grammar class here means the set of grammars the method parses without conflict. LL(1) is not contained in LALR(1), SLR(1) or LR(0), and none of those is contained in LL(1): LL(1) is incomparable with each of them. More generally every LL(k) grammar is LR(k).

Comparison of the bottom-up methods

Method

Item set

Reduce when lookahead is

Number of states

Conflicts possible

LR(0)

LR(0) items

any terminal or $

(the LR(0) count)

shift-reduce, reduce-reduce

SLR(1)

LR(0) items

in

same as LR(0)

shift-reduce, reduce-reduce

LALR(1)

LR(1) items merged by core

in the item's merged lookahead set

same as LR(0)

reduce-reduce (new ones), shift-reduce only if LR(1) had them

LR(1)

LR(1) items

the item's own lookahead

at least as many as LR(0), often many more

shift-reduce, reduce-reduce

EXAM TIP

LR(0), SLR(1) and LALR(1) always have the same number of states for one grammar; canonical LR(1) has the same or more. Parser generators of the YACC/Bison family build LALR(1) tables. An LL(1) grammar need not be SLR(1): , , is LL(1), but holds both and , and FOLLOW() = FOLLOW() = gives a reduce-reduce conflict in the SLR table.

EXAM TIP

An LL(1) grammar need not be LALR(1) either: , , , , , is LL(1), but the LR(1) states (reached after a) and (reached after b) share a core, and merging them gives a reduce-reduce conflict on a and b.

WORKED EXAMPLE

Grammar: , , . Show that it is LALR(1) but not SLR(1).

Solution
  1. = closure of contains , , , , . Goto(, ) = .

  2. FOLLOW: $ is in FOLLOW(), hence in FOLLOW() (from ). From , = is in FOLLOW(). From and , FOLLOW() = FOLLOW() = {=, $}.

  3. SLR(1): in Goto(, ), shift on = and reduce on FOLLOW(), which contains =: a shift-reduce conflict, so the grammar is not SLR(1).

  4. LR(1): in the item comes from with lookahead $ only, so the state after holds with lookahead $ only. There it shifts on = and reduces on $: no conflict.

  5. No other LR(1) state has the core , so merging leaves that state unchanged; the merged states elsewhere contain a single completed item or only shifts. So the LALR(1) table has no conflict.

Answer: The grammar is LALR(1) (hence LR(1)) but not SLR(1).

Operator-precedence parsing works for operator grammars: no right side is and no right side has two adjacent nonterminals. For each pair of terminals the parser uses one relation: ( yields precedence to : shift), (same handle, keep shifting), or ( takes precedence: reduce). The handle is the span between the nearest and the that holds between the top terminal of the stack and the next input symbol, and the parser looks only at terminals, ignoring which nonterminals sit between them. It is simple and fast, and it can parse some ambiguous expression grammars once precedence and associativity are given. Because it ignores nonterminals, it works for only a small class of grammars, it cannot handle an operator such as unary minus that shares its symbol with a binary operator, and one cannot always be sure it accepts exactly the language of the grammar.

EXAM TIP

When an LR parser generator is given an ambiguous expression grammar, precedence and associativity declarations settle each shift-reduce conflict. With on the stack and next: if has higher precedence, shift; if lower, reduce; if equal, reduce for a left-associative operator and shift for a right-associative one.

PREVIOUS-YEAR QUESTIONS

13 questions from the CS papers

Try each question first, then open the answer. We placed each question under a topic ourselves; the exam paper does not label topics.

See these papers in full: GATE CSE 2026 Set 1 · GATE CSE 2026 Set 2 · GATE CSE 2025 Set 1 · GATE CSE 2025 Set 2 · GATE CSE 2024 Set 1 · GATE CSE 2024 Set 2 · GATE CSE 2022 · GATE CSE 2020 · GATE CSE 2018

GATE 2026 CS2 Q.41

GATE 2026 · CS2Q.41 · 2 marks · MCQ

Consider the canonical parsing of the grammar below using terminals and non-terminals with as the start symbol.




Which one of the following options gives the number of shift-reduce conflicts that will occur in the ACTION table?

  1. (A)

    2

  2. (B)

    3

  3. (C)

    4

  4. (D)

    5

Answer and solution
See the question in the paper
GATE 2026 CS2 Q.41: answer and solution

GATE 2025 CS1 Q.46

GATE 2025 · CS1Q.46 · 2 marks · MSQ

Which of the following statement(s) is/are TRUE while computing First and Follow during top down parsing by a compiler?

  1. (A)

    For a production , will be added to .

  2. (B)

    If there is any input right end marker, it will be added to , where is the start symbol.

  3. (C)

    For a production , will be added to .

  4. (D)

    If there is any input right end marker, it will be added to , where is the start symbol.

Answer and solution
See the question in the paper
GATE 2025 CS1 Q.46: answer and solution

GATE 2025 CS2 Q.51

GATE 2025 · CS2Q.51 · 2 marks · MSQ

Consider two grammars and with the production rules given below:

: ;

: ; ;

where are the terminals. Which of the following option(s) is/are CORRECT?

  1. (A)

    is not and is .

  2. (B)

    is and is not .

  3. (C)

    and are not .

  4. (D)

    and are ambiguous.

Answer and solution
See the question in the paper
GATE 2025 CS2 Q.51: answer and solution

GATE 2024 CS1 Q.38

GATE 2024 · CS1Q.38 · 2 marks · MCQ

Consider the following grammar , with as the start symbol. The grammar has three incomplete productions denoted by (1), (2), and (3).

The set of terminals is . The FIRST and FOLLOW sets of the different non-terminals are as follows.

, ,

is the set of the three symbols , and the end marker $, and .

Which one of the following options CORRECTLY fills in the incomplete productions?

  1. (A)

    (1) , (2) , (3)

  2. (B)

    (1) , (2) , (3)

  3. (C)

    (1) , (2) , (3)

  4. (D)

    (1) , (2) , (3)

Answer and solution
See the question in the paper
GATE 2024 CS1 Q.38: answer and solution

GATE 2024 CS2 Q.40

GATE 2024 · CS2Q.40 · 2 marks · MCQ

Consider the following context-free grammar where the start symbol is and the set of terminals is .



The following is a partially-filled LL(1) parsing table (rows S, A, B; columns a, b, c, d, $).

Which one of the following options represents the CORRECT combination for the numbered cells in the parsing table?

Note: In the options, "blank" denotes that the corresponding cell is empty.

GATE 2024 CS2 question 40: LL(1) parsing table with columns a, b, c, d, and rows S, A, B.Tap to open full size
Figure from the GATE 2024 CS2 paper. It is part of the question.
Figure description

LL(1) parsing table with columns a, b, c, d, and rows S, A, B. Row S: a = S -> AaAb; b = S -> BbBa; c = (1); d = (2); = empty. Row A: a = A -> epsilon; b = (3); c = A -> cS; d = empty; = empty. Row B: a = (4); b = B -> epsilon; c = empty; d = B -> dS; = empty.

  1. (A)

    (1) S -> AaAb (2) S -> BbBa (3) A -> epsilon (4) B -> epsilon

  2. (B)

    (1) S -> BbBa (2) S -> AaAb (3) A -> epsilon (4) B -> epsilon

  3. (C)

    (1) S -> AaAb (2) S -> BbBa (3) blank (4) blank

  4. (D)

    (1) S -> BbBa (2) S -> AaAb (3) blank (4) blank

Answer and solution
GATE 2024 CS2 Q.40: answer and solution

GATE 2022 CS Q.13

GATE 2022 · CSQ.13 · 1 mark · MCQ

Which one of the following statements is TRUE?

  1. (A)

    The parser for a grammar cannot have reduce-reduce conflict if the parser for does not have reduce-reduce conflict.

  2. (B)

    Symbol table is accessed only during the lexical analysis phase.

  3. (C)

    Data flow analysis is necessary for run-time memory management.

  4. (D)

    parsing is sufficient for deterministic context-free languages.

Answer and solution
See the question in the paper
GATE 2022 CS Q.13: answer and solution
Show the other 3 questions

GATE 2018 CS Q.38

GATE 2018 · CSQ.38 · 2 marks · MCQ

Consider the following parse tree for the expression a#b$c$d#e#f, involving two binary operators $ and #.

Which one of the following is correct for the given parse tree?

GATE 2018 CS question 38: Parse tree.Tap to open full size
Figure from the GATE 2018 CS paper. It is part of the question.
Figure description

Parse tree. Root node # has two children: leaf a (left) and an internal node # (right). That right # node has two children: an internal node (left) and an internal # node (right). The left node has two children: an internal node (left) whose children are leaves b and c, and leaf d (right). The right # node has two children: leaf e (left) and leaf f (right). Leaves read left to right: a, b, c, d, e, f.

  1. (A)

    $ has higher precedence and is left associative; # is right associative

  2. (B)

    # has higher precedence and is left associative; $ is right associative

  3. (C)

    $ has higher precedence and is left associative; # is left associative

  4. (D)

    # has higher precedence and is right associative; $ is left associative

Answer and solution
GATE 2018 CS Q.38: answer and solution

OTHER EXAMS

ISRO: 2 questions

From ISRO's Scientist/Engineer written test: ISRO CS 2025, ISRO CS 2023. They are not counted in the GATE numbers on this page.

ISRO CS 2023 Q.11

ISRO 2023 · CSQ.11 · 1 mark · MCQ

In the context of parsing techniques, LL(1) refers to:

  1. (A)

    Grammars that parse the input from left to right, produce a rightmost derivation, with a lookahead of 1 symbol.

  2. (B)

    Grammars that parse the input from left to right, produce a leftmost derivation, with a lookahead of 1 symbol.

  3. (C)

    Grammars that parse the input from left to right, and backtrack at most once.

  4. (D)

    Grammars that parse the input from right to left, produce a leftmost derivation, and backtrack at most once.

Answer and solution
See the question in the paper
ISRO CS 2023 Q.11: answer and solution

PRACTICE

5 questions to test yourself

PRACTICE 11 mark · NAT

The grammar is rewritten by the standard procedure for removing immediate left recursion. Counting every alternative as a separate production, how many productions does the new grammar have?

Answer and solution

Answer:

  1. Here , , , .

  2. The new grammar is and .

  3. That is 2 alternatives for and 3 for , so productions.

PRACTICE 22 marks · NAT

Grammar (start symbol ): , , . What is ? (The end marker $ counts as a member where it appears.)

Answer and solution

Answer:

  1. FIRST() = . FIRST(): from we get ; from we get , and since is nullable also . So FIRST() = and is not nullable.

  2. FOLLOW() = {$}.

  3. FOLLOW(): from add FIRST() = ( is not nullable, so nothing from FOLLOW()); from add FOLLOW() to itself; from add . So FOLLOW() = , size 3.

  4. FOLLOW(): from add FOLLOW() = {$}; adds nothing new. So FOLLOW() = {$}, size 1.

  5. Sum = .

PRACTICE 32 marks · MSQ

Which of the following statements are true?

  1. (A)

    Every LL(1) grammar is LR(1).

  2. (B)

    Every LR(0) grammar is SLR(1).

  3. (C)

    Merging LR(1) states with the same core can introduce a new shift-reduce conflict.

  4. (D)

    For a given grammar, the SLR(1) and LALR(1) parsers have the same number of states.

Answer and solution

Answer: (A), (B), (D)

  1. A is true: LL(1) grammars form a proper subset of LR(1) grammars.

  2. B is true: the SLR(1) table only removes reductions (they happen on FOLLOW instead of everywhere), so an LR(0) grammar stays conflict-free.

  3. C is false: merging can introduce only reduce-reduce conflicts, since shift items depend on the core alone.

  4. D is true: both use exactly the states of the LR(0) automaton.

PRACTICE 41 mark · MCQ

Which one of the following grammars (start symbol ) is LL(1)?

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution

Answer: (C)

  1. A: both alternatives begin with , so has two entries (it needs left factoring).

  2. B: left recursive. FIRST() = FIRST() = = FIRST(), so holds both productions; not LL(1).

  3. C: FIRST() = ; the -alternative goes under FOLLOW() = {, $}. These do not meet, so there is no conflict: LL(1).

  4. D: FOLLOW() = , so is placed under , where is also placed: a conflict.

PRACTICE 52 marks · NAT

Consider the grammar (start symbol , terminals and ). An SLR(1) parser parses the string and accepts it. Counting only shift and reduce moves (the accept move is not counted), how many moves does the parser make?

Answer and solution

Answer:

  1. The string has tokens, so there are 5 shifts.

  2. The parse tree uses once and twice, so reductions.

  3. Total moves = .

  4. The sequence is: shift , reduce , shift , shift , reduce , shift , shift , reduce .

OFFICIAL GATE 2027 SYLLABUS WORDING

Copied from the GATE 2027 syllabus; see all 2027 syllabi.

GATE CS

parsing

Preparing in Kolkata? IAE Academy's course for GATE CSE.