GATE / CS ARCHIVE

GATE CSE 2002 / QUESTION 22(a)

All parse trees for i+j*k in an ambiguous grammar

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

GATE 2002, Q22(a) Descriptive
Report issue

Parsing & Syntax Analysis

Question 22(a), GATE 2002: Grammar E→E+E | E*E | id. Original22(a): Construct all parse trees for i+j*k, where i,j,k are identifiers.
Question 22(a), GATE 2002: Grammar E→E+E | E*E | id. Original22(a): Construct all parse trees for i+j*k, where i,j,k are identifiers.
Question 22(a), GATE 2002: Grammar E→E+E | E*E | id. Original22(a): Construct all parse trees for i+j*k, where i,j,k are identifiers.
Tap to enlarge
Answer & solution

Answer: Two parse trees: +(i,*(j,k)) and *(+(i,j),k), with E→id at every identifier leaf. (no official key was published)

With productions E→E+E, E→E*E, E→id, the two full parse trees are:

Tree 1, root addition:
E
├── E
│   └── id(i)
├── +
└── E
    ├── E
    │   └── id(j)
    ├── *
    └── E
        └── id(k)

Tree 2, root multiplication

E
├── E
│   ├── E
│   │   └── id(i)
│   ├── +
│   └── E
│       └── id(j)
├── *
└── E
    └── id(k)

Here id(i), id(j), and id(k) denote the id tokens with those lexemes. Both yields are i + j * k. There are exactly two trees because the root split must be at one of the two operators, and each remaining two-identifier subtree has a unique possible split. Their grouping is i+(j*k) versus (i+j)*k.

Original paper, page 10