GATE CS 2024 Set 1 — Question 37

MCQ+2 / -0.67MediumSyntax-Directed TranslationSemantic AnalysisCompiler Design

Compiler Design → Semantic Analysis → Syntax-Directed Translation

Last updated

Question

Consider the following syntax-directed definition (SDD).
ProductionSemantic Rules
S → DHTU{S.val=D.val+H.val+T.val+U.val;}\{ S.val = D.val + H.val + T.val + U.val; \}
D"M"D1D \to \text{"M"}D_1{D.val=5+D1.val;}\{ D.val = 5 + D_1.val; \}
DϵD \to \epsilon{D.val=5;}\{ D.val = -5; \}
H"L"H1H \to \text{"L"}H_1{H.val=510+H1.val;}\{ H.val = 5 * 10 + H_1.val; \}
HϵH \to \epsilon{H.val=10;}\{ H.val = -10; \}
T"C"T1T \to \text{"C"}T_1{T.val=5100+T1.val;}\{ T.val = 5 * 100 + T_1.val; \}
TϵT \to \epsilon{T.val=5;}\{ T.val = -5; \}
U"K"U \to \text{"K"}{U.val=5;}\{ U.val = 5; \}
Given "MMLK" as the input, which one of the following options is the CORRECT value computed by the SDD (in the attribute S.valS.val)?
A.
45
B.
50
C.
55
D.
65

Correct answer

(A) 45

Solution

To find the value of S.valS.val for the input string "MMLK", we first construct the parse tree based on the given grammar productions.
1. Parsing the Input "MMLK":
The start symbol is SS, and the production is S → DHTU.
We need to match the input string "MMLK" to the components D,H,T,UD, H, T, U.
  • Match DD: The prefix "MM" matches the expansion of DD.
  • D"M"D1D \to \text{"M"}D_1
  • D1"M"D2D_1 \to \text{"M"}D_2
  • D2ϵD_2 \to \epsilon (since the next character is 'L', which belongs to HH)
  • Match HH: The next character "L" matches the expansion of HH.
  • H"L"H1H \to \text{"L"}H_1
  • H1ϵH_1 \to \epsilon (since the next character is 'K', and TT must be skipped)
  • Match TT: There are no 'C' characters. The next character is 'K', which belongs to UU. Thus, TT must derive ϵ\epsilon.
  • TϵT \to \epsilon
  • Match UU: The character "K" matches UU.
  • U"K"U \to \text{"K"}
2. Computing Attributes (Bottom-Up):
Now we compute the values using the semantic rules.
  • For DD:
  • D2ϵ    D2.val=5D_2 \to \epsilon \implies D_2.val = -5
  • D1"M"D2    D1.val=5+D2.val=5+(5)=0D_1 \to \text{"M"}D_2 \implies D_1.val = 5 + D_2.val = 5 + (-5) = 0
  • D"M"D1    D.val=5+D1.val=5+0=5D \to \text{"M"}D_1 \implies D.val = 5 + D_1.val = 5 + 0 = 5
  • For HH:
  • H1ϵ    H1.val=10H_1 \to \epsilon \implies H_1.val = -10
  • H"L"H1    H.val=510+H1.val=50+(10)=40H \to \text{"L"}H_1 \implies H.val = 5 * 10 + H_1.val = 50 + (-10) = 40
  • For TT:
  • Tϵ    T.val=5T \to \epsilon \implies T.val = -5
  • For UU:
  • U"K"    U.val=5U \to \text{"K"} \implies U.val = 5
  • For SS:
  • SDHTU    S.val=D.val+H.val+T.val+U.valS \to DHTU \implies S.val = D.val + H.val + T.val + U.val
  • S.val=5+40+(5)+5S.val = 5 + 40 + (-5) + 5
  • S.val=45S.val = 45
Thus, the correct value is 45.

More questions on Semantic Analysis

Practice GATE CS PYQs with adaptive difficulty

Timed practice, skill tracking, and AI explanations — free to start.

Start practicing free