# The Rust Compiler (rustc) — User Guide

## 1. Quick Start

The `rust-lang/rust` repository is the monorepo that produces the Rust programming language compiler (`rustc`), the standard library (`core`, `alloc`, `std`, `proc_macro`), and the complete development toolchain including Clippy, rustfmt, Miri, rust-analyzer, and rustdoc. If you want to *use* Rust to compile your own programs, install via [rustup](https://www.rust-lang.org/learn/get-started) instead — building from source is for contributors and distribution builders.

**Key features:**

- Multi-stage bootstrapping compiler written in Rust, targeting LLVM for code generation
- Experimental Cranelift and GCC codegen backends for faster debug builds and broader platform support
- Standard library spanning `no_std` embedded (`core`) through full OS integration (`std`)
- Bundled tools: Clippy (800+ lints), rustfmt (auto-formatting), Miri (undefined behavior detection), rust-analyzer (IDE), rustdoc (documentation generation)
- 50,000+ tests across UI diagnostics, MIR optimizations, codegen, and integration suites
- Cross-compilation for 80+ target triples
- Incremental compilation to speed up rebuilds during development

**Prerequisites:** Python 3, a C/C++ compiler (GCC or Clang on Linux, MSVC on Windows, Xcode on macOS), `cmake`, `curl`, and 30+ GB of disk space.

**Quick build:**

```bash
git clone https://github.com/rust-lang/rust.git
cd rust
./x setup compiler
./x build
```

```text
Building bootstrap
    Finished `dev` profile [unoptimized] target(s)
Building stage0 library artifacts (x86_64-unknown-linux-gnu)
Building stage0 compiler artifacts (x86_64-unknown-linux-gnu)
Building stage1 library artifacts (x86_64-unknown-linux-gnu)
Building stage1 compiler artifacts (x86_64-unknown-linux-gnu)
```

> [!TIP]
> Run `./x setup` interactively to choose a profile (`compiler`, `library`, `tools`, `codegen`, `dist`, or `none`). Each profile pre-configures `bootstrap.toml` with sensible defaults for your workflow.

**What to try next:** Run `./x test tests/ui` to exercise the compiler's diagnostic test suite, or `./x doc library --open` to build and browse the standard library documentation.

## 2. Installation

### System Requirements

| Resource | Minimum | Recommended |
|----------|---------|-------------|
| Disk space | 15 GB (single stage) | 30+ GB (full build + tests) |
| RAM | 4 GB | 8+ GB |
| CPU | 2 cores | 8+ cores |
| Python | 3.x | 3.8+ |
| C/C++ compiler | GCC 7+ / Clang 8+ / MSVC 2019+ | Latest stable |

### Getting the Source

```bash
git clone https://github.com/rust-lang/rust.git
cd rust
```

> [!IMPORTANT]
> The repository is large (~2 GB clone). Use `--depth 1` for a shallow clone if you only need to build without full history: `git clone --depth 1 https://github.com/rust-lang/rust.git`.

### Platform Dependencies

=== "Linux (Debian/Ubuntu)"
    ```bash
    sudo apt-get install build-essential python3 cmake curl ninja-build pkg-config libssl-dev
    ```

=== "Linux (Fedora/RHEL)"
    ```bash
    sudo dnf install gcc gcc-c++ python3 cmake curl ninja-build pkgconfig openssl-devel
    ```

=== "macOS"
    ```bash
    xcode-select --install
    brew install cmake ninja python3
    ```

=== "Windows"
    ```text
    Install Visual Studio 2019+ with the "Desktop development with C++" workload.
    Ensure Python 3 is on PATH.
    Install CMake and Ninja via winget or the official installers.
    ```

### Initial Configuration

Run the interactive setup wizard:

```bash
./x setup
```

```text
Welcome to the Rust compiler build system!

The following profiles are available:

    a]  compiler: Contribute to the compiler itself
    b]  library: Contribute to the standard library
    c]  tools: Contribute to tools (Clippy, rustfmt, etc.)
    d]  codegen: Contribute to code generation (LLVM, Cranelift)
    e]  dist: Build a full distribution
    f]  none: Start from a blank slate

Please choose a profile (a-f):
```

This generates a `bootstrap.toml` configuration file. You can also copy and edit the annotated example:

```bash
cp bootstrap.example.toml bootstrap.toml
```

> [!NOTE]
> The build system uses `x.py` (aliased as `./x` on Unix, `x.ps1` on Windows) to orchestrate multi-stage builds. All `./x` commands documented here also work as `python3 x.py` if the shell alias is not available. The `RUST_IGNORE_OLD_PYTHON` environment variable suppresses warnings about older Python versions.

### Building the Compiler

```bash
# Build the compiler (stage 1 by default for the "compiler" profile)
./x build

# Build a specific component
./x build compiler
./x build library
./x build src/tools/clippy

# Build stage 2 compiler (full self-hosted, slower)
./x build --stage 2
```

### Post-Build Verification

```bash
# Run the built compiler
./build/host/stage1/bin/rustc --version
```

```text
rustc 1.XX.0-dev
```

```bash
# Create a rustup toolchain link to your build
rustup toolchain link stage1 build/host/stage1
rustc +stage1 --version
```

> [!TIP]
> Linking your build as a rustup toolchain lets you test it on real projects: `cargo +stage1 build`.

### Install Troubleshooting

### Error: `python3: command not found`

**Cause:** Python 3 is not installed or not on PATH.

**Solution:**
1. Install Python 3 from your package manager or python.org
2. Verify: `python3 --version`

**Prevention:** The `x` wrapper script checks for Python at startup.

### Error: `CMake not found`

**Cause:** CMake is required to build LLVM from source.

**Solution:**
1. Install CMake via your package manager
2. Alternatively, set `download-ci-llvm = true` in `bootstrap.toml` to skip the LLVM build entirely

### Error: `LLVM build failed with out of memory`

**Cause:** LLVM compilation is memory-intensive. Systems with less than 8 GB RAM may fail.

**Solution:**
1. Set `download-ci-llvm = true` in `[llvm]` in `bootstrap.toml` (recommended — downloads pre-built LLVM)
2. Or limit parallelism: `./x build -j 2`
3. Or set `ninja = false` under `[llvm]` to reduce peak memory

**Prevention:** Use `download-ci-llvm = true` on memory-constrained machines.

### Error: `error: linking with cc failed`

**Cause:** System linker cannot find required libraries.

**Solution:**
1. Debian/Ubuntu: `sudo apt-get install libc6-dev`
2. Fedora: `sudo dnf install glibc-devel`
3. macOS: ensure Xcode command line tools are installed

### Error: `Could not find C compiler`

**Cause:** No C/C++ toolchain installed.

**Solution:**
1. Linux: `sudo apt-get install build-essential`
2. macOS: `xcode-select --install`
3. Windows: install Visual Studio with the C++ workload

## 3. Configuration

### bootstrap.toml Overview

The primary configuration file is `bootstrap.toml` at the repository root, generated by `./x setup` or copied from `bootstrap.example.toml`. It controls every aspect of the build.

| Section | Purpose |
|---------|---------|
| `[build]` | Host/target triples, parallelism, submodules, documentation |
| `[install]` | Installation prefix and paths |
| `[llvm]` | LLVM build options (download pre-built, assertions, targets) |
| `[rust]` | Compiler options (debug assertions, codegen backends, LTO, incremental) |
| `[target.<triple>]` | Per-target linker, C compiler, LLVM config |
| `[dist]` | Distribution packaging options |

**Recommended development configuration:**

```toml
# Fast builds for compiler contributors
[llvm]
download-ci-llvm = true   # Skip LLVM build, download pre-built

[rust]
debug-assertions = true    # Catch internal bugs
incremental = true         # Faster rebuilds
```

### Key Environment Variables

| Variable | Purpose |
|----------|---------|
| `RUSTC_BOOTSTRAP` | Enable unstable features (`1` to enable). Set automatically during bootstrap. |
| `RUSTC_BREAK_ON_ICE` | Set to `1` to trigger a debugger breakpoint on Internal Compiler Errors |
| `RUST_BACKTRACE` | `1` or `full` for backtraces on panics |
| `RUST_TEST_THREADS` | Number of parallel test threads |
| `RUST_TEST_SHUFFLE` | Randomize test execution order |
| `RUST_TEST_SHUFFLE_SEED` | Seed for test shuffle ordering |
| `RUST_TEST_NOCAPTURE` | Show stdout/stderr from tests |
| `RAYON_NUM_THREADS` | Thread pool size for parallel compilation passes |
| `RAYON_RS_NUM_CPUS` | Override detected CPU count for Rayon thread pool |

> [!WARNING]
> Setting `RUSTC_BOOTSTRAP=1` enables nightly-only features on any toolchain. The build system uses this internally. Never set it in production builds — it voids all stability guarantees.

See the Admin Guide for the full configuration reference including all `bootstrap.toml` sections, internal environment variables, and per-tool configuration knobs.

## 4. Core Usage

### The `x` Build System

All interaction with the Rust build system goes through the `x` command (a wrapper around `x.py`):

| Command | Purpose |
|---------|---------|
| `./x build` | Build compiler, library, or tools |
| `./x test` | Run tests |
| `./x check` | Type-check without code generation (fast) |
| `./x doc` | Build documentation |
| `./x fmt` | Format source code with rustfmt |
| `./x clippy` | Run Clippy lints on the codebase |
| `./x clean` | Remove build artifacts |
| `./x setup` | Interactive configuration wizard |
| `./x suggest` | Suggest tests to run based on changed files |
| `./x dist` | Build distribution tarballs |
| `./x install` | Install the built toolchain |
| `./x bench` | Run benchmarks |
| `./x run` | Build and run a specific tool |
| `./x perf` | Run performance benchmarks |
| `./x vendor` | Vendor all Cargo dependencies |

**Common flags:**

| Flag | Purpose |
|------|---------|
| `--stage N` | Build or test at stage N (0, 1, or 2) |
| `-j N` | Limit build parallelism to N jobs |
| `--keep-stage N` | Reuse existing stage N artifacts (fast incremental) |
| `-v` / `-vv` | Increase build output verbosity |
| `--warnings deny` | Treat warnings as errors |
| `--target <triple>` | Cross-compile for a specific target |

> [!TIP]
> Use `./x check` during development for rapid feedback. It runs type checking without code generation, completing in a fraction of the time of a full `./x build`.

### Understanding Build Stages

The Rust compiler uses a multi-stage bootstrap process:

| Stage | What it is | When to use |
|-------|-----------|-------------|
| **Stage 0** | Pre-existing compiler downloaded from CI (beta channel) | Automatically used — you don't invoke it directly |
| **Stage 1** | Compiler built by Stage 0 from your local source | **Most development and testing** |
| **Stage 2** | Compiler built by Stage 1 (self-hosted) | Release validation, CI, confirming self-host |

Most contributors work exclusively with Stage 1. A Stage 2 build proves the compiler can compile itself but takes significantly longer.

> [!NOTE]
> The `--keep-stage 1` flag tells the build system to reuse existing Stage 1 artifacts, rebuilding only what changed. This dramatically speeds up the edit-compile-test cycle. If you see unexpected behavior, do a clean rebuild: `./x clean && ./x build`.

### Running the Built Compiler

```bash
# Direct invocation
./build/host/stage1/bin/rustc my_program.rs

# Through rustup toolchain link
rustup toolchain link stage1 build/host/stage1
rustc +stage1 my_program.rs
cargo +stage1 build
```

### Using Bundled Tools

#### Clippy (Linter)

Clippy provides 800+ lints for catching common mistakes, style issues, and performance pitfalls.

```bash
# Build and test Clippy
./x build src/tools/clippy
./x test src/tools/clippy

# Run Clippy on the compiler source
./x clippy compiler
./x clippy library
```

| Environment Variable | Purpose |
|---------------------|---------|
| `CLIPPY_CONF_DIR` | Path to Clippy configuration directory |
| `CLIPPY_ARGS` | Additional arguments passed to the Clippy driver |
| `CLIPPY_TERMINAL_WIDTH` | Terminal width for output formatting |
| `CLIPPY_DISABLE_DOCS_LINKS` | Disable documentation links in lint output |
| `CARGO_PRIMARY_PACKAGE` | Used by Clippy to identify the primary package in a workspace |

#### rustfmt (Formatter)

```bash
# Build rustfmt
./x build src/tools/rustfmt

# Format the entire repository
./x fmt

# Check formatting without modifying files
./x fmt --check
```

> [!WARNING]
> CI rejects pull requests with formatting errors. Always run `./x fmt` before pushing.

#### Miri (MIR Interpreter)

Miri interprets Rust's Mid-level Intermediate Representation to detect undefined behavior, data races, and memory leaks.

```bash
./x build src/tools/miri
./x test src/tools/miri
```

| Environment Variable | Purpose |
|---------------------|---------|
| `MIRIFLAGS` | Additional flags for the Miri interpreter |
| `MIRI_VERBOSE` | Enable verbose diagnostic output |
| `MIRI_LOCAL_CRATES` | Comma-separated list of crates considered "local" for diagnostics |

#### rust-analyzer (IDE Support)

```bash
./x build src/tools/rust-analyzer
./x test src/tools/rust-analyzer
```

| Environment Variable | Purpose |
|---------------------|---------|
| `RA_TARGET` | Override the target triple for analysis |
| `RA_LRU_CAP` | LRU cache capacity for analysis results |
| `RUST_SRC_PATH` | Path to Rust source for standard library analysis |
| `SKIP_SLOW_TESTS` | Skip slow integration tests during development |

> [!IMPORTANT]
> When developing the rust-lang/rust repo, the `./x setup` wizard configures rust-analyzer to use the proc-macro server built from the tree. Using a mismatched system-installed version can cause spurious errors in your IDE.

## 5. Common Tasks

### Task: Run the Test Suite

**Goal:** Verify your changes pass existing tests.

```bash
# Run UI tests (the primary compiler diagnostic test suite)
./x test tests/ui

# Run a specific test file
./x test tests/ui/borrowck/borrowck-moved-value-into-closure.rs

# Run all tests for a component
./x test compiler
./x test library
./x test src/tools/clippy

# Run tests matching a filter
./x test tests/ui -- my_test_name

# Run the full test suite (takes hours)
./x test
```

> [!TIP]
> Use `./x suggest` to automatically determine which tests to run based on changed files. This is much faster than running the entire suite.

### Task: Add a New UI Test

**Goal:** Create a test verifying specific compiler behavior.

1. Create a `.rs` file in the appropriate test directory:
   ```rust
   // tests/ui/my-new-test.rs
   fn main() {
       let x: i32 = "not a number"; //~ ERROR mismatched types
   }
   ```

2. Run the test to generate expected output:
   ```bash
   ./x test tests/ui/my-new-test.rs --bless
   ```

3. Review the generated `tests/ui/my-new-test.stderr` to confirm it matches your intent.

4. Commit both the `.rs` file and the `.stderr` file.

> [!IMPORTANT]
> The `--bless` flag overwrites expected output files with actual compiler output. Always review the generated `.stderr` before committing.

### Task: Build for a Different Target

**Goal:** Cross-compile the standard library for another platform.

1. Add the target to `bootstrap.toml`:
   ```toml
   [build]
   target = ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"]
   ```

2. Build:
   ```bash
   ./x build --target aarch64-unknown-linux-gnu library
   ```

### Task: Build Standard Library Documentation

```bash
# Build and open in browser
./x doc library --open

# Build compiler internals documentation
./x doc compiler
```

### Task: Debug an Internal Compiler Error (ICE)

1. Reproduce with backtraces:
   ```bash
   RUST_BACKTRACE=1 ./build/host/stage1/bin/rustc failing_code.rs
   ```

2. Enable debug assertions in `bootstrap.toml`:
   ```toml
   [rust]
   debug-assertions = true
   ```

3. Rebuild and trigger the ICE under a debugger with `RUSTC_BREAK_ON_ICE=1`.

4. File an issue at https://github.com/rust-lang/rust/issues with the backtrace, input code, and output of `rustc --version --verbose`.

### Task: Profile Compiler Performance

```bash
# Time individual compiler passes
./build/host/stage1/bin/rustc -Z time-passes my_crate.rs
```

### Task: Run the Tidy Linter

The `tidy` tool enforces repository-wide style and hygiene rules.

```bash
./x test tidy
```

### Task: Build Distribution Tarballs

```bash
./x setup dist
./x dist
# Outputs in build/dist/
```

### Task: Format Changed Files Before Committing

```bash
# Auto-format
./x fmt

# Check only (no modifications)
./x fmt --check
```

### Task: Use an Alternative Codegen Backend

**Cranelift** (faster debug builds, less optimized output):

```toml
# bootstrap.toml
[rust]
codegen-backends = ["cranelift"]
```

**GCC** (experimental, broader platform support):

The `rustc_codegen_gcc` backend uses libgccjit. Environment variables for debugging:

| Variable | Purpose |
|----------|---------|
| `CG_GCCJIT_DUMP_GIMPLE` | Dump GIMPLE representation |
| `CG_GCCJIT_DUMP_RTL` | Dump RTL representation |
| `CG_GCCJIT_DUMP_CODE` | Dump generated assembly |
| `CG_GCCJIT_DUMP_EVERYTHING` | Enable all GCC debug dumps |
| `CG_GCCJIT_VERBOSE` | Verbose GCC backend output |
| `CG_GCCJIT_KEEP_INTERMEDIATES` | Keep intermediate compilation files |

### Task: Vendor Dependencies for Offline Builds

```bash
./x vendor
```

This copies all Cargo dependencies into the repository for offline or air-gapped builds.

## 6. Troubleshooting

### Diagnostic Decision Tree

```text
Build fails?
├── LLVM error? → Set download-ci-llvm = true in bootstrap.toml
├── Stage 0 download fails? → Check internet, delete build/cache, retry
├── Linker error? → Install C/C++ toolchain and development libraries
├── Out of memory? → Reduce parallelism (-j 2) or use download-ci-llvm
└── Unexpected warnings/errors? → Run ./x clean, then rebuild

Test failure?
├── Output mismatch? → Review diff, use --bless if intentional
├── Timeout? → Increase RUST_TEST_THREADS or run specific tests
├── ICE during test? → Set RUST_BACKTRACE=1, check issue tracker
└── Flaky? → Re-run, check RUST_TEST_SHUFFLE_SEED for ordering issues

IDE errors?
├── Proc-macro mismatch? → Re-run ./x setup for VS Code configuration
├── Missing standard library? → Set RUST_SRC_PATH or rebuild library
└── Slow analysis? → Adjust RA_LRU_CAP, close unused workspaces
```

### Error: `error: failed to run custom build command for rustc_llvm`

**Cause:** LLVM build failure — missing dependencies, insufficient memory, or CMake misconfiguration.

**Solution:**
1. Set `download-ci-llvm = true` in the `[llvm]` section of `bootstrap.toml`
2. If building from source: ensure CMake and Ninja are installed, and you have 10+ GB free disk space

**Prevention:** Use `download-ci-llvm = true` unless you are specifically modifying LLVM integration.

### Error: `error[E0554]: #![feature] may not be used on the stable release channel`

**Cause:** Attempting to build compiler crates with `cargo build` instead of `./x build`.

**Solution:**
1. Always use `./x build` — it manages the bootstrap compiler and sets `RUSTC_BOOTSTRAP` correctly
2. Never run `cargo build` directly on the compiler workspace

**Prevention:** Use `./x build`, `./x test`, `./x check` for all compiler work.

### Error: `test failed: unexpected output difference`

**Cause:** A UI test's actual stderr/stdout differs from the expected `.stderr`/`.stdout` file.

**Solution:**
1. Review the diff shown in the test output
2. If the change is intentional: `./x test tests/ui/path/to/test.rs --bless`
3. If unintentional: revert or fix your compiler change

### Error: `thread 'main' panicked at 'bootstrap artifacts not found'`

**Cause:** The bootstrap process could not download or locate the Stage 0 compiler.

**Solution:**
1. Check internet connectivity
2. Delete `build/cache/` and retry: `rm -rf build/cache && ./x build`
3. Verify `src/stage0` is intact

### Issue: Build is extremely slow

**Cause:** Building LLVM and a full stage 2 compiler from scratch is resource-intensive.

**Solution:**
1. Use `download-ci-llvm = true` (saves 20-40 minutes)
2. Use `./x check` for type-checking only (no codegen)
3. Use `--keep-stage 1` for incremental rebuilds after small changes
4. Set `incremental = true` in `[rust]`
5. Reduce parallelism on memory-constrained machines: `./x build -j 4`

### Issue: `--keep-stage` produces stale or incorrect results

**Cause:** Cached artifacts from a previous build don't reflect your latest source changes.

**Solution:**
1. Do a clean build: `./x clean && ./x build`
2. Only use `--keep-stage` when your change is isolated to one stage

### ICE: `Wrust-2021-incompatible-closure-captures` (GitHub #155497)

**Cause:** Internal compiler error in closure capture analysis during edition 2021 migration.

**Solution:**
1. Check if reproducible on latest nightly
2. File or update the tracking issue with a minimal reproduction case

### ICE: `InterpErrorInfo` / `UndefinedBehavior(ValidationError ...)` (GitHub #155496)

**Cause:** MIR interpreter validation error during const evaluation.

**Solution:**
1. Simplify the const expression to isolate the trigger
2. Search the issue tracker for known instances

### Error: `llvm error: export_name` (GitHub #155495)

**Cause:** LLVM backend error related to symbol export naming.

**Solution:**
1. Check if the target triple is supported for the feature being used
2. Try building without LTO to isolate the issue

## 7. FAQ

**Q: What is `rust-lang/rust` and who is it for?**

This repository contains the source code for the Rust compiler, standard library, and toolchain. It is for compiler contributors, language designers, standard library developers, tool maintainers, and distribution packagers. Regular Rust users should install via `rustup`.

**Q: Should I use `cargo build` or `./x build`?**

Always `./x build`. The Rust compiler has a multi-stage bootstrap that `cargo build` cannot manage. The `x.py` script handles downloading the bootstrap compiler, managing stages, and setting internal environment variables.

**Q: How long does a full build take?**

A clean build with LLVM from source: 30–90 minutes depending on hardware. With `download-ci-llvm = true`: 10–30 minutes. Incremental rebuilds with `--keep-stage 1`: under 5 minutes for small changes.

**Q: Which stage should I test against?**

Stage 1 for almost all development work. Stage 2 only when verifying self-hosting behavior or preparing release builds.

**Q: How do I run only tests relevant to my change?**

Use `./x suggest` to auto-detect affected tests. Or target specific suites: `./x test tests/ui`, `./x test tests/mir-opt`, `./x test src/tools/clippy`.

**Q: What does `--bless` do?**

It updates the expected output files (`.stderr`, `.stdout`) for UI tests to match the current compiler output. Use it when you have intentionally changed compiler diagnostics.

**Q: Can I cross-compile Rust programs with a from-source build?**

Yes. Add target triples to `[build] target` in `bootstrap.toml`, build with `./x build --target <triple>`, then use `cargo +stage1 build --target <triple>`.

**Q: What are the test suite directories?**

| Directory | What it tests |
|-----------|--------------|
| `tests/ui` | Compiler diagnostics (errors, warnings, suggestions) |
| `tests/mir-opt` | MIR optimization passes |
| `tests/codegen-llvm` | LLVM IR generation |
| `tests/run-make` | Integration tests (compile + run) |
| `tests/run-make-cargo` | Cargo-based integration tests |
| `tests/rustdoc-js` | Rustdoc search functionality |
| `tests/rustdoc-gui` | Rustdoc HTML rendering |
| `tests/ui-fulldeps` | Tests requiring full compiler dependencies |

**Q: Where is the rustc dev guide?**

The comprehensive contributor guide is at https://rustc-dev-guide.rust-lang.org/ with source in `src/doc/rustc-dev-guide/`.

**Q: How do I debug a specific compiler pass?**

Set `RUSTC_LOG=<crate_name>=debug` to enable logging. For example: `RUSTC_LOG=rustc_borrowck=debug ./build/host/stage1/bin/rustc test.rs`. The `rustc_log` crate manages the logging infrastructure using the `tracing` framework.

**Q: What is `RUSTC_BOOTSTRAP`?**

An environment variable that enables `#![feature(...)]` attributes on any compiler channel. The build system sets it automatically. Setting it manually in end-user code voids Rust's stability guarantees.

**Q: How do I build a distributable release?**

Use the `dist` profile: `./x setup dist && ./x dist`. Tarballs are produced in `build/dist/`.

---

_Generated May 2026 from rust-lang/rust at b2f1ccf. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
