Crafting Interpreters · Week 8

Crafting Interpreters 14: Chunks of Bytecode: reading guide

Read the chapter

Start of clox: a C project with a dynamic array of bytecode (a chunk), a constant pool, line information, a disassembler and a memory reallocation function used for all allocation.

Time About 5 hours this week

Why it matters

Bytecode is how CPython, Lua, the JVM and many other runtimes execute code. This chapter is also a crash course in writing careful C.

How to approach it

Compile with warnings on (-Wall -Wextra) and use AddressSanitizer (-fsanitize=address) from day one. Build the disassembler and use it constantly.

Challenges

3 challenges at the end of the chapter.

Challenge 1 (compress line info, for example with run-length encoding) and challenge 2 (add a long constant instruction for more than 256 constants) are both worth doing. Challenge 3 (write your own allocator) is a big stretch; save it for later or connect it to Knuth 2.5.

Traps

  • Forgetting to update capacity or count when growing an array.
  • Reading freed memory after a reallocation moves the array. AddressSanitizer catches this.
  • Missing include guards or mixing up .h and .c responsibilities.

Links

Back to week 8