From eda3ca48ae3853e93fe5e236b0dc39909c1cfa8f Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Thu, 27 Aug 2026 09:08:48 +0200 Subject: [PATCH 01/32] document EMIT_MIR_FOR_EACH_PANIC_STRATEGY --- src/doc/rustc-dev-guide/src/tests/compiletest.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/doc/rustc-dev-guide/src/tests/compiletest.md b/src/doc/rustc-dev-guide/src/tests/compiletest.md index 4573a04d0281c..e3d044d50b040 100644 --- a/src/doc/rustc-dev-guide/src/tests/compiletest.md +++ b/src/doc/rustc-dev-guide/src/tests/compiletest.md @@ -460,6 +460,10 @@ problematic in the presence of pointers in constants or other bit width dependen In that case you can add `// EMIT_MIR_FOR_EACH_BIT_WIDTH` to your test, causing separate files to be generated for 32bit and 64bit systems. +Similarly, +to generate separate files for each panic strategy ("panic-abort" and "panic-unwind"), +add `// EMIT_MIR_FOR_EACH_PANIC_STRATEGY` to the test. + [`tests/mir-opt`]: https://github.com/rust-lang/rust/tree/HEAD/tests/mir-opt From ef45c8263f2d3f98c3cfe37fbfc36db7328e8025 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 19 Oct 2026 14:30:21 +0200 Subject: [PATCH 02/32] Document that `rustc_codegen_gcc` now uses Josh --- src/doc/rustc-dev-guide/src/external-repos.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/src/external-repos.md b/src/doc/rustc-dev-guide/src/external-repos.md index 0e23be130c403..257757c17fca9 100644 --- a/src/doc/rustc-dev-guide/src/external-repos.md +++ b/src/doc/rustc-dev-guide/src/external-repos.md @@ -42,11 +42,11 @@ you should include fixes for those in the rustc PR as well. * Using `git subtree` * `clippy` ([sync guide](https://doc.rust-lang.org/nightly/clippy/development/infrastructure/sync.html#performing-the-sync-from-rust-langrust-to-clippy)) * `portable-simd` ([sync script](https://github.com/rust-lang/portable-simd/blob/master/subtree-sync.sh)) - * `rustc_codegen_gcc` ([sync guide](https://github.com/rust-lang/rustc_codegen_gcc/blob/master/doc/subtree.md)) * Using the [josh](#synchronizing-a-josh-subtree) tool * `miri` * `rust-analyzer` * `rustc_codegen_cranelift` + * `rustc_codegen_gcc` * `rustc-dev-guide` * `rustfmt` * `compiler-builtins` From 9a62a8d918ae8769c3ed0112927f268765e68f13 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Wed, 7 Oct 2026 18:21:50 +0000 Subject: [PATCH 03/32] ci: Ignore `unpinned-uses` for `josh-sync/rustc-pull` See: https://rust-lang.zulipchat.com/#narrow/channel/242791-t-infra/topic/josh-sync.20pull.20workflow.20version.20pinning/near/629742031 Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml index 0a2cfd1c85985..675539db15762 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml @@ -9,6 +9,7 @@ on: jobs: pull: if: github.repository == 'rust-lang/rustc-dev-guide' + # zizmor: ignore[unpinned-uses] We explicitly want to track the main branch. uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@main with: github-app-id: ${{ vars.APP_CLIENT_ID }} From 2aece4bbfe42be7bdb68f557c9c6d1ed39d48229 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Wed, 7 Oct 2026 18:25:34 +0000 Subject: [PATCH 04/32] ci: Pin `actions/cache` to 4.3.0 hash See: https://github.com/actions/cache/releases/tag/v4.3.0 This is the same version we were already using at the time of writing. Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/doc/rustc-dev-guide/.github/workflows/ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/doc/rustc-dev-guide/.github/workflows/ci.yml b/src/doc/rustc-dev-guide/.github/workflows/ci.yml index 23b590e4aebaf..369207e13a706 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/ci.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/ci.yml @@ -32,7 +32,7 @@ jobs: - name: Cache binaries id: mdbook-cache - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: | ~/.cargo/bin @@ -41,7 +41,7 @@ jobs: - name: Restore cached Linkcheck if: github.event_name == 'schedule' id: cache-linkcheck-restore - uses: actions/cache/restore@v4 + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: book/linkcheck/cache.json key: linkcheck--${{ env.MDBOOK_LINKCHECK2_VERSION }}--${{ github.run_id }} @@ -73,7 +73,7 @@ jobs: - name: Save cached Linkcheck id: cache-linkcheck-save if: ${{ !cancelled() && github.event_name == 'schedule' }} - uses: actions/cache/save@v4 + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: book/linkcheck/cache.json key: linkcheck--${{ env.MDBOOK_LINKCHECK2_VERSION }}--${{ github.run_id }} From cc5cff8ae86942db56bc5a38de47815b621b9806 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Wed, 7 Oct 2026 18:26:59 +0000 Subject: [PATCH 05/32] ci: Pin `actions/checkout` to 7.0.1 hash See: https://github.com/actions/checkout/releases/tag/v7.0.1 This is the same version we were already using at the time of writing. Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/doc/rustc-dev-guide/.github/workflows/date-check.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml index fb7ff3bc04b11..6010414eaaf28 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml @@ -15,7 +15,7 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Ensure Rust is up-to-date run: | From 3d1d5a077477d7905057230381ccfbb86907ca88 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Wed, 7 Oct 2026 18:28:35 +0000 Subject: [PATCH 06/32] ci: Pin `actions/github-script` to 7.1.0 hash See: https://github.com/actions/github-script/releases/tag/v7.1.0 This is the same version we were already using at the time of writing. Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/doc/rustc-dev-guide/.github/workflows/date-check.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml index 6010414eaaf28..a3e807f71c696 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml @@ -25,7 +25,7 @@ jobs: run: cargo run --manifest-path ci/date-check/Cargo.toml . > date-check-output.txt - name: Open issue - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 with: script: | const fs = require('fs'); From 0f9d598ded94bb40d885342f0dcd319617504952 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:02:39 +0000 Subject: [PATCH 07/32] ci: Disable credential persistence Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/doc/rustc-dev-guide/.github/workflows/ci.yml | 5 +++++ src/doc/rustc-dev-guide/.github/workflows/date-check.yml | 2 ++ 2 files changed, 7 insertions(+) diff --git a/src/doc/rustc-dev-guide/.github/workflows/ci.yml b/src/doc/rustc-dev-guide/.github/workflows/ci.yml index 369207e13a706..3ab6b6dc469bf 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/ci.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/ci.yml @@ -26,6 +26,7 @@ jobs: with: # linkcheck needs the base commit. fetch-depth: 0 + persist-credentials: false - name: Test CI scripts run: ci/tests/report-scheduled-linkcheck-failure.sh @@ -109,6 +110,8 @@ jobs: issues: write steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Open an issue or comment on an existing one run: ci/report-scheduled-linkcheck-failure.sh env: @@ -124,6 +127,8 @@ jobs: issues: write steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Close issue run: ci/close-scheduled-linkcheck-issues.sh env: diff --git a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml index a3e807f71c696..3e31067a89f26 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml @@ -16,6 +16,8 @@ jobs: steps: - name: Checkout repo uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Ensure Rust is up-to-date run: | From afeff76f18aaa7db24dc5f2284ae5a2d17cfaee0 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:07:57 +0000 Subject: [PATCH 08/32] ci: Prefer shell expansion over template expansion Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/doc/rustc-dev-guide/.github/workflows/ci.yml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/doc/rustc-dev-guide/.github/workflows/ci.yml b/src/doc/rustc-dev-guide/.github/workflows/ci.yml index 3ab6b6dc469bf..6b0917f6f4776 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/ci.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/ci.yml @@ -58,9 +58,9 @@ jobs: - name: Install Dependencies if: steps.mdbook-cache.outputs.cache-hit != 'true' run: | - cargo install --locked mdbook --version ${{ env.MDBOOK_VERSION }} - cargo install --locked mdbook-linkcheck2 --version ${{ env.MDBOOK_LINKCHECK2_VERSION }} - cargo install --locked mdbook-mermaid --version ${{ env.MDBOOK_MERMAID_VERSION }} + cargo install --locked mdbook --version ${MDBOOK_VERSION} + cargo install --locked mdbook-linkcheck2 --version ${MDBOOK_LINKCHECK2_VERSION} + cargo install --locked mdbook-mermaid --version ${MDBOOK_MERMAID_VERSION} - name: Check build run: ENABLE_LINKCHECK=1 mdbook build @@ -82,16 +82,16 @@ jobs: - name: Deploy to gh-pages if: github.event_name == 'push' run: | - touch "${{ env.DEPLOY_DIR }}/.nojekyll" - cp CNAME "${{ env.DEPLOY_DIR }}" - cd "${{ env.DEPLOY_DIR }}" + touch "${DEPLOY_DIR}/.nojekyll" + cp CNAME "${DEPLOY_DIR}" + cd "${DEPLOY_DIR}" rm -rf .git git init git config user.name "Deploy from CI" git config user.email "" git add . git commit -m "Deploy ${GITHUB_SHA} to gh-pages" - git push --quiet -f "https://x-token:${{ secrets.GITHUB_TOKEN }}@github.com/${GITHUB_REPOSITORY}" HEAD:gh-pages + git push --quiet -f "https://x-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}" HEAD:gh-pages - name: Check if files comply with semantic line breaks continue-on-error: true From e6c00a8e92b2b3f789e76df387aee4619143868e Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:13:56 +0000 Subject: [PATCH 09/32] ci: Disable all permissions by default Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/doc/rustc-dev-guide/.github/workflows/ci.yml | 2 ++ src/doc/rustc-dev-guide/.github/workflows/date-check.yml | 2 ++ src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml | 2 ++ 3 files changed, 6 insertions(+) diff --git a/src/doc/rustc-dev-guide/.github/workflows/ci.yml b/src/doc/rustc-dev-guide/.github/workflows/ci.yml index 6b0917f6f4776..8ba4b8c20c246 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/ci.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/ci.yml @@ -9,6 +9,8 @@ on: # Run multiple times a day as the successful cached links are not checked every time. - cron: "0 */8 * * *" +permissions: {} + jobs: ci: if: github.repository == 'rust-lang/rustc-dev-guide' diff --git a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml index 3e31067a89f26..55544e6d71b05 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml @@ -8,6 +8,8 @@ on: # Allow manually starting the workflow workflow_dispatch: +permissions: {} + jobs: date-check: if: github.repository == 'rust-lang/rustc-dev-guide' diff --git a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml index 675539db15762..5c4a33d59477c 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml @@ -6,6 +6,8 @@ on: # Run at 04:00 UTC every Monday - cron: '0 4 * * 1' +permissions: {} + jobs: pull: if: github.repository == 'rust-lang/rustc-dev-guide' From a50f3262305fd2f2a5b061d8f145932fc15deee3 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:31:50 +0000 Subject: [PATCH 10/32] ci: Grant minimum required permissions Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/doc/rustc-dev-guide/.github/workflows/ci.yml | 9 ++++----- src/doc/rustc-dev-guide/.github/workflows/date-check.yml | 3 ++- src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml | 3 +++ 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/doc/rustc-dev-guide/.github/workflows/ci.yml b/src/doc/rustc-dev-guide/.github/workflows/ci.yml index 8ba4b8c20c246..afdf7ca185e80 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/ci.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/ci.yml @@ -15,6 +15,8 @@ jobs: ci: if: github.repository == 'rust-lang/rustc-dev-guide' runs-on: ubuntu-latest + permissions: + contents: write # Required by `git push` env: MDBOOK_VERSION: 0.5.2 MDBOOK_LINKCHECK2_VERSION: 0.13.0 @@ -107,9 +109,7 @@ jobs: if: failure() && github.event_name == 'schedule' runs-on: ubuntu-latest permissions: - actions: read - contents: read - issues: write + issues: write # Required to open issues with `gh issue create` steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -125,8 +125,7 @@ jobs: if: success() && github.event_name == 'schedule' runs-on: ubuntu-latest permissions: - contents: read - issues: write + issues: write # Required to close issues with `gh issue close` steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml index 55544e6d71b05..868891c786c24 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/date-check.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/date-check.yml @@ -14,7 +14,8 @@ jobs: date-check: if: github.repository == 'rust-lang/rustc-dev-guide' runs-on: ubuntu-latest - + permissions: + issues: write # Required by `actions/github-script` to open issues steps: - name: Checkout repo uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml index 5c4a33d59477c..fa967b3ee5bb1 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml @@ -11,6 +11,9 @@ permissions: {} jobs: pull: if: github.repository == 'rust-lang/rustc-dev-guide' + permissions: + contents: write # Required by `josh-sync/rustc-pull` to push to a branch + pull-requests: write # Required by `josh-sync/rustc-pull` to open a PR # zizmor: ignore[unpinned-uses] We explicitly want to track the main branch. uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@main with: From 9f832e0bdbdac2f179f590d51a4fd08bfb8fdad5 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 20:04:13 +0100 Subject: [PATCH 11/32] reflow src/tests/directives.md --- src/doc/rustc-dev-guide/src/tests/directives.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index ed6c8b9f93951..ab878b88eafa5 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -274,9 +274,11 @@ For example: - A test with the `//@ edition: 2015..2021` directive can be run under the 2015 and the 2018 edition, so the upper bound is exclusive just like in Rust (note that there's no equivalent to Rust's `..=` where the upper bound is inclusive). - However, CI will only run the test with the lowest edition in the range (which is 2015 in this example). + However, + CI will only run the test with the lowest edition in the range (which is 2015 in this example). - A test with the `//@ edition: 2018..` directive will run under 2018 edition or greater. - However, CI will only run the test with the lowest edition in the range (which is 2018 in this example). + However, + CI will only run the test with the lowest edition in the range (which is 2018 in this example). You can also force `./x test` to use a specific edition by passing the `-- --edition=` argument. However, tests with the `//@ edition` directive will clamp the value passed to the argument. @@ -300,7 +302,8 @@ Asked in #### Test-suite-specific directives -The test suites [`rustdoc-html`][rustdoc-html-tests], [`rustdoc-js`/`rustdoc-js-std`][rustdoc-js-tests] +The test suites [`rustdoc-html`][rustdoc-html-tests], +[`rustdoc-js`/`rustdoc-js-std`][rustdoc-js-tests] and [`rustdoc-json`][rustdoc-json-tests] each feature an additional set of directives whose basic syntax resembles the one of compiletest directives but which are ultimately read and checked by separate tools. From 1dcce6b106ca185118f880b3589c6f237ac2429a Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 20:06:29 +0100 Subject: [PATCH 12/32] improve tests/directives.md --- src/doc/rustc-dev-guide/src/tests/directives.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index ab878b88eafa5..7d8fc182ba453 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -303,10 +303,10 @@ Asked in #### Test-suite-specific directives The test suites [`rustdoc-html`][rustdoc-html-tests], -[`rustdoc-js`/`rustdoc-js-std`][rustdoc-js-tests] +[`rustdoc-js`/`rustdoc-js-std`][rustdoc-js-tests], and [`rustdoc-json`][rustdoc-json-tests] each feature an additional set of directives whose basic -syntax resembles the one of compiletest directives but which are ultimately read and checked by -separate tools. +syntax resembles one of the compiletest directives, +but which are ultimately read and checked by separate tools. For more information, please read their respective chapters as linked above. [rustdoc-html-tests]: ../rustdoc-internals/rustdoc-html-test-suite.md From 99b62e44ea9c291bfbdd2f6303cf31ea1d352ae6 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 20:26:28 +0100 Subject: [PATCH 13/32] that made me think files should have this name --- .../src/rustdoc-internals/rustdoc-html-test-suite.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/src/rustdoc-internals/rustdoc-html-test-suite.md b/src/doc/rustc-dev-guide/src/rustdoc-internals/rustdoc-html-test-suite.md index a88e60c183b0d..76105c6c9e0e7 100644 --- a/src/doc/rustc-dev-guide/src/rustdoc-internals/rustdoc-html-test-suite.md +++ b/src/doc/rustc-dev-guide/src/rustdoc-internals/rustdoc-html-test-suite.md @@ -3,7 +3,7 @@ This page is about the test suite named `rustdoc-html` used to test the HTML output of `rustdoc`. For other rustdoc-specific test suites, see [Rustdoc test suites]. -Each test file in this test suite is simply a Rust source file `file.rs` sprinkled with +Each test file in this test suite is simply a Rust source file sprinkled with so-called *directives* located inside normal Rust code comments. These come in two flavors: *Compiletest* and *HtmlDocCk*. From 73da0c1c8a4a8f07f0c270c7946fe15fa2c152e9 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 20:27:01 +0100 Subject: [PATCH 14/32] reflow src/rustdoc-internals/rustdoc-html-test-suite.md --- .../src/rustdoc-internals/rustdoc-html-test-suite.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/rustdoc-internals/rustdoc-html-test-suite.md b/src/doc/rustc-dev-guide/src/rustdoc-internals/rustdoc-html-test-suite.md index 76105c6c9e0e7..13b618e7d4e44 100644 --- a/src/doc/rustc-dev-guide/src/rustdoc-internals/rustdoc-html-test-suite.md +++ b/src/doc/rustc-dev-guide/src/rustdoc-internals/rustdoc-html-test-suite.md @@ -145,8 +145,8 @@ Checks that the directory given by `PATH` contains exactly `ENTRIES`. ## Compiletest Directives (Brief) As mentioned in the introduction, you also have access to [compiletest directives]. -Most importantly, they allow you to register auxiliary crates and -to pass flags to the `rustdoc` binary under test. +Most importantly, +they allow you to register auxiliary crates and to pass flags to the `rustdoc` binary under test. It's *strongly recommended* to read that chapter if you don't know anything about them yet. Here are some details that are relevant to this test suite specifically: @@ -177,9 +177,9 @@ the original negative check failing. **Note**: Please avoid the use of *negated* checks! -**Tip**: If you can't avoid it, please **always** pair it with an analogous positive check in the -immediate vicinity, so people changing "the shape" have a chance to notice and to update the -negated check! +**Tip**: If you can't avoid it, +please **always** pair it with an analogous positive check in the immediate vicinity, +so people changing "the shape" have a chance to notice and to update the negated check! ## Limitations From 2e541c310c7a2c3d13974cd330b5b77928a90db2 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 21:04:41 +0100 Subject: [PATCH 15/32] sembr src/traits/canonicalization.md --- .../src/traits/canonicalization.md | 159 +++++++++--------- 1 file changed, 80 insertions(+), 79 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/traits/canonicalization.md b/src/doc/rustc-dev-guide/src/traits/canonicalization.md index 4bd56a020f14f..97d138ec43490 100644 --- a/src/doc/rustc-dev-guide/src/traits/canonicalization.md +++ b/src/doc/rustc-dev-guide/src/traits/canonicalization.md @@ -4,52 +4,52 @@ > [Next-gen trait solving Canonicalization chapter](../solve/canonicalization.md). > It is suggested to reorganize these contents in the future. -Canonicalization is the process of **isolating** an inference value -from its context. It is a key part of implementing -[canonical queries][cq], and you may wish to read the parent chapter +Canonicalization is the process of **isolating** an inference value from its context. +It is a key part of implementing [canonical queries][cq], +and you may wish to read the parent chapter to get more context. Canonicalization is really based on a very simple concept: every [inference variable](../type-inference.md#vars) is always in one of -two states: either it is **unbound**, in which case we don't know yet -what type it is, or it is **bound**, in which case we do. So to -isolate some data-structure T that contains types/regions from its +two states: either it is **unbound**, in which case we don't know yet what type it is, +or it is **bound**, in which case we do. +So to isolate some data-structure T that contains types/regions from its environment, we just walk down and find the unbound variables that appear in T; those variables get replaced with "canonical variables", -starting from zero and numbered in a fixed order (left to right, for -the most part, but really it doesn't matter as long as it is +starting from zero and numbered in a fixed order (left to right, for the most part, +but really it doesn't matter as long as it is consistent). [cq]: ./canonical-queries.md -So, for example, if we have the type `X = (?T, ?U)`, where `?T` and -`?U` are distinct, unbound inference variables, then the canonical -form of `X` would be `(?0, ?1)`, where `?0` and `?1` represent these -**canonical placeholders**. Note that the type `Y = (?U, ?T)` also -canonicalizes to `(?0, ?1)`. But the type `Z = (?T, ?T)` would -canonicalize to `(?0, ?0)` (as would `(?U, ?U)`). In other words, the -exact identity of the inference variables is not important – unless +So, for example, if we have the type `X = (?T, ?U)`, where `?T` and `?U` are distinct, +unbound inference variables, then the canonical +form of `X` would be `(?0, ?1)`, where `?0` and `?1` represent these **canonical placeholders**. +Note that the type `Y = (?U, ?T)` also canonicalizes to `(?0, ?1)`. +But the type `Z = (?T, ?T)` would canonicalize to `(?0, ?0)` (as would `(?U, ?U)`). +In other words, the exact identity of the inference variables is not important – unless they are repeated. -We use this to improve caching as well as to detect cycles and other -things during trait resolution. Roughly speaking, the idea is that if -two trait queries have the same canonical form, then they will get -the same answer. That answer will be expressed in terms of the -canonical variables (`?0`, `?1`), which we can then map back to the +We use this to improve caching as well as to detect cycles and other things during trait resolution. +Roughly speaking, the idea is that if two trait queries have the same canonical form, +then they will get +the same answer. +That answer will be expressed in terms of the canonical variables (`?0`, +`?1`), which we can then map back to the original variables (`?T`, `?U`). ## Canonicalizing the query To see how it works, imagine that we are asking to solve the following trait query: `?A: Foo<'static, ?B>`, where `?A` and `?B` are unbound. -This query contains two unbound variables, but it also contains the -lifetime `'static`. The trait system generally ignores all lifetimes -and treats them equally, so when canonicalizing, we will *also* +This query contains two unbound variables, but it also contains the lifetime `'static`. +The trait system generally ignores all lifetimes and treats them equally, +so when canonicalizing, we will *also* replace any [free lifetime](../appendix/background.md#free-vs-bound) with a -canonical variable (Note that `'static` is actually a _free_ lifetime -variable here. We are not considering it in the typing context of the whole -program but only in the context of this trait reference. Mathematically, we -are not quantifying over the whole program, but only this obligation). +canonical variable (Note that `'static` is actually a _free_ lifetime variable here. +We are not considering it in the typing context of the whole +program but only in the context of this trait reference. +Mathematically, we are not quantifying over the whole program, but only this obligation). Therefore, we get the following result: ```text @@ -62,12 +62,11 @@ Sometimes we write this differently, like so: for { ?0: Foo<'?1, ?2> } ``` -This `for<>` gives some information about each of the canonical -variables within. In this case, each `T` indicates a type variable, -so `?0` and `?2` are types; the `L` indicates a lifetime variable, so -`?1` is a lifetime. The `canonicalize` method *also* gives back a -`CanonicalVarValues` array OV with the "original values" for each -canonicalized variable: +This `for<>` gives some information about each of the canonical variables within. + In this case, each `T` indicates a type variable, +so `?0` and `?2` are types; the `L` indicates a lifetime variable, so `?1` is a lifetime. +The `canonicalize` method *also* gives back a +`CanonicalVarValues` array OV with the "original values" for each canonicalized variable: ```text [?A, 'static, ?B] @@ -79,8 +78,8 @@ We'll need this vector OV later, when we process the query response. Once we've constructed the canonical query, we can try to solve it. To do so, we will wind up creating a fresh inference context and -**instantiating** the canonical query in that context. The idea is that -we create a substitution S from the canonical form containing a fresh +**instantiating** the canonical query in that context. +The idea is that we create a substitution S from the canonical form containing a fresh inference variable (of suitable kind) for each canonical variable. So, for our example query: @@ -94,22 +93,24 @@ the substitution S might be: S = [?A, '?B, ?C] ``` -We can then replace the bound canonical variables (`?0`, etc) with -these inference variables, yielding the following fully instantiated +We can then replace the bound canonical variables (`?0`, etc) with these inference variables, +yielding the following fully instantiated query: ```text ?A: Foo<'?B, ?C> ``` -Remember that substitution S though! We're going to need it later. +Remember that substitution S though! +We're going to need it later. -OK, now that we have a fresh inference context and an instantiated -query, we can go ahead and try to solve it. The trait solver itself is -explained in more detail in [another section](../solve/the-solver.md), but +OK, now that we have a fresh inference context and an instantiated query, +we can go ahead and try to solve it. +The trait solver itself is explained in more detail in [another section](../solve/the-solver.md), +but suffice to say that it will compute a [certainty value][cqqr] (`Proven` or -`Ambiguous`) and have side-effects on the inference variables we've -created. For example, if there were only one impl of `Foo`, like so: +`Ambiguous`) and have side-effects on the inference variables we've created. +For example, if there were only one impl of `Foo`, like so: [cqqr]: ./canonical-queries.md#query-response @@ -119,29 +120,29 @@ where X: 'a { ... } ``` -then we might wind up with a certainty value of `Proven`, as well as -creating fresh inference variables `'?D` and `?E` (to represent the +then we might wind up with a certainty value of `Proven`, +as well as creating fresh inference variables `'?D` and `?E` (to represent the parameters on the impl) and unifying as follows: - `'?B = '?D` - `?A = Vec` - `?C = ?E` -We would also accumulate the region constraint `?E: '?D`, due to the -where clause. +We would also accumulate the region constraint `?E: '?D`, due to the where clause. -In order to create our final query result, we have to "lift" these -values out of the query's inference context and into something that -can be reapplied in our original inference context. We do that by -**re-applying canonicalization**, but to the **query result**. +In order to create our final query result, +we have to "lift" these values out of the query's inference context and into something that +can be reapplied in our original inference context. +We do that by **re-applying canonicalization**, but to the **query result**. ## Canonicalizing the query result As discussed in [the parent section][cqqr], most trait queries wind up with a result that brings together a "certainty value" `certainty`, a -result substitution `var_values`, and some region constraints. To -create this, we wind up re-using the substitution S that we created -when first instantiating our query. To refresh your memory, we had a query +result substitution `var_values`, and some region constraints. +To create this, we wind up re-using the substitution S that we created +when first instantiating our query. +To refresh your memory, we had a query ```text for { ?0: Foo<'?1, ?2> } @@ -160,10 +161,10 @@ If we "refresh" S with the latest results, we get: S = [Vec, '?D, ?E] ``` -These are precisely the new values for the three input variables from -our original query. Note though that they include some new variables -(like `?E`). We can make those go away by canonicalizing again! We don't -just canonicalize S, though, we canonicalize the whole query response QR: +These are precisely the new values for the three input variables from our original query. +Note though that they include some new variables (like `?E`). +We can make those go away by canonicalizing again! +We don't just canonicalize S, though, we canonicalize the whole query response QR: ```text QR = { @@ -187,20 +188,20 @@ Canonical(QR) = for { } ``` -(One subtle point: when we canonicalize the query **result**, we do not -use any special treatment for free lifetimes. Note that both -references to `'?D`, for example, were converted into the same -canonical variable (`?1`). This is in contrast to the original query, -where we canonicalized every free lifetime into a fresh canonical -variable.) +(One subtle point: when we canonicalize the query **result**, +we do not use any special treatment for free lifetimes. +Note that both references to `'?D`, for example, were converted into the same +canonical variable (`?1`). +This is in contrast to the original query, +where we canonicalized every free lifetime into a fresh canonical variable.) Now, this result must be reapplied in each context where needed. ## Processing the canonicalized query result -In the previous section we produced a canonical query result. We now have -to apply that result in our original context. If you recall, way back in the -beginning, we were trying to prove this query: +In the previous section we produced a canonical query result. +We now have to apply that result in our original context. +If you recall, way back in the beginning, we were trying to prove this query: ```text ?A: Foo<'static, ?B> @@ -223,11 +224,11 @@ for { } ``` -We now want to apply that response to our context. Conceptually, how -we do that is to (a) instantiate each of the canonical variables in +We now want to apply that response to our context. +Conceptually, how we do that is to (a) instantiate each of the canonical variables in the result with a fresh inference variable, (b) unify the values in -the result with the original values, and then (c) record the region -constraints for later. Doing step (a) would yield a result of +the result with the original values, and then (c) record the region constraints for later. +Doing step (a) would yield a result of ```text { @@ -247,13 +248,13 @@ Step (b) would then unify: ?B with ?C ``` -And finally the region constraint of `?C: 'static` would be recorded -for later verification. +And finally the region constraint of `?C: 'static` would be recorded for later verification. (What we *actually* do is a mildly optimized variant of that: Rather -than eagerly instantiating all of the canonical values in the result -with variables, we instead walk the vector of values, looking for -cases where the value is just a canonical variable. In our example, -`values[2]` is `?C`, so that means we can deduce that `?C := ?B` and -`'?D := 'static`. This gives us a partial set of values. Anything for -which we do not find a value, we create an inference variable.) +than eagerly instantiating all of the canonical values in the result with variables, +we instead walk the vector of values, looking for +cases where the value is just a canonical variable. +In our example, +`values[2]` is `?C`, so that means we can deduce that `?C := ?B` and `'?D := 'static`. +This gives us a partial set of values. +Anything for which we do not find a value, we create an inference variable.) From 63fdb59964a698598e30c4fdc5dde1ea1060a0aa Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 21:22:02 +0100 Subject: [PATCH 16/32] improve traits/canonicalization.md --- .../src/traits/canonicalization.md | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/traits/canonicalization.md b/src/doc/rustc-dev-guide/src/traits/canonicalization.md index 97d138ec43490..7564fbe9072d1 100644 --- a/src/doc/rustc-dev-guide/src/traits/canonicalization.md +++ b/src/doc/rustc-dev-guide/src/traits/canonicalization.md @@ -13,7 +13,7 @@ Canonicalization is really based on a very simple concept: every [inference variable](../type-inference.md#vars) is always in one of two states: either it is **unbound**, in which case we don't know yet what type it is, or it is **bound**, in which case we do. -So to isolate some data-structure T that contains types/regions from its +So, to isolate some data-structure T that contains types/regions from its environment, we just walk down and find the unbound variables that appear in T; those variables get replaced with "canonical variables", starting from zero and numbered in a fixed order (left to right, for the most part, @@ -22,13 +22,13 @@ consistent). [cq]: ./canonical-queries.md -So, for example, if we have the type `X = (?T, ?U)`, where `?T` and `?U` are distinct, +So, for example, if we have the type `X = (?T, ?U)`, where `?T` and `?U` are distinct unbound inference variables, then the canonical form of `X` would be `(?0, ?1)`, where `?0` and `?1` represent these **canonical placeholders**. Note that the type `Y = (?U, ?T)` also canonicalizes to `(?0, ?1)`. But the type `Z = (?T, ?T)` would canonicalize to `(?0, ?0)` (as would `(?U, ?U)`). -In other words, the exact identity of the inference variables is not important – unless -they are repeated. +In other words, the exact identity of the inference variables is not important, +unless they are repeated. We use this to improve caching as well as to detect cycles and other things during trait resolution. Roughly speaking, the idea is that if two trait queries have the same canonical form, @@ -47,8 +47,8 @@ The trait system generally ignores all lifetimes and treats them equally, so when canonicalizing, we will *also* replace any [free lifetime](../appendix/background.md#free-vs-bound) with a canonical variable (Note that `'static` is actually a _free_ lifetime variable here. -We are not considering it in the typing context of the whole -program but only in the context of this trait reference. +We are not considering it in the typing context of the whole program, +but only in the context of this trait reference. Mathematically, we are not quantifying over the whole program, but only this obligation). Therefore, we get the following result: @@ -63,7 +63,7 @@ for { ?0: Foo<'?1, ?2> } ``` This `for<>` gives some information about each of the canonical variables within. - In this case, each `T` indicates a type variable, +In this case, each `T` indicates a type variable, so `?0` and `?2` are types; the `L` indicates a lifetime variable, so `?1` is a lifetime. The `canonicalize` method *also* gives back a `CanonicalVarValues` array OV with the "original values" for each canonicalized variable: @@ -142,13 +142,13 @@ with a result that brings together a "certainty value" `certainty`, a result substitution `var_values`, and some region constraints. To create this, we wind up re-using the substitution S that we created when first instantiating our query. -To refresh your memory, we had a query +To refresh your memory, we had a query: ```text for { ?0: Foo<'?1, ?2> } ``` -for which we made a substutition S: +We made a substutition S for it: ```text S = [?A, '?B, ?C] @@ -199,7 +199,7 @@ Now, this result must be reapplied in each context where needed. ## Processing the canonicalized query result -In the previous section we produced a canonical query result. +In the previous section, we produced a canonical query result. We now have to apply that result in our original context. If you recall, way back in the beginning, we were trying to prove this query: @@ -228,7 +228,7 @@ We now want to apply that response to our context. Conceptually, how we do that is to (a) instantiate each of the canonical variables in the result with a fresh inference variable, (b) unify the values in the result with the original values, and then (c) record the region constraints for later. -Doing step (a) would yield a result of +Doing step (a) would yield this result: ```text { @@ -248,7 +248,7 @@ Step (b) would then unify: ?B with ?C ``` -And finally the region constraint of `?C: 'static` would be recorded for later verification. +And finally, the region constraint of `?C: 'static` would be recorded for later verification. (What we *actually* do is a mildly optimized variant of that: Rather than eagerly instantiating all of the canonical values in the result with variables, From 4496185aebb20e45b2a0e4c2dd3006be27bd8627 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 21:23:09 +0100 Subject: [PATCH 17/32] reflow src/traits/canonicalization.md --- .../src/traits/canonicalization.md | 42 ++++++++----------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/traits/canonicalization.md b/src/doc/rustc-dev-guide/src/traits/canonicalization.md index 7564fbe9072d1..d87e3b3031022 100644 --- a/src/doc/rustc-dev-guide/src/traits/canonicalization.md +++ b/src/doc/rustc-dev-guide/src/traits/canonicalization.md @@ -6,25 +6,23 @@ Canonicalization is the process of **isolating** an inference value from its context. It is a key part of implementing [canonical queries][cq], -and you may wish to read the parent chapter -to get more context. +and you may wish to read the parent chapter to get more context. Canonicalization is really based on a very simple concept: every [inference variable](../type-inference.md#vars) is always in one of two states: either it is **unbound**, in which case we don't know yet what type it is, or it is **bound**, in which case we do. -So, to isolate some data-structure T that contains types/regions from its -environment, we just walk down and find the unbound variables that +So, to isolate some data-structure T that contains types/regions from its environment, +we just walk down and find the unbound variables that appear in T; those variables get replaced with "canonical variables", starting from zero and numbered in a fixed order (left to right, for the most part, -but really it doesn't matter as long as it is -consistent). +but really it doesn't matter as long as it is consistent). [cq]: ./canonical-queries.md So, for example, if we have the type `X = (?T, ?U)`, where `?T` and `?U` are distinct -unbound inference variables, then the canonical -form of `X` would be `(?0, ?1)`, where `?0` and `?1` represent these **canonical placeholders**. +unbound inference variables, then the canonical form of `X` would be `(?0, +?1)`, where `?0` and `?1` represent these **canonical placeholders**. Note that the type `Y = (?U, ?T)` also canonicalizes to `(?0, ?1)`. But the type `Z = (?T, ?T)` would canonicalize to `(?0, ?0)` (as would `(?U, ?U)`). In other words, the exact identity of the inference variables is not important, @@ -32,11 +30,9 @@ unless they are repeated. We use this to improve caching as well as to detect cycles and other things during trait resolution. Roughly speaking, the idea is that if two trait queries have the same canonical form, -then they will get -the same answer. +then they will get the same answer. That answer will be expressed in terms of the canonical variables (`?0`, -`?1`), which we can then map back to the -original variables (`?T`, `?U`). +`?1`), which we can then map back to the original variables (`?T`, `?U`). ## Canonicalizing the query @@ -44,8 +40,8 @@ To see how it works, imagine that we are asking to solve the following trait query: `?A: Foo<'static, ?B>`, where `?A` and `?B` are unbound. This query contains two unbound variables, but it also contains the lifetime `'static`. The trait system generally ignores all lifetimes and treats them equally, -so when canonicalizing, we will *also* -replace any [free lifetime](../appendix/background.md#free-vs-bound) with a +so when canonicalizing, +we will *also* replace any [free lifetime](../appendix/background.md#free-vs-bound) with a canonical variable (Note that `'static` is actually a _free_ lifetime variable here. We are not considering it in the typing context of the whole program, but only in the context of this trait reference. @@ -94,8 +90,7 @@ S = [?A, '?B, ?C] ``` We can then replace the bound canonical variables (`?0`, etc) with these inference variables, -yielding the following fully instantiated -query: +yielding the following fully instantiated query: ```text ?A: Foo<'?B, ?C> @@ -107,8 +102,7 @@ We're going to need it later. OK, now that we have a fresh inference context and an instantiated query, we can go ahead and try to solve it. The trait solver itself is explained in more detail in [another section](../solve/the-solver.md), -but -suffice to say that it will compute a [certainty value][cqqr] (`Proven` or +but suffice to say that it will compute a [certainty value][cqqr] (`Proven` or `Ambiguous`) and have side-effects on the inference variables we've created. For example, if there were only one impl of `Foo`, like so: @@ -140,8 +134,8 @@ We do that by **re-applying canonicalization**, but to the **query result**. As discussed in [the parent section][cqqr], most trait queries wind up with a result that brings together a "certainty value" `certainty`, a result substitution `var_values`, and some region constraints. -To create this, we wind up re-using the substitution S that we created -when first instantiating our query. +To create this, +we wind up re-using the substitution S that we created when first instantiating our query. To refresh your memory, we had a query: ```text @@ -190,8 +184,8 @@ Canonical(QR) = for { (One subtle point: when we canonicalize the query **result**, we do not use any special treatment for free lifetimes. -Note that both references to `'?D`, for example, were converted into the same -canonical variable (`?1`). +Note that both references to `'?D`, for example, +were converted into the same canonical variable (`?1`). This is in contrast to the original query, where we canonicalized every free lifetime into a fresh canonical variable.) @@ -252,8 +246,8 @@ And finally, the region constraint of `?C: 'static` would be recorded for later (What we *actually* do is a mildly optimized variant of that: Rather than eagerly instantiating all of the canonical values in the result with variables, -we instead walk the vector of values, looking for -cases where the value is just a canonical variable. +we instead walk the vector of values, +looking for cases where the value is just a canonical variable. In our example, `values[2]` is `?C`, so that means we can deduce that `?C := ?B` and `'?D := 'static`. This gives us a partial set of values. From 8f09efbb093d14c52eb4101c4e5560b56f0597f6 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 21:26:03 +0100 Subject: [PATCH 18/32] fix sembr tool fail --- src/doc/rustc-dev-guide/src/traits/canonicalization.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/traits/canonicalization.md b/src/doc/rustc-dev-guide/src/traits/canonicalization.md index d87e3b3031022..d1cd1a2cefb49 100644 --- a/src/doc/rustc-dev-guide/src/traits/canonicalization.md +++ b/src/doc/rustc-dev-guide/src/traits/canonicalization.md @@ -21,8 +21,8 @@ but really it doesn't matter as long as it is consistent). [cq]: ./canonical-queries.md So, for example, if we have the type `X = (?T, ?U)`, where `?T` and `?U` are distinct -unbound inference variables, then the canonical form of `X` would be `(?0, -?1)`, where `?0` and `?1` represent these **canonical placeholders**. +unbound inference variables, then the canonical form of `X` would be `(?0, ?1)`, +where `?0` and `?1` represent these **canonical placeholders**. Note that the type `Y = (?U, ?T)` also canonicalizes to `(?0, ?1)`. But the type `Z = (?T, ?T)` would canonicalize to `(?0, ?0)` (as would `(?U, ?U)`). In other words, the exact identity of the inference variables is not important, From 2f7cf458955ee99033a8879b46b9cf8e0df93770 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 21:31:49 +0100 Subject: [PATCH 19/32] sembr src/type-inference.md --- src/doc/rustc-dev-guide/src/type-inference.md | 249 +++++++++--------- 1 file changed, 123 insertions(+), 126 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/type-inference.md b/src/doc/rustc-dev-guide/src/type-inference.md index 196fcdd9190c3..0a37dfbd9928b 100644 --- a/src/doc/rustc-dev-guide/src/type-inference.md +++ b/src/doc/rustc-dev-guide/src/type-inference.md @@ -1,7 +1,6 @@ # Type inference -Type inference is the process of automatic detection of the type of an -expression. +Type inference is the process of automatic detection of the type of an expression. It is what allows Rust to work with fewer or no type annotations, making things easier for users: @@ -13,55 +12,52 @@ fn main() { } ``` -Here, the type of `things` is *inferred* to be `Vec<&str>` because of the value -we push into `things`. +Here, +the type of `things` is *inferred* to be `Vec<&str>` because of the value we push into `things`. -The type inference is based on the standard Hindley-Milner (HM) type inference -algorithm, but extended in various ways to accommodate subtyping, region +The type inference is based on the standard Hindley-Milner (HM) type inference algorithm, +but extended in various ways to accommodate subtyping, region inference, and higher-ranked types. ## A note on terminology -We use the notation `?T` to refer to inference variables, also called -existential variables. +We use the notation `?T` to refer to inference variables, also called existential variables. -We use the terms "region" and "lifetime" interchangeably. Both refer to -the `'a` in `&'a T`. +We use the terms "region" and "lifetime" interchangeably. +Both refer to the `'a` in `&'a T`. -The term "bound region" refers to a region that is bound in a function -signature, such as the `'a` in `for<'a> fn(&'a u32)`. A region is -"free" if it is not bound. +The term "bound region" refers to a region that is bound in a function signature, +such as the `'a` in `for<'a> fn(&'a u32)`. +A region is "free" if it is not bound. ## Creating an inference context -You create an inference context by doing something like -the following: +You create an inference context by doing something like the following: ```rust,ignore let infcx = tcx.infer_ctxt().build(); // Use the inference context `infcx` here. ``` -`infcx` has the type `InferCtxt<'tcx>`, the same `'tcx` lifetime as on -the `tcx` it was built from. +`infcx` has the type `InferCtxt<'tcx>`, the same `'tcx` lifetime as on the `tcx` it was built from. -The `tcx.infer_ctxt` method actually returns a builder, which means -there are some kinds of configuration you can do before the `infcx` is -created. See `InferCtxtBuilder` for more information. +The `tcx.infer_ctxt` method actually returns a builder, +which means there are some kinds of configuration you can do before the `infcx` is +created. +See `InferCtxtBuilder` for more information. ## Inference variables The main purpose of the inference context is to house a bunch of -**inference variables** – these represent types or regions whose precise -value is not yet known, but will be uncovered as we perform type-checking. +**inference variables** – these represent types or regions whose precise value is not yet known, +but will be uncovered as we perform type-checking. -If you're familiar with the basic ideas of unification from H-M type -systems, or logic languages like Prolog, this is the same concept. If -you're not, you might want to read a tutorial on how H-M type -inference works, or perhaps this blog post on -[unification in the Chalk project]. +If you're familiar with the basic ideas of unification from H-M type systems, +or logic languages like Prolog, this is the same concept. +If you're not, you might want to read a tutorial on how H-M type +inference works, or perhaps this blog post on [unification in the Chalk project]. [Unification in the Chalk project]: http://smallcultfollowing.com/babysteps/blog/2017/03/25/unification-in-chalk-part-1/ @@ -69,30 +65,29 @@ All told, the inference context stores five kinds of inference variables (as of March 2023): - Type variables, which come in three varieties: - - General type variables (the most common). These can be unified with any - type. + - General type variables (the most common). + These can be unified with any type. - Integral type variables, which can only be unified with an integral type, and arise from an integer literal expression like `22`. - - Float type variables, which can only be unified with a float type, and - arise from a float literal expression like `22.0`. + - Float type variables, which can only be unified with a float type, + and arise from a float literal expression like `22.0`. - Region variables, which represent lifetimes, and arise all over the place. - Const variables, which represent constants. -All the type variables work in much the same way: you can create a new -type variable, and what you get is `Ty<'tcx>` representing an -unresolved type `?T`. Then later you can apply the various operations -that the inferencer supports, such as equality or subtyping, and it -will possibly **instantiate** (or **bind**) that `?T` to a specific -value as a result. +All the type variables work in much the same way: you can create a new type variable, +and what you get is `Ty<'tcx>` representing an +unresolved type `?T`. +Then later you can apply the various operations that the inferencer supports, +such as equality or subtyping, and it +will possibly **instantiate** (or **bind**) that `?T` to a specific value as a result. -The region variables work somewhat differently, and are described -below in a separate section. +The region variables work somewhat differently, and are described below in a separate section. ## Enforcing equality / subtyping -The most basic operations you can perform in the type inferencer is -**equality**, which forces two types `T` and `U` to be the same. The -recommended way to add an equality constraint is to use the `at` +The most basic operations you can perform in the type inferencer is **equality**, +which forces two types `T` and `U` to be the same. +The recommended way to add an equality constraint is to use the `at` method, roughly like so: ```rust,ignore @@ -100,71 +95,72 @@ infcx.at(...).eq(t, u); ``` The first `at()` call provides a bit of context, i.e. why you are -doing this unification, and in what environment, and the `eq` method -performs the actual equality constraint. +doing this unification, and in what environment, +and the `eq` method performs the actual equality constraint. -When you equate things, you force them to be precisely equal. Equating -returns an `InferResult` – if it returns `Err(err)`, then equating +When you equate things, you force them to be precisely equal. +Equating returns an `InferResult` – if it returns `Err(err)`, then equating failed, and the enclosing `TypeError` will tell you what went wrong. -The success case is perhaps more interesting. The "primary" return -type of `eq` is `()` – that is, when it succeeds, it doesn't return a -value of any particular interest. Rather, it is executed for its -side-effects of constraining type variables and so forth. However, the -actual return type is not `()`, but rather `InferOk<()>`. The -`InferOk` type is used to carry extra trait obligations – your job is -to ensure that these are fulfilled (typically by enrolling them in a -fulfillment context). See the [trait chapter] for more background on that. +The success case is perhaps more interesting. +The "primary" return type of `eq` is `()` – that is, when it succeeds, it doesn't return a +value of any particular interest. +Rather, it is executed for its side-effects of constraining type variables and so forth. +However, the actual return type is not `()`, but rather `InferOk<()>`. +The `InferOk` type is used to carry extra trait obligations – your job is +to ensure that these are fulfilled (typically by enrolling them in a fulfillment context). +See the [trait chapter] for more background on that. [trait chapter]: traits/resolution.md -You can similarly enforce subtyping through `infcx.at(..).sub(..)`. The same -basic concepts as above apply. +You can similarly enforce subtyping through `infcx.at(..).sub(..)`. +The same basic concepts as above apply. ## "Trying" equality -Sometimes you would like to know if it is *possible* to equate two -types without error. You can test that with `infcx.can_eq` (or -`infcx.can_sub` for subtyping). If this returns `Ok`, then equality -is possible – but in all cases, any side-effects are reversed. +Sometimes you would like to know if it is *possible* to equate two types without error. + You can test that with `infcx.can_eq` (or `infcx.can_sub` for subtyping). +If this returns `Ok`, then equality is possible – but in all cases, any side-effects are reversed. -Be aware, though, that the success or failure of these methods is always -**modulo regions**. That is, two types `&'a u32` and `&'b u32` will -return `Ok` for `can_eq`, even if `'a != 'b`. This falls out from the -"two-phase" nature of how we solve region constraints. +Be aware, though, that the success or failure of these methods is always **modulo regions**. +That is, two types `&'a u32` and `&'b u32` will return `Ok` for `can_eq`, even if `'a != 'b`. + This falls out from the "two-phase" nature of how we solve region constraints. ## Snapshots -As described in the previous section on `can_eq`, often it is useful -to be able to do a series of operations and then roll back their -side-effects. This is done for various reasons: one of them is to be -able to backtrack, trying out multiple possibilities before settling -on which path to take. Another is in order to ensure that a series of -smaller changes take place atomically or not at all. +As described in the previous section on `can_eq`, +often it is useful to be able to do a series of operations and then roll back their +side-effects. +This is done for various reasons: one of them is to be able to backtrack, +trying out multiple possibilities before settling +on which path to take. +Another is in order to ensure that a series of smaller changes take place atomically or not at all. To allow for this, the inference context supports a `snapshot` method. -When you call it, it will start recording changes that occur from the -operations you perform. When you are done, you can either invoke -`rollback_to`, which will undo those changes, or else `confirm`, which -will make them permanent. Snapshots can be nested as long as you follow -a stack-like discipline. - -Rather than use snapshots directly, it is often helpful to use the -methods like `commit_if_ok` or `probe` that encapsulate higher-level +When you call it, it will start recording changes that occur from the operations you perform. +When you are done, you can either invoke `rollback_to`, +which will undo those changes, or else `confirm`, which +will make them permanent. +Snapshots can be nested as long as you follow a stack-like discipline. + +Rather than use snapshots directly, +it is often helpful to use the methods like `commit_if_ok` or `probe` that encapsulate higher-level patterns. ## Subtyping obligations -One thing worth discussing is subtyping obligations. When you force -two types to be a subtype, like `?T <: i32`, we can often convert those -into equality constraints. This follows from Rust's rather limited notion -of subtyping: so, in the above case, `?T <: i32` is equivalent to `?T = i32`. +One thing worth discussing is subtyping obligations. +When you force two types to be a subtype, like `?T <: i32`, we can often convert those +into equality constraints. +This follows from Rust's rather limited notion of subtyping: so, +in the above case, `?T <: i32` is equivalent to `?T = i32`. -However, in some cases we have to be more careful. For example, when -regions are involved. So if you have `?T <: &'a i32`, what we would do -is to first "generalize" `&'a i32` into a type with a region variable: -`&'?b i32`, and then unify `?T` with that (`?T = &'?b i32`). We then -relate this new variable with the original bound: +However, in some cases we have to be more careful. +For example, when regions are involved. +So if you have `?T <: &'a i32`, +what we would do is to first "generalize" `&'a i32` into a type with a region variable: +`&'?b i32`, and then unify `?T` with that (`?T = &'?b i32`). +We then relate this new variable with the original bound: ```text &'?b i32 <: &'a i32 @@ -173,73 +169,74 @@ relate this new variable with the original bound: This will result in a region constraint (see below) of `'?b: 'a`. One final interesting case is relating two unbound type variables, -like `?T <: ?U`. In that case, we can't make progress, so we enqueue -an obligation `Subtype(?T, ?U)` and return it via the `InferOk` -mechanism. You'll have to try again when more details about `?T` or -`?U` are known. +like `?T <: ?U`. + In that case, we can't make progress, so we enqueue an obligation `Subtype(?T, +?U)` and return it via the `InferOk` +mechanism. +You'll have to try again when more details about `?T` or `?U` are known. ## Region constraints -Regions are inferenced somewhat differently from types. Rather than -eagerly unifying things, we simply collect constraints as we go, but -make (almost) no attempt to solve regions. These constraints have the -form of an "outlives" constraint: +Regions are inferenced somewhat differently from types. +Rather than eagerly unifying things, we simply collect constraints as we go, but +make (almost) no attempt to solve regions. +These constraints have the form of an "outlives" constraint: ```text 'a: 'b ``` -Actually the code tends to view them as a subregion relation, but it's the same -idea: +Actually the code tends to view them as a subregion relation, but it's the same idea: ```text 'b <= 'a ``` -(There are various other kinds of constraints, such as "verifys"; see -the [`region_constraints`] module for details.) +(There are various other kinds of constraints, +such as "verifys"; see the [`region_constraints`] module for details.) -There is one case where we do some amount of eager unification. If you have an -equality constraint between two regions +There is one case where we do some amount of eager unification. +If you have an equality constraint between two regions ```text 'a = 'b ``` -we will record that fact in a unification table. You can then use -[`opportunistic_resolve_var`] to convert `'b` to `'a` (or vice -versa). This is sometimes needed to ensure termination of fixed-point -algorithms. +we will record that fact in a unification table. +You can then use [`opportunistic_resolve_var`] to convert `'b` to `'a` (or vice +versa). +This is sometimes needed to ensure termination of fixed-point algorithms. [`region_constraints`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_infer/infer/region_constraints/index.html [`opportunistic_resolve_var`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_infer/infer/region_constraints/struct.RegionConstraintCollector.html#method.opportunistic_resolve_var ## Solving region constraints -Region constraints are only solved at the very end of -typechecking, once all other constraints are known and -all other obligations have been proven. There are two -ways to solve region constraints right now: lexical and -non-lexical. Eventually there will only be one. +Region constraints are only solved at the very end of typechecking, +once all other constraints are known and +all other obligations have been proven. +There are two ways to solve region constraints right now: lexical and +non-lexical. +Eventually there will only be one. An exception here is the leak-check which is used during trait solving -and relies on region constraints containing higher-ranked regions. Region +and relies on region constraints containing higher-ranked regions. +Region constraints in the root universe (i.e. not arising from a `for<'a>`) must -not influence the trait system, as these regions are all erased during -codegen. +not influence the trait system, as these regions are all erased during codegen. -To solve **lexical** region constraints, you invoke -[`resolve_regions_and_report_errors`]. This "closes" the region -constraint process and invokes the [`lexical_region_resolve`] code. Once -this is done, any further attempt to equate or create a subtyping +To solve **lexical** region constraints, you invoke [`resolve_regions_and_report_errors`]. + This "closes" the region constraint process and invokes the [`lexical_region_resolve`] code. +Once this is done, any further attempt to equate or create a subtyping relationship will yield an ICE. -The NLL solver (actually, the MIR type-checker) does things slightly -differently. It uses canonical queries for trait solving which use -[`take_and_reset_region_constraints`] at the end. This extracts all of the -outlives constraints added during the canonical query. This is required -as the NLL solver must not only know *what* regions outlive each other, -but also *where*. Finally, the NLL solver invokes [`get_region_var_infos`], +The NLL solver (actually, the MIR type-checker) does things slightly differently. +It uses canonical queries for trait solving which use +[`take_and_reset_region_constraints`] at the end. +This extracts all of the outlives constraints added during the canonical query. +This is required as the NLL solver must not only know *what* regions outlive each other, +but also *where*. +Finally, the NLL solver invokes [`get_region_var_infos`], providing all region variables to the solver. [`resolve_regions_and_report_errors`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/traits/struct.ObligationCtxt.html#method.resolve_regions_and_report_errors @@ -249,8 +246,8 @@ providing all region variables to the solver. ## Lexical region resolution -Lexical region resolution is done by initially assigning each region -variable to an empty value. We then process each outlives constraint -repeatedly, growing region variables until a fixed-point is reached. +Lexical region resolution is done by initially assigning each region variable to an empty value. +We then process each outlives constraint repeatedly, +growing region variables until a fixed-point is reached. Region variables can be grown using a least-upper-bound relation on the region lattice in a fairly straightforward fashion. From eaeddd61678d5b4c3bf6ab848d4789fe50ac797c Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 21:46:06 +0100 Subject: [PATCH 20/32] improve type-inference.md --- src/doc/rustc-dev-guide/src/type-inference.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/type-inference.md b/src/doc/rustc-dev-guide/src/type-inference.md index 0a37dfbd9928b..aaedb2b825132 100644 --- a/src/doc/rustc-dev-guide/src/type-inference.md +++ b/src/doc/rustc-dev-guide/src/type-inference.md @@ -51,7 +51,8 @@ See `InferCtxtBuilder` for more information. ## Inference variables The main purpose of the inference context is to house a bunch of -**inference variables** – these represent types or regions whose precise value is not yet known, +**inference variables**. +These represent types or regions whose precise value is not yet known, but will be uncovered as we perform type-checking. If you're familiar with the basic ideas of unification from H-M type systems, @@ -77,7 +78,7 @@ All told, the inference context stores five kinds of inference variables All the type variables work in much the same way: you can create a new type variable, and what you get is `Ty<'tcx>` representing an unresolved type `?T`. -Then later you can apply the various operations that the inferencer supports, +You can then later apply the various operations that the inferencer supports, such as equality or subtyping, and it will possibly **instantiate** (or **bind**) that `?T` to a specific value as a result. @@ -119,12 +120,12 @@ The same basic concepts as above apply. ## "Trying" equality Sometimes you would like to know if it is *possible* to equate two types without error. - You can test that with `infcx.can_eq` (or `infcx.can_sub` for subtyping). +You can test that with `infcx.can_eq` (or `infcx.can_sub` for subtyping). If this returns `Ok`, then equality is possible – but in all cases, any side-effects are reversed. Be aware, though, that the success or failure of these methods is always **modulo regions**. That is, two types `&'a u32` and `&'b u32` will return `Ok` for `can_eq`, even if `'a != 'b`. - This falls out from the "two-phase" nature of how we solve region constraints. +This falls out from the "two-phase" nature of how we solve region constraints. ## Snapshots @@ -156,8 +157,8 @@ This follows from Rust's rather limited notion of subtyping: so, in the above case, `?T <: i32` is equivalent to `?T = i32`. However, in some cases we have to be more careful. -For example, when regions are involved. -So if you have `?T <: &'a i32`, +An example is when regions are involved. +So, if you have `?T <: &'a i32`, what we would do is to first "generalize" `&'a i32` into a type with a region variable: `&'?b i32`, and then unify `?T` with that (`?T = &'?b i32`). We then relate this new variable with the original bound: @@ -170,7 +171,7 @@ This will result in a region constraint (see below) of `'?b: 'a`. One final interesting case is relating two unbound type variables, like `?T <: ?U`. - In that case, we can't make progress, so we enqueue an obligation `Subtype(?T, +In that case, we can't make progress, so we enqueue an obligation `Subtype(?T, ?U)` and return it via the `InferOk` mechanism. You'll have to try again when more details about `?T` or `?U` are known. @@ -226,7 +227,7 @@ constraints in the root universe (i.e. not arising from a `for<'a>`) must not influence the trait system, as these regions are all erased during codegen. To solve **lexical** region constraints, you invoke [`resolve_regions_and_report_errors`]. - This "closes" the region constraint process and invokes the [`lexical_region_resolve`] code. +This "closes" the region constraint process and invokes the [`lexical_region_resolve`] code. Once this is done, any further attempt to equate or create a subtyping relationship will yield an ICE. From 8ce5ef2b98d2a56cbdc0e167e96c8f83a84338c1 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 21:47:05 +0100 Subject: [PATCH 21/32] reflow src/type-inference.md --- src/doc/rustc-dev-guide/src/type-inference.md | 68 ++++++++----------- 1 file changed, 28 insertions(+), 40 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/type-inference.md b/src/doc/rustc-dev-guide/src/type-inference.md index aaedb2b825132..31f2f4b198e63 100644 --- a/src/doc/rustc-dev-guide/src/type-inference.md +++ b/src/doc/rustc-dev-guide/src/type-inference.md @@ -16,8 +16,7 @@ Here, the type of `things` is *inferred* to be `Vec<&str>` because of the value we push into `things`. The type inference is based on the standard Hindley-Milner (HM) type inference algorithm, -but extended in various ways to accommodate subtyping, region -inference, and higher-ranked types. +but extended in various ways to accommodate subtyping, region inference, and higher-ranked types. ## A note on terminology @@ -42,23 +41,21 @@ let infcx = tcx.infer_ctxt().build(); `infcx` has the type `InferCtxt<'tcx>`, the same `'tcx` lifetime as on the `tcx` it was built from. The `tcx.infer_ctxt` method actually returns a builder, -which means there are some kinds of configuration you can do before the `infcx` is -created. +which means there are some kinds of configuration you can do before the `infcx` is created. See `InferCtxtBuilder` for more information. ## Inference variables -The main purpose of the inference context is to house a bunch of -**inference variables**. +The main purpose of the inference context is to house a bunch of **inference variables**. These represent types or regions whose precise value is not yet known, but will be uncovered as we perform type-checking. If you're familiar with the basic ideas of unification from H-M type systems, or logic languages like Prolog, this is the same concept. -If you're not, you might want to read a tutorial on how H-M type -inference works, or perhaps this blog post on [unification in the Chalk project]. +If you're not, you might want to read a tutorial on how H-M type inference works, +or perhaps this blog post on [unification in the Chalk project]. [Unification in the Chalk project]: http://smallcultfollowing.com/babysteps/blog/2017/03/25/unification-in-chalk-part-1/ @@ -76,11 +73,10 @@ All told, the inference context stores five kinds of inference variables - Const variables, which represent constants. All the type variables work in much the same way: you can create a new type variable, -and what you get is `Ty<'tcx>` representing an -unresolved type `?T`. +and what you get is `Ty<'tcx>` representing an unresolved type `?T`. You can then later apply the various operations that the inferencer supports, -such as equality or subtyping, and it -will possibly **instantiate** (or **bind**) that `?T` to a specific value as a result. +such as equality or subtyping, +and it will possibly **instantiate** (or **bind**) that `?T` to a specific value as a result. The region variables work somewhat differently, and are described below in a separate section. @@ -88,8 +84,7 @@ The region variables work somewhat differently, and are described below in a sep The most basic operations you can perform in the type inferencer is **equality**, which forces two types `T` and `U` to be the same. -The recommended way to add an equality constraint is to use the `at` -method, roughly like so: +The recommended way to add an equality constraint is to use the `at` method, roughly like so: ```rust,ignore infcx.at(...).eq(t, u); @@ -100,12 +95,12 @@ doing this unification, and in what environment, and the `eq` method performs the actual equality constraint. When you equate things, you force them to be precisely equal. -Equating returns an `InferResult` – if it returns `Err(err)`, then equating -failed, and the enclosing `TypeError` will tell you what went wrong. +Equating returns an `InferResult` – if it returns `Err(err)`, then equating failed, +and the enclosing `TypeError` will tell you what went wrong. The success case is perhaps more interesting. -The "primary" return type of `eq` is `()` – that is, when it succeeds, it doesn't return a -value of any particular interest. +The "primary" return type of `eq` is `()` – that is, when it succeeds, +it doesn't return a value of any particular interest. Rather, it is executed for its side-effects of constraining type variables and so forth. However, the actual return type is not `()`, but rather `InferOk<()>`. The `InferOk` type is used to carry extra trait obligations – your job is @@ -130,18 +125,15 @@ This falls out from the "two-phase" nature of how we solve region constraints. ## Snapshots As described in the previous section on `can_eq`, -often it is useful to be able to do a series of operations and then roll back their -side-effects. +often it is useful to be able to do a series of operations and then roll back their side-effects. This is done for various reasons: one of them is to be able to backtrack, -trying out multiple possibilities before settling -on which path to take. +trying out multiple possibilities before settling on which path to take. Another is in order to ensure that a series of smaller changes take place atomically or not at all. To allow for this, the inference context supports a `snapshot` method. When you call it, it will start recording changes that occur from the operations you perform. When you are done, you can either invoke `rollback_to`, -which will undo those changes, or else `confirm`, which -will make them permanent. +which will undo those changes, or else `confirm`, which will make them permanent. Snapshots can be nested as long as you follow a stack-like discipline. Rather than use snapshots directly, @@ -151,16 +143,16 @@ patterns. ## Subtyping obligations One thing worth discussing is subtyping obligations. -When you force two types to be a subtype, like `?T <: i32`, we can often convert those -into equality constraints. +When you force two types to be a subtype, like `?T <: i32`, +we can often convert those into equality constraints. This follows from Rust's rather limited notion of subtyping: so, in the above case, `?T <: i32` is equivalent to `?T = i32`. However, in some cases we have to be more careful. An example is when regions are involved. So, if you have `?T <: &'a i32`, -what we would do is to first "generalize" `&'a i32` into a type with a region variable: -`&'?b i32`, and then unify `?T` with that (`?T = &'?b i32`). +what we would do is to first "generalize" `&'a i32` into a type with a region variable: `&'?b i32`, +and then unify `?T` with that (`?T = &'?b i32`). We then relate this new variable with the original bound: ```text @@ -172,15 +164,14 @@ This will result in a region constraint (see below) of `'?b: 'a`. One final interesting case is relating two unbound type variables, like `?T <: ?U`. In that case, we can't make progress, so we enqueue an obligation `Subtype(?T, -?U)` and return it via the `InferOk` -mechanism. +?U)` and return it via the `InferOk` mechanism. You'll have to try again when more details about `?T` or `?U` are known. ## Region constraints Regions are inferenced somewhat differently from types. -Rather than eagerly unifying things, we simply collect constraints as we go, but -make (almost) no attempt to solve regions. +Rather than eagerly unifying things, we simply collect constraints as we go, +but make (almost) no attempt to solve regions. These constraints have the form of an "outlives" constraint: ```text @@ -204,8 +195,7 @@ If you have an equality constraint between two regions ``` we will record that fact in a unification table. -You can then use [`opportunistic_resolve_var`] to convert `'b` to `'a` (or vice -versa). +You can then use [`opportunistic_resolve_var`] to convert `'b` to `'a` (or vice versa). This is sometimes needed to ensure termination of fixed-point algorithms. [`region_constraints`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_infer/infer/region_constraints/index.html @@ -214,10 +204,8 @@ This is sometimes needed to ensure termination of fixed-point algorithms. ## Solving region constraints Region constraints are only solved at the very end of typechecking, -once all other constraints are known and -all other obligations have been proven. -There are two ways to solve region constraints right now: lexical and -non-lexical. +once all other constraints are known and all other obligations have been proven. +There are two ways to solve region constraints right now: lexical and non-lexical. Eventually there will only be one. An exception here is the leak-check which is used during trait solving @@ -228,8 +216,8 @@ not influence the trait system, as these regions are all erased during codegen. To solve **lexical** region constraints, you invoke [`resolve_regions_and_report_errors`]. This "closes" the region constraint process and invokes the [`lexical_region_resolve`] code. -Once this is done, any further attempt to equate or create a subtyping -relationship will yield an ICE. +Once this is done, +any further attempt to equate or create a subtyping relationship will yield an ICE. The NLL solver (actually, the MIR type-checker) does things slightly differently. It uses canonical queries for trait solving which use From b22380e03d003a1758a7e926570071e0ebff3df5 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 22:50:03 +0100 Subject: [PATCH 22/32] double space is very common... I do not remember seeing more --- src/doc/rustc-dev-guide/ci/sembr/src/main.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/doc/rustc-dev-guide/ci/sembr/src/main.rs b/src/doc/rustc-dev-guide/ci/sembr/src/main.rs index 56761cbb07487..10b41e7703449 100644 --- a/src/doc/rustc-dev-guide/ci/sembr/src/main.rs +++ b/src/doc/rustc-dev-guide/ci/sembr/src/main.rs @@ -122,9 +122,8 @@ fn comply(content: &str) -> String { }; let mut newly_split_lines = line.split_inclusive(&*REGEX_SPLIT); let first = newly_split_lines.next().unwrap().trim_end().to_owned(); - let mut remaining: Vec<_> = newly_split_lines - .map(|portion| format!("{:indent$}{}", "", portion.trim_end())) - .collect(); + let mut remaining: Vec<_> = + newly_split_lines.map(|portion| format!("{:indent$}{}", "", portion.trim())).collect(); let mut new_lines = Vec::new(); new_lines.push(first); new_lines.append(&mut remaining); @@ -244,13 +243,14 @@ some code. block ``` sentence with *italics* should not be ignored. truly. git log main.. compiler - foo. bar. baz o? whatever r? @reviewer r? @reviewer ~? diagnostic the queries that we do, as well as the **query DAG**. The + +trim double space. or many spaces. in this next sentence "; let expected = " # some. heading @@ -276,9 +276,6 @@ some code. block sentence with *italics* should not be ignored. truly. git log main.. compiler - foo. - bar. - baz o? whatever r? @reviewer @@ -287,6 +284,10 @@ r? @reviewer the queries that we do, as well as the **query DAG**. The + +trim double space. +or many spaces. +in this next sentence "; assert_eq!(expected, comply(original)); } From 70a37c2b6b6600ddf912b9460924b21c928ebbda Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 22:59:11 +0100 Subject: [PATCH 23/32] binding not needed --- src/doc/rustc-dev-guide/ci/sembr/src/main.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/doc/rustc-dev-guide/ci/sembr/src/main.rs b/src/doc/rustc-dev-guide/ci/sembr/src/main.rs index 10b41e7703449..6125f2261cc77 100644 --- a/src/doc/rustc-dev-guide/ci/sembr/src/main.rs +++ b/src/doc/rustc-dev-guide/ci/sembr/src/main.rs @@ -121,11 +121,10 @@ fn comply(content: &str) -> String { line.find(|ch: char| !ch.is_whitespace()).unwrap() }; let mut newly_split_lines = line.split_inclusive(&*REGEX_SPLIT); - let first = newly_split_lines.next().unwrap().trim_end().to_owned(); + let mut new_lines = Vec::new(); + new_lines.push(newly_split_lines.next().unwrap().trim_end().to_owned()); let mut remaining: Vec<_> = newly_split_lines.map(|portion| format!("{:indent$}{}", "", portion.trim())).collect(); - let mut new_lines = Vec::new(); - new_lines.push(first); new_lines.append(&mut remaining); new_content.splice(new_n..=new_n, new_lines.clone()); new_n += new_lines.len() - 1; From 0a70cc57aee6470fc99b4b21222e699a1b8d54e1 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 22:59:52 +0100 Subject: [PATCH 24/32] sembr src/ty-module/early-binder.md --- .../src/ty-module/early-binder.md | 37 ++++++++++++++----- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/ty-module/early-binder.md b/src/doc/rustc-dev-guide/src/ty-module/early-binder.md index d83d73c955bfc..e5b43f3837a4a 100644 --- a/src/doc/rustc-dev-guide/src/ty-module/early-binder.md +++ b/src/doc/rustc-dev-guide/src/ty-module/early-binder.md @@ -10,11 +10,20 @@ fn main() { } ``` -When type checking `main` we cannot just naively look at the return type of `foo` and assign the type `T` to the variable `c`, The function `main` does not define any generic parameters, `T` is completely meaningless in this context. More generally whenever an item introduces (binds) generic parameters, when accessing types inside the item from outside, the generic parameters must be instantiated with values from the outer item. +When type checking `main` we cannot just naively look at the return type of `foo` and assign the type `T` to the variable `c`, The function `main` does not define any generic parameters, +`T` is completely meaningless in this context. +More generally whenever an item introduces (binds) generic parameters, when accessing types inside the item from outside, +the generic parameters must be instantiated with values from the outer item. -In rustc we track this via the [`EarlyBinder`] type, the return type of `foo` is represented as an `EarlyBinder` with the only way to access `Ty` being to provide arguments for any generic parameters `Ty` might be using. This is implemented via the [`EarlyBinder::instantiate`] method which discharges the binder returning the inner value with all the generic parameters replaced by the provided arguments. +In rustc we track this via the [`EarlyBinder`] type, +the return type of `foo` is represented as an `EarlyBinder` with the only way to access `Ty` being to provide arguments for any generic parameters `Ty` might be using. +This is implemented via the [`EarlyBinder::instantiate`] method which discharges the binder returning the inner value with all the generic parameters replaced by the provided arguments. -To go back to our example, when type checking `main` the return type of `foo` would be represented as `EarlyBinder(T/#0)`. Then, because we called the function with `i32, u128` for the generic arguments, we would call `EarlyBinder::instantiate` on the return type with `[i32, u128]` for the args. This would result in an instantiated return type of `i32` that we can use as the type of the local `c`. +To go back to our example, +when type checking `main` the return type of `foo` would be represented as `EarlyBinder(T/#0)`. +Then, because we called the function with `i32, u128` for the generic arguments, we would call `EarlyBinder::instantiate` on the return type with `[i32, +u128]` for the args. +This would result in an instantiated return type of `i32` that we can use as the type of the local `c`. Here are some more examples: @@ -45,12 +54,14 @@ fn bar(foo: Foo) { } ``` -In the compiler the `instantiate` call for this is done in [`FieldDef::ty`] ([src][field_def_ty_src]), at some point during type checking `bar` we will wind up calling `FieldDef::ty(x, &[u32, f32])` in order to obtain the type of `foo.x`. +In the compiler the `instantiate` call for this is done in [`FieldDef::ty`] ([src][field_def_ty_src]), at some point during type checking `bar` we will wind up calling `FieldDef::ty(x, &[u32, +f32])` in order to obtain the type of `foo.x`. -**Note on indices:** It is a bug if the index of a `Param` does not match what the `EarlyBinder` binds. For -example, if the index is out of bounds or the index of a lifetime corresponds to a type parameter. +**Note on indices:** It is a bug if the index of a `Param` does not match what the `EarlyBinder` binds. +For example, +if the index is out of bounds or the index of a lifetime corresponds to a type parameter. These sorts of errors are caught earlier in the compiler during name resolution where we disallow references -to generics parameters introduced by items that should not be nameable by the inner item. +to generics parameters introduced by items that should not be nameable by the inner item. [`FieldDef::ty`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.FieldDef.html#method.ty [field_def_ty_src]: https://github.com/rust-lang/rust/blob/44d679b9021f03a79133021b94e6d23e9b55b3ab/compiler/rustc_middle/src/ty/mod.rs#L1421-L1426 @@ -59,7 +70,8 @@ to generics parameters introduced by items that should not be nameable by the in --- -As mentioned previously when _outside_ of an item, it is important to instantiate the `EarlyBinder` with generic arguments before accessing the value inside, but the setup for when we are conceptually inside of the binder already is a bit different. +As mentioned previously when _outside_ of an item, it is important to instantiate the `EarlyBinder` with generic arguments before accessing the value inside, +but the setup for when we are conceptually inside of the binder already is a bit different. For example: ```rust @@ -68,9 +80,14 @@ impl Trait for Vec { } ``` -When constructing a `Ty` to represent the `b` parameter's type we need to get the type of `Self` on the impl that we are inside. This can be acquired by calling the [`type_of`] query with the `impl`'s `DefId`, however, this will return a `EarlyBinder` as the impl block binds generic parameters that may have to be discharged if we are outside of the impl. +When constructing a `Ty` to represent the `b` parameter's type we need to get the type of `Self` on the impl that we are inside. +This can be acquired by calling the [`type_of`] query with the `impl`'s `DefId`, however, +this will return a `EarlyBinder` as the impl block binds generic parameters that may have to be discharged if we are outside of the impl. -The `EarlyBinder` type provides an [`instantiate_identity`] function for discharging the binder when you are "already inside of it". This is effectively a more performant version of writing `EarlyBinder::instantiate(GenericArgs::identity_for_item(..))`. Conceptually this discharges the binder by instantiating it with placeholders in the root universe (we will talk about what this means in the next few chapters). In practice though it simply returns the inner value with no modification taking place. +The `EarlyBinder` type provides an [`instantiate_identity`] function for discharging the binder when you are "already inside of it". +This is effectively a more performant version of writing `EarlyBinder::instantiate(GenericArgs::identity_for_item(..))`. +Conceptually this discharges the binder by instantiating it with placeholders in the root universe (we will talk about what this means in the next few chapters). +In practice though it simply returns the inner value with no modification taking place. [`type_of`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.type_of [`instantiate_identity`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/type.EarlyBinder.html#method.instantiate_identity From 0ca475be2896cf1bc9f99c383d92fcd1de58c378 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 23:08:12 +0100 Subject: [PATCH 25/32] improve ty-module/early-binder.md --- .../src/ty-module/early-binder.md | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/ty-module/early-binder.md b/src/doc/rustc-dev-guide/src/ty-module/early-binder.md index e5b43f3837a4a..016ac9de84d42 100644 --- a/src/doc/rustc-dev-guide/src/ty-module/early-binder.md +++ b/src/doc/rustc-dev-guide/src/ty-module/early-binder.md @@ -1,6 +1,9 @@ # `EarlyBinder` and instantiating parameters -Given an item that introduces a generic parameter `T`, whenever we refer to types inside of `foo` (i.e. the return type or argument types) from outside of `foo` we must take care to handle the generic parameters defined on `foo`. As an example: +Given an item that introduces a generic parameter `T`, +whenever we refer to types inside of `foo` (i.e. the return type or argument types) from outside of `foo`, +we must take care to handle the generic parameters defined on `foo`. +As an example: ```rust,ignore fn foo(a: T, _b: U) -> T { a } @@ -10,9 +13,11 @@ fn main() { } ``` -When type checking `main` we cannot just naively look at the return type of `foo` and assign the type `T` to the variable `c`, The function `main` does not define any generic parameters, -`T` is completely meaningless in this context. -More generally whenever an item introduces (binds) generic parameters, when accessing types inside the item from outside, +When type checking `main`, +we cannot just naively look at the return type of `foo` and assign the type `T` to the variable `c`. +The function `main` does not define any generic parameters, +and `T` is completely meaningless in this context. +More generally, whenever an item introduces (binds) generic parameters, when accessing types inside the item from outside, the generic parameters must be instantiated with values from the outer item. In rustc we track this via the [`EarlyBinder`] type, @@ -20,7 +25,8 @@ the return type of `foo` is represented as an `EarlyBinder` with the only wa This is implemented via the [`EarlyBinder::instantiate`] method which discharges the binder returning the inner value with all the generic parameters replaced by the provided arguments. To go back to our example, -when type checking `main` the return type of `foo` would be represented as `EarlyBinder(T/#0)`. +when type checking `main`, +the return type of `foo` would be represented as `EarlyBinder(T/#0)`. Then, because we called the function with `i32, u128` for the generic arguments, we would call `EarlyBinder::instantiate` on the return type with `[i32, u128]` for the args. This would result in an instantiated return type of `i32` that we can use as the type of the local `c`. @@ -44,7 +50,7 @@ struct Foo { .. } -fn bar(foo: Foo) { +fn bar(foo: Foo) { // the type of `foo`'s `x` field before instantiating it would be: // `EarlyBinder(Vec)` // we then instantiate the binder with `[u32, f32]` as those are the @@ -54,7 +60,7 @@ fn bar(foo: Foo) { } ``` -In the compiler the `instantiate` call for this is done in [`FieldDef::ty`] ([src][field_def_ty_src]), at some point during type checking `bar` we will wind up calling `FieldDef::ty(x, &[u32, +In the compiler, the `instantiate` call for this is done in [`FieldDef::ty`] ([src][field_def_ty_src]), and at some point during type checking `bar`, we will wind up calling `FieldDef::ty(x, &[u32, f32])` in order to obtain the type of `foo.x`. **Note on indices:** It is a bug if the index of a `Param` does not match what the `EarlyBinder` binds. @@ -80,14 +86,15 @@ impl Trait for Vec { } ``` -When constructing a `Ty` to represent the `b` parameter's type we need to get the type of `Self` on the impl that we are inside. -This can be acquired by calling the [`type_of`] query with the `impl`'s `DefId`, however, +When constructing a `Ty` to represent the `b` parameter's type, we need to get the type of `Self` on the impl that we are inside of. +This can be acquired by calling the [`type_of`] query with the `impl`'s `DefId`. However, this will return a `EarlyBinder` as the impl block binds generic parameters that may have to be discharged if we are outside of the impl. The `EarlyBinder` type provides an [`instantiate_identity`] function for discharging the binder when you are "already inside of it". This is effectively a more performant version of writing `EarlyBinder::instantiate(GenericArgs::identity_for_item(..))`. -Conceptually this discharges the binder by instantiating it with placeholders in the root universe (we will talk about what this means in the next few chapters). -In practice though it simply returns the inner value with no modification taking place. +Conceptually, this discharges the binder by instantiating it with placeholders in the root universe +(and we will talk about what this means in the next few chapters). +In practice, though, it simply returns the inner value with no modification taking place. [`type_of`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.type_of [`instantiate_identity`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/type.EarlyBinder.html#method.instantiate_identity From 321fc64bd3db74df12a97f922f9a79dee9ecb3a6 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 23:10:36 +0100 Subject: [PATCH 26/32] sembr src/ty-module/early-binder.md --- .../src/ty-module/early-binder.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/ty-module/early-binder.md b/src/doc/rustc-dev-guide/src/ty-module/early-binder.md index 016ac9de84d42..d46f8a5fb935c 100644 --- a/src/doc/rustc-dev-guide/src/ty-module/early-binder.md +++ b/src/doc/rustc-dev-guide/src/ty-module/early-binder.md @@ -17,7 +17,8 @@ When type checking `main`, we cannot just naively look at the return type of `foo` and assign the type `T` to the variable `c`. The function `main` does not define any generic parameters, and `T` is completely meaningless in this context. -More generally, whenever an item introduces (binds) generic parameters, when accessing types inside the item from outside, +More generally, whenever an item introduces (binds) generic parameters, +when accessing types inside the item from outside, the generic parameters must be instantiated with values from the outer item. In rustc we track this via the [`EarlyBinder`] type, @@ -27,7 +28,8 @@ This is implemented via the [`EarlyBinder::instantiate`] method which discharges To go back to our example, when type checking `main`, the return type of `foo` would be represented as `EarlyBinder(T/#0)`. -Then, because we called the function with `i32, u128` for the generic arguments, we would call `EarlyBinder::instantiate` on the return type with `[i32, +Then, because we called the function with `i32, u128` for the generic arguments, +we would call `EarlyBinder::instantiate` on the return type with `[i32, u128]` for the args. This would result in an instantiated return type of `i32` that we can use as the type of the local `c`. @@ -60,7 +62,8 @@ fn bar(foo: Foo) { } ``` -In the compiler, the `instantiate` call for this is done in [`FieldDef::ty`] ([src][field_def_ty_src]), and at some point during type checking `bar`, we will wind up calling `FieldDef::ty(x, &[u32, +In the compiler, the `instantiate` call for this is done in [`FieldDef::ty`] ([src][field_def_ty_src]), and at some point during type checking `bar`, we will wind up calling `FieldDef::ty(x, +&[u32, f32])` in order to obtain the type of `foo.x`. **Note on indices:** It is a bug if the index of a `Param` does not match what the `EarlyBinder` binds. @@ -76,7 +79,8 @@ to generics parameters introduced by items that should not be nameable by the in --- -As mentioned previously when _outside_ of an item, it is important to instantiate the `EarlyBinder` with generic arguments before accessing the value inside, +As mentioned previously when _outside_ of an item, +it is important to instantiate the `EarlyBinder` with generic arguments before accessing the value inside, but the setup for when we are conceptually inside of the binder already is a bit different. For example: @@ -86,8 +90,10 @@ impl Trait for Vec { } ``` -When constructing a `Ty` to represent the `b` parameter's type, we need to get the type of `Self` on the impl that we are inside of. -This can be acquired by calling the [`type_of`] query with the `impl`'s `DefId`. However, +When constructing a `Ty` to represent the `b` parameter's type, +we need to get the type of `Self` on the impl that we are inside of. +This can be acquired by calling the [`type_of`] query with the `impl`'s `DefId`. +However, this will return a `EarlyBinder` as the impl block binds generic parameters that may have to be discharged if we are outside of the impl. The `EarlyBinder` type provides an [`instantiate_identity`] function for discharging the binder when you are "already inside of it". From 3fa40ce8d3ec7d889cf7066853aa98e64b353edb Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 23:13:55 +0100 Subject: [PATCH 27/32] reflow src/ty-module/early-binder.md --- src/doc/rustc-dev-guide/src/ty-module/early-binder.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/ty-module/early-binder.md b/src/doc/rustc-dev-guide/src/ty-module/early-binder.md index d46f8a5fb935c..d1c311827cc1b 100644 --- a/src/doc/rustc-dev-guide/src/ty-module/early-binder.md +++ b/src/doc/rustc-dev-guide/src/ty-module/early-binder.md @@ -29,8 +29,7 @@ To go back to our example, when type checking `main`, the return type of `foo` would be represented as `EarlyBinder(T/#0)`. Then, because we called the function with `i32, u128` for the generic arguments, -we would call `EarlyBinder::instantiate` on the return type with `[i32, -u128]` for the args. +we would call `EarlyBinder::instantiate` on the return type with `[i32, u128]` for the args. This would result in an instantiated return type of `i32` that we can use as the type of the local `c`. Here are some more examples: @@ -62,9 +61,9 @@ fn bar(foo: Foo) { } ``` -In the compiler, the `instantiate` call for this is done in [`FieldDef::ty`] ([src][field_def_ty_src]), and at some point during type checking `bar`, we will wind up calling `FieldDef::ty(x, -&[u32, -f32])` in order to obtain the type of `foo.x`. +In the compiler, the `instantiate` call for this is done in [`FieldDef::ty`] ([src][field_def_ty_src]), +and at some point during type checking `bar`, +we will wind up calling `FieldDef::ty(x, &[u32, f32])` in order to obtain the type of `foo.x`. **Note on indices:** It is a bug if the index of a `Param` does not match what the `EarlyBinder` binds. For example, From a0dbfe0728f17c31f5b5f81b00466b0928f14c53 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 23:14:32 +0100 Subject: [PATCH 28/32] sembr src/traits/resolution.md --- .../rustc-dev-guide/src/traits/resolution.md | 194 +++++++++--------- 1 file changed, 98 insertions(+), 96 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/traits/resolution.md b/src/doc/rustc-dev-guide/src/traits/resolution.md index 394d800b5f868..1ae5bde54d53d 100644 --- a/src/doc/rustc-dev-guide/src/traits/resolution.md +++ b/src/doc/rustc-dev-guide/src/traits/resolution.md @@ -3,15 +3,15 @@ This chapter describes the general process of _trait resolution_ and points out some non-obvious things. -**Note:** This chapter (and its subchapters) describe how the trait -solver **currently** works. However, we are in the process of -designing a new trait solver. If you'd prefer to read about *that*, +**Note:** This chapter (and its subchapters) describe how the trait solver **currently** works. +However, we are in the process of designing a new trait solver. +If you'd prefer to read about *that*, see [*this* subchapter](./chalk.md). ## Major concepts -Trait resolution is the process of pairing up an impl with each -reference to a trait. So, for example, if there is a generic function like: +Trait resolution is the process of pairing up an impl with each reference to a trait. +So, for example, if there is a generic function like: ```rust,ignore fn clone_slice(x: &[T]) -> Vec { ... } @@ -26,9 +26,10 @@ let v: Vec = clone_slice(&[1, 2, 3]) it is the job of trait resolution to figure out whether there exists an impl of (in this case) `isize : Clone`. -Note that in some cases, like generic functions, we may not be able to -find a specific impl, but we can figure out that the caller must -provide an impl. For example, consider the body of `clone_slice`: +Note that in some cases, like generic functions, we may not be able to find a specific impl, +but we can figure out that the caller must +provide an impl. +For example, consider the body of `clone_slice`: ```rust,ignore fn clone_slice(x: &[T]) -> Vec { @@ -39,57 +40,55 @@ fn clone_slice(x: &[T]) -> Vec { } ``` -The line marked `(*)` is only legal if `T` (the type of `*e`) -implements the `Clone` trait. Naturally, since we don't know what `T` -is, we can't find the specific impl; but based on the bound `T:Clone`, +The line marked `(*)` is only legal if `T` (the type of `*e`) implements the `Clone` trait. +Naturally, since we don't know what `T` is, +we can't find the specific impl; but based on the bound `T:Clone`, we can say that there exists an impl which the caller must provide. -We use the term *obligation* to refer to a trait reference in need of -an impl. Basically, the trait resolution system resolves an obligation -by proving that an appropriate impl does exist. +We use the term *obligation* to refer to a trait reference in need of an impl. +Basically, +the trait resolution system resolves an obligation by proving that an appropriate impl does exist. During type checking, we do not store the results of trait selection. -We simply wish to verify that trait selection will succeed. Then -later, at codegen time, when we have all concrete types available, we -can repeat the trait selection to choose an actual implementation, which -will then be generated in the output binary. +We simply wish to verify that trait selection will succeed. +Then later, at codegen time, when we have all concrete types available, we +can repeat the trait selection to choose an actual implementation, +which will then be generated in the output binary. ## Overview Trait resolution consists of three major parts: -- **Selection**: Deciding how to resolve a specific obligation. For - example, selection might decide that a specific obligation can be +- **Selection**: Deciding how to resolve a specific obligation. + For example, selection might decide that a specific obligation can be resolved by employing an impl which matches the `Self` type, or by using a parameter bound (e.g. `T: Trait`). In the case of an impl, selecting one - obligation can create *nested obligations* because of where clauses - on the impl itself. It may also require evaluating those nested - obligations to resolve ambiguities. + obligation can create *nested obligations* because of where clauses on the impl itself. + It may also require evaluating those nested obligations to resolve ambiguities. -- **Fulfillment**: The fulfillment code is what tracks that obligations - are completely fulfilled. Basically it is a worklist of obligations - to be selected: once selection is successful, the obligation is +- **Fulfillment**: The fulfillment code is what tracks that obligations are completely fulfilled. + Basically it is a worklist of obligations to be selected: once selection is successful, + the obligation is removed from the worklist and any nested obligations are enqueued. Fulfillment constrains inference variables. -- **Evaluation**: Checks whether obligations holds without constraining - any inference variables. Used by selection. +- **Evaluation**: Checks whether obligations holds without constraining any inference variables. + Used by selection. ## Selection -Selection is the process of deciding whether an obligation can be -resolved and, if so, how it is to be resolved (via impl, where clause, etc). -The main interface is the `select()` function, which takes an obligation -and returns a `SelectionResult`. There are three possible outcomes: +Selection is the process of deciding whether an obligation can be resolved and, +if so, how it is to be resolved (via impl, where clause, etc). +The main interface is the `select()` function, +which takes an obligation and returns a `SelectionResult`. +There are three possible outcomes: -- `Ok(Some(selection))` – yes, the obligation can be resolved, and - `selection` indicates how. If the impl was resolved via an impl, - then `selection` may also indicate nested obligations that are required - by the impl. +- `Ok(Some(selection))` – yes, the obligation can be resolved, and `selection` indicates how. + If the impl was resolved via an impl, + then `selection` may also indicate nested obligations that are required by the impl. -- `Ok(None)` – we are not yet sure whether the obligation can be - resolved or not. This happens most commonly when the obligation - contains unbound type variables. +- `Ok(None)` – we are not yet sure whether the obligation can be resolved or not. + This happens most commonly when the obligation contains unbound type variables. - `Err(err)` – the obligation definitely cannot be resolved due to a type error or because there are no impls that could possibly apply. @@ -97,42 +96,42 @@ and returns a `SelectionResult`. There are three possible outcomes: The basic algorithm for selection is broken into two big phases: candidate assembly and confirmation. -Note that because of how lifetime inference works, it is not possible to -give back immediate feedback as to whether a unification or subtype -relationship between lifetimes holds or not. Therefore, lifetime -matching is *not* considered during selection. This is reflected in -the fact that subregion assignment is infallible. This may yield -lifetime constraints that will later be found to be in error (in +Note that because of how lifetime inference works, +it is not possible to give back immediate feedback as to whether a unification or subtype +relationship between lifetimes holds or not. +Therefore, lifetime matching is *not* considered during selection. +This is reflected in the fact that subregion assignment is infallible. +This may yield lifetime constraints that will later be found to be in error (in contrast, the non-lifetime-constraints have already been checked -during selection and can never cause an error, though naturally they -may lead to other errors downstream). +during selection and can never cause an error, +though naturally they may lead to other errors downstream). ### Candidate assembly **TODO**: Talk about _why_ we have different candidates, and why it needs to happen in a probe. -Searches for impls/where-clauses/etc that might -possibly be used to satisfy the obligation. Each of those is called -a candidate. To avoid ambiguity, we want to find exactly one -candidate that is definitively applicable. In some cases, we may not -know whether an impl/where-clause applies or not – this occurs when +Searches for impls/where-clauses/etc that might possibly be used to satisfy the obligation. +Each of those is called a candidate. +To avoid ambiguity, we want to find exactly one candidate that is definitively applicable. +In some cases, we may not know whether an impl/where-clause applies or not – this occurs when the obligation contains unbound inference variables. The subroutines that decide whether a particular impl/where-clause/etc applies to a particular obligation are collectively referred to as the process of _matching_. For `impl` candidates , this amounts to unifying the impl header (the `Self` type and the trait arguments) -while ignoring nested obligations. If matching succeeds then we add it -to a set of candidates. There are other rules when assembling candidates for -built-in traits such as `Copy`, `Sized`, and `CoerceUnsized`. +while ignoring nested obligations. +If matching succeeds then we add it to a set of candidates. +There are other rules when assembling candidates for built-in traits such as `Copy`, +`Sized`, and `CoerceUnsized`. -Once this first pass is done, we can examine the set of candidates. If -it is a singleton set, then we are done: this is the only impl in -scope that could possibly apply. Otherwise, we can **winnow** down the set -of candidates by using where clauses and other conditions. Winnowing uses -`evaluate_candidate` to check whether the nested obligations may apply. -If this still leaves more than 1 candidate, we use ` fn candidate_should_be_dropped_in_favor_of` -to prefer some candidates over others. +Once this first pass is done, we can examine the set of candidates. +If it is a singleton set, then we are done: this is the only impl in +scope that could possibly apply. +Otherwise, we can **winnow** down the set of candidates by using where clauses and other conditions. +Winnowing uses `evaluate_candidate` to check whether the nested obligations may apply. +If this still leaves more than 1 candidate, +we use ` fn candidate_should_be_dropped_in_favor_of` to prefer some candidates over others. If this reduced set yields a single, unambiguous entry, we're good to go, @@ -140,8 +139,8 @@ otherwise the result is considered ambiguous. #### Winnowing: Resolving ambiguities -But what happens if there are multiple impls where all the types -unify? Consider this example: +But what happens if there are multiple impls where all the types unify? +Consider this example: ```rust,ignore trait Get { @@ -161,24 +160,26 @@ impl Get for Box { } ``` -What happens when we invoke `get(&Box::new(1_u16))`, for example? In this -case, the `Self` type is `Box` – that unifies with both impls, -because the first applies to all types `T`, and the second to all -`Box`. In order for this to be unambiguous, the compiler does a *winnowing* -pass that considers `where` clauses -and attempts to remove candidates. In this case, the first impl only -applies if `Box : Copy`, which doesn't hold. After winnowing, +What happens when we invoke `get(&Box::new(1_u16))`, for example? +In this case, the `Self` type is `Box` – that unifies with both impls, +because the first applies to all types `T`, and the second to all `Box`. +In order for this to be unambiguous, +the compiler does a *winnowing* pass that considers `where` clauses +and attempts to remove candidates. +In this case, the first impl only applies if `Box : Copy`, which doesn't hold. +After winnowing, then, we are left with just one candidate, so we can proceed. #### `where` clauses -Besides an impl, the other major way to resolve an obligation is via a -where clause. The selection process is always given a [parameter -environment] which contains a list of where clauses, which are -basically obligations that we can assume are satisfiable. We will iterate -over that list and check whether our current obligation can be found -in that list. If so, it is considered satisfied. More precisely, we -want to check whether there is a where-clause obligation that is for +Besides an impl, the other major way to resolve an obligation is via a where clause. +The selection process is always given a [parameter +environment] which contains a list of where clauses, +which are basically obligations that we can assume are satisfiable. +We will iterate over that list and check whether our current obligation can be found +in that list. +If so, it is considered satisfied. +More precisely, we want to check whether there is a where-clause obligation that is for the same trait (or some subtrait) and which can match against the obligation. [parameter environment]: ../typing-parameter-envs.md @@ -201,12 +202,13 @@ fn foo(x: X) { } ``` -In the body of `foo`, clearly we can use methods of `A1`, `A2`, or `B` -on variable `x`. The line marked `(*)` will incur an obligation `X: A1`, -while the line marked `(#)` will incur an obligation `X: B`. Meanwhile, +In the body of `foo`, clearly we can use methods of `A1`, `A2`, or `B` on variable `x`. +The line marked `(*)` will incur an obligation `X: A1`, +while the line marked `(#)` will incur an obligation `X: B`. +Meanwhile, the parameter environment will contain two where-clauses: `X : A2` and `X : B`. -For each obligation, then, we search this list of where-clauses. The -obligation `X: B` trivially matches against the where-clause `X: B`. +For each obligation, then, we search this list of where-clauses. +The obligation `X: B` trivially matches against the where-clause `X: B`. To resolve an obligation `X:A1`, we would note that `X:A2` implies that `X:A1`. ### Confirmation @@ -214,8 +216,7 @@ To resolve an obligation `X:A1`, we would note that `X:A2` implies that `X:A1`. _Confirmation_ unifies the output type parameters of the trait with the values found in the obligation, possibly yielding a type error. -Suppose we have the following variation of the `Convert` example in the -previous section: +Suppose we have the following variation of the `Convert` example in the previous section: ```rust,ignore trait Convert { @@ -230,24 +231,25 @@ let y: char = x.convert(); // NOTE: `y: char` now! ``` Confirmation is where an error would be reported because the impl specified -that `Target` would be `usize`, but the obligation reported `char`. Hence the -result of selection would be an error. +that `Target` would be `usize`, but the obligation reported `char`. +Hence the result of selection would be an error. -Note that the candidate impl is chosen based on the `Self` type, but -confirmation is done based on (in this case) the `Target` type parameter. +Note that the candidate impl is chosen based on the `Self` type, +but confirmation is done based on (in this case) the `Target` type parameter. ### Selection during codegen -As mentioned above, during type checking, we do not store the results of trait -selection. At codegen time, we repeat the trait selection to choose a particular -impl for each method call. This is done using `fn codegen_select_candidate`. +As mentioned above, during type checking, we do not store the results of trait selection. +At codegen time, we repeat the trait selection to choose a particular impl for each method call. +This is done using `fn codegen_select_candidate`. In this second selection, we do not consider any where-clauses to be in scope because we know that each resolution will resolve to a particular impl. -One interesting twist has to do with nested obligations. In general, in codegen, +One interesting twist has to do with nested obligations. +In general, in codegen, we only need to figure out which candidate applies, and we do not care about nested obligations, -as these are already assumed to be true. Nonetheless, we *do* currently fulfill all of them. +as these are already assumed to be true. +Nonetheless, we *do* currently fulfill all of them. That is because it can sometimes inform the results of type inference. That is, we do not have the full substitutions in terms of the type variables -of the impl available to us, so we must run trait selection to figure -everything out. +of the impl available to us, so we must run trait selection to figure everything out. From b4ac0554a756089bdd54c0ac2d9717ffbc4f7381 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 23:27:59 +0100 Subject: [PATCH 29/32] improve traits/resolution.md --- src/doc/rustc-dev-guide/src/traits/resolution.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/traits/resolution.md b/src/doc/rustc-dev-guide/src/traits/resolution.md index 1ae5bde54d53d..77793bdd3e904 100644 --- a/src/doc/rustc-dev-guide/src/traits/resolution.md +++ b/src/doc/rustc-dev-guide/src/traits/resolution.md @@ -67,9 +67,9 @@ Trait resolution consists of three major parts: It may also require evaluating those nested obligations to resolve ambiguities. - **Fulfillment**: The fulfillment code is what tracks that obligations are completely fulfilled. - Basically it is a worklist of obligations to be selected: once selection is successful, + Basically, it is a worklist of obligations to be selected: once selection is successful, the obligation is - removed from the worklist and any nested obligations are enqueued. + removed from the worklist, and any nested obligations are enqueued. Fulfillment constrains inference variables. - **Evaluation**: Checks whether obligations holds without constraining any inference variables. @@ -120,7 +120,7 @@ The subroutines that decide whether a particular impl/where-clause/etc applies to a particular obligation are collectively referred to as the process of _matching_. For `impl` candidates , this amounts to unifying the impl header (the `Self` type and the trait arguments) -while ignoring nested obligations. +while ignoring nested obligations. If matching succeeds then we add it to a set of candidates. There are other rules when assembling candidates for built-in traits such as `Copy`, `Sized`, and `CoerceUnsized`. From 8abb3a52f58104430048891eecb4fe90b4725d3d Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 23:28:18 +0100 Subject: [PATCH 30/32] reflow src/traits/resolution.md --- .../rustc-dev-guide/src/traits/resolution.md | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/traits/resolution.md b/src/doc/rustc-dev-guide/src/traits/resolution.md index 77793bdd3e904..5d4c8a2b758fe 100644 --- a/src/doc/rustc-dev-guide/src/traits/resolution.md +++ b/src/doc/rustc-dev-guide/src/traits/resolution.md @@ -27,8 +27,7 @@ it is the job of trait resolution to figure out whether there exists an impl of (in this case) `isize : Clone`. Note that in some cases, like generic functions, we may not be able to find a specific impl, -but we can figure out that the caller must -provide an impl. +but we can figure out that the caller must provide an impl. For example, consider the body of `clone_slice`: ```rust,ignore @@ -51,8 +50,8 @@ the trait resolution system resolves an obligation by proving that an appropriat During type checking, we do not store the results of trait selection. We simply wish to verify that trait selection will succeed. -Then later, at codegen time, when we have all concrete types available, we -can repeat the trait selection to choose an actual implementation, +Then later, at codegen time, when we have all concrete types available, +we can repeat the trait selection to choose an actual implementation, which will then be generated in the output binary. ## Overview @@ -68,8 +67,7 @@ Trait resolution consists of three major parts: - **Fulfillment**: The fulfillment code is what tracks that obligations are completely fulfilled. Basically, it is a worklist of obligations to be selected: once selection is successful, - the obligation is - removed from the worklist, and any nested obligations are enqueued. + the obligation is removed from the worklist, and any nested obligations are enqueued. Fulfillment constrains inference variables. - **Evaluation**: Checks whether obligations holds without constraining any inference variables. @@ -101,8 +99,8 @@ it is not possible to give back immediate feedback as to whether a unification o relationship between lifetimes holds or not. Therefore, lifetime matching is *not* considered during selection. This is reflected in the fact that subregion assignment is infallible. -This may yield lifetime constraints that will later be found to be in error (in -contrast, the non-lifetime-constraints have already been checked +This may yield lifetime constraints that will later be found to be in error (in contrast, +the non-lifetime-constraints have already been checked during selection and can never cause an error, though naturally they may lead to other errors downstream). @@ -126,8 +124,8 @@ There are other rules when assembling candidates for built-in traits such as `Co `Sized`, and `CoerceUnsized`. Once this first pass is done, we can examine the set of candidates. -If it is a singleton set, then we are done: this is the only impl in -scope that could possibly apply. +If it is a singleton set, +then we are done: this is the only impl in scope that could possibly apply. Otherwise, we can **winnow** down the set of candidates by using where clauses and other conditions. Winnowing uses `evaluate_candidate` to check whether the nested obligations may apply. If this still leaves more than 1 candidate, @@ -176,8 +174,7 @@ Besides an impl, the other major way to resolve an obligation is via a where cla The selection process is always given a [parameter environment] which contains a list of where clauses, which are basically obligations that we can assume are satisfiable. -We will iterate over that list and check whether our current obligation can be found -in that list. +We will iterate over that list and check whether our current obligation can be found in that list. If so, it is considered satisfied. More precisely, we want to check whether there is a where-clause obligation that is for the same trait (or some subtrait) and which can match against the obligation. From 8dcc6f8d5512654a508d74d8cb734347509c995d Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 23:39:26 +0100 Subject: [PATCH 31/32] reflow src/tests/ci.md --- src/doc/rustc-dev-guide/src/tests/ci.md | 217 ++++++++++++------------ 1 file changed, 108 insertions(+), 109 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/tests/ci.md b/src/doc/rustc-dev-guide/src/tests/ci.md index 7f3c38385ceca..efda4844f4c37 100644 --- a/src/doc/rustc-dev-guide/src/tests/ci.md +++ b/src/doc/rustc-dev-guide/src/tests/ci.md @@ -3,19 +3,19 @@ The primary goal of our CI system is to ensure that the `main` branch of `rust-lang/rust` is always in a valid state by passing our test suite. -From a high-level point of view, when you open a pull request at -`rust-lang/rust`, the following will happen: +From a high-level point of view, when you open a pull request at `rust-lang/rust`, +the following will happen: - A small [subset](#pull-request-builds) of tests and checks are run after each push to the PR. This should help catch common errors. - When the PR is approved, the [bors] bot enqueues the PR into a [merge queue]. -- Once the PR gets to the front of the queue, bors will create a merge commit - and run the [full test suite](#auto-builds) on it. +- Once the PR gets to the front of the queue, + bors will create a merge commit and run the [full test suite](#auto-builds) on it. The merge commit either contains only one specific PR or it can be a ["rollup"](#rollups) which combines multiple PRs together, to reduce CI costs and merge delays. - Once the whole test suite finishes, two things can happen. - Either CI fails with an error that needs to be addressed by the developer, or CI succeeds and - the merge commit is then pushed to the `main` branch. + Either CI fails with an error that needs to be addressed by the developer, + or CI succeeds and the merge commit is then pushed to the `main` branch. If you want to modify what gets executed on CI, see [Modifying CI jobs](#modifying-ci-jobs). @@ -23,13 +23,13 @@ If you want to modify what gets executed on CI, see [Modifying CI jobs](#modifyi -Our CI is primarily executed on [GitHub Actions], with a single workflow defined -in [`.github/workflows/ci.yml`], which contains a bunch of steps that are -unified for all CI jobs that we execute. +Our CI is primarily executed on [GitHub Actions], +with a single workflow defined in [`.github/workflows/ci.yml`], +which contains a bunch of steps that are unified for all CI jobs that we execute. When a commit is pushed to a corresponding branch or a PR, the workflow executes the [`src/ci/citool`] crate, which dynamically generates the specific CI jobs that should be executed. -This script uses the [`jobs.yml`] file as an -input, which contains a declarative configuration of all our CI jobs. +This script uses the [`jobs.yml`] file as an input, +which contains a declarative configuration of all our CI jobs. > Almost all build steps shell out to separate scripts. This keeps the CI fairly > platform independent (i.e., we are not overly reliant on GitHub Actions). @@ -48,14 +48,14 @@ There are two broad categories of jobs that are executed, `dist` and non-`dist` The same builds are also used for actual releases: our release process basically consists of copying those artifacts from `rust-lang-ci2` to the production endpoint and signing them. -- Non-dist jobs run our full test suite on the platform, and the test suite of - all the tools we ship through rustup; +- Non-dist jobs run our full test suite on the platform, + and the test suite of all the tools we ship through rustup; The amount of stuff we test depends on - the platform (for example some tests are run only on Tier 1 platforms), and - some quicker platforms are grouped together on the same builder to avoid wasting CI resources. + the platform (for example some tests are run only on Tier 1 platforms), + and some quicker platforms are grouped together on the same builder to avoid wasting CI resources. -Based on an input event (usually a push to a branch), we execute one of three -kinds of builds (sets of jobs). +Based on an input event (usually a push to a branch), +we execute one of three kinds of builds (sets of jobs). 1. PR builds 2. Auto builds @@ -66,15 +66,15 @@ kinds of builds (sets of jobs). ### Pull Request builds After each push to a pull request, a set of `pr` jobs are executed. -Currently, these execute the `test-x86_64-gnu-llvm-X`, `test-x86_64-gnu-tools`, `test-pr-check-1`, `test-pr-check-2` -and `test-tidy` jobs, all running on Linux. +Currently, these execute the `test-x86_64-gnu-llvm-X`, `test-x86_64-gnu-tools`, `test-pr-check-1`, +`test-pr-check-2` and `test-tidy` jobs, all running on Linux. These execute a relatively short (~40 minutes) and lightweight test suite that should catch common issues. -More specifically, they run a set of lints, they try to perform a cross-compile check -build to Windows mingw (without producing any artifacts), and they test the -compiler using a *system* version of LLVM. -Unfortunately, it would take too many -resources to run the full test suite for each commit on every PR. +More specifically, they run a set of lints, +they try to perform a cross-compile check build to Windows mingw (without producing any artifacts), +and they test the compiler using a *system* version of LLVM. +Unfortunately, +it would take too many resources to run the full test suite for each commit on every PR. > **Note on doc comments** > @@ -87,8 +87,8 @@ resources to run the full test suite for each commit on every PR. > changes to help catch these early. PR jobs are defined in the `pr` section of [`jobs.yml`]. -Their results can be observed -directly on the PR, in the "CI checks" section at the bottom of the PR page. +Their results can be observed directly on the PR, +in the "CI checks" section at the bottom of the PR page. ### Auto builds @@ -110,12 +110,12 @@ At any given time, at most a single `auto` build is being executed. Find out more in [Merging PRs serially with bors](#merging-prs-serially-with-bors). Normally, when an auto job fails, the whole CI workflow immediately ends. -However, it can be useful to -create auto jobs that are "non-blocking", or optional, to test them on CI for some time before blocking -merges on them. +However, it can be useful to create auto jobs that are "non-blocking", +or optional, to test them on CI for some time before blocking merges on them. This can be useful if those jobs can be flaky. -To do that, prefix such a job with `optional-`, and set `continue_on_error: true` for it in [`jobs.yml`]. +To do that, prefix such a job with `optional-`, +and set `continue_on_error: true` for it in [`jobs.yml`]. [platform tiers]: https://forge.rust-lang.org/release/platform-support.html#rust-platform-support [auto]: https://github.com/rust-lang/rust/tree/automation/bors/auto @@ -135,20 +135,20 @@ There are several use-cases for try builds: try build that runs the [dist-x86_64-linux] CI job, which builds an optimized version of the compiler on Linux (this job is currently executed by default when you start a try build). - To create a try build and schedule it for a - performance benchmark, you can use the `@bors try @rust-timer queue` command combination. + To create a try build and schedule it for a performance benchmark, + you can use the `@bors try @rust-timer queue` command combination. - Check the impact of the PR across the Rust ecosystem, using a [Crater](crater.md) run. - Again, a working compiler build is needed for this, which can be produced by - the [dist-x86_64-linux] CI job. + Again, a working compiler build is needed for this, + which can be produced by the [dist-x86_64-linux] CI job. - Run a specific CI job (e.g. Windows tests) on a PR, to quickly test if it passes the test suite executed by that job. -By default, if you send a comment with `@bors try`, the jobs defined in the `try` section of -[`jobs.yml`] will be executed. +By default, if you send a comment with `@bors try`, +the jobs defined in the `try` section of [`jobs.yml`] will be executed. We call this mode a "fast try build". Such a try build will not execute any tests, and it will allow compilation warnings. -It is useful when you want to -get an optimized toolchain as fast as possible, for a Crater run or performance benchmarks, +It is useful when you want to get an optimized toolchain as fast as possible, +for a Crater run or performance benchmarks, even if it might not be working fully correctly. The CI job executed in fast try builds has a special suffix (`-quick`), @@ -157,13 +157,14 @@ If you want to do the full build instead, specify its job name in a job pattern (explained below). If you want to run custom CI jobs in a try build and make sure that they pass all tests and do -not produce any compilation warnings, you can select CI jobs to be executed by specifying a *job pattern*, +not produce any compilation warnings, +you can select CI jobs to be executed by specifying a *job pattern*, which can be used in one of two ways: - You can add a set of `try-job: ` directives to the PR description (described below) and then simply run `@bors try`. CI will read these directives and run the jobs that you have specified. - This is - useful if you want to rerun the same set of try jobs multiple times, after incrementally modifying a PR. + This is useful if you want to rerun the same set of try jobs multiple times, + after incrementally modifying a PR. - You can specify the job pattern using the `jobs` parameter of the try command: `@bors try jobs=`. This is useful for one-off try builds with specific jobs. Note that the `jobs` parameter has a higher priority than the PR description directives. @@ -172,8 +173,8 @@ which can be used in one of two ways: Each job pattern can either be an exact name of a job or a glob pattern that matches multiple jobs, for example `*msvc*` or `*-alt`. You can start at most 20 jobs in a single try build. -When using -glob patterns in the PR description, you can optionally wrap them in backticks (`` ` ``) to avoid GitHub rendering +When using glob patterns in the PR description, +you can optionally wrap them in backticks (`` ` ``) to avoid GitHub rendering the pattern as Markdown if it contains e.g. an asterisk. Note that this escaping will not work when using the `@bors jobs=` parameter. @@ -221,34 +222,34 @@ their results can be seen on [the GitHub Actions workflows page], although usually you will be notified of the result by a comment made by bors on the corresponding PR. -Multiple try builds can execute concurrently across different PRs, but there can be at most -a single try build running on a single PR at any given time. +Multiple try builds can execute concurrently across different PRs, +but there can be at most a single try build running on a single PR at any given time. [rustc-perf]: https://github.com/rust-lang/rustc-perf [try]: https://github.com/rust-lang/rust/tree/automation/bors/try ### Modifying CI jobs -If you want to modify what gets executed on our CI, you can simply modify the -`pr`, `auto` or `try` sections of the [`jobs.yml`] file. +If you want to modify what gets executed on our CI, you can simply modify the `pr`, +`auto` or `try` sections of the [`jobs.yml`] file. -You can also modify what gets executed temporarily, for example to test a -particular platform or configuration that is challenging to test locally (for +You can also modify what gets executed temporarily, +for example to test a particular platform or configuration that is challenging to test locally (for example, if a Windows build fails, but you don't have access to a Windows machine). Don't hesitate to use CI resources in such situations. You can perform an arbitrary CI job in two ways: -- Use the [try build](#try-builds) functionality, and specify the CI jobs that - you want to be executed in try builds in your PR description. +- Use the [try build](#try-builds) functionality, + and specify the CI jobs that you want to be executed in try builds in your PR description. - Modify the [`pr`](#pull-request-builds) section of `jobs.yml` to specify which CI jobs should be executed after each push to your PR. This might be faster than repeatedly starting try builds. -To modify the jobs executed after each push to a PR, you can simply copy one of -the job definitions from the `auto` section to the `pr` section. +To modify the jobs executed after each push to a PR, +you can simply copy one of the job definitions from the `auto` section to the `pr` section. For example, the `x86_64-msvc` job is responsible for running the 64-bit MSVC tests. -You can copy it to the `pr` section to cause it to be executed after a commit is pushed -to your PR, like this: +You can copy it to the `pr` section to cause it to be executed after a commit is pushed to your PR, +like this: ```yaml pr: @@ -276,41 +277,40 @@ A good practice is to prefix `[WIP]` in PR title while still running try jobs and `[DO NOT MERGE]` in the commit that modifies the CI jobs for testing purposes. -Although you are welcome to use CI, just be conscious that this is a shared -resource with limited concurrency. +Although you are welcome to use CI, +just be conscious that this is a shared resource with limited concurrency. Try not to enable too many jobs at once; one or two should be sufficient in most cases. ## Merging PRs serially with bors -CI services usually test the last commit of a branch merged with the last commit -in `main`, and while that’s great to check if the feature works in isolation, +CI services usually test the last commit of a branch merged with the last commit in `main`, +and while that’s great to check if the feature works in isolation, it doesn’t provide any guarantee the code is going to work once it’s merged. -Breakages like these usually happen when another, incompatible PR is merged -after the build happened. +Breakages like these usually happen when another, +incompatible PR is merged after the build happened. To ensure a `main` branch that works all the time, we forbid manual merges. Instead, all PRs have to be approved through our bot, [bors]. All the approved PRs are put in a [merge queue] (sorted by priority and creation date) and are automatically tested one at the time. -If all the builders are green, the PR is merged, otherwise the failure is -recorded and the PR will have to be re-approved again. +If all the builders are green, the PR is merged, +otherwise the failure is recorded and the PR will have to be re-approved again. Bors doesn’t interact with CI services directly, but it works by pushing the merge commit it wants to test to specific branches (like `automation/bors/auto` or `automation/bors/try`), which are configured to execute CI checks. Bors then detects the outcome of the build by listening for either Commit Statuses or Check Runs. -Since the merge commit is -based on the latest `main` and only one can be tested at the same time, when -the results are green, `main` is fast-forwarded to that merge commit. +Since the merge commit is based on the latest `main` and only one can be tested at the same time, +when the results are green, `main` is fast-forwarded to that merge commit. -Unfortunately, testing a single PR at a time, combined with our long CI (~2 -hours for a full run), means we can’t merge a lot of PRs in a single day, and a -single failure greatly impacts our throughput. +Unfortunately, testing a single PR at a time, combined with our long CI (~2 hours for a full run), +means we can’t merge a lot of PRs in a single day, +and a single failure greatly impacts our throughput. The maximum number of PRs we can merge in a day is around ~10. -The long CI run times, and requirement for a large builder pool, is largely due -to the fact that full release artifacts are built in the `dist-` builders. +The long CI run times, and requirement for a large builder pool, +is largely due to the fact that full release artifacts are built in the `dist-` builders. This is worth it because these release artifacts: - Allow perf testing even at a later date. @@ -320,18 +320,18 @@ This is worth it because these release artifacts: ### Rollups Some PRs don’t need the full test suite to be executed: trivial changes like -typo fixes or README improvements *shouldn’t* break the build, and testing every -single one of them for 2+ hours would be wasteful. -To solve this, we regularly create a "rollup", a PR where we merge several pending trivial PRs so -they can be tested together. +typo fixes or README improvements *shouldn’t* break the build, +and testing every single one of them for 2+ hours would be wasteful. +To solve this, we regularly create a "rollup", +a PR where we merge several pending trivial PRs so they can be tested together. Rollups are created manually by a team member using the "create a rollup" button on the [merge queue]. The team member uses their judgment to decide if a PR is risky or not. ## Docker -All CI jobs, except those on macOS and Windows, are executed inside that -platform’s custom [Docker container]. +All CI jobs, except those on macOS and Windows, +are executed inside that platform’s custom [Docker container]. This has a lot of advantages for us: - The build environment is consistent regardless of the changes of the @@ -352,8 +352,8 @@ The Docker images prefixed with `dist-` are used for building artifacts while those without that prefix run tests and checks. We also run tests for less common architectures (mainly Tier 2 and Tier 3 platforms) in CI. -Since those platforms are not x86, we either run everything -inside QEMU, or we just cross-compile if we don’t want to run the tests for that platform. +Since those platforms are not x86, we either run everything inside QEMU, +or we just cross-compile if we don’t want to run the tests for that platform. These builders are running on a special pool of builders set up and maintained for us by GitHub. @@ -366,20 +366,20 @@ Our CI workflow uses various caching mechanisms, mainly for two things: ### Docker images caching The Docker images we use to run most of the Linux-based builders take a *long* time to fully build. -To speed up the build, we cache them using [Docker registry -caching], with the intermediate artifacts being stored on [ghcr.io]. +To speed up the build, we cache them using [Docker registry caching], +with the intermediate artifacts being stored on [ghcr.io]. We also push the built Docker images to ghcr, so that they can be reused by other tools (rustup) or by developers running the Docker build locally (to speed up their build). -Since we test multiple, diverged branches (`main`, `beta` and `stable`), we -can’t rely on a single cache for the images, otherwise builds on a branch would -override the cache for the others. -Instead, we store the images under different -tags, identifying them with a custom hash made from the contents of all the +Since we test multiple, diverged branches (`main`, `beta` and `stable`), +we can’t rely on a single cache for the images, +otherwise builds on a branch would override the cache for the others. +Instead, we store the images under different tags, +identifying them with a custom hash made from the contents of all the Dockerfiles and related scripts. -The CI calculates a hash key, so that the cache of a Docker image is -invalidated if one of the following changes: +The CI calculates a hash key, +so that the cache of a Docker image is invalidated if one of the following changes: - Dockerfile - Files copied into the Docker image in the Dockerfile @@ -390,10 +390,10 @@ invalidated if one of the following changes: ### LLVM caching with Sccache -We build some C/C++ stuff in various CI jobs, and we rely on [Sccache] to cache -the intermediate LLVM artifacts. -Sccache is a distributed ccache developed by -Mozilla, which can use an object storage bucket as the storage backend. +We build some C/C++ stuff in various CI jobs, +and we rely on [Sccache] to cache the intermediate LLVM artifacts. +Sccache is a distributed ccache developed by Mozilla, +which can use an object storage bucket as the storage backend. With Sccache there's no need to calculate the hash key ourselves. Sccache invalidates the cache automatically when it detects changes to relevant inputs, @@ -402,8 +402,8 @@ So we just pass the Sccache wrapper on top of Cargo and Sccache does the rest. We store the persistent artifacts on the S3 bucket, `rust-lang-ci-sccache2`. So when the CI runs, if Sccache sees that LLVM is being compiled with the same C/C++ -compiler and the LLVM source code is the same, Sccache retrieves the individual -compiled translation units from S3. +compiler and the LLVM source code is the same, +Sccache retrieves the individual compiled translation units from S3. [sccache]: https://github.com/mozilla/sccache @@ -413,8 +413,8 @@ During the years, we developed some custom tooling to improve our CI experience. ### Rust Log Analyzer to show the error message in PRs -The build logs for `rust-lang/rust` are huge, and it’s not practical to find -what caused the build to fail by looking at the logs. +The build logs for `rust-lang/rust` are huge, +and it’s not practical to find what caused the build to fail by looking at the logs. We therefore developed a bot called [Rust Log Analyzer][rla] (RLA) that receives the build logs on failure, and extracts the error message automatically, posting it on the PR thread. @@ -428,26 +428,25 @@ good at identifying the relevant lines, even if it’s an error we've never seen ### Toolstate to support allowed failures -The `rust-lang/rust` repo doesn’t only test the compiler on its CI, but also a -variety of tools and documentation. +The `rust-lang/rust` repo doesn’t only test the compiler on its CI, +but also a variety of tools and documentation. Some documentation is pulled in via git submodules. If we blocked merging rustc PRs on the documentation being fixed, we would be stuck in a chicken-and-egg problem, because the documentation's CI would not pass since updating it would need the not-yet-merged version of rustc to test against (and we usually require CI to be passing). -To avoid the problem, submodules are allowed to fail, and their status is -recorded in [rust-toolstate]. -When a submodule breaks, a bot automatically pings -the maintainers so they know about the breakage, and it records the failure on -the toolstate repository. -The release process will then ignore broken tools on -nightly, removing them from the shipped nightlies. +To avoid the problem, submodules are allowed to fail, +and their status is recorded in [rust-toolstate]. +When a submodule breaks, a bot automatically pings the maintainers so they know about the breakage, +and it records the failure on the toolstate repository. +The release process will then ignore broken tools on nightly, +removing them from the shipped nightlies. While tool failures are allowed most of the time, they’re automatically forbidden a week before a release: we don’t care if tools are broken on nightly -but they must work on beta and stable, so they also need to work on nightly a -few days before we promote nightly to beta. +but they must work on beta and stable, +so they also need to work on nightly a few days before we promote nightly to beta. More information is available in the [toolstate documentation]. @@ -473,8 +472,8 @@ To learn more about the dashboard, see the [Datadog CI docs]. ## Determining the CI configuration -If you want to determine which `bootstrap.toml` settings are used in CI for a -particular job, it is probably easiest to just look at the build log. +If you want to determine which `bootstrap.toml` settings are used in CI for a particular job, +it is probably easiest to just look at the build log. To do this: 1. Go to [the Rust CI successful workflow runs page][workflow runs] From ed64975edf18fc9409ae77e7692a81855eedccfc Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 31 Oct 2026 23:50:16 +0100 Subject: [PATCH 32/32] improve tests/ci.md --- src/doc/rustc-dev-guide/src/tests/ci.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/tests/ci.md b/src/doc/rustc-dev-guide/src/tests/ci.md index efda4844f4c37..68e35287dac4a 100644 --- a/src/doc/rustc-dev-guide/src/tests/ci.md +++ b/src/doc/rustc-dev-guide/src/tests/ci.md @@ -78,10 +78,10 @@ it would take too many resources to run the full test suite for each commit on e > **Note on doc comments** > -> Note that PR CI as of Oct 2024 by default does not try to -> run `./x doc xxx`. This means that if you have any broken intradoc links that -> would lead to `./x doc xxx` failing, it will happen very late into the full -> merge queue CI pipeline. +> Note that PR CI as of Oct 2024 by default does not try to run `./x doc xxx`. +> This means that if you have any broken intradoc links that +> would lead to `./x doc xxx` failing, +> it will happen very late into the full merge queue CI pipeline. > > Thus, it is a good idea to run `./x doc xxx` locally for any doc comment > changes to help catch these early. @@ -175,8 +175,8 @@ for example `*msvc*` or `*-alt`. You can start at most 20 jobs in a single try build. When using glob patterns in the PR description, you can optionally wrap them in backticks (`` ` ``) to avoid GitHub rendering -the pattern as Markdown if it contains e.g. an asterisk. Note that this escaping will not work when using -the `@bors jobs=` parameter. +the pattern as Markdown if it contains e.g. an asterisk. +Note that this escaping will not work when using the `@bors jobs=` parameter. The job pattern needs to match one or more jobs defined in the `auto` or `optional` sections of [`jobs.yml`]: @@ -371,7 +371,7 @@ with the intermediate artifacts being stored on [ghcr.io]. We also push the built Docker images to ghcr, so that they can be reused by other tools (rustup) or by developers running the Docker build locally (to speed up their build). -Since we test multiple, diverged branches (`main`, `beta` and `stable`), +Since we test multiple, diverged branches (`main`, `beta`, and `stable`), we can’t rely on a single cache for the images, otherwise builds on a branch would override the cache for the others. Instead, we store the images under different tags,