Crafting Interpreters · Week 12
Ch 14: Chunks of Bytecode
Updated
Summary
Crafting Interpreters chapter 14, Chunks of Bytecode: 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. Budget about 5 hours; it is a reading chapter, with no tests to pass.
See it
All visualsStep through at your own pace; the arrow keys work too.
Bytes
Disassembly
| 0000 | OP_CONSTANT | 0 '1' | |
| 0002 | OP_CONSTANT | 1 '2' | |
| 0004 | OP_ADD | ||
| ip | 0005 | OP_NEGATE | |
| 0006 | OP_CONSTANT | 2 '3' | |
| 0008 | OP_MULTIPLY | ||
| 0009 | OP_RETURN |
Constants
- 1
- 2
- 3
Stack
- 3
stackTop
Printed
nothing yet
OP_ADD pops 2 and then 1, adds them and pushes 3.
This week's steps
3 stepsCompile with warnings on (-Wall -Wextra) and use AddressSanitizer (-fsanitize=address) from day one.
Write the code in your lox repo
Type it into clox/ (C) yourself as you read, and get it running.
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.
Sign in to track this: tick each step off and it counts toward your week.
Your notes
Only youSign in to keep private notes on this guide, in Markdown. They stay yours: never on your profile, and you can export them all.
Discussion
0 postsQuestions about this chapter, tips, and what tripped you up. Hints over answers: full solutions go in a spoiler.
No posts yet. Ask a question or share a tip.
Sign in to postAnyone can read. Posting needs an account with a confirmed email.
Reference
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.
Common 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.