Back to the 2026 paper

Module 3: Semantic Analysis, Symbol Table, Run-time environment

20267m

Consider the following grammar:
E→E+T∣TE \to E + T \mid T
T→T∗F∣FT \to T * F \mid F
F→digitF \to \text{digit}
Define suitable synthesized attributes to evaluate an arithmetic expression. Construct the annotated syntax tree and evaluate the following expression:
3+5∗23 + 5 * 2

Worked SolutionAI Assisted

Grammar: E→E+T∣TE \to E + T \mid T,   T→T∗F∣F\;T \to T * F \mid F,   F→digit\;F \to \text{digit}

Synthesized attribute: give every non-terminal EE, TT, FF an attribute val (its numeric value). The terminal digit has the attribute lexval supplied by the lexical analyzer.

Syntax-directed definition

Production Semantic rule
E→E1+TE \to E_1 + T E.val=E1.val+T.valE.val = E_1.val + T.val
E→TE \to T E.val=T.valE.val = T.val
T→T1∗FT \to T_1 * F T.val=T1.val×F.valT.val = T_1.val \times F.val
T→FT \to F T.val=F.valT.val = F.val
F→digitF \to \text{digit} F.val=digit.lexvalF.val = \text{digit}.lexval

Every attribute is computed from the attributes of the children, so val is synthesized and the definition is S-attributed (it can be evaluated during bottom-up parsing).

Annotated parse tree for 3+5∗23 + 5 * 2

Because of the grammar's structure, * sits lower in the tree than +, so 5 * 2 is evaluated first.

MermaidDiagram
Rendering diagram…

Evaluation (bottom-up, post-order)

Step Node Rule used Value
1 FF (digit 3) F.val=digit.lexvalF.val = \text{digit}.lexval 3
2 TT over that FF T.val=F.valT.val = F.val 3
3 EE over that TT E.val=T.valE.val = T.val 3
4 FF (digit 5) F.val=digit.lexvalF.val = \text{digit}.lexval 5
5 TT over that FF T.val=F.valT.val = F.val 5
6 FF (digit 2) F.val=digit.lexvalF.val = \text{digit}.lexval 2
7 T→T∗FT \to T * F T.val=5×2T.val = 5 \times 2 10
8 E→E+TE \to E + T E.val=3+10E.val = 3 + 10 13
3+5∗2=13\boxed{3 + 5 * 2 = 13}

Similar questions

AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.