Tbh, this is something I struggled with for a while, so I hope it helps someone.
Every developer uses an interpreter or a compiler daily, and for most of us it stays a black box. We know there is a parser, something about a syntax tree, maybe "bytecode". But how does a closure keep a variable alive after its function returned? What does `super.method()` actually look up? Why is a bytecode VM faster than walking the tree?
Robert Nystrom's book *Crafting Interpreters* answers those questions by building one small language, Lox, twice: first as a tree-walk interpreter in Java ("jlox"), then as a bytecode virtual machine in C ("clox"). `rlox` is my implementation of both in Rust, in one repository, sharing one scanner and one test suite. This post is about what I built and what it teaches.
Lox is a small dynamic language with a C-like syntax. Both back ends in `rlox` support the full language: variables, blocks, `if`/`while`/`for`, functions, closures, classes, fields, methods, initializers, `this`, inheritance and `super`, plus the `clock()` native function.
**A shared scanner.** `scanner.rs` turns source text into tokens. Both back ends use it.
**The tree-walk interpreter** lives in `src/tree/` and follows the book's jlox. It has three stages:
tbh, - `parser.rs` builds an AST. A `for` loop is desugared into a `while`, so the evaluator only knows one kind of loop.
resolver.rswalks the AST once before execution and computes the scope depth of each local reference. That is what makes closures bind statically: a variable refers to the declaration that was visible where the code was written, not to whatever has that name at run time.interpreter.rsevaluates the tree, with environments stored asRc<RefCell<..>>.
**The bytecode VM** lives in `src/vm/` and follows the book's clox:
compiler.rsis a single-pass Pratt compiler. It emits bytecode directly while parsing, with no AST in between. Locals live in stack slots, and variables captured by a closure become upvalues.machine.rsis a stack VM. It runs the bytecode with call frames, open and closed upvalues,InvokeandSuperInvokefast paths for method calls, and copy-down inheritance.
basically, **A REPL and a file runner** for both. Exit codes follow the book: `65` for compile errors, `70` for runtime errors.
Clone the repository and build it with Cargo:
git clone
cd rlox
cargo build --release
./target/release/rlox # REPL (bytecode VM)
./target/release/rlox --tree # REPL (tree-walker)
./target/release/rlox script.lox # run a file with the VM
./target/release/rlox --tree script.lox # run a file with the tree-walker
Here is a small Lox program that uses closures and inheritance, the two features that are the most interesting to implement:
fun makeCounter() {
var count = 0;
fun next() {
count = count + 1;
return count;
}
return next;
}
var counter = makeCounter();
print counter(); // 1
print counter(); // 2
class Animal {
init(name) { this.name = name; }
speak() { print this.name + " makes a sound."; }
}
class Dog < Animal {
speak() {
super.speak();
print this.name + " barks.";
}
}
Dog("Rex").speak();
Save it as `script.lox` and run it with both back ends. The output is the same. What happens inside is very different.
**The same language, two execution models.** In the tree-walker, `count` in the example lives in an environment object that the `next` closure keeps a reference to. In the VM, `count` starts as a slot on the stack. When `makeCounter` returns, that slot is about to disappear, so the VM "closes" the upvalue: it moves the value off the stack to a place the closure owns. Open and closed upvalues can look like an odd detail on paper. Writing them makes clear that they are the price of keeping locals on the stack, which is where the VM's speed comes from.
honestly, **The resolver exists for a real bug.** Without it, a closure can see a different variable after a later declaration shadows the one it captured. Computing the scope depth of every local reference ahead of time fixes that, and it also turns a chain of name lookups into a direct jump to the right environment.
**Single-pass compilation is a constraint, and a useful one.** The Pratt compiler emits code while it parses. It cannot look ahead at the whole function. Jumps for `if` and loops are emitted with a placeholder and patched once the target is known. You end up understanding why real compilers have the limits they have.
**Method calls deserve a fast path.** `object.method()` could be compiled as "get the property, then call it", which creates a bound method object only to throw it away. The `Invoke` and `SuperInvoke` instructions do the lookup and the call in one step.
**Rust changes the memory story.** The book's clox has a mark-and-sweep garbage collector. `rlox` uses reference counting instead, which is the natural tool in Rust, and it has a known cost that I list below.
**Two back ends test each other.** `tests/lox/*.lox` is a suite of Lox programs annotated with `// expect: ...`, `// expect runtime error: ...` and `// expect compile error: ...`. `tests/lox_suite.rs` runs every file against both back ends and checks stdout, stderr and the exit code. When the two disagree, one of them has a bug. A REPL test also checks that state persists across lines.
**The speed difference is measurable.** On `fib(27)`, the VM is about 4x faster than the tree-walker in a release build. That is the README's figure for one recursive benchmark, not a general claim.
This is a learning project, and the README lists its limits:
- Reference cycles leak. The VM uses reference counting instead of the book's mark-and-sweep GC, so a cycle (for example an object holding a closure that captures it) leaks memory.
- No string interning. Strings compare by content.
- Fixed limits. At most 256 constants per function, 256 locals, 256 call frames in the VM, and 1000 nested calls in the tree-walker.
- The test suite is a hand-written subset, not the official Crafting Interpreters suite.
in my experience, reading about interpreters only goes so far. The book is written to be followed with a keyboard, and porting it to another language forces you to understand each decision instead of copying it. Java's garbage collector hides the environment lifetime questions in jlox, and C's raw pointers hide nothing in clox. Rust sits in between: it asks you to say who owns every value, which is exactly the question an interpreter author has to answer.
Having both implementations side by side in one repository, behind one command-line flag, also makes a good reference. You can take one feature, say classes, and read how the tree-walker and the VM each handle it.
The source and the Lox test programs are on GitHub: It's MIT licensed. Issues and pull requests are welcome. And if you have not read *Crafting Interpreters* yet, it is free to read at craftinginterpreters.com.
*Originally published at [abdeldjalilchougui.biz](
Anyway, that's my take on it! What do you guys think?