Skip to content
all projects

2024 · Languages · Swift

slox: A Lox Interpreter in Swift

My companion fork of a Swift Lox interpreter, kept close while working through Crafting Interpreters to see how a language really runs.

Terminal window running the slox interpreter

Overview

slox is a complete tree-walk interpreter for Lox, the language from Robert Nystrom's Crafting Interpreters, written in Swift. Honesty first: the repo on my GitHub is my fork of Alejandro Martinez's implementation, which I used as my companion while working through the book, reading the real Swift alongside Nystrom's Java chapter by chapter.

The structure is lovely. A LoxCore framework holds the language itself: a Scanner that walks the source string and produces tokens, a recursive descent Parser that builds the syntax tree, a Resolver that handles variable binding and scope analysis before anything runs, and a tree-walk Interpreter backed by a chain of Environments. The runtime types, LoxCallable, LoxClass, and LoxInstance, are what make functions, classes, and objects real at execution time. A small slox executable wraps it all in a CLI that runs a script file or drops you into a REPL, and a GenerateAst tool writes the syntax tree code so nobody has to by hand.

It covers chapters 4 through 13 of the book, which is the entire tree-walk language: variables and block scope, control flow with a bonus break statement, functions with closures and anonymous lambda syntax, classes with this and init, and inheritance with super. There are book challenge extras too, like C-style block comments and an AST printer that outputs reverse Polish notation. The repo even carries Nystrom's own Lox test suite, hundreds of tiny .lox files covering everything from operator precedence to closure edge cases, run through a modified Python test script.

Working through an interpreter this way demystified how programming languages actually work. Every error message, scope rule, and operator precedence decision is something I have traced through real code, and it is a big part of why language internals stopped feeling like magic to me.