Example of phase of compiler – Lexical/Syntax/Semantic Intermediate Code Target

Example of phase of compiler – Lexical/Syntax/Semantic Intermediate Code Target



play-rounded-fill play-rounded-outline play-sharp-fill play-sharp-outline
pause-sharp-outline pause-sharp-fill pause-rounded-outline pause-rounded-fill
00:00

Phases of a Compiler – Examples for Each Phase

A compiler translates high-level code into machine code through multiple phases. These phases can be categorized into front-end (analysis) and back-end (synthesis) processes.

 1. Lexical Analysis (Tokenization)

  • Purpose: Converts source code into a sequence of tokens.

  • Example:
    Input Code (C language):

    int x = 10;

    Output (Tokens):

    Keyword: int
    Identifier: x
    Operator: =
    Number: 10
    Symbol: ;

Tool Used: Lexical Analyzer (Lexer)

 2. Syntax Analysis (Parsing)

  • Purpose: Checks if tokens form a valid syntax according to the language grammar.

  • Example:
    Input Tokens:

    int x = 10;

    Parsing Tree (Abstract Syntax Tree – AST):

    =
    / \
    int 10
    \
    x

    Error Detected: Missing semicolon (;) or incorrect placement of keywords.

Tool Used: Parser

 3. Semantic Analysis (Meaning Verification)

  • Purpose: Ensures code makes logical sense (type checking, scope checking, etc.).

  • Example:
    Input Code:

    int x;
    x = "Hello"; // Error: Type mismatch

    Error: x is declared as an integer, but assigned a string value.

Tool Used: Semantic Analyzer

 4. Intermediate Code Generation

  • Purpose: Converts the code into an intermediate representation (IR) that is independent of machine architecture.

  • Example (Three-Address Code Representation):
    Input Code:

    a = b + c * d;

    Intermediate Code (Three-Address Code – TAC):

    t1 = c * d
    t2 = b + t1
    a = t2

Tool Used: Intermediate Code Generator

 5. Target Code Generation

  • Purpose: Converts intermediate code into machine code (assembly language) for execution.

  • Example (x86 Assembly Code):

    MOV R1, c
    MUL R1, d
    MOV R2, b
    ADD R2, R1
    MOV a, R2

Tool Used: Code Generator

 Summary Table

Phase Purpose Example Output
Lexical Analysis Converts code into tokens int → Keyword, x → Identifier
Syntax Analysis Creates syntax tree Parses expressions a = b + c;
Semantic Analysis Checks for logical errors Type mismatch: int vs string
Intermediate Code Converts code to IR (Three-Address Code) t1 = c * d
Target Code Generation Generates machine/assembly code MOV R1, c

Would you like me to explain Compiler Optimizations as well?

Example of phase of compiler – Lexical/Syntax/Semantic Intermediate Code Target



Leave a Reply

Your email address will not be published. Required fields are marked *

error: