GATE / CS ARCHIVE

SUBJECT COLLECTION

Compiler Design · Semantic Analysis & Type Checking

29 questions, newest first

GATE CSE has asked 29 questions on Semantic Analysis & Type Checking (Compiler Design) from 1992 to 2026, in 26 of the 46 papers; the most recent is in GATE CSE 2026 Set 1. In the last five years it carried 1.4 marks per 100-mark paper on average, against 0.8 since 2003. Since 2014 the questions have been 8 MCQ, 2 MSQ and 2 NAT. 7 groups of questions here are solved the same way; “One per method” keeps the newest of each.

Browse topics
2 marks · MSQ
Report issue

Two syntax-directed type declarations

Semantic Analysis & Type Checking

Question 53, GATE 2026: G1 has D→TV, T→int|float, V→V₁ id|id; G2 has D→D₁ id|T id, T→int|float. In SDD1, T.type is set by its keyword, D.type=T.type, V.type=T.type, V₁.type=V.type, and each id is entered with V.type. In SDD2, D.type comes from D₁.type or T.type and each id is entered with that child’s type. Decide A same language, B SDD2 S-attributed, C SDD1 L-attributed with only inherited attributes, D same symbol-table entries.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A, B, D

Givens and goal

G1 has D→TV, T→int|float, V→V₁ id|id; G2 has D→D₁ id|T id, T→int|float. In SDD1, T.type is set by its keyword, D.type=T.type, V.type=T.type, V₁.type=V.type, and each id is entered with V.type. In SDD2, D.type comes from D₁.type or T.type and each id is entered with that child’s type. Decide A same language, B SDD2 S-attributed, C SDD1 L-attributed with only inherited attributes, D same symbol-table entries.

Approach

Compare generated token sequences separately from how attribute values flow through each parse tree.

Step-by-step solution

1. Both grammars generate a type keyword, either int or float, followed by one or more identifier tokens. G1 builds an identifier list through V; G2 builds the same sequence by extending D. Therefore their languages are identical, establishing A.
2. In SDD2, T.type comes from a type keyword and D.type comes from a child T or D. Every attribute value flows upward from children to the left-hand-side symbol, or is a constant. All attributes are synthesized, so SDD2 is S-attributed and B is true.
3. SDD1 passes the type inherited by V down through the identifier list. But it also contains synthesized attributes, including T.type and D.type. Its inherited dependencies are L-attributed, yet the stronger wording that it contains only inherited attributes is false. Thus C is false.
4. In either definition, every identifier receives the same type supplied by the leading keyword. Thus the same identifier/type entries are recorded, establishing D. The ways in which the values flow through the parse tree differ; the resulting entries do not.

Common error: L-attributed does not mean exclusively inherited. An L-attributed definition can contain synthesized attributes as well.

Example: for the token sequence int id₁ id₂, SDD1 obtains int from T and passes it down through V to both identifiers. SDD2 first constructs the declaration for int id₁, synthesizes its type upward, and uses that type when extending the declaration with id₂. Both call put with (id₁,int) and (id₂,int). In SDD1, the existence of the inherited V.type does not erase the synthesized T.type and D.type; that is the exact overstatement in C.

Original paper, page 41 · Answer key

1 mark · MCQ
Report issue

Locating symbol-table uses beyond parsing

Semantic Analysis & Type Checking

Question 12, GATE 2025: Which claim about a compiler symbol table is false? A It tracks variable scope. B It can use a binary search tree. C It is no longer needed after parsing. D It is created during lexical analysis.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Approach: Follow identifier information through the compiler rather than treating parsing as the last compilation phase.
A symbol table maps names to attributes such as type, declaration scope and storage location. Scope checking needs those associations, so A describes a normal role. A binary search tree can support lookup and insertion by identifier name, so B is a valid implementation possibility even though hash tables are also common.
After parsing, semantic analysis still needs symbol information for declaration and type checks; later code generation may need storage and addressing attributes. Therefore C’s claim that the table is unnecessary after parsing is false, and C is the keyed answer.
D reflects the conventional introductory pipeline in which lexical analysis begins identifier entries. Real implementations may create or enrich tables at other stages, so D should not be read as a universal requirement on every compiler architecture. The decisive false claim in the intended model is C.

Original paper, page 12 · Answer key

1 mark · MCQ
Report issue

Semantic Analysis & Type Checking

Question 22, GATE 2025: Classify these syntax-directed attribute rules:
1. R→AB with B.i=R.i−1, A.i=B.i, R.i=A.i+1.
2. P→CD with P.i=C.i+D.i, D.i=C.i+2.
3. Q→EF with Q.i=E.i+F.i.
Options list the classification of rules 1,2,3 respectively:
A. [S and L], [S not L], [neither].
B. [neither], [S and L], [S and L].
C. [neither], [L not S], [S and L].
D. [S not L], [L not S], [S and L].
Here S means S-attributed and L means L-attributed.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

An S-attributed definition has only synthesized attributes: the parent obtains its values from children. An L-attributed definition additionally permits a child's inherited attributes to depend on the parent's inherited attributes and on attributes of siblings to that child's left, so a left-to-right evaluation is possible.

Rule 1 assigns attributes on both children, so it is not S-attributed. In particular A.i depends on B.i, an attribute of A's right sibling. That violates the L-attributed direction restriction. The listed dependencies also form the cycle R.i→B.i→A.i→R.i; they do not provide a straightforward acyclic evaluation. Thus rule 1 is neither.

In rule 2, P.i is synthesized, but D.i is inherited from its left sibling C. This is permitted in an L-attributed definition and disallowed in an S-attributed one. Rule 3 only synthesizes the parent's Q.i from E.i and F.i, so it is S-attributed, and every S-attributed definition is also L-attributed. The sequence is [neither], [L not S], [S and L], which is C. The letters used to name an attribute, such as i, do not determine its classification; its dependency does.

Original paper, page 19 · Answer key

2 marks · MCQ
Report issue

Evaluate an SDD including epsilon attributes

Semantic Analysis & Type Checking

Question 37, GATE 2024: An SDD uses S→DHTU with S.val equal to the sum of the four child values. D→M D1 adds 5 to D1.val, while D→ε has value −5. H→L H1 adds 50, while H→ε has value −10. T→C T1 adds 500, while T→ε has value −5. U→K has value 5. For input MMLK, find S.val. A 45; B 50; C 55; D 65.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (14 steps)

Approach: Split the input according to the grammar and evaluate synthesized attributes from each terminating production upward.
1. D consumes the two Ms: D→M D1→M M D2→M M ε. The bottom value is −5, so D1.val=5−5=0 and D.val=5+0=5.
2. H consumes the single L. Its recursive rule contributes 50, then its epsilon rule contributes −10. Hence H.val=50−10=40.
3. There is no C between L and K, so T immediately uses T→ε. This still assigns T.val=−5; generating no terminal symbols does not mean an attribute value of zero.
4. U consumes K and has U.val=5. The start rule sums the values: S.val=5+40−5+5=45.
Answer: A. The three distinct epsilon base values are part of the semantics and must be applied even when their terminal run is empty.

Original paper, page 23 · Answer key

1 mark · MSQ
Report issue

Recognize the false attribute-evaluation claims

Semantic Analysis & Type Checking

Question 29, GATE 2024: Select FALSE statements. A an attribute grammar is an SDD whose semantic functions have no side effects; B L-attributed definitions cannot always be evaluated depth first; C synthesized attributes can be evaluated during bottom-up parsing; D every L-attributed definition on an LR(1) grammar can be evaluated by bottom-up parsing.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: B, D

Approach: Check the allowed dependency direction and distinguish a completed-tree traversal from evaluation during parsing.

1. Derivation. The question asks for false statements. A is the usual side-effect-free definition of an attribute grammar. L-attributed definitions admit a left-to-right depth-first evaluation, assigning inherited attributes on entry and synthesized ones on return, so B is false. Synthesized attributes can be computed at reductions, making C true. Arbitrary inherited dependencies in an L-attributed definition need not be available at the relevant point in an LR parse, so D’s universal claim about evaluation during bottom-up parsing is false. Thus B, D. Constructing a full parse tree and doing a separate attribute-evaluation traversal is distinct from the intended parsing-time claim.

2. Explanation and checks. An L-attributed production restricts an inherited attribute of a child to information available from the parent and earlier siblings. A left-to-right depth-first traversal can therefore compute it before entering that child and compute synthesized values after returning. A bottom-up reduction naturally has child synthesized values available, but arbitrary inherited context may be required earlier than that reduction. Hence an LR(1) grammar alone does not ensure the claimed parsing-time attribute evaluation. The question asks for the false choices, not the true ones.

Original paper, page 20 · Answer key

2 marks · NAT
Report issue

Semantic Analysis & Type Checking

Question 60, GATE 2023: Syntax-directed rules: N→I#F gives N.val=I.val+F.val; I→I1 B gives I.val=2I1.val+B.val and I→B copies B.val; F→B F1 gives F.val=(B.val+F1.val)/2 and F→B gives B.val/2; B→0 or 1 takes the bit value. Evaluate 10#011 to three decimals.
Tap to enlarge
Answer & solution

Official answer: 2.374 to 2.376

Our answer: 2.375

Step through it (19 steps)

The I rules interpret the left substring as a binary integer: I(10)=2*1+0=2. Evaluate the fractional suffix from right to left: F(1)=1/2, F(11)=(1+1/2)/2=3/4, and F(011)=(0+3/4)/2=3/8. Thus N.val=2+3/8=2.375, within the official interval 2.374 to 2.376.

Teaching detail. The separator # plays the role of a binary radix point in these semantic rules, not a multiplication or concatenation operator on numbers. The left-recursive integer production multiplies the accumulated prefix by two before appending the next bit. The right-recursive fractional production halves the sum of the current bit and the suffix fraction, placing successive bits at weights 1/2,1/4,1/8. Directly, 10#011 represents 2+0/2+1/4+1/8. This corroborates the synthesized-attribute evaluation and yields an exact terminating decimal.

Original paper, page 63 · Answer key

2 marks · NAT
Report issue

Semantic Analysis & Type Checking

Question 65, GATE 2022: Translation grammar: S→S1#T gives S.val=S1.val*T.val; S→T copies T.val; T→T1%R gives T.val=T1.val/R.val; T→R copies R.val; R→id copies integer id.val. Evaluate root S.val for 20#10%5#8%2%2. The source lists an unused nonterminal P as well.
Tap to enlarge
Answer & solution

Official answer: 80

Step through it (28 steps)

The grammar gives % higher precedence than #, with both operators left-associative. Their semantic operations are division and multiplication, respectively, rather than C remainder. The three T values are 20, 10/5=2, and (8/2)/2=2. The left-associative S combination therefore gives (20*2)*2=80. The printed nonterminal list includes an unused P, but no production or calculation depends on it.

The parse groups as (20 # (10 % 5)) # ((8 % 2) % 2). The left recursion in T fixes the latter association, so its value is (8/2)/2=2 rather than 8/(2/2)=8. S’s translation multiplies the three T values: 20×2×2=80.

Original paper, page 41 · Answer key

2 marks · MCQ
Report issue

Semantic Analysis & Type Checking

Question 26, GATE 2021: A grammar and SDT are: P→D* E*; D→int ID records the identifier as int; D→bool ID records it as bool; E→E1+E2 checks E1.type=E2.type=int and sets E.type=int; E→!E1 checks E1.type=bool and sets E.type=bool; E→ID unconditionally sets E.type=int. Which claim holds? A correctly type-checks every syntactically correct program; B type-checks syntactically correct integer declarations and integer expressions; C type-checks syntactically correct boolean declarations and boolean expressions; D leads to an infinite loop.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

The ID expression action unconditionally sets its type to int instead of consulting the declarations. Consequently integer-only, properly declared expressions using + receive the intended types, but a declared boolean is still labeled int and a valid negation can be rejected. The finite semantic actions do not themselves loop. Thus B. As usual, the limited claim assumes the mentioned integer identifiers have valid declarations; the displayed action does not implement undeclared-variable checking.

Trace a valid boolean declaration/expression: bool flag; !flag. The declaration records bool, but E→ID labels flag as int; the negation action then demands bool and rejects a valid expression. Conversely int a; int b; a+b labels both operands int and passes. A corrected ID action would look up ID.lexeme in the symbol table, reject undeclared identifiers, and copy the declared type. Thus the exact defect is the unconditional int assignment, not the grammar's use of repetition.

Original paper, page 23 · Answer key

1 mark · MCQ
Report issue

Semantic Analysis & Type Checking

Question 3, GATE 2021: ANSI C program: int main(){ Integer x; return 0; }. No declaration of Integer is supplied. Which conceptual seven-phase compiler stage reports the error? A lexical analysis; B syntax analysis; C semantic analysis; D machine-dependent optimization.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C in the textbook phase model

Integer is an identifier rather than a built-in C type, and no typedef declaration introduces it. The intended seven-phase classification is an undeclared-type/name error detected by semantic analysis, C. Real C front ends can report a parse error because typedef-name classification interacts with parsing; the answer describes the conceptual phase classification rather than a guarantee about every compiler diagnostic.

Lexing can recognize Integer as a legal identifier, so its spelling is not itself a lexical error. Semantic analysis normally resolves declarations and type meanings. The conceptual answer should not be read as promising that a particular real C parser will proceed to a separately named semantic phase for this malformed declaration.

Original paper, page 56 · Answer key

2 marks · MCQ
Report issue

Semantic Analysis & Type Checking

Question 33, GATE 2020: Productions A→PQ and A→XY have inherited i and synthesized s attributes on each nonterminal. Rule 1: P.i=A.i+2; Q.i=P.i+A.i; A.s=P.s+Q.s. Rule 2: X.i=A.i+Y.s; Y.i=X.s+A.i. Which are L-attributed? A both; B only Rule 1; C only Rule 2; D neither.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Worked explanation

An inherited attribute of a child in an L-attributed definition may depend on inherited attributes of the parent and attributes of siblings to its left. In A→PQ, P has no left sibling, and its inherited value depends only on A.i. Q can use P.i because P is left of Q. Synthesized A.s is evaluated after both children return. A valid evaluation order is A.i, P.i, process P to get P.s, Q.i, process Q to get Q.s, then A.s. In A→XY, X.i needs Y.s even though Y is on X’s right, violating the restriction. Y.i’s use of X.s would be allowed by itself; it does not rescue the first dependency.

Derivation and answer

Rule1 computes each inherited attribute from the parent’s inherited attribute and, for Q, a left sibling’s attribute; the parent synthesized attribute can then combine child results. This is L-attributed. Rule2 computes X.i using right sibling Y.s, violating the left-to-right dependency restriction. Only Rule1, B.

Original paper, page 11 · Answer key

2 marks · MCQ
Report issue

Propagating declaration types

Semantic Analysis & Type Checking

Question 36, GATE 2019: For declarations use D→T L; T→int|float; L→L1 , id|id. T synthesizes the chosen type. Semantic actions include D→TL: X1.type=X2.type and L→L1,id: X3.type=X4.type. Find X1,X2,X3,X4: A (L,T,L1,L), B (T,L,L1,T), C (L,L,L1,T), D (T,L,T,L1).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

1. T reads the type keyword and synthesizes its type value: int for T→int or float for T→float. The identifier list must receive this value from its declaration context.
2. In D→T L, the value flows from sibling T to L. Therefore L.type=T.type, giving X1=L and X2=T. Reversing this assignment would try to obtain the declared type from an untyped identifier list.
3. In L→L1,id, the parent L already has an inherited type. The shorter list L1 must inherit that same type, so L1.type=L.type. Consequently X3=L1 and X4=L.
4. The last identifier also gets L.type through addType; in the base case L→id, the single identifier receives L.type. For example, int a,b passes int from T to the outer list, then to its inner list and to both identifier entries.
5. The requested tuple is (L,T,L1,L), option A. T need not appear directly in recursive list productions: its value has already been propagated into the inherited L attribute.

Original paper, page 12 · Answer key

2 marks · MCQ
Report issue

Semantic Analysis & Type Checking

Question 46, GATE 2016: A syntax-directed translation scheme has S→aA {print 1}, S→a {print 2}, A→Sb {print 3}. A bottom-up parser processes input aab. What is the output? A:1 3 2. B:2 2 3. C:2 3 1. D:syntax error.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step through it (8 steps)

Bottom-up parsing of aab first reduces the second a by S→a, printing 2. Then Sb reduces to A, printing 3. Finally aA reduces to S, printing 1. The action order is 2, 3, 1, option C.

Reduction order follows a rightmost derivation in reverse, not the textual order in which productions are listed. A valid derivation is S⇒aA⇒aSb⇒aab. Reversing those steps first collapses the second a into S, then Sb into A, then aA into S. Each semantic action is at the end of its production, so it runs at the corresponding reduction and emits 2,3,1. The successful derivation also rules out syntax error.

Original paper, page 18 · Answer key

1 mark · MCQ
Report issue

Compiler variable attributes

Semantic Analysis & Type Checking

Question 13, GATE 2010: Which compiler data structure manages information about variables and their attributes?
Options: (A) Abstract syntax tree; (B) Symbol table; (C) Semantic stack; (D) Parse table.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

A symbol table stores identifier entries and attributes such as type, scope, storage location and parameter information. An abstract syntax tree represents program structure, a parse table guides parsing, and a semantic stack supports intermediate parser actions. Therefore the data structure asked for is the symbol table, B.

For example, a declaration “int count” can create a symbol-table entry recording the name count, integer type and scope. Later uses look up that entry for type checking and storage access. The syntax tree may refer to the entry but is not itself the lookup structure; a parse table instead maps parser states/lookahead to parsing actions.

Original paper, page 3

2 marks · MCQ
Report issue

Translation scheme with nonstandard precedence

Semantic Analysis & Type Checking

Question 59, GATE 2006: A syntax-directed translation has productions:
S→ER
R→*E {print('*')} R | ε
E→F+E {print('+')} | F
F→(S) | id {print(id.value)}
Here id denotes an integer. What is printed on input 2*3+4?
Options:
(A) 2*3+4
(B) 2*+34
(C) 23*4+
(D) 234+*
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. S→ER and R→*E{print(*)}R|ε put multiplication below the expression E; E→F+E{print(+)}|F groups the addition on the right. For 2*3+4, first print 2, then parse E for 3+4, printing 3,4,+, then print * when that E finishes.

2. The output is 234+*, option D. Applying ordinary arithmetic precedence would incorrectly give 23*4+.

3. Teaching check: Semantic print actions fire at their positions in the grammar, not according to the usual arithmetic-precedence rules. The E nonterminal consumes the whole 3+4 before R’s multiplication-print action runs. The result is therefore postfix for 2*(3+4).

Original paper, page 9

2 marks · MCQ
Report issue

Translation-rule precedence

Semantic Analysis & Type Checking

Question 45, GATE 2004: Grammar and semantic rules, start E: E→E1 # T with E.value=E1.value×T.value, or E→T with E.value=T.value; T→T1 & F with T.value=T1.value+F.value, or T→F with T.value=F.value; F→num with F.value=num.value. Find the root value for 2 # 3 & 5 # 6 & 4. The addition rule is visible in GFG; GateForum instead prints multiplication for that rule as well.
Options:
(A) 200
(B) 180
(C) 160
(D) 40
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. The grammar groups & inside T, hence it has higher precedence than #. Image the T→T1 & F semantic rule is T.value=T1.value+F.value, while E→E1 # T multiplies.

2. Therefore 2 # 3 & 5 # 6 & 4 evaluates as 2×(3+5)×(6+4)=160, option C.

4. Teaching check: Precedence comes from the grammar, not the symbols’ usual meanings. T binds & before the E-level #. Thus the parse groups 3&5 and 6&4 before combining the factors with #.

Original paper, page 6

1 mark · MCQ
Report issue

Inherited attributes during bottom-up parsing

Semantic Analysis & Type Checking

Question 18, GATE 2003: In bottom-up evaluation of a syntax-directed definition, inherited attributes can: A. Always be evaluated; B. Be evaluated only if the definition is L-attributed; C. Be evaluated only if the definition has synthesized attributes; D. Never be evaluated. Discuss the usual parsing-time interpretation and its limitation.
Tap to enlarge
Your answer
Answer & solution

Answer: B under a restricted one-pass evaluation model (no official key was published)

1. A synthesized attribute flows from children to parent and is naturally evaluated when a bottom-up parser reduces a production. An inherited attribute flows from parent or siblings toward a child and may be needed before that child is reduced. Therefore identify which dependency schedule the question permits before selecting an option.

2. Inherited attributes cannot in general be computed by the simple reduce-only mechanism used for synthesized attributes. In the usual left-to-right one-pass implementation, usable inherited information must be available from the parent context and already processed left siblings, the L-attributed dependency condition behind B. Even then suitable scheduling/marker productions or stack access may be needed; being L-attributed is not a blanket guarantee for every unmodified LR evaluation scheme. If bottom-up evaluation instead allows building a full parse/dependency graph and later scheduling arbitrary acyclic dependencies, L-attributedness is not necessary. The choice therefore depends on the conventional parsing-time model, which the prompt does not spell out.

Original paper, page 2

2 marks · MCQ
Report issue

Output order of embedded translation actions

Semantic Analysis & Type Checking

Question 58, GATE 2003: A translation scheme is S→TR; R→+ T {print('+');} R | ε; T→num {print(num.val);}. Token num represents an integer, and num.val is its value. For input 9+5+2, what is printed?
A. 9+5+2
B. 95+2+
C. 952++
D. ++952
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Step through it (19 steps)

1. Expand S→TR. The initial T consumes 9 and immediately prints 9.
2. The first R consumes + and invokes T on 5, printing 5. Its following action prints + before the recursive R begins.
3. That recursive R consumes +, invokes T on 2 and prints 2, then prints +. Its final R chooses ε and prints nothing.
4. Concatenating the actions yields 9,5,+,2,+, or 95+2+, B. Moving the plus action to after the recursive R would change the result, but that is not this scheme.

Solution: The initial T prints 9. Each R expansion reads +, processes T (which prints the next number), prints +, and only then processes the remaining R. Hence the execution order is 9,5,+,2,+, yielding 95+2+, option B. The action is before the recursive R, so it does not postpone both plus signs to the end.

Original paper, page 8

Descriptive
Report issue

Translate repeat-until statements

Semantic Analysis & Type Checking

Question 17, GATE 2001: S→repeat S1 until E. S1.code is body code; E.code computes a Boolean into E.varName (1=true,0=false). newlabel() returns a fresh label; gen(s) emits a code line.
Question 17, GATE 2001: S→repeat S1 until E. S1.code is body code; E.code computes a Boolean into E.varName (1=true,0=false). newlabel() returns a fresh label; gen(s) emits a code line.
Tap to enlarge
Answer & solution

Answer: S.code = gen(L+":") || S1.code || E.code || gen("if "+E.varName+" == 0 goto "+L), where L=newlabel(). (no official key was published)

Associate the production with this semantic rule:

L = newlabel();
S.code = gen(L + ":")
         || S1.code
         || E.code
         || gen("if " + E.varName + " == 0 goto " + L);

Here || denotes concatenation of generated code strings, not Boolean OR. The resulting three-address layout is:

L:
    [body code]
    [compute E into t]
    if t == 0 goto L
    [next statement]

The body is before the condition so it runs at least once. A false result repeats; a true result falls through. E.code must be inside the loop because the condition is recomputed after every iteration. A fresh label for each production application avoids collisions when repeats are nested. No explicit exit label is necessary because the successful path falls through.

Original paper, page 9

Descriptive
Report issue

Synthesize reduction-count attributes

Semantic Analysis & Type Checking

Question 19(b), 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. Add synthesized attributes to compute E.red, the total reductions without changing the grammar.
Question 19(b), 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. Add synthesized attributes to compute E.red, the total reductions without changing the grammar.
Question 19(b), 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. Add synthesized attributes to compute E.red, the total reductions without changing the grammar.
Tap to enlarge
Answer & solution

Answer: Each production adds 1 to the sum of its nonterminal children’s red attributes; the given input has E.red=10. (no official key was published)

Every nonterminal node in a parse tree represents one use of a grammar production, hence one reduction in a bottom-up parse. A terminal contributes no reduction by itself; F→2 or F→4 contributes one. Preserve all original val actions and append:

E → E1 * T : E.red = E1.red + T.red + 1
E → T      : E.red = T.red + 1
T → F − T1 : T.red = F.red + T1.red + 1
T → F      : T.red = F.red + 1
F → 2      : F.red = 1
F → 4      : F.red = 1

These are synthesized because each left-hand attribute depends only on child attributes. No global counter or inherited attribute is needed. In 4−2−4*2, there are four F reductions, four T reductions (two T→F and two T→F−T), and two E reductions (E→T and E→E*T), totaling 10. One bottom-up production sequence is F→4, F→2, F→4, T→F, T→F−T, T→F−T, E→T, F→2, T→F, E→E*T, understood as reductions from right-hand sides to left-hand sides. Parser accept is not an additional grammar reduction, and any augmented start rule is outside the question’s requested reduction to E.

Original paper, page 9

5 marks · Descriptive
Report issue

Synthesized attributes for binary fractions

Semantic Analysis & Type Checking

Question 9, GATE 1999: Assign synthesized attributes to evaluate a binary numeral, exemplified by 101.101=5.625. The reproduced grammar is damaged: GateForum prints “S → LL\L; L → LB\B; B → 0\1”, with no radix point; GFG has conventional alternative bars but an unclear/missing radix-point glyph. Conditional intended grammar used below: S→L.L | L; L→LB | B; B→0 | 1. Write semantic rules for every production.
Tap to enlarge
Shared context

Assign synthesized attributes to evaluate a binary numeral, exemplified by 101.101=5.625. Conditional intended grammar used below: S→L.L | L; L→LB | B; B→0 | 1. Write semantic rules for every production.

Answer & solution

Answer: For S→L₁.L₂, use S.val=L₁.val+L₂.val/2^(L₂.len); synthesize L.val and L.len. (no official key was published)

a radix-point production is required to parse the supplied fractional example. The following is an explicitly stated reconstruction consistent with that example, not a claim that an official original was verified. If the production is literally S→LL with no point terminal, the grammar does not parse 101.101 at all and is ambiguous about splitting an unmarked bit string.

Use synthesized attributes L.val (the bit string interpreted as an unsigned integer) and L.len (its number of bits). Let B.val be the numeric value of one bit. Distinguish repeated L occurrences by subscripts:

S → L₁ . L₂ : S.val := L₁.val + L₂.val / 2^(L₂.len)
S → L        : S.val := L.val
L → L₁ B     : L.val := 2*L₁.val + B.val; L.len := L₁.len + 1
L → B        : L.val := B.val; L.len := 1
B → 0        : B.val := 0
B → 1        : B.val := 1

Appending a bit shifts the existing integer one binary place left, hence multiplication by two. The fractional substring represents its integer value divided by 2 raised to its length; this also handles leading zeros correctly. All right-hand sides depend only on child attributes, so the definition is S-attributed.

For 101, successive (val,len) pairs are (1,1),(2,2),(5,3). Both L occurrences in 101.101 therefore have (5,3), and S.val=5+5/8=5.625. For 0.001, the fractional attributes (1,3) give 1/8 rather than 1/2, showing why the length attribute is essential.

Original paper, page 7

1 mark · MCQ
Report issue

Where type checking occurs

Semantic Analysis & Type Checking

Question 1.27, GATE 1998: Choose lexical analysis, syntax analysis, syntax-directed translation, or code optimization as the normal type-checking mechanism.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Lexical analysis identifies tokens, and parsing checks grammatical structure. Type checking instead propagates and compares semantic attributes: for example, an addition node checks operand types and computes the result type. Syntax-directed definitions or translation rules attach exactly these operations to grammar productions, making C the appropriate option. Optimization can use type information but is not the normal first stage responsible for establishing semantic type compatibility.

Original paper, page 3

5 marks · Descriptive
Report issue

Fractional binary attributes

Semantic Analysis & Type Checking

Question 23, GATE 1998: Give synthesized semantic rules for S→L.L|L; L→LB|B; B→0|1, with 101.101=5.625. The dot is visible in the GateForum raster but faint/lost in some extraction.
Tap to enlarge
Answer & solution

Answer: Use integer value and length attributes for the supplied fractional grammar. (no official key was published)

This production parses the fractional example; replacing it by dotless S→LL would describe a different grammar.

Use L.val for the integer represented by its bit string and L.len for its number of bits. All attributes are synthesized:
S→L1 . L2: S.val=L1.val+L2.val/2L2.len
S→L: S.val=L.val
L→L1 B: L.val=2*L1.val+B.val; L.len=L1.len+1
L→B: L.val=B.val; L.len=1
B→0: B.val=0
B→1: B.val=1

Appending a bit shifts the prior number left by one, hence multiplication by two. A fractional bit string of length k represents its integer value divided by 2k. For each 101, (val,len) grows (1,1),(2,2),(5,3); S.val=5+5/8=5.625. The length attribute is necessary: .001 and .1 have the same integer value 1 but represent 1/8 and 1/2 respectively. Every semantic expression uses only child attributes, meeting the synthesized-only requirement. Original official wording has not been established by these secondary copies.

Original paper, page 8

5 marks · Descriptive
Report issue

Typed postfix syntax-directed translation

Semantic Analysis & Type Checking

Question 23, GATE 1997: The grammar is assign-stmt→LHS := E; E→E+T | T; T→T*V | V; V→id | (E); LHS→id. Variables have integer or real types. Convert expressions and assignments to postfix using typed tokens (+,i), (+,r), (*,i), (*,r), (:=,i), (:=,r). give-type(id) and give-name(id) return an identifier's type and name. Give a syntax-directed translation scheme. Mixed-type conversion and narrowing policies are not stated in the source.
Question 23, GATE 1997: The grammar is assign-stmt→LHS := E; E→E+T | T; T→T*V | V; V→id | (E); LHS→id. Variables have integer or real types. Convert expressions and assignments to postfix using typed tokens (+,i), (+,r), (*,i), (*,r), (:=,i), (:=,r). give-type(id) and give-name(id) return an identifier's type and name. Give a syntax-directed translation scheme. Mixed-type conversion and narrowing policies are not stated in the source.
Tap to enlarge
Answer & solution

Answer: Synthesize type and postfix code; choose numeric promotion for each operator, emit left operand then right operand then typed operator, and check assignment compatibility. (no official key was published)

Use synthesized attributes X.type and X.code for E,T,V; use LHS.type and LHS.name for the assignment target. A code value is a token list, and || denotes concatenation. Identifier type is i or r. The following semantic actions specify the traversal without depending on a particular parser implementation.

V→id:       V.type=give-type(id); V.code=[give-name(id)]
V→(E):      V.type=E.type; V.code=E.code
T→V:        T.type=V.type; T.code=V.code
E→T:        E.type=T.type; E.code=T.code
LHS→id:     LHS.type=give-type(id); LHS.name=give-name(id)

For E→E1+T, let t=join(E1.type,T.type), where join(i,i)=i and every other numeric pair gives r. Set E.type=t and E.code=E1.code || T.code || [(+,t)]. For T→T1*V, set t=join(T1.type,V.type), T.type=t and T.code=T1.code || V.code || [(*,t)]. Subscripting E1 and T1 distinguishes the right-hand-side occurrence from the left-hand-side occurrence of the same nonterminal.

For assign-stmt→LHS:=E, check that the expression can be assigned to the destination. Emit [address(LHS.name)] || E.code || [(:=,LHS.type)]. Writing the LHS first follows the conventional postfix assignment form x y (:=,i); the assignment operator consumes the target address and the computed value. In a textual postfix language the name in that first position can denote its address implicitly.

A necessary semantic convention: with precisely the six listed typed operator tokens, the r arithmetic operators must accept integer operands by implicit widening, and (:=,r) must widen an integer value when needed. Under that convention the rules above handle mixed expressions. For integer x,y and real z, the translation of z:=x+y*z is z x y z (*,r) (+,r) (:=,r). Multiplication is emitted first, preserving the grammar's precedence. A real-to-integer assignment is rejected unless an explicit narrowing rule has been authorized.

If the target instead requires both operands already to have the operator's physical type, implicit widening is unavailable. Then replace operand code c by c||[i2r] whenever its integer result is consumed as real, and similarly before assignment to a real target. This alternative introduces an extra conversion token not supplied in the question. Homogeneous expressions need no such extension. Type tags alone do not define a real-to-integer rounding rule or a machine-level cast. Keeping these conventions explicit avoids silently inventing conversion behavior while still giving a complete translation scheme for the stated operator alphabet.

Original paper, page 9

5 marks · Descriptive
Report issue

Postfix translation by reduction actions

Semantic Analysis & Type Checking

Question 20, GATE 1996: Use the SDTS E→E+E {print “+”}, E→E*E {print “.”}, E→id {print id.name}, E→(E) {no action}. An LR parser executes a production's action immediately after reducing by it. Draw the parse tree and give the translation of (a+b)*(c+d).
Tap to enlarge
Answer & solution

Answer: Literal output ab+cd+. (final dot is emitted); root multiplication with two parenthesized addition subtrees. (no official key was published)

The root production is E→E*E. Its left E derives (E), whose inner E derives E+E with identifier leaves a and b. Its right E derives (E), whose inner E derives E+E with identifier leaves c and d. Thus a textual description of the full parse tree is E(E('(',E(E(id a),'+',E(id b)),')'), '*', E('(',E(E(id c),'+',E(id d)),')')). Parentheses are terminal children of their E→(E) nodes, not emitted characters.

Actions run on reduction, after the right-hand-side subexpressions have been recognized. Reducing id a prints a, reducing id b prints b, and reducing their addition prints +. The parenthesized left operand therefore emits a b +. The E→(E) reduction emits nothing. Similarly the right operand emits c d +. Only after both operand E nodes exist can the root multiplication reduce and print the dot specified by its action.

The literal complete output is a b + c d + ., or ab+cd+. when concatenated without separators. The final dot is an emitted multiplication token, not sentence punctuation. It is postfix notation: each operation follows its operands. As a check, a postfix evaluator pushes a and b, combines them by +, pushes c and d, combines them by +, then multiplies the two resulting values. The grammar is ambiguous in general for unparenthesized mixed operators, but these explicit parentheses fix the intended tree for this particular sentence. Conventional postfix ab+cd+* expresses the same multiplication, but it is not the exact string emitted by the printed SDTS and must not replace it silently.

Original paper, page 9

2 marks · MCQ
Report issue

Reduction-time translation

Semantic Analysis & Type Checking

Question 2.10, GATE 1995: Grammar S→xxW {print1}, S→y {print2}, W→Sz {print3}. What is printed by a shift-reduce parse of xxxxyzz?
Tap to enlarge
Your answer
Answer & solution

Answer: A: 23131 (no official key was published)

Step through it (14 steps)

The innermost y reduces to S first, printing 2. That S followed by z reduces to W, printing 3. The preceding xx and this W reduce to S, printing 1. The remaining outer z then permits W→Sz, printing another 3, and the remaining outer xxW reduces to S, printing the last 1. Thus the output is 23131. Actions occur after reductions, giving inside-out order rather than the order of productions in a top-down derivation.

Original paper, page 4

Report issue

A context-sensitive language check

Semantic Analysis & Type Checking

Question 1.18, GATE 1994: Which feature cannot generally be enforced by a CFG alone: if-then-else syntax, recursive-procedure syntax, declaration before variable use, or arbitrary-length variable names?
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

A CFG can describe nested statements, recursive syntactic structures and identifier shapes of unbounded length. Checking that a particular identifier was previously declared requires matching that name against the declarations valid in its scope, not merely recognizing a syntactic category. Compilers therefore use symbol tables and semantic analysis for this context-sensitive condition. The claim concerns unrestricted identifiers and general programs; a finite fixed universe could be encoded into a much larger grammar, but that is not the usual language model.

Original paper, page 2

Report issue

FORTRAN mixed arithmetic and integer assignment

Semantic Analysis & Type Checking

Question 2.5, GATE 1993: For X=4.0, evaluate integer I assigned −2**2+(5.0*X)/(X*3)+3/4, following the displayed fraction grouping.
Tap to enlarge
Answer & solution

Answer: −2 (no official key was published)

Exponentiation binds before unary negation, so −2**2 is −4, not +4. The middle term is real arithmetic: 20.0/12.0=5/3. The literal operands in 3/4 are integers, so FORTRAN integer division gives zero. The resulting real value is −4+5/3=−7/3. Assignment to integer I truncates toward zero, yielding −2. The printed source uses two-dimensional fractions rather than literal FORTRAN source; the grouping in the paraphrase is stated explicitly so a flattened division/multiplication expression is not silently substituted.

Original paper, page 2

2 marks · MSQ
Report issue

Nil pointer dereference

Semantic Analysis & Type Checking

Question 7.5, GATE 1993: Pascal allocates ptr, assigns ptr:=nil, then attempts ptr^.d:=5.2 and prints the reproduced text write ln(ptr). Which error claims are justified?
Tap to enlarge
Select all that apply
Answer & solution

Answer: B, D (runtime nil dereference); as printed, A (compile-time error) also applies (no official key was published)

After new(ptr), assigning nil discards the usable pointer. Dereferencing ptr^ then attempts to access a nonexistent record, so a checked execution reports nil-pointer dereference rather than printing 5.2. This supports the intended runtime-error and nil-error choices B,D. Those issues can cause compile-time rejection before runtime. No claim that the literal program necessarily reaches the dereference is made.

Original paper, page 7

Descriptive
Report issue

Type assignment with end-only semantic actions

Semantic Analysis & Type Checking

Question 11(a), GATE 1992: Add syntax-directed semantic rules to the ends of productions, without changing the grammar, so each identifier gets its declared type in the symbol table:
D → T L ;
T → int | real
L → L , id | id
Tap to enlarge
Answer & solution

Answer: Collect identifier-entry references in synthesized L.entries; assign T.type to them at D → T L ;. (no official key was published)

A synthesized list of symbol-table references solves the end-only restriction without needing to pass an inherited type into L before parsing it. Give T a synthesized attribute type and L a synthesized attribute entries. The lexical token id.entry is a reference to that identifier's symbol-table entry (or the declaration entry created for it in the current scope).

Attach precisely these actions at production ends:
D → T L ; { for each p in L.entries: p.type := T.type }
T → int { T.type := integer }
T → real { T.type := real }
L₀ → L₁ , id { L₀.entries := append(L₁.entries, id.entry) }
L → id { L.entries := [id.entry] }

The subscripts distinguish the two occurrences of L; they are attribute notation, not new grammar symbols. append constructs or extends a list of references, not copies of symbol-table records. On reduction of L → id, the one-element list is available. Each reduction of the recursive production adds one further identifier. By induction on the list length, the final L.entries contains exactly the identifiers in this declaration. At the D reduction both T.type and the complete list are available, so every listed entry receives the same type.

For real x,y,z;, T.type becomes real, the L lists successively become [x], [x,y], [x,y,z], and the final action assigns real to x, y, and z. All actions are at the right ends, and the original productions are untouched. Redeclaration detection and nested-scope lookup are separate symbol-table concerns. With a tail pointer or linked-list concatenation, building and processing a k-identifier list costs O(k) time and O(k) references.

Original paper, page 8