Back to the 2023 paper

Module 1: Introduction, Lexical Analysis

20237m

Explain the working of each phase of compiler in detail with an example.

Worked SolutionAI Assisted

The six phases of a compiler (with an example)

A compiler translates a high-level program into target (machine) code in several phases. They are divided into the front end (source-language dependent) and back end (machine dependent).

  1. Lexical Analysis (Scanner)

    • Reads the raw character stream and groups it into meaningful tokens (identifiers, keywords, operators, literals).
    • Output: a stream of tokens ⟨type, attribute⟩\langle \text{type, attribute}\rangle.
    • Uses a symbol table to record identifiers.
    • Example: for position = initial + rate * 60, tokens are: ident(position), =, ident(initial), +, ident(rate), *, num(60).
  2. Syntax Analysis (Parsing)

    • Groups tokens into a parse tree / syntax tree according to the grammar.
    • Detects syntactic errors (e.g. x = + * y).
    • Output: a parse tree (for position = initial + rate*60 we get precedence built in: rate*60 is computed first).
  3. Semantic Analysis

    • Checks the parse tree for semantic correctness: type checking, name/declaration matching, etc.
    • For types: if position, initial, rate are float and 10 is int, it may insert implicit conversion int→real.
    • Output: annotated syntax tree.
  4. Intermediate Code Generation

    • Produces a machine-independent intermediate representation (e.g. three-address code).
    • Example for the above assignment:
      t1 = int_to_float(10)
      t2 = rate * t1
      t3 = initial + t2
      position = t3
      
  5. Code Optimization

    • Improves the intermediate code, e.g. reduces t1 = int_to_float(10) because 10 is a constant that can be folded and converted once. After optimization:
      t2 = rate * 10.0
      position = initial + t2
      
  6. Code Generation (Target Code Generation)

    • Maps optimized intermediate code onto target machine's assembly instructions, e.g.:
      MOVF R2, #10.0      (or LDF)
      MULF R2, R1
      ADDF R2, R0
      MOVF position, R2
      

Symbol Table is a central data structure maintained throughout all phases, storing names, types, scope, and addresses.

Order: Lexical → Syntax → Semantic → Intermediate Code → Optimization → Code Generation\boxed{\text{Order: Lexical → Syntax → Semantic → Intermediate Code → Optimization → Code Generation}}

Similar questions

Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.