Parsing
Building syntax trees from tokens — context-free grammars, parse trees vs ASTs, ambiguity, precedence and associativity, recursive descent, Pratt parsing, LL vs LR, parser generators, and error recovery.
The parser checks that the token stream follows the language's grammar and builds an abstract syntax tree (AST) — the structured representation every later phase works on.
Grammars
Syntax is specified with a context-free grammar (CFG) (Context-free grammars), usually written in BNF/EBNF:
program → statement* EOF
statement → "let" IDENT "=" expr ";"
| "return" expr ";"
| expr ";"
expr → term (("+" | "-") term)*
term → factor (("*" | "/") factor)*
factor → INT | IDENT | "(" expr ")" | "-" factor- Terminals: tokens (
INT,"+"). - Nonterminals: syntactic categories (
expr,term). - Productions: rules for rewriting a nonterminal.
The layering expr → term → factor encodes precedence: * binds tighter than + because multiplication is handled deeper in the grammar.
Parse tree vs AST
A parse tree (concrete syntax tree) records every grammar rule applied, including parentheses and semicolons. An AST keeps only what matters for meaning:
from dataclasses import dataclass
@dataclass
class Num: value: int
@dataclass
class Var: name: str
@dataclass
class Binary: op: str; left: object; right: object
@dataclass
class Let: name: str; value: objectAmbiguity, precedence and associativity
A grammar like expr → expr "-" expr | INT is ambiguous: 1 - 2 - 3 has two parse trees, giving −4 or 2. Fix ambiguity by:
- Precedence: separate levels (
expr/term/factor) or precedence declarations. - Associativity:
-is left-associative ((1 - 2) - 3);=and**are usually right-associative (a = b = cmeansa = (b = c)).
The dangling else (if a if b x else y — which if owns the else?) is resolved by convention: the nearest if.
Recursive descent
The most common hand-written technique (GCC, Clang, Go, rustc, V8, TypeScript): one function per nonterminal, each consuming tokens and calling others. It's top-down, LL-style, and easy to read, debug and give good error messages.
class Parser:
def __init__(self, tokens):
self.toks, self.pos = tokens, 0
def peek(self): return self.toks[self.pos]
def advance(self):
tok = self.toks[self.pos]; self.pos += 1; return tok
def expect(self, type_):
tok = self.advance()
if tok.type != type_:
raise SyntaxError(f"{tok.line}:{tok.col}: expected {type_}, got {tok.type}")
return tok
# expr → term (("+" | "-") term)* — the loop makes + and - left-associative
def expr(self):
node = self.term()
while self.peek().type in ("PLUS", "MINUS"):
op = self.advance().text
node = Binary(op, node, self.term())
return node
def term(self):
node = self.factor()
while self.peek().type in ("STAR", "SLASH"):
op = self.advance().text
node = Binary(op, node, self.factor())
return node
def factor(self):
tok = self.advance()
if tok.type == "INT": return Num(int(tok.text))
if tok.type == "IDENT": return Var(tok.text)
if tok.type == "MINUS": return Binary("-", Num(0), self.factor())
if tok.type == "LPAREN":
node = self.expr()
self.expect("RPAREN")
return node
raise SyntaxError(f"{tok.line}:{tok.col}: unexpected {tok.type}")Limitation: left recursion (expr → expr "+" term) would recurse forever; rewrite it as iteration, as above.
Pratt parsing (precedence climbing)
With 15+ precedence levels, one function per level gets tedious. Pratt parsing handles all binary operators in one loop driven by a binding-power table:
PRECEDENCE = {"||": 1, "&&": 2, "==": 3, "!=": 3, "<": 4, ">": 4,
"+": 5, "-": 5, "*": 6, "/": 6}
RIGHT_ASSOC = {"**"}
def parse_expr(self, min_prec=0):
left = self.factor() # prefix: literal, name, unary, (…)
while True:
op = self.peek().text
prec = PRECEDENCE.get(op)
if prec is None or prec < min_prec:
return left
self.advance()
next_min = prec if op in RIGHT_ASSOC else prec + 1
right = self.parse_expr(next_min) # binds tighter operators first
left = Binary(op, left, right)Pratt parsers also handle prefix, postfix, call and index operators elegantly; they're used in many modern compilers and in JS/TS tooling.
LL vs LR parsing
| LL(k) — top-down | LR(k) — bottom-up | |
|---|---|---|
| Builds the tree | From the root down, predicting productions | From leaves up, shifting tokens and reducing by rules |
| Reads | Left to right, Leftmost derivation | Left to right, Rightmost derivation (in reverse) |
| Handles left recursion | No | Yes |
| Grammar power | Smaller class | Larger class (LALR(1) covers most languages) |
| Typical form | Hand-written recursive descent; ANTLR (ALL(*)) | Generated tables: yacc, Bison |
An LR parser is a stack machine: shift pushes the next token; reduce pops the right-hand side of a rule and pushes its left-hand side. Conflicts in the generated table (shift/reduce, reduce/reduce) signal grammar ambiguities.
Parser generators vs hand-written
| Approach | Tools | Pros | Cons |
|---|---|---|---|
| Hand-written recursive descent / Pratt | — | Full control, great errors, fast | More code |
| LR generators | yacc, Bison, Lemon (SQLite) | Grammar is the spec; handles left recursion | Cryptic conflicts, weaker errors |
| LL/ALL(*) generators | ANTLR | Many target languages, good tooling | Runtime dependency |
| PEG / parser combinators | pest, nom, parsimmon, Lark | Composable, no separate lexer needed | Ordered choice can hide ambiguity; backtracking cost |
| Incremental | tree-sitter | Re-parses on each keystroke; error-tolerant | For editors/tools rather than compilers |
Error recovery
A good parser reports many errors per run, not just the first. Panic-mode recovery: on an error, skip tokens until a synchronisation point (;, }, a statement keyword), then resume. IDE parsers go further and build partial trees from broken code so autocomplete still works.
- The parser checks syntax against a context-free grammar and builds an AST.
- Precedence and associativity are encoded by grammar layering or binding powers.
- Recursive descent (one function per rule) is the most common hand-written technique; rewrite left recursion as loops.
- Pratt parsing handles many operator levels with a precedence table.
- LL parsers are top-down and predictive; LR parsers are bottom-up shift/reduce machines generated from grammars.
- Good parsers recover from errors to report many at once.
QHow would you write a parser for arithmetic expressions with correct precedence?medium
Use recursive descent with one function per precedence level — expr handles + and −, term handles * and /, factor handles numbers, names, unary minus and parentheses — with loops for left-associativity. Or use Pratt parsing: parse a prefix expression, then loop while the next operator's precedence is at least the minimum, recursively parsing the right side with a higher minimum (or the same, for right-associative operators). Both produce an AST you can evaluate by walking it.