Week 13 of 125

Crafting Interpreters, chapters 24 and 25

Sign up or sign in to tick these off and give this week a due date.

  • Build Ch 24: Calls and Functions Verified by tests

    Function objects, call frames, a compiler per function, the call instruction, return, stack traces for errors, and native functions.

    Time About 8 hours this week

    Why it matters

    Call frames are exactly how your CPU and every runtime manage function calls. After this chapter, stack traces make complete sense.

    How to approach it

    One of the biggest chapters; plan two sessions. Draw the value stack and frames during a recursive call. Compare your Fibonacci benchmark against jlox from chapter 10.

    Challenges

    4 challenges at the end of the chapter.

    Challenge 1 (cache ip in a local or register) is a real speedup worth measuring. Challenges 2 and 3 (arity and error handling for natives) make the VM safer. Challenge 4 (add your own natives) is fun.

    Traps

    • Wrong slot offset for the callee and arguments in a frame.
    • Not checking frame count for stack overflow on deep recursion.
    • Forgetting to update the cached frame pointer after a call or return.

    Reading guide

  • Build Ch 25: Closures Verified 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.

    Reading guide

  • Two problems from the NeetCode 150, in order. One box for the pair.