Week 12 of 125
Crafting Interpreters, chapters 22 and 23
Sign up or sign in to tick these off and give this week a due date.
-
Local variables on the VM stack: the compiler tracks locals and scope depth, so each local is just a stack slot index, making access much faster than hash lookups.
Time About 6 hours this week
Why it matters
This is how real compilers do register and stack slot allocation in simple form. It also explains why locals are faster than globals in Python and Lua.
How to approach it
Use the disassembler to watch GET_LOCAL and SET_LOCAL slot numbers. Trace a nested block example on paper.
Challenges
4 challenges at the end of the chapter.
Challenge 3 (const or final variables) and challenge 4 (more than 256 locals) are the implementable ones. Challenge 1 asks about faster local resolution.
Traps
- Popping the wrong number of locals at the end of a scope.
- Reading a local in its own initializer must be an error.
-
Control flow in bytecode: jump instructions with backpatching for if/else, logical operators, while loops with backward jumps, and for loops.
Time About 5 hours this week
Why it matters
Backpatching is how every assembler and compiler resolves forward jumps. You will see it again in real assemblers and in Knuth's MIX.
How to approach it
Disassemble each control structure and draw the jump arrows. Off-by-one jump offsets are the usual bug; the disassembler shows them immediately.
Challenges
3 challenges at the end of the chapter.
Challenge 1 (a switch statement) and challenge 2 (continue) are both excellent. Challenge 3 is an open design question. 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
- Jump offsets off by the size of the operand bytes.
- Not popping the condition value on both branches.
-
NeetCode LeetCode: 2 NeetCode 150 problems
Two problems from the NeetCode 150, in order. One box for the pair.