Semantic Analysis: Names, Scopes, and Rules
Lesson, slides, and applied problem sets.
View SlidesLesson
Semantic Analysis: Names, Scopes, and Rules
Why this module exists
Parsing gives structure, but not meaning. Semantic analysis answers questions like:
- Is a variable declared before it is used?
- Is a
constbeing reassigned? - Does a
returnappear outside a function?
These checks make programs understandable before running them.
1) Scopes
Each block introduces a new scope. A scope holds bindings:
- name
- kind (var/const/function/param)
Lookups search from inner to outer scope.
2) Core rules for this pack
We enforce these rules:
- No duplicate declarations in the same scope
- Names must be declared before use
constmust be initialized and cannot be reassignedreturnonly inside a function- Function calls must match a known function's arity
We do not type-check expressions. The language is dynamic.
3) Readable errors
Semantic errors should be short and clear. Examples:
- "undefined name: x"
- "redeclare in same scope: x"
- "cannot assign to const: pi"
- "return outside function"
- "arity mismatch: add expects 2"
4) Open-ended design
You could add:
- type checks
- closures and upvalues
- modules and imports
The core idea is to keep the analysis phase explicit and easy to reason about.