Saltar a contenido

Week 23 - Compiler Internals: MIR, Borrow Check, Codegen

23.1 Conceptual Core

  • The Rust compiler is query-based: every piece of derived information (types, traits, MIR, codegen units) is computed lazily and memoized in a query system (rustc_query_system).
  • MIR (Mid-level IR) is the IR on which borrow checking, optimization, and constant evaluation run. It is a CFG of basic blocks with statements and terminators, much closer to LLVM IR than HIR.
  • Bootstrap: rustc is written in Rust. To build it from source you compile a stage-0 (downloaded prebuilt) → stage-1 (built by stage-0) → stage-2 (built by stage-1, the deliverable). Understanding bootstrap is half the battle of contributing.

23.2 Mechanical Detail

  • Clone rust-lang/rust, run ./x.py setup (choose compiler or library profile), ./x.py build library/std. Plan ~30 minutes for the first build. Subsequent incremental builds are ~minutes.
  • Read rustc-dev-guide.rust-lang.org cover-to-cover. The high-yield chapters: "Overview of the compiler", "Queries", "MIR", "Borrow checking", "Trait resolution".
  • rustc -Z unpretty=mir to dump MIR; rustc -Z unpretty=hir for HIR. Read the MIR of a small program with a borrow-check error-the diagnostics make sense once you see the IR.
  • The E-easy and E-mentor labels in the rust-lang/rust issue tracker: the on-ramp. Pair with rustc-dev-guide's "your first PR" walkthrough.

23.3 Lab-"Read, Build, Land"

  1. Build rustc from source. Modify a single diagnostic message in compiler/rustc_borrowck/src/... to add a new help line. Rebuild stage-1 and confirm the new message in - -explain`.
  2. Find an issue with E-easy. Read the linked discussion. Cross-reference with rustc-dev-guide. Do not yet open a PR; instead, write a one-page plan describing the proposed change. Discuss with a maintainer in the issue comments.

23.4 Idiomatic & Clippy Drill

  • The rustc codebase has its own rustc_lint lints. Read compiler/rustc_lint_defs/src/builtin.rs to see how lints are defined; this is the same machinery clippy uses.

23.5 Production Hardening Slice

  • Configure your shell with rust-analyzer.checkOnSave.command = "clippy". Adopt cargo +nightly fmt -- --config-path rustfmt.toml. The compiler repo enforces its own rustfmt config; using the same locally avoids surprise CI failures.

Comments