Crafting Interpreters · Week 13

Crafting Interpreters 25: Closures: reading guide

Read the chapterVerified by tests

Closures in clox with upvalues: variables captured from enclosing functions live on the stack until their frame returns, then get "closed" by moving them to the heap.

Time About 8 hours this week

Why it matters

Upvalues are Lua's clever design for fast closures. This is widely considered the hardest chapter in the book and the most satisfying to get right.

How to approach it

Read the whole chapter once before coding. Draw the open upvalues list and the stack for the counter example. Use the test suite heavily; closure bugs are subtle.

Challenges

3 challenges at the end of the chapter.

Challenge 2 (a fresh variable per loop iteration) is a semantics change; do it on a branch. Challenge 3 (objects from closures) is a fun Lox program to write. Challenge 1 is a performance design question.

Traps

  • Keeping the open upvalues list unsorted, which breaks closing.
  • Closing upvalues in the wrong place (must happen when locals leave scope and at return).
  • Upvalue index versus local slot confusion in the compiler.

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

Links

Back to week 13