A compiler of your own: bytecode and a stack machine

: a database turns the text of a query into a tree, then makes a plan from the tree, then runs the plan. This lesson does the same for a program. The tree from the interpreter becomes a plan, and the plan is a flat list of small steps.
On 2026-11-28 we ran the small language from the interpreter lesson on a Linux server (AMD EPYC 9J14, Python 3.12.3). I asked it for fib(25), the 25th Fibonacci number, 75025. It took about 490 milliseconds. Then we asked it to add the numbers from 1 to 1,000,000 with a while loop. That took about 1,300 milliseconds. A million turns is a small job, and the program was slow at it. The cause is not a bug. The tree-walker looks at the same tree nodes again on every turn, and each look costs work.
By the end of this lesson you will be able to write a compiler that turns a program in that language into bytecode once, run the bytecode on a small stack machine, print the bytecode as readable words, and show with real counts why this is faster.
The history (optional)
In 2005 Roberto Ierusalimschy, Luiz Henrique de Figueiredo and Waldemar Celes published “The Implementation of Lua 5.0” in the Journal of Universal Computer Science. They wrote that Lua 5.0 had, as far as they knew, the first register-based virtual machine to be widely used. A register machine keeps values in numbered slots instead of one pile. This lesson builds the pile version.
Before you start. An interpreter of your own gave you the language, a lexer that cuts text into tokens, a parser that builds a tree, and a tree-walker that computes the answer. Build a stack machine gave you the idea of a virtual machine: a loop that reads one instruction, does it, and moves on, working on a pile of numbers called a stack. You need Python 3 to run the code.