GATE / CS ARCHIVE

GATE CSE 2001 / QUESTION 18(b)

Enumerate parse trees for abab

Compiler Design · Parsing & Syntax Analysis · Full GATE CSE 2001 paper

GATE 2001, Q18(b) Descriptive
Report issue

Parsing & Syntax Analysis

Question 18(b), GATE 2001: Grammar S→aSbS | bSaS | ε; construct all parse trees of abab and determine ambiguity.
Question 18(b), GATE 2001: Grammar S→aSbS | bSaS | ε; construct all parse trees of abab and determine ambiguity.
Tap to enlarge
Answer & solution

Answer: Exactly two parse trees; grammar is ambiguous. (no official key was published)

Step through it (2 derivations)

The root must use S→aSbS because the yield begins with a. Its explicit b can be the b at position 2 or position 4. These exhaust the possibilities. Use S[children] for an ordered parse-tree node; S[ε] is an empty production.

Tree 1: S[a, S[ε], b, S[a, S[ε], b, S[ε]]]
Tree 2: S[a, S[b, S[ε], a, S[ε]], b, S[ε]]

Accessible tree description: in tree 1 the root’s first S is empty and its final S generates ab. In tree 2 its first S generates ba and its final S is empty. Their leftmost derivations are:
S⇒aSbS⇒abS⇒abaSbS⇒ababS⇒abab.
S⇒aSbS⇒abSaSbS⇒abaSbS⇒ababS⇒abab.
The inner two-letter strings ab and ba each have only their direct production with both S children empty. Consequently there are precisely two trees, not merely at least two. Distinct trees with the same terminal yield prove ambiguity.

Original paper, page 10