IAE Academy

GATE 2022 CS Q.65: solution and answer

GATE 2022 · CSQ.65 · 2 marks · NAT

Consider the following grammar along with translation rules.





Here # and % are operators and is a token that represents an integer and represents the corresponding integer value. The set of non-terminals is and a subscripted non-terminal indicates an instance of the non-terminal.

Using this translation scheme, the computed value of for root of the parse tree for the expression 20#10%5#8%2%2 is ______.

See the question in the paper

Answer and solution

ANSWER

The computed value of at the root is .

Official answer: 80Source: Official answer key, GATE 2022 CS (IIT Kharagpur)

  1. The grammar is left-recursive in both and , so both # and % are left-associative. % is generated inside , which sits below , so % binds tighter than #.

  2. Group the input by #: .

  3. First is with , so .

  4. Second uses : .

  5. Third is left-associative, so it is .

  6. is left-recursive, so .

  7. Hence .

KEY IDEA

The grammar fixes the parse. A left-recursive rule makes its operator left-associative, and an operator generated lower in the grammar ( in ) binds tighter than one generated higher up ( in ). Parse the string first, then evaluate each node bottom-up.

WATCH OUT FOR

Using the usual meaning of # and %, or evaluating strictly left to right. That computes here by coincidence, but the operations are not in that order. Another slip is grouping as instead of .

From the GATE 2022 CS paper. Every question of this paper · Download the full paper · All 7 Syntax-directed translation questions, with notes

More Syntax-directed translation questions