Compiler Design
105601Module 3: Semantic Analysis, Symbol Table, Run-time environment
Q1c. A shift reduce parser carries out the actions specified within braces immediately after reducing with the corresponding rule of grammar: S \to xxW {print "1"}, S \to y {print "2"}, S \to Sz {print "3"} What is the translation of xxxxyzz using the syntax directed translation scheme described by the above rules? (i) 23131 (ii) 11233 (iii) 11231 (iv) 3321120232m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →A shift reduce parser carries out the actions specified within braces immediately after reducing with the corresponding rule of grammar:
{print "1"}, {print "2"}, {print "3"}
What is the translation of using the syntax directed translation scheme described by the above rules?
(i) 23131
(ii) 11233
(iii) 11231
(iv) 33211Worked SolutionAnswer: (iii) 11231
Reasoning (shift–reduce with actions executed on reduce)
Grammar:
Input string:
x x x x y z z.Reducing the string from the input up to (the actions fire in the order the reductions are performed):
Step Stack contents (top right) Action Printed 1 x xcollected,W → … yreduce xxW → S1 2 next x x+ …reduce xxW → S1 3 yreduce y → S2 4 S+zreduce Sz → S3 5 S+zthen top combinereduce (top-level xxW/final)1 Collecting the prints in the order the reductions happen:
Hence the correct choice is (iii).
Q1e. Consider a symbol table implemented using hashing with table size 10. For key 27, using h(k) = k \bmod 10, the initial position is: (i) 5 (ii) 7 (iii) 6 (iv) 820262m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →Consider a symbol table implemented using hashing with table size . For key , using , the initial position is:
(i)
(ii)
(iii)
(iv)Worked SolutionAnswer: (ii) 7
Calculation
because . The key is initially placed at index of the hash table.
Note: if slot is already occupied (a collision, e.g. key ), it is resolved by chaining (linked list at slot 7) or open addressing (linear probing to slot 8, 9, ...).
Q1f. Under static scoping, the meaning of a variable reference is determined primarily by: (i) Runtime call sequence (ii) CPU register contents (iii) Heap location (iv) Lexical program structure20262m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →Under static scoping, the meaning of a variable reference is determined primarily by:
(i) Runtime call sequence
(ii) CPU register contents
(iii) Heap location
(iv) Lexical program structureWorked SolutionAnswer: (iv) Lexical program structure
Explanation
In static (lexical) scoping, a variable reference is bound to the declaration found by looking at the textual nesting of blocks/procedures in the source code: first the innermost enclosing block, then the next one outward, and so on.
- The binding can be decided at compile time, without running the program.
- The call sequence at run time (option i) decides the binding only in dynamic scoping.
- Registers (ii) and heap location (iii) have nothing to do with name resolution.
int x = 10; void f() { printf("%d", x); } // x refers to the global x void g() { int x = 20; f(); } // still prints 10 under static scopingQ1h. Synthesized attributed are calculated (i) From the values of attributes of the children of the node (ii) From the values of attributes of the parent of the node (iii) From the values of attributes of the siblings of the node (iv) None of these20232m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →Synthesized attributed are calculated
(i) From the values of attributes of the children of the node
(ii) From the values of attributes of the parent of the node
(iii) From the values of attributes of the siblings of the node
(iv) None of theseWorked SolutionAnswer: (iii) children of the node (option (i))
Explanation
Attributes in a syntax-directed definition are classified by the direction of their dependency:
Synthesized attribute (S-attribute): computed from the attribute values of the children of a node. Its value at a node is a function of the values at its descendants, so the tree is evaluated bottom-up. A classic example is
E.val = E1.val * T.val.Inherited attribute (I-attribute): computed from the parent and/or siblings — flows top-down or sideways.
Since the question is about synthesized attributes, they are calculated:
Q2b. What is an activation record? Explain how they are used to access various local and global variables.20237m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →What is an activation record? Explain how they are used to access various local and global variables.
Worked SolutionWhat is an activation record? How are local/global variables accessed?
Activation record (AR) — also called a stack frame — is a block of memory pushed onto the run-time stack for each call of a procedure/function. It holds everything needed to return from the call and to run the callee. When the procedure returns, its record is popped (unless it is kept for certain closures).
Typical layout (higher addresses → lower):
[ actual parameters ] [ return value (if any) ] [ access link / control link (saved frame pointer) ] [ return address (saved PC) ] [ saved machine status ] [ local data (locals, temporaries) ] [ saved top-of-stack pointer ]Accessing local variables:
- While a procedure is active, the runtime keeps a base pointer (frame pointer) that names the bottom of the current AR.
- Every local variable is stored at a fixed offset from the start of the AR, an offset chosen at compile time.
- So
xis accessed asbase + offset(x)— no runtime search: justload [base+off].
Accessing global (non-local) variables:
- Globals live in a global/static data area (not on the stack in most compilers). Each global has a fixed compile-time address/offset from a global base register/area, so access is again just an absolute/relative memory load.
- Some compilers (old Pascal-style) used an access link/display to reach enclosing non-locals: each frame holds a pointer to the frame of the statically enclosing procedure; accessing a nonlocal of depth follows links. (Dynamic scoping instead uses a dynamic link up the call chain.)
Example (C):
int g = 10; /* global */ int f(int p) { int l; l = g + p; return l; }At run time while inside
f:pandlare atFP + offset_pandFP + offset_l(local, in the AR).gis at its fixed global-area address (single load).
Conclusion
- Locals → offsets within the current activation record on the run-time stack (
FP + offset). - Globals → fixed addresses in a global data region, known at compile time.
Q4a. Given the Syntax-Directed Definition below with the synthesized attribute val. Draw the annotated parse tree for the expression (3+4) * (5+6) L \to E, L.val = E.val E \to T, E.val = T.val E \to E_1 + T, E.val = E_1.val + T.val T \to F, T.val = F.val T \to T_1 * F, T.val = T_1.val * F.val F \to (E), F.val = E.val F \to digit, F.val = digit.lexval20237m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →Given the Syntax-Directed Definition below with the synthesized attribute val. Draw the annotated parse tree for the expression
,
,
,
,
,
,
,Worked SolutionAnnotated parse tree for
Syntax-directed definition (synthesized
val):- ,
- ,
- ,
- ,
- ,
- ,
- ,
Parse tree with every node's
valannotated (evaluated bottom-up):L ─ E.val = 77 (L → E, L.val = E.val) | E.val = 77 (E → T, E.val = T.val) | T.val = 77 (T → T1 * F, T.val = 7 * 11) / \ T1.val = 7 F.val = 11 | | F.val = 7 F → ( E ) .val = 11 F → ( E ) .val=7 | | E → E1 + T .val = 5 + 6 = 11 E.val = 7 / \ E1.val = 3 T.val = 3 ? ... (details below)To avoid a confusing drawing, here is the node-by-node annotated tree (the expected exam answer):
L → E : val = 77 E → T : val = 77 T → T1 * F : val = T1.val * F.val = 7 * 11 = 77 Left subtree (3+4): T1 → F : val = 7 F → (E) : val = 7 [parenthesized] E → E1 + T E1 → T → F → digit(3) : val = 3 T → F → digit(4) : val = 4 E.val = 3 + 4 = 7 ⇒ T1 (left factor) val = 7 Right subtree (5+6): F → ( E ) : val = 11 [parenthesized] E → E1 + T E1 → T → F → digit(5) : val = 5 T → F → digit(6) : val = 6 E.val = 5 + 6 = 11 ⇒ F (right factor) val = 11 Root: T.val = 7 * 11 = 77, E.val = 77, L.val = 77Each digit is a leaf via , with (3, 4, 5, 6).
Q5a. Explain the structure of an activation record and its role during procedure execution.20267m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →Explain the structure of an activation record and its role during procedure execution.
Worked SolutionActivation record (stack frame)
An activation record is the block of memory pushed on the run-time stack each time a procedure is called. It holds everything one activation of the procedure needs. Records are pushed on a call and popped on return, so the stack mirrors the chain of active calls.
Structure of an activation record
SVGVector Architecture Diagram (SVG)Field Purpose Returned value Space where the callee stores its result for the caller Actual parameters Arguments supplied by the caller Control (dynamic) link Points to the caller's activation record, so the stack can be unwound on return Access (static) link Points to the record of the lexically enclosing procedure, used to reach non-local variables Saved machine status Return address and the register contents of the caller, restored on return Local variables Data declared inside the procedure Temporaries Intermediate values of expression evaluation Role during procedure execution
- Call sequence. The caller evaluates and stores the actual parameters and the return address; the callee saves registers, sets the frame pointer
fp, and allocates space for locals and temporaries. - Execution. Local variables are accessed at a fixed offset from
fp. Non-local variables are reached by following access links (static scope) the required number of levels, then adding the offset. Global variables live in static memory with a fixed address. - Return sequence. The callee stores the return value, restores the saved registers and
fp, pops its record, and jumps to the return address. - Recursion. Every call gets its own record, so each recursive activation has its own copy of locals and parameters.
Accessing variables: for a local
xuse[fp + offset_x]. For a non-localydeclared nesting levels up, follow the access link times to that procedure's record, then use[record + offset_y].- Call sequence. The caller evaluates and stores the actual parameters and the return address; the callee saves registers, sets the frame pointer
Q5b. Explain how type checking and error reporting are performed in compiler. Draw syntax tree and DAG for the statement: a = (a * b + c) \uparrow (b + c) * b + c20237m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →Explain how type checking and error reporting are performed in compiler. Draw syntax tree and DAG for the statement:
Worked SolutionType checking, error reporting, and the syntax tree / DAG for
Part 1 — Type checking
- Type checking verifies each operator's operands have the expected type and computes/infers the result type while traversing the syntax tree.
- It is typically performed in the semantic-analysis phase using a syntax-directed definition where each expression node carries a synthesized
typeattribute, e.g. for . - Type synthesis:
int + int → int,float op … → float; conversions (e.g.int → float) may be inserted automatically as a unary nodeinttofloat(type coercion). - Checking can be static (compile time) or dynamic (run time).
Part 2 — Error reporting
- Each phase reports its errors to a central error handler: lexical (illegal token), syntactic (parse errors, e.g. mismatched brackets), semantic (type mismatch, undeclared/unused variable).
- The parser uses error-recovery strategies (panic mode, error productions, phrase-level recovery) so it can report more than one syntax error in a single run.
- Semantic errors are reported with line number, offending token, and message; code generation is attempted only when there are no fatal errors.
Part 3 — Syntax tree for the statement
a = (a*b + c) ↑ (b + c)*b + cPrecedence order:
↑>*>+. So the RHS reads as:Syntax tree (AST):
= / \ a + / \ ↑ c / \ (a*b + c) ( (b+c) * b ) / \ / \ (a*b) + c (b+c) b / \ / \ a b b c Equivalently, using operator-labelled nodes: = / \ a + / \ (↑) c / \ (a*b+c) * (mul) | / \ (a*b)+c (b+c) b / \ / \ (a*b) c b c / \ a bDAG (Directed Acyclic Graph)
In the DAG, each unique subexpression appears exactly once; repeated uses share the same node.
The statement contains these distinct nodes (reading bottom-up):
a*b— node*with leaves (a, b)(a*b)+c— node+over (1) and leaf cb+c— node+with leaves (b, c)(b+c)*b— node*over (3) and leaf b↑— node↑over (2) and (4)RHS + c— node+over (5) and leaf ca = RHS— node=with leaves (a, 6)
= / \ a + ← (6) / \ ↑ c / \ (a*b)+c (b+c)*b ← nodes (2), (4) / \ / \ (a*b) c (b+c) b ← nodes (1), (3) / \ / \ a b b cNote the leaf
bandcare each single nodes shared by all their uses (this is what makes it a DAG rather than a tree).Q5b. Discuss the structure of a symbol table and the information stored for each identifier.20267m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →Discuss the structure of a symbol table and the information stored for each identifier.
Worked SolutionSymbol table
A symbol table is a data structure used by the compiler to store information about every identifier (variables, constants, functions, labels, types, parameters) found in the source program. It is created during lexical/syntax analysis and used by every later phase.
Structure
Each entry is a record, and the table is organized for fast lookup and insertion.
MermaidDiagramRendering diagram…Common organizations:
Implementation Lookup Remarks Unordered linear list Simple, only for tiny programs Ordered list / binary search tree Slower insertion Hash table average Most common; collisions resolved by chaining Handling scope: one table per scope, chained to its enclosing scope (or a single stack-like table). Entering a block creates a new table; leaving it discards that table. Lookup searches the innermost scope first, then outwards.
Operations:
insert(name, attributes),lookup(name),delete/ exit scope,modify attributes.Information stored for each identifier
Attribute Meaning Name The lexeme (or an index into a string table) Kind / category Variable, constant, function, procedure, parameter, label, type name Data type int, float, char, array, struct, pointer, ... Size Bytes needed (for arrays: element type and dimensions/bounds) Scope / nesting level Block or procedure where the name is visible Storage location Address or offset in the activation record (or static address) For functions Number, order and types of parameters, return type, parameter-passing mode For records/classes Fields, their types and offsets Line numbers Declaration and usage lines, for error messages and cross-reference Other flags Initialized or not, constant value, access mode Example: for
float rate;declared inmain, the entry is<rate, variable, float, 4 bytes, level 1, offset 8>.Use by the phases: the scanner inserts names, the parser and semantic analyzer add type and scope information and check for undeclared or redeclared names, type checking reads types, and the code generator reads sizes and offsets.
Q7a. Differentiate between S-attribute SDT and L-attribute SDT with suitable examples.20237m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →Differentiate between S-attribute SDT and L-attribute SDT with suitable examples.
Worked SolutionS-attribute SDT vs L-attribute SDT
S-Attribute (Synthesized) SDTs
- An SDT is S-attributed ("synthesized") if every attribute is a synthesized attribute — computed from the children of a nonterminal.
- All the evaluation is bottom-up.
- An S-attributed SDT can be evaluated during a bottom-up parse — the semantic action is placed at the right end of the production:
A → α { do action }. - Supported: only bottom-up based LL/LR? Precisely: LR parser can implement any S-attributed SDD without changing the parsing stack (just attach the attributes value with each stack symbol).
L-Attributed SDTs
- An SDT is L-attributed when:
- each attribute is either synthesized, or inherited, and
- inherited attributes depend only on: attributes of the left siblings, the parent, and attributes of the symbols themselves (i.e. dependencies can flow from left to right, and from parent → children).
- Condition: In the production , an inherited attribute of can only depend on:
- attributes of (the symbols to its left), and
- inherited attributes of (the parent).
- Evaluation is basically top-down / left-to-right — works with LL / predictive parsers too, and can be implemented in a top-down or LR parser with suitable actions.
Key differences:
Point S-attributed L-attributed Attributes All synthesized synthesized + inherited (with L- constraint) Evaluation pass bottom–up depth-first left-to-right following structure Parser suitable any LR / bottom-up LL / top-down (recursive-descent; LR also if aug.) Action placement can move to the end of RHS must keep in position (actions constrained) Which is larger — L is a superset of S Every S-attributed definition is also L-attributed, but not vice versa.
Example
S-attribute example: grammar with
val
All attributes synthesized ⇒ S-attributed (also L).L-attribute (non-S) example: an inherited attribute such as in a
Cfloatconversion
For instance, declaring arrays:D → T L,L → id , L_1;L.inh = T.type; L1.inh = L.inh. The inherited attributeinhmust always be computed before the symbol is parsed — that's the left-to-right constraint.Summary: an S-SDT = simply synthesized attributes; evaluate bottom-up. L-SDT = a wider class, allows inherited attributes under the restriction that they use only attributes from the left (or inherited from context above) — evaluated in a depth-first left-first traversal. Since L is a superset of S, any S-scheme is a special case of L.
- Install PocketlyBudget App•POCKETLY
Pocketly on Android
Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.
Q8b. Consider the following grammar: E \to E + T \mid T T \to T * F \mid F F \to \text{digit} Define suitable synthesized attributes to evaluate an arithmetic expression. Construct the annotated syntax tree and evaluate the following expression: 3 + 5 * 220267m
Module 3: Semantic Analysis, Symbol Table, Run-time environment
View this question on its own page →Consider the following grammar:
Define suitable synthesized attributes to evaluate an arithmetic expression. Construct the annotated syntax tree and evaluate the following expression:Worked SolutionGrammar: , ,
Synthesized attribute: give every non-terminal , , an attribute
val(its numeric value). The terminaldigithas the attributelexvalsupplied by the lexical analyzer.Syntax-directed definition
Production Semantic rule Every attribute is computed from the attributes of the children, so
valis synthesized and the definition is S-attributed (it can be evaluated during bottom-up parsing).Annotated parse tree for
Because of the grammar's structure,
*sits lower in the tree than+, so5 * 2is evaluated first.MermaidDiagramRendering diagram…Evaluation (bottom-up, post-order)
Step Node Rule used Value 1 (digit 3) 3 2 over that 3 3 over that 3 4 (digit 5) 5 5 over that 5 6 (digit 2) 2 7 10 8 13