Lesson 3 of 9 · 24m
AST Design That Survives Interpreters, Compilers, and Tooling
Design a tree that preserves meaning, supports analysis and refactoring, and does not collapse distinction too early.
The first AST most people build is a direct transcript of the parser: one class per grammar rule, fields named after whichever token came first. That works until you need a formatter, a linter, a type checker, and a compiler. Then you learn the hard lesson: a good AST is not merely parse output. It is the canonical model of program meaning.
Concrete syntax and abstract syntax are different
Concrete syntax includes parentheses, comments, semicolons, and exact operator spellings. Abstract syntax keeps semantic structure. A formatter may need the concrete tree; a compiler usually wants the abstract one. Do not throw away distinctions your semantics still needs:
@dataclass
class Literal:
value: object
span: Span
@dataclass
class Grouping:
expression: object
span: SpanIf parentheses are only precedence control, they can vanish from the AST. If integer literals distinguish decimal from hexadecimal for reflection or formatting, preserve that in the node or token.
Use a small algebra, not a class explosion
A language implementation often needs expressions, statements, patterns, types, and declarations. Resist creating a node for every production rule. A small algebra with explicit variants is easier to traverse:
Expr = Literal | Variable | Unary | Binary | Call | Assign
Stmt = ExprStmt | Let | Block | If | While | ReturnYou do not need algebraic data types in the host language to borrow the idea. Python dataclasses, Rust enums, TypeScript discriminated unions, or Java sealed classes all work better than loosely typed dictionaries.
Spans are the minimum provenance
Every AST node should know where it came from. Add spans even if your first interpreter never prints them. Later, a type checker will need to report where a bad value flows; a compiler will need line tables for stack traces; a linter will need precise suppression comments. Retrofitting provenance is miserable.
Binary span: offsets 10..27
operator span: offsets 15..16
left span: offsets 10..14
right span: offsets 17..27Separate desugaring from parsing
Desugaring means rewriting convenience syntax into simpler core forms:
for x in items -> iterator protocol loop
a += 1 -> a = a + 1
x?.name -> conditional access chain
while let Some(v) -> loop plus pattern matchDo not desugar in the parser if users need source-aware tooling. Record the original construct and lower it in a later pass. The lowering pass can create a simpler IR while the AST remains faithful.
Field notes
- Do not use Python tuples of arbitrary lengths as nodes; field names are documentation and refactoring leverage.
- Every pass should have a contract: consumes which nodes, preserves which provenance, produces which invariants.
Was this lesson helpful?