Week 8 of 125
Crafting Interpreters, chapters 14 and 15
Sign up or sign in to tick these off and give this week a due date.
-
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.
-
The virtual machine: the instruction pointer, the main dispatch loop, a value stack, and arithmetic instructions, with tracing of the stack as it runs.
Time About 5 hours this week
Why it matters
This loop is the beating heart of every bytecode interpreter. Understanding stack machines also helps you read JVM or WebAssembly bytecode.
How to approach it
Enable the execution trace and step through a few hand-built chunks. Notice how each instruction pushes and pops.
Challenges
4 challenges at the end of the chapter.
Challenge 1 (write out bytecode for several expressions) is a quick and useful exercise. Challenge 3 (grow the stack dynamically) and challenge 4 (negate in place) are short C exercises worth doing.
Traps
- Stack overflow with the fixed-size stack, since pushes are unchecked.
- Pop order for binary operators: the right operand is on top.
-
NeetCode LeetCode: 2 NeetCode 150 problems
Two problems from the NeetCode 150, in order. One box for the pair.