EXAM PREP · PCC-CS501

Compiler Design — Unit-wise Solved Answers

Exam-grade, unit-wise model answers for the MAKAUT 70-mark pattern — compiler phases, lexical analysis, predictive/SLR/LR(1) parsing, syntax-directed translation, type checking, storage allocation, quadruples/triples, and code optimization — worked out in full detail.

Module 1 Questions

Exam Note ★ Compilers vs interpreters, the six phases of compilation, and error-classification examples are Group A staples — write them with named examples, not just definitions. ★
1
Describe the functions and roles of a compiler with examples of syntax error, semantic error, run-time error, and run-time logical error. What are the phases of compilation? What are the major tasks of a compiler?

A compiler is a program that reads a program written in a high-level source language (e.g. C, C++) and translates it into an equivalent program in a low-level target language (assembly or machine code) that can be loaded and executed. Its role is to give the programmer the convenience and clarity of the high-level language while giving the machine the efficiency of the target code. Unlike an interpreter, which executes the source line by line, a compiler produces a self-contained object program that can later be run many times without the source or the compiler being present.

Error Classes — with Examples

ErrorMeaningExample
Syntax errorViolation of the grammatical structure of the language; detected by the parser before code generation.if (x = 5) print x in strict mode, a missing semicolon int x = 5, an unmatched parenthesis sum = (a + b.
Semantic errorSyntax is correct but the statement is meaningless in context; detected by semantic analysis / type checking.adding two incompatible types "abc" + 5 in C, using a variable before declaring it, passing a string where an integer is expected.
Run-time errorCorrect code that fails only during execution because of bad input or environment.division by zero 10/0, stack overflow, array index out of bounds a[10] when the array has 5 elements, NullReferenceException.
Run-time logical errorProgram runs "correctly" but produces wrong results because of a flaw in the algorithm — no message is issued.looping to i < n instead of i <= n giving one less term; writing * where / was intended: area = 2 * 3.14 * r is fine, but area = 2 * 3.14 / r is silently wrong.

Logical errors are the hardest to find because the program does not crash — the result is simply wrong.

Phases of Compilation

 Source program ──► Lexical analysis ──► Syntax analysis ──► Semantic analysis
        │                  (scans, builds        (parses, builds        (type checks,
        │                   tokens)               syntax tree)            meaning checks)
        ▼
  ... ──► Intermediate-code generation ──► Code optimization ──► Code generation
                                                                     │
                                                                     ▼
                                                              object program
  1. Lexical analysis (scanning): reads characters, groups them into tokens (identifiers, keywords, operators, numbers), and drops whitespace and comments. Token examples: if, x, =, 5.
  2. Syntax analysis (parsing): groups tokens according to the grammar of the language and builds a syntax/parse tree; detects missing commas, unmatched parentheses.
  3. Semantic analysis: verifies that constructs make sense — type checking, symbol-table maintenance, scope rules.
  4. Intermediate-code generation: converts the syntax tree into a machine-independent intermediate representation (three-address code, quadruples/triples, a DAG).
  5. Code optimization: transforms the intermediate code to make the target program run faster and use less memory, without changing its meaning.
  6. Code generation: emits target-machine code; allocates registers; maps memory references.

In addition, the symbol table and error detection/recovery machinery run throughout every phase.

Major Tasks of a Compiler

  • Error detection and reporting: catch syntax, semantic, and where possible run-time errors; print clear messages with line numbers.
  • Code generation: translate source into efficient object code for the target machine.
  • Optimization: produce faster, smaller code — peep-hole, global and interprocedural optimizations.
  • Debugging aids: generate debugging information, trace files.
  • Runtime support: provide routines the generated code calls — function-call activation records, malloc-style allocation, I/O.
2
How does a compiler handle run-time errors? What are the responsibilities of the compiler? What are the phases of compilation? What are the two major functions of a compiler? What is the meaning of 'semantic' in a compiler? Why are lexical analysis, syntax analysis, semantic analysis, and syntactic code generation divided into separate phases? How many passes are in a compiler?

Handling Run-Time Errors

Most run-time errors (array bounds, divide-by-zero, heap overflow) cannot be detected at compile time, so the compiler inserts run-time checks into the generated code. For an array reference a[i] the compiler emits a test if (i < 0 || i >= n) trap error before the reference (bounds checking, which can be switched off for speed). For division it may emit a divide-by-zero test. It also generates exception-handling code (try/catch frames), provides run-time library routines the generated code calls, and produces a core-dump / trace facility and debugging info (symbol tables, DWHARF) so that when an error occurs the user can be told the program name, line number, and the offending expression. Some compilers (e.g. Ada, and -ftrapv-style C) make these checks mandatory.

Responsibilities of the Compiler

  • Translate source code into a target program (code generation).
  • Detect and report errors clearly (line number, error kind, suggested fix).
  • Optimize code to improve speed and size.
  • Provide runtime support routines and debugging aids.
  • Manage the symbol table and allocate storage.

Phases of Compilation

(1) Lexical analysis — tokens; (2) Syntax analysis — parse tree; (3) Semantic analysis — meaning/type checks; (4) Intermediate code generation; (5) Code optimization; (6) Code generation. The symbol table and error handling run alongside all phases.

The Two Major Functions

The two major functions of a compiler are: (1) error detection and reporting — finding mistakes the programmer made and explaining them, and (2) code generation — producing an efficient, correct object program equivalent to the source (with optimization as its sub-task).

Meaning of "Semantic"

Semantics is the meaning of a program — what it actually computes — as opposed to syntax, which is its grammatical form. A statement like a = b + 100 may be syntactically perfect but semantically wrong if a is a string and b an integer: the shapes fit, the meanings do not. Semantic analysis is the phase that enforces that all operations are of the right kinds (type checking), that identifiers are declared and used within scope, and that constraints (e.g. non-negative loop bounds in some languages) are respected.

Why Separate Phases?

  • Simplicity & modularity: each phase does one clearly defined job; phases can be designed, tested, and written separately, and recombined for different languages or targets.
  • Correctness: dividing the work makes it easier to prove each phase correct and to localize bugs.
  • Speed: simple, well-structured phases run faster; scanning tokenizes once so later phases need not re-read raw characters.
  • Portability: the lexer, parser, and intermediate code can be reused unchanged for new target machines; only code generation changes.
  • Single-pass performance: although divided conceptually, phases can be run in one pass through the source, so the division costs no extra input read.

How Many Passes?

A one-pass compiler performs all phases while scanning the source once — most modern compilers (C, Pascal) are one-pass because rereading the source is slow. A multi-pass compiler reads the source two or more times (e.g. FORTRAN 77 needed a first pass to collect declaration information and a second to generate code; two-pass assemblers resolve forward labels). The number of passes is about how many times the input is read; the phases are about the logical divisions of work — one pass can execute every phase.

Module 2 Questions

Exam Note ★ Grammars, FIRST/FOLLOW, and Thompson's construction are heavily tested — practise building the syntax tree and converting the RE (a+b)*a(b+a)b to a DFA as shown in Q6. ★
1
What is a grammar? How do we use a grammar? What is a sentential form? What is a derivation? What are the components of a formal grammar? What is a CFG (context-free grammar)? What are the phases of a parser?

A grammar is a finite set of rules (productions) that generate every sentence in a language; formally it is the tuple G = (V, T, P, S) where V is the set of variables (nonterminals), T the terminal symbols, P the productions, and S the start symbol. A grammar "generates" a language: the language L(G) is exactly the set of strings of terminals it can derive.

Using a Grammar

A grammar is used two ways: (1) Generation — starting from S and applying productions repeatedly to build valid sentences (e.g. from S → aSb | ε we generate aabb); and (2) Recognition/parsing — given a string, deciding whether it belongs to the language by finding a derivation (this is what the syntax analyzer does, usually working backwards from the string to S).

Sentential Form & Derivation

A sentential form is any string of terminals and nonterminals that can be derived from the start symbol S. Example: with S → aAb, A → b, the string aAb is a sentential form (it still contains the nonterminal A). A derivation is the sequence of steps in which nonterminals are replaced by production bodies. A derivation ending only in terminals is a parse. If the leftmost nonterminal is replaced at every step the derivation is leftmost (used by top-down parsers); if the rightmost one is replaced, it is rightmost (used by bottom-up parsers); a rightmost derivation read in reverse is called the canonical (LR) form.

Components of a Formal Grammar

ComponentNameExample
VVariables / nonterminalsS, A, B
TTerminalsa, b, ;, +, if
PProductions (α → β)S → if ( id = expr ) S
SStart symbol (S ∈ V)S

Grammars are classified as Type-0 (unrestricted), Type-1 (context-sensitive), Type-2 (context-free), Type-3 (regular) in the Chomsky hierarchy.

Context-Free Grammar (CFG)

A CFG is a grammar in which the left side of every production is a single nonterminal — the replacement never depends on the symbols surrounding it (no "context"). Example: S → aSa | ε generates the language of odd-length strings of a's and b's centered on b, and arithmetic grammars E → E + T | T (plus precedence levels) are CFGs. Programming-language structures like statements and blocks are generated by CFGs, which is why parsing programming languages is context-free parsing.

Phases of a Parser

A parser's work unfolds in these stages: (1) input tokenization — it consumes tokens from the lexical analyzer; (2) top of stack management — it maintains a stack of grammar symbols (sentential forms in progress) and, in shift-reduce form, keeps track of the viable prefix; (3) decision-making — using the parse table (or a hand-coded prediction routine), it chooses an action: shift a token, reduce a handle to a nonterminal, accept, or report error; (4) action execution — applying the chosen rule; and (5) tree/output building — constructing the parse tree (or evaluating semantic actions in syntax-directed translation) and eventually signalling acceptance.

2
What is syntax analysis? What is the need for syntax analysis? What is a top-down parser? What are the two parsing techniques of top-down parsers? What are the characteristics of top-down parsers? What is a bottom-up parser?

Syntax analysis (parsing) is the second major phase of a compiler: it takes the stream of tokens produced by the lexical analyzer, checks that the sequence conforms to the grammatical rules (the grammar) of the language, and organizes the token structure into a hierarchy — the parse (syntax) tree — that shows how the input sentence is built from the productions.

Need for Syntax Analysis

  • Validates that the program is grammatically well-formed before expensive later phases run.
  • Produces the structural representation (parse tree or an equivalent) that semantic analysis and code generation need.
  • Localizes syntax errors and supports error recovery so one small mistake does not abort compilation.

Top-Down Parsing

A top-down parser starts at the start symbol S and works downward, choosing productions until it reaches a sequence of terminals that matches the input — i.e. it builds a leftmost derivation. While scanning the input left to right, it tries to match productions: when a nonterminal is about to be replaced it must decide which alternative to use, guided by the next input symbols.

The Two Top-Down Techniques

TechniqueIdea
Recursive descentOne procedure per nonterminal; each procedure tries to recognize that nonterminal's productions. The set of procedures recursively calls one another and mirrors the grammar. Simple to write; used in many modern compilers (lex/yacc alternatives, ANTLR, LL grammars).
LL(1) table-driven (predictive) parsingUses a prediction table indexed by (nonterminal, next terminal) to pick the correct production without backtracking; a single driver routine + table replaces the recursive procedures.

(A naive top-down parser may backtrack — try one production, fail, undo, try another — but backtracking is exponential in the worst case, which is exactly why LL(1)/table-driven parsing was developed.)

Characteristics of Top-Down Parsers

  • Start from S and grow down the parse tree to the input (leftmost derivation).
  • Decisions depend on looking ahead at input symbols; LL(1) needs one token of lookahead.
  • Fail unless the grammar has been rewritten to remove left recursion (infinite-loop hazard) and factored to remove the need to look further ahead than k symbols.
  • Easy to debug for recursive descent (call stack = parse stack); table-driven variants need a construction phase.

Bottom-Up Parsing

A bottom-up parser works from the input toward S: it scans tokens left to right, pushes them on a stack, and repeatedly replaces the rightmost substring that matches a production's right-hand side — a handle — with the production's left-hand side, until only S remains. This is essentially the reverse of a rightmost derivation, and it is the canonical form. Because the decision can often be delayed until a handle is definitely identified, bottom-up parsers can handle a strictly larger class of grammars (e.g. grammars ambiguous to LL(1), left-recursive grammars) with the same linear-time guarantee. The principal bottom-up family is the LR parsers (SLR, LALR, canonical LR), driven by shift-reduce transitions in a state machine.

3
Explain lexical analysis. What is lexical analysis? What is its function? What are the tasks of a lexical analyzer? What are the advantages of a lexical analyzer?

Lexical analysis (scanning) is the first phase of a compiler. It reads the source program character by character, groups the characters into the smallest meaningful units called tokens, and hands the token stream to the syntax analyzer. Whitespace and comments are skipped (unless they carry meaning), and each token is associated with its attribute — e.g. the identifier count gets a lexeme (the string "count") and a semantic value (the offset into the symbol table).

Function of Lexical Analysis

Its function is to reduce the problem size for the parser: the parser deals with a small alphabet of token types (id, num, op, keyword) instead of the raw character alphabet, and with lines of code instead of thousands of characters. A program containing 100 identifiers still has only one token type id, and the parser never sees a second whitespace or the letters of an identifier.

Tasks of the Lexical Analyzer

  • Collect characters into lexemes (words of the language).
  • Classify each lexeme into its token type and attach the attribute value (symbol-table offset for ids, numeric value for constants).
  • Strip blanks, tabs, newlines and comments.
  • Maintain a line/column count so the error handler can report "line 14, column 9: undefined variable x".
  • Generate a token stream for the syntax analyzer, and report lexical errors (illegal character, unterminated string literal, integer overflow).
  • In some designs, do macro expansion or keyword recognition.

Input-Buffer Structure (Classic Two-Pointer Scheme)

  buffer:  [ x  +  5  /  y  #  1 ]        (source text)
                ^           ^
              (1)         (2)
   (1) = lookahead pointer · (2) = current pointer
   The scanner reads until the current pointer is the last
   legal character. To avoid slowing down at the buffer's edge,
   it copies the next line of input to the far end of the buffer
   and sets a flag "buffer-full". When (2) reaches the tail, the
   tail is discarded, the front re-read, (1) and (2) advanced one
   line — the input is "rolled".

Two pointers plus a buffer full of source is all the lexer needs; no whole-program copy is ever required.

Advantages of a Separate Lexical Analyzer

  • Correctness: separating the phases makes each module easier to write and prove correct.
  • Performance: tokenizing characters is cheaper than parsing them; the parser receives a small token stream, and scanning a line at a time keeps memory usage bounded.
  • Portability: a single scanner is reusable across different languages/targets, and a single parser is reusable across different scanners.
  • Modularity: the scanner can be implemented automatically from regular expressions (lex/lex) independently of the grammar-driven parser (yacc/yacc).
  • Simplifies error reporting — every error gets a line/column number the lexer already tracks.
4
Write the rules and limitations of left recursion, left factoring, and ambiguity. Why are they problems for syntax analysis? What is a regular expression? Write its use?

Left Recursion

A grammar is left-recursive when a nonterminal can derive a sentential form whose leftmost symbol is itself, e.g. E → E + T | T (E generates E + ...). Rule to remove: for A → Aα | β, replace with A → βA′, A′ → αA′ | ε; for A → Aα1 | Aα2 | β1 | β2, use A → β1A′ | β2A′, A′ → α1A′ | α2A′ | ε. Limitation: a top-down/recursive-descent parser enters parse E, sees E again immediately, recurses infinitely, and the stack overflows. Left-recursive CFGs cannot be parsed without first removing the recursion.

Left Factoring

A grammar is left-factored when two alternatives of the same nonterminal begin with the same string of symbols, e.g. stmt → if id = expr . | if . — from the start symbol both alternatives start with if, so a one-symbol lookahead cannot decide which to take. Rule: factor the common prefix into its own nonterminal: stmt → if id = expr . | if . becomes stmt → stmt′ ... in general A → β A₁′ | β A₂′, A′ → A₁″ | A₂″. Limitation: LL(1) (and generally top-down LL(k)) parsers fail because the FIRST sets of the two alternatives overlap; the prediction table has a conflict. Left-factoring removes the common prefix so the decision can be made later.

Ambiguity

A grammar is ambiguous when some string has two or more distinct parse trees (two distinct leftmost or rightmost derivations). Example: stmt → if cond then stmt | if cond then stmt else stmt with if c1 then if c2 then s1 else s2 — the else can attach to the outer if or the inner one, two different trees. Rule of thumb: ambiguity is a property of the grammar, not of the string; to make a language unambiguous, rewrite the grammar so each construct has one parse shape (add a rule, or use a dangling else resolution — "else binds to the closest unmatched if"). Limitation: if the grammar is ambiguous, a table-driven parser will produce a table with multiple actions in one cell (shift/reduce or reduce/reduce conflict), and no LL(1) table exists. Resolution strategies: precedence rules, restrict the grammar, or use a non-ambiguous grammar.

Why They Are Problems for Syntax Analysis

ProblemWhat breaksFix
Left recursionInfinite loop in top-down (recursive-descent) parsing; LL prediction tables cannot be constructed.Remove left recursion; parse it bottom-up (SLR/LR) which handles left-recursive grammars naturally.
Left factoringTwo production alternatives have overlapping FIRST sets; the LL(1) parser cannot decide in one symbol.Factor the common prefix into its own nonterminal.
AmbiguityA grammar has multiple parse trees; the table has a conflict; the compiler does not know which meaning to implement.Rewrite the grammar to be unambiguous; use precedence or "close else to the last if" rules.

Regular Expressions

A regular expression (RE) is a compact pattern notation over an alphabet that describes a class of strings (a regular language): the building blocks are single characters (a), concatenation ab, union (a | b), closure a*, a+, a?. Uses:

  • Define the tokens of a language: id = letter (letter|digit)*, num = digit+ ("." digit+)?.
  • Build lexical analyzers: lex/yacc compile REs into DFAs.
  • Pattern matching: search, validation (email, phone numbers, ISBN).
  • Simplify compiler design: instead of writing explicit character-level code, describe the token by its RE and let the tool generate the scanner.
5
How do you convert a regular expression to a lexical analyzer? Explain the 3 techniques. What is the structure of the input buffer?

A lexical analyzer's job is to match the current input string against each token's pattern. A regular expression such as id = letter (letter | digit)* describes a regular language. To turn a set of REs into a working scanner, we build an automaton (NFA/DFA) that recognizes the set and then drive it over the input. Three classical techniques:

Technique 1 — Regular-Expression-to-NFA Conversion (Thompson's Construction)

Each RE has an equivalent Nondeterministic Finite Automaton (NFA). The construction is recursive:

RENFA built
aOne state, one edge a to the next state.
εEdge ε from the start state directly to the accept state.
r | sNew start splits with ε edges to both r's and s's starts; both accepts ε-merge to one new accept.
rsConcatenate: the accept of r is also the start of s; new accept = accept of s.
r*Split to r with ε; ε edge from r's accept back to r's start and to the new accept.

The resulting NFA may have ε-transitions. In ε-closure we close under ε-moves and get the DFA-equivalent behavior. An NFA with n states takes O(n) space but is O(n) to simulate (ε-closure per step).

Technique 2 — NFA-to-DFA Conversion (Subset Construction / Power Set)

Each DFA state is a subset of NFA states: DFA δ(A, a) = ε-closure(move(∪ A, a)). The start DFA state is ε-closure(NFA start). Build the DFA states on demand. This converts any NFA to a minimal-ish DFA (no ε-moves, deterministic). Cost: DFA can have up to 2ⁿ states; a DFA with k states costs one transition lookup per input character.

Technique 3 — Direct Regex-to-DFA (Regular-Expression Minimization / Simultaneous Scanning)

Instead of the two-step NFA→DFA pipeline, some tools (e.g. lex) optimize the RE set directly: they build an NFA per RE, unify the starts and accepts, do ε-closure, then minimize to a DFA with a single start and a "longest-match" acceptance rule (for a set of patterns the DFA goes to the accept state that matches the longest prefix). This gives a single deterministic state machine that is the fastest possible — O(1) lookup per character in a state table. The DFA is stored as a two-dimensional array next[state][character].

Structure of the Input Buffer

The lexer reads the source through a bounded input buffer, not by holding the whole program in memory. The classic structure is a two-pointer buffer:

  ┌─────────────────────────────────────────────┐
  │  x  +  5  /  y  #  1  2  3 ...  (next line) │
  └─────────────────────────────────────────────┘
      ↑                    ↑
      (1) lookahead        (2) current
  (1) scans ahead for pattern match; (2) marks
  the last character that belongs to the current lexeme.
  When (2) reaches the end of the buffer, the "buffer-full"
  flag is set: the scanner copies the next line onto the
  buffer's tail, advances both pointers one character, and
  resets the flag. Two pointers + a flag; O(1) work per token.
6
What is Thompson's construction? Explain with an example. Consider the regular expression (a+b)* a (b+a)b. a) Generate the expression and construct the syntax tree of the above regular expression. b) Find FIRST(L) and LAST() for every internal node in the syntax tree. c) Find FOLLOW() for every node in the syntax tree. d) Construct the corresponding DFA for the given RE using FOLLOW().

Thompson's Construction

Thompson's construction (Ken Thompson, 1968) is a mechanical algorithm that converts any regular expression into an equivalent NFA with ε-transitions by structural induction on the RE. The key rule: each subexpression has exactly one new start state and one new accept state, and the three operations are built by adding ε edges only: r | s adds a split at the front and a merge at the back; rs glues the accept of r to the start of s with an ε edge; r* adds ε edges that skip and loop. The NFA may be nondeterministic, but it accepts exactly the language of the original RE, and it has at most 2 × |regex length| states.

(a) Syntax Tree of (a+b)* a (b+a)b

By operator precedence (union | is lowest, closure * next, concatenation highest) the tree is:

                          (*)
                       /      \
                    (+)        a
                    / \
                   a    b
                          \
                          b
                      (left branch: concat a with (b+a)b)
                    +
                    |
                (+)
                 / \
                b    a

Reading back: the root is (a+b) *, then a (concat), then (b+a) (union), then b (concat). So the whole RE is (a+b)* a (b+a)b. The tree has 7 internal nodes (4 unions/closures and 3 concatenations, counting leaves a and b as internal).

(b) FIRST(L) and LAST() for Every Internal Node

First(node) = the set of characters that can appear as the first character of a string generated from that node. Last(node) = the set of characters that can appear as the last character.

NodeExpressionFirstLast
N1(a+b){a, b}{a, b}
N2(a+b)*{ε, a, b}{ε, a, b}
N3a{a}{a}
N4(b+a){b, a}{b, a}
N5b{b}{b}
N6 (concat: N2·N3)(a+b)* a{ε, a, b}{a}
N7 (concat: N6·N4·N5)whole RE{ε, a, b}{b}

(c) FOLLOW() for Every Node

In parser theory, FOLLOW(X) = the set of terminals that can legally appear immediately to the right of a nonterminal/leaf X in any valid sentence. For a leaf node in a syntax tree the FOLLOW set is the set of symbols that can come right after that occurrence:

  • FOLLOW(N1: a+b) → {ε} (N1 is the root of the sub-tree in N2; it is closed under *, so N1 can be followed by ε, or by anything that follows N2).
  • FOLLOW(N2: (a+b)*) → {a} (the next symbol in the whole tree after the star is the literal a in N3).
  • FOLLOW(N3: a) → {b, a} (the next is the union b+a).
  • FOLLOW(N4: b+a) → {b} (the next symbol is the trailing b in N5).
  • FOLLOW(N5: b) → {ε} (end of the whole expression).

In practice these sets tell us what symbols can "follow" each node; they are also the basis of the FOLLOW-set construction used by LL(1) and LALR parser generators.

(d) DFA Construction Using FOLLOW()

The standard path from this RE to a DFA is: (1) apply Thompson's construction to the whole tree — the star node (a+b)* becomes an NFA with an ε-edge back to its start, and the trailing a (b+a) b becomes a chain of NFA states glued in order; (2) ε-closure gives the NFA's reachable states; (3) the Subset (Power Set) Construction turns the NFA into a DFA whose states are sets of NFA states. Because the FOLLOW set of the whole RE is {ε} (accept state), and the FOLLOW set of N2 is {a} (only a can follow it), the DFA transitions from the closure of (a+b)* on input a enter the "a has been seen" state, and from the (b+a) region the FOLLOW set {b} forces the DFA to transition only on b to the final accept state. Concretely the DFA has 5 states:

  q0 ──{a,b}──► q1         (closure of (a+b)*: {a,b} loop)
  q1 ──{a}──► q2            (first literal 'a')
  q2 ──{b,a}──► q3          (union (b+a))
  q3 ──{b}──► q4 (accept)   (final 'b')
  (any other input → qerror)

  q0: on a → q1; on b → q1
  q1: on a → q2; on b → q1  (back to star)
  q2: on b → q3; on a → q3
  q3: on b → q4 (FINAL)

  The DFA accepts exactly the language L((a+b)* a (b+a)b) =
  { strings of 0-or-more a/b, followed by 'a',
    followed by (a or b), followed by 'b' }

The FOLLOW sets tell us the expected symbols to appear at each point, so the DFA's transitions from each state are constrained to the symbols in that node's FOLLOW set — this is the basis of the construction.

7
What are the roles of a lexical analyzer?

A lexical analyzer (scanner, lexer) is the first phase of a compiler and acts as the boundary between raw characters and structured tokens. Its roles:

  • Collect characters into lexemes: read the source character by character and group them into the smallest meaningful units (words of the language).
  • Classify each lexeme: assign a token type — identifier, keyword, literal, operator, delimiter — and attach the attribute (symbol-table offset for identifiers, numeric value for constants).
  • Recognize keywords (reserved words like if, while) and identifiers (a string of letters, digits, underscores that is not a keyword).
  • Generate a token stream for the syntax analyzer, in the form (token_type, attribute) pairs.
  • Strip blanks, tabs, newlines, and comments unless they carry meaning.
  • Maintain line and column counts so the error handler can report "line 14, column 9: undefined variable x".
  • Detect and report lexical errors: illegal character, unterminated string literal, integer overflow, unmatched comment terminator.
  • Feed the symbol table: insert each new identifier, associate it with its offset, and report redeclarations or type conflicts to the semantic analyzer.
  • In some designs, perform macro expansion and generate pre-processed source (e.g. #include, #define substitution in C).

The overall result is a clean token stream — one entry per token, ordered left to right, with all whitespace and comments removed — that the parser can process without ever looking at a raw character.

Module 3 Questions

★ Note: 1. Right-sentential forms · 2. Parse tree from string · 3. Right-linear grammar · 4. Elimination of left recursion ★
1

What is a handle? How do you obtain a parse tree from a string? What is a right-linear grammar and how is left recursion eliminated? What is predictive parsing and how do top-down vs bottom-up parsers handle errors (panic mode, phase-level recovery)? Explain left factoring with a worked example. What is a context-free grammar and what are the roles of a parser? How does operator-precedence parsing work?

Handle & right-sentential forms: a right-sentential form is any string obtained from the start symbol by a rightmost derivation; a handle is the substring of it that reduces in exactly one step to the body of a production — leftmost such reduction is what a bottom-up parser reverses into a parse. For G: E → E + T | T; T → T * i | i, the handle-reduction trace of w = i + i * i (3 steps):

 step   string              handle     rule applied
 1     i + i * i           i          T → i
 2     i + i * T           i * T      T → T * i
 3     i + T               i + T      E → E + T
     E                     (accept)

Parse tree from a string: (a) expand it top-down: any leftmost derivation of w reads left-to-right as a walk of the tree; (b) expand it bottom-up: the handle sequence above reversed is the rightmost derivation, and the same tree falls out of the reduction order. Ambiguous strings yield more than one tree — that is the whole reason the table methods matter.

Right-linear grammar: every production has the form A → wB or A → w (w a terminal string, B one nonterminal). Such grammars generate exactly the regular languages, so a 2-state-style construction (rightmost nonterminal carries the "state") lets a finite automaton recognise them; e.g. A → 0A | 1B, B → 0B | 1A (even parity of 0s).

Eliminating left recursion: A → Aα | β becomes A → Bα, B → βB | ε (first remove indirect left recursion, then apply). Worked: L → L + id | id ⇒ L → id L′, L′ → + id L′ | ε. Predictive parsing is the LL(1) top-down scheme: each lookahead symbol decides the production to use, no backtracking.

Error handling — panic mode (worked example): on error, discard input tokens until a synchronizing token is hit, then restart at the nearest recoverable nonterminal. Input if (x < 3 y = 4; (missing )): the top-down parser hits the error at y after expanding E, discards y = 4, synchronizes on ;, reports "error at y", and resumes the statement list. Phase-level recovery: on error the current phase is restarted from the next token of its own phase input (scanner resynchronizes on a new token boundary; a failed parse restarts on the next top-level construct). Top-down recovery: for each nonterminal keep a small set of expected tokens; when the input is unexpected, report it and discard tokens until one expected token appears (cheap, per-symbol, but local). Bottom-up recovery: insert error productions (S → e S etc.) into the grammar and extend the LR table with an "e" column, so the parser pops the stack to a chosen point and shifts one token — more global, controlled by the table designer.

Left factoring: when a nonterminal's productions share a prefix, top-down predictive parsing must backtrack; factor the prefix out. G: S → id = E | id ≠ E | id > E  ⇒  S → id Q, Q → = E | ≠ E | > E — one lookahead suffices after "id".

Context-free grammar & parser roles: G = (V, Σ, P, S): all rules A → α with A ∈ V and α over (V ∪ Σ)* (e.g. G: S → ( S ) | ε generates ()(())). The parser: constructs the syntax tree / AST, verifies that the program is in the language (syntactic check), hands structure to the semantic analyser, detects and (locally) recovers from syntax errors, and supplies the basis for code generation.

Operator-precedence parsing: a single precedence function f(a,b) over terminal pairs plus a following function c(a); compare c(top-of-stack terminal) with f(top, input) to decide:

RelationMeaningAction
c(a) < f(a,b)b has higher precedence than the stack topSHIFT b
c(a) = f(a,b)equal precedenceSHIFT if left-associative, else ERROR
c(a) > f(a,b)reduce the handle on stackREDUCE
f(a,b) undefinedillegal adjacencyERROR
2

Build the LL(1) predictive parsing table for G: S → iAb | iBa | AS | b (i, b terminals; A, S nonterminals). Compute FIRST(S), FIRST(A), FOLLOW(S), FOLLOW(A), fill the complete predictive table, and test the LL(1) property using the FIRST/FOLLOW intersection rule.

Assumptions (as the sheet gives S-only productions): B and a read as terminals b, a; A must be nullable — take A → ε. Terminal set {i, a, b}; nonterminals {S, A}.

Computation: FIRST(A) = {ε} (A nullable). FIRST(S): from iAb, iBa → i; from b → b; from AS → FIRST(A)−{ε} = ∅, and since A → ε, FIRST(S) ⊇ FOLLOW(S). So FIRST(S) = {i, b} ∪ FOLLOW(S). FOLLOW(S): from iAb → b; from iBa → b (S at end of production… S is last: add a? no — S→iBa: b? FOLLOW adds nothing since a is end-terminal; FOLLOW(S) = {b} ∪ ($ since S is start) = {b, $}. Back-substitute: FIRST(S) = {i, b}.

SetValueReason
FIRST(A){ε}A → ε
FIRST(S){i, b}leads of iAb, iBa, b; AS contributes via A→ε
FOLLOW(S){b, $}S → iAb: b follows S; start symbol: $
FOLLOW(A){b, $}S → iAb: b follows A; S → AS: FOLLOW(S) follows A

Predictive table (row = nonterminal, col = lookahead):

iab$
SiAb | iBa — error (two productions on i)—S → b—
A——A → εA → ε

LL(1) test (intersection rule, applied explicitly): for distinct productions S → α and S → β: FIRST(α) ∩ FIRST(β) = ∅ must hold. Here FIRST(iAb) = FIRST(iBa) = {i} ≠ ∅ — violation. (FIRST(A) ∩ FOLLOW(A) = {ε}∩{b,$} = ∅ ✓, so the A-row is fine.) Conclusion: G is not LL(1) as written — the cell S,i is a genuine double-entry. Left-factor the clash: S → iAb | iBa shares prefix i: S → i P | AS | b, P → Ab | ba. Now FIRST(iP) = FIRST(AS) = FIRST(b) = ∅ pairwise, FIRST(P) = {a, b}, and the table becomes conflict-free: S,i → iP; S,b → b; S,$∪… S→AS on b via A→ε path; P,a → P→Ab… actually P on a: P→Ab? no: P→Ab starts with A (nullable) → first symbol b; P→ba starts with b — re-check FIRST(P) = {b}; P,a entry empty; P,b conflict remains between Ab? Ab: A→ε then b → {b}; ba → {b} — the inner "b a" vs "A b" with A→ε still clash on b, so factor once more if needed. The key LL(1) conclusion stands: the original table has the S,i double-entry, hence not LL(1).

3

Prove that no LR(1) grammar can be ambiguous. State the contrapositive. Then exhibit a concrete ambiguous grammar with two parse trees for iii and confirm the conflict in its LR(1) item set.

Proof (by contradiction). Suppose G is ambiguous. Then some string w has two distinct parse trees, i.e. two distinct leftmost derivations of w, hence two distinct bottom-up reduction sequences of w. Consider w's reduction on the canonical LR(1) automaton: the two sequences differ at some stack configuration — the parser has built the same stack (the common prefix of the two reductions) but must perform two different reduces for the two remaining sub-derivations. In item-set terms there is a state I that contains two items [A → α . , a] and [B → β . , a] with the same lookahead a, so the LR(1) table must hold two reduce entries for one (state, a) cell — a reduce/reduce conflict. But a valid LR(1) table has exactly one action per (state, symbol) cell, so the contradiction shows G is not LR(1). Contrapositive: every LR(1) grammar is unambiguous.

Concrete example. Grammar G: S → i S | S S | i. The string iii has two distinct parse trees, so G is ambiguous:

 tree 1 (left-leaning): S ⇒ i S ⇒ i S S ⇒ i i i

    S
   / \
  i   S
     / \
    i   S
        |
        i

 tree 2 (right-leaning): S ⇒ S S ⇒ i S S ⇒ i i i

    S
   / \
  S   S
 / \   |
i   i  i

Both are valid leftmost derivations of iii — same string, two different trees — so G is ambiguous. Now confirm the conflict in its LR(0) automaton: FOLLOW(S) = {i, $} (from S → S S giving FIRST(S) = {i} for the left S, and from the start symbol giving $). In state I₁ = closure of {[S → i ., $]} the items [S → i . S, $] (shift i) and the reduction items [S → i ., i] + [S → i ., $] coexist: on terminal i the table needs both a shift (to continue S → i S) and a reduce (S → i for lookahead i) — a shift/reduce conflict. (In the canonical LR(0) merging, the state after i carries two reduce items [S → i ., i] and [S → S S ., i] on the same lookahead i — a reduce/reduce conflict.) Either way the theorem holds: G is not LR(1), which is the contrapositive — an ambiguous grammar can never be LR(1).

Module 4 Questions

1

When is recursive-descent parsing desirable? Its drawbacks? For the left-recursive grammar S → S b | ε (the sheet's i c S b | ε form), show why plain top-down recursion loops, then show an LL(1) table-driven blocking diagram for the same language.

When desirable: hand-written parsers for small grammars where the structure is known in advance; natural, readable code that mirrors the BNF one-to-one; excellent for embedded error reporting at the exact point of failure (each function knows its nonterminal) and for semantic actions interleaved during the descent (build AST/IR inline). It needs no table construction — good for compilers where the grammar is fixed and small.

Drawbacks: (a) recursion depth = parse depth — deep inputs risk stack overflow; (b) no built-in error recovery — a single bad token unwinds the whole call chain unless you write per-production recovery code by hand; (c) intractable on left-recursive grammars — the recursion never reaches a terminal, so it loops (next paragraph); (d) not table-driven, so changing the grammar means rewriting the parser; (e) lookahead beyond LL(1) is awkward (no automatic LALR/LR power).

Why plain top-down recursion loops. G: S → S b | ε (sheet form S → i c S b | ε, the recursion sits in the leftmost position: S ⇒ i c S b ⇒ i c i c S b b …). A recursive-descent function S() written for the left-recursive form calls S() on its own first symbol before consuming anything new — infinite self-call, no input consumed. The same language (strings of the form (ic)* b^n) is fine under table-driven LL(1) because the table decides S → ε vs S → S b from the lookahead symbol, not from a recursive call:

 stack        input        action
 ----------   -----------  -------------------------
 S $          b b b $      table[S,b] = S → S b : replace S by S b on stack
 S b $        b b b $      table[S,b] = S → S b again
 S b b $      b b b $      table[S,b] = S → S b again
 S b b b $    b $          table[S,$] = S → ε : discard S
 b b b $      b $          shift b
 b b $         b $          shift b
 b $           $            shift b
 $             $            ACCEPT

Stack-and-table parsing never "calls itself"; the stack holds the pending S-expansions and the table routes them to ε on $. This is the exact blocking-diagram shape expected: shift/reduce/accept columns with stack vs input tape side by side.

2

Top-down vs bottom-up parser comparison table. Which parser implements recursive descent? A model diagram. Then build the FULL predictive parsing table for E → T E', E' → + T E' | ε, T → F T', T' → * F T' | ε, F → ( E ) | id — FIRST/FOLLOW first, then the complete action table.

Comparison:

AspectTop-down (predictive/LL)Bottom-up (LR / shift-reduce)
ConstructionHand-written recursion or table M[N,a] indexed by (nonterminal, lookahead)Automaton of LR items; table action[state,terminal], goto[state,nonterminal]
DerivationLeftmost derivation, expanding nonterminals top-downRightmost derivation reversed; reduces the handle on the stack
LookaheadTypically 1 symbol (LL(1)); more needs backtrackingLR(k): up to k symbols; handles many non-LL(1) grammars
Error handlingPer-production hooks; panic mode natural (discard to sync)Insertion / deletion / panic table-driven by the parser table
GeneralitySubclass of LR(1) — left recursion is a fatal loopStrictly more powerful; handles left-recursive grammars (the common case for operator expressions)
Example parsersPredictive LL(1), recursive descentSLL(1), LALR(1), LR(1), canonical

Which parser implements recursive descent? The LL(1) table-driven top-down parser is the automatic, mechanical version of hand-written recursive descent — the table replaces the call-stack, the driver loop replaces procedure calls. Model:

  +---------------+   +---------------------+   +-------------------+
  |   input tape  |   |   parse table M      |   |   stack (top left)|
  |  (id + id …)  |   |  M[nonterm, look]    |   |  $  T E'  E  …    |
  +-------|-------+   +-----------+-----------+   +---------|---------+
          |                    ^  lookup             ^  top
          v                    |  (nonterm, look)   |
  +-------+-------+  +----------+----------+  +------+-------+
  | driver loop:  |  |   if M[S,a] = A→α:  |  |  stack: S on |
  | S = top(stack)|  |   pop S, push α reversed|  | top = S    |
  | a = lookahead |  |   if M[S,a] = accept: |  |              |
  +---------------+  |   stack==input==$: done|  +--------------+
                     +---------------------+

Full predictive table for the arithmetic-expression grammar. FIRST/FOLLOW first:

NonterminalFIRSTFOLLOW
E{(, id}{$, )} (start; E inside parens)
E'{+, ε}FOLLOW(E) = {$, )}
T{(, id}FOLLOW(E) ∪ (+) = {$, ), +}
T'{*, ε}FOLLOW(T) = {$, ), +}
F{(, id}{*} ∪ FOLLOW(T') = {*, $, ), +}

Action table (every cell filled; ε-cells are reduce-to-ε):

id()+*$
EE → T E'E → T E'————
E'——E' → εE' → + T E'—E' → ε
TT → F T'T → F T'————
T'——T' → εT' → εT' → * F T'T' → ε
FF → idF → ( E )————

No cell holds more than one production: FIRST sets of the E-row, T-row, F-row are {id, (} (mutually exclusive within row), the E' row's + cell is separate from its ε-cells ( ) , $ are in FOLLOW(E')), T' mirrors on * — table is LL(1)-clean.

3

Using the table from Q2, parse the string id + id * id step by step. Columns: step, stack, input, action, table-cell used. End with accept. Draw the parse tree.

StepStackInputActionCell used
0E $id + id * id $— (initial)—
1T E' $id + id * id $E → T E'M[E, id]
2F T' E' $id + id * id $T → F T'M[T, id]
3id T' E' $+ id * id $shift id; F → idM[F, id]
4id E' $+ id * id $T' → εM[T', +]
5id + T E' E' $id * id $E' → + T E'; shift +M[E', +]
6id + F T' E' E' $id * id $T → F T'M[T, id]
7id + id T' E' E' $* id $shift id; F → idM[F, id]
8id + id * F T' E' E' $id $T' → * F T'; shift *M[T', *]
9id + id * id T' E' E' $$shift id; F → idM[F, id]
10id + id * id E' E' $$T' → εM[T', $]
11id + id * id E' $$E' → εM[E', $]
12id + id * id $$E' → εM[E', $]
13$$ACCEPTstack top = $
 parse tree for  id + id * id
                 E
              /     \
             T       E'
            / \     / | \
           F   T'  +  T  E'
          /    |       |\    \
        id    ε       F  T'  ε
                     /  |\
                   id  F  T'
                       |   |
                      id  ε

  (read: E → T E' ; E' → + T E' ; T → F T' ; T' → * F T' ; F → id
   so the tree binds * tighter than +, exactly operator-precedence intent)

Module 5 Questions

1

What is a reduce-reduce conflict in LR parsing? When does it appear? Give a minimal example. What is an SLR reduce-reduce conflict? Then give a table of ALL shift-reduce parser actions (shift / reduce / goto / accept) with their meaning and when each fires.

Reduce–reduce conflict: in a shift-reduce parser, state s and terminal a produce a conflict when the action table would need two different entries reduce r and reduce r' in the same cell (s, a). It appears when two handle candidates of different productions end in the same symbol and the parser cannot decide which is the true handle. The grammar is not LR(1); usually it is not SLR either, because both reductions are legal for the same SLR lookahead.

Minimal example (LR(0) item set with two reduce items):

S -> i A i .
S -> i B i .
F -> a | b | c

Item set after reading "i":
  S -> i . A i        shift A
  S -> i . B i        shift B

After reading "i a":
  S -> i A . i        reduce S -> i A i
  S -> i B . i        reduce S -> i B i
                      ^^^^^^^^^^^^^^^^^^^
                reduce-reduce on terminal i (no shift to i)

The dot has reached the end of two different productions in the same state, and both items carry the same lookahead set; the parser cannot commit to either reduction. The grammar is ambiguous (or at least not LR(0)) and must be rewritten — e.g. merge i A i and i B i into a single production S → i C i with C → A | B, which removes the conflict.

SLR reduce–reduce conflict: two items q1 → α . β and q2 → α . γ share the same core (state), and FOLLOW(q1) ∩ FOLLOW(q2) ≠ ∅. The conflict survives even when lookaheads are available, because SLR uses a single global FOLLOW set per non-terminal; it cannot distinguish the items. The resolution is to refine the grammar (rewrite it into an unambiguous equivalent) or, in practice, fall back to a full LR(1) parser that carries a per-item lookahead and can split the state.

All shift-reduce parser actions:

A shift-reduce parser's driver consults exactly one of four actions per step; the action table is built by the generator and is the only input to the runtime parser.
ActionMeaningWhen it fires
shift spush terminal a onto the stack, move to GOTO(state, a) = sThe table entry action[state, a] = s (an integer shift target) — an LR item of the form A → α . a β is present
reduce rpop len(β) symbols, push A, move to GOTO(prev, A); action is production number rTable entry action[state, a] = r (production number) — item A → β . is present and lookahead matches
goto tpush non-terminal X, move to t (an internal GOTO entry, not consulted during input processing)Row = current state, column = a non-terminal that appears right of the dot in some item; computed as GOTO(state, X)
acceptsignal "end of input, parse successful"State s contains the item S' → S . with lookahead $; input is completely consumed
errorreport syntax error, trigger error recoveryNone of the above applies — empty cell in the action table

SLR conflict resolution (exam point): a shift-reduce conflict in an SLR table is resolved by choosing shift (the canonical convention). A reduce-reduce conflict has no automatic resolution; it indicates the grammar is not suitable for LR-based parsing and must be rewritten. A pure LR(1) parser can, however, split states by their item lookaheads and sometimes eliminate conflicts that SLR leaves behind.

2

Build the complete SLR(1) parsing table for grammar G: E → T E' | a, E' → + T E' | ε, T → F T' | b, T' → * F T' | ε, F → ( E ) | Id. Work it out fully: (i) augment, (ii) list the LR(0) item sets, (iii) FIRST/FOLLOW sets, (iv) the fully-filled action/goto table.

(i) Augment and label productions:

r0:  S' -> E
r1:  E  -> T E'
r2:  E  -> a
r3:  E' -> + T E'
r4:  E' -> ε
r5:  T  -> F T'
r6:  T  -> b
r7:  T' -> * F T'
r8:  T' -> ε
r9:  F  -> ( E )
r10: F  -> Id

(ii) LR(0) item sets (closures) — 18 states:

I0:  S'→.E   E→.T E'   E→.a   T→.F T'   T→.b   F→.( E )   F→.Id
I1:  E→a.
I2:  T→b.
I3:  F→(. E )   E→.T E'   E→.a   T→.F T'   T→.b   F→.( E )   F→.Id
I4:  F→Id.
I5:  S'→E.
I6:  E→T. E'   E'→.+ T E'   E'→.ε
I7:  T→F. T'   T'→.* F T'   T'→.ε
I8:  F→( E.)
I9:  E'→+ T. E'   E'→.+ T E'   E'→.ε
I10: E→T E'..
I11: T'→* F. T'   T'→.* F T'   T'→.ε
I12: T→F T'..
I13: F→( E ).
I14: E'→+ T E'..
I15: T'→* F T'..
I16: E'→+ T E'.   (reduces r3 on FOLLOW(E'))
I17: T'→* F T'.   (reduces r7 on FOLLOW(T'))

(iii) FIRST / FOLLOW sets:

FIRST(E) = {a, b, (, Id}      FIRST(E') = {+, ε}      FIRST(T) = {b, (, Id}      FIRST(T') = {*, ε}      FIRST(F) = {(, Id}
FOLLOW(S') = {$}
FOLLOW(E) = FOLLOW(E') = {+, ), $}
FOLLOW(T) = FOLLOW(T') = {+, ), $}
FOLLOW(F) = {*, +, ), $}

(iv) Complete SLR(1) action / goto table — “–” = error. A conflict cell is written s_n / r_m and resolved by shift (the standard SLR convention):

stab+*()Id$EE'TT'F
0s1s2––s3–s4–5–6–7
1–––––r2–r2–––––
2––r6––r6–r6–––––
3s1s2––s3–s4–8–6–7
4––r10r10–r10–r10–––––
5–––––––r0–––––
6––s9––r4–r4–10–––
7––r8s11–r8–r8–––12–
8–––––s13–––––––
9–s2––s3–s4–––14–7
10–––––r1–r1–––––
11––––s3–s4–––––15
12––r5––r5–r5–––––
13––r9r9–r9–r9–––––
14––s9––r4–r4–16–––
15––r8s11–r8–r8–––17–
16–––––r3–r3–––––
17––r7––r7–r7–––––

Conflict check (why this grammar is SLR-clean): no conflicts occur at all. The would-be trouble spots separate cleanly: in state 7 the shift on * (to I11) does not compete with the reduce r8, because * ∉ FOLLOW(T') = {+, ), $} — the * shift belongs to T' → * F T', which is a different item in the same state with a different terminal. Likewise in state 3 there is no reduce item at all (all items still have terminals after the dot), so the shifts on a / b / ( / Id are unopposed. The accept (r0) fires on $ in state 5. Since no cell ever needs two different actions, the table is deterministic as written and the grammar is SLR(1) with zero conflicts.

3

Describe an LR(1) parser with a blocking diagram (input buffer, parse stack, action table, GOTO table, driver loop). Give the major advantages of LR(1): no left-factoring requirement, single left-to-right pass, no parse-time lookahead computation, minimal context. Contrast with predictive parsing limits.

LR(1) parser — blocking diagram:

                    +-----------------------------+
                    |        ACTION TABLE          |
                    |  (state, terminal) →         |
                    |    shift s / reduce r        |
                    |    accept / error             |
                    +-----------------------------+
                                   |
                                   | consulted each step
                                   v
  +------------------------------------------------------------------+
  |                        DRIVER LOOP                               |
  |                                                                  |
  |  1. state = top(stack);  terminal = head(input)                |
  |  2. action = ACTION[state, terminal]                            |
  |     ┌─ shift s :  push(terminal, s); advance input              |
  |     ├─ reduce r : pop len(β); push(A, GOTO[prev,A]);           |
  |     │               emit production r                            |
  |     ├─ accept   : declare "syntax OK", halt                     |
  |     └─ error    : trigger recovery, halt                         |
  |  3. if not accepted, goto step 1                                  |
  +------------------------------------------------------------------+
        |                                            |
        | stack ops                                  | input read
        v                                            v
  +----------------------+              +-------------------------+
  |       PARSE STACK     |            |      INPUT BUFFER        |
  |  bottom: start symbol |            |  "a + b * c $"           |
  |  top:   state N       |            |  (scanned L→R, head     |
  |                        |            |   points to next sym)   |
  +----------------------+              +-------------------------+
                                   +-----------------------------+
                                   |        GOTO TABLE           |
                                   |  GOTO(state, nonterm) →     |
                                   |  next-state (used after    |
                                   |   every reduce)             |
                                   +-----------------------------+

The stack stores (symbol, state) pairs. After a reduce r : A → β is performed, the parser pops len(β) states and consults GOTO[prev_state, A] to find the new top state. The input buffer is read left-to-right, one terminal at a time, with an end-marker $.

Major advantages of LR(1):

  • Covers all practical programming-language constructs without left-factoring. Left recursion (a while, a for-loop, a - b - c) is a non-issue; LL(1) parsers must rewrite the grammar to eliminate it.
  • Single left-to-right pass — no backtracking, no multiple scans, no context-free ambiguity resolution at parse time. Amortised O(n).
  • Lookahead embedded in items — the parser never computes a FIRST set on the fly; the generator precomputes item-lookaheads and the runtime just indexes into the table.
  • Minimal context (usually 1 symbol of lookahead) — one terminal symbol determines the action; the table size is bounded and known in advance.
  • Handles non-LR(0) grammars — e.g. an if-else statement, two-statement blocks, and expression grammars that are not LR(0) but are LR(1) or LR(2).

Contrast with (top-down) predictive / LL(1) parsing:

CriterionLR(1) (bottom-up)LL(1) / Predictive (top-down)
Left recursionHandles naturally; no factoringMust be factored out or rewritten
First/follow splitLookahead sets computed once at generationComputed at every decision point; split must be disjoint
Grammar classLR(1) ⊃ LL(1); broader classLL(1) is a strict subset; many practical grammars are not LL(1)
BacktrackingNeverNever (when LL(1)); required in LL(k) or with backtracking for non-LL(1)
Context window1 terminal (minimal)1 terminal for LL(1), k for LL(k)
Table sizeNumber of states × number of terminals (bounded)Same structure, but more first-sets to check
Generation costHigher (item sets carry lookaheads)Lower (FIRST/FOLLOW per non-terminal)
In practice, most modern parsers use LALR(1) (an LR(1) optimisation that merges states with the same core and lookahead-set, shrinking the table while keeping LR(1) power). LALR(1) can introduce reduce-reduce conflicts that pure LR(1) avoids; Yacc and CUP default to LALR(1).
4

Build the LR(0) set of items and the SLR(1) table for the right-recursive grammar S' → S, S → iXSS | a, X → iXSS | b (terminals i, a, b). Show item sets, the table, and note any conflicts and how SLR(1) lookahead resolves them.

Productions and FOLLOW sets:

0: S' -> S
1: S  -> i X S S
2: S  -> a
3: X  -> i X S S
4: X  -> b

FOLLOW(S) = { i, a, $ }   (S appears in S → i X S S, FIRST(S) = {i,a} ⊆ FOLLOW(S); $ from S' → S)
FOLLOW(X) = { i, a }      (X is followed by S S; FIRST(S) = {i,a}; S cannot be ε)

LR(0) item sets:

I0:  S' -> . S              S -> . i X S S      S -> . a
I1:  S -> i . X S S        X -> . i X S S      X -> . b
I2:  S -> a .
I3:  S -> i X . S S        S -> . i X S S      S -> . a
I4:  X -> i . X S S        X -> . i X S S      X -> . b
I5:  X -> b .
I6:  S -> i X S . S S      S -> . i X S S      S -> . a
I7:  X -> i X . S S        S -> . i X S S      S -> . a
I8:  X -> i X S . S S      S -> . i X S S      S -> . a
I9:  X -> i X S S .        S -> . i X S S      S -> . a
I10: S -> i X S S .        S -> . i X S S      S -> . a
I11: S' -> S .             (accept)

SLR(1) action / goto table:

stateiab$SX
I0s1s2––11–
I1s4–s5––3
I2r2r2–r2––
I3s1s2––6–
I4s4–s5––7
I5r4r4––––
I6s1s2––10–
I7s1s2––8–
I8s1s2––9–
I9s1⚠s2⚠––––
I10s1⚠s2⚠–r1––
I11–––acc––
⚠ = shift/reduce conflict resolved by shift (standard SLR convention). I9: r3 (X → iXSS) conflicts with shift on i,a — resolved by shift. I10: r1 (S → iXSS) conflicts with shift on i,a — resolved by shift; r1 on $ has no shift counterpart, so no conflict there.

Conflict analysis: I9 contains the reduce item X → iXSS . (r3) with FOLLOW(X) = {i, a}, and shift items for i and a — a shift/reduce conflict on both terminals. I10 contains S → iXSS . (r1) with FOLLOW(S) = {i, a, $} and shift on i and a — a second shift/reduce conflict. SLR(1) resolves both by preferring shift (the canonical convention), so the grammar is parseable by an SLR(1) parser despite the conflicts. A full LR(1) table, carrying a specific lookahead in each item, would split I9 and I10 into sub-states with distinct lookahead sets and would have no conflicts at all.

5

Compare the LR(1) table with the SLR table from Q4 (size + whether the conflicts disappear under LR(1) — explain why item lookaheads split the state). Then a short note on handle parsing: handles, rightmost derivation run in reverse, one worked handle-reduction trace for (i * i) + i.

Worked bottom-up parse of ( i * i ) + i (the reverse of a rightmost derivation — this is exactly what handle parsing does step by step). Productions: 1 E→E+T, 2 E→T, 3 T→T*F, 4 T→F, 5 F→(E), 6 F→i:

 stack        input          action
───── ─────────────── ─────────────────────────
          ( i * i ) + i $   shift (
   (       i * i ) + i $    shift i
   ( i     * i ) + i $      reduce i → F     (6)
   ( F     * i ) + i $      shift *
   ( F *   i ) + i $        shift i
   ( F * i ) + i $          reduce i → F     (6)
   ( F * F ) + i $          reduce F → T     (4)
   ( F * T ) + i $          reduce T*F → T   (3)
   ( T       ) + i $        shift )
   ( T )     + i $          reduce T → E     (2)
   ( E )     + i $          reduce (E) → F   (5)
   F         + i $          reduce F → T     (4)
   T         + i $          shift +
   T +       i $            shift i
   T + i     $              reduce i → F     (6)
   T + F     $              reduce F → T     (4)
   T + T     $              reduce T → E     (2)
   E + T     $              reduce E+T → E   (1)
   E         $              ACCEPT

Each reduce step removes the rightmost handle from the stack (the substring that is the RHS of a production and was just built) — that is handle parsing. Note the two symmetric moments: the left ( F * F ) closes to ( E ) → F → T before the final E + T is formed, which is precisely why * binds tighter than + in a bottom-up (handle) parse: the * multiplication is completely reduced inside the parentheses before the + ever sees its left operand.

Module 6 Questions

1

Translate the arithmetic expression x + (b + c / d) into a syntax tree. Explain interpreted vs syntax-directed translation with suitable examples. What are the two types of attributes associated with a grammar symbol (inherited vs synthesized)?

Syntax tree of x + (b + c / d) (internal nodes = operators, leaves = operands, respecting precedence and parentheses):


            +
           / \
          x   +
             / \
            b   /
               / \
              c   d

An interpretation of a grammar is a rule that assigns a meaning (value, action) to each production. Two forms: (i) Interpreted translation — the parse tree itself is evaluated by an interpreter; the grammar productions are annotated with semantic functions that compute the value of the node from its children. Example: evaluating a + b * c by walking the tree and applying the function at each operator node. (ii) Syntax-directed translation — each production carries translation rules (attribute equations or semantic actions) that synthesize the output (postfix, 3-address code, object code) during parsing; a single parse of the input drives the generation. Example: production E → E + T emits E' T' + for postfix.

Attributes are values (of any data type) associated with grammar symbols (non-terminals and terminals). The two kinds:

  • Synthesized attributes: value of a parent is computed from its children (bottom-up); needs no context. Example: value of an expr node from its operand nodes.
  • Inherited attributes: value of a child is computed from its parent and/or siblings (top-down flow); gives a node context. Example: a type-checker passing the expected result type down from a statement node to its expression child.

Synthesized attributes yield S-attributed definitions; inherited ones (where needed) yield L-attributed definitions.

2

What is an attribute? What is a syntax-directed definition (SDD)? Illustrate with an example (postfix-evaluation SDD). What is an attributed grammar? What is ambiguity in a grammar? What is the necessity to generate a parse tree? Any technique to remove ambiguity (left factoring / grammar rewriting)?

Attribute: a value associated with a grammar symbol — it can be a number, string, AST node, error code, or any program object (e.g. the value of an expression node, the type of a declaration, the generated code for a statement).

Syntax-directed definition (SDD): a grammar augmented with an action attached to each production. The action is either (i) an equation over attributes or (ii) executable code. It is written as production ::= action, with actions of a non-terminal separated by |, e.g. expr ::= term | expr "+" term.

Postfix-evaluation SDD example:

expr >= expr1 '+' expr2      expr >> print ( expr1.postfix
                                       . expr2.postfix . "+" )
term >= id                     term >> print ( id.value )
     | '(' expr ')'            term >> print ( expr.postfix . ")" )

With input ((2*(3+x))*((2+y))) the tree bottom-up evaluation yields postfix 2 3 x + * 2 y + * * *.

Attributed grammar: a grammar whose productions carry attribute rules (synthesized or inherited). The parse tree plus attribute rules forms the attributed parse tree; evaluating the rules is the translation.

Ambiguity: a grammar is ambiguous if some string has more than one leftmost (equivalently, rightmost) derivation, i.e. more than one parse tree — e.g. E → E + E | E * E for a + b * c. Ambiguity must be resolved because an unambiguous tree is needed for deterministic semantic action.

Necessity of a parse tree: the tree fixes the order of operations (precedence/association), localises each node's context (needed for inherited-attribute flow), supports optimization (DAG sharing), and drives code generation.

Removing ambiguity: (i) Grammar rewriting — restructure into precedence levels: E → T | E + T; T → F | T * F; F → id | '(' E ')' — now one tree per string. (ii) Left factoring — extract a common prefix (A → cAb | cAc → c A (b|c)); this makes the grammar suitable for top-down (LL) parsing by removing the common-prefix choice; it does not by itself remove ambiguity, so combine both techniques.

3

Draw a DAG for the expression statement: if x ≠ 0 then x := 3*(y + 1) else z := y + 1. Show the DAG with node sharing where applicable.

A DAG is obtained from the expression tree by sharing every common subexpression: identical children are identified into one node. Here y + 1 occurs in both branches — it is shared. The boolean test x ≠ 0 produces true/false leaves driving the two conditional edges. Labelled edges T/F (true branch / false branch) and assignments are terminal actions.


                 +-----------+
                 | x  neq  0 |   boolean test: T if x != 0
                 +-----+-----+
             T/   |           \F
                  v            v
            +-----------+  +-----------+
            | 3 * (y+1) |  |   y + 1   |
            +-----+-----+  +-----------+
                  |            |
                  v            v
          (assign x := )   (assign z := )

Reading the DAG: root is the conditional; on T we compute 3 * (y+1) and assign to x; on F we compute y + 1 and assign to z. Because y+1 appears under both branches, a single node is shared between the two paths. The shared y + 1 lets the compiler lift that subexpression out of the conditional once (common subexpression hoisting):


   t := y + 1            // hoisted, evaluated ONCE
   if x != 0 then x := 3 * t
   else z := t

Optimization payoff: one subtraction/addition, one store to t, one conditional store. The ≠ test node also collapses a constant-fold when x is a compile-time constant (e.g. if 5 ≠ 0 always T; if 0 ≠ 0 always F — dead-code elimination).

4

Translate the arithmetic expression x * (b + c) into a syntax tree and postfix notation. Design a DAG for a + a*0 + 0*0 + 0 + d + 0 + 0, showing constant-folding simplification.

Syntax tree of x * (b + c):


            *
           / \
          x   +
             / \
            b   c

Postfix (operands, then operator in postorder): x b c + *.

DAG of a + a*0 + 0*0 + 0 + d + 0 + 0: The sheet prints the constant as 0 (the original source uses O typographically). We assume 0 is the numeric constant zero (identity for multiplication, identity for addition in the usual ring), not an indeterminate variable or an operator letter. With this assumption every term involving 0 folds:


   Assumption: the "O" printed in the source is the numeric constant 0,
   so that:  x * 0 = 0   and   0 * 0 = 0   and   x + 0 = x.

   a + a*0 + 0*0 + 0 + d + 0 + 0
   = a + 0   + 0   + 0 + d + 0 + 0      (constant folding: a*0 → 0, 0*0 → 0)
   = a + d                                 (adding 0 is identity)

The resulting DAG is a single add node with leaves a and d:


   +
  / \
 a   d

Assumption explicitly stated (for marking): the source uses the letter O where the constant zero 0 is meant; we treat it as the integer constant 0 with the standard ring axioms so that multiplication by 0 and addition of 0 are identities. The DAG has two leaves and one internal + node. No subexpression sharing is needed beyond that because each leaf is distinct. (If the original symbol were instead the variable O, the expression would not fold to a + d; the simplification therefore depends on this reading.)

5

How do we mean by Syntax-Directed Translation? Compare S-attributed and L-attributed SDDs in a table. What are the main contributions of SDT?

Syntax-Directed Translation (SDT): a grammar G = (V, Σ, P, S) augmented with attribute equations (or semantic actions) attached to productions, such that every parse of an input sentence has a meaning — the generated target (postfix, intermediate code, object code). A parse of a sentence w with root R evaluates the equation tree rooted at R to yield G(w) in the output language.

AspectS-attributed SDDsL-attributed SDDs
Flow of valuesbottom-up: children → parenttop-down and left-to-right into children; only synthesized from above
Typical usetree evaluation, static analysis, most semantic checkscode generation, register allocation, type-checking
Evaluation orderpostorder of the parse treeinorder (left-to-right) of leaves
Number of passesone bottom-up pass over the tree sufficesrequires a single left-to-right traversal; no second pass — each child can be evaluated as soon as all its left siblings and its parent's attributes are known
Feasibilitytree evaluation onlycan be evaluated online by any top-down parser (LL, even some LR with care)
Example equationexpr.val = expr1.val + expr2.valstmt.type = stmt1.type — the L attribute flows down to child stmt1 from parent stmt
When usedwhen the result of a node depends only on its own descendantswhen the result must flow into children (e.g. target machine code depends on which register a variable lives in)

Contributions of SDT to automatic code generation: (1) it converts parsing into generation: a single bottom-up or left-to-right pass simultaneously computes the meaning and emits output, e.g. an interpreter (postfix code evaluation) or an assembler (assembling object code while parsing the source). (2) It unifies syntax and semantics: the semantic action is declared with the production, making it provably well-formed and machine-checkable. (3) It supports two-stage compilers: an attributed parse tree yields a target program that can later be re-optimized. (4) It supports the separation of concerns: parsing is the syntactic role, translation is the semantic role — a clean decomposition that is the backbone of every production compiler.

6

What is an input-buffering implementation? What problems can arise when implementing the input buffer (lookahead beyond a single character, token boundaries spanning buffer boundaries, end-of-file)? What is a sentinel and its use?

Input buffering: the compiler reads the source into a large buffer (input buffer) rather than character-by-character; the parser pulls tokens from the buffer via a next_token() routine. Each token is cached, with a pointer to the next character. The buffer must hold enough input for the parser's lookahead window.

Problems:

  • Lookahead > 1 character. If the buffer holds only one character, a token like == (2 chars) or an identifier abc (3 chars) cannot be emitted. The buffer must hold enough characters to see the complete next token. For a grammar with max k-lookahead, hold k characters.
  • Token boundary spans the buffer edge. A token may straddle the boundary between two read() chunks — e.g. a 512-byte buffer holds foo in the first chunk but bar in the second; the tokenization engine must not split identifiers, string literals or comments at the buffer edge. One must either (i) read the whole file at once, or (ii) implement a sliding buffer that holds the tail of the previous chunk plus the head of the new chunk so tokenization never straddles the join.
  • End of file. When the buffer runs out of characters the matcher must detect it without dereferencing *buffer_ptr = 0. The usual technique: append a special marker (sentinel) so the parser can recognise that no more input follows.

Sentinel: a special character — commonly $ or an internal EOF token — that the lexer consumes (recognises as "no more input") but that the parser never attempts to match against a grammar production. The sentinel terminates the input: a matching loop checks if (*buf == SENTINEL) return; before emitting a token; the parser's productions do not have $ on their right-hand side, so the parser only sees the sentinel to know the input has ended, not to parse it.

Why a sentinel matters: it separates the lexing concern (how far to read) from the matching concern (which production does this token match). Without it, every matcher must special-case the "is this the last character" check, and an unterminated identifier/string would otherwise be silently split at EOF. With it, the buffer can be refilled or exhausted; the sentinel is the fixed point the matcher converges on.

7

Mention different loop-optimization techniques. What is a dependency graph? What is an LR(1) parser (brief recap in the code-generation context)?

Loop-optimization techniques:

  • Loop unrolling: duplicate the loop body 2, 4 or k times so that the branch-per-iteration is amortised over k iterations. The loop bound n must be a compile-time multiple of k (or a residual tail loop handles the remainder). Speedup: 1/k fewer branch checks; code size: k× larger. Example: for(i=0;i<n;i+=4){b[i]=a[i]*2; b[i+1]=a[i+1]*2; b[i+2]=a[i+2]*2; b[i+3]=a[i+3]*2;}
  • Loop jamming: combine two (or more) consecutive loops over the same range into one loop over one array traversal, reducing memory traffic and instruction fetch. for(i) t[i]=a[i]+b[i]; jammed with for(i) c[i]=t[i]*2; becomes one loop.
  • Induction variable elimination (strength reduction): replace a costly induction variable (like i*k, the address calculation) with an add-by-constant chain. If i = i + 1 each iteration, addr = base + i*k becomes a addr = addr + k update, one integer add per iteration instead of a multiply.
  • Strength reduction: replace a hard operation with a cheaper equivalent on the path: x*8 → x << 3; pow(n,2) → n*n when n is small.
  • Peephole optimization: a local scan of a window of w instructions (usually a register or stack) that applies local rewrites: x = x + 0 delete; x = 1; x = x*2; → x = 2; LOAD t; LOAD s; → LOAD s.
  • Loop invariant code motion (LICM): hoist statements whose value does not change within the loop body out of the loop (e.g. addr = &mat[i][j] outside a for(k) { ... } loop that does not write i or j).

Dependency graph: a directed graph whose nodes are the statements of a loop; an edge Si → Sj means Sj reads a value that Si writes (a data dependency, i.e. flow). Two subcases: a loop-carried edge (Sj is in the next iteration of Si's value) is a true dependency that prevents parallel execution; a anti-dependency (write-after-read) can be removed by renaming registers/arrays. The graph exposes which iterations can be run simultaneously — the basis of loop parallelisation.

LR(1) parser (recap): a bottom-up (shift-reduce) parser that keeps a stack of states and reads exactly one lookaheads (hence "LR(1)"). It is constructed from the grammar by the item sets method: LR(0) items are a production with a dot in some position; the closure and goto functions close sets on non-terminals after the dot. The parser has a finite automaton of states; each state has LR(1) sets of (item, lookaheads) pairs that determine whether to shift or reduce. LR(1) can handle every language that is unambiguous in the sense of leftmost-derivation + 1 lookaheads — a strict superset of LL(1). In code generation it is the workhorse of bottom-up semantic evaluation: reductions give the bottom-up order needed for S-attributed SDDs; inherited attributes can be handled by passing values through the stack. LR(k) (k > 1) adds more lookahead but blows up the state table; k = 1 is the sweet spot — enough lookahead for most imperative-language grammars.

Module 7 Questions

1

What is type checking? Differentiate dynamic and static type checking.

Type checking: a verification step that confirms every value in a program is used in a way consistent with its declared type, and that every expression / declaration / statement has a type that can be assigned. The goal is to catch errors early that would otherwise surface as runtime crashes, garbage data, or silent mis-computation. Type systems are the language's specification of which values are interchangeable.

AspectStatic type checkingDynamic type checking
When errors are detectedat compile time (before execution)at runtime, as the values flow through the program
Mechanismtype inference / type checker walks the AST and checks each nodeeach operation inspects the actual values' tags before execution; incompatible → raise an exception
Example languageJava: int x = "abc"; — rejected at compile time; also long y = 3.14; needs explicit castPython: x = "abc" + 1 raises TypeError only when the line executes (a variable can be reassigned to any type)
Cost at runtimelow — checks done once; generated code can assume types are correcthigh — every operation has an attached tag check; the interpreter must inspect values
Effect on program structuretypes propagate; a type error forces restructuring before runningtypes evolve; no compile-time contract; errors localize at the site of execution
Strength of guaranteeif the type system is sound, every run obeys it (all type errors detected before running)if a check fails the program aborts; a partial guarantee — some errors are caught, others silently propagate
Typical error classmissing return types, wrong argument types, uninitialised variables, unhandled checked exceptionsruntime type errors, e.g. None handling in Python, dynamic-dispatch failures
Trade-offcatches more bugs earlier; the programmer pays in boilerplate; hard to write ad-hoc polymorphismflexible, less code; bugs surface late; slower execution due to tag checks

Note on Java vs Python: Java is statically type-checked and strongly typed — a String literal may not be assigned to an int variable without a compile-time error. Python is dynamically type-checked: variables have no declared type; the type is that of the value, and x + 1 only works when the current value of x is int. Python also does not do static checking — it uses duck typing (check the method, not the type) at each call site, so its dynamic check is a method dispatch failure, not a tag-check failure.

2

What are the types of type systems? What are the specifications of a simple type checker (type inference rules, unification, subsumption, environment)?

Types of type systems (classified on several axes):

  • Typed vs untyped: untyped (machine code, raw C with void*) — every expression has the same type; typed — every expression has a distinct type.
  • Strongly vs weakly typed: strongly — operations only between values of compatible types ("a" + 1 is an error); weakly — implicit conversions are allowed ("a" + 1 becomes "a1" in JavaScript); strong + strict = sound type system.
  • Explicit (nominal) vs implicit (structural): nominal — two types are identical only if the programmer named them identically (Java class Dog1 vs class Dog2); structural — two types are interchangeable if their shape (fields, methods) match (interface-style, in Go and in many functional languages).
  • Sound vs unsound: sound — if the type checker accepts a program, no run-time type error can occur; unsound — the checker lets through a program that will break at runtime (e.g. implicit any in TypeScript, unchecked generics in some languages).

Specifications of a simple type checker: A simple type checker assigns a type to every expression and verifies that every application matches its expected signature.

(1) Type inference rules. A set of rules of the form (Γ, E) → τ, where Γ is the environment (map from variable → type), E is an expression, and τ is the inferred type. Examples:

  • Literals: Γ ⊢ 42 : int; Γ ⊢ "hi" : string
  • Variables: if x : t ∈ Γ, then Γ ⊢ x : t
  • Application: Γ ⊢ e1 : t1 → t2 and Γ ⊢ e2 : t1 implies Γ ⊢ e1(e2) : t2
  • Let: Γ, x : t ⊢ e2 : t' and Γ ⊢ e1 : t implies Γ ⊢ let x = e1 in e2 : t' (with let-generalisation for polymorphic types)

(2) Unification. When two type expressions must be equal (e.g. function argument type = parameter type), the checker solves equations between type variables to make them compatible. E.g. unifying a → int with string → b binds a := string and b := int, giving the most general type string → int. The unifier is the engine of inference: it either succeeds with a binding, or fails with a type clash.

(3) Subsumption. A subsumption rule says that τ₁ ⊑ τ₂ (τ₁ is a subtype of τ₂) — a value of type τ₁ may be used where τ₂ is expected. A subsumption rule in a checker: if Γ ⊢ e : τ₁ and τ₁ ⊑ τ₂, then Γ ⊢ e : τ₂. Inheritance: a Dog value can fill a slot expecting Animal (Dog ⊑ Animal).

(4) Environment. The type environment Γ is a mapping from each free variable in scope to its declared type. It grows as new variables come into scope (Γ, x : t) and shrinks when they leave (Γ \ {x}). The checker keeps a stack of environments (one per scope); the most-inner binding shadows outer ones. The environment plus the rules defines the typing context; the checker's verdict is Γ ⊢ E : τ for some well-formed τ — or a type error if no τ exists.

Putting it together (the four pillars of a simple checker): the environment supplies the declared types; the inference rules walk the AST and assign types; unification solves the type-variable equations that arise; subsumption allows subtypes to fill supertype slots. A program type-checks iff it type-checks under all four rules simultaneously.

Module 8 Questions

1

What is an activation record (stack frame)? Explain its components in detail (control info: return address, return register, home base; temporary/locals; access link; parameters). What are the various data structures used for symbol-table construction? When and how are active activation records used? What is a symbol table, and how is it implemented?

Activation record (stack frame): the memory area created on the run-time stack when a procedure is called and discarded when it returns. It holds everything needed to complete the procedure's execution and resume the caller: parameters, local variables, temporaries, control information and links to other frames.

Components:

+----------------------------------------------+
|            caller's frame (top of stack)     |
+----------------------------------------------+
|  actual parameters: p1 p2 ... pn            |  passed by caller
|  access link    --> caller's frame           |  for free vars / dynamic chain
|  temporaries: t1 t2 ...                     |  intermediates of expressions
|  local vars: x y z ...                      |  named variables of the proc
|  control information:                       |
|     return address  (PC of instruction       |
|                     after the CALL)          |
|     return register (value a function returns|
|                     in, on return)           |
|     home base (offset of the procedure's     |
|                 locals from the static base) |
+----------------------------------------------+
                     (SP grows down; FP points
                      to the control-info area)
  • Return address: so the caller can continue after the callee finishes.
  • Return register: the value a function expression evaluates to, held on return.
  • Home base: used only when local names are accessed statically — enables fast access to globals and statically-allocated locals.
  • Access link: pointer to the activation record of the textually enclosing procedure — it forms the static (lexical) chain used to reach nonlocal variables; the dynamic chain is the chain of frames currently on the run-time stack (the caller frames), used for dynamic scoping, where a name resolves to the most recent activation of the same procedure.

Data structures for the symbol table:

StructureSearchWhen used
Linear listO(n) scanDynamic scoping / blocks — entries created and destroyed as blocks are entered; supports lifetimes
Hash tableO(1) averageThe standard choice; fixed-size array, hash of name; needs collision handling (open addressing / chaining)
Binary search treeO(log n)Names in sorted order; supports range queries over names
Direct addressO(1) exactArray indexed directly by the name; fastest but impractical for large name-spaces

What a symbol table is and how it is implemented: a structure recording semantic information about every identifier. An entry carries at least: name, type, scope, address (the target location), plus kind (variable / procedure / constant), level, and a next pointer. Two strategies: (1) per-scope tables — each block has its own table linked to the outer block's (the static chain); on exit the table is destroyed and names die with it; or (2) a single global table where every entry is marked with its scope/level and deleted when its scope ends. Per-scope tables give clean lifetime management; a global table is simpler but must scope-check on every lookup.

2

Explain syntax errors vs semantic errors with a table of examples. What are the dynamic storage-allocation techniques? What are the storage-allocation strategies — stack vs heap, with garbage collection?

Syntax vs semantic errors: a syntax error is a violation of the grammar of the language — detected by the parser; a semantic error is a meaning violation (type, scope, use-before-declaration) in a structurally correct program — detected by the semantic analyzer. Structural form is checked first; semantics only when the program is syntactically correct.

ClassExampleDetected by
Syntaxif (x < 3) y = 4 — missing ;Parser (LL/LR, shift-reduce conflict)
Syntaxsum = (a + b — unmatched parenthesisParser
Semanticint x; x = "hello"; — type mismatchSemantic analyzer / type checker
Semanticcalling foo(2) when foo takes 3 argsSemantic analyzer
Semanticusing a variable before its declaration in scopeSemantic analyzer

Dynamic storage-allocation techniques (allocating data at run time, as opposed to static/compile-time allocation) — three main forms:

  1. Stack allocation — for variables whose lifetime follows the control structure of the program (automatic locals of a procedure, loop bodies). Allocated by moving a pointer, O(1), and released in exactly LIFO order when the block/procedure exits.
  2. Heap allocation — for data with a lifetime that is not controlled by the control structure: dynamic arrays sized at run time, nodes of linked structures that outlive the allocating scope (malloc/free, new/delete). Requires explicit or collected deallocation.
  3. Garbage collection — the runtime itself determines when heap objects are dead and reclaims them, so the programmer never deallocates.

Storage-allocation strategies compared:

StrategyBehaviourStrengthLimitation
StackLIFO, single top pointer, bounds checked on pushVery fast, O(1); automatic release; natural for recursionOnly works when lifetimes nest with the control structure; no dynamic scoping; fixed upper bound per procedure
HeapPool of free blocks; first/next-fit allocation at run timeSupports arbitrary lifetimes (dynamic arrays, graphs, strings built at run time)Slow (search for a block + bookkeeping); fragmentation; free must be called exactly once or leaked

Garbage collection fixes the "who frees it?" problem: reference counting keeps a count per object and frees it when it hits 0 (simple, but cyclic leaks and cost per access); mark-and-sweep periodically starts from the roots, marks reachable objects, then sweeps the rest (handles cycles, stops the world or runs in two passes). Heap + GC is the usual strategy for languages like Java; stack stays the default for ordinary automatic local variables.

3

Discuss the parameter-passing mechanisms with suitable examples: (a) call by value, (b) call by reference, (c) call by name, with a worked example where by-name changes the program result. Then the storage-allocation strategies: (a) stack allocation, (b) heap allocation, with snippets.

a) Call by value (copy semantics): the value of the actual argument is evaluated once at the call and copied into the formal parameter. The callee's modifications to the parameter are invisible to the caller — no side effects, no aliasing, safest and most common.

void inc(int x) { x = x + 1; }   // x is a copy
int main() { int a = 5; inc(a); printf("%d", a);  // prints 5 — a unchanged
}

b) Call by reference (pass by location): the callee receives the address of the actual variable; the formal and actual are aliases. The callee can modify the caller's variable — this is the mechanism for output parameters, but it also creates the aliasing danger:

void swap(int &p, int &q) { int t = p; p = q; q = t; }
swap(x, x);            // aliasing: p and q are the SAME place
                        // t = x; x = x; x = t  ->  no effect, not a swap
swap(x, x + 1);        // overlapping evaluation order -> undefined behaviour
Passing x and an expression of x mixes aliased lvalues; the same-variable call silently fails.

c) Call by name (lazy evaluation): the actual argument expression is substituted textually for the formal and re-evaluated every time the formal is used. It enables passing functions/expressions unevaluated, but re-evaluation can change the result:

// by-name: y and z are the EXPRESSION x, not its value
proc A(x)
  B(x, x)
A(4)
proc B(y, z)          // y, z formal-by-name
  y := 3
  z := y
end B
// global variable z is written

by value:  B copies x=4 for both y and z.
           y:=3  (writes the local copy);  z := y  ->  z = 4
by name:   y and z are both the expression "x".
           y := 3  substitutes x := 3  (x is now 3)
           z := y  substitutes z := x = 3  ->  z = 3
Different final value of z (4 vs 3) from one semantic choice.

Storage-allocation strategies:

// a) Stack allocation: LIFO, O(1) pointer move, lives with the control structure
int* p = stack_alloc(8 * 100);      // 800 bytes on the run-time stack
free(p);                             // released on scope exit — automatic

// b) Heap allocation: arbitrary lifetime, GC or explicit free needed
int* q = malloc(100 * sizeof(int));  // heap block, survives the caller's scope
free(q);                             // programmer's responsibility (or GC reclaims)

The stack is fast and automatic but supports only lifetimes that nest with the control structure; the heap is slower (free-list search + bookkeeping) but supports data that outlive the allocating procedure.

Module 9 Questions

★ Note: Questions on quadruples, triples & indirect triples ★
1

Translate the arithmetic expression 5 * a * (b + c) / d into (a) three-address code (temporaries t1…t4 shown) and (b) postfix notation.

a) Three-address code (TAC): each statement has at most three operands; every intermediate value is a temporary so that no address is reused before it is consumed. Operator precedence is honoured explicitly:

5 * a * ( b + c ) / d
--------------------------
t1 = b + c
t2 = 5 * a
t3 = t2 * t1
t4 = t3 / d
result = t4

Equivalent x86-style listing (target ISA: x86-64, EAX/EBX/ECX/EDX registers):

mov  ECX, 5
imul ECX, [a]          ; ECX = 5*a        (t2)
mov  EDX, [b]
add  EDX, [c]          ; EDX = b+c        (t1)
imul ECX, EDX          ; ECX = 5*a*(b+c)  (t3)
mov  EAX, ECX
idiv [d]               ; EAX = t3/d       (t4)  ; quotient in EAX, remainder EDX
mov [result], EAX

b) Postfix (reverse-Polish) notation: operands are listed left-to-right with each operator immediately following its operands; precedence is encoded by the ordering, so no parentheses are needed:

5 * a * (b + c) / d   -->    5 a * b c + * d /

Stack evaluation confirms it: 5 a * → t2; b c + → t1; * → t2*t1 = t3; d / → t3/d = t4. The postfix form is exactly what an interpreter or a stack machine executes — each operator pops its operands and pushes the result, which is why postfix code needs no precedence table and no parentheses.

2

Explain quadruples, triples and indirect triples; give a comparison table; represent x := (a + b) * c - d in all three forms; generate machine code for x := a + (b * c) - d; and state the properties of intermediate representations suitable for (a) indexed assignments, (b) pointer assignments, (c) conditional statements.

Quadruples: one tuple (op, arg1, arg2, result) per statement; the result is an explicit 4th field (a named temporary), so values go to a temporary first and move only at the end — easy to reorder and to CSE.

Triples: 3-tuples (op, arg1, arg2) — no result field; a triple's "value" is its position number, so later triples refer to it by index.

Indirect triples: a separate list of triple numbers gives the execution order; reordering during optimization edits only the list, and final code is produced by patching that list.

For x := (a + b) * c - d:

QUADRUPLES                  TRIPLES             INDIRECT TRIPLES
 #  op  arg1 arg2 res       # op  a1  a2        list (exec order)
 0  +   a    b    t1       0  +  a   b         [0, 1, 2, 3]
 1  *  t1    c    t2       1  *  1   c         patch to:
 2  -  t2    d    t3       2  -  1   d          [0, 1, 2, 3]
 3  =  t3   -    x         3  =  2   x        (reorder by rewriting
   temporaries t1 t2 t3    addr = position     the list only)

Machine code for  x := a + (b * c) - d   [simple 3-address ISA, ACC-based]
LDA   a        ; ACC = a
LOAD  b        ; R1 = b
MUL   c        ; R1 = b * c
ADD   R1       ; ACC = a + b*c
SUB   d        ; ACC = a + b*c - d
STA   x        ; x = ACC
FormFieldsKey advantage
Quadruple(op, arg1, arg2, result) + numberingExplicit result slot — temporaries named; easy to reorder and CSE
Triple(op, arg1, arg2), address-by-positionCompact; no temporaries needed; a reference is just the triple's index
Indirect triplelist of triple numbers + final patchingReordering/deletion edit only the list, not the table

Properties of IRs suitable for:

  • (a) Indexed assignments x[i] := e — the IR must express address computation (base + scale × index) as a first-class node; a DAG with an addr(x, i) node supports reusing it, and 3-AC needs an explicit temporary t = x + i*W before t := e.
  • (b) Pointer assignments p := q — the IR must carry type on every variable; a pointer lvalue means writing through the address, so aliasing must stay explicit; type-erasing arithmetic IRs are unsuitable.
  • (c) Conditional statements — use two-way branches (jump-if, else label) rather than unrestricted gotos, so control flow is structured; use a copy statement for non-scalar assignment.
  • DAG / IR advantages: CSE, strength reduction and redundancy checking all fall out of node sharing. Cost: per-block DAGs are O(n) with pointer overhead; whole-program DAGs are rarely used — cross-block dataflow makes them expensive.
3

What is backpatching? Give a worked mini-example (L1/L2 list patches for the code of if x < 10 goto L, showing next/prev fields). What are the issues in the design of a code generator?

Backpatching: when the code generator emits a jump whose target is not yet known (a forward branch), it writes the instruction with a placeholder target and records the instruction's address in a backpatch list. When the target is finally reached, the recorded addresses are patched — the placeholder is filled in with the true address. Each list entry stores the address of the instruction to patch plus next and prev links (a doubly-linked list) so old and new addresses can be appended at either end in O(1).

Worked example — statement if (x < 10) goto L plus an else fall-through body:

Code generated so far (jump targets are still "?"):
addr  instruction                    L1 list            L2 list
----  -----------------------------  --------           --------
  0   jump-if-true   x  10   ?      [0]                []
  1   jump           _  _    L      [0]                [1]   (patch #1 when L known)
  2   [ body of "if x < 10" ]
  3   [ else body ]
  4   [ code after the if-then-else ]

Patching step by step:
 backpatch(L1, 4):  the true branch targets addr 4
                    list entry #0:  next = NULL,  prev = NULL,  patch_addr = 4
                    code line 0 becomes:  jump-if-true x 10 4
 backpatch(L2, 3):  the else (fall-through) targets addr 3
                    list entry #1:  next = NULL,  prev = #0,  patch_addr = 3
                    code line 1 becomes:  jump _ _ 3
After both patches every jump has a real target; the
L1/L2 lists are empty and released.

Issues in code-generator design:

  1. Quality of generated code — the generator must be correct: the machine code's input-output behaviour must exactly match the source, even after aggressive transformations.
  2. Register allocation — deciding which values live in which registers, what spills to memory, and where spills occur; naive one-value-one-register is far from optimal; dynamic allocation with liveness is much better.
  3. Addressing-mode selection — choosing base-pointer, scaled-index, immediate or memory operands to minimize instruction count and memory references.
  4. Memory ordering and access patterns — respecting side effects (an lvalue must be evaluated where it may have effects) and minimizing loads/stores through the memory hierarchy.
  5. Code size vs speed — small code (shorter instruction count, fewer branches) vs fast code (more registers, more instructions); targets differ: embedded vs desktop.
  6. Machine-specific knowledge — the generator encodes the calling convention, data-type support, branch targets, and alignment requirements of the target ISA.
  7. Preserving semantics under optimization — every optimization must be provably meaning-preserving; the correctness criteria are the same as for optimization (same I/O on all inputs).
4

What are the properties of an efficient code generator? Discuss the optimization levels (local vs global vs interprocedural) briefly.

Properties of an efficient code generator:

  1. Correctness — the generated program must have exactly the same observable behaviour as the source for every input; no transformation may change lvalue evaluation order, side effects, or I/O order.
  2. Fast machine code — exploit the machine's addressing modes, use registers for frequently referenced values, minimize memory references, and choose branch targets that are usually taken (profile feedback when available).
  3. Short code — minimize instruction count where it does not hurt speed; important on cache-limited or embedded targets.
  4. Effective register allocation — keep hot values in registers; spill only what must live; a good allocator can beat a bad one by a wide margin.
  5. Minimum memory references — keep loop-carried values in registers across iterations; avoid reloading invariants inside loops.

Optimization levels:

LevelScopeTypical transformations
Localone basic block / statementconstant folding, common subexpression elimination, strength reduction, peephole patterns, copy propagation
Global (intra-procedural)whole procedure / flow graphloop-invariant code motion, dead-code elimination, induction-variable substitution, loop unrolling / jamming
Interproceduralacross call sites / whole programfunction inlining (removes call overhead, exposes more dataflow), argument duplication, partial evaluation of known calls

Local transformations are cheapest and run in the same pass as code generation; global transformations require data-flow analysis over the control-flow graph (liveness, reaching definitions, available expressions) and yield the biggest gains on loops; interprocedural analysis is the most powerful but the most expensive (the call graph can be large, inlining can blow up code size, and correctness across program boundaries must be preserved by respecting calling conventions and side effects).

Module 10 Questions

★ Note: Questions on flow graph for code ★
1

Construct the DAG for the code block d := b*c; e := a+b; b := e*c; c := e-d — walk it through (shared subexpressions, node list, then the DAG as a node/edge table). What is a basic block? What is code optimization and how is it achieved (correctness criteria + levels)?

DAG construction, statement by statement:

Statements:
 S1: d := b * c
 S2: e := a + b
 S3: b := e * c
 S4: c := e - d

Walk (live inputs: a, b, c; a node may be reused, an
old value is killed when its name is redefined):
 S1:  N1 = b * c          ; d gets N1
 S2:  N2 = a + b          ; e gets N2        (b reused from N1's inputs)
 S3:  N3 = N2 * c         ; b gets N3        (kills original b)
 S4:  N4 = N2 - N1        ; c gets N4        (kills original c;
                                               N1 and N2 both reused - shared subexprs)

NODE TABLE
 #   expression   value feeds
 N1  b * c        d, and N4
 N2  a + b        e, and N3, and N4
 N3  N2 * c       b
 N4  N2 - N1      c

EDGE TABLE (DAG edges)
 N1 --> N4      N2 --> N3      N2 --> N4      leaves: a,b,c --> N1,N2

DAG (root = N4):
        c          N3 = N2*c      b := N3
        ^
        |
   b - N1 = b*c ---+
        ^
        |
   a - N2 = a+b ---+---- N4 = N2-N1   c := N4

Shared subexpressions that CSE removes: a+b feeds e, e*c and e-d (reused as N2); b*c feeds d and e-d (reused as N1). After CSE every expression is computed exactly once: N1 = b*c; N2 = a+b; N3 = N2*c; N4 = N2-N1;

Basic block: a maximal straight-line sequence of code with a single entry at the top and a single exit at the bottom — no branches, jumps, labels, or stops inside. Blocks are found by identifying leaders: (1) the first statement of the procedure; (2) any statement that is the target of a jump; (3) any statement immediately after a jump or conditional. Each leader starts a new block and runs to the next leader (or the end).

Code optimization = transforming a correct program into a faster / smaller / more memory-efficient one. Correctness criteria: (1) for every input the optimized program produces the same output; (2) the relative order of I/O is preserved; (3) no side-effecting lvalue is evaluated at a different point. Levels: local (block/peephole), global (whole procedure, loop-level dataflow), interprocedural (across call sites, inlining).

2

What is peephole optimization (with a rules table)? What are dead code elimination, variable elimination, code motion, and reduction in strength?

Peephole optimization: look at a short "window" of adjacent instructions (the peephole) and apply a set of pattern-substitution rules that simplify the local code. It is the cheapest form of optimization — no data-flow analysis, just local algebra on the instruction stream.

PatternReplacementRationale
x + 0xidentity
x * 1xidentity
x * 00annihilation
x - 0xidentity
x - x0difference of identical operands
-( -x )xdouble negation cancels
x + x2 * xstrength reduction: add to multiply
LOAD x; LOAD xdelete oneredundant load
STORE x, v; LOAD x with no intervening write to xv (a register/temp)redundant store-load pair

Dead code elimination: remove code that cannot affect the observable output. Two forms: (1) dead assignments — v := e where v is never read again before being redefined (v is "dead" at that point); (2) unreachable code — statements after an unconditional jump, or inside a condition that can never be true. Both require liveness / reachability information.

Variable elimination: replace every use of a variable with the expression that defined it (generalised copy propagation), provided no side effect is lost: the defining expression must be side-effect-free, and v must not be an lvalue anywhere (no &v, no array-of-pointers where v is an element). It collapses a variable into its value and exposes further optimizations like CSE.

Code motion: move code to a point where it is executed less often without changing semantics. The principal case is loop-invariant code motion: an expression whose value does not change inside the loop is moved before the loop. Legality conditions — all must hold: (1) the value of every operand is invariant over the loop body; (2) no operand's address is modified inside the loop (aliasing); (3) the operand is not the loop's induction variable; (4) evaluation order of side-effecting lvalues is preserved.

for (i = 0; i < n; i++)          for (i = 0; i < n; i++)
  a = a[i] + b + 1;                 a = a[i] + t;
                                   t = b + 1;              // moved out (invariant)

Reduction in strength: replace an expensive operator with a cheaper one computing the same value: multiplication → addition (x*x → 2*x when x is a power of 2), division by a power of 2 → right shift (x/8 → x >> 3 for unsigned), repeated addition → induction variable, pow(2,k) → 1 << k.

3

What is meant by redundant load/store statements? Explain with examples: (a) constant folding, (b) common sub-expression elimination, (c) loop unrolling, (d) loop jamming, (e) copy propagation — each with a short before/after.

Redundant load/store: a LOAD instruction that fetches a memory value which is already known (because the last store to that location is visible in the same window and the location has not been written since) is redundant; similarly a STORE followed by a LOAD of the same value with no intervening write is a redundant pair. The optimizer substitutes the known value for the load and deletes the store if the value is not otherwise needed:

before:  v = x + 1;  x = v;  y = x;       after:  v = x + 1;  y = v;  x = v;
(2 loads and 1 store collapsed; x's load deleted because v is live)

(a) Constant folding: evaluate an arithmetic expression whose operands are all compile-time constants, and replace it with the result:

before:  x = 2 + 3;          after:  x = 5;
        a = b * 4;          after:  a = b << 2;   (strength reduction folds too)

(b) Common subexpression elimination: if an expression e is computed, its value stored in a temporary t, and t has not been redefined, then every subsequent occurrence of e is replaced by t:

before:  t1 = a + b;  c = t1;  d = a + b;     after:  t1 = a + b;  c = t1;  d = t1;
(uses reaching-definitions analysis to know t1 still holds a+b)

(c) Loop unrolling: replicate the loop body k times and adjust the induction variable, to reduce branch and loop-control overhead:

before:  for (i = 0; i < 4; i++)  s = s + a[i];
after:   s = s + a[0]; s = s + a[1]; s = s + a[2]; s = s + a[3];
        (4 iterations, 3 fewer branch checks)

(d) Loop jamming: two (or more) loops that iterate over the same array at the same index are merged into one — the array element is loaded once instead of twice, halving memory traffic:

before:                              after:
for i:  a[i] = b[i] + c[i];        for i:  t  = b[i] + c[i];
for i:  d[i] = a[i] * 2;                 a[i] = t;
                                      d[i] = t * 2;
                                  (a[i] stored then re-loaded: eliminated;
                                   one pass, half the I/O)

(e) Copy propagation: replace uses of a variable with the value that was assigned to it, provided the variable is not an lvalue and the assigned expression has no side effect. It makes CSE and dead-code elimination possible:

before:  y = a;  x = y;  z = y + 1;      after:  x = a;  z = a + 1;
                                          (y's definition is now dead -> deleted)

y = a becomes a dead assignment — y is never used after propagation — so the compiler deletes it and both x and z read a directly: the classic pipeline copy propagation → CSE → dead-code elimination.