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
| Part | Topic | The Hard Problem |
|---|---|---|
| Part 1 | Setup, AST, parser, code generation | Getting MLIR to emit working code |
| Part 2 | Garbage collection from scratch | Managing memory without a runtime |
| Part 3 | Finding roots | Tracking live objects through the stack |
| Part 4 | MLIR integration | Connecting GC to the generated code |
| Part 5 | Closures | Capturing variables that outlive their scope |
| Part 6 | Complete reference | Everything in one place |
| Part 7 | Classes and instances | Object-oriented features on tagged unions |
| Part 8 | What we built, what we skipped, and why | Knowing what to simplify — and being honest about it |
| Part 9 | Standard library and runtime | The print and clock built-ins |
| Part 10 | Error reporting and debugging | Source locations, runtime errors, diagnostics |
| Part 11 | Cross-module linking | Connecting 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.