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

The Problem

A token stream is still flat and lacks structure. The compiler needs to verify whether the sequence of tokens forms a valid program according to the language’s grammar — checking for missing semicolons, unbalanced parentheses, incorrect statement ordering, and structural violations.

Core Idea

Syntax analysis (parsing) is the second phase of a compiler. It takes the token stream from the lexer and determines whether it conforms to the grammar rules of the programming language. The output is typically a parse tree (or syntax tree) that represents the grammatical structure of the program.

How It Works

The parser reads tokens and applies grammar rules to build a derivation of the program. It uses a context-free grammar (CFG) as its specification. Two major parsing strategies exist: top-down (builds the tree from the start symbol, expanding non-terminals) and bottom-up (builds the tree from the tokens, reducing to the start symbol).

Visual Explanation

syntax_analysis Tokens Token Stream <id> <=> <num> <;> Parser Parser (Syntax Analysis) Tokens->Parser ParseTree Parse Tree    =   / \  id  42 Parser->ParseTree valid program SymbolTable Symbol Table Parser->SymbolTable adds identifiers Error Syntax Error Reporting Parser->Error invalid program

Key Properties

  • Input: Token stream from lexical analysis
  • Output: Parse tree / syntax tree (or error)
  • Grammar-based: Uses a context-free grammar to define valid syntax
  • Error recovery: Can report errors and continue parsing to find more errors
  • Two strategies: Top-down (recursive descent, LL) vs bottom-up (LR, LALR)

Connections

Edge Cases & Gotchas

  • Left recursion: Top-down parsers cannot handle left-recursive grammars — must be eliminated
  • Ambiguity: An ambiguous grammar can produce two different parse trees for the same program
  • Error recovery strategies: Panic mode (skip tokens until sync token found), phrase-level recovery, error productions