GATE / CS ARCHIVE

GATE CSE 2002 / QUESTION 22(c)

An unambiguous LALR(1) expression grammar

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

GATE 2002, Q22(c) Descriptive
Report issue

Parsing & Syntax Analysis

Question 22(c), GATE 2002: Grammar E→E+E | E*E | id. Original22(c): Modify the grammar to obtain exactly one parse tree per string in the same language and a nonambiguous LALR(1) grammar.
Question 22(c), GATE 2002: Grammar E→E+E | E*E | id. Original22(c): Modify the grammar to obtain exactly one parse tree per string in the same language and a nonambiguous LALR(1) grammar.
Question 22(c), GATE 2002: Grammar E→E+E | E*E | id. Original22(c): Modify the grammar to obtain exactly one parse tree per string in the same language and a nonambiguous LALR(1) grammar.
Tap to enlarge
Answer & solution

Answer: E→E+T | T; T→T*F | F; F→id. (no official key was published)

One replacement grammar is

E → E + T | T
T → T * F | F
F → id
It accepts exactly the original token language id ((+|*) id)*, without introducing parentheses or changing which token strings are allowed. The E/T levels make * bind more tightly than +, and the left-recursive productions make repeated uses of either operator associate left. Thus i+j*k has only the i+(j*k) parse. This standard expression grammar is SLR(1), and hence LALR(1); separating the levels resolves the shift/reduce ambiguity. The original grammar specified no precedence, so multiplication-before-addition and left associativity are a legitimate choice of an unambiguous interpretation, not properties already forced by that grammar.

Original paper, page 10