GATE / CS ARCHIVE

GATE CSE 2000 / QUESTION 19(a)

Parse unusual arithmetic precedence

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

GATE 2000, Q19(a) Descriptive
Report issue

Parsing & Syntax Analysis

Question 19(a), GATE 2000: Grammar/SDTS: E→E1*T {E.val=E1.val*T.val}; E→T {E.val=T.val}; T→F−T1 {T.val=F.val−T1.val}; T→F {T.val=F.val}; F→2 {F.val=2}; F→4 {F.val=4}. Attributes are evaluated immediately after bottom-up reductions. Construct the parse tree for 4−2−4*2 and evaluate it.
Question 19(a), GATE 2000: Grammar/SDTS: E→E1*T {E.val=E1.val*T.val}; E→T {E.val=T.val}; T→F−T1 {T.val=F.val−T1.val}; T→F {T.val=F.val}; F→2 {F.val=2}; F→4 {F.val=4}. Attributes are evaluated immediately after bottom-up reductions. Construct the parse tree for 4−2−4*2 and evaluate it.
Tap to enlarge
Answer & solution

Answer: (4−(2−4))*2 = 12 (no official key was published)

Step through it (19 steps)

The grammar makes subtraction part of T and multiplication part of E. Thus subtraction binds more tightly than multiplication. Moreover T→F−T is right-recursive, so the subtraction chain groups to the right, not to the left. The annotated parse tree is:

E[12]
├── E[6]
│   └── T[6]
│       ├── F[4] → 4
│       ├── −
│       └── T[−2]
│           ├── F[2] → 2
│           ├── −
│           └── T[4]
│               └── F[4] → 4
├── *
└── T[2]
    └── F[2] → 2

Its left-to-right terminal yield is exactly 4−2−4*2. Bottom-up, the innermost T has value 4; its parent computes 2−4=−2; the next T computes 4−(−2)=6. E→T copies 6. The final right T has value 2, so the root computes 6*2=12. Ordinary arithmetic precedence would give a different result; here the supplied grammar, not familiar operator conventions, defines the grouping.

Original paper, page 9