Crafting Interpreters · Week 15
Ch 17: Compiling Expressions
Updated
Summary
Crafting Interpreters chapter 17, Compiling Expressions: 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. Budget about 7 hours; the book's chap17_compiling tests check your code.
See it
All visualsStep through at your own pace; the arrow keys work too.
Grammar, lowest precedence first
expression → termterm → factor (( "+" | "-" ) factor)*factor → primary (( "*" | "/" ) primary)*primary → NUMBER
Call stack
- expression()
Built so far
(- (+ 1 (* 2 3)) 4)
No tokens left: expression returns the whole tree, (- (+ 1 (* 2 3)) 4).
This week's steps
4 stepsThis chapter is dense.
Write the code in your lox repo
Type it into clox/ (C) yourself as you read, and get it running.
Challenge 1 (trace a tricky expression through the parse functions) is the most important; do it on paper.
Push and let the tests verify it
Your repo runs the book's chap17_compiling tests on every push; passing marks this done.
Sign in to track this: tick each step off and it counts toward your week.
Your notes
Only youSign in to keep private notes on this guide, in Markdown. They stay yours: never on your profile, and you can export them all.
Discussion
0 postsQuestions about this chapter, tips, and what tripped you up. Hints over answers: full solutions go in a spoiler.
No posts yet. Ask a question or share a tip.
Sign in to postAnyone can read. Posting needs an account with a confirmed email.
Reference
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.
Common traps
- Getting precedence levels off by one in the rule table.
- Forgetting that the compiler emits code as it parses, so order matters.