An interpreter runs a program directly instead of translating it ahead of time, and a virtual machine is the abstract computer many languages run on, defined by its own instruction set. Together they power Python, JavaScript, Java and many more. Building one is the quickest way to understand what a language really does.
Key concepts
- Tree-walking: evaluate the syntax tree directly; simple and slow.
- Bytecode: compile to compact instructions for a virtual machine, then run them in a dispatch loop.
- Stack or register machine: operands live on a stack or in numbered registers; each design shapes the bytecode.
- Environments and closures: how variables are stored, captured and looked up.
- Memory management: reference counting or tracing garbage collection, and where objects live.
- Just-in-time compilation: turning hot code into machine code while the program runs.
Vocabulary
- Bytecode: the instruction set of a virtual machine.
- REPL: read-eval-print loop, an interactive prompt.
- Dispatch: choosing and running the next instruction.
- Garbage collector: the part of a runtime that reclaims memory nobody can reach.
What to study, in order
- Write a calculator that parses and evaluates expressions with a tree-walking evaluator.
- Add variables, conditionals, loops, functions and closures to it.
- Rewrite it as a compiler to bytecode plus a stack machine, and compare speed.
- Add a garbage collector, first a simple mark and sweep.
- Profile your machine, then try one optimisation such as caching variable lookups.
- Read the documentation of a real virtual machine and its bytecode listing.