CS Atlas GATE 2027
Compiler Design course
0 / 90 complete

Compiler Design/Phase 0 · Foundations

Lesson 0.1.3 · Item 4 of 90

The phases of a compiler; symbol table; error handler; which phase catches which error

Read at your own pace. Try the questions before opening the answers.

On this page

0 · Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the end of this lesson.

  • Which tool runs immediately before the compiler, and what does it do? from Lesson 0.1.2
  • What does the compiler hand to the assembler? from Lesson 0.1.2
  • Name one advantage of a compiler over an interpreter. from Lesson 0.1.1

1 · The Story

📖

Inside the translation team

Mr. Patel’s booklet is made by six desks, one after another. His first line is: “Aaje dudh no bhaav vadhyo.” (“Today the price of milk went up.”)

Mira at the Word Desk receives a stream of letters with spaces and commas. She cuts it into words and stamps each word with its kind: Aaje → time-word, dudh → noun, bhaav → noun, vadhyo → verb. A stray “@” in the middle of a word is something she cannot stamp, so she complains. Every new name she meets (“Ramesh”, “Surat”) she writes in the Index Book, which every desk can read and add to.

Kabir at the Sentence Desk receives only the stamped words. He checks that they form a proper sentence shape and groups them: [today] [[milk’s] price] [went up]. Two verbs and no noun? He complains.

Anaya at the Meaning Desk checks that the grouped sentence makes sense: the verb agrees with its subject, every person mentioned was introduced earlier (she looks names up in the Index Book). “The price drank milk” has a proper shape but no sense, so she complains.

Dev in the Drafting Room writes a plain, literal English draft in very short sentences that any English desk can work from. Ishaan in the Optimization Room removes repetition so the draft says the same thing in fewer words. Zoya in the Print Room produces the final English text in the booklet’s exact format.

All complaints go to one Complaints Desk, which records them and lets work continue so that many problems are found in one round.

Mrs. Desai’s best idea: the first three desks understand Gujarati; the last three only ever see the plain English draft. When a Marathi speaker arrives, she hires three new Marathi-reading desks and reuses the same Drafting, Optimization and Print rooms.

2 · Predict First

🤔

A programmer writes whlie (x < 5) x++; (a misspelled while). Which desk complains first: the Word Desk, the Sentence Desk or the Meaning Desk? Write your guess down. The answer is in the vault.

3 · Core Concept

Two halves: analysis and synthesis

A compiler works in two halves.

  • Analysis (the front end) breaks the source program into pieces, checks it, and records information about every name. It depends on the source language.
  • Synthesis (the back end) builds the target program from a simple, machine-independent intermediate code. It depends on the target machine.

The six phases

PhaseReadsProduces
1. Lexical analyzer (scanner)characters of the sourcetokens: each word stamped with its kind, e.g. ⟨id,1⟩, ⟨=⟩, ⟨num,50⟩
2. Syntax analyzer (parser)tokensthe grouping structure of the program, checked against the language’s grammar rules
3. Semantic analyzerthe structure + symbol tablethe same structure, checked for meaning: declarations, types (type checking), with conversions inserted
4. Intermediate code generatorchecked structuresimple machine-independent code, one operation per line, using helper names temporaries t1, t2, …
5. Code optimizerintermediate codebetter intermediate code: same meaning, fewer or cheaper steps
6. Code generatorintermediate codetarget code (assembly or machine code), choosing registers and memory locations

Symbol table

The symbol table is one table shared by all phases. It has one entry per name used in the program (variables, functions) recording what is known about it: its type, where it was declared, its memory location, and for functions, the number and types of parameters.

The early phases fill it in; the later phases read it.

Error handler

Every phase can find errors. The error handler reports each error with its position and helps the compiler continue, so one compilation reports many errors instead of stopping at the first.

Which phase catches which error (GATE favourite)

ErrorExampleCaught by
illegal charactera = b @ c;lexical analyzer
quoted text or comment never closedprintf("hi);lexical analyzer
misspelled keywordwhlie (x<5) x++;not lexical: whlie is a valid name; shows up as a syntax error
missing semicolon, unbalanced bracketsa = (b + c;syntax analyzer
undeclared variabley = x + 1; with x never declaredsemantic analyzer
type mismatchassigning a number to an array namesemantic analyzer
wrong number of argumentsf(1, 2) when f takes one intsemantic analyzer
division by zero from input, index out of range, infinite loopx = 10 / y; with y = 0 read at run timenot caught by the compiler (run-time or logical error)

The journey line through all six phases

Throughout these notes one line travels through the compiler. Here is its whole trip at a glance (later phases explain every step). Assume total and price are float and qty is int.

PhaseOutput for total = price * qty + 50;
Lexical⟨id,1⟩ ⟨=⟩ ⟨id,2⟩ ⟨*⟩ ⟨id,3⟩ ⟨+⟩ ⟨num,50⟩ ⟨;⟩ — 8 tokens; symbol table: 1 total, 2 price, 3 qty
Syntaxtotal = ((price * qty) + 50) — the grouping is now explicit
Semantictotal = ((price * inttofloat(qty)) + 50.0) — qty converted to float
Intermediate codet1 = inttofloat(qty) t2 = price * t1 t3 = t2 + 50.0 total = t3
Optimizert1 = inttofloat(qty) t2 = price * t1 total = t2 + 50.0
Code generatorLD R2, qty / ITOF R2, R2 / LDF R1, price / MULF R1, R1, R2 / ADDF R1, R1, #50.0 / STF total, R1

Passes

A pass is one complete reading of the program (or of its intermediate form). Several phases are often combined in one pass: for example lexical, syntax and semantic analysis and intermediate code generation can run together, with the parser asking the scanner for the next token whenever it needs one. A one-pass compiler reads the source once; a multi-pass compiler reads some form of the program several times (useful for optimization).

Why split front end and back end?

With m source languages and n target machines, separate compilers for every pair need m × n compilers. With a shared intermediate code you need only m front ends + n back ends. Four languages and three machines: 12 full compilers, or just 7 parts.

Story → compiler term

In the storyIn the compiler
Mira at the Word Desklexical analyzer (scanner)
words stamped with their kindtokens
Kabir at the Sentence Desksyntax analyzer (parser)
Anaya at the Meaning Desksemantic analyzer (type checking, declarations)
Dev’s plain literal draftintermediate code
Ishaan shortening the draftcode optimizer
Zoya’s final printed textcode generator → target code
the Index Booksymbol table
the Complaints Deskerror handler
the three Gujarati-reading desksanalysis = front end
the three English-only desks, reused for Marathisynthesis = back end

4 · Visual

Diagram: Lexical analyzer · characters → tokens · ⟨id,1⟩ ⟨=⟩ ⟨id,2⟩ ⟨⟩ … · Syntax analyzer · tokens → structure · total = ((priceqty)+50) · Semantic analyzer · checks meaning, types · … inttofloat(qty) … · Intermediate code · one operation per line · t1 = … t2 = … t3 = … · Code optimizer · same meaning, cheaper · t1, t2 only · Code generator · target code

The six phases. Front end = the first three (analysis); back end = the last three (synthesis). All six read and write the symbol table and report to the error handler.

#NameKindTypeDeclared at
1totalvariablefloatline 2
2pricevariablefloatline 2
3qtyvariableintline 3

The symbol table for the journey line: tokens refer to entries by number, like ⟨id,2⟩ for price.

5 · Worked Examples

Example 1 Easy

Name the phase that reports each error: (a) a = b @ c; (b) a = (b + c; (c) a = b + count; where count is never declared (d) x = 10 / y; where y is read from input and happens to be 0.

Solution

(a) lexical: “@” is not a character any word of C can contain, just as Mira cannot stamp a word with “@” in it. (b) syntax: the brackets do not balance, a sentence-shape problem for Kabir. (c) semantic: the name must be looked up in the symbol table, a meaning check for Anaya. (d) none: the compiler never sees the value of y; it is a run-time error.

Example 2 Medium

Trace total = price * qty + 50; through the phases (price, total float; qty int).

Solution

See the journey table above. The key steps: the lexical analyzer produces 8 tokens and fills the symbol table; the parser makes the grouping (price*qty)+50 explicit because * binds tighter than +; the semantic analyzer inserts inttofloat(qty) and turns 50 into 50.0; the intermediate code uses temporaries t1–t3; the optimizer removes t3 by assigning the sum directly to total; the code generator emits loads, a float multiply, a float add and a store.

Example 3 GATE

Which phase reports each of these? (i) whlie (x < 5) x++; (ii) int a; a = ; (iii) int a[10]; a = 5;

Solution

(i) Syntax. The scanner happily returns whlie as an identifier; the parser then sees a call whlie(x < 5) immediately followed by x, which no statement shape allows.

(ii) Syntax: an assignment needs an expression after =.

(iii) Semantic: the statement is shaped correctly, but an array name cannot be assigned a number, a type error found with the symbol table.

6 · Shortcuts

⚡

How much context does the error need? One word alone → lexical. The arrangement of words in this statement → syntax. Facts from other lines (declarations, types) → semantic. The actual input values → run time. Valid when: classifying a single error in C-like code.

⚡

Reuse count: m languages and n machines need m × n compilers without a shared intermediate code, but only m + n front and back ends with one. Valid when: questions about why compilers have a front end and a back end.

7 · GATE Traps

⚠️

  • A misspelled keyword is not a lexical error: it is a valid identifier, and the trouble shows up in the parser.
  • Undeclared variables and type mismatches are semantic errors, because the check needs the symbol table, not just the shape of the statement.
  • Division by zero or an out-of-range index caused by input values is a run-time error: no compiler phase can catch it.
  • The symbol table is used by every phase, not only the lexical analyzer.
  • The optimizer must never change what the program computes; it is also the phase most often switched off.
  • Phases are a logical split; a real compiler may run several phases together in one pass.

8 · Memory Hook

🧠

“Lazy Students Sleep In Our Classes”: Lexical, Syntax, Semantic, Intermediate code, Optimizer, Code generator. Words, sentences, meaning, draft, polish, print.

9 · Connect the Dots

You now know the six departments and what each one hands on. Before we can study the first department properly, we need exact vocabulary for “a sequence of characters” and “a collection of such sequences”. That is the next primer.

10 · Self-Test

GATE format. Try every question before opening the vault.

Q1MCQ1 markError phase

An undeclared variable is detected during:

  • (A) lexical analysis
  • (B) syntax analysis
  • (C) semantic analysis
  • (D) code generation

Q2MCQ1 markError phase

A missing closing parenthesis in if (x > 0 { … } is reported by:

  • (A) the lexical analyzer
  • (B) the syntax analyzer
  • (C) the semantic analyzer
  • (D) the loader

Q3NAT1 markFront/back end

A company supports 5 source languages on 4 target machines and shares one intermediate code. How many front ends plus back ends must it write?

Numerical answer: ________

Q4MSQ1 markAnalysis

Which phases belong to the analysis part (front end) of a compiler?

  • (A) lexical analysis
  • (B) syntax analysis
  • (C) semantic analysis
  • (D) code generation

Q5MCQ1 markSymbol table

The symbol table is best described as:

  • (A) a table used only by the lexical analyzer
  • (B) a table shared by all phases holding information about each name
  • (C) the final output of the compiler
  • (D) a list of error messages

11 · Rule Card

  • Phases: lexical → syntax → semantic → intermediate code → optimizer → code generator.
  • Front end (analysis) = first three, language-dependent; back end (synthesis) = last three, machine-dependent.
  • Symbol table: one entry per name (type, location, …), shared by all phases.
  • Errors: illegal character → lexical; shape/brackets/semicolon → syntax; undeclared/types/argument count → semantic; input-dependent → run time.
  • A misspelled keyword is an identifier to the scanner.
  • m languages × n machines: m × n compilers vs m + n parts.

12 · Concept Ledger

phaseanalysis / front endsynthesis / back endlexical analyzer (scanner)tokensyntax analyzer (parser)semantic analyzertype checkingintermediate codetemporary (t1, t2, …)code optimizercode generatorsymbol tableerror handlerlexical / syntax / semantic errorpass

13 · Answer Vault

Answer Vault

Try the questions first. Open when you are ready to check.

Warm-up

  • The preprocessor. It expands # lines: pastes header files and replaces macros, purely as text.
  • Assembly language: readable mnemonics, one machine instruction per line.
  • The program runs faster, because translation happens once before running; source errors are reported before running.

Predict First

Not the Word Desk. whlie is a perfectly good name, so the lexical analyzer stamps it as an identifier. The problem appears at the Sentence Desk: whlie(x < 5) looks like a function call followed directly by x, with no semicolon between them, so the parser reports a syntax error.

Self-Test

Q1 Answer: (C)1 mark

Checking whether a name was declared needs the symbol table: a semantic check.

  • (A) is wrong: The scanner only sees the name as a valid identifier.
  • (B) is wrong: The statement is correctly shaped.
  • (D) is wrong: Code generation runs only on programs that passed the checks.

Re-read: Lesson 0.1.3 — The phases of a compiler; symbol table; error handler; which phase catches which error

Q2 Answer: (B)1 mark

Balanced brackets are part of the shape of a statement: syntax.

  • (A) is wrong: Every character here is legal and forms valid tokens.
  • (C) is wrong: Meaning is checked only after the shape is valid.
  • (D) is wrong: The loader never sees source code.

Re-read: Lesson 0.1.3 — The phases of a compiler; symbol table; error handler; which phase catches which error

Q3 Answer: 91 mark

m + n = 5 + 4 = 9 (instead of 5 × 4 = 20 full compilers).

Re-read: Lesson 0.1.3 — The phases of a compiler; symbol table; error handler; which phase catches which error

Q4 Answer: (A) (B) (C)1 mark

The front end understands and checks the source; code generation is synthesis (back end).

Re-read: Lesson 0.1.3 — The phases of a compiler; symbol table; error handler; which phase catches which error

Q5 Answer: (B)1 mark

All phases read or add information about names (type, location, parameters).

  • (A) is wrong: Later phases need types and locations too.
  • (C) is wrong: The final output is the target program.
  • (D) is wrong: Errors go to the error handler.

Re-read: Lesson 0.1.3 — The phases of a compiler; symbol table; error handler; which phase catches which error

Ready for the next idea?

Mark this item complete when you’ve finished reading and working through it.