GATE / CS ARCHIVE

GATE CSE 1992 / QUESTION 11(a)

Type assignment with end-only semantic actions

Compiler Design · Semantic Analysis & Type Checking · Full GATE CSE 1992 paper

GATE 1992, Q11(a) Descriptive
Report issue

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