Compiler midterm revision

Chapters 1–4 · Dr. Mohammed Khader · from the course slides

f b i a a = 5 b = a + 3.2 p b $
scanner
floatdclidbintdclidaidaassigninum5idbassignidaplusfnum3.2printidb$
The ac program from Chapter 2, as the scanner hands it to the parser

Chapter 1 · Introduction

What a compiler is, the kinds of output it produces, and the phases inside it.

In 30 seconds

  • A compiler translates source code into machine code: the front-end analyses the source, the back-end generates code.
  • 3 kinds of machine code: pure (no OS), augmented (OS + runtime routines), virtual (bytecode, runs on a VM).
  • 3 target formats: assembly (needs an assembler), relocatable (needs a linker), absolute (runs directly, recompile every time).
  • Phases: Scanner → Parser → Type checker → Translator → Optimizer → Code generator, all sharing the symbol table.

What a compiler does

A compiler is a translator: it turns a human-oriented language (source) into a machine-oriented language (target). The first real compilers were the FORTRAN compilers of the late 1950s. "Translator" is the general term and covers compilers, assemblers and interpreters.

Compiler techniques show up outside compilers too: text formatters (LaTeX), silicon compilers for VLSI circuits, OS command languages and database query languages.

Front-end (analysis)

Analyses the source and builds the intermediate representation (IR). Scanner, parser, type checker.

Back-end (synthesis)

Generates target code (assembly/machine) from the IR. Optimizer, code generator.

Compilers differ in two ways

1. The kind of machine code generated

KindMeaningUsed for / example
Pure machine codeOnly instructions of a real instruction set. Assumes no OS and no library routines; runs on bare hardware.System implementation languages: OS kernels, embedded code (C, C++, Rust).
Augmented machine codeMachine code + OS routines + runtime language support routines (I/O, storage allocation, math). Together these act like a "virtual machine".Most normal application compilers.
Virtual machine codeOnly virtual instructions (e.g. Java bytecode, Pascal P-code). Runs anywhere a VM interpreter exists.Java/JVM. Portability: write one VM interpreter per architecture. JIT can translate hot code to native.

2. The format of the target code

FormatAdvantagesDisadvantage
Assembly languageSimplifies translation (assembler decides addresses) · cross-compilation (symbolic output moves easily between machines) · good for experimental languages · easy to check compiler correctness (output is readable)Needs an extra pass: the assembler
Relocatable binaryAddresses are relative (not yet bound) · more efficient (skips assembler step) · modular compilation · cross-language references · supports subroutine librariesNeeds a linkage step to add libraries and produce executable absolute binary
Absolute binary (memory image)Runs directly after compiling, no linking · fast, prepare + run in one step · always uses the newest library routines · good for debugging/studentsLimited ability to interface with other code · must recompile for each execution

Compiler vs interpreter

Compiler

Two phases: compilation (source → target program), then execution (target program reads input, produces output).

Interpreter

Executes the source program directly, reading input and writing output with no separate target program.

Real systems mix both. Java compiles ahead of time to bytecode and the JVM interprets/JITs it. Python compiles to bytecode at run time and the Python VM interprets it.

Syntax and semantics

  • Syntax = structure, specified with a CFG. a=b+c is legal, b+c=a is not.
  • Semantics = meaning. a=b+c is illegal if a variable is undeclared or b is Boolean.
    • Static semantics: rules checked at compile time that decide which syntactically legal programs are valid: declarations, type compatibility, number of parameters. Can be formal, e.g. attribute grammars.
    • Runtime semantics: what the program computes (e.g. array index out of bounds is detected at runtime). Usually informal (language manual), sometimes formal.
Attribute grammar example
  E → E + T
  E_result → E_v1 + T_v2
     if v1.type = numeric and v2.type = numeric
        then result.type ← numeric
        else call ERROR()

Organization of a syntax-directed compiler (Fig 1.4)

Modern compilers are syntax-directed: the parser's recognition of program structure drives all the other actions.

sourceScannertokens →ParserAST →Type checkerdecorated AST →TranslatorIR →OptimizerIR →Code generator→ target code

Symbol tables are shared by all phases.

PhaseJob
Scanner (lexical analyzer)Reads characters and groups them into tokens (identifiers, integers, reserved words, delimiters). Removes comments, processes compiler directives, puts preliminary info in the symbol table.
Parser (syntax analyzer)Groups tokens into phrases using the CFG. Usually builds the AST.
Type checker (semantic analysis)Checks static semantics of each AST node and decorates it with type info. Checks type correctness, reachability/termination, exception handling. Else issues an error.
TranslatorTurns AST nodes into IR (e.g. Java bytecode). Simple compilers may produce target code directly.
OptimizerTransforms IR into functionally equivalent but faster code. Can also run after code generation.
Code generatorMaps IR to target machine code. Machine-dependent: register allocation, code scheduling. gcc has machine description files for 10+ architectures.
Symbol tableAssociates information with identifiers, shared among phases (declaration, use, type checking).

Aho/Ullman version of the same pipeline: Lexical analyzer → Syntax analyzer → Semantic analyzer → Intermediate code generator → Machine-independent optimization → Code generator → Machine-dependent optimization.

Compiler-writing tools

Packaged as compiler generators / compiler-compilers: scanner generators (Lex, input = tokens as regular expressions), parser generators (Yacc), symbol table managers, attribute grammar evaluators, code-generation tools. Most effort still goes into the semantic phases, which are usually hand-coded.

Exam traps

Relocatable binary needs a linker; assembly needs an assembler; absolute binary needs neither but must be recompiled every run. Pure code = no OS; augmented = OS + runtime routines; virtual = portable via VM interpreter.

Self-test

Give three advantages of generating assembly language as target code.

Simplifies translation (address decisions left to the assembler); supports cross-compilation because symbolic output moves easily between machines; makes compiler output easy to inspect, so correctness is easier to check. (Also good for experimental language designs.) Disadvantage: needs an extra assembler pass.

Why does virtual machine code give portability?

The program contains only VM instructions, so it runs on any architecture that has a VM interpreter. You only write one interpreter per target machine instead of one compiler back-end per machine.

Static vs runtime semantics, with an example of each.

Static: checked at compile time, e.g. using an undeclared variable or adding a Boolean to an int. Runtime: what the program computes / errors found while running, e.g. array index out of bounds.

What does the type checker add to the AST?

Type information on each node ("decorated AST"), after checking static semantics.

Which phases are machine-dependent?

The code generator (register allocation, code scheduling) and machine-dependent optimization. Scanner, parser and type checker are machine-independent.

Chapter 2 · Design of a Simple Compiler (ac)

A full tiny compiler end to end: scanning, parsing, AST, semantic analysis, code generation.

In 30 seconds

  • ac is a tiny calculator language: keywords f, i, p, 23 one-letter variables, int and float.
  • It is compiled into dc code, written in postfix (RPN).
  • Parser = recursive descent: one procedure per nonterminal, choose the rule using predict sets.
  • The AST is a smaller tree than the parse tree. Semantic analysis = symbol table + type checking (which inserts int2float).

Pass

One traversal of the entire program by the compiler.

Phase

A distinct stage that takes the previous stage's output and produces input for the next. A pass can contain several phases.

The ac (adding calculator) language

  • Types: integer and float (5 fractional digits). Integer is automatically converted to float.
  • Keywords (3): f declares float, i declares integer, p prints.
  • Variables: only 23 names: lowercase letters except f, i, p.
  • Target: dc (desk calculator), a stack calculator using Reverse Polish Notation.
  • Tokens are specified with regular expressions; syntax with a CFG.

Token specification

TokenRegular expression
floatdcl"f"
intdcl"i"
print"p"
id[a-e] | [g-h] | [j-o] | [q-z]
assign"="
plus / minus"+" / "-"
inum[0-9]+
fnum[0-9]+.[0-9]+
blank(" ")+

Grammar (Fig 2.1)

Prog  → Dcls Stmts $
Dcls  → Dcl Dcls | λ
Dcl   → floatdcl id
      | intdcl id
Stmts → Stmt Stmts | λ
Stmt  → id assign Val Expr
      | print id
Expr  → plus Val Expr
      | minus Val Expr
      | λ
Val   → id | inum | fnum

Worked example: scanning

Source:   f b   i a   a = 5   b = a + 3.2   p b   $

Tokens:   floatdcl  id(b)
          intdcl    id(a)
          id(a) assign inum(5)
          id(b) assign id(a) plus fnum(3.2)
          print id(b)
          $

A token has a type (which terminal it is) and a semantic value (extra info like the name b or the number 3.2). The ac scanner uses one character of lookahead: peek() looks at the next character, advance() consumes it.

function SCANNER() returns Token            (Fig 2.5)
    while s.PEEK() = blank do s.ADVANCE()
    if s.EOF() then ans.type ← $
    else if s.PEEK() ∈ {0..9} then ans ← SCANDIGITS()
    else
        ch ← s.ADVANCE()
        switch ch
            case {a..z} − {i, f, p}: ans.type ← id; ans.val ← ch
            case f: floatdcl   case i: intdcl   case p: print
            case =: assign     case +: plus     case -: minus
            default: LEXICALERROR()
    return ans

function SCANDIGITS()                        (Fig 2.6)
    read digits while PEEK() is a digit
    if PEEK() ≠ "." then type ← inum
    else type ← fnum; read "." and the digits after it

Why real scanners are harder: + is a prefix of ++; comments and strings need special symbols and escapes (\"); identifiers, numbers and comments are variable length.

Parsing: recursive descent

A recursive descent parser is a top-down parser made of mutually recursive procedures, one per nonterminal. Each procedure peeks at the next token and uses the predict sets to choose a production.

Predict sets for all 15 productions (these are the ones your professor wrote by hand on the Fig 2.1 slide):

#ProductionPredict set
1Prog → Dcls Stmts ${ floatdcl, intdcl, id, print, $ }
2Dcls → Dcl Dcls{ floatdcl, intdcl }
3Dcls → λ{ id, print, $ }
4Dcl → floatdcl id{ floatdcl }
5Dcl → intdcl id{ intdcl }
6Stmts → Stmt Stmts{ id, print }
7Stmts → λ{ $ }
8Stmt → id assign Val Expr{ id }
9Stmt → print id{ print }
10Expr → plus Val Expr{ plus }
11Expr → minus Val Expr{ minus }
12Expr → λ{ id, print, $ }
13–15Val → id | inum | fnum{ id } { inum } { fnum }

Fig 2.2 derives the example program with a leftmost derivation in 20 steps. Rule 6 (Stmts → Stmt Stmts) generates each new statement, and rule 7 (Stmts → λ) ends the list at step 19.

procedure Stmts()
    if ts.peek() = id or ts.peek() = print then
        call Stmt()
        call Stmts()
    else if ts.peek() = $ then
        /* do nothing for λ */
    else call ERROR()

procedure Stmt()
    if ts.peek() = id then
        call MATCH(ts, id); call MATCH(ts, assign); call Val(); call Expr()
    else if ts.peek() = print then
        call MATCH(ts, print); call MATCH(ts, id)
    else call ERROR()

Code rules: a terminal becomes a MATCH() call · a nonterminal becomes a call to its procedure · λ generates no code.

Parse tree vs AST

Parse trees are large and too detailed: the expression a + 3.2 takes 8 nodes in the parse tree but only 3 in the AST. The AST:

  • drops inessential punctuation and delimiters
  • is the common IR for all phases after syntax analysis
  • keeps declarations only as id name + type
  • keeps statement order explicitly (needed for code generation)
  • assignment node has exactly 2 children (id and expression); compute nodes hold operator + operands; print keeps the id name

The AST is built with attribute grammar rules. Scanner + parser together form the syntax analysis phase.

Things a CFG cannot express (so they go to later phases): declare-before-use / type consistency; x.y.z in Java (package.class.field or var.field.field?); operator overloading (+ adds numbers or joins strings).

Semantic analysis

The catch-all term for post-parsing checks that syntax can't handle. For ac it has two parts:

  1. Symbol table construction: walk the AST and record each identifier and its type. ac needs 23 entries, type = integer, float or unused (null). Real languages also store scope, storage class and protection (public/private…).
  2. Type checking: walk the AST bottom-up (leaves to root). If an int and a float meet, insert a conversion (int2float) node. Assigning a float to an int variable is an error.
AST after semantic analysis (Fig 2.13)

Program
 ├─ floatdcl b
 ├─ intdcl a
 ├─ assign : integer ── id a , inum 5
 ├─ assign : float   ── id b , plus : float
 │                                ├─ int2float : float ── id a
 │                                └─ fnum 3.2
 └─ print b

Symbol table (Fig 2.11): a = integer, b = float, the other 21 letters = null.

Code generation for dc

Traverse the AST from the root using visitor methods:

visit(…)Effect
ComputingGenerate left and right subtrees, then emit + or -
AssigningEvaluate the expression, store into a dc register (sa), reset precision to integer (0 k)
SymReferencingLoad the variable's register and push it (la)
PrintingLoad, print (p), then si to pop the value into register i (dc doesn't pop on print; i is a keyword so it's free)
ConvertingSet precision to 5 fractional digits: 5 k
ac source          dc code
a = 5              5 sa 0 k
b = a + 3.2        la 5 k 3.2 + sb 0 k
p b                lb p si

Infix, postfix, prefix

Notation3 + 5(3 + 5) * (7 − 2)
Infix3 + 5(3 + 5) * (7 - 2)
Reverse Polish (postfix)3 5 +3 5 + 7 2 - *
Polish (prefix)+ 3 5* + 3 5 - 7 2

Evaluating 3 5 + 7 2 - * on a stack: push 3, push 5, + → 8; push 7, push 2, − → 5 (7 − 2, the top is the right operand); * → 40.

Exam traps

λ produces no code in recursive descent. ac has 23 variables and 3 keywords. Type checking walks bottom-up. In RPN subtraction, the value below the top is the left operand.

Self-test

Convert a * (b + c) - d to postfix and prefix.

Postfix: a b c + * d -
Prefix: - * a + b c d

Evaluate the RPN expression 6 2 / 3 4 * +.

6/2 = 3; 3*4 = 12; 3 + 12 = 15.

Tokenize the ac program i x f y x = 7 y = x - 1.5 p y.

intdcl id(x) floatdcl id(y) id(x) assign inum(7) id(y) assign id(x) minus fnum(1.5) print id(y) $. Semantic analysis will insert int2float on x in x - 1.5.

Why is i safe to use as a scratch register in the generated dc code?

Because i is a reserved keyword in ac (integer declaration), so no program variable can be named i.

Difference between a pass and a phase?

A pass is one complete traversal of the program; a phase is one stage of processing. One pass can contain several phases.

Write the recursive descent procedure for Expr → plus Val Expr | minus Val Expr | λ.
procedure Expr()
    if ts.peek() = plus then
        MATCH(ts, plus); Val(); Expr()
    else if ts.peek() = minus then
        MATCH(ts, minus); Val(); Expr()
    else if ts.peek() ∈ {id, print, $} then
        /* λ: do nothing */
    else ERROR()

The λ predict set is FOLLOW(Expr) = {id, print, $}.

Chapter 3 · Theory and Practice of Scanning

Regular expressions describe tokens; finite automata recognize them. The core chain: RE → NFA → DFA → minimized DFA.

In 30 seconds

  • Tokens are described with regular expressions and recognized with finite automata.
  • The main pipeline: RE → NFA → DFA → minimized DFA.
  • NFA → DFA uses subset construction: each DFA state is a set of NFA states, built with CLOSE (λ-closure).
  • Minimize by splitting: start with {accepting} and {non-accepting}, split until every group agrees.

Scanner basics

The scanner (lexical analyzer, lexer) turns a character stream into a token stream. The parser calls getNextToken; both use the symbol table. It puts the program into a compact uniform format and removes comments. Scanner generators are declarative: you say what to scan, not how.

  • Regular set: a set of strings defined by a regular expression.
  • Lexeme: an actual instance of a token class (e.g. count is a lexeme of identifier).
  • λ / ε: empty string. ∅: empty set.
  • Meta-characters: ( ) ' * + |, quote them to use literally: ('('|')'|;|,)

Regular expression operations

OperationMeaningExample
Catenation PQa string from P followed by a string from Q. sλ = λs = sab
Alternation P|Qs is in P or in QD = (0|1|…|9)
Kleene closure P*zero or more strings from P(0|1)*
Positive closure P+one or more. P* = P+ | λ, P+ = P*P(0|1)+
Not(A)all characters of Σ not in A (Σ − A)Not(Eol)
Akexactly k strings from A(0|1)32 = 32-bit strings

Formal definition: ∅ and λ are REs; any symbol s is an RE for {s}; if A and B are REs then A|B, AB, A* are REs.

Standard examples (memorize)

D = digit, L = letter

Fixed-decimal literal     Lit        = D+ . D+
Signed integer            IntLiteral = ('+' | - | λ) D+
Single-line comment       Comment    = // (Not(Eol))* Eol
Real literal              RealLit    = (D+ (λ | .)) | (D* . D+)
Identifier                ID         = L (L | D)* ( _ (L | D)+ )*

The identifier RE allows single underscores between letter/digit groups but no trailing underscore and no __.

Regular vs not regular

  • Every finite set is regular. Proof from the slides: ∅ is regular, and a finite set {s1, …, sn} is the RE s1 | s2 | … | sn. Some infinite sets are regular too (e.g. (0|1)*).
  • { anbn | n ≥ 0 } is not regular. An FSM has only a finite amount of memory, so it can't remember how many a's it has read.
  • { [m ]m | m ≥ 1 } (balanced brackets) is not regular: an FA has finitely many states, so it can't count an unbounded number of [. With k states, after reading more than k ['s two prefixes land in the same state, so the FA would also accept an unbalanced string.
  • Every regular set can be defined by a CFG (CFGs are more powerful). REs are enough for token-level syntax.

Finite automata

An FA has: a finite set of states, a finite vocabulary Σ, transitions labelled with characters, one start state, and a set of accepting (final) states. Drawn as a transition diagram.

Example from the slides: the FA for (abc+)+ accepts abccabc and rejects abcab.

DFA

Every state has at most one transition per symbol. No λ moves. Easy to program; used to drive scanners. Stored as a transition table T[state, char].

NFA

Allows λ transitions and multiple transitions on the same symbol. Easy to build from an RE, then converted to a DFA.

Transition table for // (Not(Eol))* Eol

State/Eola b c …
1 (start)2––
23––
3343
4 (accept)–––

Two ways to code a DFA

Table-driven: the table is data, a generic driver interprets it.

state ← start
while state ≠ error and not eof
    c ← READ()
    state ← T[state, c]
if state ∈ accepting
    then return token

Explicit control: the table is hidden in the program's if/while logic.

if READ() = '/' and READ() = '/' then
    while READ() ≠ Eol do skip
    accept
else ERROR()

Full tables have one column per character; to save space use table compression (store only non-error entries with hashing or linked structures).

A transducer is an FA that also does something with the input beyond accepting it: e.g. saves the identifier's text or computes the integer value of 431. It uses an action table parallel to the transition table.

Slides example, quoted strings: " ( Not(") | "" )* ". Inside a string, "" stands for one literal quote. The transducer uses T(") to mean "read the quote but don't copy it to the output":

"EE468"                        →  EE468
"it's an ""easy"" job"         →  it's an "easy" job
"""Polaris"" beats ""SUIF"""   →  "Polaris" beats "SUIF"

RE → NFA (Thompson construction)

Build from the atoms a and λ using three operations. Each piece has one start and one final state, glued with λ edges:

a       :  (s) --a--> (f)
A | B   :  new start --λ--> A and --λ--> B ; ends of A and B --λ--> new final
A B     :  final of A --λ--> start of B
A*      :  new start --λ--> A --λ--> new final
           new start --λ--> new final      (zero times)
           end of A  --λ--> start of A     (repeat)

NFA → DFA (subset construction)

Each DFA state is a set of NFA states: the DFA is in state {x,y,z} iff the NFA could be in any of x, y or z.

  • CLOSE(S) (λ-closure): all states reachable from S using only λ edges, including S itself.
  • Move(S, a): all states reachable from S on one a edge. Then take CLOSE of that.
  • Start state of D = CLOSE({start of N}). Repeat for every new set and every symbol.
  • Accepting DFA states = sets that contain any NFA accepting state.
  • Worst case: an n-state NFA gives up to 2n DFA states, but token NFAs don't blow up in practice.

Small cases (slide 42): 0 –a→ 1 and 0 –a→ 2 become A{0} –a→ B{1,2}. With 0 –a→ 1 and 0 –λ→ 2, the start is CLOSE({0}) = A{0,2}, which goes –a→ B{1}.

Slides example 1 (Fig 3.24 → 3.25). NFA edges: 1 –b→ 1, 1 –λ→ 2, 1 –a→ 3, 2 –a→ 4, 2 –a→ 5, 3 –b→ 4, 4 –a|b→ 5. Accepting state: 5.

DFA stateabAccept?
{1,2} start{3,4,5}{1,2}no
{3,4,5}{5}{4,5}yes
{4,5}{5}{5}yes
{5}––yes

Slides example 2 (slides 54–59). NFA edges: 0 –ε→ 1, 0 –ε→ 3, 1 –b→ 2, 3 –a→ 4, 2 –ε→ 5, 4 –ε→ 5, 5 –ε→ 0, 5 –ε→ 6, 6 –b→ 7, 7 –c→ 8, 8 –d→ 9. Accepting state: 9. The language is (a|b)+ bcd.

DFA stateabcd
A = {0,1,3} startBC––
B = {0,1,3,4,5,6}BD––
C = {0,1,2,3,5,6}BD––
D = {0,1,2,3,5,6,7}BDE–
E = {8}–––F
F = {9} accept––––

How to get each row: from A on a, only 3 –a→ 4 applies, so the result is CLOSE({4}) = {4,5,0,6,1,3}. On b from D, both 1 –b→ 2 and 6 –b→ 7 apply, so the result is CLOSE({2,7}) = D again.

MAKEDETERMINISTIC(N)                         (Fig 3.23)
    D.Start ← RECORDSTATE({N.Start})
    foreach S in WorkList: remove S
        foreach c in Σ: D.T(S,c) ← RECORDSTATE( ∪ N.T(s,c) for s in S )
    D.Accept ← { S | S ∩ N.Accept ≠ ∅ }
RECORDSTATE(s): s ← CLOSE(s); if new, add to D.States and to WorkList

Minimizing a DFA

Every DFA has a unique smallest equivalent DFA.

  • Remove unreachable states (can't be reached from start) and dead states (can't reach any accepting state).
  • Split algorithm (greedy, optimistic): start with two groups, accepting and non-accepting. If states in a group disagree on where some character takes them (to different groups), split the group. Repeat until no group splits. Each final group becomes one state.

Slides example (Fig 3.26 → 3.28). 1 –a→ 2 –b→ 3 –c→ 4 and 1 –d→ 5 –b→ 6 –c→ 7, with 4 and 7 accepting. Groups: {4,7} accept; {1,2,3,5,6} non-accept. On c, states 3 and 6 go to the accepting group but the others don't, so split off {3,6}. Then on b, states 2 and 5 go to {3,6}, so split off {2,5}. Result: 1 –a|d→ {2,5} –b→ {3,6} –c→ {4,7}, 4 states instead of 7.

Practice: minimize this DFA. Start A; accepting {C, D}. A: a→B, b→C · B: a→B, b→D · C: a→B, b→C · D: a→B, b→D

Initial groups: {A, B} (non-accepting), {C, D} (accepting).
{A,B} on a → B,B (same group); on b → C,D (both accepting, same group). No split.
{C,D} on a → B,B; on b → C,D. No split.
Result: 2 states. N = {A,B} (start), F = {C,D} (accept). N: a→N, b→F; F: a→N, b→F. The language is "strings ending in b".

FA → RE (state elimination)

Useful when you have an FA and need an RE for Lex. Start from an FA with one start and one accepting state, then remove states one by one:

  • T1: two parallel edges R and S between the same states → one edge R|S
  • T2: bypass a middle state with in-edge X and out-edge Y → XY
  • T3: bypass a middle state that has a self-loop Z → XZ*Y

Stop when one edge goes from start to the accepting state.

Slides example (Fig 3.29 → 3.32). Original DFA: 1 –b→ 1, 1 –a→ 2, 2 –b→ 3, 2 –a→ 4, 3 –a|b→ 4, with 2, 3 and 4 accepting. First add a new start 0 –λ→ 1 and a single accepting state 5, with λ edges from 2, 3 and 4 into it. Then remove states:

remove 1 (T3, loop b):   0 --b*a--> 2
remove 2 (T2):           0 --b*ab--> 3 ,  0 --b*aa--> 4 ,  0 --b*a--> 5
remove 4 (T2):           3 --(a|b)--> 5 ,  0 --b*aa--> 5
merge parallel (T1):     0 --b*aa | b*a--> 5 ,  3 --a|b|λ--> 5
remove 3 (T2) + T1:      0 --b*ab(a|b|λ) | b*aa | b*a--> 5

simplify:  b*aba | b*abb | b*ab | b*aa | b*a  =  b*a(ba | bb | b | a | λ)

Lex

Lex is a scanner generator: input is each token as a regular expression, output is a scanner. In Lex REs, . matches any character except newline, and metacharacters need \ to be literal (".*\.txt$" matches strings ending in .txt).

Exam traps

* is zero-or-more, + is one-or-more. CLOSE always includes the state itself. A DFA state is accepting if it contains any NFA final state. Minimization starts with two groups (accept / non-accept), not one per state.

Self-test

Write an RE for binary strings whose third-from-last symbol is 0.

(0|1)*0(0|1)(0|1) (this is the example from the slides).

Write an RE for C-style identifiers: letter or underscore, then letters, digits, underscores.

(L | _)(L | D | _)*

Which of these match ID = L(L|D)*(_(L|D)+)*: x_1, _x, ab_, a_b_c, a__b?

x_1 · _x (must start with letter) · ab_ (underscore needs a following letter/digit) · a_b_c · a__b (double underscore)

Build the NFA and DFA for (a|b)*abb.

A small NFA: 0 –a,b→ 0; 0 –a→ 1; 1 –b→ 2; 2 –b→ 3 (accept). Subset construction:

DFAab
{0} start{0,1}{0}
{0,1}{0,1}{0,2}
{0,2}{0,1}{0,3}
{0,3} accept{0,1}{0}
Why can't a scanner (RE/FA) check balanced parentheses?

Balanced brackets [m]m are not regular. An FA has a fixed finite number of states, so it can't remember an unbounded count. This needs a CFG (the parser).

What is a transducer? Give an example.

An FA that does more than accept/reject: it transforms or records input. Example: while recognizing 431, also compute its integer value, or save an identifier's name for the symbol table.

Chapter 4 · Grammars and Parsing

CFG notation, derivations, parse trees, ambiguity, EBNF, parser types, and the most-tested skill: FIRST and FOLLOW sets.

In 30 seconds

  • A CFG is G = (N, Σ, P, S). Leftmost derivation = top-down parsing; rightmost = bottom-up.
  • The handle is the leftmost simple phrase. Ambiguous = a string has 2+ parse trees (undecidable in general).
  • EBNF [ ] and { } are removed by adding a new nonterminal with a λ rule.
  • FIRST = what a string can start with. FOLLOW = what can come right after a nonterminal. Practise these most.

Context-free grammar G = (N, Σ, P, S)

  • N: finite set of nonterminals (variables)
  • Σ: finite set of terminals (the tokens from the scanner)
  • P: productions A → X1…Xm, A ∈ N, Xi ∈ N ∪ Σ, m ≥ 0 (m = 0 means A → λ)
  • S: start (goal) symbol, S ∈ N
  • Vocabulary V = N ∪ Σ, and N ∩ Σ = ∅
Symbol styleMeansExamples
UppercaseNonterminal (N)A, B, Prefix
Lowercase, punctuationTerminal (Σ)a, b, if, (, ;
X, YAny grammar symbol (N ∪ Σ)Xi
Greek α, β, γString of symbols (N ∪ Σ)*α, β
  • ⇒ one derivation step · ⇒+ one or more · ⇒* zero or more
  • If S ⇒* β then β is a sentential form. SF(G) = all sentential forms.
  • L(G) = { w ∈ Σ* | S ⇒+ w } = SF(G) ∩ Σ* (sentential forms with only terminals)

Leftmost and rightmost derivations

Grammar used in the slides (Fig 4.1):

E      → Prefix ( E ) | v Tail
Prefix → f | λ
Tail   → + E | λ

Leftmost (expand the leftmost nonterminal; top-down parsers)

E ⇒lm Prefix ( E )
  ⇒lm f ( E )
  ⇒lm f ( v Tail )
  ⇒lm f ( v + E )
  ⇒lm f ( v + v Tail )
  ⇒lm f ( v + v )

Rightmost = canonical (expand the rightmost; bottom-up parsers, in reverse)

E ⇒rm Prefix ( E )
  ⇒rm Prefix ( v Tail )
  ⇒rm Prefix ( v + E )
  ⇒rm Prefix ( v + v Tail )
  ⇒rm Prefix ( v + v )
  ⇒rm f ( v + v )

Sentential forms from these are left sentential forms and right sentential forms.

Parse trees, phrases, handles

  • Parse tree: root = S; interior nodes = nonterminals; a node + its children = one production; leaves = terminals or λ when complete.
  • Phrase: symbols derived from a single nonterminal in the tree.
  • Simple (prime) phrase: a phrase containing no smaller phrase (directly derived from one nonterminal).
  • Handle: the leftmost simple phrase. It's the next step a bottom-up parser reduces.
  • Example: in f ( v Tail ), the simple phrases are f and v Tail; the handle is f.

Problems with grammars

Useless symbols / reduced grammars. A grammar is reduced if every nonterminal and production helps derive some terminal string. Useless nonterminals are either non-terminating (can never derive a terminal string) or unreachable from S.

S → A | B
A → a
B → B b        B never terminates → useless (remove B and S → B)
C → c          C is unreachable from S → useless
Reduced:  S → A,  A → a

Ambiguity. A grammar is ambiguous if some string has two or more parse trees (equivalently two leftmost derivations). Checking ambiguity is undecidable: no algorithm works for every CFG.

Expr → Expr - Expr | id
"id - id - id" has two trees:
   (id - id) - id        and        id - (id - id)
Fix (left-assoc):  Expr → Expr - id | id

Extended BNF → standard form (Fig 4.4)

[ X ] = optional (all present or all absent) · { X } = repeated zero or more times.

Declaration → [final] [static] [const] Type identifier { , identifier }

Rule for optional:   A → α [X1…Xn] β   ⇒   A → α N β
                                            N → X1…Xn | λ
Rule for repeat:     B → α {X1…Xm} β   ⇒   B → α N β
                                            N → X1…Xm N | λ

Parsers and recognizers

Recognizer

Only answers: is x ∈ L(G)?

Parser

Answers that and also produces the structure (parse tree).

Top-down

Starts at the root, expands depth-first. Preorder, predictive, leftmost derivation. Includes recursive descent. LL(1).

Bottom-up

Starts at the leaves and reduces to S. Postorder, reverse rightmost derivation. LR(1).

Slides example (Figs 4.5, 4.6): parse begin simplestmt ; simplestmt ; end $ with

Program → begin Stmts end $
Stmts   → Stmt ; Stmts | λ
Stmt    → simplestmt | begin Stmts end

Top-down expands Program first, then Stmts → Stmt ; Stmts, then Stmt → simplestmt, and so on down the left side (preorder). Bottom-up first recognizes the leftmost simplestmt as Stmt, then the second Stmt, then Stmts → λ, then builds Stmts upward and recognizes Program last (postorder).

LL(1) / LR(1): 1st L = read input left to right; 2nd letter = Leftmost or Rightmost derivation; (1) = one token of lookahead.

Which nonterminals derive λ?

Not trivial because it can take several steps: A ⇒ BCD ⇒ BC ⇒ B ⇒ λ. Algorithm: mark every A with A → λ; then repeatedly mark A if some production A → X1…Xn has all Xi marked; stop when nothing changes.

FIRST sets

FIRST(α) = terminals that can begin a string derived from α (plus λ if α ⇒* λ).

  1. If X is a terminal: FIRST(X) = {X}.
  2. If X → λ: add λ to FIRST(X).
  3. If X → Y1Y2…Yk: add FIRST(Y1) − {λ}. If Y1 can derive λ, also add FIRST(Y2) − {λ}, and so on. If all Yi derive λ, add λ.

FOLLOW sets

FOLLOW(A) = terminals that can appear immediately to the right of A in some sentential form (A's right context).

  1. Put $ in FOLLOW(S).
  2. For A → α B β: add FIRST(β) − {λ} to FOLLOW(B).
  3. For A → α B, or A → α B β where β ⇒* λ: add FOLLOW(A) to FOLLOW(B).
  4. Repeat until no set changes. FOLLOW never contains λ.

Worked example (the classic one from the slides)

E  → T E'
E' → + T E' | λ
T  → F T'
T' → * F T' | λ
F  → ( E ) | id
NonterminalFIRSTFOLLOWWhy (FOLLOW)
E{ (, id }{ ), $ }start symbol → $; F → ( E ) → )
E'{ +, λ }{ ), $ }at the end of E → T E', so gets FOLLOW(E)
T{ (, id }{ +, ), $ }followed by E': FIRST(E') − λ = {+}; E' ⇒ λ so add FOLLOW(E)
T'{ *, λ }{ +, ), $ }at the end of T → F T', gets FOLLOW(T)
F{ (, id }{ *, +, ), $ }followed by T': {*}; T' ⇒ λ so add FOLLOW(T)

FIRST of each production's RHS: T E' → {(, id} · + T E' → {+} · F T' → {(, id} · * F T' → {*} · ( E ) → {(} · id → {id}. For λ-productions, the parser uses FOLLOW of the LHS.

Predict set (links ch. 2 and 4): Predict(A → α) = FIRST(α) − {λ}, plus FOLLOW(A) if α ⇒* λ. FIRSTk and FOLLOWk generalize to k tokens for LL(k)/LR(k).

Two conventions in your slides: know both

The slides mix the Aho ("Dragon book") style with the Fischer textbook style (the figures with "Level / Marker" columns).

Aho style (slides 37–39, 43–45, 48)Fischer style (Fig 4.11, 4.12, slides 40, 46)
λ in FIRST?Yes: FIRST(E') = {+, λ}No: FIRST holds terminals only; "derives λ" is tracked separately (Fig 4.7)
$ in FOLLOW(start)?Yes, always add $No. The grammar writes $ itself (e.g. Prog → … $), so FOLLOW(S) = { } if S is on no right-hand side
S → A B c, A → a | λ, B → b | λFIRST(A) = {a, λ}, FOLLOW(S) = {$}FIRST(A) = {a}, FIRST(S) = {a, b, c}, FOLLOW(A) = {b, c}, FOLLOW(B) = {c}, FOLLOW(S) = { }

In the exam, use the style the question's grammar suggests. If the grammar has ε and no explicit $, use the Aho style. If it uses λ and writes $, use the Fischer style. If unsure, write one line saying which convention you're using.

Termination (slide 41): with A → B, B → C, C → A, FIRST(A) depends on itself. Mark nonterminals as "visited" or iterate until nothing changes, so the computation doesn't loop forever.

Exam traps

λ can be in FIRST but never in FOLLOW. Always put $ in FOLLOW(start). When β can vanish, keep reading FIRST of the next symbol and finally add FOLLOW of the LHS. Rightmost = canonical = bottom-up. Ambiguity is undecidable in general.

Self-test

Compute FIRST and FOLLOW for: S → A B c, A → a | λ, B → b | λ

FIRST(A) = {a, λ}; FIRST(B) = {b, λ}; FIRST(S) = {a, b, c} (A and B can both vanish, so c can come first).
FOLLOW(S) = {$}; FOLLOW(A) = FIRST(B c) = {b, c}; FOLLOW(B) = {c}.
This is the exact grammar from slides 40 and 46. Their Fischer-style answer drops λ from FIRST and gives FOLLOW(S) = { }. See the conventions box above.

Compute FIRST and FOLLOW for: S → a B D h, B → c C, C → b C | λ, D → E F, E → g | λ, F → f | λ
FIRSTFOLLOW
S{a}{$}
B{c}{g, f, h}
C{b, λ}{g, f, h}
D{g, f, λ}{h}
E{g, λ}{f, h}
F{f, λ}{h}
Give leftmost and rightmost derivations of id + id * id using E → E + T | T, T → T * F | F, F → id.
Leftmost:  E ⇒ E + T ⇒ T + T ⇒ F + T ⇒ id + T ⇒ id + T * F
             ⇒ id + F * F ⇒ id + id * F ⇒ id + id * id
Rightmost: E ⇒ E + T ⇒ E + T * F ⇒ E + T * id ⇒ E + F * id
             ⇒ E + id * id ⇒ T + id * id ⇒ F + id * id ⇒ id + id * id
Show E → E + E | E * E | id is ambiguous.

id + id * id has two parse trees: one with + at the root, id + (id * id), and one with * at the root, (id + id) * id.

Convert to standard BNF: Stmt → if Expr then Stmt [ else Stmt ] and List → id { , id }
Stmt     → if Expr then Stmt ElsePart
ElsePart → else Stmt | λ
List     → id Rest
Rest     → , id Rest | λ
Find the useless symbols: S → a A | B, A → b, B → B c, D → d

B is non-terminating (every B production contains B). D is unreachable. Reduced grammar: S → a A, A → b.

What do the letters in LL(1) and LR(1) mean?

First L: scan input Left to right. Second letter: produce a Leftmost (LL) or Rightmost (LR, in reverse) derivation. (1): one token of lookahead.

Exam drill

A full question set for each chapter, stacked in order. Answer on paper first, then open the question to check.

How to use this

  • Work through one chapter block at a time. Each has true/false, short-answer and worked problems.
  • Count what you got right. Below about 70%, re-read that chapter's tab before going on.
  • Questions marked Problem are the long calculations that usually carry the most marks.

Chapter 1 · Introduction

True / False

1. An absolute binary compiler needs a linker.

False. Relocatable binary needs a linker. Absolute binary runs directly but must be recompiled for each run.

2. Pure machine code assumes an operating system is present.

False. Pure code runs on bare hardware with no OS or library routines. Augmented code is the one that needs OS and runtime routines.

3. Virtual machine code can run on any machine that has a VM interpreter.

True. That is how Java gets portability.

4. The code generator is machine-independent.

False. It is machine-dependent (register allocation, code scheduling).

5. The symbol table is used only by the scanner.

False. All phases share it.

Short answer

6. List the three kinds of machine code a compiler can generate.

Pure machine code, augmented machine code, virtual machine code.

7. List the three target code formats, with one advantage and one disadvantage of each.
FormatAdvantageDisadvantage
AssemblyEasy to translate and check; cross-compilationNeeds an assembler pass
Relocatable binaryModular compilation, libraries, cross-language callsNeeds a linking step
Absolute binaryRuns immediately, no linking, good for debuggingMust recompile every run; hard to interface with other code
8. Which target format is best for cross-compilation, and why?

Assembly language: its symbolic form is easy to move to another computer and assemble there.

9. Classify each error: (a) x = y + ; (b) using an undeclared variable (c) array index out of bounds while running.

(a) Syntax error, caught by the parser. (b) Static semantic error, caught by the type checker. (c) Runtime semantics, detected while the program runs.

10. What is the difference between a compiler and an interpreter?

A compiler first produces a target program (compilation phase) and then that program runs (execution phase). An interpreter executes the source program directly, with no separate target program.

11. Which phases belong to the front-end and which to the back-end?

Front-end (analysis): scanner, parser, type checker (and translator to IR). Back-end (synthesis): optimizer, code generator.

12. Using the attribute grammar rule for E → E + T, what happens if one operand is Boolean?

The condition "v1.type = numeric and v2.type = numeric" fails, so ERROR() is called.

13. What do Lex and Yacc generate, and what is each one's input?

Lex generates a scanner; its input is the tokens written as regular expressions. Yacc generates a parser; its input is a grammar.

Problem

14. Draw the phases of a syntax-directed compiler and label the data passed between each pair.
source → Scanner → tokens → Parser → AST → Type checker → decorated AST
       → Translator → IR → Optimizer → IR → Code generator → target code
(all phases use the Symbol table)

Chapter 2 · The ac compiler

True / False

1. In ac, p can be used as a variable name.

False. f, i and p are keywords, which leaves 23 variable names.

2. A float value can be assigned to an integer variable in ac.

False. Only int → float is converted automatically; float → int is a type error.

3. In recursive descent, a λ-production generates no code.

True.

4. A pass can contain several phases.

True.

5. Type checking in ac walks the AST top-down.

False. It walks bottom-up, from the leaves to the root.

Short answer

6. Convert (a + b) * c - d / e to postfix and to prefix.

Postfix: a b + c * d e / -
Prefix: - * + a b c / d e

7. Evaluate the RPN expression 5 1 2 + 4 * + 3 -. Show the stack.
5        → [5]
1 2 +    → [5, 3]
4 *      → [5, 12]
+        → [17]
3 -      → [14]          answer: 14
8. What is the predict set of Dcls → λ, and why?

{ id, print, $ }. Dcls can vanish, so we look at what follows it: in Prog → Dcls Stmts $, that is FIRST(Stmts) = {id, print} plus, because Stmts can also vanish, $.

9. What does MATCH(ts, x) do?

If the next token is x, it consumes it; otherwise it reports a syntax error.

10. Give three ways the AST differs from the parse tree.

It drops punctuation and λ leaves; declarations keep only the name and type; each assignment node has exactly 2 children (target id and expression). For example, a + 3.2 takes 8 nodes in the parse tree but 3 in the AST.

11. Is i a a = 3.5 a valid ac program? Which phase decides?

No. It is syntactically fine, but assigning a float to an integer variable is a type error, so the semantic analysis (type checking) phase rejects it.

Problems

12. Tokenize f x i y y = 3 x = y + 2.5 p x.

floatdcl id(x) intdcl id(y) id(y) assign inum(3) id(x) assign id(y) plus fnum(2.5) print id(x) $

13. Write the recursive-descent procedure for Dcls → Dcl Dcls | λ.
procedure Dcls()
    if ts.peek() = floatdcl or ts.peek() = intdcl then
        call Dcl(); call Dcls()
    else if ts.peek() ∈ {id, print, $} then
        /* λ: do nothing */
    else call ERROR()
14. Generate the dc code for i a f b a = 2 b = a + 1.5 p b.
2 sa 0 k              a = 2
la 5 k 1.5 + sb 0 k   b = a + 1.5   (5 k is the int2float conversion)
lb p si               p b
15. Draw the AST after semantic analysis for b = a + 3.2, where a is int and b is float.
assign : float
 ├─ id b
 └─ plus : float
     ├─ int2float : float ── id a
     └─ fnum 3.2

Chapter 3 · Scanning

True / False

1. Every finite language is regular.

True. Write it as s1 | s2 | … | sn.

2. { anbn | n ≥ 0 } is regular.

False. An FA has finite memory and can't count n.

3. Every NFA has an equivalent DFA.

True. Use subset construction.

4. An NFA with n states gives a DFA with at most 2n states.

False. At most 2n states.

5. A DFA can have λ transitions.

False. Only NFAs can.

Short answer

6. Write REs over {a, b} for: (a) an even number of a's (b) strings starting and ending with b.

(a) b*(a b* a b*)*
(b) b | b(a|b)*b

7. Write an RE for binary strings with no two consecutive 0s.

(1 | 01)* (0 | λ)

8. Which match RealLit = (D+(λ|.)) | (D*.D+): 12, 12., .5, ., 1.2.3?

12 · 12. · .5 · . · 1.2.3

9. Table-driven vs explicit-control scanner?

Table-driven: the transition table is stored as data and a generic driver loop reads it. Explicit control: the transitions are written directly as if/while statements in the code.

10. Define CLOSE(S). Using the slides NFA (0 –ε→ 1, 0 –ε→ 3, 2 –ε→ 5, 4 –ε→ 5, 5 –ε→ 0, 5 –ε→ 6), find CLOSE({2}).

CLOSE(S) is every state reachable from S using only λ/ε edges, including S itself. CLOSE({2}) = {2, 5, 6, 0, 1, 3}.

11. What is a transducer? Give the slides example.

An FA that also transforms or records its input. Example: quoted strings "(Not(")|"")*", where "it's an ""easy"" job" becomes it's an "easy" job.

Problems

12. Draw the Thompson NFA for a (b | c)*.
s0 --a--> s1 --λ--> s2                    (s2 = start of the * part)
s2 --λ--> s3 ;  s2 --λ--> s9              (enter loop / skip loop)
s3 --λ--> s4 --b--> s5 --λ--> s8          (b branch)
s3 --λ--> s6 --c--> s7 --λ--> s8          (c branch)
s8 --λ--> s3 ;  s8 --λ--> s9              (repeat / leave)
s9 = accepting
13. Convert the NFA for (a|b)*abb to a DFA. NFA: 0 –a,b→ 0, 0 –a→ 1, 1 –b→ 2, 2 –b→ 3 (accept).
DFAab
{0} start{0,1}{0}
{0,1}{0,1}{0,2}
{0,2}{0,1}{0,3}
{0,3} accept{0,1}{0}
14. Minimize: A start; E accepting. A: a→B, b→C · B: a→B, b→D · C: a→B, b→C · D: a→B, b→E · E: a→B, b→C

Start: {A,B,C,D} and {E}.
On b, D goes to E (accepting) and the others don't → split: {A,B,C}, {D}, {E}.
On b, B goes to D but A and C go to C → split: {A,C}, {B}, {D}, {E}.
{A,C}: on a → B, B; on b → C, C. They agree, so stop.
Result: 4 states. AC –a→ B, AC –b→ AC, B –a→ B, B –b→ D, D –a→ B, D –b→ E, E –a→ B, E –b→ AC.

15. Convert to an RE: 1 start, 1 –a→ 2, 2 –b→ 2, 2 –c→ 3, 3 accepting.

Remove state 2 with T3 (X = a, loop Z = b, Y = c): a b* c.

Chapter 4 · Grammars and Parsing

True / False

1. λ can belong to a FOLLOW set.

False. FOLLOW holds only terminals (and $).

2. A rightmost derivation is also called a canonical derivation.

True.

3. There is an algorithm that decides if any CFG is ambiguous.

False. It is undecidable.

4. Top-down parsers produce a rightmost derivation.

False. Top-down gives a leftmost derivation; bottom-up gives a rightmost one, in reverse.

5. The handle is the leftmost simple phrase.

True.

Short answer

6. Name the four parts of G = (N, Σ, P, S), and define L(G).

N = nonterminals, Σ = terminals, P = productions, S = start symbol. L(G) = { w ∈ Σ* | S ⇒+ w }.

7. Using E → Prefix ( E ) | v Tail, Prefix → f | λ, Tail → + E | λ, give leftmost and rightmost derivations of f ( v ).
lm: E ⇒ Prefix ( E ) ⇒ f ( E ) ⇒ f ( v Tail ) ⇒ f ( v )
rm: E ⇒ Prefix ( E ) ⇒ Prefix ( v Tail ) ⇒ Prefix ( v ) ⇒ f ( v )
8. In the sentential form Prefix ( v Tail ), what are the simple phrases and the handle?

The tree is E → Prefix ( E ) with the inner E → v Tail. The only simple phrase is v Tail, so the handle is v Tail. (Prefix has not been expanded yet, so it is not a phrase by itself.)

9. What do the letters in LL(1) and LR(1) mean?

First L: read input Left to right. Second letter: Leftmost or Rightmost derivation. (1): one lookahead token.

10. What are the predict sets of E' → + T E' and E' → λ?

{ + } and FOLLOW(E') = { ), $ }.

Problems

11. Show the dangling-else grammar is ambiguous: S → if E then S | if E then S else S | other

The string if E then if E then other else other has two parse trees. In one, the else belongs to the inner if; in the other, it belongs to the outer if.

12. Find the reduced grammar: S → A B | a, A → a, B → b B, C → c

B never terminates, so remove B and S → A B. Now A is unreachable, and C was always unreachable. Reduced grammar: S → a. (Trap: A only becomes useless after B is removed.)

13. Convert to standard BNF: Params → ( [ id { , id } ] )
Params  → ( OptList )
OptList → id Rest | λ
Rest    → , id Rest | λ
14. Compute FIRST and FOLLOW (Aho style): S → A C B | C b b | B a, A → d a | B C, B → g | λ, C → h | λ
FIRSTFOLLOW
S{d, g, h, b, a, λ}{$}
A{d, g, h, λ}{h, g, $}
B{g, λ}{a, h, g, $}
C{h, λ}{b, g, h, $}

Key steps: A → B C can vanish, so S → A C B can be fully empty (λ ∈ FIRST(S)). FOLLOW(C) gets b from C b b, g and $ from C B at the end of S, and FOLLOW(A) from A → B C.

15. Which nonterminals in question 14 can derive λ?

B and C directly; A through A → B C; S through S → A C B. So all four.

Mixed quick-fire

An NFA has 4 states. What is the maximum number of states in the equivalent DFA?

24 = 16.

Why separate scanning from parsing?

Tokens are regular, so a simple fast FA can handle them, and the parser then works on a compact token stream. Separate phases are easier to write and maintain.

What three things does a scanner do besides producing tokens?

Removes comments and whitespace; processes compiler directives; enters preliminary info into the symbol table.

Why can't the scanner check balanced parentheses?

Balanced brackets are not regular, so they need a CFG, which means the parser.

Cheat sheet

Everything worth memorizing, one chapter after another. Read it the night before and again just before the exam.

Chapter 1 · Introduction

Compiler
Translator from source language to target (machine) language. First real compilers: FORTRAN, late 1950s
Front-end
Analysis: scanner, parser, type checker → builds the IR
Back-end
Synthesis: optimizer, code generator → target code
Pure code
Only real machine instructions, no OS or libraries. OS kernels, embedded
Augmented code
Machine code + OS routines + runtime support routines
Virtual code
VM instructions (Java bytecode, P-code). Portable: one interpreter per machine
Assembly format
+ easy translation, cross-compilation, readable output · − needs assembler
Relocatable
+ modular compilation, libraries, cross-language calls · − needs linker
Absolute binary
+ runs immediately, no linking, good for debugging · − recompile every run
Compiler
Compile phase then execute phase
Interpreter
Executes source directly
Syntax
Structure, CFG. b+c=a is illegal
Static semantics
Compile-time rules: declarations, types, number of parameters. Attribute grammars
Runtime semantics
What the program computes; e.g. index out of bounds
Syntax-directed
Parser's recognition of structure drives every other phase
Symbol table
Identifier info shared by all phases
Tools
Lex → scanner (from REs) · Yacc → parser (from grammar)
Scanner → tokens → Parser → AST → Type checker → decorated AST
→ Translator → IR → Optimizer → IR → Code generator → target code

Chapter 2 · The ac compiler

Pass / phase
Pass = one traversal of the whole program · phase = one stage · a pass can hold several phases
ac types
integer, float (5 fractional digits), int → float automatic, never float → int
Keywords
f float · i integer · p print → 23 variable names left
Target
dc, a stack calculator using postfix (RPN)
Token
Type (which terminal) + semantic value (name, number)
Scanner
One character of lookahead: peek() looks, advance() consumes
Recursive descent
One procedure per nonterminal · terminal → MATCH · nonterminal → call · λ → nothing
Predict
Peek at the next token and choose the production whose predict set contains it
AST
No punctuation; decl = name + type; assign has 2 children; a + 3.2: 8 parse nodes → 3 AST nodes
Semantic analysis
Symbol table (23 entries, int / float / null) + type checking bottom-up, inserts int2float
Prog  → Dcls Stmts $        Stmt → id assign Val Expr | print id
Dcls  → Dcl Dcls | λ        Expr → plus Val Expr | minus Val Expr | λ
Dcl   → floatdcl id | intdcl id      Val → id | inum | fnum
Stmts → Stmt Stmts | λ

dc:  5 sa 0 k            store a, precision 0
     la 5 k 3.2 + sb 0 k load a, float mode, add, store b
     lb p si             print b, pop into register i
Infix → postfix
(3+5)*(7-2) → 3 5 + 7 2 - * = 40 · prefix * + 3 5 - 7 2
RPN rule
Operator pops two; the lower one is the left operand

Chapter 3 · Scanning

Lexeme
One actual instance of a token class
RE operations
PQ catenation · P|Q alternation · P* zero or more · P+ one or more · Not(A) · Ak
Identities
P* = P+ | λ · P+ = P*P · sλ = λs = s
Regular
Every finite set · many infinite ones
Not regular
anbn, balanced brackets [m]m: FA has finite memory
FA
States, Σ, transitions, one start, accepting states
DFA
Unique transition per symbol, no λ, stored as table T[s, c]
NFA
λ edges and several edges on one symbol
Coding a DFA
Table-driven (driver reads table) · explicit control (if/while code)
Transducer
FA that also outputs or records something; action table parallel to transition table
Size blow-up
n-state NFA → up to 2n DFA states
Minimal DFA
Unique. Remove unreachable and dead states, then split
Comment  = // (Not(Eol))* Eol
RealLit  = (D+ (λ | .)) | (D* . D+)
ID       = L (L | D)* ( _ (L | D)+ )*

RE → NFA      atoms a, λ; glue A|B, AB, A* with λ edges
NFA → DFA     start = CLOSE({s0}); each step = CLOSE(move(S, c));
              accepting = any set holding an NFA final state
Minimize      groups {accept} {non-accept}; split on disagreement; repeat
FA → RE       T1 R|S (parallel)  T2 XY (bypass)  T3 XZ*Y (bypass loop)

Chapter 4 · Grammars and parsing

CFG
G = (N, Σ, P, S) · V = N ∪ Σ · N ∩ Σ = ∅
Language
L(G) = { w ∈ Σ* | S ⇒+ w } = SF(G) ∩ Σ*
Sentential form
Any β with S ⇒* β
Leftmost
Expand leftmost nonterminal · top-down parsers
Rightmost
Canonical · bottom-up parsers (in reverse)
Phrase
Symbols derived from one nonterminal
Simple phrase
Contains no smaller phrase
Handle
Leftmost simple phrase. In f ( v Tail ) the handle is f
Useless
Non-terminating or unreachable. Remove non-terminating first, then recheck reachability
Ambiguous
2+ parse trees for one string. Undecidable in general
EBNF
[X] → N → X | λ · {X} → N → X N | λ
Recognizer
Only answers x ∈ L(G)
Parser
Also builds the structure
Top-down
Root first, preorder, predictive, LL(1)
Bottom-up
Leaves first, postorder, LR(1)
LL(1)
Left-to-right scan · Leftmost derivation · 1 token lookahead
FIRST(X1…Xk): add FIRST(X1)−λ; if X1 ⇒* λ add FIRST(X2)−λ; …
              if all Xi ⇒* λ add λ
FOLLOW:       $ ∈ FOLLOW(S)
              A → αBβ        add FIRST(β)−λ to FOLLOW(B)
              A → αB, or β ⇒* λ   add FOLLOW(A) to FOLLOW(B)
Predict(A→α) = FIRST(α)−λ, plus FOLLOW(A) if α ⇒* λ

E → T E'   E' → + T E' | λ   T → F T'   T' → * F T' | λ   F → ( E ) | id
FIRST  E T F = { (, id }   E' = { +, λ }   T' = { *, λ }
FOLLOW E E'  = { ), $ }    T T' = { +, ), $ }   F = { *, +, ), $ }
Two styles
Aho: λ in FIRST, $ in FOLLOW(S) · Fischer: no λ in FIRST, $ written in the grammar, FOLLOW(S) may be { }