The tree-walking interpreter from Crafting Interpreters (jlox), reinterpreted in Go.
Requires Go 1.26 or newer.
go build -o golox . # build the binary
./golox script.lox # run a script
./golox # start the REPLYou can also skip the build step with go run . script.lox.
Exit codes: 64 for bad usage, 65 for scan, parse or resolver errors, and 1 if the script file can't be read.
Lox is a small dynamically typed language.
class Animal {
init(name) { this.name = name; }
speak() { print this.name + " makes a sound"; }
}
class Dog < Animal {
speak() {
super.speak();
print "Woof!";
}
}
fun fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
var d = Dog("Rex");
d.speak();
for (var i = 0; i < 10; i = i + 1) print fib(i);
Supported features:
- Types: numbers, strings, booleans,
nil - Variables (
var), block scoping,if/else,while,for,break,continue,and/or - Functions, closures and
return - Classes with
init,this, single inheritance andsuper - Built-in
clock(), which returns the time in seconds printstatements,//line comments and nestable/* ... */block comments
Not implemented: static methods, getters and anonymous functions (book challenges).
go test ./...
go vet ./...Layout:
| Path | Purpose |
|---|---|
main.go |
Command-line entry point |
interpreter/scanner.go |
Source text to tokens |
interpreter/parser.go |
Tokens to AST (interpreter/ast) |
interpreter/resolver.go |
Static variable resolution pass |
interpreter/interpreter.go |
Evaluates the AST |
interpreter/environment.go |
Variable scopes |
Note that .lox files are git-ignored.
See LICENSE.