Crafting Interpreters · Week 9

Crafting Interpreters 17: Compiling Expressions: reading guide

Read the chapterVerified by tests

A single-pass compiler that parses expressions with a Pratt parser (a table of prefix and infix parse functions with precedence) and emits bytecode directly, with no AST.

Time About 7 hours this week

Why it matters

Pratt parsing is an elegant, compact way to handle operator precedence and is used in many real compilers and tools.

How to approach it

This chapter is dense. Read the Pratt parser part twice. Trace the parse of a small expression through parsePrecedence and the rule table by hand, which is exactly what challenge 1 asks.

Challenges

3 challenges at the end of the chapter.

Challenge 1 (trace a tricky expression through the parse functions) is the most important; do it on paper. Challenge 3 (add the ternary operator) is a good stretch. Do challenges that change Lox's behavior on a separate git branch. The cracked.guide check runs the official test suite for this chapter, and a challenge that changes semantics (new syntax, different errors) can make tests fail on main.

Traps

  • Getting precedence levels off by one in the rule table.
  • Forgetting that the compiler emits code as it parses, so order matters.

Verified by the book's chap17_compiling tests when you push your repo.

Links

Back to week 9