TIMED REVISION · 1-MINUTE PANIC SHEETS

Compiler Design 10-Minute Rapid Revision

For the last few minutes before the exam hall: one core rule per topic, the formulas you must remember, and the traps that cost marks.

PANIC SHEET 01 · Lexical Analysis, Tokenization & Finite Automata

Lexical Tokens, Buffer Pairs & Finite Automata Scanning

Full Lesson →
CORE INVARIANT ANCHOR:

“Lexical analyzers strip whitespace and comments, group characters into tokens, and communicate with the symbol table using (token_name, attribute_pointer).”

Must-Remember Principles:
  • —Tokens per string literal = 1 (enclosed contents are treated as a single token attribute).
  • —Operators like '++' or '>=' are single multi-character tokens, not pairs of individual symbols.
  • —Buffer size 2N with sentinels reduces loop branches by half.
Critical Exam Pitfalls:
  • —Do not count header files `#include <stdio.h>` as compiler tokens if the preprocessor runs before the lexer.
  • —Lexer cannot detect undeclared variables or syntax errors.
PANIC SHEET 02 · Lexical Analysis, Tokenization & Finite Automata

Token Specification, Regular Expressions to Lexical DFA & Longest Match

Full Lesson →
CORE INVARIANT ANCHOR:

“Lexical rules use Regular Expressions converted via Thompson's NFA to minimal DFA. Conflicts are resolved by: (1) Longest Match (Maximal Munch) and (2) First Rule Priority for equal-length matches.”

Must-Remember Principles:
  • —Maximal Munch (Longest Match): The scanner always matches the longest prefix of remaining input that corresponds to a valid token (e.g., `===` is tokenized as `==` and `=`, not three `=` tokens).
  • —Keyword vs Identifier: A keyword like `while` matches the regular expression for identifiers `[a-zA-Z][a-zA-Z0-9]*`. The lexer disambiguates by testing against a reserved keyword hash table or placing keyword patterns first in rule order.
  • —Thompson's Construction: Creates an NFA with at most $2|r|$ states and at most $4|r|$ transitions for a regular expression of length $|r|$.
  • —DFA Subset Construction: Converts NFA with $n$ states to DFA with at most $2^n$ states (though practical programming language token DFAs have linear state counts).
  • —Hopcroft's DFA Minimization: Partitions state space into equivalence groups, separating accepting states from non-accepting states in $O(k cdot n log n)$ time.
Critical Exam Pitfalls:
  • —Floating point regular expressions require care: `[0-9]+(\.[0-9]+)?` requires digits on both sides of decimal point. If empty decimal is permitted, parentheses and question marks must be structured to avoid matching a lone dot.
  • —Maximal munch can cause lexical errors on valid programs: e.g., in early C++, `vector<vector<int>>` was scanned as `>>` (right-shift operator) instead of two nested template brackets.
PANIC SHEET 03 · Top-Down Syntax Analysis & LL(1) Parsing

FIRST & FOLLOW Computation, Left Recursion & Factoring

Full Lesson →
CORE INVARIANT ANCHOR:

“Top-down parsers construct derivations from the root down. They require grammars without left recursion or common prefixes. FIRST(alpha) is the set of terminals starting alpha; FOLLOW(A) is the set of terminals immediately trailing non-terminal A.”

Must-Remember Principles:
  • —Immediate Left Recursion Elimination: Production $A \to A\alpha_1 \mid A\alpha_2 \mid \dots \mid \beta_1 \mid \beta_2$ (where no $\beta_i$ starts with $A$) transforms to: $A \to \beta_1 A' \mid \beta_2 A'$, and $A' \to \alpha_1 A' \mid \alpha_2 A' \mid \epsilon$.
  • —General (Indirect) Left Recursion: Order non-terminals $A_1, A_2, \dots, A_n$. For $i = 1$ to $n$, for $j = 1$ to $i-1$, replace $A_i \to A_j \gamma$ with productions substituting $A_j$'s expansions, then eliminate immediate left recursion on $A_i$.
  • —Left Factoring: $A \to \alpha\beta_1 \mid \alpha\beta_2$ transforms to $A \to \alpha A'$ and $A' \to \beta_1 \mid \beta_2$.
  • —FIRST Set Rules: (1) If $X$ is terminal, $\text{FIRST}(X) = \{X\}$. (2) If $X \to \epsilon$, $\epsilon \in \text{FIRST}(X)$. (3) For $X \to Y_1 Y_2 \dots Y_k$, add $(\text{FIRST}(Y_1) - \{\epsilon\})$ to $\text{FIRST}(X)$. If $Y_1 \Rightarrow^* \epsilon$, add $(\text{FIRST}(Y_2) - \{\epsilon\})$, continuing until some $Y_i$ is not nullable. If all $Y_1 \dots Y_k \Rightarrow^* \epsilon$, add $\epsilon$ to $\text{FIRST}(X)$.
  • —FOLLOW Set Rules: (1) Add $\$$ to $\text{FOLLOW}(S)$ where $S$ is the start symbol. (2) For $A \to \alpha B \beta$, add $(\text{FIRST}(\beta) - \{\epsilon\})$ to $\text{FOLLOW}(B)$. (3) If $A \to \alpha B$ or $A \to \alpha B \beta$ where $\beta \Rightarrow^* \epsilon$, add $\text{FOLLOW}(A)$ to $\text{FOLLOW}(B)$.
Critical Exam Pitfalls:
  • —Epsilon ($\epsilon$) can NEVER belong to any FOLLOW set under any circumstance.
  • —When computing $\text{FOLLOW}(B)$ from $A \to \alpha B \beta$, do NOT add $\text{FOLLOW}(A)$ unless $\beta \Rightarrow^* \epsilon$ (or $\beta$ is completely absent).
  • —Left-recursive grammars can NEVER be LL(1) because the parser enters an infinite loop predicting the same non-terminal.
PANIC SHEET 04 · Top-Down Syntax Analysis & LL(1) Parsing

LL(1) Predictive Parsing Table Construction & Conflict Analysis

Full Lesson →
CORE INVARIANT ANCHOR:

“A grammar is LL(1) iff its predictive parsing table M[A, a] contains NO cell with more than one production. Ambiguous grammars, left-recursive grammars, and improperly factored grammars are NEVER LL(1).”

Must-Remember Principles:
  • —LL(1) Theorem: A context-free grammar G is LL(1) if and only if for every pair of distinct productions A -> alpha | beta:
  • — 1. FIRST(alpha) and FIRST(beta) are disjoint: FIRST(alpha) ∩ FIRST(beta) = ∅.
  • — 2. At most one of alpha or beta can derive epsilon.
  • — 3. If beta =>* epsilon, then FIRST(alpha) ∩ FOLLOW(A) = ∅.
  • —Table Construction Algorithm:
  • — For each production A -> alpha in G:
  • — 1. For each terminal 'a' in FIRST(alpha), add A -> alpha to M[A, a].
  • — 2. If epsilon in FIRST(alpha), for each symbol 'b' in FOLLOW(A) (including $), add A -> alpha to M[A, b].
  • —Error Recovery in LL(1): If cell M[A, a] is blank, it indicates a syntax error. In 'panic mode', the parser skips input tokens until reaching a token in the SYNC set (typically chosen as FOLLOW(A)).
Critical Exam Pitfalls:
  • —If epsilon is in FIRST(alpha), the production A -> alpha is placed in columns corresponding to FOLLOW(A), NOT FIRST(A)!
  • —An ambiguous grammar can NEVER be LL(1) (or LR(k) for any k) because ambiguity means an input string has multiple leftmost derivations, forcing at least one parsing table cell to have multiple entries.
PANIC SHEET 05 · Bottom-Up Syntax Analysis & LR Parsers

Shift-Reduce Parsing Mechanics & LR(0) Canonical Items

Full Lesson →
CORE INVARIANT ANCHOR:

“Bottom-up parsers construct derivations in REVERSE of a Rightmost derivation. At each step, a 'Handle' on top of the stack is reduced to its LHS non-terminal.”

Must-Remember Principles:
  • —Handle: A substring beta in a right-sentential form alpha beta w such that replacing beta with A yields the preceding right-sentential form in the derivation (A -> beta).
  • —Viable Prefix: A prefix of a right-sentential form that does not extend past the right end of the handle.
  • —LR(0) Item: A production with a dot at some position on the RHS (e.g., A -> alpha . beta). The dot represents how much of the production has already been seen on the stack.
  • —Augmented Grammar: G' adds S' -> S so the parser halts and accepts when S' -> S . is reached.
  • —CLOSURE(I): (1) Every item in I is in CLOSURE(I). (2) If A -> alpha . B beta is in CLOSURE(I), add B -> . gamma for every production B -> gamma in G.
  • —GOTO(I, X): CLOSURE of all items A -> alpha X . beta such that A -> alpha . X beta is in I.
Critical Exam Pitfalls:
  • —A handle is NOT simply any substring matching a RHS production; it must be the exact substring whose reduction reconstructs the unique rightmost derivation.
  • —For epsilon production A -> epsilon, the only LR(0) item is A -> . (which is immediately ready for reduction).
PANIC SHEET 06 · Bottom-Up Syntax Analysis & LR Parsers

SLR(1) Parsing Tables & Conflict Resolution

Full Lesson →
CORE INVARIANT ANCHOR:

“SLR(1) uses the exact same states as LR(0), but places REDUCE actions ONLY in columns belonging to FOLLOW(A). If an LR(0) state has conflicts, SLR(1) resolves them if the lookahead sets are disjoint.”

Must-Remember Principles:
  • —LR(0) Table Action Rule: If item A -> alpha . is in state I_k, put 'reduce by A -> alpha' in ALL terminal columns of row k (including $).
  • —SLR(1) Table Action Rule: If item A -> alpha . is in state I_k, put 'reduce by A -> alpha' ONLY in columns 'a' where a in FOLLOW(A).
  • —Shift Action Rule (same for LR(0) and SLR(1)): If [A -> alpha . a beta] is in I_k and GOTO(I_k, a) = I_j, put 'shift j' in cell Action[k, a].
  • —Shift-Reduce (SR) Conflict: State contains [A -> alpha . a beta] and [B -> gamma .], and 'a' is an allowed reduce lookahead (for SLR(1), a in FOLLOW(B)).
  • —Reduce-Reduce (RR) Conflict: State contains [A -> alpha .] and [B -> beta .], and FOLLOW(A) ∩ FOLLOW(B) ≠ ∅.
Critical Exam Pitfalls:
  • —LR(0) grammars CANNOT have any epsilon productions unless the non-terminal derives ONLY epsilon and never shifts.
  • —If a state contains a completed item A -> alpha . and a shift item B -> beta . a gamma, it is an LR(0) conflict. But it is ONLY an SLR(1) conflict if 'a' belongs to FOLLOW(A).
PANIC SHEET 07 · Bottom-Up Syntax Analysis & LR Parsers

CLR(1) vs LALR(1) Parsing Tables & State Merging Theorems

Full Lesson →
CORE INVARIANT ANCHOR:

“CLR(1) (Canonical LR) splits states by exact 1-token lookaheads. LALR(1) merges CLR(1) states having identical LR(0) cores. Merging NEVER creates new Shift-Reduce conflicts, but MAY create Reduce-Reduce conflicts.”

Must-Remember Principles:
  • —LR(1) Item Structure: [A -> alpha . beta, a] where 'a' is a terminal or $. Reduction to A is valid ONLY when the lookahead is exactly 'a'.
  • —State Counts Equality: Number of States: |LR(0)| = |SLR(1)| = |LALR(1)| <= |CLR(1)|.
  • —LALR(1) Core Definition: The core of an LR(1) state is its set of LR(0) items without the lookahead components.
  • —LALR(1) State Merging Theorem (SR Conflicts): Merging two CLR(1) states with identical cores can NEVER introduce a Shift-Reduce conflict. Proof: If a merged state had an SR conflict on 'a', one original state had [A -> alpha ., a] and the other had [B -> beta . a gamma, b]. But since both states have the identical core, the shift item [B -> beta . a gamma, ...] existed in the first state too, meaning the SR conflict already existed in CLR(1)!
  • —LALR(1) State Merging Theorem (RR Conflicts): Merging CAN combine lookaheads of two distinct reduce items [A -> alpha ., a] and [B -> beta ., b] from different states, producing an RR conflict if their combined lookahead sets intersect.
Critical Exam Pitfalls:
  • —If a grammar is LALR(1), it is GUARANTEED to be CLR(1). But if it is CLR(1), it might NOT be LALR(1) due to potential RR conflicts.
  • —LALR(1) parsing tables are vastly smaller than CLR(1) tables (typically 10x smaller for real programming languages like C or Java), which is why real parser generators (Yacc, Bison) use LALR(1).
PANIC SHEET 08 · Syntax-Directed Translation & Intermediate Code Generation

Syntax-Directed Definitions: S-Attributed vs L-Attributed Systems

Full Lesson →
CORE INVARIANT ANCHOR:

“S-attributed definitions use ONLY synthesized attributes and evaluate bottom-up during LR parsing. L-attributed definitions permit synthesized and inherited attributes from parent and left siblings ONLY, evaluating in a single depth-first pass.”

Must-Remember Principles:
  • —Synthesized Attribute: Computed from attribute values of children nodes in the parse tree (or lexical values for terminals).
  • —Inherited Attribute: Computed from attribute values of parent node and/or sibling nodes.
  • —S-Attributed SDD: Contains ONLY synthesized attributes. Can be implemented naturally by augmenting the LR parser stack with an extra value field.
  • —L-Attributed SDD: For production A -> X_1 X_2 ... X_n, an inherited attribute of X_j can depend ONLY on: (1) Inherited attributes of parent A, and/or (2) Synthesized or inherited attributes of left siblings X_1, X_2, ..., X_{j-1}.
  • —Crucial Theorem: Every S-attributed definition is automatically an L-attributed definition (since the set of inherited attributes in an S-attributed SDD is empty).
  • —Syntax-Directed Translation Scheme (SDT): A context-free grammar with embedded semantic actions { ... } enclosed in curly braces indicating exact execution order.
Critical Exam Pitfalls:
  • —In an L-attributed SDD, an inherited attribute can NEVER depend on an attribute of a RIGHT sibling or on a synthesized attribute of the parent.
  • —Actions in an S-attributed SDT are placed STRICTLY at the end of productions (e.g., A -> alpha { action }).
PANIC SHEET 09 · Syntax-Directed Translation & Intermediate Code Generation

Intermediate Representations: Three-Address Code, SSA & Forms

Full Lesson →
CORE INVARIANT ANCHOR:

“Intermediate representations decouple machine-independent front-ends from machine-dependent back-ends. Three-Address Code (TAC) allows at most one operator on the RHS of each statement.”

Must-Remember Principles:
  • —Three-Address Code (TAC): Linear instruction sequence of form: `x = y op z`, `x = op y`, `x = y`, `goto L`, `if x relop y goto L`.
  • —Quadruples: Record structure with 4 fields: `(op, arg1, arg2, result)`. Explicit temporary variables appear in the result field.
  • —Triples: Record structure with 3 fields: `(op, arg1, arg2)`. Results of operations are referenced implicitly by instruction index `(i)`. Avoids temporary variable names but complicates instruction reordering during optimization.
  • —Indirect Triples: Uses an array of pointers to Triples. Optimization reorders the pointer array without moving the underlying triple records.
  • —Static Single Assignment (SSA) Form: Every variable is defined (assigned) exactly ONCE in the entire program text. Merging execution paths use phi-functions: `x_3 = phi(x_1, x_2)`.
  • —Array Offset Formula in TAC: For 2D row-major array $A[N_1][N_2]$ with element size $w$: $\text{Offset} = (i \times N_2 + j) \times w$. Base address $A[i][j] = \text{Base}(A) + \text{Offset}$.
Critical Exam Pitfalls:
  • —In Triples, do NOT invent temporary variable names ($t_1, t_2$); use pointer indices $(0), (1)$ to refer to earlier results.
  • —SSA requires a phi-function at any basic block where two or more reaching definitions of the same source variable converge.
PANIC SHEET 10 · Code Optimization & Runtime Environments

Basic Blocks, Control Flow Graphs, DAGs & Loop Optimizations

Full Lesson →
CORE INVARIANT ANCHOR:

“Basic Blocks enter at the first instruction and exit at the last without branching in between. Control Flow Graphs model program execution flow. DAGs eliminate local common subexpressions.”

Must-Remember Principles:
  • —Leader Selection Algorithm (3 Rules):
  • — 1. Instruction 1 (first statement) is a leader.
  • — 2. Any target instruction of a conditional or unconditional jump is a leader.
  • — 3. Any instruction immediately following a conditional or unconditional jump is a leader.
  • —Basic Block Construction: A basic block starts at a leader and includes all instructions up to (but not including) the next leader or the end of the program.
  • —DAG for Basic Blocks: Leaves represent initial variable values. Interior nodes represent operators. Identical expressions share the same interior node (Common Subexpression Elimination).
  • —Loop-Invariant Code Motion: Hoisting expressions whose operand values do not change inside the loop body outside to a preheader.
  • —Induction Variable Elimination & Strength Reduction: Replaces expensive operations (e.g., multiplication `t = i * 4` in a loop where `i` increments by 1) with inexpensive operations (`t = t + 4`).
  • —Activation Records (Stack Frames): Contains Local variables, Temporary variables, Machine status (saved registers, Program Counter), Dynamic Link (control link to caller's frame), Static Link (access link to lexical enclosing scope), and Return value.
Critical Exam Pitfalls:
  • —Do NOT forget Rule 3: The instruction immediately AFTER a goto is ALWAYS a leader, even if it is not targeted by any jump.
  • —Static link is used for accessing non-local variables in nested lexical scopes; dynamic link points to the caller's activation record for stack unwinding.