Two implementations of the Lox programming language from the book Crafting Interpreters by Robert Nystrom.
Lox is a high-level, dynamically-typed language designed for learning about interpreters and compilers.
Lox/
├── src/ # Rust tree-walk interpreter (Part I)
├── vm/ # C bytecode VM/compiler (Part II)
└── README.md
src/- Tree-walk interpreter written in Rustvm/- Bytecode virtual machine and compiler written in C (clox)
# Run in REPL mode
cargo run
# Run a Lox script
cargo run path/to/script.loxcd vm
mkdir build && cd build
cmake ..
make
./clox # REPL mode
./clox script.lox # Run script| Category | Features |
|---|---|
| Operators | +, -, *, /, >, >=, <, <=, ==, !=, !, and, or |
| Literals | Numbers, strings, booleans (true/false), nil |
| Statements | var, print, if/else, while, for, fun, return, blocks |
| Functions | Function declarations, function calls with arity validation, closures |
| Scope | Global and local variables, static resolution for closures |
| Category | Features |
|---|---|
| Operators | +, -, *, /, >, >=, <, <=, ==, !=, ! |
| Literals | Numbers, strings, booleans (true/false), nil |
| Statements | var, print, expression statements, blocks |
| Variables | Global and local variables |
| Compilation | Bytecode compilation to chunks, precedence-based parsing |
| VM | Stack-based VM with opcode dispatch, constant pool |
// Fibonacci function
fun fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
// Print first 10 Fibonacci numbers
for (var i = 0; i < 10; i = i + 1) {
print fib(i);
}
// Variables and arithmetic
var a = 10;
var b = 20;
print a + b;
// String concatenation
var greeting = "Hello, " + "World!";
print greeting;
// Logical operators
var x = true;
var y = false;
print x and y; // false
print x or y; // true
Output:
0
1
1
2
3
5
8
13
21
34
30
Hello, World!
false
true
| Feature | Rust | C |
|---|---|---|
| Implementation style | Tree-walk AST traversal | Bytecode VM |
| Performance | Slower (interpreted) | Faster (compiled) |
| Closures | Supported | Not implemented |
| Classes | Not implemented | Not implemented |
| For loops | Supported | Not implemented |
and/or keywords |
Supported | Token defined, not parsed |
- Crafting Interpreters by Robert Nystrom
- Part I: A Tree-Walk Interpreter
- Part II: A Bytecode Virtual Machine
MIT