Skip to content
Official PYQ · 2022

GATE CS 2022 Q55 — Syntax-directed Translation

Explain with AI
Consider the following grammar along with translation rules.
S→S1#T{S.val=S1.val  ∗T.val}S→T{S.val=T.val}T→T1%R{T.val=T1.val÷R.val}T→R{T.val=R.val}R→id{R.val=id.val}\begin{aligned} & S \rightarrow S_{1} \# T \qquad \{S._{\text{val}} =S_{1}. _{\text{val}} \; ^{\ast} T._{\text{val}}\}\\ & S \rightarrow T \qquad \qquad \{S._{\text{val}} = T._{\text{val}}\}\\ & T \rightarrow T_{1} \% R \qquad \{T._{\text{val}} =T_{1}._{\text{val}} ÷ R._{\text{val}}\}\\ & T \rightarrow R \qquad \qquad \{T._{\text{val}} = R._{\text{val}}\} \\ & R \rightarrow \text{id} \qquad \qquad \{R._{\text{val}} = \text{id}._{\text{val}}\} \end{aligned}
Here #\# and %\% are operators and id\text{id} is a token that represents an integer and id.val\text{id}._{\text{val}} represents the corresponding integer value. The set of non-terminals is {S, T, R, P}\{\text{S, T, R, P}\} and a subscripted non-terminal indicates an instance of the non-terminal.

Using this translation scheme, the computed value of S.valS._{\text{val}} for root of the parse tree for the expression 20#10%5#8%2%220 \# 10 \% 5 \# 8 \% 2 \% 2 is ________________.
View worked solution

Answer: 80

To find the computed value of SvalS_{\text{val}} for the expression 20#10%5#8%2%220 \# 10 \% 5 \# 8 \% 2 \% 2, we first analyze the precedence and associativity of the operators from the given grammar.

1. Operator Precedence and Associativity

  • Precedence: Since SS derives TT (S→TS \rightarrow T) and TT derives RR (T→RT \rightarrow R), the operator %\% (associated with TT) has higher precedence than the operator #\# (associated with SS).
  • Associativity:
    • The production S→S1#TS \rightarrow S_1 \# T is left-recursive, so #\# is left-associative.
    • The production T→T1%RT \rightarrow T_1 \% R is left-recursive, so %\% is left-associative.

2. Evaluation Steps

Given the expression: Expr=20#10%5#8%2%2\text{Expr} = 20 \# 10 \% 5 \# 8 \% 2 \% 2

Due to the higher precedence of %\%, we first group and evaluate the sub-expressions containing %\%.

Step 1: Evaluate the %\% sub-expressions (left-to-right)

  • First sub-expression: 10%5=10÷5=210 \% 5 = 10 \div 5 = 2
  • Second sub-expression (left-associative): 8%2%2=(8÷2)÷2=4÷2=28 \% 2 \% 2 = (8 \div 2) \div 2 = 4 \div 2 = 2

Substituting these values back into the expression gives: 20#2#220 \# 2 \# 2

Step 2: Evaluate the #\# operations (left-to-right)

  • Since #\# represents multiplication (∗*) and is left-associative: (20#2)#2=(20×2)×2=40×2=80(20 \# 2) \# 2 = (20 \times 2) \times 2 = 40 \times 2 = 80

Thus, the computed value of SvalS_{\text{val}} at the root of the parse tree is 80.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Syntax-directed Translation questions