Question

Consider the following grammar (that admits a series of declarations, followed by expressions) and the associated syntax directed translation (SDT) actions, given as pseudo-code:

P→D∗EP \rightarrow D^* E
D→int ID{record that ID.lexeme is of type int}D \rightarrow \text{int } ID \quad \{\text{record that } ID.\text{lexeme is of type int}\}
D→bool ID{record that ID.lexeme is of type bool}D \rightarrow \text{bool } ID \quad \{\text{record that } ID.\text{lexeme is of type bool}\}
E→E1+E2{check that E1.type=E2.type=int; set E.type:=int}E \rightarrow E_1 + E_2 \quad \{\text{check that } E_1.\text{type} = E_2.\text{type} = \text{int}; \text{ set } E.\text{type} := \text{int}\}
E→!E1{check that E1.type=bool; set E.type:=bool}E \rightarrow !E_1 \quad \{\text{check that } E_1.\text{type} = \text{bool}; \text{ set } E.\text{type} := \text{bool}\}
E→ID{set E.type:=int}E \rightarrow ID \quad \{\text{set } E.\text{type} := \text{int}\}

With respect to the above grammar, which one of the following choices is correct?

Choose one option
Official answer and solution
Official answer
B
From
Official GATE 2021 answer key

Solution

Trace how type attributes are assigned and verified for integer versus boolean identifiers.

Inspect the semantic rule associated with the identifier production E→IDE \rightarrow ID:

{set E.type:=int}\{ \text{set } E.\text{type} := \text{int} \}

Notice that this action unconditionally assigns E.type=intE.\text{type} = \text{int} to any variable reference, without looking up the declared type of IDID in the symbol table.

If a boolean variable bb is declared (bool b;) and subsequently used in an expression such as !b, the rule E→IDE \rightarrow ID sets E.type:=intE.\text{type} := \text{int}. Then the rule E→!E1E \rightarrow !E_1 checks whether E1.type==boolE_1.\text{type} == \text{bool}, which fails because E1.typeE_1.\text{type} was forced to int! Thus boolean expressions cannot be correctly type-checked.

However, for integer variable declarations (int a, c;) and expressions (a + c), E→IDE \rightarrow ID sets E.type:=intE.\text{type} := \text{int}, and E→E1+E2E \rightarrow E_1 + E_2 correctly checks E1.type=E2.type=intE_1.\text{type} = E_2.\text{type} = \text{int}. Thus, the actions can correctly type-check syntactically correct integer declarations and integer expressions (option B).

Final answer

B

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2021 Computer Science and Information Technology (CS, Set-1)
Question
36 of 65, printed as CS Q.26
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.