• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

A program can be syntactically correct but semantically meaningless or unsafe. For example, adding a string to an integer or using an undeclared variable passes syntax analysis but makes no sense. The compiler needs to catch these logical and type errors.

Core Idea

Semantic analysis is the third phase of a compiler. It checks the source program for semantic consistency — type compatibility, variable declaration before use, function call argument matching, and scope rules. It augments the syntax tree with type information and performs type checking.

How It Works

The semantic analyzer traverses the syntax tree (or parse tree) and verifies semantic rules. It checks that every identifier is declared, that types are compatible in expressions and assignments, that function calls match their signatures, and that control flow constructs are well-formed. It uses the symbol table extensively to resolve identifiers and their attributes.

Visual Explanation

semantic_analysis ParseTree Parse Tree    =   / \  id  42 Semantic Semantic Analyzer ParseTree->Semantic Augmented Annotated Syntax Tree Semantic->Augmented with type info SymbolTable Symbol Table count: int sum: float Augmented->SymbolTable updates SymbolTable->Semantic lookup

Key Properties

  • Input: Parse tree / syntax tree
  • Output: Annotated syntax tree with type information
  • Type checking: Ensures operands have compatible types
  • Scope resolution: Maps identifier usages to their declarations
  • L-value/R-value checking: Ensures the left side of assignment is an l-value

Connections

Edge Cases & Gotchas

  • Type coercion: Languages like C automatically convert int to float — the analyzer must insert implicit type conversion nodes
  • Duck typing: Dynamically typed languages defer type checking to runtime — semantic analysis in their compilers is lighter
  • Function overloading: The semantic analyzer must resolve which overloaded function is being called based on argument types