Crafting Interpreters · Week 15

Ch 17: Compiling Expressions

Updated

About 7 hoursVerified by tests

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.

Flashcards 9 cards for Anki and AnkiMobile · all decks

Anki deck.tsv

Step through at your own pace; the arrow keys work too.

Crafting Interpreters · Ch 6 Parsing: precedence becomes depth Recursive descent turns 1 + 2 * 3 - 4 into a tree; the tighter an operator binds, the deeper its node sits.

Grammar, lowest precedence first

  1. expression → term
  2. term → factor (( "+" | "-" ) factor)*
  3. factor → primary (( "*" | "/" ) primary)*
  4. primary → NUMBER

Call stack

  1. 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 steps
  1. Read the chapter

    This chapter is dense.

  2. Write the code in your lox repo

    Type it into clox/ (C) yourself as you read, and get it running.

  3. Do the challenges (1–3)

    Challenge 1 (trace a tricky expression through the parse functions) is the most important; do it on paper.

  4. 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 you

Sign 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 posts

Questions 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.

Spot a mistake? Report it

Back to week 15