Compilation and interpretation
How code gets translated
- Source code must become machine code to run.
- An interpreter does it line by line; a compiler does it all at once, in phases.
- Knowing the compiler's stages explains where each kind of error is caught.
How an interpreter runs a program
- An interpreter translates and runs the source at the same time, statement by statement.
- For each line it analyses, type-checks, then executes the action.
- Errors are reported immediately (and it usually stops); no executable is produced.
- It re-translates every run (slower) but gives fast feedback and is portable.
Practice
An interpreter:
It works line by line, reporting errors as it reaches them; nothing is saved as an executable, and it is generally slower.
The stages of compilation
- Lexical analysis — group characters into tokens (keywords, identifiers, operators), discarding whitespace/comments.
- Syntax analysis (parsing) — check the tokens fit the grammar and build an abstract syntax tree; a missing bracket is a syntax error.
- Semantic analysis — check it makes sense (variables declared, types match).
- Code generation — emit target machine code from the tree.
- Code optimisation — remove redundant work, fold constants, reorder for the pipeline.
Practice
Lexical analysis (the lexer) turns:
The lexer groups characters into tokens and discards whitespace/comments; parsing then builds the tree.
Practice
Which compiler stage catches a missing bracket?
Parsing checks the tokens against the grammar; a missing bracket breaks the grammar — a syntax error.
Practice
Put the compiler stages in order.
Lexical → syntax → semantic → code generation → optimisation.
Practice
Code optimisation aims to:
Optimisation improves the generated code (constant folding, removing redundancy, reordering for the pipeline).
You've got it
Key idea
- an interpreter translates + runs line by line (immediate errors, no executable, slower)
- compiler stages: lexical (tokens) → syntax (parse → AST) → semantic → code generation → optimisation
- a syntax error is caught during syntax analysis
- the compiler's output is a stand-alone executable