Docsity

Compiler Design Complete Study Material | Dragon Book Based | Exam notes, Summaries of Compiler Design

Toggle sidebar
bg1
COMPILER DESIGN | 22CS1106 | COMPLETE STUDY MATERIAL Page 1
Based on: Aho, Lam, Sethi, Ullman — Compilers: Principles, Techniques & Tools (Dragon Book) 2nd Ed.
COMPILER DESIGN
Course Code: 22CS1106
COMPLETE EXAM-READY STUDY MATERIAL
Based on: Aho, Lam, Sethi & Ullman — Dragon Book 2nd Edition
Units I – V | Full Long-Answer Coverage | 10–15 Mark Level
COURSE OUTCOMES
CO1: Classify various phases of compiler.
CO2: Apply parsing techniques for a given grammar.
CO3: Illustrate various Syntax Directed Translation Schemes.
CO4: Model SDDs using Intermediate Representations.
CO5: Use algorithms to generate code for a target machine.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27

Partial preview of the text

Download Compiler Design Complete Study Material | Dragon Book Based | Exam notes and more Summaries Compiler Design in PDF only on Docsity!

COMPILER DESIGN

Course Code: 22CS

COMPLETE EXAM-READY STUDY MATERIAL

Based on: Aho, Lam, Sethi & Ullman — Dragon Book 2nd Edition

Units I – V | Full Long-Answer Coverage | 10–15 Mark Level

COURSE OUTCOMES

CO1: Classify various phases of compiler.

CO2: Apply parsing techniques for a given grammar.

CO3: Illustrate various Syntax Directed Translation Schemes.

CO4: Model SDDs using Intermediate Representations.

CO5: Use algorithms to generate code for a target machine.

UNIT I: INTRODUCTION TO COMPILING & LEXICAL

ANALYSIS

TOPIC 1: OVERVIEW OF COMPILERS AND PHASES OF A

COMPILER

u 1. INTRODUCTION

A compiler is a special program that translates a source program written in a high-level programming language (such as C, C++, or Java) into an equivalent target program in a low-level language (assembly code or machine code) that a computer can execute directly. The compiler does not just convert syntax; it must preserve the exact meaning (semantics) of the original program while producing efficient target code.

Compilers are among the most sophisticated software tools ever created. Understanding compiler design gives deep insight into programming languages, machine architecture, and software optimization. The theoretical foundations draw from formal language theory, automata theory, and algorithm design.

Pre-requisites: Familiarity with at least one programming language, basic data structures, and concepts from Theory of Computation (automata, regular expressions, context-free grammars).

u 2. COMPILER vs INTERPRETER

Both compilers and interpreters process source code, but in fundamentally different ways. A compiler reads the entire source program, translates it completely into target code, and the target code is then executed separately. An interpreter , by contrast, reads and executes the source program statement by statement without producing a separate target program.

Feature Compiler Interpreter Translation Entire program at once Line by line

Execution Speed Faster (pre-compiled) Slower (runtime translation)

Error Detection All errors before run Stops at first error

Output Separate object/executable file No separate output file

Examples GCC (C/C++), javac Python, Ruby, BASIC

u 3. DETAILED EXPLANATION — PHASES OF A COMPILER

An essential function of the compiler is to record the variable names used in the source program and collect information about various attributes of each name. The symbol table is a data structure containing a record for each variable name with fields for the attributes of the name such as its type, scope, memory location, and number of arguments. It is created during lexical analysis and used/updated by all subsequent phases.

n Error Handler

Each phase can encounter errors. The error handler must deal with each error in a way that allows compilation to proceed, permitting more errors to be detected. A compiler should report meaningful error messages , then recover and continue processing to find additional errors. Error recovery strategies include: panic mode (skip tokens until a synchronizing token is found), phrase-level recovery, and error productions.

u 4. DIAGRAM — PHASES OF A COMPILER

SOURCE PROGRAM | v +------------------+ | LEXICAL ANALYZER | <-- Phase 1 (Tokens) +------------------+ | v +------------------+ | SYNTAX ANALYZER | <-- Phase 2 (Parse Tree) +------------------+ | v +--------------------+ | SEMANTIC ANALYZER | <-- Phase 3 (Annotated Tree) +--------------------+ | v +---------------------------+ | INTERMEDIATE CODE GEN. | <-- Phase 4 (Three-Addr Code) +---------------------------+ | v +--------------------+ | CODE OPTIMIZER | <-- Phase 5 (Optimized IR) +--------------------+ | v +--------------------+ | CODE GENERATOR | <-- Phase 6 (Target Code) +--------------------+ | v TARGET MACHINE CODE

[Symbol Table] <----> All Phases [Error Handler] <---> All Phases

u 5. WORKED EXAMPLE — TRACING ALL PHASES

Consider the source statement: position = initial + rate * 60

Phase Output / Action Lexical Analysis (id,1) = (id,2) + (id,3) * (60) — 7 tokens generated

Syntax Analysis Parse tree built: assign → id = expr → id + (id * num)

Semantic Analysis Type check: 60 (int) coerced to 60.0 (float); tree annotated

Intermediate Code t1=inttofloat(60); t2=id3*t1; t3=id2+t2; id1=t

Code Optimization t1=id3*60.0; id1=id2+t1 (inttofloat removed, t3 eliminated)

Code Generation LDF R2,id3; MULF R2,R2,#60.0; LDF R1,id2; ADDF R1,R1,R2; STF id1,R

u 6. BOOTSTRAPPING

Bootstrapping refers to the technique of writing a compiler for a language in that same language itself. The term comes from the phrase 'pulling oneself up by one's own bootstraps,' which seems paradoxical at first — how can you compile a compiler written in its own language if the compiler doesn't exist yet?

The process is carried out in stages. First, a simple subset of the language is implemented using another existing compiler or an interpreter. This is called the T-diagram approach or Tombstone diagram. The T-diagram notation represents a compiler for language S to T, written in language L as: S→T (written in L).

Bootstrap Process Steps: (1) Write a compiler C1 for a subset of language L, using an existing language M. (2) Use C1 to compile a more complete compiler C2 written in the subset of L. (3) Use C to compile a full compiler C3 written in full L. Now C3 is a self-hosting compiler.

Practical Example: The original C compiler was written in assembly, then rewritten in C itself. GCC (GNU Compiler Collection) is written in C and compiles itself. Java compilers are compiled using existing Java compilers.

u 7. ADVANTAGES AND DISADVANTAGES OF COMPILERS

ADVANTAGES DISADVANTAGES 3 Produces fast executable code — runs without translation overhead

7 Compilation step adds delay to development cycle

3 Errors detected before execution — safer deployment

7 Platform-specific code — not portable without recompilation

3 Code optimization possible — more efficient output

7 Harder to debug compiled code

TOPIC 2: LEXICAL ANALYSIS

u 1. INTRODUCTION

Lexical analysis is the first phase of a compiler. It reads the stream of characters from the source program and produces a sequence of tokens as output. The component that performs lexical analysis is called the lexical analyzer (also called the lexer or scanner ). The lexical analyzer is invoked by the parser on a 'get-next-token' call. It strips out whitespace and comments, which are not significant to the parse.

Lexical analysis simplifies the parser's job by eliminating irrelevant details. It handles machine-dependent features such as input devices, character sets, and line endings, insulating the rest of the compiler from these concerns.

u 2. KEY TERMINOLOGY

Term Definition Example Token A (name, attribute) pair representing a lexical unit

(id, position), (relop, <=)

Pattern A rule describing the form a lexeme can take (RegEx)

letter(letter|digit)*

Lexeme The actual character sequence matched by the pattern

position, <=, 3.

Alphabet A finite set of symbols used by the language

{a-z, A-Z, 0-9, +, *, ...}

Example: In the statement if (x >= 10) , the tokens are: (keyword, if), (punctuation, '('), (id, x), (relop, >=), (number, 10), (punctuation, ')').

u 3. ROLE OF THE LEXICAL ANALYZER

  • Read input characters one at a time and group them into lexemes.
  • Return the next token to the parser when requested via get-next-token.
  • Strip whitespace (spaces, tabs, newlines) and comments from the input.
  • Expand macros (in some implementations, e.g., C preprocessor).
  • Maintain the line count for error reporting.
  • Interact with the symbol table: insert identifier names during scanning.

u 4. INPUT BUFFERING

To handle lookahead efficiently, lexical analyzers use a two-buffer scheme. Each buffer holds N characters (typically N = 4096, one disk block). Reading is done from the current buffer. When the

lexer reaches the end of one buffer, the other buffer is refilled from the input. Two pointers are used:

  • lexemeBegin : marks the beginning of the current lexeme being scanned.
  • forward : advances through the input until a match is found; then the lexeme is extracted between lexemeBegin and forward.

A sentinel character (eof) is placed at the end of each buffer to signal the end of the buffer without requiring an explicit test in the inner loop, making scanning faster.

n Two-Buffer Scheme Diagram Buffer 1 Buffer 2 +----------------------------+ +----------------------------+ | E | = | M | * | C | * | * | eof |. |.. source... | eof | +----------------------------+ +----------------------------+ ^ ^ lexemeBegin forward

u 5. SPECIFICATION OF TOKENS — REGULAR EXPRESSIONS

Regular expressions provide a concise and flexible means of specifying patterns for tokens. A regular expression is built from an alphabet using the following operations:

Operation Notation Meaning Union r | s Any string in L(r) or L(s)

Concatenation rs Any string in L(r) followed by string in L(s)

Kleene Star r* Zero or more repetitions of strings in L(r)

Plus r+ One or more repetitions (r+ = rr*)

Optional r? Zero or one occurrence (r? = r | ε)

Grouping (r) Parentheses for grouping

n Examples of Regular Expressions for Tokens

  • Integer literal: [0-9]+ or digit+ where digit = [0-9]
  • Identifier: letter(letter | digit)* where letter = [a-zA-Z_]
  • Real number: digit+.digit+ or digit+(. digit+)?(E(+|-)?digit+)?
  • Relational operator: < | > | <= | >= | == | !=
  • Keyword (if): i f (exact match, higher priority than identifier)

u 6. REGULAR DEFINITIONS

A regular definition allows us to give names to regular expressions and use those names in subsequent expressions. This makes complex patterns more readable. The format is: name → regular expression.

digit → [0-9] digits → digit+ letter → [a-zA-Z_] id → letter ( letter | digit )*

%% int main() { yylex(); return 0; }

Key Lex variables: yytext holds the matched lexeme string; yyleng holds its length; yylval holds the token value for the parser; yylex() is the main lexer function called by the parser.

n How Lex Works Internally

  • Lex converts the regular expressions in the specification into a Non-deterministic Finite Automaton (NFA).
  • The NFA is converted into a Deterministic Finite Automaton (DFA) using the subset construction algorithm.
  • The DFA is minimized and encoded as a transition table in the generated C code.
  • At runtime, the lexer simulates the DFA on input characters to identify tokens.
  • When multiple patterns match, Lex uses: (1) Longest match rule — choose the longest lexeme; (2) Rule priority — if tie, choose the first rule listed.

u 9. NFA TO DFA — SUBSET CONSTRUCTION (BRIEF)

An NFA may have multiple transitions on the same input symbol and epsilon (ε) transitions. A DFA has exactly one transition per state per input symbol. The subset construction algorithm converts NFA to DFA: each DFA state corresponds to a set of NFA states. Starting from the ε-closure of the start state, new DFA states are computed by finding which sets of NFA states are reachable on each input symbol. A DFA state is accepting if any of its NFA states is accepting.

u 10. ADVANTAGES AND DISADVANTAGES OF LEXICAL ANALYSIS TOOLS

ADVANTAGES DISADVANTAGES 3 Lex/Flex automates scanner generation — saves developer time

7 Regular expressions cannot describe nested structures

3 Regular expressions are well-understood and formally defined

7 Generated scanners may be large for complex token sets

3 DFA-based scanners are very fast — O(n) in input length

7 Debugging Lex programs can be tricky

3 Separating lexical analysis from parsing improves modularity

7 Cannot handle context-sensitive tokenization easily

3 Easy to modify token rules without touching the parser

7 Lex-generated code may not be as readable as hand-written scanners

u 11. APPLICATIONS

  • Every compiler and interpreter uses a lexical analyzer as its front-end scanner.
  • Text editors use lexical analysis for syntax highlighting.
  • Search tools (grep, awk) use regular expression matching — same theory.
  • Network packet analyzers parse protocol headers using token patterns.
  • HTML/XML parsers use lexical analysis to identify tags and content.

u 12. CONCLUSION

Lexical analysis is the entry point of the compiler. It reads raw characters and produces a clean token stream for the parser. The key concepts — tokens, patterns, lexemes, regular expressions, regular definitions, transition diagrams, and Lex — form the foundation of scanner construction. The use of DFAs ensures that scanners are efficient. Tools like Lex/Flex automate the generation of scanners from declarative specifications, making compiler construction significantly faster and less error-prone.

H EXAM-READY KEY POINTS 3 Token = (token-name, attribute-value); Pattern = regex rule; Lexeme = actual string matched 3 Two-buffer scheme: lexemeBegin and forward pointers; sentinel eof character 3 Regular Expression operations: union (|), concatenation, Kleene star (*), + ,? 3 Regular Definition: naming regex patterns for reuse (e.g., digit → [0-9]) 3 Transition diagram = DFA used to recognize tokens 3 Lex structure: declarations %% rules %% functions; yytext holds matched string 3 Lex uses: Longest match rule first; then rule priority (first rule wins ties) 3 NFA → DFA via Subset Construction; DFA is minimized for efficiency 3 Lex internally: RegEx → NFA → DFA → Transition Table → C code

n Parse Tree for id+idid* E / | E + T | / T T * F | | | F F id | | id id

u 4. AMBIGUITY IN GRAMMARS

A grammar is ambiguous if there exists a string that has more than one parse tree (or equivalently, more than one leftmost derivation or more than one rightmost derivation). Ambiguity is problematic because it means the program has multiple interpretations. For example, the grammar E → E+E | EE | id is ambiguous — id+idid can be parsed in two ways, giving different structures and thus different precedences.

Ambiguity is resolved by: (1) rewriting the grammar to be unambiguous (as shown above with E/T/F structure that encodes precedence); (2) specifying disambiguation rules external to the grammar (e.g., in Yacc/Bison, operator precedence declarations).

u 5. ELIMINATION OF LEFT RECURSION

A grammar is left-recursive if it has a non-terminal A such that there is a derivation A ⇒+ Aα for some string α. Top-down parsers cannot handle left recursion because they would loop infinitely trying to expand A by choosing the production A → Aα.

n Immediate Left Recursion Elimination

For productions of the form: A → Aα | β (where β does not begin with A), eliminate left recursion by transforming to:

A → β A' A' → α A' | ε

n Worked Example Original grammar: E → E + T | T After eliminating left recursion: E → T E' E' → + T E' | ε

n General Algorithm for Left Recursion Elimination

  • Order non-terminals: A1, A2, ..., An
  • For i = 1 to n: For j = 1 to i-1: Replace each production Ai → Aj γ with Ai → δ 1 γ | δ 2 γ | ... (where Aj → δ1 | δ2 | ... are current productions)
  • Eliminate immediate left recursion in Ai

u 6. LEFT FACTORING

Left factoring is a grammar transformation that is useful for producing a grammar suitable for predictive (top-down) parsing. The problem arises when two or more alternatives for a non-terminal begin with the same terminal. The parser cannot decide which production to use without looking ahead further.

If A → αβ1 | αβ2 (two productions sharing common prefix α), left-factor to:

A → α A' A' → β1 | β 2

n Example Original: stmt → if expr then stmt else stmt | if expr then stmt Left-factored: stmt → if expr then stmt stmt' stmt' → else stmt | ε

After left-factoring, on seeing 'if', the parser always chooses stmt → if expr then stmt stmt', and then determines whether to derive else stmt or ε by looking at the next token.

u 7. EXAM-READY COMPARISON TABLE

Property Left Recursion Left Factoring Problem Causes infinite loop in top-down parsers

Ambiguous parser choice on same prefix

Solution Replace A→Aα|β with A→βA', A'→αA'|ε

Factor A→αβ1|αβ2 into A→αA', A'→β1|β 2

When needed Before top-down parsing Before top-down parsing

Effect Makes grammar non-left-recursive Makes grammar suitable for predictive parsing

H EXAM-READY KEY POINTS

3 CFG: G=(V,T,P,S); Productions: A→α; L(G) = language generated 3 Ambiguous grammar: more than one parse tree for same string 3 Left Recursion: A→Aα|β becomes A→βA', A'→αA'|ε 3 Left Factoring: A→αβ1|αβ2 becomes A→αA', A'→β1|β 2 3 Top-down parsers CANNOT handle left recursion — must eliminate first 3 Parse tree: internal nodes = non-terminals; leaves = terminals

Rules for computing FIRST(X):

  • If X is a terminal: FIRST(X) = {X}
  • If X → ε is a production: add ε to FIRST(X)
  • If X → Y1Y2...Yk: add FIRST(Y1)-{ε} to FIRST(X). If ε ∈ FIRST(Y1), add FIRST(Y2)-{ε}, and so on. If all Yi can derive ε, add ε to FIRST(X).

n FOLLOW Set

FOLLOW(A) is the set of terminals that can appear immediately to the right of A in some sentential form. It is used to know when to apply an ε-production.

Rules for computing FOLLOW(A):

  • Place $ (end of input marker) in FOLLOW(S), where S is the start symbol.
  • If there is a production B → αAβ: add FIRST(β)-{ε} to FOLLOW(A).
  • If there is a production B → αA or B → αAβ where ε ∈ FIRST(β): add FOLLOW(B) to FOLLOW(A).

n Example — Compute FIRST and FOLLOW Grammar: E → T E' E' → + T E' | ε T → F T' T' → * F T' | ε F → ( E ) | id FIRST(F) = { (, id } FIRST(T) = FIRST(F) = { (, id } FIRST(E) = FIRST(T) = { (, id } FIRST(E') = { +, ε } FIRST(T') = { *, ε } FOLLOW(E) = { $, ) } FOLLOW(E') = FOLLOW(E) = { $, ) } FOLLOW(T) = { +, $, ) } (FIRST(E')-{ε} + FOLLOW(E') since ε in FIRST(E')) FOLLOW(T') = FOLLOW(T) = { +, $, ) } FOLLOW(F) = { *, +, $, ) }

u 4. PREDICTIVE PARSING AND LL(1) GRAMMARS

A predictive parser is a top-down parser that uses a parsing table (M[A,a]) and a stack to parse without backtracking. The table entry M[A,a] contains the production to use when the current non-terminal is A and the current lookahead token is a.

A grammar is LL(1) if: (1) No two productions for the same non-terminal have FIRST sets that overlap; (2) If A → α | β and ε ∈ FIRST(α), then FIRST(β) and FOLLOW(A) are disjoint. The name LL(1) means: Left-to-right scan, Leftmost derivation, 1 token of lookahead.

n Construction of Predictive Parsing Table M[A,a]

  • For each production A → α:
  • For each terminal a in FIRST(α): add A→α to M[A,a]
  • If ε ∈ FIRST(α): for each terminal b in FOLLOW(A): add A→α to M[A,b]
  • If ε ∈ FIRST(α) and $ ∈ FOLLOW(A): add A→α to M[A,$]
  • Any undefined entries are error entries.

n Predictive Parsing Table for Expression Grammar

Non-Term id + * ( ) $ E E→TE' E→TE'

E' E'→+TE' E'→ε E'→ε

T T→FT' T→FT'

T' T'→ε T'→*FT' T'→ε T'→ε

F F→id F→(E)

n Predictive Parsing Algorithm Push $ and S onto stack (S on top) a = next_token() LOOP: X = top of stack if X == $ and a == $: accept if X is terminal: if X == a: pop X, a = next_token() else: error() else (X is non-terminal): if M[X,a] = X → Y1Y2...Yk: pop X; push Yk...Y2Y1 (Y1 on top) else: error()

n Trace: Parsing id+idid*

Stack Input Action $E id+id*id$ M[E,id]=E→TE'; expand

$E'T id+id*id$ M[T,id]=T→FT'; expand

$E'T'F id+id*id$ M[F,id]=F→id; expand

$E'T'id id+id*id$ match id

$E'T' +id*id$ M[T',+]=T'→ε; pop

$E' +id*id$ M[E',+]=E'→+TE'; expand

$E'T+ +id*id$ match +

$E'T id*id$ M[T,id]=T→FT'; expand ... (continue)

$ $ ACCEPT

u 5. CONCLUSION

Top-down parsing systematically constructs the parse tree from the root. Recursive descent parsing is intuitive and directly implements grammar rules as procedures. Predictive parsing uses FIRST and FOLLOW sets to build a parsing table that drives a stack-based parser with no backtracking. LL(1)

UNIT III: BOTTOM-UP PARSING &

SYNTAX-DIRECTED TRANSLATION

TOPIC 5: BOTTOM-UP PARSING — SHIFT-REDUCE, LR PARSERS

(SLR, CLR, LALR)

u 1. INTRODUCTION

Bottom-up parsing builds the parse tree from the leaves (input tokens) upward to the root (start symbol). It attempts to reduce the input string to the start symbol by repeatedly replacing substrings that match the right-hand side of some production with the corresponding left-hand side non-terminal. This process is the reverse of a rightmost derivation.

Bottom-up parsers are more powerful than top-down parsers — they can parse a larger class of grammars. The dominant class of bottom-up parsers is LR parsers , which stand for Left-to-right scan, Rightmost derivation (in reverse).

u 2. SHIFT-REDUCE PARSING

A shift-reduce parser uses a stack and an input buffer. The parser performs one of four actions at each step:

Action Description Shift Push the current input token onto the stack and advance input pointer

Reduce Replace the top of the stack (matching RHS of some production A→β) with A

Accept Parsing completed successfully (start symbol on stack, input exhausted)

Error Syntax error detected; invoke error recovery

n Trace: Parsing idid using S* → SS | id*

Stack Input Action $ id*id$ Shift

$id *id$ Reduce by S→id

$S *id$ Shift

$S* id$ Shift

$S*id $ Reduce by S→id

Stack Input Action $SS $ Reduce by S→SS

$S $ Accept

u 3. LR PARSING — GENERAL FRAMEWORK

An LR parser uses two tables: the ACTION table and the GOTO table , along with a stack of state numbers. The configuration of an LR parser is (stack, input). The parser looks up ACTION[state, token] and GOTO[state, non-terminal]:

  • ACTION[s, a] = shift t: push state t; advance input
  • ACTION[s, a] = reduce A→β: pop |β| states; push GOTO[top, A]
  • ACTION[s, a] = accept: done
  • ACTION[s, a] = error: syntax error

u 4. SLR(1) PARSING — SIMPLE LR

SLR(1) is the simplest LR method. It builds LR(0) items — productions with a dot (•) indicating how far parsing has progressed — and groups them into canonical collection of LR(0) item sets.

n LR(0) Items

An LR(0) item is a production with a dot: A → α•β. The dot divides what has been parsed (α, on stack) from what remains (β, expected from input). A→•αβ means parsing of A has just started; A→αβ• means A can be reduced (complete item).

n Canonical LR(0) Collection — Algorithm

  • Augment grammar: add S' → S
  • Initial item set I0 = CLOSURE({S'→•S})
  • CLOSURE(I): add all items A→•αβ for each B→α•Aβ in I and each production A→γ
  • GOTO(I, X) = CLOSURE of all items A→αX•β where A→α•Xβ is in I
  • Repeat until no new item sets are generated

n Resolving Reduce using FOLLOW (SLR)

In SLR, a reduce action A→α is added to ACTION[s, a] only if a ∈ FOLLOW(A). This is what distinguishes SLR from pure LR(0). If there is a shift-reduce or reduce-reduce conflict that cannot be resolved by FOLLOW, the grammar is not SLR(1).

u 5. CANONICAL LR(1) — CLR PARSING

Canonical LR(1) uses LR(1) items of the form [A→α•β, a] where 'a' is the lookahead — the terminal that must follow A for this reduction to apply. This gives more precise information than SLR's FOLLOW sets, allowing more conflicts to be resolved. CLR is the most powerful LR method but generates very large tables.

  • CLOSURE for LR(1): For item [A→α•Bβ, a], add [B→•γ, b] for each b in FIRST(βa)
  • Reduce item [A→α•, a]: add 'reduce A→α' to ACTION[state, a] only
  • CLR parsers can parse strictly more grammars than SLR