Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

MLIR for Lox

Building a compiler is hard. Building a compiler correctly is harder. You need to generate code, manage memory, handle types, support closures — and each of these problems interacts with the others.

MLIR is a compiler framework that lets you define multiple intermediate representations — each one simpler, each one independently verifiable. Instead of jumping straight from your source language to machine code, you lower through these representations. At every step, MLIR gives you tools to verify, optimize, and debug your compiler.

This tutorial series builds a Lox compiler using MLIR via the Melior crate (Rust bindings for MLIR). We go all the way from parsing to a working runtime with garbage collection, closures, and classes.

What You’ll Find Here

PartTopicThe Hard Problem
Part 1Setup, AST, parser, code generationGetting MLIR to emit working code
Part 2Garbage collection from scratchManaging memory without a runtime
Part 3Finding rootsTracking live objects through the stack
Part 4MLIR integrationConnecting GC to the generated code
Part 5ClosuresCapturing variables that outlive their scope
Part 6Complete referenceEverything in one place
Part 7Classes and instancesObject-oriented features on tagged unions
Part 8What we built, what we skipped, and whyKnowing what to simplify — and being honest about it
Part 9Standard library and runtimeThe print and clock built-ins
Part 10Error reporting and debuggingSource locations, runtime errors, diagnostics
Part 11Cross-module linkingConnecting functions across multiple Lox files

Each part builds on the last.

Version Note

This tutorial uses melior 0.27 (LLVM 22). Melior’s Rust API changes significantly between versions — the same MLIR concepts work across all versions, but method signatures, type names, and module locations shift. If you’re on a different LLVM version, see the version table in Part 1 for the corresponding melior version.


Next: MLIR for Lox: Part 1 — From Lox Source to MLIR Dialect — We start from scratch: parse Lox source, build an AST, and emit it as an MLIR dialect. No prior MLIR experience required.