Semantic Analysis
Checking meaning after syntax — symbol tables and scopes, name resolution, type checking, type inference (Hindley–Milner), static vs dynamic typing, and other checks like definite assignment and reachability.
A program can be syntactically valid but meaningless:
let x: int = "hello"; // type mismatch
print(y); // y is undeclared
fn f(a: int) {} f(1, 2); // wrong number of arguments
return 5; // return outside a functionSemantic analysis walks the AST to catch these errors and to annotate the tree with information later phases need: what each name refers to, and the type of every expression.
Symbol tables and scopes
A symbol table maps names to declarations (kind, type, location). Because scopes nest, it's typically a stack of hash maps (or a chain of scope objects with parent pointers):
class Scope:
def __init__(self, parent=None):
self.symbols, self.parent = {}, parent
def declare(self, name, info):
if name in self.symbols:
raise SemanticError(f"'{name}' already declared in this scope")
self.symbols[name] = info
def lookup(self, name):
scope = self
while scope: # walk outward: innermost declaration wins
if name in scope.symbols:
return scope.symbols[name]
scope = scope.parent
raise SemanticError(f"undeclared name '{name}'")let x = 1; // global scope: x
fn f(y) { // function scope: y
let x = 2; // block scope: x shadows global x
{ let z = x + y; }// inner block: z; x resolves to the local x = 2
}Name resolution links each use of a name to its declaration. Languages differ: most use lexical (static) scoping — determined by program text (Scope and closures); some require declaration before use (C), others allow forward references within a scope (Java methods, Rust items), which requires a first pass to collect declarations.
Type checking
A type system assigns a type to each expression and checks rules like "both operands of + must be numbers" or "the argument type must match the parameter type". Type rules are often written as inference rules; the checker is a recursive function over the AST:
def check(node, scope) -> Type:
match node:
case Num():
return INT
case Str():
return STRING
case Var(name):
return scope.lookup(name).type
case Binary(op, left, right):
lt, rt = check(left, scope), check(right, scope)
if op in "+-*/":
if lt == rt == INT: return INT
if op == "+" and lt == rt == STRING: return STRING
raise TypeError(f"cannot apply {op} to {lt} and {rt}")
if op in ("<", ">", "==", "!="):
if lt != rt: raise TypeError(f"cannot compare {lt} with {rt}")
return BOOL
case Call(fn, args):
ft = check(fn, scope)
if len(args) != len(ft.params):
raise TypeError(f"expected {len(ft.params)} args, got {len(args)}")
for arg, param in zip(args, ft.params):
if not is_assignable(check(arg, scope), param):
raise TypeError("argument type mismatch")
return ft.returnsType system dimensions
| Dimension | Options | Examples |
|---|---|---|
| When types are checked | Static (compile time) vs dynamic (runtime) | Java, Rust, TypeScript vs Python, JavaScript, Ruby |
| How strictly | Strong (few implicit conversions) vs weak | Python is strong + dynamic; C is static + fairly weak; JS is dynamic + weak (Coercion) |
| Compatibility | Nominal (by declared name) vs structural (by shape) | Java, Rust vs TypeScript, Go interfaces |
| Annotations | Explicit vs inferred | Java (mostly explicit) vs Haskell, OCaml, Rust (let) |
Gradual typing mixes both: TypeScript and Python type hints are checked statically by a tool, but the runtime stays dynamic (Python typing).
Type inference
Many languages infer types so you don't write them:
let v = Vec::new(); // Vec<?> — element type unknown yet
v.push(3u8); // now inferred: Vec<u8>The classic algorithm is Hindley–Milner (ML, Haskell, OCaml; Rust uses a variant locally):
- Assign a fresh type variable to each unknown (
v : Vec<α>). - Walk the code generating constraints (
pushtakesα, givenu8, soα = u8). - Unify the constraints, solving for type variables; a contradiction is a type error.
- Generalise unconstrained variables in let-bound functions into polymorphic types (
id : ∀α. α → α).
Local inference (Java's var, C++'s auto, Go's :=) is simpler: the type comes from the initialiser alone.
Other semantic checks
- Definite assignment: a variable is assigned before use on all paths (Java, C#, Rust).
- Reachability / return checks: every path of a non-void function returns; no code after
return. - Control flow legality:
breakonly inside loops,awaitonly in async functions. - Mutability and ownership:
const/finalreassignments; Rust's borrow checker is a sophisticated semantic analysis over the control-flow graph (Borrowing). - Exhaustiveness:
match/switchcovers all enum variants. - Access control:
privatemembers used outside their class. - Overload resolution: picking which
print(int)vsprint(String)a call refers to.
The output is a decorated AST (each node annotated with its type and resolved symbol), ready for IR generation.
- Semantic analysis checks meaning: names, types, and language rules the grammar can't express.
- Symbol tables are stacks or chains of scopes; name resolution finds the innermost declaration.
- Type checking is a recursive walk computing and checking each expression's type.
- Static vs dynamic, strong vs weak, nominal vs structural are independent design axes.
- Hindley–Milner infers types by generating and unifying constraints.
- Definite assignment, reachability, exhaustiveness and borrow checking are further semantic checks.