Lesson 2 of 9 · 25m
Parsing with Recursive Descent
Build a parser humans can read: precedence, associativity, lookahead, and why panic-mode recovery beats one-shot failure.
Parsing is where many learners surrender to a generator before understanding the problem. Resist that. A recursive descent parser is one function per grammar rule, and writing one teaches you more about language structure than any configuration file ever will.
The parser mirrors the grammar
class Parser:
def parse_statement(self):
if self.match("let"):
name = self.expect("ident")
self.expect("equal")
value = self.parse_expression()
self.expect("semicolon")
return Let(name.text, value)
return ExprStatement(self.parse_expression())Three primitives do most of the work: at(kind) peeks, match(kind) consumes when present, and expect(kind) consumes or raises a precise error. That small toolkit scales surprisingly far.
Precedence is a ladder
1 + 2 * 3 must parse as 1 + (2 * 3). Encode precedence as nested functions, loosest binding at the top and tightest at the bottom:
def parse_expression(self):
return self.parse_equality()
def parse_equality(self):
expr = self.parse_comparison()
while self.match("equal_equal"):
expr = Binary(expr, "==", self.parse_comparison())
return expr
def parse_term(self):
expr = self.parse_factor()
while self.match("plus", "minus"):
op = self.previous().text
expr = Binary(expr, op, self.parse_factor())
return exprThe call order is the precedence table. You can explain it on a whiteboard, which is exactly what you want from a first parser.
Associativity changes the recursion shape
Loops produce left-associative operators: a - b - c becomes (a - b) - c. Assignment and exponentiation are usually right-associative, so they recurse instead:
if self.match("equal"):
value = self.parse_assignment() # a = b = c works
return Assign(target, value)For malformed input, use panic-mode recovery: report the error, skip to ;, }, or the start of the next statement, then continue. Users should fix many errors per run, not one typo at a time.
Field notes
- Infinite loops almost always mean a rule matched without consuming input. Every successful branch must make progress.
- Do not validate semantics here.
breakoutside a loop can parse perfectly; reject it in a later pass. - Print the AST in parser tests. Pretty-printed trees catch precedence regressions better than a few hand-picked assertions.
- Parser generators are useful after you can read the grammar; before that they mostly hide the lesson.
Was this lesson helpful?