Crafting Interpreters · Week 12

Ch 14: Chunks of Bytecode

Updated

About 5 hours

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.

Flashcards 13 cards for Anki and AnkiMobile · all decks

Anki deck.tsv

Step through at your own pace; the arrow keys work too.

Crafting Interpreters · Ch 14 and 15 A bytecode VM, one instruction at a time The instruction pointer walks the chunk while values are pushed and popped on the stack.

Bytes

00000001010500020306

Disassembly

0000OP_CONSTANT0 '1'
0002OP_CONSTANT1 '2'
0004OP_ADD
ip0005OP_NEGATE
0006OP_CONSTANT2 '3'
0008OP_MULTIPLY
0009OP_RETURN

Constants

  1. 1
  2. 2
  3. 3

Stack

  1. 3

stackTop

Printed

nothing yet

OP_ADD pops 2 and then 1, adds them and pushes 3.

This week's steps

3 steps
  1. Read the chapter

    Compile with warnings on (-Wall -Wextra) and use AddressSanitizer (-fsanitize=address) from day one.

  2. Write the code in your lox repo

    Type it into clox/ (C) yourself as you read, and get it running.

  3. Do the challenges (1–3)

    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 you

Sign 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 posts

Questions 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.

Spot a mistake? Report it

Back to week 12