Lesson 3 of 9 · 24m
AST Design: Structure Worth Keeping
Design abstract syntax trees that carry truth forward: what belongs in the tree, what does not, and how semantic validation stays sane.
An AST is not just what the parser happened to return. It is the canonical program representation every later phase depends on. Once diagnostics, optimization, formatting, and editor tooling hang off it, bad early choices fossilize.
Abstract means leaving punctuation behind
Concrete syntax includes parentheses, commas, semicolons, and keyword spelling. Abstract syntax keeps meaning. The source if (ready) run(); should become something like:
@dataclass(frozen=True)
class If:
condition: Expr
then_branch: Stmt
else_branch: Stmt | None
span: SpanThe punctuation disappears because the tree already encodes grouping. The span stays because errors must point back to real source.
One node per semantic idea
Avoid a generic node with a type string and a bag of children. Explicit dataclasses or algebraic data types make passes honest:
@dataclass(frozen=True)
class Binary:
left: Expr
op: str
right: Expr
span: SpanThe boilerplate buys exhaustiveness checks, IDE autocomplete, and clear pattern matching. Add a node type and the compiler or type checker tells you which passes forgot it.
Validate after parsing
Parsing answers "what did the source say?" Semantic validation answers "does it mean anything?" Keep checks such as these in a separate visitor:
- variables are declared before use
- break and continue appear inside loops
- return appears inside functions
- assignment targets are assignableA resolver can collect several errors in one pass:
def visit_break(self, node):
if self.loop_depth == 0:
self.error(node.span, "break outside a loop")Coupling scope rules into the parser is tempting because the parser is nearby. Do not do it; grammar and scope evolve on different axes. Likewise, rather than mutating nodes in every pass, keep analysis in side tables such as types[expr] and resolved_vars[expr]; immutable nodes plus discardable analysis are easier to cache, inspect, and parallelize.
Field notes
(a + b)anda + bare the same program; parentheses guide parsing but do not need AST nodes.- Desugar carefully. Turning
forintowhileis fine only if diagnostics still point at the originalfor. - Build an AST printer immediately. Debugging object graphs in a debugger gets old within one afternoon.
- Freeze node shapes early in tests; accidental parser output drift becomes very expensive once tooling exists.
Was this lesson helpful?