A working interpreter for Lox (the language from Robert Nystrom's Crafting Interpreters) implemented in pure Python. Scanner, recursive-descent parser, pretty-printer, and tree-walk evaluator — all in one readable file. Real Lox programs run: variables, control flow, first-class functions, closures, recursion.
Built in under 48 hours with Claude Code while reaching CodeCrafters Python leaderboard rank #13.
If you searched for "Crafting Interpreters in Python", "Lox interpreter from scratch", "tree-walk interpreter tutorial", or "recursive descent parser Python" — this repo is a compact, end-to-end reference.
$ cat hello.lox
fun fib(n) {
if (n < 2) return n;
return fib(n - 2) + fib(n - 1);
}
for (var i = 0; i < 8; i = i + 1) print fib(i);
$ ./your_program.sh run hello.lox
0
1
1
2
3
5
8
13| Command | What it does |
|---|---|
./your_program.sh tokenize |
Scan source → print tokens (TYPE lexeme literal) |
./your_program.sh parse |
Parse one expression → print Lisp-style AST (+ 1.0 2.0) |
./your_program.sh evaluate |
Parse + evaluate one expression → print the value |
./your_program.sh run |
Execute a full Lox program (statements, functions, scope…) |
- Scanner: all Lox tokens — single/double char operators, string literals (multiline), number literals (with
.0literal formatting), identifiers, keywords,//comments - Parser: full Lox grammar — expressions (precedence-correct), statements (
var,print, block,if/else,while,for, function declarations,return), with proper error recovery / panic-mode synchronization - Evaluator:
- Environments with lexical scoping
- Truthiness & Lox equality semantics
- Short-circuit
and/or - Function declarations, calls, closures over their enclosing env
returnimplemented as a control-flow exception- Runtime errors with
[line N]reporting (exit 70) - Parse errors → exit 65 (CodeCrafters-compatible)
- Native function:
clock()returns wall time, used for benchmarks
- Single file (
app/main.py, ~700 lines): scanner → AST dataclasses → parser → AST printer → interpreter → CLI dispatcher - Recursive-descent parser mirrors the grammar one-to-one with the book
- Tree-walk interpreter uses
isinstancedispatch for readability instead of the visitor pattern
./your_program.sh run path/to/program.loxRequires uv and Python 3.14.
Most Lox implementations you find online are Java (the book's language) or C (Part III). This is Python, single-file, and covers the complete Part II interpreter through functions and closures — a good companion if you're working through Crafting Interpreters in a different language.
Part of the CodeCrafters "Build Your Own Interpreter" challenge. Language and grammar by Robert Nystrom.