Crafting Interpreters · Week 13

Ch 15: A Virtual Machine

Updated

About 5 hours

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.

Flashcards 6 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

    Enable the execution trace and step through a few hand-built chunks.

  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–4)

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

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.

Spot a mistake? Report it

Back to week 13