Crafting Interpreters · Week 13
Ch 15: A Virtual Machine
Updated
Summary
Crafting Interpreters chapter 15, A Virtual Machine: The virtual machine: the instruction pointer, the main dispatch loop, a value stack, and arithmetic instructions, with tracing of the stack as it runs. 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 stepsEnable the execution trace and step through a few hand-built chunks.
Write the code in your lox repo
Type it into clox/ (C) yourself as you read, and get it running.
Challenge 1 (write out bytecode for several expressions) is a quick and useful exercise.
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
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.
Common traps
- Stack overflow with the fixed-size stack, since pushes are unchecked.
- Pop order for binary operators: the right operand is on top.