Consider two grammars and with the production rules given below:
: ;
: ; ;
where are the terminals. Which of the following option(s) is/are CORRECT?
- (A)
is not and is .
- (B)
is and is not .
- (C)
and are not .
- (D)
and are ambiguous.
Consider two grammars and with the production rules given below:
: ;
: ; ;
where are the terminals. Which of the following option(s) is/are CORRECT?
is not and is .
is and is not .
and are not .
and are ambiguous.
ANSWER
(C) and (D): neither grammar is LL(1), and both are ambiguous.
Official answer: C, DSource: Official answer key, GATE 2025 CS2 (IIT Roorkee)
An grammar needs, for every nonterminal, the FIRST sets of its alternatives to be pairwise disjoint (and, for a nullable alternative, disjoint from FOLLOW). No nonterminal here is nullable, so only the FIRST sets matter. Any ambiguous grammar is also not .
: both and have . They overlap, so is not .
is the dangling-else grammar, so it is ambiguous. The string if b then if b then a else a has two parse trees: the else can belong to the inner if ( outside, inside) or to the outer if ( outside, inside).
: . The alternatives of are with and with . Both contain , so on input the parser cannot choose between them. is not . So (A) and (B) are false and (C) is true.
Is ambiguous? The else-part of is an , and an can be an unmatched . So an else written after it can attach in two places. Take the string if b then if b then c else if b then c else c, and number its keywords if1 … if2 … else1 if3 … else2.
Parse 1 (else2 belongs to if1): with . Here with and (using ). Every step uses a production of .
Parse 2 (else2 belongs to if3): . Then with , and with and . Every step is again valid.
The two trees are different (in one else2 pairs with if1, in the other with if3) and they produce the same string. So is ambiguous. It is not the standard unambiguous matched/unmatched grammar, because there the else-part of a matched statement must itself be matched, while allows any .
Both grammars are ambiguous, so (D) is true. (C) is true as well. Correct options: (C) and (D).
KEY IDEA
FIRST sets clash for both grammars on the token , so neither is . is the classic dangling-else grammar. only looks like the fix: the else-part of is a general , which can be an unmatched if, so a later else can still attach in two places, as in if b then if b then c else if b then c else c.
WATCH OUT FOR
Treating as the textbook unambiguous dangling-else grammar. In that grammar the else-part of a matched statement must itself be matched. writes , which lets an unmatched if sit inside a matched one. A short test string like if b then if b then c else c has only one parse, so you need a longer string with two elses to see the ambiguity.
From the GATE 2025 CS2 paper. Every question of this paper · Download the full paper · All 13 Parsing questions, with notes