From 70f1868fad9f52bcec78167ce54eee9412e0f487 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 11 Nov 2026 10:06:59 +0100 Subject: [PATCH 01/43] Add CI workflow to publish backtrace after a push to main --- .github/workflows/post-merge.yml | 48 +++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.yml index 7200aa22a4162..066334199d774 100644 --- a/.github/workflows/post-merge.yml +++ b/.github/workflows/post-merge.yml @@ -1,7 +1,10 @@ -# Workflow that runs after a merge to the default branch, analyses changes in test executions -# and posts the result to the merged PR. +# Workflow that runs after a merge to the default branch. +# It performs two things: +# 1) Analyses changes in test executions and posts the result to the merged PR. +# 2) Performs a cargo publish on crates published from the `rust-lang/rust` repository, and if a +# publish happened, post the result to the merged PR. -name: Post merge analysis +name: Post merge workflow on: push: @@ -13,7 +16,7 @@ jobs: runs-on: ubuntu-26.04 if: github.repository == 'rust-lang/rust' permissions: - pull-requests: write + pull-requests: write # For sending a PR comment steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -21,6 +24,7 @@ jobs: # Since all merges should be through merge commits, fetching two commits # should be enough to get the parent bors merge commit. fetch-depth: 2 + persist-credentials: false - name: Perform analysis and send PR env: GH_TOKEN: ${{ github.token }} @@ -51,3 +55,39 @@ jobs: cat output.log gh pr comment ${HEAD_PR} -F output.log + publish: + runs-on: ubuntu-26.04 + if: github.repository == 'rust-lang/rust' + environment: publish-crates-io + permissions: + id-token: write # For OIDC crates.io publishing + pull-requests: write # For sending a PR comment + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 + id: auth + - run: | + git submodule update --init library/backtrace + cd library/backtrace + + if cargo publish; then + # Find PR for the current commit + HEAD_PR=`gh pr list --search "${{ github.sha }}" --state merged --json number --jq '.[0].number'` + if [ -z "${HEAD_PR}" ]; then + echo "PR for commit SHA ${{ github.sha }} not found, exiting" + exit 1 + fi + echo "HEAD: ${{ github.sha }} (#${HEAD_PR})" + + VERSION=`cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "backtrace") | .version'` + + echo "backtrace \`${VERSION}\` published to crates.io" > output.log + + gh pr comment ${HEAD_PR} -F output.log + else + echo "Nothing to publish" + fi + env: + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} From a3d000e7958c7ea34342eb25eb8a4b841262aa3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 11 Nov 2026 10:24:13 +0100 Subject: [PATCH 02/43] Harden bash code --- .github/workflows/post-merge.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.yml index 066334199d774..989c608bbd32e 100644 --- a/.github/workflows/post-merge.yml +++ b/.github/workflows/post-merge.yml @@ -69,6 +69,8 @@ jobs: - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 id: auth - run: | + set -eux + git submodule update --init library/backtrace cd library/backtrace From a81886cd5e772746247b71c1d6d8949df243d374 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 11 Nov 2026 13:32:22 +0100 Subject: [PATCH 03/43] Set environment variables for the `gh` command --- .github/workflows/post-merge.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.yml index 989c608bbd32e..e4736669df7e9 100644 --- a/.github/workflows/post-merge.yml +++ b/.github/workflows/post-merge.yml @@ -89,7 +89,11 @@ jobs: gh pr comment ${HEAD_PR} -F output.log else - echo "Nothing to publish" + echo "Nothing was published. Either there is no version update or some error has occurred." fi env: CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + # Running `gh` commands in a submodule would cause it to load data from the submodule's + # repo. So we override it here to `rust-lang/rust`. + GH_REPO: ${{ github.repository }} + GH_TOKEN: ${{ github.token }} From e451490bc1b271243dc559431c740886951a92bf Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Thu, 12 Nov 2026 17:50:55 +0000 Subject: [PATCH 04/43] Report a recursion limit error instead of delaying a bug in RPITIT collector --- .../src/check/compare_impl_item/refine.rs | 5 ++++- .../in-trait/refine-self-referential-rtn.rs | 1 + .../in-trait/refine-self-referential-rtn.stderr | 14 +++++++++++--- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs index 969a6ae8c3079..49bc252fda8f0 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs @@ -14,6 +14,7 @@ use rustc_middle::ty::{ }; use rustc_span::def_id::ModId; use rustc_span::{Span, span_bug}; +use rustc_trait_selection::error_reporting::traits::suggest_new_overflow_limit; use rustc_trait_selection::regions::InferCtxtRegionExt; use rustc_trait_selection::traits::{ObligationCtxt, elaborate, normalize_param_env_or_error}; @@ -283,10 +284,12 @@ impl<'tcx> TypeVisitor> for ImplTraitInTraitCollector<'tcx> { && self.tcx.is_impl_trait_in_trait(proj.kind) { if !self.tcx.recursion_limit().value_within_limit(self.depth) { - self.tcx.dcx().span_delayed_bug( + let mut err = self.tcx.dcx().struct_span_err( self.tcx.def_span(proj.kind), "recursion limit exceeded while collecting implied RPITIT bounds", ); + suggest_new_overflow_limit(self.tcx, &mut err); + err.emit(); return ControlFlow::Break(()); } if self.types.insert(proj) { diff --git a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.rs b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.rs index 0936f6e33635f..b52e3b8117292 100644 --- a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.rs +++ b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.rs @@ -2,6 +2,7 @@ trait IntFactory { fn stream(&self) -> impl IntFactory; + //~^ ERROR recursion limit exceeded while collecting implied RPITIT bounds } struct S; diff --git a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.stderr b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.stderr index 35c9cfd19408c..3c9896877468b 100644 --- a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.stderr +++ b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.stderr @@ -1,5 +1,5 @@ error[E0277]: the trait bound `!: IntFactory` is not satisfied - --> $DIR/refine-self-referential-rtn.rs:10:25 + --> $DIR/refine-self-referential-rtn.rs:11:25 | LL | fn stream(&self) -> impl IntFactory { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `IntFactory` is not implemented for `!` @@ -8,7 +8,7 @@ LL | todo!() | ------- return type was inferred to be `!` here | help: the trait `IntFactory` is implemented for `S` - --> $DIR/refine-self-referential-rtn.rs:9:1 + --> $DIR/refine-self-referential-rtn.rs:10:1 | LL | impl IntFactory for S { | ^^^^^^^^^^^^^^^^^^^^^ @@ -17,6 +17,14 @@ help: `!` can be coerced to any type; consider casting it to a concrete type tha LL | todo!() as /* Type */ | +++++++++++++ -error: aborting due to 1 previous error +error: recursion limit exceeded while collecting implied RPITIT bounds + --> $DIR/refine-self-referential-rtn.rs:4:25 + | +LL | fn stream(&self) -> impl IntFactory; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`refine_self_referential_rtn`) + +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. From 7674cdac36a658eaf7c6dc2c199440c4591f9377 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Thu, 12 Nov 2026 17:50:55 +0000 Subject: [PATCH 05/43] Add test for self-referential RTN impl returning a concrete type --- .../refine-self-referential-rtn-self-ty.rs | 14 ++++++++++++++ .../refine-self-referential-rtn-self-ty.stderr | 10 ++++++++++ 2 files changed, 24 insertions(+) create mode 100644 tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.rs create mode 100644 tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.stderr diff --git a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.rs b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.rs new file mode 100644 index 0000000000000..72f96dc845f70 --- /dev/null +++ b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.rs @@ -0,0 +1,14 @@ +#![feature(return_type_notation)] + +trait IntFactory { + fn stream(&self) -> impl IntFactory; + //~^ ERROR recursion limit exceeded while collecting implied RPITIT bounds +} + +impl IntFactory for u32 { + fn stream(&self) -> Self { + todo!() + } +} + +fn main() {} diff --git a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.stderr b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.stderr new file mode 100644 index 0000000000000..a7aab3cee692b --- /dev/null +++ b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.stderr @@ -0,0 +1,10 @@ +error: recursion limit exceeded while collecting implied RPITIT bounds + --> $DIR/refine-self-referential-rtn-self-ty.rs:4:25 + | +LL | fn stream(&self) -> impl IntFactory; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`refine_self_referential_rtn_self_ty`) + +error: aborting due to 1 previous error + From 720dcc62b134cf49c33dde824ab1901eb37653e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Fri, 13 Nov 2026 12:32:48 +0100 Subject: [PATCH 06/43] Check if crate version alraedy exists on crates.io --- .github/workflows/post-merge.yml | 53 ++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.yml index e4736669df7e9..dfea8b5fe49b4 100644 --- a/.github/workflows/post-merge.yml +++ b/.github/workflows/post-merge.yml @@ -69,31 +69,52 @@ jobs: - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 id: auth - run: | - set -eux + set -eux -o pipefail + + # Give GitHub some time to propagate the information that the PR was merged + sleep 60 + + # Find PR for the current commit + HEAD_PR=$(gh pr list --search "${GITHUB_SHA}" --state merged --json number --jq '.[0].number') + if [ -z "${HEAD_PR}" ]; then + echo "PR for commit SHA ${GITHUB_SHA} not found, exiting" + exit 1 + fi + echo "HEAD: ${GITHUB_SHA} (#${HEAD_PR})" git submodule update --init library/backtrace cd library/backtrace - if cargo publish; then - # Find PR for the current commit - HEAD_PR=`gh pr list --search "${{ github.sha }}" --state merged --json number --jq '.[0].number'` - if [ -z "${HEAD_PR}" ]; then - echo "PR for commit SHA ${{ github.sha }} not found, exiting" - exit 1 - fi - echo "HEAD: ${{ github.sha }} (#${HEAD_PR})" + VERSION=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "backtrace") | .version') + CRATE=backtrace - VERSION=`cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "backtrace") | .version'` + # Check if the version exists on crates.io already with a HEAD request to the CDN + code=$(curl --head --silent -o /dev/null --write-out '%{http_code}' "https://static.crates.io/crates/${CRATE}/${CRATE}-${VERSION}.crate") - echo "backtrace \`${VERSION}\` published to crates.io" > output.log + # If the crate version already exists, then there is nothing left to do + if [[ $code == 200 ]]; then + exit 0 + fi - gh pr comment ${HEAD_PR} -F output.log + set +e + cargo publish --locked &> ${RUNNER_TEMP}/cargo-log.txt + STATUS=$? + set -e + + if [[ ${STATUS} == 0 ]]; then + echo "backtrace \`${VERSION}\` published to crates.io" > comment.txt else - echo "Nothing was published. Either there is no version update or some error has occurred." + echo "backtrace \`${VERSION}\` could not be published to crates.io" > comment.txt + printf "
\nCargo publish log\n\n" >> comment.txt + printf '```\n' >> comment.txt + cat "${RUNNER_TEMP}/cargo-log.txt" >> comment.txt + printf '\n```\n' >> comment.txt + printf "
\n\n" >> comment.txt fi + + gh pr comment "${HEAD_PR}" -F comment.txt + exit "${STATUS}" env: CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} - # Running `gh` commands in a submodule would cause it to load data from the submodule's - # repo. So we override it here to `rust-lang/rust`. - GH_REPO: ${{ github.repository }} GH_TOKEN: ${{ github.token }} + GITHUB_SHA: ${{ github.sha }} From 9fe76f21ffa3b2b152f22bbae612ee1bf4ee1475 Mon Sep 17 00:00:00 2001 From: panstromek Date: Fri, 13 Nov 2026 20:01:49 +0100 Subject: [PATCH 07/43] Avoid using Terminator:None in simplify_cfg We replace it with dummy terminator value, which is the simplest solution for now. --- compiler/rustc_mir_transform/src/simplify.rs | 33 +++++++++++++++----- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_mir_transform/src/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs index c0281871f2a73..bd2f82ae0d267 100644 --- a/compiler/rustc_mir_transform/src/simplify.rs +++ b/compiler/rustc_mir_transform/src/simplify.rs @@ -35,6 +35,7 @@ //! pre-"runtime" MIR! use itertools::Itertools as _; +use rustc_data_structures::thin_vec::ThinVec; use rustc_index::bit_set::DenseBitSet; use rustc_index::{Idx, IndexSlice, IndexVec}; use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor}; @@ -158,8 +159,7 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { debug!("simplifying {:?}", bb); - let mut terminator = - self.basic_blocks[bb].terminator.take().expect("invalid terminator state"); + let mut terminator = self.take_terminator(bb).expect("invalid terminator state"); terminator.successors_mut(|successor| { self.collapse_goto_chain(successor, &mut changed); @@ -207,6 +207,18 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { outer_changed } + /// Replaces the terminator of a basic block with a dummy value. + fn take_terminator(&mut self, bb: BasicBlock) -> Option> { + if has_dummy_terminator(&self.basic_blocks[bb]) { + return None; + } + let dummy_terminator = Terminator { + source_info: SourceInfo { span: DUMMY_SP, scope: SourceScope::ZERO }, + kind: TerminatorKind::Goto { target: BasicBlock::MAX, loop_hint_attrs: ThinVec::new() }, + }; + std::mem::replace(&mut self.basic_blocks[bb].terminator, Some(dummy_terminator)) + } + /// This function will return `None` if /// * the block has statements /// * the block has a terminator other than `goto` @@ -218,7 +230,7 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { terminator: ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }), .. - } if statements.is_empty() => terminator.take(), + } if statements.is_empty() => self.take_terminator(bb), // if `terminator` is None, this means we are in a loop. In that // case, let all the loop collapse to its entry. _ => None, @@ -289,7 +301,7 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { }; debug!("merging block {:?} into {:?}", target, terminator); - *terminator = match self.basic_blocks[target].terminator.take() { + *terminator = match self.take_terminator(target) { Some(terminator) => terminator, None => { // unreachable loop - this should not be possible, as we @@ -350,12 +362,12 @@ pub(super) fn simplify_duplicate_switch_targets(terminator: &mut Terminator<'_>) pub(super) fn remove_dead_blocks(body: &mut Body<'_>) { let should_deduplicate_unreachable = |bbdata: &BasicBlockData<'_>| { - // CfgSimplifier::simplify leaves behind some unreachable basic blocks without a - // terminator. Those blocks will be deleted by remove_dead_blocks, but we run just + // CfgSimplifier::simplify leaves behind some unreachable basic blocks with + // dummy terminator. Those blocks will be deleted by remove_dead_blocks, but we run just // before then so we need to handle missing terminators. // We also need to prevent confusing cleanup and non-cleanup blocks. In practice we // don't emit empty unreachable cleanup blocks, so this simple check suffices. - bbdata.terminator.is_some() && bbdata.is_empty_unreachable() && !bbdata.is_cleanup + !has_dummy_terminator(bbdata) && bbdata.is_empty_unreachable() && !bbdata.is_cleanup }; let reachable = traversal::reachable_as_bitset(body); @@ -414,6 +426,13 @@ pub(super) fn remove_dead_blocks(body: &mut Body<'_>) { } } +fn has_dummy_terminator(bbdata: &BasicBlockData<'_>) -> bool { + match bbdata.terminator().kind { + TerminatorKind::Goto { target, .. } => target == BasicBlock::MAX, + _ => false, + } +} + pub(super) enum SimplifyLocals { BeforeConstProp, AfterGVN, From 001c3f571667204a92eb2ee1e57945869e78d08a Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 6 Nov 2026 22:03:30 +0100 Subject: [PATCH 08/43] view-types: add test for view type unsizedness --- tests/ui/view-types/unsized.rs | 34 +++++++++++ tests/ui/view-types/unsized.stderr | 93 ++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 tests/ui/view-types/unsized.rs create mode 100644 tests/ui/view-types/unsized.stderr diff --git a/tests/ui/view-types/unsized.rs b/tests/ui/view-types/unsized.rs new file mode 100644 index 0000000000000..74c1817d9754e --- /dev/null +++ b/tests/ui/view-types/unsized.rs @@ -0,0 +1,34 @@ +#![feature(view_types, sized_hierarchy)] + +use std::marker::{MetaSized, PointeeSized, Sized}; +use std::view::view_type; + +struct A { + b: (), + c: (), +} + +fn assert_sized() {} +fn assert_metasized() {} +fn assert_pointeesized() {} + +fn main() { + assert_sized::(); + //~^ ERROR the size for values of type `view_type!(A.{ () })` cannot be known at compilation time + assert_metasized::(); + //~^ ERROR the size for values of type `view_type!(A.{ () })` cannot be known + assert_pointeesized::(); + + // View types stay unsized even if they borrow some/all the fields. + assert_sized::(); + //~^ ERROR the size for values of type `view_type!(A.{ (field_of!(A, b),) })` cannot be known at compilation time + assert_metasized::(); + //~^ ERROR the size for values of type `view_type!(A.{ (field_of!(A, b),) })` cannot be known + assert_pointeesized::(); + + assert_sized::(); + //~^ ERROR the size for values of type `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` cannot be known at compilation time + assert_metasized::(); + //~^ ERROR the size for values of type `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` cannot be known + assert_pointeesized::(); +} diff --git a/tests/ui/view-types/unsized.stderr b/tests/ui/view-types/unsized.stderr new file mode 100644 index 0000000000000..58566753c749a --- /dev/null +++ b/tests/ui/view-types/unsized.stderr @@ -0,0 +1,93 @@ +error[E0277]: the size for values of type `view_type!(A.{ () })` cannot be known at compilation time + --> $DIR/unsized.rs:16:20 + | +LL | assert_sized::(); + | ^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `view_type!(A.{ () })` +note: required by an implicit `Sized` bound in `assert_sized` + --> $DIR/unsized.rs:11:17 + | +LL | fn assert_sized() {} + | ^ required by the implicit `Sized` requirement on this type parameter in `assert_sized` +help: consider relaxing the implicit `Sized` restriction + | +LL | fn assert_sized() {} + | ++++++++ + +error[E0277]: the size for values of type `view_type!(A.{ () })` cannot be known + --> $DIR/unsized.rs:18:24 + | +LL | assert_metasized::(); + | ^^^^^^^^^^^^^^^^ doesn't have a known size + | + = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ () })` +note: required by a bound in `assert_metasized` + --> $DIR/unsized.rs:12:24 + | +LL | fn assert_metasized() {} + | ^^^^^^^^^ required by this bound in `assert_metasized` + +error[E0277]: the size for values of type `view_type!(A.{ (field_of!(A, b),) })` cannot be known at compilation time + --> $DIR/unsized.rs:23:20 + | +LL | assert_sized::(); + | ^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `view_type!(A.{ (field_of!(A, b),) })` +note: required by an implicit `Sized` bound in `assert_sized` + --> $DIR/unsized.rs:11:17 + | +LL | fn assert_sized() {} + | ^ required by the implicit `Sized` requirement on this type parameter in `assert_sized` +help: consider relaxing the implicit `Sized` restriction + | +LL | fn assert_sized() {} + | ++++++++ + +error[E0277]: the size for values of type `view_type!(A.{ (field_of!(A, b),) })` cannot be known + --> $DIR/unsized.rs:25:24 + | +LL | assert_metasized::(); + | ^^^^^^^^^^^^^^^^^^^ doesn't have a known size + | + = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ (field_of!(A, b),) })` +note: required by a bound in `assert_metasized` + --> $DIR/unsized.rs:12:24 + | +LL | fn assert_metasized() {} + | ^^^^^^^^^ required by this bound in `assert_metasized` + +error[E0277]: the size for values of type `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` cannot be known at compilation time + --> $DIR/unsized.rs:29:20 + | +LL | assert_sized::(); + | ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` +note: required by an implicit `Sized` bound in `assert_sized` + --> $DIR/unsized.rs:11:17 + | +LL | fn assert_sized() {} + | ^ required by the implicit `Sized` requirement on this type parameter in `assert_sized` +help: consider relaxing the implicit `Sized` restriction + | +LL | fn assert_sized() {} + | ++++++++ + +error[E0277]: the size for values of type `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` cannot be known + --> $DIR/unsized.rs:31:24 + | +LL | assert_metasized::(); + | ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a known size + | + = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` +note: required by a bound in `assert_metasized` + --> $DIR/unsized.rs:12:24 + | +LL | fn assert_metasized() {} + | ^^^^^^^^^ required by this bound in `assert_metasized` + +error: aborting due to 6 previous errors + +For more information about this error, try `rustc --explain E0277`. From 35a34741a1a2f14b4bc1b0fac93088dc1467e1c5 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Mon, 9 Nov 2026 12:19:59 +0100 Subject: [PATCH 09/43] view-types: fix view type pretty printing --- compiler/rustc_middle/src/ty/print/pretty.rs | 37 ++++++++++++++++++-- tests/ui/view-types/unsized.rs | 12 +++---- tests/ui/view-types/unsized.stderr | 24 ++++++------- 3 files changed, 52 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 354140a794615..e24699a955207 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1038,9 +1038,40 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::View(def, args, fields) => { write!(self, "view_type!(")?; self.print_def_path(def.did(), args)?; - write!(self, ".{{ ")?; - self.print_type(fields)?; - write!(self, " }})")?; + write!(self, ".{{")?; + match fields.kind() { + ty::Tuple(fields) => { + let mut first = true; + if !fields.is_empty() { + write!(self, " ")?; + } + for field in fields.iter() { + if first { + first = false; + } else { + write!(self, ", ")?; + } + + match field.kind() { + ty::Adt(def_, args_) + if let Some(FieldInfo { variant, name, .. }) = + def_.field_representing_type_info(self.tcx(), *args_) => + { + // sanity check: view types on enums are not a thing. + debug_assert!(variant.is_none()); + write!(self, "{name}")?; + } + _ => self.print_type(field)?, + } + } + if !fields.is_empty() { + write!(self, " ")?; + } + } + + _ => self.print_type(fields)?, + } + write!(self, "}})")?; } } diff --git a/tests/ui/view-types/unsized.rs b/tests/ui/view-types/unsized.rs index 74c1817d9754e..a607ec0fdab85 100644 --- a/tests/ui/view-types/unsized.rs +++ b/tests/ui/view-types/unsized.rs @@ -14,21 +14,21 @@ fn assert_pointeesized() {} fn main() { assert_sized::(); - //~^ ERROR the size for values of type `view_type!(A.{ () })` cannot be known at compilation time + //~^ ERROR the size for values of type `view_type!(A.{})` cannot be known at compilation time assert_metasized::(); - //~^ ERROR the size for values of type `view_type!(A.{ () })` cannot be known + //~^ ERROR the size for values of type `view_type!(A.{})` cannot be known assert_pointeesized::(); // View types stay unsized even if they borrow some/all the fields. assert_sized::(); - //~^ ERROR the size for values of type `view_type!(A.{ (field_of!(A, b),) })` cannot be known at compilation time + //~^ ERROR the size for values of type `view_type!(A.{ b })` cannot be known at compilation time assert_metasized::(); - //~^ ERROR the size for values of type `view_type!(A.{ (field_of!(A, b),) })` cannot be known + //~^ ERROR the size for values of type `view_type!(A.{ b })` cannot be known assert_pointeesized::(); assert_sized::(); - //~^ ERROR the size for values of type `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` cannot be known at compilation time + //~^ ERROR the size for values of type `view_type!(A.{ b, c })` cannot be known at compilation time assert_metasized::(); - //~^ ERROR the size for values of type `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` cannot be known + //~^ ERROR the size for values of type `view_type!(A.{ b, c })` cannot be known assert_pointeesized::(); } diff --git a/tests/ui/view-types/unsized.stderr b/tests/ui/view-types/unsized.stderr index 58566753c749a..7ce70c5ca198f 100644 --- a/tests/ui/view-types/unsized.stderr +++ b/tests/ui/view-types/unsized.stderr @@ -1,10 +1,10 @@ -error[E0277]: the size for values of type `view_type!(A.{ () })` cannot be known at compilation time +error[E0277]: the size for values of type `view_type!(A.{})` cannot be known at compilation time --> $DIR/unsized.rs:16:20 | LL | assert_sized::(); | ^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: the trait `Sized` is not implemented for `view_type!(A.{ () })` + = help: the trait `Sized` is not implemented for `view_type!(A.{})` note: required by an implicit `Sized` bound in `assert_sized` --> $DIR/unsized.rs:11:17 | @@ -15,26 +15,26 @@ help: consider relaxing the implicit `Sized` restriction LL | fn assert_sized() {} | ++++++++ -error[E0277]: the size for values of type `view_type!(A.{ () })` cannot be known +error[E0277]: the size for values of type `view_type!(A.{})` cannot be known --> $DIR/unsized.rs:18:24 | LL | assert_metasized::(); | ^^^^^^^^^^^^^^^^ doesn't have a known size | - = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ () })` + = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{})` note: required by a bound in `assert_metasized` --> $DIR/unsized.rs:12:24 | LL | fn assert_metasized() {} | ^^^^^^^^^ required by this bound in `assert_metasized` -error[E0277]: the size for values of type `view_type!(A.{ (field_of!(A, b),) })` cannot be known at compilation time +error[E0277]: the size for values of type `view_type!(A.{ b })` cannot be known at compilation time --> $DIR/unsized.rs:23:20 | LL | assert_sized::(); | ^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: the trait `Sized` is not implemented for `view_type!(A.{ (field_of!(A, b),) })` + = help: the trait `Sized` is not implemented for `view_type!(A.{ b })` note: required by an implicit `Sized` bound in `assert_sized` --> $DIR/unsized.rs:11:17 | @@ -45,26 +45,26 @@ help: consider relaxing the implicit `Sized` restriction LL | fn assert_sized() {} | ++++++++ -error[E0277]: the size for values of type `view_type!(A.{ (field_of!(A, b),) })` cannot be known +error[E0277]: the size for values of type `view_type!(A.{ b })` cannot be known --> $DIR/unsized.rs:25:24 | LL | assert_metasized::(); | ^^^^^^^^^^^^^^^^^^^ doesn't have a known size | - = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ (field_of!(A, b),) })` + = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ b })` note: required by a bound in `assert_metasized` --> $DIR/unsized.rs:12:24 | LL | fn assert_metasized() {} | ^^^^^^^^^ required by this bound in `assert_metasized` -error[E0277]: the size for values of type `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` cannot be known at compilation time +error[E0277]: the size for values of type `view_type!(A.{ b, c })` cannot be known at compilation time --> $DIR/unsized.rs:29:20 | LL | assert_sized::(); | ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: the trait `Sized` is not implemented for `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` + = help: the trait `Sized` is not implemented for `view_type!(A.{ b, c })` note: required by an implicit `Sized` bound in `assert_sized` --> $DIR/unsized.rs:11:17 | @@ -75,13 +75,13 @@ help: consider relaxing the implicit `Sized` restriction LL | fn assert_sized() {} | ++++++++ -error[E0277]: the size for values of type `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` cannot be known +error[E0277]: the size for values of type `view_type!(A.{ b, c })` cannot be known --> $DIR/unsized.rs:31:24 | LL | assert_metasized::(); | ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a known size | - = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ (field_of!(A, b), field_of!(A, c)) })` + = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ b, c })` note: required by a bound in `assert_metasized` --> $DIR/unsized.rs:12:24 | From 4d98bd63ca2920047c73f0289e26d952968b8e2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Sat, 14 Nov 2026 12:17:21 +0100 Subject: [PATCH 10/43] Store comment content in a temporary directory --- .github/workflows/post-merge.yml | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.yml index dfea8b5fe49b4..87a5eb8603fe2 100644 --- a/.github/workflows/post-merge.yml +++ b/.github/workflows/post-merge.yml @@ -101,18 +101,20 @@ jobs: STATUS=$? set -e + COMMENT_FILE=${RUNNER_TEMP}/comment.txt + if [[ ${STATUS} == 0 ]]; then - echo "backtrace \`${VERSION}\` published to crates.io" > comment.txt + echo "backtrace \`${VERSION}\` published to crates.io" > ${COMMENT_FILE} else - echo "backtrace \`${VERSION}\` could not be published to crates.io" > comment.txt - printf "
\nCargo publish log\n\n" >> comment.txt - printf '```\n' >> comment.txt - cat "${RUNNER_TEMP}/cargo-log.txt" >> comment.txt - printf '\n```\n' >> comment.txt - printf "
\n\n" >> comment.txt + echo "backtrace \`${VERSION}\` could not be published to crates.io" > ${COMMENT_FILE} + printf "
\nCargo publish log\n\n" >> ${COMMENT_FILE} + printf '```\n' >> ${COMMENT_FILE} + cat "${RUNNER_TEMP}/cargo-log.txt" >> ${COMMENT_FILE} + printf '\n```\n' >> ${COMMENT_FILE} + printf "
\n\n" >> ${COMMENT_FILE} fi - gh pr comment "${HEAD_PR}" -F comment.txt + gh pr comment "${HEAD_PR}" -F ${COMMENT_FILE} exit "${STATUS}" env: CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} From 26498e50df5825a6e9c0f0327646a86c79c9db6a Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Mon, 16 Nov 2026 13:07:20 +0100 Subject: [PATCH 11/43] Use attribute parser for lang attributes in `LateResolutionVisitor` --- compiler/rustc_attr_ir/src/data_structures.rs | 2 +- .../rustc_attr_ir/src/encode_cross_crate.rs | 2 +- .../src/attributes/codegen_attrs.rs | 2 +- .../src/attributes/rustc_internal.rs | 4 +- .../rustc_codegen_ssa/src/codegen_attrs.rs | 2 +- compiler/rustc_resolve/src/late/lang_items.rs | 76 ++++++++----------- 6 files changed, 39 insertions(+), 49 deletions(-) diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index 6e86fd3f3aa5c..e8480fa46cdd8 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -958,7 +958,7 @@ pub enum AttributeKind { InstrumentFn(InstrumentFnAttr), /// Represents `#[lang]` - Lang(LangItem), + Lang(LangItem, Span), /// Represents `#[link]`. Link(ThinVec, Span), diff --git a/compiler/rustc_attr_ir/src/encode_cross_crate.rs b/compiler/rustc_attr_ir/src/encode_cross_crate.rs index 0f4bb8f167d9f..166763d567821 100644 --- a/compiler/rustc_attr_ir/src/encode_cross_crate.rs +++ b/compiler/rustc_attr_ir/src/encode_cross_crate.rs @@ -262,7 +262,7 @@ impl AttributeKind { Inline(..) => false, InstructionSet(..) => false, InstrumentFn(..) => false, - Lang(item) => item.link_name().is_some(), + Lang(item, _) => item.link_name().is_some(), Link(..) => false, LinkName { .. } => false, LinkOrdinal { .. } => false, diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index e88b1751e4b6c..0f3dfb718c33d 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -390,7 +390,7 @@ impl NoArgsAttributeParser for TrackCallerParser { Target::Fn => { // `#[track_caller]` is not valid on weak lang items because they are called via // `extern` declarations and `#[track_caller]` would alter their ABI. - if let Some(item) = find_attr!(cx.parsed_attrs, Lang(item) => item) + if let Some(item) = find_attr!(cx.parsed_attrs, Lang(item, _) => item) && item.is_weak() { cx.emit_err(TrackCallerOnLangItem { diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index 0c056240a81d4..198a40ee65957 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -569,7 +569,7 @@ impl SingleAttributeParser for LangParser { let allowed_targets: &[_] = &[Allow(lang_item.target())]; cx.check_target(&format!(" = \"{name}\""), &AllowedTargets::AllowList(allowed_targets)); - Some(AttributeKind::Lang(lang_item)) + Some(AttributeKind::Lang(lang_item, cx.attr_span)) } } @@ -594,7 +594,7 @@ impl NoArgsAttributeParser for PanicHandlerParser { const PATH: &[Symbol] = &[sym::panic_handler]; const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[Allow(Target::Fn)]); const STABILITY: AttributeStability = AttributeStability::Stable; - const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::Lang(LangItem::PanicImpl); + const CREATE: fn(Span) -> AttributeKind = |s| AttributeKind::Lang(LangItem::PanicImpl, s); } pub(crate) struct RustcNounwindParser; diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 8f7970da96402..6b58ffff687bd 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -563,7 +563,7 @@ fn handle_lang_items( attrs: &[Attribute], codegen_fn_attrs: &mut CodegenFnAttrs, ) { - let lang_item = find_attr!(attrs, Lang(lang) => lang); + let lang_item = find_attr!(attrs, Lang(lang, _) => lang); // Weak lang items have the same semantics as "std internal" symbols in the // sense that they're preserved through all our LTO passes and only diff --git a/compiler/rustc_resolve/src/late/lang_items.rs b/compiler/rustc_resolve/src/late/lang_items.rs index b53928df24dc8..b3aff17afbaae 100644 --- a/compiler/rustc_resolve/src/late/lang_items.rs +++ b/compiler/rustc_resolve/src/late/lang_items.rs @@ -9,7 +9,8 @@ use rustc_ast as ast; use rustc_attr_ir::target::Target; -use rustc_attr_ir::{GenericRequirement, LangItem, LanguageItems}; +use rustc_attr_ir::{AttributeKind, GenericRequirement, LangItem, LanguageItems}; +use rustc_attr_parsing::AttributeParser; use rustc_crate_store::ExternCrate; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::ty::TyCtxt; @@ -34,51 +35,40 @@ impl<'tcx> LateResolutionVisitor<'_, '_, '_, 'tcx> { item_span: Span, generics: Option<&ast::Generics>, ) { - let attrs = attrs.iter().find_map(|attr| { - Some(match attr { - _ if attr.has_name(sym::lang) => (attr.value_str()?, attr.span), - _ if attr.has_name(sym::panic_handler) => (sym::panic_impl, attr.span), - _ => return None, + if let Some(rustc_attr_ir::Attribute::Parsed(AttributeKind::Lang(lang_item, attr_span))) = + AttributeParser::parse_limited(self.r.tcx.sess, attrs, &|attr| { + attr.has_any_name(&[sym::lang, sym::panic_handler]) }) - }); - if let Some((name, attr_span)) = attrs { - match LangItem::from_name(name) { - // Known lang item - Some(lang_item) => { - if actual_target != lang_item.target() { - // `#[panic_handler]` is turned into `#[lang = "panic_impl"]`, but in contrast - // to the actual lang item attr, is applied to `Fn` instead of `ForeignFn`. - if !(lang_item.is_weak() - && actual_target == Target::Fn - && lang_item.target() == Target::ForeignFn - && matches!(lang_item, LangItem::PanicImpl)) - { - self.r.tcx - .dcx() - .delayed_bug(format!("lang item target is checked in attribute parser: {:?} has {} but expected {}", def_id, actual_target, lang_item.target())); - return; - } - } - // Weak lang items are handled separately - if lang_item.is_weak() && actual_target == Target::ForeignFn { - self.r.lang_items.missing.push(lang_item); - } else { - // Weak only lang items are always handled here - self.collect_item_extended( - lang_item, - def_id, - item_span, - attr_span, - generics, - actual_target, - ); - } - } - // Unknown lang item. - _ => { - self.r.tcx.dcx().delayed_bug("unknown lang item"); + { + if actual_target != lang_item.target() { + // `#[panic_handler]` is turned into `#[lang = "panic_impl"]`, but in contrast + // to the actual lang item attr, is applied to `Fn` instead of `ForeignFn`. + if !(lang_item.is_weak() + && actual_target == Target::Fn + && lang_item.target() == Target::ForeignFn + && matches!(lang_item, LangItem::PanicImpl)) + { + self.r.tcx + .dcx() + .delayed_bug(format!("lang item target is checked in attribute parser: {:?} has {} but expected {}", def_id, actual_target, lang_item.target())); + return; } } + + // Weak lang items are handled separately + if lang_item.is_weak() && actual_target == Target::ForeignFn { + self.r.lang_items.missing.push(lang_item); + } else { + // Weak only lang items are always handled here + self.collect_item_extended( + lang_item, + def_id, + item_span, + attr_span, + generics, + actual_target, + ); + } } } From 5cbb98236941201a6a23b4d997537dda4b9c27a8 Mon Sep 17 00:00:00 2001 From: Xubai Wang Date: Tue, 17 Nov 2026 00:11:53 +0800 Subject: [PATCH 12/43] Add const generic transmute min support Signed-off-by: Xubai Wang --- compiler/rustc_hir_typeck/src/intrinsicck.rs | 15 +++- compiler/rustc_lint/src/types.rs | 2 +- compiler/rustc_middle/src/ty/layout.rs | 44 +++++++++-- tests/ui/const-generics/transmute-fail.rs | 9 --- tests/ui/const-generics/transmute-fail.stderr | 77 ++++++++----------- tests/ui/const-generics/transmute.rs | 38 ++++++++- 6 files changed, 119 insertions(+), 66 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/intrinsicck.rs b/compiler/rustc_hir_typeck/src/intrinsicck.rs index 364b7e35ae920..5d54d150c9fef 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -57,6 +57,13 @@ fn skeleton_string<'tcx>( bug!("{:?} overflow for u128", size) } } + Ok(SizeSkeleton::Array { base, const_lens, .. }) => { + let base_bits = u128::from(base.bytes()) + .checked_mul(8) + .unwrap_or_else(|| bug!("{:?} overflow for u128", base)); + let lens = const_lens.iter().map(|l| format!("({l})")).collect::>().join(" * "); + format!("{base_bits} * {lens} bits") + } Err(LayoutError::TooGeneric(bad)) => { if *bad == ty { "this type does not have a fixed size".to_owned() @@ -97,10 +104,10 @@ fn check_transmute<'tcx>( trace!(?sk_from, ?sk_to); // Check for same size using the skeletons. - if let Ok(sk_from) = sk_from - && let Ok(sk_to) = sk_to + if let Ok(sk_from) = &sk_from + && let Ok(sk_to) = &sk_to { - if sk_from.same_size(sk_to) { + if sk_from.same_size(&sk_to) { return Ok(()); } @@ -109,7 +116,7 @@ fn check_transmute<'tcx>( let from = unpack_option_like(tcx, from); if let ty::FnDef(..) = from.kind() && let SizeSkeleton::Known(size_to, _) = sk_to - && size_to == Pointer(tcx.data_layout.instruction_address_space).size(&tcx) + && *size_to == Pointer(tcx.data_layout.instruction_address_space).size(&tcx) { struct_span_code_err!(tcx.sess.dcx(), span, E0591, "can't transmute zero-sized type") .with_note(format!("source type: {from}")) diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index b66e06a93a074..35d8cfda63644 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -982,7 +982,7 @@ pub(crate) fn repr_nullable_ptr<'tcx>( // being applied (and we've got a problem somewhere). let compute_size_skeleton = |t| SizeSkeleton::compute(t, tcx, typing_env, DUMMY_SP).ok(); - if !compute_size_skeleton(ty)?.same_size(compute_size_skeleton(field_ty)?) { + if !compute_size_skeleton(ty)?.same_size(&compute_size_skeleton(field_ty)?) { bug!("improper_ctypes: Option nonnull optimization not applied?"); } diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 1f1a769665c26..b298ea415a57c 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -16,6 +16,7 @@ use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Spanned, Symbol, bug, span_bug use rustc_structures::Limit; use rustc_target::callconv::FnAbi; use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi}; +use rustc_type_ir::Const; use tracing::debug; use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; @@ -333,12 +334,21 @@ impl<'tcx> LayoutCx<'tcx> { /// While this is conservative, (aside from constant sizes, only pointers, /// newtypes thereof and null pointer optimized enums are allowed), it is /// enough to statically check common use cases of transmute. -#[derive(Copy, Clone, Debug)] +#[derive(Clone, Debug)] pub enum SizeSkeleton<'tcx> { /// Any statically computable Layout. /// Alignment can be `None` if unknown. Known(Size, Option), + /// An array with unevaluated const lengths. + Array { + /// The base size, including the element size and all known array + /// lengths accumulated. + base: Size, + align: Option, + const_lens: Vec>>, + }, + /// A potentially-wide pointer. Pointer { /// If true, this pointer is never null. @@ -471,9 +481,25 @@ impl<'tcx> SizeSkeleton<'tcx> { .checked_mul(c) .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?; // Alignment is unchanged by arrays. - return Ok(SizeSkeleton::Known(Size::from_bytes(size), a)); + Ok(SizeSkeleton::Known(Size::from_bytes(size), a)) + } else if s.bytes() == 0 { + Ok(SizeSkeleton::Known(s, a)) + } else { + Ok(SizeSkeleton::Array { base: s, align: a, const_lens: vec![len] }) + } + } + SizeSkeleton::Array { mut base, align, mut const_lens } => { + match len_eval { + Some(c) => { + base = Size::from_bytes(base.bytes().checked_mul(c).ok_or_else( + || &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)), + )?); + } + None => { + const_lens.push(len); + } } - Err(err) + Ok(SizeSkeleton::Array { base, align, const_lens }) } SizeSkeleton::Pointer { .. } => Err(err), } @@ -537,6 +563,9 @@ impl<'tcx> SizeSkeleton<'tcx> { return Err(err); } } + SizeSkeleton::Array { .. } => { + return Err(err); + } SizeSkeleton::Pointer { .. } => { if ptr.is_some() { return Err(err); @@ -590,7 +619,8 @@ impl<'tcx> SizeSkeleton<'tcx> { // But in the case of `!null` patterns we need to note that in the // raw pointer. ty::PatternKind::NotNull => match base? { - SizeSkeleton::Known(..) => base, + known @ SizeSkeleton::Known(..) => Ok(known), + array @ SizeSkeleton::Array { .. } => Ok(array), SizeSkeleton::Pointer { non_zero: _, tail } => { Ok(SizeSkeleton::Pointer { non_zero: true, tail }) } @@ -602,12 +632,16 @@ impl<'tcx> SizeSkeleton<'tcx> { } } - pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool { + pub fn same_size(&self, other: &SizeSkeleton<'tcx>) -> bool { match (self, other) { (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b, (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => { a == b } + ( + SizeSkeleton::Array { base: a, const_lens: al, .. }, + SizeSkeleton::Array { base: b, const_lens: bl, .. }, + ) => a == b && al == bl, _ => false, } } diff --git a/tests/ui/const-generics/transmute-fail.rs b/tests/ui/const-generics/transmute-fail.rs index cf9064bd8f4ba..46f1d343070b5 100644 --- a/tests/ui/const-generics/transmute-fail.rs +++ b/tests/ui/const-generics/transmute-fail.rs @@ -1,7 +1,6 @@ // ignore-tidy-linelength //@ normalize-stderr: "values of the type `[^`]+` are too big" -> "values of the type $$REALLY_TOO_BIG are too big" - #![feature(transmute_generic_consts)] #![feature(generic_const_exprs)] #![allow(incomplete_features)] @@ -39,7 +38,6 @@ fn overflow_more(v: [[[u32; 8888888]; 9999999]; 777777777]) -> [[[u32; 9999999]; unsafe { std::mem::transmute(v) } //~ ERROR cannot transmute between types of different sizes } - fn transpose(v: [[u32; H]; W]) -> [[u32; W]; H] { unsafe { std::mem::transmute(v) @@ -97,13 +95,6 @@ fn condense_bytes(v: [u8; L * 2]) -> [u16; L] { } } -fn singleton_each(v: [u8; L]) -> [[u8; 1]; L] { - unsafe { - std::mem::transmute(v) - //~^ ERROR: cannot transmute between types of different sizes, or dependently-sized types - } -} - fn transpose_with_const( v: [[u32; 2 * H]; W + W], ) -> [[u32; W + W]; 2 * H] { diff --git a/tests/ui/const-generics/transmute-fail.stderr b/tests/ui/const-generics/transmute-fail.stderr index 30541e539b63a..9780d6ae6f325 100644 --- a/tests/ui/const-generics/transmute-fail.stderr +++ b/tests/ui/const-generics/transmute-fail.stderr @@ -1,5 +1,5 @@ error: the constant `W` is not of type `usize` - --> $DIR/transmute-fail.rs:16:53 + --> $DIR/transmute-fail.rs:15:53 | LL | fn bar(v: [[u32; H]; W]) -> [[u32; W]; H] { | ------------- `W` defined here ^ array length expected `usize`, found `bool` @@ -7,7 +7,7 @@ LL | fn bar(v: [[u32; H]; W]) -> [[u32; W]; H] { = note: the length of array `[[u32; H]; W]` must be type `usize` error: the constant `W` is not of type `usize` - --> $DIR/transmute-fail.rs:19:9 + --> $DIR/transmute-fail.rs:18:9 | LL | fn bar(v: [[u32; H]; W]) -> [[u32; W]; H] { | ------------- `W` defined here @@ -18,25 +18,25 @@ LL | std::mem::transmute(v) = note: the length of array `[[u32; H]; W]` must be type `usize` error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:11:9 + --> $DIR/transmute-fail.rs:10:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[u32; H + 1]; W]` (size can vary because of [u32; H + 1]) - = note: target type: `[[u32; W + 1]; H]` (size can vary because of [u32; W + 1]) + = note: source type: `[[u32; H + 1]; W]` (32 * (H + 1) * (W) bits) + = note: target type: `[[u32; W + 1]; H]` (32 * (W + 1) * (H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:26:9 + --> $DIR/transmute-fail.rs:25:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[u32; H]; W]` (size can vary because of [u32; H]) - = note: target type: `[u32; W * H * H]` (this type does not have a fixed size) + = note: source type: `[[u32; H]; W]` (32 * (H) * (W) bits) + = note: target type: `[u32; W * H * H]` (32 * (W * H * H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:33:9 + --> $DIR/transmute-fail.rs:32:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ @@ -45,7 +45,7 @@ LL | std::mem::transmute(v) = note: target type: `[[[u32; 9999999]; 777777777]; 8888888]` (values of the type $REALLY_TOO_BIG are too big for the target architecture) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:39:14 + --> $DIR/transmute-fail.rs:38:14 | LL | unsafe { std::mem::transmute(v) } | ^^^^^^^^^^^^^^^^^^^ @@ -54,67 +54,67 @@ LL | unsafe { std::mem::transmute(v) } = note: target type: `[[[u32; 9999999]; 777777777]; 239]` (values of the type $REALLY_TOO_BIG are too big for the target architecture) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:45:9 + --> $DIR/transmute-fail.rs:43:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[u32; H]; W]` (size can vary because of [u32; H]) - = note: target type: `[[u32; W]; H]` (size can vary because of [u32; W]) + = note: source type: `[[u32; H]; W]` (32 * (H) * (W) bits) + = note: target type: `[[u32; W]; H]` (32 * (W) * (H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:56:9 + --> $DIR/transmute-fail.rs:54:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[u32; H]; W]` (size can vary because of [u32; H]) - = note: target type: `[u32; W * H]` (this type does not have a fixed size) + = note: source type: `[[u32; H]; W]` (32 * (H) * (W) bits) + = note: target type: `[u32; W * H]` (32 * (W * H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:63:9 + --> $DIR/transmute-fail.rs:61:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[u32; H * W]` (this type does not have a fixed size) - = note: target type: `[[u32; W]; H]` (size can vary because of [u32; W]) + = note: source type: `[u32; H * W]` (32 * (H * W) bits) + = note: target type: `[[u32; W]; H]` (32 * (W) * (H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:72:9 + --> $DIR/transmute-fail.rs:70:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[[u32; D]; H]; W]` (size can vary because of [u32; D]) - = note: target type: `[u32; D * W * H]` (this type does not have a fixed size) + = note: source type: `[[[u32; D]; H]; W]` (32 * (D) * (H) * (W) bits) + = note: target type: `[u32; D * W * H]` (32 * (D * W * H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:81:9 + --> $DIR/transmute-fail.rs:79:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[[u32; D]; H]; W]` (size can vary because of [u32; D]) - = note: target type: `[[u32; D * W]; H]` (size can vary because of [u32; D * W]) + = note: source type: `[[[u32; D]; H]; W]` (32 * (D) * (H) * (W) bits) + = note: target type: `[[u32; D * W]; H]` (32 * (D * W) * (H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:88:9 + --> $DIR/transmute-fail.rs:86:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[u16; L]` (this type does not have a fixed size) - = note: target type: `[u8; L * 2]` (this type does not have a fixed size) + = note: source type: `[u16; L]` (16 * (L) bits) + = note: target type: `[u8; L * 2]` (8 * (L * 2) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:95:9 + --> $DIR/transmute-fail.rs:93:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[u8; L * 2]` (this type does not have a fixed size) - = note: target type: `[u16; L]` (this type does not have a fixed size) + = note: source type: `[u8; L * 2]` (8 * (L * 2) bits) + = note: target type: `[u16; L]` (16 * (L) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types --> $DIR/transmute-fail.rs:102:9 @@ -122,18 +122,9 @@ error[E0512]: cannot transmute between types of different sizes, or dependently- LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[u8; L]` (this type does not have a fixed size) - = note: target type: `[[u8; 1]; L]` (this type does not have a fixed size) + = note: source type: `[[u32; 2 * H]; W + W]` (32 * (2 * H) * (W + W) bits) + = note: target type: `[[u32; W + W]; 2 * H]` (32 * (W + W) * (2 * H) bits) -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:111:9 - | -LL | std::mem::transmute(v) - | ^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[[u32; 2 * H]; W + W]` (size can vary because of [u32; 2 * H]) - = note: target type: `[[u32; W + W]; 2 * H]` (size can vary because of [u32; W + W]) - -error: aborting due to 15 previous errors +error: aborting due to 14 previous errors For more information about this error, try `rustc --explain E0512`. diff --git a/tests/ui/const-generics/transmute.rs b/tests/ui/const-generics/transmute.rs index 6108139f3ce5c..d17d1ed75bd4d 100644 --- a/tests/ui/const-generics/transmute.rs +++ b/tests/ui/const-generics/transmute.rs @@ -1,13 +1,43 @@ //@ run-pass #![feature(generic_const_exprs)] +#![feature(transmute_generic_consts)] #![allow(incomplete_features)] fn ident(v: [[u32; H]; W]) -> [[u32; H]; W] { - unsafe { - std::mem::transmute(v) - } + unsafe { std::mem::transmute(v) } +} + +fn singleton_each(v: [u8; L]) -> [[u8; 1]; L] { + unsafe { std::mem::transmute(v) } +} + +#[derive(Clone, Copy)] +#[repr(C)] +struct T(u8); + +fn element(v: [T; N]) -> [u8; N] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn element2(v: [[T; N]; M]) -> [[u8; N]; M] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn element3_mixed(v: [[[T; N]; 42]; M]) -> [[[u8; N]; 42]; M] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn element4_swap_lit( + v: [[[[T; N]; 3]; 7]; M], +) -> [[[[u8; 7]; N]; M]; 3] { + unsafe { std::mem::transmute::<_, _>(v) } } fn main() { - let _ = ident([[0; 8]; 16]); + let _ = ident([[0; 8]; 16]); + let _ = singleton_each([0; 8]); + let _ = element([T(0); 8]); + let _ = element2([[T(0); 8]; 16]); + let _ = element3_mixed([[[T(0); 8]; 42]; 16]); + let _ = element4_swap_lit([[[[T(0); 8]; 3]; 7]; 16]); } From 771b22f3ab4c3e98e939d5c2f5ee595d19a4dc48 Mon Sep 17 00:00:00 2001 From: xonx4l Date: Mon, 16 Nov 2026 23:21:18 +0530 Subject: [PATCH 13/43] bootstrap:fix keep-stage-std --- src/bootstrap/src/core/build_steps/compile.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index c7af07210cc57..6ccc6d3b55d02 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -195,8 +195,10 @@ impl CommandLineStep for Std { return None; } + // Reuse std for `--keep-stage-std` if it was built before, otherwise build it. if builder.config.keep_stage.contains(&build_compiler.stage) - || builder.config.keep_stage_std.contains(&build_compiler.stage) + || (builder.config.keep_stage_std.contains(&build_compiler.stage) + && build_stamp::libstd_stamp(builder, build_compiler, target).path().exists()) { trace!(keep_stage = ?builder.config.keep_stage); trace!(keep_stage_std = ?builder.config.keep_stage_std); From 8f55c12872f97f517d2238b15ddf626e51f75270 Mon Sep 17 00:00:00 2001 From: Takayuki Maeda Date: Wed, 18 Nov 2026 02:51:01 +0900 Subject: [PATCH 14/43] add regression test for re-exporting a private import of a primitive type --- .../imports/reexport-private-import-of-primitive-type.rs | 9 +++++++++ .../reexport-private-import-of-primitive-type.stderr | 9 +++++++++ 2 files changed, 18 insertions(+) create mode 100644 tests/ui/imports/reexport-private-import-of-primitive-type.rs create mode 100644 tests/ui/imports/reexport-private-import-of-primitive-type.stderr diff --git a/tests/ui/imports/reexport-private-import-of-primitive-type.rs b/tests/ui/imports/reexport-private-import-of-primitive-type.rs new file mode 100644 index 0000000000000..c718e27509b0e --- /dev/null +++ b/tests/ui/imports/reexport-private-import-of-primitive-type.rs @@ -0,0 +1,9 @@ +// Regression test for https://github.com/rust-lang/rust/issues/165827 + +//@ edition: 2024 + +use str; +pub use str as b; +//~^ ERROR `str` is only public within the crate, and cannot be re-exported outside + +fn main() {} diff --git a/tests/ui/imports/reexport-private-import-of-primitive-type.stderr b/tests/ui/imports/reexport-private-import-of-primitive-type.stderr new file mode 100644 index 0000000000000..29afdc30e72c6 --- /dev/null +++ b/tests/ui/imports/reexport-private-import-of-primitive-type.stderr @@ -0,0 +1,9 @@ +error[E0365]: `str` is only public within the crate, and cannot be re-exported outside + --> $DIR/reexport-private-import-of-primitive-type.rs:6:9 + | +LL | pub use str as b; + | ^^^^^^^^ re-export of crate public `str` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0365`. From 7bc94db4df5e6f91a19e7b39916a81344da6f117 Mon Sep 17 00:00:00 2001 From: Takayuki Maeda Date: Wed, 18 Nov 2026 02:51:23 +0900 Subject: [PATCH 15/43] avoid ICE on re-exports of private imports without a `DefId` --- compiler/rustc_resolve/src/diagnostics/mod.rs | 4 ++-- compiler/rustc_resolve/src/imports.rs | 12 +++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_resolve/src/diagnostics/mod.rs b/compiler/rustc_resolve/src/diagnostics/mod.rs index 4a54269a30137..c2a053fc0e731 100644 --- a/compiler/rustc_resolve/src/diagnostics/mod.rs +++ b/compiler/rustc_resolve/src/diagnostics/mod.rs @@ -837,7 +837,7 @@ pub(crate) struct CannotBeReexportedPrivateNS { pub(crate) span: Span, pub(crate) ident: Ident, #[note("consider declaring {$descr} `{$ident}` with `pub`")] - pub(crate) parent: Span, + pub(crate) parent: Option, pub(crate) descr: &'static str, } @@ -849,7 +849,7 @@ pub(crate) struct CannotBeReexportedCratePublicNS { pub(crate) span: Span, pub(crate) ident: Ident, #[note("consider declaring {$descr} `{$ident}` with `pub`")] - pub(crate) parent: Span, + pub(crate) parent: Option, pub(crate) descr: &'static str, } diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index f7e86925800a3..68f07e204c092 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -1685,9 +1685,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { diagnostic: diagnostic.into(), }); } else if ns == TypeNS { - let def_id = decl.res().def_id(); - let parent = if !def_id.is_crate_root() { self.def_span(def_id) } else { DUMMY_SP }; - let descr = self.tcx().def_descr(def_id); + let res = decl.res(); + let (parent, descr) = match res.opt_def_id() { + Some(def_id) => { + let parent = + if !def_id.is_crate_root() { self.def_span(def_id) } else { DUMMY_SP }; + (Some(parent), self.tcx().def_descr(def_id)) + } + None => (None, res.descr()), + }; if crate_private_reexport { self.dcx().emit_err(CannotBeReexportedCratePublicNS { From ec54b14a5dd225081fe1af280437c81791161229 Mon Sep 17 00:00:00 2001 From: David Walker Date: Tue, 17 Nov 2026 18:02:05 -0800 Subject: [PATCH 16/43] Move ub_checks() inside the const_eval_select branch. This looks like it shouldn't change anything, but it is a small speedup for CTFE that goes through this macro. Presumably by avoiding the MIR for the early-out `&&` entirely, it can go a little faster. --- library/core/src/ub_checks.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/ub_checks.rs b/library/core/src/ub_checks.rs index f25781ea8ce5a..63393c58ef636 100644 --- a/library/core/src/ub_checks.rs +++ b/library/core/src/ub_checks.rs @@ -102,9 +102,9 @@ pub(crate) const fn check_language_ub() -> bool { false } else { // Disable UB checks in Miri. - !cfg!(miri) + !cfg!(miri) && intrinsics::ub_checks() } - ) && intrinsics::ub_checks() + ) } /// Checks whether `ptr` is properly aligned with respect to the given alignment, and From 421b1b2f236e0d178b40843651121fbcac728025 Mon Sep 17 00:00:00 2001 From: Joseph Zhao Date: Wed, 18 Nov 2026 02:40:18 +0000 Subject: [PATCH 17/43] fix ICE when a forced keyword follows a parameter pattern MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix ICE when a forced keyword follows a parameter pattern * Update compiler/rustc_parse/src/parser/diagnostics.rs * fix the errors * fix format error * update stderr Co-authored-by: Joseph Zhao <65984904+programskillforverification@users.noreply.github.com> Co-authored-by: León Orell Valerian Liehr --- .../rustc_parse/src/parser/diagnostics.rs | 5 +- compiler/rustc_parse/src/parser/item.rs | 5 +- .../ui/async-await/in-trait/bad-signatures.rs | 3 +- .../in-trait/bad-signatures.stderr | 8 +-- .../forced-keywords/missing-kw-before-item.rs | 10 ++++ .../missing-kw-before-item.stderr | 18 ++++++ .../forced-keywords/param-without-type.rs | 13 +++++ .../forced-keywords/param-without-type.stderr | 28 ++++++++++ ...70549-resolve-after-recovered-self-ctor.rs | 6 +- ...9-resolve-after-recovered-self-ctor.stderr | 33 ++--------- .../kw-in-const-item-pos-recovery-149692.rs | 5 +- ...w-in-const-item-pos-recovery-149692.stderr | 21 ++----- .../macro/kw-in-item-pos-recovery-149692.rs | 13 ++--- .../kw-in-item-pos-recovery-149692.stderr | 56 +++++-------------- .../macro/kw-in-item-pos-recovery-151238.rs | 5 +- .../kw-in-item-pos-recovery-151238.stderr | 8 +-- 16 files changed, 111 insertions(+), 126 deletions(-) create mode 100644 tests/ui/parser/forced-keywords/missing-kw-before-item.rs create mode 100644 tests/ui/parser/forced-keywords/missing-kw-before-item.stderr create mode 100644 tests/ui/parser/forced-keywords/param-without-type.rs create mode 100644 tests/ui/parser/forced-keywords/param-without-type.stderr diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 9e6a92d4bbdae..5b858cfacd2e2 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -2008,11 +2008,12 @@ impl<'a> Parser<'a> { ) -> Option { // If we find a pattern followed by an identifier, it could be an (incorrect) // C-style parameter declaration. - if self.check_ident() + if let Some((ident, kind)) = self.token.ident() + && (ident.name == kw::SelfLower || !token::ident_of_kind_is_reserved(ident, kind)) && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseParen) { // `fn foo(String s) {}` - let ident = self.parse_ident_common(true).unwrap(); + self.bump(); // ident let span = pat.span.with_hi(ident.span.hi()); err.span_suggestion_verbose( diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 27646bac1c21e..58788cf4504e8 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -507,12 +507,13 @@ impl<'a> Parser<'a> { let span = if is_pub { self.prev_token.span.to(ident_span) } else { ident_span }; let insert_span = ident_span.shrink_to_lo(); - let ident = if self.token.is_ident() + let ident = if let Some(ident) = self.token.non_reserved_ident() && (!is_const || self.look_ahead(1, |t| *t == token::OpenParen)) && self.look_ahead(1, |t| { matches!(t.kind, token::Lt | token::OpenBrace | token::OpenParen) }) { - self.parse_ident_common(true).unwrap() + self.bump(); // ident + ident } else { return Ok(()); }; diff --git a/tests/ui/async-await/in-trait/bad-signatures.rs b/tests/ui/async-await/in-trait/bad-signatures.rs index 57a0ccb0d18e0..a74d35b1c77a4 100644 --- a/tests/ui/async-await/in-trait/bad-signatures.rs +++ b/tests/ui/async-await/in-trait/bad-signatures.rs @@ -3,8 +3,7 @@ trait MyTrait { async fn bar(&abc self); - //~^ ERROR expected identifier, found keyword `self` - //~| ERROR expected one of `:`, `@`, or `|`, found keyword `self` + //~^ ERROR expected one of `:`, `@`, or `|`, found keyword `self` } impl MyTrait for () { diff --git a/tests/ui/async-await/in-trait/bad-signatures.stderr b/tests/ui/async-await/in-trait/bad-signatures.stderr index 1f2f0537af3d1..2e5cb2e2faa57 100644 --- a/tests/ui/async-await/in-trait/bad-signatures.stderr +++ b/tests/ui/async-await/in-trait/bad-signatures.stderr @@ -1,9 +1,3 @@ -error: expected identifier, found keyword `self` - --> $DIR/bad-signatures.rs:5:23 - | -LL | async fn bar(&abc self); - | ^^^^ expected identifier, found keyword - error: expected one of `:`, `@`, or `|`, found keyword `self` --> $DIR/bad-signatures.rs:5:23 | @@ -16,5 +10,5 @@ LL - async fn bar(&abc self); LL + async fn bar(: ); | -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/parser/forced-keywords/missing-kw-before-item.rs b/tests/ui/parser/forced-keywords/missing-kw-before-item.rs new file mode 100644 index 0000000000000..ca113b9233d82 --- /dev/null +++ b/tests/ui/parser/forced-keywords/missing-kw-before-item.rs @@ -0,0 +1,10 @@ +// Check that we don't ICE when recovering a missing `fn`/`struct` keyword before a forced keyword. +// +//@ edition: 2021.. +#![feature(forced_keywords)] + +pub k#self() {} +//~^ ERROR visibility `pub` is not followed by an item +//~| ERROR expected item, found keyword `k#self` + +fn main() {} diff --git a/tests/ui/parser/forced-keywords/missing-kw-before-item.stderr b/tests/ui/parser/forced-keywords/missing-kw-before-item.stderr new file mode 100644 index 0000000000000..c6585157c8090 --- /dev/null +++ b/tests/ui/parser/forced-keywords/missing-kw-before-item.stderr @@ -0,0 +1,18 @@ +error: visibility `pub` is not followed by an item + --> $DIR/missing-kw-before-item.rs:6:1 + | +LL | pub k#self() {} + | ^^^ the visibility + | + = help: you likely meant to define an item, e.g., `pub fn foo() {}` + +error: expected item, found keyword `k#self` + --> $DIR/missing-kw-before-item.rs:6:5 + | +LL | pub k#self() {} + | ^^^^^^ expected item + | + = note: for a full list of items that can appear in modules, see + +error: aborting due to 2 previous errors + diff --git a/tests/ui/parser/forced-keywords/param-without-type.rs b/tests/ui/parser/forced-keywords/param-without-type.rs new file mode 100644 index 0000000000000..2bcc584283e3a --- /dev/null +++ b/tests/ui/parser/forced-keywords/param-without-type.rs @@ -0,0 +1,13 @@ +// Regression test for . +// +//@ edition: 2021.. +#![feature(forced_keywords)] + +fn foo(S k#self) {} +//~^ ERROR expected one of `:`, `@`, or `|`, found keyword `k#self` +//~| ERROR `self` parameter is only allowed in associated functions + +fn bar(S k#not_a_keyword) {} +//~^ ERROR expected one of `:`, `@`, or `|`, found `k#not_a_keyword` + +fn main() {} diff --git a/tests/ui/parser/forced-keywords/param-without-type.stderr b/tests/ui/parser/forced-keywords/param-without-type.stderr new file mode 100644 index 0000000000000..9c92f77ad9c4f --- /dev/null +++ b/tests/ui/parser/forced-keywords/param-without-type.stderr @@ -0,0 +1,28 @@ +error: expected one of `:`, `@`, or `|`, found keyword `k#self` + --> $DIR/param-without-type.rs:6:10 + | +LL | fn foo(S k#self) {} + | ^^^^^^ expected one of `:`, `@`, or `|` + | +help: declare the type after the parameter binding + | +LL - fn foo(S k#self) {} +LL + fn foo(: ) {} + | + +error: expected one of `:`, `@`, or `|`, found `k#not_a_keyword` + --> $DIR/param-without-type.rs:10:10 + | +LL | fn bar(S k#not_a_keyword) {} + | ^^^^^^^^^^^^^^^ expected one of `:`, `@`, or `|` + +error: `self` parameter is only allowed in associated functions + --> $DIR/param-without-type.rs:6:8 + | +LL | fn foo(S k#self) {} + | ^ not semantically valid as function parameter + | + = note: associated functions are those in `impl` or `trait` definitions + +error: aborting due to 3 previous errors + diff --git a/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.rs b/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.rs index ada10fcda27d9..292019a5c46fd 100644 --- a/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.rs +++ b/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.rs @@ -2,14 +2,10 @@ struct S {} impl S { fn foo(&mur Self) {} - //~^ ERROR expected identifier, found keyword `Self` - //~| ERROR expected one of `:`, `@` - //~| ERROR expected unit struct, found self constructor `Self` + //~^ ERROR expected one of `:`, `@` fn bar(&'static mur Self) {} //~^ ERROR unexpected lifetime - //~| ERROR expected identifier, found keyword `Self` //~| ERROR expected one of `:`, `@` - //~| ERROR expected unit struct, found self constructor `Self` fn baz(&mur Self @ _) {} //~^ ERROR expected one of `:`, `@` diff --git a/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.stderr b/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.stderr index 9c632a8332a19..cb0f514f40c93 100644 --- a/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.stderr +++ b/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.stderr @@ -1,9 +1,3 @@ -error: expected identifier, found keyword `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:4:17 - | -LL | fn foo(&mur Self) {} - | ^^^^ expected identifier, found keyword - error: expected one of `:`, `@`, or `|`, found keyword `Self` --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:4:17 | @@ -17,7 +11,7 @@ LL + fn foo(&mut Self) {} | error: unexpected lifetime `'static` in pattern - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:8:13 + --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:6:13 | LL | fn bar(&'static mur Self) {} | ^^^^^^^ @@ -28,14 +22,8 @@ LL - fn bar(&'static mur Self) {} LL + fn bar(&mur Self) {} | -error: expected identifier, found keyword `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:8:25 - | -LL | fn bar(&'static mur Self) {} - | ^^^^ expected identifier, found keyword - error: expected one of `:`, `@`, or `|`, found keyword `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:8:25 + --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:6:25 | LL | fn bar(&'static mur Self) {} | ^^^^ expected one of `:`, `@`, or `|` @@ -47,7 +35,7 @@ LL + fn bar(&'static mut Self) {} | error: expected one of `:`, `@`, or `|`, found keyword `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:14:17 + --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:10:17 | LL | fn baz(&mur Self @ _) {} | ^^^^ expected one of `:`, `@`, or `|` @@ -58,18 +46,5 @@ LL - fn baz(&mur Self @ _) {} LL + fn baz(&mut Self @ _) {} | -error[E0533]: expected unit struct, found self constructor `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:4:17 - | -LL | fn foo(&mur Self) {} - | ^^^^ not a unit struct - -error[E0533]: expected unit struct, found self constructor `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:8:25 - | -LL | fn bar(&'static mur Self) {} - | ^^^^ not a unit struct - -error: aborting due to 8 previous errors +error: aborting due to 4 previous errors -For more information about this error, try `rustc --explain E0533`. diff --git a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs index 8619856cad670..a92384cce3bfc 100644 --- a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs +++ b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs @@ -2,11 +2,10 @@ //! specifically for `const` items. macro_rules! m { - (const $id:item()) => {} + (const $id:item()) => {}; } m!(const Self()); -//~^ ERROR expected identifier, found keyword `Self` -//~^^ ERROR missing `fn` or `struct` for function or struct definition +//~^ ERROR expected one of `!` or `::`, found `(` fn main() {} diff --git a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr index d412c59c4372a..4b7448458f3ce 100644 --- a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr +++ b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr @@ -1,22 +1,11 @@ -error: expected identifier, found keyword `Self` - --> $DIR/kw-in-const-item-pos-recovery-149692.rs:8:10 +error: expected one of `!` or `::`, found `(` + --> $DIR/kw-in-const-item-pos-recovery-149692.rs:8:14 | -LL | m!(const Self()); - | ^^^^ expected identifier, found keyword - -error: missing `fn` or `struct` for function or struct definition - --> $DIR/kw-in-const-item-pos-recovery-149692.rs:8:10 - | -LL | (const $id:item()) => {} +LL | (const $id:item()) => {}; | -------- while parsing argument for this `item` macro fragment ... LL | m!(const Self()); - | ^^^^ - | -help: if you meant to call a macro, try - | -LL | m!(const Self!()); - | + + | ^ expected one of `!` or `::` -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs index 77372ced09c42..ea14c4252fef1 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs @@ -4,19 +4,16 @@ //! See . macro_rules! m { - ($id:item()) => {} + ($id:item()) => {}; } m!(Self()); -//~^ ERROR expected identifier, found keyword `Self` -//~^^ ERROR missing `fn` or `struct` for function or struct definition +//~^ ERROR expected one of `!` or `::`, found `(` -m!(Self{}); -//~^ ERROR expected identifier, found keyword `Self` -//~^^ ERROR missing `enum` or `struct` for enum or struct definition +m!(Self {}); +//~^ ERROR expected one of `!` or `::`, found `{` m!(crate()); -//~^ ERROR expected identifier, found keyword `crate` -//~^^ ERROR missing `fn` or `struct` for function or struct definition +//~^ ERROR expected one of `!` or `::`, found `(` fn main() {} diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr index 39f3e2d3a9ea5..25f3cdd918bc7 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr @@ -1,57 +1,29 @@ -error: expected identifier, found keyword `Self` - --> $DIR/kw-in-item-pos-recovery-149692.rs:10:4 +error: expected one of `!` or `::`, found `(` + --> $DIR/kw-in-item-pos-recovery-149692.rs:10:8 | -LL | m!(Self()); - | ^^^^ expected identifier, found keyword - -error: missing `fn` or `struct` for function or struct definition - --> $DIR/kw-in-item-pos-recovery-149692.rs:10:4 - | -LL | ($id:item()) => {} +LL | ($id:item()) => {}; | -------- while parsing argument for this `item` macro fragment ... LL | m!(Self()); - | ^^^^ - | -help: if you meant to call a macro, try - | -LL | m!(Self!()); - | + - -error: expected identifier, found keyword `Self` - --> $DIR/kw-in-item-pos-recovery-149692.rs:14:4 - | -LL | m!(Self{}); - | ^^^^ expected identifier, found keyword + | ^ expected one of `!` or `::` -error: missing `enum` or `struct` for enum or struct definition - --> $DIR/kw-in-item-pos-recovery-149692.rs:14:4 +error: expected one of `!` or `::`, found `{` + --> $DIR/kw-in-item-pos-recovery-149692.rs:13:9 | -LL | ($id:item()) => {} +LL | ($id:item()) => {}; | -------- while parsing argument for this `item` macro fragment ... -LL | m!(Self{}); - | ^^^^ - -error: expected identifier, found keyword `crate` - --> $DIR/kw-in-item-pos-recovery-149692.rs:18:4 - | -LL | m!(crate()); - | ^^^^^ expected identifier, found keyword +LL | m!(Self {}); + | ^ expected one of `!` or `::` -error: missing `fn` or `struct` for function or struct definition - --> $DIR/kw-in-item-pos-recovery-149692.rs:18:4 +error: expected one of `!` or `::`, found `(` + --> $DIR/kw-in-item-pos-recovery-149692.rs:16:9 | -LL | ($id:item()) => {} +LL | ($id:item()) => {}; | -------- while parsing argument for this `item` macro fragment ... LL | m!(crate()); - | ^^^^^ - | -help: if you meant to call a macro, try - | -LL | m!(crate!()); - | + + | ^ expected one of `!` or `::` -error: aborting due to 6 previous errors +error: aborting due to 3 previous errors diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs index bd1785ba5b3c1..27bed26b959ce 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs @@ -5,9 +5,8 @@ macro_rules! x { } x! { trait MyTrait { fn bar(c self) } - //~^ ERROR expected identifier, found keyword `self` - //~^^ ERROR expected one of `:`, `@`, or `|`, found keyword `self` - //~^^^ ERROR expected one of `->`, `;`, `where`, or `{`, found `}` + //~^ ERROR expected one of `:`, `@`, or `|`, found keyword `self` + //~| ERROR expected one of `->`, `;`, `where`, or `{`, found `}` } fn main() {} diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr index 3a7e4779aadfb..a27b7a2a7d921 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr @@ -1,9 +1,3 @@ -error: expected identifier, found keyword `self` - --> $DIR/kw-in-item-pos-recovery-151238.rs:7:28 - | -LL | trait MyTrait { fn bar(c self) } - | ^^^^ expected identifier, found keyword - error: expected one of `:`, `@`, or `|`, found keyword `self` --> $DIR/kw-in-item-pos-recovery-151238.rs:7:28 | @@ -24,5 +18,5 @@ LL | trait MyTrait { fn bar(c self) } | | | while parsing this `fn` -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors From 1dd5f239fc3ba53ea36492f4decd11151ad76cae Mon Sep 17 00:00:00 2001 From: Jed McKenna Date: Wed, 18 Nov 2026 15:36:55 +1100 Subject: [PATCH 18/43] Added regression test. --- tests/ui/closures/ref-to-fn-once.rs | 56 +++++++ tests/ui/closures/ref-to-fn-once.stderr | 200 ++++++++++++++++++++++++ 2 files changed, 256 insertions(+) create mode 100644 tests/ui/closures/ref-to-fn-once.rs create mode 100644 tests/ui/closures/ref-to-fn-once.stderr diff --git a/tests/ui/closures/ref-to-fn-once.rs b/tests/ui/closures/ref-to-fn-once.rs new file mode 100644 index 0000000000000..b52552e742189 --- /dev/null +++ b/tests/ui/closures/ref-to-fn-once.rs @@ -0,0 +1,56 @@ +// Regression test for issue: #47648 +//@ edition:2024 + +struct Foo {} + +fn call Foo>(f: F) { + call(&f); + //~^ ERROR expected `FnOnce()` signature, found `&F` +} + +fn async_call Foo>(f: F) { + async_call(&f); + //~^ ERROR the trait bound `&F: AsyncFnOnce()` is not satisfied +} + +fn main() { + let foo = Foo {}; + let once = move || foo; + //~^ ERROR expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` [E0525] + //~| ERROR expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` [E0525] + + call(&once); + call(&mut once); + + let foo = Foo {}; + let once = &move || foo; + //~^ ERROR expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` [E0525] + + call(once); + + let foo = Foo {}; + let once = &mut move || foo; + //~^ ERROR expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` [E0525] + + call(once); + + let foo = Foo {}; + let async_once = async move || foo; + //~^ ERROR expected a closure that implements the `AsyncFn` trait, but this closure only implements `AsyncFnOnce` [E0525] + //~| ERROR expected a closure that implements the `AsyncFnMut` trait, but this closure only implements `AsyncFnOnce` [E0525] + + async_call(&async_once); + async_call(&mut async_once); + + let foo = Foo {}; + let async_once = &async move || foo; + //~^ ERROR expected a closure that implements the `AsyncFn` trait, but this closure only implements `AsyncFnOnce` [E0525] + + async_call(async_once); + + let foo = Foo {}; + let async_once = &mut async move || foo; + //~^ ERROR expected a closure that implements the `AsyncFnMut` trait, but this closure only implements `AsyncFnOnce` [E0525] + + async_call(async_once); +} diff --git a/tests/ui/closures/ref-to-fn-once.stderr b/tests/ui/closures/ref-to-fn-once.stderr new file mode 100644 index 0000000000000..74af1d3fad888 --- /dev/null +++ b/tests/ui/closures/ref-to-fn-once.stderr @@ -0,0 +1,200 @@ +error[E0277]: expected `FnOnce()` signature, found `&F` + --> $DIR/ref-to-fn-once.rs:7:11 + | +LL | call(&f); + | ---- ^ expected `FnOnce()` signature, found `&F` + | | + | required by a bound introduced by this call + | + = note: wrap the `&F` in a closure with no arguments: `|| { /* code */ }` + = note: `F` implements `FnOnce`, but it must implement `Fn`, which is more general + = note: required for `&F` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:6:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` + +error[E0277]: the trait bound `&F: AsyncFnOnce()` is not satisfied + --> $DIR/ref-to-fn-once.rs:12:17 + | +LL | async_call(&f); + | ---------- ^ the trait `AsyncFn()` is not implemented for `F` + | | + | required by a bound introduced by this call + | + = note: required for `&F` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:11:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` +help: consider further restricting type parameter `F` with trait `AsyncFn` + | +LL | fn async_call Foo + AsyncFn()>(f: F) { + | +++++++++++ + +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` + --> $DIR/ref-to-fn-once.rs:18:16 + | +LL | let once = move || foo; + | ^^^^^^^ --- closure is `FnOnce` because it moves the variable `foo` out of its environment + | | + | this closure implements `FnOnce`, not `Fn` +... +LL | call(&once); + | ---- ---- the requirement to implement `Fn` derives from here + | | + | required by a bound introduced by this call + | + = note: required for `&{closure@$DIR/ref-to-fn-once.rs:18:16: 18:23}` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:6:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` + +error[E0525]: expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` + --> $DIR/ref-to-fn-once.rs:18:16 + | +LL | let once = move || foo; + | ^^^^^^^ --- closure is `FnOnce` because it moves the variable `foo` out of its environment + | | + | this closure implements `FnOnce`, not `FnMut` +... +LL | call(&mut once); + | ---- ---- the requirement to implement `FnMut` derives from here + | | + | required by a bound introduced by this call + | + = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:18:16: 18:23}` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:6:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` + +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` + --> $DIR/ref-to-fn-once.rs:26:17 + | +LL | let once = &move || foo; + | ^^^^^^^ --- closure is `FnOnce` because it moves the variable `foo` out of its environment + | | + | this closure implements `FnOnce`, not `Fn` +... +LL | call(once); + | ---- ---- the requirement to implement `Fn` derives from here + | | + | required by a bound introduced by this call + | + = note: required for `&{closure@$DIR/ref-to-fn-once.rs:26:17: 26:24}` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:6:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` + +error[E0525]: expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` + --> $DIR/ref-to-fn-once.rs:32:21 + | +LL | let once = &mut move || foo; + | ^^^^^^^ --- closure is `FnOnce` because it moves the variable `foo` out of its environment + | | + | this closure implements `FnOnce`, not `FnMut` +... +LL | call(once); + | ---- ---- the requirement to implement `FnMut` derives from here + | | + | required by a bound introduced by this call + | + = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:32:21: 32:28}` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:6:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` + +error[E0525]: expected a closure that implements the `AsyncFn` trait, but this closure only implements `AsyncFnOnce` + --> $DIR/ref-to-fn-once.rs:38:22 + | +LL | let async_once = async move || foo; + | ^^^^^^^^^^^^^ --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment + | | + | this closure implements `AsyncFnOnce`, not `AsyncFn` +... +LL | async_call(&async_once); + | ---------- ----------- the requirement to implement `AsyncFn` derives from here + | | + | required by a bound introduced by this call + | + = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:38:22: 38:35}` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:11:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` + +error[E0525]: expected a closure that implements the `AsyncFnMut` trait, but this closure only implements `AsyncFnOnce` + --> $DIR/ref-to-fn-once.rs:38:22 + | +LL | let async_once = async move || foo; + | ^^^^^^^^^^^^^ --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment + | | + | this closure implements `AsyncFnOnce`, not `AsyncFnMut` +... +LL | async_call(&mut async_once); + | ---------- --------------- the requirement to implement `AsyncFnMut` derives from here + | | + | required by a bound introduced by this call + | + = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:38:22: 38:35}` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:11:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` + +error[E0525]: expected a closure that implements the `AsyncFn` trait, but this closure only implements `AsyncFnOnce` + --> $DIR/ref-to-fn-once.rs:46:23 + | +LL | let async_once = &async move || foo; + | ^^^^^^^^^^^^^ --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment + | | + | this closure implements `AsyncFnOnce`, not `AsyncFn` +... +LL | async_call(async_once); + | ---------- ---------- the requirement to implement `AsyncFn` derives from here + | | + | required by a bound introduced by this call + | + = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:46:23: 46:36}` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:11:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` + +error[E0525]: expected a closure that implements the `AsyncFnMut` trait, but this closure only implements `AsyncFnOnce` + --> $DIR/ref-to-fn-once.rs:52:27 + | +LL | let async_once = &mut async move || foo; + | ^^^^^^^^^^^^^ --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment + | | + | this closure implements `AsyncFnOnce`, not `AsyncFnMut` +... +LL | async_call(async_once); + | ---------- ---------- the requirement to implement `AsyncFnMut` derives from here + | | + | required by a bound introduced by this call + | + = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:52:27: 52:40}` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:11:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` + +error: aborting due to 10 previous errors + +Some errors have detailed explanations: E0277, E0525. +For more information about an error, try `rustc --explain E0277`. From dd1ab82f7d5edb73b765c53f2957c63d01da22a2 Mon Sep 17 00:00:00 2001 From: Jed McKenna Date: Fri, 30 Oct 2026 21:24:26 +1100 Subject: [PATCH 19/43] Added TyCtx conveiniance method for getting the closure kind of a maybe async closure from DefId. Added conveiniance method for getting trait prefix from Asyncness. --- compiler/rustc_middle/src/middle/lang_items.rs | 18 +++++++++++++++++- compiler/rustc_middle/src/ty/mod.rs | 8 ++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/middle/lang_items.rs b/compiler/rustc_middle/src/middle/lang_items.rs index 9d07c2edeb386..85b1150bc96c5 100644 --- a/compiler/rustc_middle/src/middle/lang_items.rs +++ b/compiler/rustc_middle/src/middle/lang_items.rs @@ -12,7 +12,7 @@ use rustc_hir::def_id::DefId; use rustc_span::Span; use rustc_target::spec::PanicStrategy; -use crate::ty::{self, TyCtxt}; +use crate::ty::{self, Asyncness, TyCtxt}; impl<'tcx> TyCtxt<'tcx> { /// Returns the `DefId` for a given `LangItem`. @@ -44,6 +44,22 @@ impl<'tcx> TyCtxt<'tcx> { } } + /// Given a [`DefId`] of one of the [`Fn`], [`FnMut`], [`FnOnce`], [`AsyncFn`], [`AsyncFnMut`], or [`AsyncFnOnce`] traits, + /// returns a corresponding [`ty::ClosureKind`] and [`Asyncness`]. + /// For any other [`DefId`] return `None`. + pub fn maybe_async_fn_trait_kind_from_def_id( + self, + id: DefId, + ) -> Option<(Asyncness, ty::ClosureKind)> { + if let Some(kind) = self.fn_trait_kind_from_def_id(id) { + Some((Asyncness::No, kind)) + } else if let Some(kind) = self.async_fn_trait_kind_from_def_id(id) { + Some((Asyncness::Yes, kind)) + } else { + return None; + } + } + /// Given a [`DefId`] of one of the `AsyncFn`, `AsyncFnMut` or `AsyncFnOnce` traits, /// returns a corresponding [`ty::ClosureKind`]. /// For any other [`DefId`] return `None`. diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index e6321fadd0701..b2215b40c4e87 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -243,6 +243,14 @@ impl Asyncness { pub fn is_async(self) -> bool { matches!(self, Asyncness::Yes) } + + /// Returns "Async" if [`Self::Yes`], otherwise returns an empty string slice. + pub fn as_trait_prefix_str(&self) -> &'static str { + match self { + Asyncness::Yes => "Async", + Asyncness::No => "", + } + } } #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, BlobDecodable, StableHash)] From c510c13b61478831fb0a7114c9125396e2081f4d Mon Sep 17 00:00:00 2001 From: Jed McKenna Date: Fri, 30 Oct 2026 21:26:59 +1100 Subject: [PATCH 20/43] Added new clearer error messages when when &FnOnce was provided when FnOnce was expected in function arguments. Blessed `ref-to-fn-once.rs` with new output. Refactored emit_specialized_closure_kind_error to use new convenience methods and slightly stronger typing. accepted changes for test --- .../rustc_trait_selection/src/diagnostics.rs | 13 ++ .../traits/fulfillment_errors.rs | 107 +++++++++--- tests/ui/closures/ref-to-fn-once.rs | 20 ++- tests/ui/closures/ref-to-fn-once.stderr | 160 ++++++++++-------- 4 files changed, 197 insertions(+), 103 deletions(-) diff --git a/compiler/rustc_trait_selection/src/diagnostics.rs b/compiler/rustc_trait_selection/src/diagnostics.rs index 7eacbebc091dd..13bac0d6266cd 100644 --- a/compiler/rustc_trait_selection/src/diagnostics.rs +++ b/compiler/rustc_trait_selection/src/diagnostics.rs @@ -141,6 +141,19 @@ pub(crate) struct ClosureKindMismatch { pub fn_mut_label: Option, } +#[derive(Diagnostic)] +#[diag("expected `{$trait_prefix}FnOnce`, found reference", code = E0525)] +#[note("`{$trait_prefix}FnOnce` isn't implemented for references")] +pub(crate) struct RefToFnOnce { + #[primary_span] + #[label("closure passed by reference here")] + pub cause_span: Span, + pub trait_prefix: &'static str, + + #[subdiagnostic] + pub fn_once_label: Option, +} + #[derive(Subdiagnostic)] #[label( "closure is `{$trait_prefix}FnOnce` because it moves the variable `{$place}` out of its environment" diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index ca68ee77d67b3..3c9e23128ce9e 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -43,7 +43,7 @@ use super::suggestions::get_explanation_based_on_obligation; use super::{ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate}; use crate::diagnostics::{ AssocTypeWithSameName, ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, - CoroClosureNotFn, + CoroClosureNotFn, RefToFnOnce, }; use crate::error_reporting::TypeErrCtxt; use crate::error_reporting::infer::TyCategory; @@ -1060,17 +1060,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let self_ty = if is_ref_to_closure { peeled_self_ty } else { original_self_ty }; - let (expected_kind, is_async) = - if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) { - (expected_kind, false) - } else if let Some(expected_kind) = - self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id()) - { - (expected_kind, true) - } else { - return None; - }; - let trait_prefix = if is_async { "Async" } else { "" }; + let (asyncness, expected_kind) = + self.tcx.maybe_async_fn_trait_kind_from_def_id(trait_pred.def_id())?; + + let trait_prefix = asyncness.as_trait_prefix_str(); let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() { ty::Closure(def_id, args) => { @@ -1104,7 +1097,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if found_kind.is_none() && is_ref_to_closure - && !is_async + && !asyncness.is_async() && let Some(local_def_id) = closure_def_id.as_local() && let Some((inferred_kind, origin)) = (self.infer_closure_kind)(local_def_id) { @@ -1112,6 +1105,31 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { kind_origin = origin; } + let (_, root_trait_pred) = obligation.cause.code().peel_derives_with_predicate(); + let root_expected = root_trait_pred + .and_then(|pred| self.tcx.maybe_async_fn_trait_kind_from_def_id(pred.def_id())); + + // Prevent confusing errors when `&FnOnce` was provided when `FnOnce` was expected + // in function arguments + if let ty::ClosureKind::Fn | ty::ClosureKind::FnMut = expected_kind + && let Some(ty::ClosureKind::FnOnce) = found_kind + && let Some((root_asyncness, ty::ClosureKind::FnOnce)) = root_expected + && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() + && let arg = self.tcx.hir_expect_expr(*arg_hir_id) + && asyncness == root_asyncness + { + let mut err = self.report_ref_to_fn_once_error( + closure_def_id, + trait_prefix, + kind_origin, + arg.span, + ); + + self.suggest_remove_ref_for_closure(&mut err, obligation); + self.note_obligation_cause(&mut err, obligation); + return Some(err.emit_err()); + } + if let Some(found_kind) = found_kind && !found_kind.extends(expected_kind) { @@ -1123,7 +1141,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { trait_prefix, kind_origin, ); - self.suggest_change_mut_ref_for_closure(&mut err, &obligation); + + self.suggest_change_mut_ref_for_closure(&mut err, obligation); self.note_obligation_cause(&mut err, &obligation); return Some(err.emit_err()); } @@ -3127,6 +3146,26 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } + fn suggest_remove_ref_for_closure( + &self, + err: &mut Diag<'_>, + obligation: &PredicateObligation<'tcx>, + ) { + if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() + && let (_, Some(root_trait_pred)) = + obligation.cause.code().peel_derives_with_predicate() + && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) + && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, _) = arg.kind + { + let mut obligation = obligation.clone(); + // Error reporting may narrow the cause span to the borrow's operand. + // Use the whole argument so `suggest_remove_reference` can replace the borrow. + obligation.cause.span = arg.span; + + self.suggest_remove_reference(&obligation, err, root_trait_pred); + } + } + /// Register when multiple obligations come from the same statement and only emit one. /// /// This can significantly reduce the number of `_: Sized` failures on method chains. @@ -3675,6 +3714,38 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } + fn infer_closure_origin( + &self, + closure_def_id: DefId, + ) -> Option<(Span, rustc_middle::hir::place::Place<'tcx>)> { + let typeck_results = self.typeck_results.as_ref()?; + let local_def_id = closure_def_id.as_local()?; + let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id); + typeck_results.closure_kind_origins().get(hir_id).cloned() + } + + fn report_ref_to_fn_once_error( + &self, + closure_def_id: DefId, + trait_prefix: &'static str, + kind_origin: Option<(Span, rustc_middle::hir::place::Place<'tcx>)>, + cause_span: Span, + ) -> Diag<'a> { + let origin = kind_origin.or_else(|| self.infer_closure_origin(closure_def_id)); + + let err = RefToFnOnce { + cause_span, + trait_prefix, + fn_once_label: origin.map(|(span, place)| ClosureFnOnceLabel { + span, + place: ty::place_to_string_for_capture(self.tcx, &place), + trait_prefix, + }), + }; + + self.dcx().create_err(err) + } + fn report_closure_error( &self, obligation: &PredicateObligation<'tcx>, @@ -3698,12 +3769,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // Additional context information explaining why the closure only implements // a particular trait. - let origin = kind_origin.or_else(|| { - let typeck_results = self.typeck_results.as_ref()?; - let local_def_id = closure_def_id.as_local()?; - let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id); - typeck_results.closure_kind_origins().get(hir_id).cloned() - }); + let origin = kind_origin.or_else(|| self.infer_closure_origin(closure_def_id)); match (found_kind, origin) { (ty::ClosureKind::FnOnce, Some((span, place))) => { @@ -3722,6 +3788,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } _ => {} } + self.dcx().create_err(err) } diff --git a/tests/ui/closures/ref-to-fn-once.rs b/tests/ui/closures/ref-to-fn-once.rs index b52552e742189..383920768decb 100644 --- a/tests/ui/closures/ref-to-fn-once.rs +++ b/tests/ui/closures/ref-to-fn-once.rs @@ -1,4 +1,6 @@ -// Regression test for issue: #47648 +// Provide clear diagnostics when `&FnOnce` was provided +// when `FnOnce` was expected in function arguments. +// Related issue: #47648 //@ edition:2024 struct Foo {} @@ -16,41 +18,41 @@ fn async_call Foo>(f: F) { fn main() { let foo = Foo {}; let once = move || foo; - //~^ ERROR expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` [E0525] - //~| ERROR expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` [E0525] call(&once); + //~^ ERROR expected `FnOnce`, found reference [E0525] call(&mut once); + //~^ ERROR expected `FnOnce`, found reference [E0525] let foo = Foo {}; let once = &move || foo; - //~^ ERROR expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` [E0525] call(once); + //~^ ERROR expected `FnOnce`, found reference [E0525] let foo = Foo {}; let once = &mut move || foo; - //~^ ERROR expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` [E0525] call(once); + //~^ ERROR expected `FnOnce`, found reference [E0525] let foo = Foo {}; let async_once = async move || foo; - //~^ ERROR expected a closure that implements the `AsyncFn` trait, but this closure only implements `AsyncFnOnce` [E0525] - //~| ERROR expected a closure that implements the `AsyncFnMut` trait, but this closure only implements `AsyncFnOnce` [E0525] async_call(&async_once); + //~^ ERROR expected `AsyncFnOnce`, found reference [E0525] async_call(&mut async_once); + //~^ ERROR expected `AsyncFnOnce`, found reference [E0525] let foo = Foo {}; let async_once = &async move || foo; - //~^ ERROR expected a closure that implements the `AsyncFn` trait, but this closure only implements `AsyncFnOnce` [E0525] async_call(async_once); + //~^ ERROR expected `AsyncFnOnce`, found reference [E0525] let foo = Foo {}; let async_once = &mut async move || foo; - //~^ ERROR expected a closure that implements the `AsyncFnMut` trait, but this closure only implements `AsyncFnOnce` [E0525] async_call(async_once); + //~^ ERROR expected `AsyncFnOnce`, found reference [E0525] } diff --git a/tests/ui/closures/ref-to-fn-once.stderr b/tests/ui/closures/ref-to-fn-once.stderr index 74af1d3fad888..c8753f44f71ff 100644 --- a/tests/ui/closures/ref-to-fn-once.stderr +++ b/tests/ui/closures/ref-to-fn-once.stderr @@ -1,5 +1,5 @@ error[E0277]: expected `FnOnce()` signature, found `&F` - --> $DIR/ref-to-fn-once.rs:7:11 + --> $DIR/ref-to-fn-once.rs:9:11 | LL | call(&f); | ---- ^ expected `FnOnce()` signature, found `&F` @@ -10,13 +10,13 @@ LL | call(&f); = note: `F` implements `FnOnce`, but it must implement `Fn`, which is more general = note: required for `&F` to implement `FnOnce()` note: required by a bound in `call` - --> $DIR/ref-to-fn-once.rs:6:12 + --> $DIR/ref-to-fn-once.rs:8:12 | LL | fn call Foo>(f: F) { | ^^^^^^^^^^^^^^^ required by this bound in `call` error[E0277]: the trait bound `&F: AsyncFnOnce()` is not satisfied - --> $DIR/ref-to-fn-once.rs:12:17 + --> $DIR/ref-to-fn-once.rs:14:17 | LL | async_call(&f); | ---------- ^ the trait `AsyncFn()` is not implemented for `F` @@ -25,7 +25,7 @@ LL | async_call(&f); | = note: required for `&F` to implement `AsyncFnOnce()` note: required by a bound in `async_call` - --> $DIR/ref-to-fn-once.rs:11:18 + --> $DIR/ref-to-fn-once.rs:13:18 | LL | fn async_call Foo>(f: F) { | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` @@ -34,162 +34,174 @@ help: consider further restricting type parameter `F` with trait `AsyncFn` LL | fn async_call Foo + AsyncFn()>(f: F) { | +++++++++++ -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` - --> $DIR/ref-to-fn-once.rs:18:16 +error[E0525]: expected `FnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:22:10 | LL | let once = move || foo; - | ^^^^^^^ --- closure is `FnOnce` because it moves the variable `foo` out of its environment - | | - | this closure implements `FnOnce`, not `Fn` -... + | --- closure is `FnOnce` because it moves the variable `foo` out of its environment +LL | LL | call(&once); - | ---- ---- the requirement to implement `Fn` derives from here + | ---- ^^^^^ closure passed by reference here | | | required by a bound introduced by this call | - = note: required for `&{closure@$DIR/ref-to-fn-once.rs:18:16: 18:23}` to implement `FnOnce()` + = note: `FnOnce` isn't implemented for references + = note: required for `&{closure@$DIR/ref-to-fn-once.rs:20:16: 20:23}` to implement `FnOnce()` note: required by a bound in `call` - --> $DIR/ref-to-fn-once.rs:6:12 + --> $DIR/ref-to-fn-once.rs:8:12 | LL | fn call Foo>(f: F) { | ^^^^^^^^^^^^^^^ required by this bound in `call` +help: consider removing the leading `&`-reference + | +LL - call(&once); +LL + call(once); + | -error[E0525]: expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` - --> $DIR/ref-to-fn-once.rs:18:16 +error[E0525]: expected `FnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:24:10 | LL | let once = move || foo; - | ^^^^^^^ --- closure is `FnOnce` because it moves the variable `foo` out of its environment - | | - | this closure implements `FnOnce`, not `FnMut` + | --- closure is `FnOnce` because it moves the variable `foo` out of its environment ... LL | call(&mut once); - | ---- ---- the requirement to implement `FnMut` derives from here + | ---- ^^^^^^^^^ closure passed by reference here | | | required by a bound introduced by this call | - = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:18:16: 18:23}` to implement `FnOnce()` + = note: `FnOnce` isn't implemented for references + = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:20:16: 20:23}` to implement `FnOnce()` note: required by a bound in `call` - --> $DIR/ref-to-fn-once.rs:6:12 + --> $DIR/ref-to-fn-once.rs:8:12 | LL | fn call Foo>(f: F) { | ^^^^^^^^^^^^^^^ required by this bound in `call` +help: consider removing the leading `&`-reference + | +LL - call(&mut once); +LL + call(once); + | -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` - --> $DIR/ref-to-fn-once.rs:26:17 +error[E0525]: expected `FnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:30:10 | LL | let once = &move || foo; - | ^^^^^^^ --- closure is `FnOnce` because it moves the variable `foo` out of its environment - | | - | this closure implements `FnOnce`, not `Fn` -... + | --- closure is `FnOnce` because it moves the variable `foo` out of its environment +LL | LL | call(once); - | ---- ---- the requirement to implement `Fn` derives from here + | ---- ^^^^ closure passed by reference here | | | required by a bound introduced by this call | - = note: required for `&{closure@$DIR/ref-to-fn-once.rs:26:17: 26:24}` to implement `FnOnce()` + = note: `FnOnce` isn't implemented for references + = note: required for `&{closure@$DIR/ref-to-fn-once.rs:28:17: 28:24}` to implement `FnOnce()` note: required by a bound in `call` - --> $DIR/ref-to-fn-once.rs:6:12 + --> $DIR/ref-to-fn-once.rs:8:12 | LL | fn call Foo>(f: F) { | ^^^^^^^^^^^^^^^ required by this bound in `call` -error[E0525]: expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` - --> $DIR/ref-to-fn-once.rs:32:21 +error[E0525]: expected `FnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:36:10 | LL | let once = &mut move || foo; - | ^^^^^^^ --- closure is `FnOnce` because it moves the variable `foo` out of its environment - | | - | this closure implements `FnOnce`, not `FnMut` -... + | --- closure is `FnOnce` because it moves the variable `foo` out of its environment +LL | LL | call(once); - | ---- ---- the requirement to implement `FnMut` derives from here + | ---- ^^^^ closure passed by reference here | | | required by a bound introduced by this call | - = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:32:21: 32:28}` to implement `FnOnce()` + = note: `FnOnce` isn't implemented for references + = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:34:21: 34:28}` to implement `FnOnce()` note: required by a bound in `call` - --> $DIR/ref-to-fn-once.rs:6:12 + --> $DIR/ref-to-fn-once.rs:8:12 | LL | fn call Foo>(f: F) { | ^^^^^^^^^^^^^^^ required by this bound in `call` -error[E0525]: expected a closure that implements the `AsyncFn` trait, but this closure only implements `AsyncFnOnce` - --> $DIR/ref-to-fn-once.rs:38:22 +error[E0525]: expected `AsyncFnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:42:16 | LL | let async_once = async move || foo; - | ^^^^^^^^^^^^^ --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment - | | - | this closure implements `AsyncFnOnce`, not `AsyncFn` -... + | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment +LL | LL | async_call(&async_once); - | ---------- ----------- the requirement to implement `AsyncFn` derives from here + | ---------- ^^^^^^^^^^^ closure passed by reference here | | | required by a bound introduced by this call | - = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:38:22: 38:35}` to implement `AsyncFnOnce()` + = note: `AsyncFnOnce` isn't implemented for references + = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:40:22: 40:35}` to implement `AsyncFnOnce()` note: required by a bound in `async_call` - --> $DIR/ref-to-fn-once.rs:11:18 + --> $DIR/ref-to-fn-once.rs:13:18 | LL | fn async_call Foo>(f: F) { | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` +help: consider removing the leading `&`-reference + | +LL - async_call(&async_once); +LL + async_call(async_once); + | -error[E0525]: expected a closure that implements the `AsyncFnMut` trait, but this closure only implements `AsyncFnOnce` - --> $DIR/ref-to-fn-once.rs:38:22 +error[E0525]: expected `AsyncFnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:44:16 | LL | let async_once = async move || foo; - | ^^^^^^^^^^^^^ --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment - | | - | this closure implements `AsyncFnOnce`, not `AsyncFnMut` + | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment ... LL | async_call(&mut async_once); - | ---------- --------------- the requirement to implement `AsyncFnMut` derives from here + | ---------- ^^^^^^^^^^^^^^^ closure passed by reference here | | | required by a bound introduced by this call | - = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:38:22: 38:35}` to implement `AsyncFnOnce()` + = note: `AsyncFnOnce` isn't implemented for references + = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:40:22: 40:35}` to implement `AsyncFnOnce()` note: required by a bound in `async_call` - --> $DIR/ref-to-fn-once.rs:11:18 + --> $DIR/ref-to-fn-once.rs:13:18 | LL | fn async_call Foo>(f: F) { | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` +help: consider removing the leading `&`-reference + | +LL - async_call(&mut async_once); +LL + async_call(async_once); + | -error[E0525]: expected a closure that implements the `AsyncFn` trait, but this closure only implements `AsyncFnOnce` - --> $DIR/ref-to-fn-once.rs:46:23 +error[E0525]: expected `AsyncFnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:50:16 | LL | let async_once = &async move || foo; - | ^^^^^^^^^^^^^ --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment - | | - | this closure implements `AsyncFnOnce`, not `AsyncFn` -... + | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment +LL | LL | async_call(async_once); - | ---------- ---------- the requirement to implement `AsyncFn` derives from here + | ---------- ^^^^^^^^^^ closure passed by reference here | | | required by a bound introduced by this call | - = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:46:23: 46:36}` to implement `AsyncFnOnce()` + = note: `AsyncFnOnce` isn't implemented for references + = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:48:23: 48:36}` to implement `AsyncFnOnce()` note: required by a bound in `async_call` - --> $DIR/ref-to-fn-once.rs:11:18 + --> $DIR/ref-to-fn-once.rs:13:18 | LL | fn async_call Foo>(f: F) { | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` -error[E0525]: expected a closure that implements the `AsyncFnMut` trait, but this closure only implements `AsyncFnOnce` - --> $DIR/ref-to-fn-once.rs:52:27 +error[E0525]: expected `AsyncFnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:56:16 | LL | let async_once = &mut async move || foo; - | ^^^^^^^^^^^^^ --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment - | | - | this closure implements `AsyncFnOnce`, not `AsyncFnMut` -... + | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment +LL | LL | async_call(async_once); - | ---------- ---------- the requirement to implement `AsyncFnMut` derives from here + | ---------- ^^^^^^^^^^ closure passed by reference here | | | required by a bound introduced by this call | - = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:52:27: 52:40}` to implement `AsyncFnOnce()` + = note: `AsyncFnOnce` isn't implemented for references + = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:54:27: 54:40}` to implement `AsyncFnOnce()` note: required by a bound in `async_call` - --> $DIR/ref-to-fn-once.rs:11:18 + --> $DIR/ref-to-fn-once.rs:13:18 | LL | fn async_call Foo>(f: F) { | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` From c657c93d5d67e7b9d4cb30f264c7bb019f4e241e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 18 Nov 2026 11:50:57 +0100 Subject: [PATCH 21/43] Move the publish logic into a separate Bash file --- .github/workflows/post-merge.yml | 47 ++----------------------- src/ci/publish_backtrace.sh | 60 ++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 44 deletions(-) create mode 100755 src/ci/publish_backtrace.sh diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.yml index 87a5eb8603fe2..f47d490839f88 100644 --- a/.github/workflows/post-merge.yml +++ b/.github/workflows/post-merge.yml @@ -69,54 +69,13 @@ jobs: - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 id: auth - run: | - set -eux -o pipefail - # Give GitHub some time to propagate the information that the PR was merged sleep 60 - # Find PR for the current commit - HEAD_PR=$(gh pr list --search "${GITHUB_SHA}" --state merged --json number --jq '.[0].number') - if [ -z "${HEAD_PR}" ]; then - echo "PR for commit SHA ${GITHUB_SHA} not found, exiting" - exit 1 - fi - echo "HEAD: ${GITHUB_SHA} (#${HEAD_PR})" - - git submodule update --init library/backtrace - cd library/backtrace - - VERSION=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "backtrace") | .version') - CRATE=backtrace - - # Check if the version exists on crates.io already with a HEAD request to the CDN - code=$(curl --head --silent -o /dev/null --write-out '%{http_code}' "https://static.crates.io/crates/${CRATE}/${CRATE}-${VERSION}.crate") - - # If the crate version already exists, then there is nothing left to do - if [[ $code == 200 ]]; then - exit 0 - fi - - set +e - cargo publish --locked &> ${RUNNER_TEMP}/cargo-log.txt - STATUS=$? - set -e - - COMMENT_FILE=${RUNNER_TEMP}/comment.txt - - if [[ ${STATUS} == 0 ]]; then - echo "backtrace \`${VERSION}\` published to crates.io" > ${COMMENT_FILE} - else - echo "backtrace \`${VERSION}\` could not be published to crates.io" > ${COMMENT_FILE} - printf "
\nCargo publish log\n\n" >> ${COMMENT_FILE} - printf '```\n' >> ${COMMENT_FILE} - cat "${RUNNER_TEMP}/cargo-log.txt" >> ${COMMENT_FILE} - printf '\n```\n' >> ${COMMENT_FILE} - printf "
\n\n" >> ${COMMENT_FILE} - fi - - gh pr comment "${HEAD_PR}" -F ${COMMENT_FILE} - exit "${STATUS}" + # Publish backtrace + ./src/ci/publish_backtrace.sh env: CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} GH_TOKEN: ${{ github.token }} GITHUB_SHA: ${{ github.sha }} + TEMPDIR: ${{ runner.temp }} diff --git a/src/ci/publish_backtrace.sh b/src/ci/publish_backtrace.sh new file mode 100755 index 0000000000000..b801943415daa --- /dev/null +++ b/src/ci/publish_backtrace.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +# Publish the backtrace crate to crates.io +# Should be called from the a CI workflow +# Expects the following environment variables as input: +# - GITHUB_SHA: SHA of the currently merged commit from which backtrace should be published +# - TEMPDIR: scratch directory for temporary files + +set -eux pipefail + +# Find PR for the current commit +HEAD_PR=$(gh pr list --search "${GITHUB_SHA}" --state merged --json number --jq '.[0].number') +if [ -z "${HEAD_PR}" ]; then + echo "PR for commit SHA ${GITHUB_SHA} not found, exiting" + exit 1 +fi +echo "HEAD: ${GITHUB_SHA} (#${HEAD_PR})" + +git submodule update --init library/backtrace +cd library/backtrace + +# Find the version of backtrace +VERSION=$( + cargo metadata --no-deps --format-version 1 | + jq -r '.packages[] | select(.name == "backtrace") | .version' +) +CRATE=backtrace + +# Check if the version exists on crates.io already with a HEAD request to the CDN +code=$( + curl --head --silent -o /dev/null --write-out '%{http_code}' \ + "https://static.crates.io/crates/${CRATE}/${CRATE}-${VERSION}.crate" +) + +# If the crate version already exists, then there is nothing left to do +if [[ $code == 200 ]]; then + exit 0 +fi + +set +e +cargo publish --locked &> "${TEMPDIR}"/cargo-log.txt +STATUS=$? +set -e + +COMMENT_FILE=${TEMPDIR}/comment.txt + +if [[ ${STATUS} == 0 ]]; then + echo "backtrace \`${VERSION}\` published to crates.io" > "${COMMENT_FILE}" +else + echo "backtrace \`${VERSION}\` could not be published to crates.io" > "${COMMENT_FILE}" + printf "
\nCargo publish log\n\n" >> "${COMMENT_FILE}" + printf '```\n' >> "${COMMENT_FILE}" + cat "${RUNNER_TEMP}/cargo-log.txt" >> "${COMMENT_FILE}" + printf '\n```\n' >> "${COMMENT_FILE}" + printf "
\n\n" >> "${COMMENT_FILE}" +fi + +# Comment on the PR to let it know how it went +gh pr comment "${HEAD_PR}" -F "${COMMENT_FILE}" +exit "${STATUS}" From ad4be697652b21c629267ad9a82f8fc58e504df1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Rakic?= Date: Wed, 18 Nov 2026 16:10:57 +0100 Subject: [PATCH 22/43] bump some tools `toml` dependency This reduces the number of duplicate versions of toml, toml-edit, winnow, etc crates. --- Cargo.lock | 40 +++-------------------------- src/tools/build-manifest/Cargo.toml | 2 +- src/tools/tidy/Cargo.toml | 2 +- 3 files changed, 5 insertions(+), 39 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 73c3f74ce348f..ba20bd1649b11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -360,7 +360,7 @@ dependencies = [ "serde_json", "sha2", "tar", - "toml 0.7.8", + "toml 0.8.23", "xz2", ] @@ -5830,7 +5830,7 @@ dependencies = [ "similar", "tempfile", "termcolor", - "toml 0.7.8", + "toml 0.8.23", "walkdir", ] @@ -5874,18 +5874,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" -[[package]] -name = "toml" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd79e69d3b627db300ff956027cc6c3798cef26d22526befdfcd12feeb6d2257" -dependencies = [ - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.11", - "toml_edit 0.19.15", -] - [[package]] name = "toml" version = "0.8.23" @@ -5895,7 +5883,7 @@ dependencies = [ "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.11", - "toml_edit 0.22.27", + "toml_edit", ] [[package]] @@ -5931,19 +5919,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap", - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.11", - "winnow 0.5.40", -] - [[package]] name = "toml_edit" version = "0.22.27" @@ -6826,15 +6801,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "winnow" -version = "0.5.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" -dependencies = [ - "memchr", -] - [[package]] name = "winnow" version = "0.7.13" diff --git a/src/tools/build-manifest/Cargo.toml b/src/tools/build-manifest/Cargo.toml index 0900afd6594fe..dca1d01221563 100644 --- a/src/tools/build-manifest/Cargo.toml +++ b/src/tools/build-manifest/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -toml = "0.7" +toml = "0.8" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" anyhow = "1.0.32" diff --git a/src/tools/tidy/Cargo.toml b/src/tools/tidy/Cargo.toml index 4b38f9479fbc6..e452be545e508 100644 --- a/src/tools/tidy/Cargo.toml +++ b/src/tools/tidy/Cargo.toml @@ -17,7 +17,7 @@ serde = { version = "1.0.125", features = ["derive"], optional = true } termcolor = "1.1.3" rustc-hash = "2.0.0" similar = "2.5.0" -toml = "0.7.8" +toml = "0.8" tempfile = "3.15.0" clap = "4.5.54" From bb05ffd5fac77857f7ea21c06e526b4a6ec9a934 Mon Sep 17 00:00:00 2001 From: Tess4552 Date: Mon, 26 Oct 2026 14:47:24 +0100 Subject: [PATCH 23/43] reflection: doc attributes from adts, fields, and variants --- .../src/const_eval/machine.rs | 44 +++++++++++++ .../src/const_eval/type_info.rs | 43 ++++++++++++- .../rustc_hir_analysis/src/check/intrinsic.rs | 22 +++++++ compiler/rustc_span/src/symbol.rs | 2 + library/core/src/intrinsics/reflection.rs | 21 +++++++ library/core/src/mem/type_info.rs | 63 +++++++++++++++++++ library/coretests/tests/mem/type_info.rs | 39 ++++++++++++ .../auxiliary/const-eval-doc-attrs.rs | 19 ++++++ tests/ui/intrinsics/const-eval-doc-attrs.rs | 20 ++++++ 9 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 tests/ui/intrinsics/auxiliary/const-eval-doc-attrs.rs create mode 100644 tests/ui/intrinsics/const-eval-doc-attrs.rs diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 3e6329cfe0a12..11e463727d838 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -838,6 +838,50 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { }; } + sym::type_id_docs => { + let ty = ecx.read_type_id(&args[0])?; + let attrs = match ty.kind() { + ty::Adt(def, args) + if let Some(FieldInfo { base, variant_idx, field_idx, .. }) = + def.field_representing_type_info(ecx.tcx(), *args) => + { + match base.kind() { + ty::Adt(base_def, _) => { + let field = &base_def.variants()[variant_idx].fields[field_idx]; + Some(field.did) + } + ty::Tuple(_) => None, + _ => { + // only adts and tuples have fields + span_bug!(ecx.cur_span(), "expected adt or tuple type, got {ty}"); + } + } + } + ty::Adt(def, _) => Some(def.did()), + _ => None, + }; + + ecx.write_doc_attributes(dest, attrs)?; + } + + sym::type_id_variant_docs => { + let base = ecx.read_type_id(&args[0])?; + + if let ty::Adt(def, _) = base.kind() { + let variant_idx = ecx.read_target_usize(&args[1])? as usize; + if variant_idx >= def.variants().len() { + throw_ub!(BoundsCheckFailed { + len: def.variants().len() as u64, + index: variant_idx as u64 + }); + } + let var = def.variant(VariantIdx::from_usize(variant_idx)).def_id; + ecx.write_doc_attributes(dest, Some(var))?; + } else { + span_bug!(ecx.cur_span(), "expected enum type, got {base}") + }; + } + sym::type_id_variant_non_exhaustive => { let base = ecx.read_type_id(&args[0])?; diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index b31fb5904e7d1..f1700e57e6585 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -3,13 +3,14 @@ mod adt; use std::borrow::Cow; use rustc_abi::{ExternAbi, FieldIdx}; -use rustc_attr_ir::AttrItem; use rustc_attr_ir::Attribute::Tool; use rustc_attr_ir::lang_items::LangItem; +use rustc_attr_ir::{AttrItem, Attribute, AttributeKind, HasAttrs}; use rustc_hir::intravisit::HirTyCtxt; use rustc_lint_defs::{Reflectiveness, ToolOptions}; use rustc_middle::ty::layout::{HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, FnHeader, FnSigKind, FnSigTys, ScalarInt, Ty, TyCtxt}; +use rustc_span::def_id::DefId; use rustc_span::{Symbol, span_bug, sym}; use crate::const_eval::CompileTimeMachine; @@ -393,4 +394,44 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { ) }) } + + pub(crate) fn write_doc_attributes( + &mut self, + place: &impl Writeable<'tcx, CtfeProvenance>, + def_id: Option, + ) -> InterpResult<'tcx> { + // only the doc comments of exported items are encoded in cross-crate metadata + // see `rustc_metadata::rmeta::encoder::EncodeContext::encode_attrs` + // this mirrors the check so that we return the same comments regardless of crate + let attrs = if let Some(d) = def_id + && d.as_local().map_or(true, |d| { + !self.tcx.needs_metadata() || self.tcx.effective_visibilities(()).is_exported(d) + }) { + d.get_attrs(&self.tcx) + } else { + &[] + }; + + let docs = attrs + .iter() + .filter_map(|x| match x { + Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment), + _ => None, + }) + .collect::>(); + + self.allocate_fill_and_write_slice_ptr(place, docs.len() as _, |this, i, place| { + let doc = docs[i as usize]; + + let ptr = this.allocate_bytes_dedup(doc.as_str().as_bytes())?; + + this.write_immediate( + Immediate::ScalarPair( + Scalar::from_pointer(ptr, this), + Scalar::from_target_usize(doc.as_str().len() as u64, this), + ), + &place, + ) + }) + } } diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 9595d1cbb9428..f15febe2c1633 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -156,6 +156,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::trunc | sym::type_id | sym::type_id_array_len + | sym::type_id_docs | sym::type_id_element_ty | sym::type_id_eq | sym::type_id_field_representing_type @@ -169,6 +170,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::type_id_reflected_attrs | sym::type_id_size_of | sym::type_id_type_of + | sym::type_id_variant_docs | sym::type_id_variant_name | sym::type_id_variant_non_exhaustive | sym::type_id_variant_reflected_attrs @@ -323,6 +325,26 @@ pub(crate) fn check_intrinsic_type( sym::type_id_variant_name => { (0, 0, vec![type_id_ty(), tcx.types.usize], Ty::new_static_str(tcx)) } + sym::type_id_variant_docs => ( + 0, + 0, + vec![type_id_ty(), tcx.types.usize], + Ty::new_imm_ref( + tcx, + tcx.lifetimes.re_static, + Ty::new_slice(tcx, Ty::new_static_str(tcx)), + ), + ), + sym::type_id_docs => ( + 0, + 0, + vec![type_id_ty()], + Ty::new_imm_ref( + tcx, + tcx.lifetimes.re_static, + Ty::new_slice(tcx, Ty::new_static_str(tcx)), + ), + ), sym::type_id_variant_non_exhaustive => { (0, 0, vec![type_id_ty(), tcx.types.usize], tcx.types.bool) } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index d53e8c7d25482..bda700a4a7f0d 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2208,6 +2208,7 @@ symbols! { type_changing_struct_update, type_id, type_id_array_len, + type_id_docs, type_id_element_ty, type_id_eq, type_id_field_representing_type, @@ -2221,6 +2222,7 @@ symbols! { type_id_reflected_attrs, type_id_size_of, type_id_type_of, + type_id_variant_docs, type_id_variant_name, type_id_variant_non_exhaustive, type_id_variant_reflected_attrs, diff --git a/library/core/src/intrinsics/reflection.rs b/library/core/src/intrinsics/reflection.rs index 0054cd32cdc03..700bb1f307dcc 100644 --- a/library/core/src/intrinsics/reflection.rs +++ b/library/core/src/intrinsics/reflection.rs @@ -118,6 +118,19 @@ pub fn type_id_variant_reflected_attrs( _variant_index: usize, ) -> &'static [&'static str]; +/// Gets the raw documentation attributes of the variant represented by the base `TypeId` and variant_idx. +/// +/// The more user-friendly version of this intrinsic is [`core::mem::type_info::VariantId::docs`]. +/// +/// [`TypeId`]: crate::any::TypeId +#[rustc_intrinsic] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_comptime] +pub fn type_id_variant_docs( + _base: crate::any::TypeId, + _variant_index: usize, +) -> &'static [&'static str]; + /// Returns true when the variant represented by the base `TypeId` and variant_idx is non /// exhaustive. /// @@ -190,3 +203,11 @@ pub fn type_id_function_ptr(_type_id: crate::any::TypeId) -> Option &'static [&'static str]; + +/// Returns the raw documentation attributes given a `TypeId` which represents a structure, enumeration, union or `FieldId`. +/// +/// The more user-friendly version of this intrinsic is [`core::any::TypeId::docs`]. +#[rustc_intrinsic] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_comptime] +pub fn type_id_docs(_type_id: crate::any::TypeId) -> &'static [&'static str]; diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 1ad39e3c2f3ac..a4374ce5e70eb 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -679,6 +679,26 @@ impl TypeId { pub fn reflected_attrs(self) -> &'static [&'static str] { intrinsics::reflection::type_id_reflected_attrs(self) } + + /// Returns the raw documentation attributes when given a `TypeId` which represents a structure, enumeration or union. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// #[doc = "first"] + /// /** second + /// * third + /// */ + /// struct A; + /// + /// assert_eq!(const { TypeId::of::().docs() }, ["first", " second\n* third\n"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_docs(self) + } } /// Variant representing type ID. Representing a variant of an enum. @@ -721,6 +741,28 @@ impl VariantId { intrinsics::reflection::type_id_variant_name(self.base, self.variant) } + /// Returns the raw documentation attributes when given a `VariantId`. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// enum A { + /// #[doc = "first"] + /// /** second + /// * third*/ + /// B, + /// C, + /// } + /// + /// assert_eq!(const { TypeId::of::().variant(0).docs() }, ["first", " second\n * third"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_variant_docs(self.base, self.variant) + } + /// Returns whether this variant is marked with `#[non_exhaustive]`. #[unstable(feature = "type_info", issue = "146922")] #[rustc_const_unstable(feature = "type_info", issue = "146922")] @@ -815,6 +857,27 @@ impl FieldId { pub fn name(self) -> &'static str { intrinsics::field_representing_type_name(self.frt_type_id) } + + /// Returns the raw documentation attributes when given a `FieldId`. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// struct A { + /// #[doc = "first"] + /// /// second + /// first: u8, + /// } + /// + /// assert_eq!(const { TypeId::of::().field(0, 0).docs() }, ["first", " second"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_docs(self.frt_type_id) + } + /// Returns the offset of the field wrt to its containing type. /// /// ``` diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index 76e2adad18f1c..c8f547a20d1af 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -58,11 +58,15 @@ fn test_tuples() { fn test_structs() { const { #[reflective_tool::TestStruct] + ///test-doc struct TestStruct { #[reflective_tool::first(1)] #[reflective_tool::first(2)] + #[doc = "first-doc 1"] + ///first-doc 2 first: u8, #[reflective_tool::second] + /// second-doc second: u16, reference: &'static u16, } @@ -71,6 +75,7 @@ fn test_structs() { assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::TestStruct]"]); + assert!(ty_id.docs() == &["test-doc"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 3); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); @@ -80,13 +85,16 @@ fn test_structs() { ty_id.field(0, 0).reflected_attrs() == &["#[reflective_tool::first(1)]", "#[reflective_tool::first(2)]"] ); + assert!(ty_id.field(0, 0).docs() == &["first-doc 1", "first-doc 2"]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).offset() == offset_of!(TestStruct, second)); assert!(ty_id.field(0, 1).name() == "second"); assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflective_tool::second]"]); + assert!(ty_id.field(0, 1).docs() == &[" second-doc"]); assert!(ty_id.field(0, 2).type_id() == TypeId::of::<&u16>()); assert!(ty_id.field(0, 2).offset() == offset_of!(TestStruct, reference)); assert!(ty_id.field(0, 2).name() == "reference"); + assert!(ty_id.field(0, 2).docs() == &[""; 0]); } const { @@ -107,17 +115,21 @@ fn test_structs() { assert!(ty_id.fields(0) == 2); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 0).name() == "0"); + assert!(ty_id.field(0, 0).docs() == &[""; 0]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).name() == "1"); + assert!(ty_id.field(0, 1).docs() == &[""; 0]); } const { #[reflective_tool::a] + ///doc struct Generics<'a, T, const C: u64> { a: &'a T, } let ty_id = TypeId::of::>(); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.fields(0) == 1); assert!(ty_id.generics().len() == 3); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); @@ -136,34 +148,43 @@ fn test_structs() { fn test_unions() { const { #[reflective_tool::a] + ///test-doc 1 + ///test-doc 2 union TestUnion { #[reflective_tool::first] + #[doc = "first-doc"] first: i16, #[reflective_tool::second] + ///second-doc second: u16, } let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &["test-doc 1", "test-doc 2"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 2); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); assert!(ty_id.field(0, 0).name() == "first"); + assert!(ty_id.field(0, 0).docs() == &["first-doc"]); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 0).reflected_attrs() == &["#[reflective_tool::first]"]); assert!(ty_id.field(0, 1).name() == "second"); + assert!(ty_id.field(0, 1).docs() == &["second-doc"]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflective_tool::second]"]); } const { #[reflective_tool::a] + ///doc union Generics<'a, T: Copy, const C: u64> { a: T, z: &'a (), } let ty_id = TypeId::of::>(); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.fields(0) == 2); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); assert!(ty_id.field(0, 1).offset() == offset_of!(Generics<'static, i32, 1_u64>, a)); @@ -184,16 +205,21 @@ fn test_unions() { fn test_enums() { const { #[reflective_tool::a] + ///doc enum E { #[reflective_tool::some] + ///somedoc Some(u32), #[reflective_tool::none] + ///nonedoc None, #[reflective_tool::foomp] #[non_exhaustive] + ///foompdoc Foomp { a: (), #[reflective_tool::b] + ///bdoc b: &'static str, }, } @@ -202,27 +228,32 @@ fn test_enums() { assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.variants() == 3); assert!(ty_id.variant(0).name() == "Some"); assert!(ty_id.variant(0).reflected_attrs() == &["#[reflective_tool::some]"]); + assert!(ty_id.variant(0).docs() == &["somedoc"]); assert!(!ty_id.variant(0).non_exhaustive()); assert!(ty_id.fields(0) == 1); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.variant(1).name() == "None"); assert!(ty_id.variant(1).reflected_attrs() == &["#[reflective_tool::none]"]); + assert!(ty_id.variant(1).docs() == &["nonedoc"]); assert!(!ty_id.variant(1).non_exhaustive()); assert!(ty_id.fields(1) == 0); assert!(ty_id.variant(2).name() == "Foomp"); assert!(ty_id.variant(2).reflected_attrs() == &["#[reflective_tool::foomp]"]); + assert!(ty_id.variant(2).docs() == &["foompdoc"]); assert!(ty_id.variant(2).non_exhaustive()); assert!(ty_id.fields(2) == 2); assert!(ty_id.field(2, 0).type_id() == TypeId::of::<()>()); assert!(ty_id.field(2, 1).type_id() == TypeId::of::<&str>()); assert!(ty_id.field(2, 1).name() == "b"); assert!(ty_id.field(2, 1).reflected_attrs() == &["#[reflective_tool::b]"]); + assert!(ty_id.field(2, 1).docs() == &["bdoc"]); assert!(ty_id.generics().is_empty()); } @@ -255,12 +286,14 @@ fn test_primitives() { let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Char, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; @@ -268,6 +301,7 @@ fn test_primitives() { assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; @@ -275,6 +309,7 @@ fn test_primitives() { assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; @@ -282,6 +317,7 @@ fn test_primitives() { assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; @@ -289,18 +325,21 @@ fn test_primitives() { assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Float, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Str(_ty), .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == None); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); } } diff --git a/tests/ui/intrinsics/auxiliary/const-eval-doc-attrs.rs b/tests/ui/intrinsics/auxiliary/const-eval-doc-attrs.rs new file mode 100644 index 0000000000000..6686a2092bee6 --- /dev/null +++ b/tests/ui/intrinsics/auxiliary/const-eval-doc-attrs.rs @@ -0,0 +1,19 @@ +#![feature(type_info)] + +use std::any::TypeId; + +///CCC +#[doc = "DDD"] +pub struct C; + +pub const N: usize = { + struct TestStruct { + /// aaa + #[doc = "bbb"] + field: u8, + } + let ty_id = TypeId::of::(); + ty_id.field(0, 0).docs().len() +}; + +const _: () = assert!( N == 0 ); diff --git a/tests/ui/intrinsics/const-eval-doc-attrs.rs b/tests/ui/intrinsics/const-eval-doc-attrs.rs new file mode 100644 index 0000000000000..57273deb958c7 --- /dev/null +++ b/tests/ui/intrinsics/const-eval-doc-attrs.rs @@ -0,0 +1,20 @@ +//@ aux-crate: dep=const-eval-doc-attrs.rs +//@ run-pass + +#![feature(type_info, const_cmp, const_trait_impl)] +use std::any::TypeId; + + +// should be encoded since UI test is of CrateType::Executable +///AAA +#[doc = "BBB"] +struct A; + +const _: () = assert!( dep::N == 0 ) ; +const _: () = const { assert!( TypeId::of::().docs() == &["AAA", "BBB"] ) }; +const _: () = const { assert!( TypeId::of::().docs() == &["CCC", "DDD"] ) }; + + + +fn main() { +} From 50557ccb6186236cfd751cab06121b2f20d594e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 18 Nov 2026 21:25:58 +0100 Subject: [PATCH 24/43] Reword comments Co-authored-by: Jubilee --- src/ci/publish_backtrace.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ci/publish_backtrace.sh b/src/ci/publish_backtrace.sh index b801943415daa..999c0db9148ab 100755 --- a/src/ci/publish_backtrace.sh +++ b/src/ci/publish_backtrace.sh @@ -1,7 +1,7 @@ #!/bin/bash # Publish the backtrace crate to crates.io -# Should be called from the a CI workflow +# Should be called from a CI workflow # Expects the following environment variables as input: # - GITHUB_SHA: SHA of the currently merged commit from which backtrace should be published # - TEMPDIR: scratch directory for temporary files @@ -26,7 +26,7 @@ VERSION=$( ) CRATE=backtrace -# Check if the version exists on crates.io already with a HEAD request to the CDN +# Check if the version already exists on crates.io with a HEAD request to the CDN code=$( curl --head --silent -o /dev/null --write-out '%{http_code}' \ "https://static.crates.io/crates/${CRATE}/${CRATE}-${VERSION}.crate" From 64b54df92e2cb8e68db1c324a56e0b0418e96b32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 18 Nov 2026 21:29:40 +0100 Subject: [PATCH 25/43] Fix environment variable and shell config --- src/ci/publish_backtrace.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ci/publish_backtrace.sh b/src/ci/publish_backtrace.sh index 999c0db9148ab..783b2f08877a4 100755 --- a/src/ci/publish_backtrace.sh +++ b/src/ci/publish_backtrace.sh @@ -6,7 +6,7 @@ # - GITHUB_SHA: SHA of the currently merged commit from which backtrace should be published # - TEMPDIR: scratch directory for temporary files -set -eux pipefail +set -euxo pipefail # Find PR for the current commit HEAD_PR=$(gh pr list --search "${GITHUB_SHA}" --state merged --json number --jq '.[0].number') @@ -50,7 +50,7 @@ else echo "backtrace \`${VERSION}\` could not be published to crates.io" > "${COMMENT_FILE}" printf "
\nCargo publish log\n\n" >> "${COMMENT_FILE}" printf '```\n' >> "${COMMENT_FILE}" - cat "${RUNNER_TEMP}/cargo-log.txt" >> "${COMMENT_FILE}" + cat "${TEMPDIR}/cargo-log.txt" >> "${COMMENT_FILE}" printf '\n```\n' >> "${COMMENT_FILE}" printf "
\n\n" >> "${COMMENT_FILE}" fi From aee0a6974423c26c7df40b44779052c30f41cc3e Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 19 Nov 2026 13:39:42 +1100 Subject: [PATCH 26/43] Move some initial-setup steps out of `run_tests` --- src/tools/compiletest/src/cli.rs | 62 ++++++++++++++++++++++++++++++-- src/tools/compiletest/src/lib.rs | 59 +----------------------------- 2 files changed, 60 insertions(+), 61 deletions(-) diff --git a/src/tools/compiletest/src/cli.rs b/src/tools/compiletest/src/cli.rs index 778d53f1d8d4f..1016482ec6322 100644 --- a/src/tools/compiletest/src/cli.rs +++ b/src/tools/compiletest/src/cli.rs @@ -1,19 +1,33 @@ //! Isolates the APIs used by `bin/main.rs`, to help minimize the surface area //! of public exports from the compiletest library crate. -use std::env; use std::io::IsTerminal; use std::sync::{Arc, OnceLock}; +use std::{env, fs}; use camino::{Utf8Path, Utf8PathBuf}; use clap::Parser; use crate::common::{CodegenBackend, CompareMode, Config, ForcePassMode, TestMode, TestSuite}; use crate::edition::Edition; -use crate::{debuggers, directives, early_config_check, run_tests}; +use crate::{debuggers, directives, help, panic_hook, raise_fd_limit, run_tests, warning}; pub fn main() { + // sadly osx needs some file descriptor limits raised for running tests in + // parallel (especially when we have lots and lots of child processes). + // For context, see #8904 + unsafe { + raise_fd_limit::raise_fd_limit(); + } + + // Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows + // If #11207 is resolved (adding manifest to .exe) this becomes unnecessary + // + // SAFETY: at this point we're still single-threaded. + unsafe { env::set_var("__COMPAT_LAYER", "RunAsInvoker") }; + tracing_subscriber::fmt::init(); + panic_hook::install_panic_hook(); // colored checks stdout by default, but for some reason only stderr is a terminal. // compiletest *does* print many things to stdout, but it doesn't really matter. @@ -24,12 +38,54 @@ pub fn main() { } let config = Arc::new(parse_config(env::args().collect())); - early_config_check(&config); + // If we want to collect rustfix coverage information, + // we first make sure that the coverage file does not exist. + // It will be created later on. + if config.rustfix_coverage { + let mut coverage_file_path = config.build_test_suite_root.clone(); + coverage_file_path.push("rustfix_missing_coverage.txt"); + if coverage_file_path.exists() { + if let Err(e) = fs::remove_file(&coverage_file_path) { + panic!("Could not delete {} due to {}", coverage_file_path, e) + } + } + } + + if let TestMode::DebugInfo = config.mode { + // FIXME: this should ideally happen somewhere else.. + if config.target.contains("android") { + println!("{} debug-info test uses tcp 5039 port. please reserve it", config.target); + + // android debug-info test uses remote debugger so, we test 1 thread + // at once as they're all sharing the same TCP port to communicate + // over. + // + // we should figure out how to lift this restriction! (run them all + // on different ports allocated dynamically). + // + // SAFETY: at this point we are still single-threaded. + unsafe { env::set_var("RUST_TEST_THREADS", "1") }; + } + }; + run_tests(config); } +fn early_config_check(config: &Config) { + if !config.profiler_runtime && config.mode == TestMode::CoverageRun { + let actioned = if config.bless { "blessed" } else { "checked" }; + warning!("profiler runtime is not available, so `.coverage` files won't be {actioned}"); + help!("try setting `profiler = true` in the `[build]` section of `bootstrap.toml`"); + } + + // `RUST_TEST_NOCAPTURE` is a libtest env var, but we don't callout to libtest. + if env::var("RUST_TEST_NOCAPTURE").is_ok() { + warning!("`RUST_TEST_NOCAPTURE` is not supported; use the `--no-capture` flag instead"); + } +} + /// Compiletest command-line arguments. #[derive(clap::Parser)] struct Args { diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index 8b5ec7c3ed531..d55123591c508 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -29,7 +29,7 @@ use std::fmt::Write; use std::io::{self, ErrorKind}; use std::sync::Arc; use std::time::SystemTime; -use std::{env, fs, vec}; +use std::{fs, vec}; use build_helper::git::{get_git_modified_files, get_git_untracked_files}; use camino::{Utf8Component, Utf8Path, Utf8PathBuf}; @@ -49,53 +49,9 @@ use crate::executor::{CollectedTest, TestVariant}; fn run_tests(config: Arc) { debug!(?config, "run_tests"); - panic_hook::install_panic_hook(); - - // If we want to collect rustfix coverage information, - // we first make sure that the coverage file does not exist. - // It will be created later on. - if config.rustfix_coverage { - let mut coverage_file_path = config.build_test_suite_root.clone(); - coverage_file_path.push("rustfix_missing_coverage.txt"); - if coverage_file_path.exists() { - if let Err(e) = fs::remove_file(&coverage_file_path) { - panic!("Could not delete {} due to {}", coverage_file_path, e) - } - } - } - - // sadly osx needs some file descriptor limits raised for running tests in - // parallel (especially when we have lots and lots of child processes). - // For context, see #8904 - unsafe { - raise_fd_limit::raise_fd_limit(); - } - // Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows - // If #11207 is resolved (adding manifest to .exe) this becomes unnecessary - // - // SAFETY: at this point we're still single-threaded. - unsafe { env::set_var("__COMPAT_LAYER", "RunAsInvoker") }; - // Debugging emscripten code doesn't make sense today let ignore_tests = config.mode == TestMode::DebugInfo && config.target.contains("emscripten"); - if let TestMode::DebugInfo = config.mode { - // FIXME: this should ideally happen somewhere else.. - if config.target.contains("android") { - println!("{} debug-info test uses tcp 5039 port. please reserve it", config.target); - - // android debug-info test uses remote debugger so, we test 1 thread - // at once as they're all sharing the same TCP port to communicate - // over. - // - // we should figure out how to lift this restriction! (run them all - // on different ports allocated dynamically). - // - // SAFETY: at this point we are still single-threaded. - unsafe { env::set_var("RUST_TEST_THREADS", "1") }; - } - }; - // Discover all of the tests in the test suite directory, and build a `CollectedTest` // structure for each test (or each revision of a multi-revision test). let mut tests = Vec::new(); @@ -714,16 +670,3 @@ fn check_for_overlapping_test_paths(found_path_stems: &HashSet) { ); } } - -fn early_config_check(config: &Config) { - if !config.profiler_runtime && config.mode == TestMode::CoverageRun { - let actioned = if config.bless { "blessed" } else { "checked" }; - warning!("profiler runtime is not available, so `.coverage` files won't be {actioned}"); - help!("try setting `profiler = true` in the `[build]` section of `bootstrap.toml`"); - } - - // `RUST_TEST_NOCAPTURE` is a libtest env var, but we don't callout to libtest. - if env::var("RUST_TEST_NOCAPTURE").is_ok() { - warning!("`RUST_TEST_NOCAPTURE` is not supported; use the `--no-capture` flag instead"); - } -} From 8e3c1c1c9e4377a79d754fa305f05f8682322714 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 19 Nov 2026 16:25:07 +1100 Subject: [PATCH 27/43] Move test-running and reporting out of `run_tests`, now `discover_tests` --- src/tools/compiletest/src/cli.rs | 41 ++++++++++++++++++++++++++++++-- src/tools/compiletest/src/lib.rs | 37 ++-------------------------- 2 files changed, 41 insertions(+), 37 deletions(-) diff --git a/src/tools/compiletest/src/cli.rs b/src/tools/compiletest/src/cli.rs index 1016482ec6322..a89397b653ef6 100644 --- a/src/tools/compiletest/src/cli.rs +++ b/src/tools/compiletest/src/cli.rs @@ -1,6 +1,7 @@ //! Isolates the APIs used by `bin/main.rs`, to help minimize the surface area //! of public exports from the compiletest library crate. +use std::fmt::Write; use std::io::IsTerminal; use std::sync::{Arc, OnceLock}; use std::{env, fs}; @@ -10,7 +11,9 @@ use clap::Parser; use crate::common::{CodegenBackend, CompareMode, Config, ForcePassMode, TestMode, TestSuite}; use crate::edition::Edition; -use crate::{debuggers, directives, help, panic_hook, raise_fd_limit, run_tests, warning}; +use crate::{ + debuggers, directives, discover_tests, executor, help, panic_hook, raise_fd_limit, warning, +}; pub fn main() { // sadly osx needs some file descriptor limits raised for running tests in @@ -70,7 +73,41 @@ pub fn main() { } }; - run_tests(config); + let tests = discover_tests(&config); + + // Delegate to the executor to filter and run the big list of test structures + // created during test discovery. When the executor decides to run a test, + // it will return control to the rest of compiletest by calling `runtest::run`. + let ok = executor::run_tests(&config, tests); + + // Check the outcome reported by the executor. + if !ok { + // We want to report that the tests failed, but we also want to give + // some indication of just what tests we were running. Especially on + // CI, where there can be cross-compiled tests for a lot of + // architectures, without this critical information it can be quite + // easy to miss which tests failed, and as such fail to reproduce + // the failure locally. + + let mut msg = String::from("Some tests failed in compiletest"); + write!(msg, " suite={}", config.suite).unwrap(); + + if let Some(compare_mode) = config.compare_mode.as_ref() { + write!(msg, " compare_mode={}", compare_mode).unwrap(); + } + + if let Some(pass_mode) = config.force_pass_mode.as_ref() { + write!(msg, " pass_mode={}", pass_mode).unwrap(); + } + + write!(msg, " mode={}", config.mode).unwrap(); + write!(msg, " host={}", config.host).unwrap(); + write!(msg, " target={}", config.target).unwrap(); + + println!("{msg}"); + + std::process::exit(1); + } } fn early_config_check(config: &Config) { diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index d55123591c508..dceddd7b8c2f2 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -25,7 +25,6 @@ mod util; use core::panic; use std::collections::HashSet; -use std::fmt::Write; use std::io::{self, ErrorKind}; use std::sync::Arc; use std::time::SystemTime; @@ -46,7 +45,7 @@ use crate::directives::{AuxProps, DirectivesCache, FileDirectives}; use crate::executor::{CollectedTest, TestVariant}; /// Called by `main` after the config has been parsed. -fn run_tests(config: Arc) { +pub(crate) fn discover_tests(config: &Arc) -> Vec { debug!(?config, "run_tests"); // Debugging emscripten code doesn't make sense today @@ -61,39 +60,7 @@ fn run_tests(config: Arc) { tests.sort_by(|a, b| Ord::cmp(&a.desc.name, &b.desc.name)); - // Delegate to the executor to filter and run the big list of test structures - // created during test discovery. When the executor decides to run a test, - // it will return control to the rest of compiletest by calling `runtest::run`. - let ok = executor::run_tests(&config, tests); - - // Check the outcome reported by the executor. - if !ok { - // We want to report that the tests failed, but we also want to give - // some indication of just what tests we were running. Especially on - // CI, where there can be cross-compiled tests for a lot of - // architectures, without this critical information it can be quite - // easy to miss which tests failed, and as such fail to reproduce - // the failure locally. - - let mut msg = String::from("Some tests failed in compiletest"); - write!(msg, " suite={}", config.suite).unwrap(); - - if let Some(compare_mode) = config.compare_mode.as_ref() { - write!(msg, " compare_mode={}", compare_mode).unwrap(); - } - - if let Some(pass_mode) = config.force_pass_mode.as_ref() { - write!(msg, " pass_mode={}", pass_mode).unwrap(); - } - - write!(msg, " mode={}", config.mode).unwrap(); - write!(msg, " host={}", config.host).unwrap(); - write!(msg, " target={}", config.target).unwrap(); - - println!("{msg}"); - - std::process::exit(1); - } + tests } /// Read-only context data used during test collection. From 26361a34ced87282dad5c2386ba3f1e02ac3d597 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 19 Nov 2026 16:39:52 +1100 Subject: [PATCH 28/43] Temporarily rename `lib.rs` to `discovery.rs` This will make it possible to move all code out of the crate root, while retaining as much line history as possible. --- src/tools/compiletest/Cargo.toml | 1 + src/tools/compiletest/src/{lib.rs => discovery.rs} | 0 2 files changed, 1 insertion(+) rename src/tools/compiletest/src/{lib.rs => discovery.rs} (100%) diff --git a/src/tools/compiletest/Cargo.toml b/src/tools/compiletest/Cargo.toml index 6f8c8eed07d18..9394cfc4a0b78 100644 --- a/src/tools/compiletest/Cargo.toml +++ b/src/tools/compiletest/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" [lib] doctest = false +path = "src/discovery.rs" [[bin]] name = "compiletest" diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/discovery.rs similarity index 100% rename from src/tools/compiletest/src/lib.rs rename to src/tools/compiletest/src/discovery.rs From eaa2f7192875d1f33dd77a7ef4f532af44680d6c Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 19 Nov 2026 16:43:41 +1100 Subject: [PATCH 29/43] Move all test-discovery code out of the crate root --- src/tools/compiletest/Cargo.toml | 1 - src/tools/compiletest/src/cli.rs | 4 +-- src/tools/compiletest/src/directives.rs | 4 +-- src/tools/compiletest/src/discovery.rs | 39 +++++++------------------ src/tools/compiletest/src/lib.rs | 25 ++++++++++++++++ src/tools/compiletest/src/runtest.rs | 5 ++-- src/tools/compiletest/src/tests.rs | 2 +- 7 files changed, 43 insertions(+), 37 deletions(-) create mode 100644 src/tools/compiletest/src/lib.rs diff --git a/src/tools/compiletest/Cargo.toml b/src/tools/compiletest/Cargo.toml index 9394cfc4a0b78..6f8c8eed07d18 100644 --- a/src/tools/compiletest/Cargo.toml +++ b/src/tools/compiletest/Cargo.toml @@ -5,7 +5,6 @@ edition = "2024" [lib] doctest = false -path = "src/discovery.rs" [[bin]] name = "compiletest" diff --git a/src/tools/compiletest/src/cli.rs b/src/tools/compiletest/src/cli.rs index a89397b653ef6..f8ae7442656f9 100644 --- a/src/tools/compiletest/src/cli.rs +++ b/src/tools/compiletest/src/cli.rs @@ -12,7 +12,7 @@ use clap::Parser; use crate::common::{CodegenBackend, CompareMode, Config, ForcePassMode, TestMode, TestSuite}; use crate::edition::Edition; use crate::{ - debuggers, directives, discover_tests, executor, help, panic_hook, raise_fd_limit, warning, + debuggers, directives, discovery, executor, help, panic_hook, raise_fd_limit, warning, }; pub fn main() { @@ -73,7 +73,7 @@ pub fn main() { } }; - let tests = discover_tests(&config); + let tests = discovery::discover_tests(&config); // Delegate to the executor to filter and run the big list of test structures // created during test discovery. When the executor decides to run a test, diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index 4e99ab99f6059..1f0cc0577b082 100644 --- a/src/tools/compiletest/src/directives.rs +++ b/src/tools/compiletest/src/directives.rs @@ -7,7 +7,7 @@ use camino::{Utf8Path, Utf8PathBuf}; use semver::Version; use tracing::*; -use crate::common::{Config, Debugger, PassFailMode, TestMode}; +use crate::common::{CodegenBackend, Config, Debugger, PassFailMode, TestMode}; use crate::debuggers::{LldbVersion, extract_cdb_version, extract_gdb_version}; use crate::directives::auxiliary::parse_and_update_aux; pub(crate) use crate::directives::auxiliary::{AuxCrate, AuxProps}; @@ -1218,7 +1218,7 @@ fn needs_backends(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision { /// When using the GCC backend, ignore tests for which we did not find a libgccjit.so. fn ignore_unsupported_backend_target(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision { - if config.default_codegen_backend != crate::CodegenBackend::Gcc { + if config.default_codegen_backend != CodegenBackend::Gcc { return IgnoreDecision::Continue; } diff --git a/src/tools/compiletest/src/discovery.rs b/src/tools/compiletest/src/discovery.rs index dceddd7b8c2f2..9609f7ac173be 100644 --- a/src/tools/compiletest/src/discovery.rs +++ b/src/tools/compiletest/src/discovery.rs @@ -1,28 +1,3 @@ -#![crate_name = "compiletest"] -#![warn(unreachable_pub)] - -#[cfg(test)] -mod tests; - -// Public modules needed by the compiletest binary or by `rustdoc-gui-test`. -pub mod cli; -pub mod rustdoc_gui_test; - -mod common; -mod debuggers; -mod diagnostics; -mod directives; -mod edition; -mod errors; -mod executor; -mod json; -mod output_capture; -mod panic_hook; -mod raise_fd_limit; -mod read2; -mod runtest; -mod util; - use core::panic; use std::collections::HashSet; use std::io::{self, ErrorKind}; @@ -36,13 +11,15 @@ use rayon::iter::{ParallelBridge, ParallelIterator}; use tracing::debug; use walkdir::WalkDir; -use self::directives::{EarlyProps, make_test_description}; use crate::common::{ CodegenBackend, Config, Debugger, TestMode, TestPaths, UI_EXTENSIONS, expected_output_path, output_base_dir, output_relative_path, }; -use crate::directives::{AuxProps, DirectivesCache, FileDirectives}; +use crate::directives::{ + self, AuxProps, DirectivesCache, EarlyProps, FileDirectives, make_test_description, +}; use crate::executor::{CollectedTest, TestVariant}; +use crate::{fatal, runtest, warning}; /// Called by `main` after the config has been parsed. pub(crate) fn discover_tests(config: &Arc) -> Vec { @@ -311,7 +288,7 @@ fn collect_tests_from_dir( } /// Returns true if `file_name` looks like a proper test file name. -fn is_test(file_name: &str) -> bool { +pub(crate) fn is_test(file_name: &str) -> bool { if !file_name.ends_with(".rs") { return false; } @@ -417,7 +394,11 @@ fn make_test(cx: &TestCollectorCx, collector: &mut TestCollector, testpaths: &Te /// The path of the `stamp` file that gets created or updated whenever a /// particular test completes successfully. -fn stamp_file_path(config: &Config, testpaths: &TestPaths, variant: &TestVariant) -> Utf8PathBuf { +pub(crate) fn stamp_file_path( + config: &Config, + testpaths: &TestPaths, + variant: &TestVariant, +) -> Utf8PathBuf { output_base_dir(config, testpaths, variant).join("stamp") } diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs new file mode 100644 index 0000000000000..c8c39900fc645 --- /dev/null +++ b/src/tools/compiletest/src/lib.rs @@ -0,0 +1,25 @@ +#![crate_name = "compiletest"] +#![warn(unreachable_pub)] + +#[cfg(test)] +mod tests; + +// Public modules needed by the compiletest binary or by `rustdoc-gui-test`. +pub mod cli; +pub mod rustdoc_gui_test; + +mod common; +mod debuggers; +mod diagnostics; +mod directives; +mod discovery; +mod edition; +mod errors; +mod executor; +mod json; +mod output_capture; +mod panic_hook; +mod raise_fd_limit; +mod read2; +mod runtest; +mod util; diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 2092a0077088f..4cb7401a51262 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -26,7 +26,7 @@ use crate::output_capture::ConsoleOut; use crate::read2::{Truncated, read2_abbreviated}; use crate::runtest::compute_diff::{DiffLine, diff_by_lines, make_diff, write_diff}; use crate::util::{ArgFileCommand, Utf8PathBufExt, add_dylib_path, static_regex}; -use crate::{json, stamp_file_path}; +use crate::{discovery, json}; // Helper modules that implement test running logic for each test suite. // tidy-alphabetical-start @@ -3121,7 +3121,8 @@ impl<'test> TestCx<'test> { } fn create_stamp(&self) { - let stamp_file_path = stamp_file_path(&self.config, self.testpaths, self.variant); + let stamp_file_path = + discovery::stamp_file_path(&self.config, self.testpaths, self.variant); fs::write(&stamp_file_path, compute_stamp_hash(&self.config, self.variant)).unwrap(); } diff --git a/src/tools/compiletest/src/tests.rs b/src/tools/compiletest/src/tests.rs index 59bed76bdb510..9289a66d5d148 100644 --- a/src/tools/compiletest/src/tests.rs +++ b/src/tools/compiletest/src/tests.rs @@ -1,7 +1,7 @@ use semver::Version; use crate::debuggers::{LldbVersion, extract_gdb_version, extract_lldb_version}; -use crate::is_test; +use crate::discovery::is_test; #[test] fn test_extract_gdb_version() { From 7b405efacb74e4ae825e082ca29160fec8e67c0b Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 19 Nov 2026 16:48:20 +1100 Subject: [PATCH 30/43] Small cleanups in `cli.rs` --- src/tools/compiletest/src/cli.rs | 42 +++++++++++++++----------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/src/tools/compiletest/src/cli.rs b/src/tools/compiletest/src/cli.rs index f8ae7442656f9..e5c42e503fdf2 100644 --- a/src/tools/compiletest/src/cli.rs +++ b/src/tools/compiletest/src/cli.rs @@ -19,9 +19,7 @@ pub fn main() { // sadly osx needs some file descriptor limits raised for running tests in // parallel (especially when we have lots and lots of child processes). // For context, see #8904 - unsafe { - raise_fd_limit::raise_fd_limit(); - } + unsafe { raise_fd_limit::raise_fd_limit() }; // Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows // If #11207 is resolved (adding manifest to .exe) this becomes unnecessary @@ -35,7 +33,7 @@ pub fn main() { // colored checks stdout by default, but for some reason only stderr is a terminal. // compiletest *does* print many things to stdout, but it doesn't really matter. if std::io::stderr().is_terminal() - && matches!(std::env::var("NO_COLOR").as_deref(), Err(_) | Ok("0")) + && matches!(env::var("NO_COLOR").as_deref(), Err(_) | Ok("0")) { colored::control::set_override(true); } @@ -50,29 +48,27 @@ pub fn main() { let mut coverage_file_path = config.build_test_suite_root.clone(); coverage_file_path.push("rustfix_missing_coverage.txt"); if coverage_file_path.exists() { - if let Err(e) = fs::remove_file(&coverage_file_path) { - panic!("Could not delete {} due to {}", coverage_file_path, e) - } + fs::remove_file(&coverage_file_path) + .unwrap_or_else(|e| panic!("Could not delete {coverage_file_path} due to {e}")); } } - if let TestMode::DebugInfo = config.mode { - // FIXME: this should ideally happen somewhere else.. - if config.target.contains("android") { - println!("{} debug-info test uses tcp 5039 port. please reserve it", config.target); - - // android debug-info test uses remote debugger so, we test 1 thread - // at once as they're all sharing the same TCP port to communicate - // over. - // - // we should figure out how to lift this restriction! (run them all - // on different ports allocated dynamically). - // - // SAFETY: at this point we are still single-threaded. - unsafe { env::set_var("RUST_TEST_THREADS", "1") }; - } - }; + // FIXME: this should ideally happen somewhere else.. + if config.mode == TestMode::DebugInfo && config.target.contains("android") { + println!("{} debug-info test uses tcp 5039 port. please reserve it", config.target); + + // android debug-info test uses remote debugger so, we test 1 thread + // at once as they're all sharing the same TCP port to communicate + // over. + // + // we should figure out how to lift this restriction! (run them all + // on different ports allocated dynamically). + // + // SAFETY: at this point we are still single-threaded. + unsafe { env::set_var("RUST_TEST_THREADS", "1") }; + } + // Scan the test directory for tests, and create a test struct for each test/variant. let tests = discovery::discover_tests(&config); // Delegate to the executor to filter and run the big list of test structures From e60e0731bd2fcb2e4a59c35728680509d4b8083f Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 17 Nov 2026 17:34:41 +0000 Subject: [PATCH 31/43] Remove ebadf handling from stdio But still ignore EBADF in (e)println. --- library/std/src/io/stdio.rs | 51 ++++++++++++++++-------------------- tests/ui/process/no-stdio.rs | 41 +++++++++++++++++------------ 2 files changed, 46 insertions(+), 46 deletions(-) diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index f72a55366bfdd..0e630fc976e8a 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -97,15 +97,15 @@ const fn stderr_raw() -> StderrRaw { impl Read for StdinRaw { fn read(&mut self, buf: &mut [u8]) -> io::Result { - handle_ebadf(self.0.read(buf), || Ok(0)) + self.0.read(buf) } fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> { - handle_ebadf(self.0.read_buf(buf), || Ok(())) + self.0.read_buf(buf) } fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { - handle_ebadf(self.0.read_vectored(bufs), || Ok(0)) + self.0.read_vectored(bufs) } #[inline] @@ -117,33 +117,32 @@ impl Read for StdinRaw { if buf.is_empty() { return Ok(()); } - handle_ebadf(self.0.read_exact(buf), || Err(io::Error::READ_EXACT_EOF)) + self.0.read_exact(buf) } fn read_buf_exact(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> { if buf.capacity() == 0 { return Ok(()); } - handle_ebadf(self.0.read_buf_exact(buf), || Err(io::Error::READ_EXACT_EOF)) + self.0.read_buf_exact(buf) } fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { - handle_ebadf(self.0.read_to_end(buf), || Ok(0)) + self.0.read_to_end(buf) } fn read_to_string(&mut self, buf: &mut String) -> io::Result { - handle_ebadf(self.0.read_to_string(buf), || Ok(0)) + self.0.read_to_string(buf) } } impl Write for StdoutRaw { fn write(&mut self, buf: &[u8]) -> io::Result { - handle_ebadf(self.0.write(buf), || Ok(buf.len())) + self.0.write(buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { - let total = || Ok(bufs.iter().map(|b| b.len()).sum()); - handle_ebadf(self.0.write_vectored(bufs), total) + self.0.write_vectored(bufs) } #[inline] @@ -152,30 +151,29 @@ impl Write for StdoutRaw { } fn flush(&mut self) -> io::Result<()> { - handle_ebadf(self.0.flush(), || Ok(())) + self.0.flush() } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - handle_ebadf(self.0.write_all(buf), || Ok(())) + self.0.write_all(buf) } fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { - handle_ebadf(self.0.write_all_vectored(bufs), || Ok(())) + self.0.write_all_vectored(bufs) } fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { - handle_ebadf(self.0.write_fmt(fmt), || Ok(())) + self.0.write_fmt(fmt) } } impl Write for StderrRaw { fn write(&mut self, buf: &[u8]) -> io::Result { - handle_ebadf(self.0.write(buf), || Ok(buf.len())) + self.0.write(buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { - let total = || Ok(bufs.iter().map(|b| b.len()).sum()); - handle_ebadf(self.0.write_vectored(bufs), total) + self.0.write_vectored(bufs) } #[inline] @@ -184,26 +182,19 @@ impl Write for StderrRaw { } fn flush(&mut self) -> io::Result<()> { - handle_ebadf(self.0.flush(), || Ok(())) + self.0.flush() } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - handle_ebadf(self.0.write_all(buf), || Ok(())) + self.0.write_all(buf) } fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { - handle_ebadf(self.0.write_all_vectored(bufs), || Ok(())) + self.0.write_all_vectored(bufs) } fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { - handle_ebadf(self.0.write_fmt(fmt), || Ok(())) - } -} - -fn handle_ebadf(r: io::Result, default: impl FnOnce() -> io::Result) -> io::Result { - match r { - Err(ref e) if stdio::is_ebadf(e) => default(), - r => r, + self.0.write_fmt(fmt) } } @@ -1158,7 +1149,9 @@ where return; } - if let Err(e) = global_s().write_fmt(args) { + if let Err(e) = global_s().write_fmt(args) + && !stdio::is_ebadf(&e) + { panic!("failed printing to {label}: {e}"); } } diff --git a/tests/ui/process/no-stdio.rs b/tests/ui/process/no-stdio.rs index 5cc7cacbb22f0..c41811b91d3e0 100644 --- a/tests/ui/process/no-stdio.rs +++ b/tests/ui/process/no-stdio.rs @@ -17,7 +17,7 @@ unsafe fn without_stdio R>(f: F) -> R { let doit = |a| { let r = libc::dup(a); assert!(r >= 0); - return r + return r; }; let a = doit(0); let b = doit(1); @@ -33,7 +33,7 @@ unsafe fn without_stdio R>(f: F) -> R { assert!(libc::dup2(b, 1) >= 0); assert!(libc::dup2(c, 2) >= 0); - return r + return r; } #[cfg(unix)] @@ -66,7 +66,7 @@ unsafe fn without_stdio R>(f: F) -> R { let handle = GetStdHandle(id); assert!(handle != INVALID_HANDLE_VALUE); assert!(SetStdHandle(id, INVALID_HANDLE_VALUE) != 0); - return handle + return handle; }; let a = doit(STD_INPUT_HANDLE); @@ -82,7 +82,7 @@ unsafe fn without_stdio R>(f: F) -> R { doit(STD_OUTPUT_HANDLE, b); doit(STD_ERROR_HANDLE, c); - return r + return r; } fn main() { @@ -99,10 +99,10 @@ fn main() { assert_fd_is_valid(0); assert_fd_is_valid(1); assert_fd_is_valid(2); - return + return; } - // First, make sure reads/writes without stdio work if stdio itself is + // First, make sure reads/writes without stdio error if stdio itself is // missing. let (a, b, c) = unsafe { without_stdio(|| { @@ -114,25 +114,32 @@ fn main() { }) }; - assert_eq!(a.unwrap(), 5); - assert_eq!(b.unwrap(), 5); - assert_eq!(c.unwrap(), 0); + if cfg!(windows) { + // On Windows it's not an error to write to unset stdio. + assert_eq!(a.unwrap(), 5); + assert_eq!(b.unwrap(), 5); + assert_eq!(c.unwrap(), 0); + } else { + // On Unix platforms it is. + assert!(a.is_err()); + assert!(b.is_err()); + assert!(c.is_err()); + } // Second, spawn a child and do some work with "null" descriptors to make // sure it's ok let me = env::current_exe().unwrap(); let status = Command::new(&me) - .arg("next") - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status().unwrap(); + .arg("next") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .unwrap(); assert!(status.success(), "{} isn't a success", status); // Finally, close everything then spawn a child to make sure everything is // *still* ok. - let status = unsafe { - without_stdio(|| Command::new(&me).arg("next").status()) - }.unwrap(); + let status = unsafe { without_stdio(|| Command::new(&me).arg("next").status()) }.unwrap(); assert!(status.success(), "{} isn't a success", status); } From 922260107d3e7cbefc9a72000c66a04d3fb71c36 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 17 Nov 2026 17:38:26 +0000 Subject: [PATCH 32/43] Windows ignore stdio to NUL This used to be handled indirectly in std::stdio --- library/std/src/sys/process/windows.rs | 4 ++-- library/std/src/sys/stdio/windows.rs | 16 ++++++---------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/library/std/src/sys/process/windows.rs b/library/std/src/sys/process/windows.rs index db2e2373adf95..1a520b76cdbd4 100644 --- a/library/std/src/sys/process/windows.rs +++ b/library/std/src/sys/process/windows.rs @@ -618,14 +618,14 @@ fn program_exists(path: &Path) -> Option> { impl Stdio { fn to_handle(&self, stdio_id: u32, pipe: &mut Option) -> io::Result { let use_stdio_id = |stdio_id| match stdio::get_handle(stdio_id) { - Ok(io) => unsafe { + Some(io) => unsafe { let io = Handle::from_raw_handle(io); let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS); let _ = io.into_raw_handle(); // Don't close the handle ret }, // If no stdio handle is available, then propagate the null value. - Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) }, + None => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) }, }; match *self { Stdio::Inherit => use_stdio_id(stdio_id), diff --git a/library/std/src/sys/stdio/windows.rs b/library/std/src/sys/stdio/windows.rs index f669527352246..c7c7a1ea3817f 100644 --- a/library/std/src/sys/stdio/windows.rs +++ b/library/std/src/sys/stdio/windows.rs @@ -70,15 +70,9 @@ pub const STDIN_BUF_SIZE: usize = MAX_BUFFER_SIZE / 2 * 3; #[cfg(not(target_vendor = "win7"))] const MAX_WRITE_HEAP_LEN: usize = 64 * 1024; // In u16 -> 128KiB -pub fn get_handle(handle_id: u32) -> io::Result { +pub fn get_handle(handle_id: u32) -> Option { let handle = unsafe { c::GetStdHandle(handle_id) }; - if handle == c::INVALID_HANDLE_VALUE { - Err(io::Error::last_os_error()) - } else if handle.is_null() { - Err(io::Error::from_raw_os_error(c::ERROR_INVALID_HANDLE as i32)) - } else { - Ok(handle) - } + if handle.is_null() || handle == c::INVALID_HANDLE_VALUE { None } else { Some(handle) } } /// Returns true if `handle` refers to a proper console (aka conhost). @@ -115,7 +109,8 @@ fn write(handle_id: u32, data: &[u8], incomplete_utf8: &mut IncompleteUtf8) -> i return Ok(0); } - let handle = get_handle(handle_id)?; + // If no handle is available, treat it like writing to NUL + let Some(handle) = get_handle(handle_id) else { return Ok(data.len()) }; // At the time of writing, console IO on Windows is high latency: // Windows has no TTY buffers, making every call a fully synchronous RPC. @@ -267,7 +262,8 @@ impl Stdin { impl io::Read for Stdin { fn read(&mut self, buf: &mut [u8]) -> io::Result { - let handle = get_handle(c::STD_INPUT_HANDLE)?; + // If no handle is available then treat it as if reading from NUL + let Some(handle) = get_handle(c::STD_INPUT_HANDLE) else { return Ok(0) }; if !is_console(handle) { unsafe { let handle = Handle::from_raw_handle(handle); From 80b557c7eacb165db0345f355a4cb303803959ce Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Wed, 18 Nov 2026 22:35:03 +0100 Subject: [PATCH 33/43] Add regression test --- tests/ui/lint/pre-expansion-parsing.rs | 1 + .../parser/recover/recover-seperated-list.rs | 15 +++++++++++++ .../recover/recover-seperated-list.stderr | 21 +++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 tests/ui/parser/recover/recover-seperated-list.rs create mode 100644 tests/ui/parser/recover/recover-seperated-list.stderr diff --git a/tests/ui/lint/pre-expansion-parsing.rs b/tests/ui/lint/pre-expansion-parsing.rs index 772c61b8e212f..08f0cd3cf4885 100644 --- a/tests/ui/lint/pre-expansion-parsing.rs +++ b/tests/ui/lint/pre-expansion-parsing.rs @@ -8,5 +8,6 @@ #[expect[helix::]] // OK #[allow = 1u7] // OK #[allow = "x"suffix] // OK +#[allow(foo(a b))] // OK #[cfg(false)] const _: () = (); diff --git a/tests/ui/parser/recover/recover-seperated-list.rs b/tests/ui/parser/recover/recover-seperated-list.rs new file mode 100644 index 0000000000000..8248103bf6af9 --- /dev/null +++ b/tests/ui/parser/recover/recover-seperated-list.rs @@ -0,0 +1,15 @@ +macro_rules! probe { + ($ty:ty) => { + compile_error!("TY FRAGMENT MATCHED") + //~^ ERROR TY FRAGMENT MATCHED + }; +} + +fn f<'a, 'b>() -> probe!(impl Sized + use<'a 'b>) { + //~^ ERROR expected one of `,` or `>`, found `'b` + loop {} +} + +fn main() { + +} diff --git a/tests/ui/parser/recover/recover-seperated-list.stderr b/tests/ui/parser/recover/recover-seperated-list.stderr new file mode 100644 index 0000000000000..2414a97024530 --- /dev/null +++ b/tests/ui/parser/recover/recover-seperated-list.stderr @@ -0,0 +1,21 @@ +error: expected one of `,` or `>`, found `'b` + --> $DIR/recover-seperated-list.rs:8:46 + | +LL | fn f<'a, 'b>() -> probe!(impl Sized + use<'a 'b>) { + | -^^ expected one of `,` or `>` + | | + | help: missing `,` + +error: TY FRAGMENT MATCHED + --> $DIR/recover-seperated-list.rs:3:9 + | +LL | macro_rules! probe { +LL | ($ty:ty) => { +LL | compile_error!("TY FRAGMENT MATCHED") + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +... +LL | fn f<'a, 'b>() -> probe!(impl Sized + use<'a 'b>) { + | ------------------------------- in this macro invocation + +error: aborting due to 2 previous errors + From 354c2ef85fa9e18fc162d1c31c2ed35c27b99e31 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Wed, 18 Nov 2026 22:36:27 +0100 Subject: [PATCH 34/43] Don't recover if not allowed in `parse_seq_to_before_tokens` --- compiler/rustc_parse/src/parser/mod.rs | 4 ++++ .../parser/recover/recover-seperated-list.rs | 1 - .../recover/recover-seperated-list.stderr | 18 ++++-------------- 3 files changed, 8 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 10f4d73e3e4cd..f5bb585628b3d 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -883,6 +883,10 @@ impl<'a> Parser<'a> { break; } Err(mut expect_err) => { + if !self.may_recover() { + return Err(expect_err); + } + let sp = self.prev_token.span.shrink_to_hi(); let token_str = pprust::token_kind_to_string(&exp.tok); diff --git a/tests/ui/parser/recover/recover-seperated-list.rs b/tests/ui/parser/recover/recover-seperated-list.rs index 8248103bf6af9..25fb7fe6a5dfb 100644 --- a/tests/ui/parser/recover/recover-seperated-list.rs +++ b/tests/ui/parser/recover/recover-seperated-list.rs @@ -1,7 +1,6 @@ macro_rules! probe { ($ty:ty) => { compile_error!("TY FRAGMENT MATCHED") - //~^ ERROR TY FRAGMENT MATCHED }; } diff --git a/tests/ui/parser/recover/recover-seperated-list.stderr b/tests/ui/parser/recover/recover-seperated-list.stderr index 2414a97024530..74c105d3bbff3 100644 --- a/tests/ui/parser/recover/recover-seperated-list.stderr +++ b/tests/ui/parser/recover/recover-seperated-list.stderr @@ -1,21 +1,11 @@ error: expected one of `,` or `>`, found `'b` - --> $DIR/recover-seperated-list.rs:8:46 + --> $DIR/recover-seperated-list.rs:7:46 | -LL | fn f<'a, 'b>() -> probe!(impl Sized + use<'a 'b>) { - | -^^ expected one of `,` or `>` - | | - | help: missing `,` - -error: TY FRAGMENT MATCHED - --> $DIR/recover-seperated-list.rs:3:9 - | -LL | macro_rules! probe { LL | ($ty:ty) => { -LL | compile_error!("TY FRAGMENT MATCHED") - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ------ while parsing argument for this `ty` macro fragment ... LL | fn f<'a, 'b>() -> probe!(impl Sized + use<'a 'b>) { - | ------------------------------- in this macro invocation + | ^^ expected one of `,` or `>` -error: aborting due to 2 previous errors +error: aborting due to 1 previous error From 7e41a8e28d4bc565c64d130fe0519e8b522154c4 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 19 Nov 2026 03:00:22 -0600 Subject: [PATCH 35/43] simd-test: Fix cfg syntax in the test macro Missed as part of 78c5cdd4a2b0 ("std: Combine `is_mips64_feature_detected` into `is_mips_feature_detected`"). --- library/stdarch/crates/simd-test-macro/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/stdarch/crates/simd-test-macro/src/lib.rs b/library/stdarch/crates/simd-test-macro/src/lib.rs index 286b36d3dd249..7b903723664fe 100644 --- a/library/stdarch/crates/simd-test-macro/src/lib.rs +++ b/library/stdarch/crates/simd-test-macro/src/lib.rs @@ -142,7 +142,7 @@ pub fn simd_test( } any( target_arch = "mips", - target_arch = "mips32r6" + target_arch = "mips32r6", target_arch = "mips64", target_arch = "mips64r6", ) => { From 54e07ae911086c71d6b033654f88fcc0835f366f Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 19 Nov 2026 05:14:36 -0600 Subject: [PATCH 36/43] std: Constify `std::process::abort` `abort` is getting used a bit more in places where unwinding via `panic!` isn't desired. Some of these places involve shared const and runtime code, so mark `abort` unstably `const` to make this a bit easier. This uses `core::process::crash` as the const implementation, which will be const stable in the near future. --- library/std/src/lib.rs | 2 + library/std/src/process.rs | 10 ++++- tests/ui/consts/const-eval/const_panic.rs | 6 ++- tests/ui/consts/const-eval/const_panic.stderr | 43 ++++++++++++------- 4 files changed, 42 insertions(+), 19 deletions(-) diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 192f1931fb69d..fc22eaecc0043 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -269,6 +269,7 @@ // // Language features: // tidy-alphabetical-start +#![feature(abort_immediate)] #![feature(alloc_error_handler)] #![feature(allocator_internals)] #![feature(allow_internal_unsafe)] @@ -279,6 +280,7 @@ #![feature(cfg_target_has_threads)] #![feature(cfg_target_thread_local)] #![feature(cfi_encoding)] +#![feature(const_eval_select)] #![feature(const_trait_impl)] #![feature(decl_macro)] #![feature(deprecated_suggestion)] diff --git a/library/std/src/process.rs b/library/std/src/process.rs index cc7fab7aba9d1..fb3b72607e4d8 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -174,6 +174,8 @@ ))] mod tests; +use core::intrinsics; + use crate::ffi::OsStr; use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; @@ -2642,11 +2644,15 @@ pub fn exit(code: i32) -> ! { /// /// [panic hook]: crate::panic::set_hook #[stable(feature = "process_abort", since = "1.17.0")] +#[rustc_const_unstable(feature = "const_abort", issue = "166193")] #[cold] #[cfg_attr(not(test), rustc_diagnostic_item = "process_abort")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -pub fn abort() -> ! { - crate::sys::abort_internal(); +pub const fn abort() -> ! { + // Some code uses `abort` as a non-unwinding alternative to `panic`. That + // should work in const, but `sys` code invokes native host functions. So we + // invoke `intrinsics::crash` instead to safely hard-abort execution. + intrinsics::const_eval_select((), crash, crate::sys::abort_internal) } #[doc(inline)] diff --git a/tests/ui/consts/const-eval/const_panic.rs b/tests/ui/consts/const-eval/const_panic.rs index a3f299decd0ba..60dbf35f71217 100644 --- a/tests/ui/consts/const-eval/const_panic.rs +++ b/tests/ui/consts/const-eval/const_panic.rs @@ -1,5 +1,6 @@ //@ edition:2015..2021 #![feature(abort_immediate)] +#![feature(const_abort)] #![allow(non_fmt_panics)] #![crate_type = "lib"] @@ -41,5 +42,8 @@ const W_CORE: () = core::panic!(MSG); const W2_CORE: () = core::panic!("{}", MSG); //~^ ERROR evaluation panicked -const ABORT: () = core::process::crash(); +const ABORT: () = std::process::abort(); +//~^ ERROR the program aborted execution + +const CRASH: () = core::process::crash(); //~^ ERROR the program aborted execution diff --git a/tests/ui/consts/const-eval/const_panic.stderr b/tests/ui/consts/const-eval/const_panic.stderr index 16facaa2d4962..65dafb7dd6df7 100644 --- a/tests/ui/consts/const-eval/const_panic.stderr +++ b/tests/ui/consts/const-eval/const_panic.stderr @@ -1,84 +1,95 @@ error[E0080]: evaluation panicked: cheese - --> $DIR/const_panic.rs:8:15 + --> $DIR/const_panic.rs:9:15 | LL | const Z: () = std::panic!("cheese"); | ^^^^^^^^^^^^^^^^^^^^^ evaluation of `Z` failed here error[E0080]: evaluation panicked: explicit panic - --> $DIR/const_panic.rs:11:16 + --> $DIR/const_panic.rs:12:16 | LL | const Z2: () = std::panic!(); | ^^^^^^^^^^^^^ evaluation of `Z2` failed here error[E0080]: evaluation panicked: internal error: entered unreachable code - --> $DIR/const_panic.rs:14:15 + --> $DIR/const_panic.rs:15:15 | LL | const Y: () = std::unreachable!(); | ^^^^^^^^^^^^^^^^^^^ evaluation of `Y` failed here error[E0080]: evaluation panicked: not implemented - --> $DIR/const_panic.rs:17:15 + --> $DIR/const_panic.rs:18:15 | LL | const X: () = std::unimplemented!(); | ^^^^^^^^^^^^^^^^^^^^^ evaluation of `X` failed here error[E0080]: evaluation panicked: hello - --> $DIR/const_panic.rs:20:15 + --> $DIR/const_panic.rs:21:15 | LL | const W: () = std::panic!(MSG); | ^^^^^^^^^^^^^^^^ evaluation of `W` failed here error[E0080]: evaluation panicked: hello - --> $DIR/const_panic.rs:23:16 + --> $DIR/const_panic.rs:24:16 | LL | const W2: () = std::panic!("{}", MSG); | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `W2` failed here error[E0080]: evaluation panicked: cheese - --> $DIR/const_panic.rs:26:20 + --> $DIR/const_panic.rs:27:20 | LL | const Z_CORE: () = core::panic!("cheese"); | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `Z_CORE` failed here error[E0080]: evaluation panicked: explicit panic - --> $DIR/const_panic.rs:29:21 + --> $DIR/const_panic.rs:30:21 | LL | const Z2_CORE: () = core::panic!(); | ^^^^^^^^^^^^^^ evaluation of `Z2_CORE` failed here error[E0080]: evaluation panicked: internal error: entered unreachable code - --> $DIR/const_panic.rs:32:20 + --> $DIR/const_panic.rs:33:20 | LL | const Y_CORE: () = core::unreachable!(); | ^^^^^^^^^^^^^^^^^^^^ evaluation of `Y_CORE` failed here error[E0080]: evaluation panicked: not implemented - --> $DIR/const_panic.rs:35:20 + --> $DIR/const_panic.rs:36:20 | LL | const X_CORE: () = core::unimplemented!(); | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `X_CORE` failed here error[E0080]: evaluation panicked: hello - --> $DIR/const_panic.rs:38:20 + --> $DIR/const_panic.rs:39:20 | LL | const W_CORE: () = core::panic!(MSG); | ^^^^^^^^^^^^^^^^^ evaluation of `W_CORE` failed here error[E0080]: evaluation panicked: hello - --> $DIR/const_panic.rs:41:21 + --> $DIR/const_panic.rs:42:21 | LL | const W2_CORE: () = core::panic!("{}", MSG); | ^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `W2_CORE` failed here error[E0080]: the program aborted execution - --> $DIR/const_panic.rs:44:19 + --> $DIR/const_panic.rs:45:19 | -LL | const ABORT: () = core::process::crash(); - | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `ABORT` failed inside this call +LL | const ABORT: () = std::process::abort(); + | ^^^^^^^^^^^^^^^^^^^^^ evaluation of `ABORT` failed inside this call | +note: inside `abort` + --> $SRC_DIR/std/src/process.rs:LL:COL note: inside `crash` --> $SRC_DIR/core/src/process.rs:LL:COL -error: aborting due to 13 previous errors +error[E0080]: the program aborted execution + --> $DIR/const_panic.rs:48:19 + | +LL | const CRASH: () = core::process::crash(); + | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `CRASH` failed inside this call + | +note: inside `crash` + --> $SRC_DIR/core/src/process.rs:LL:COL + +error: aborting due to 14 previous errors For more information about this error, try `rustc --explain E0080`. From 433fb54838a55a79737968651de89490c28487ca Mon Sep 17 00:00:00 2001 From: Xubai Wang Date: Thu, 19 Nov 2026 20:45:05 +0800 Subject: [PATCH 37/43] test zst and zero len Signed-off-by: Xubai Wang --- tests/ui/const-generics/transmute.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/ui/const-generics/transmute.rs b/tests/ui/const-generics/transmute.rs index d17d1ed75bd4d..bff8cc86a5158 100644 --- a/tests/ui/const-generics/transmute.rs +++ b/tests/ui/const-generics/transmute.rs @@ -33,6 +33,18 @@ fn element4_swap_lit( unsafe { std::mem::transmute::<_, _>(v) } } +fn zst(v: [(); N]) -> () { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn zero_len(v: [[u8; N]; 0]) -> () { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn zst_zero_len(v: [(); N]) -> [[u8; N]; 0] { + unsafe { std::mem::transmute::<_, _>(v) } +} + fn main() { let _ = ident([[0; 8]; 16]); let _ = singleton_each([0; 8]); @@ -40,4 +52,7 @@ fn main() { let _ = element2([[T(0); 8]; 16]); let _ = element3_mixed([[[T(0); 8]; 42]; 16]); let _ = element4_swap_lit([[[[T(0); 8]; 3]; 7]; 16]); + let _ = zst([(); 8]); + let _ = zero_len([[0; 8]; 0]); + let _ = zst_zero_len([(); 8]); } From 7e291dcb9d99bdfe5534de106b441c295675e09f Mon Sep 17 00:00:00 2001 From: Xubai Wang Date: Thu, 19 Nov 2026 21:30:54 +0800 Subject: [PATCH 38/43] test normalized Signed-off-by: Xubai Wang --- tests/ui/const-generics/transmute.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/ui/const-generics/transmute.rs b/tests/ui/const-generics/transmute.rs index bff8cc86a5158..e58600d9533c0 100644 --- a/tests/ui/const-generics/transmute.rs +++ b/tests/ui/const-generics/transmute.rs @@ -45,14 +45,31 @@ fn zst_zero_len(v: [(); N]) -> [[u8; N]; 0] { unsafe { std::mem::transmute::<_, _>(v) } } +const L1: usize = 42; +const L2: usize = L1; +const L3: usize = 42; + +fn len_normalized_alias(v: [u8; L1]) -> [u8; L2] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn len_normalized_equal(v: [u8; L1]) -> [u8; L3] { + unsafe { std::mem::transmute::<_, _>(v) } +} + fn main() { let _ = ident([[0; 8]; 16]); let _ = singleton_each([0; 8]); + let _ = element([T(0); 8]); let _ = element2([[T(0); 8]; 16]); let _ = element3_mixed([[[T(0); 8]; 42]; 16]); let _ = element4_swap_lit([[[[T(0); 8]; 3]; 7]; 16]); + let _ = zst([(); 8]); let _ = zero_len([[0; 8]; 0]); let _ = zst_zero_len([(); 8]); + + let _ = len_normalized_alias([2; L1]); + let _ = len_normalized_equal([2; L1]); } From 2c42b4d3e5c382cd5695081bf549aa80a6a0e7ba Mon Sep 17 00:00:00 2001 From: panstromek Date: Thu, 19 Nov 2026 16:32:52 +0100 Subject: [PATCH 39/43] ref: avoid terminator: None in insert_direct_enum_check We can avoid this one by just moving some code around, but there's a slight change in how local ids are assigned, because the discr_masked is now allocated before the locals in insert_discr_cast_to_u128. Before this change, it was allocated after those. --- .../rustc_mir_transform/src/check_enums.rs | 47 ++++++++++--------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_mir_transform/src/check_enums.rs b/compiler/rustc_mir_transform/src/check_enums.rs index 6cc12f48debb8..82945c8974827 100644 --- a/compiler/rustc_mir_transform/src/check_enums.rs +++ b/compiler/rustc_mir_transform/src/check_enums.rs @@ -347,8 +347,32 @@ fn insert_direct_enum_check<'tcx>( source_info: SourceInfo, new_block: BasicBlock, ) { + // Local for masked out bits of the discriminant type. + let discr_masked = + local_decls.push(LocalDecl::with_source_info(tcx.types.u128, source_info)).into(); + // Insert a new target block that is branched to in case of an invalid discriminant. - let invalid_discr_block_data = BasicBlockData::maybe_unterminated(None, false); + let invalid_discr_block_data = BasicBlockData::new( + Terminator { + source_info, + kind: TerminatorKind::Assert { + cond: Operand::Constant(Box::new(ConstOperand { + span: source_info.span, + user_ty: None, + const_: Const::Val(ConstValue::from_bool(false), tcx.types.bool), + })), + expected: true, + target: new_block, + msg: Box::new(AssertKind::InvalidEnumConstruction(Operand::Copy(discr_masked))), + // This calls panic_invalid_enum_construction, which is #[rustc_nounwind]. + // We never want to insert an unwind into unsafe code, because unwinding could + // make a failing UB check turn into much worse UB when we start unwinding. + unwind: UnwindAction::Unreachable, + }, + }, + false, + ); + let invalid_discr_block = basic_blocks.push(invalid_discr_block_data); let block_data = &mut basic_blocks[current_block]; let discr_place = insert_discr_cast_to_u128( @@ -364,8 +388,6 @@ fn insert_direct_enum_check<'tcx>( // Mask out the bits of the discriminant type. let mask = discr.size.unsigned_int_max(); - let discr_masked = - local_decls.push(LocalDecl::with_source_info(tcx.types.u128, source_info)).into(); let rvalue = Rvalue::BinaryOp( BinOp::BitAnd, Box::new(( @@ -394,25 +416,6 @@ fn insert_direct_enum_check<'tcx>( ), }, }); - - // Abort in case of an invalid enum discriminant. - basic_blocks[invalid_discr_block].terminator = Some(Terminator { - source_info, - kind: TerminatorKind::Assert { - cond: Operand::Constant(Box::new(ConstOperand { - span: source_info.span, - user_ty: None, - const_: Const::Val(ConstValue::from_bool(false), tcx.types.bool), - })), - expected: true, - target: new_block, - msg: Box::new(AssertKind::InvalidEnumConstruction(Operand::Copy(discr_masked))), - // This calls panic_invalid_enum_construction, which is #[rustc_nounwind]. - // We never want to insert an unwind into unsafe code, because unwinding could - // make a failing UB check turn into much worse UB when we start unwinding. - unwind: UnwindAction::Unreachable, - }, - }); } fn insert_uninhabited_enum_check<'tcx>( From dba4d78721f64b44cb498edec15932c77d13b1c3 Mon Sep 17 00:00:00 2001 From: xonx4l Date: Thu, 19 Nov 2026 22:02:39 +0530 Subject: [PATCH 40/43] add stamp for --keep-stage --- src/bootstrap/src/core/build_steps/compile.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 6ccc6d3b55d02..d9545aa2846d0 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -196,9 +196,9 @@ impl CommandLineStep for Std { } // Reuse std for `--keep-stage-std` if it was built before, otherwise build it. - if builder.config.keep_stage.contains(&build_compiler.stage) - || (builder.config.keep_stage_std.contains(&build_compiler.stage) - && build_stamp::libstd_stamp(builder, build_compiler, target).path().exists()) + if (builder.config.keep_stage.contains(&build_compiler.stage) + || builder.config.keep_stage_std.contains(&build_compiler.stage)) + && build_stamp::libstd_stamp(builder, build_compiler, target).path().exists() { trace!(keep_stage = ?builder.config.keep_stage); trace!(keep_stage_std = ?builder.config.keep_stage_std); From 610d5c3543999513082a90c6b18d3388e348e279 Mon Sep 17 00:00:00 2001 From: Goat Date: Mon, 9 Nov 2026 20:01:47 +0300 Subject: [PATCH 41/43] bootstrap: Make low priority the default --- bootstrap.example.toml | 10 +++++++--- src/bootstrap/defaults/bootstrap.dist.toml | 3 +++ src/bootstrap/src/core/config/config.rs | 2 +- src/bootstrap/src/utils/change_tracker.rs | 5 +++++ 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/bootstrap.example.toml b/bootstrap.example.toml index 6c2e3917fb697..43042d4150faf 100644 --- a/bootstrap.example.toml +++ b/bootstrap.example.toml @@ -474,9 +474,13 @@ # linked or not. #build.cargo-native-static = false -# Run the build with low priority, by setting the process group's "nice" value -# to +10 on Unix platforms, and by using a "low priority" job object on Windows. -#build.low-priority = false +# Run the build with low priority, by setting the process's "nice" value to +10 +# on Unix platforms, and by using a "low priority" job object on Windows. +# This will improve the responsiveness of foreground tasks and will not slow the +# build down unless there are competing CPU-saturating jobs, so there is +# typically no reason to opt out of this behavior. See the discussion in +# https://github.com/rust-lang/rust/pull/165707 for more details. +#build.low-priority = true # Arguments passed to the `./configure` script, used during distcheck. You # probably won't fill this in but rather it's filled in by the `./configure` diff --git a/src/bootstrap/defaults/bootstrap.dist.toml b/src/bootstrap/defaults/bootstrap.dist.toml index 03e012079b079..c7f551aa68d51 100644 --- a/src/bootstrap/defaults/bootstrap.dist.toml +++ b/src/bootstrap/defaults/bootstrap.dist.toml @@ -7,6 +7,9 @@ test-stage = 2 doc-stage = 2 # When compiling from source, you usually want all tools. extended = true +# Builds for distribution typically run beneath some other build +# system that is expected to perform its own priority lowering. +low-priority = false # Most users installing from source want to build all parts of the project from source. [llvm] diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 9bff78dbf49b3..4006fe6a91a0e 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1526,7 +1526,7 @@ NOTE: Please add `--stage 2` to your command line, or if you're sure you want to llvm_version_suffix, local_rebuild, locked_deps: build_locked_deps.unwrap_or(false), - low_priority: build_low_priority.unwrap_or(false), + low_priority: build_low_priority.unwrap_or(true), mandir: install_mandir.map(PathBuf::from), miri_info, musl_root: rust_musl_root.map(PathBuf::from), diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index 3db429b5f5124..78d0b22b0cbfc 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -686,4 +686,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Info, summary: "A new option `llvm.tpde` has been added to control whether the TPDE pass plugin should be built as an experimental alternative LLVM backend.", }, + ChangeInfo { + change_id: 165707, + severity: ChangeSeverity::Info, + summary: "`low-priority` is now enabled by default aside from `bootstrap.dist.toml`, which is optimal for the overwhelming majority of situations.", + }, ]; From d7bfe5e5756e2ac5c6ecd4401b26b78021e39a00 Mon Sep 17 00:00:00 2001 From: panstromek Date: Mon, 9 Nov 2026 19:37:24 +0100 Subject: [PATCH 42/43] refactor split_block in check_pointers to avoid Terminator: None We also inline split_block and outline insert_check instead in check_pointers. The goal is to separate inserting the check from creating and inserting the new block. This should make the logic slightly easier to follow --- .../rustc_mir_transform/src/check_pointers.rs | 94 ++++++++++--------- 1 file changed, 50 insertions(+), 44 deletions(-) diff --git a/compiler/rustc_mir_transform/src/check_pointers.rs b/compiler/rustc_mir_transform/src/check_pointers.rs index 0c73e3af0eb00..079ceefae65e2 100644 --- a/compiler/rustc_mir_transform/src/check_pointers.rs +++ b/compiler/rustc_mir_transform/src/check_pointers.rs @@ -88,34 +88,56 @@ pub(crate) fn check_pointers<'tcx, F>( for (local, ty, context) in finder.into_found_pointers() { debug!("Inserting check for {:?}", ty); - let new_block = split_block(basic_blocks, location); - - // Invoke `on_finding` which appends to `local_decls` and the - // blocks statements. It returns information about the assert - // we're performing in the Terminator. - let block_data = &mut basic_blocks[block]; - let pointer_check = on_finding( - tcx, - local, - ty, - context, - local_decls, - &mut block_data.statements, - source_info, - ); - block_data.terminator = Some(Terminator { - source_info, - kind: TerminatorKind::Assert { - cond: pointer_check.cond, - expected: true, - target: new_block, - msg: pointer_check.assert_kind, - // This calls a panic function associated with the pointer check, which - // is #[rustc_nounwind]. We never want to insert an unwind into unsafe - // code, because unwinding could make a failing UB check turn into much - // worse UB when we start unwinding. - unwind: UnwindAction::Unreachable, - }, + + let mut insert_check = |block_data: &mut BasicBlockData<'tcx>, new_block_idx| { + // Invoke `on_finding` which appends to `local_decls` and the + // blocks statements. It returns information about the assert + // we're performing in the Terminator. + let pointer_check = on_finding( + tcx, + local, + ty, + context, + local_decls, + &mut block_data.statements, + source_info, + ); + let new_terminator = Terminator { + source_info, + kind: TerminatorKind::Assert { + cond: pointer_check.cond, + expected: true, + // new_block_idx will contain the rest of the original block + target: new_block_idx, + msg: pointer_check.assert_kind, + // This calls a panic function associated with the pointer check, which + // is #[rustc_nounwind]. We never want to insert an unwind into unsafe + // code, because unwinding could make a failing UB check turn into much + // worse UB when we start unwinding. + unwind: UnwindAction::Unreachable, + }, + }; + + // Terminate the split block with the new terminator + // and return the original terminator + std::mem::replace(block_data.terminator_mut(), new_terminator) + }; + + basic_blocks.push_with(|new_block_idx, basic_blocks| { + let block_data = &mut basic_blocks[location.block]; + + // Drain every statement after this one + let remaining_stmts = block_data.statements.split_off(location.statement_index); + + // insert the check (push statements and replace old terminator) + let old_terminator = insert_check(block_data, new_block_idx); + + // move the rest to a new block + BasicBlockData::new_stmts( + remaining_stmts, + old_terminator, + block_data.is_cleanup, + ) }); } } @@ -227,19 +249,3 @@ impl<'a, 'tcx> Visitor<'tcx> for PointerFinder<'a, 'tcx> { self.super_place(place, context, location); } } - -fn split_block( - basic_blocks: &mut IndexVec>, - location: Location, -) -> BasicBlock { - let block_data = &mut basic_blocks[location.block]; - - // Drain every statement after this one and move the current terminator to a new basic block. - let new_block = BasicBlockData::maybe_unterminated_stmts( - block_data.statements.split_off(location.statement_index), - block_data.terminator.take(), - block_data.is_cleanup, - ); - - basic_blocks.push(new_block) -} From 0c2fc3bfaf6c07a8ac700e65ee553fdc1cc11519 Mon Sep 17 00:00:00 2001 From: Goat Date: Thu, 19 Nov 2026 22:30:57 +0300 Subject: [PATCH 43/43] bootstrap: `job.rs` improvements --- src/bootstrap/Cargo.lock | 1 + src/bootstrap/Cargo.toml | 1 + src/bootstrap/src/core/session.rs | 4 +-- src/bootstrap/src/utils/job.rs | 46 ++++++++++++++++++++++++++----- 4 files changed, 42 insertions(+), 10 deletions(-) diff --git a/src/bootstrap/Cargo.lock b/src/bootstrap/Cargo.lock index 4d72f562a0bc6..c89f06a5b3174 100644 --- a/src/bootstrap/Cargo.lock +++ b/src/bootstrap/Cargo.lock @@ -48,6 +48,7 @@ dependencies = [ "clap", "clap_complete", "cmake", + "errno", "expect-test", "home", "ignore", diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml index fa744c895477f..37fd7540ed5d7 100644 --- a/src/bootstrap/Cargo.toml +++ b/src/bootstrap/Cargo.toml @@ -39,6 +39,7 @@ cmake = "=0.1.54" build_helper = { path = "../build_helper" } clap = { version = "4.4", default-features = false, features = ["std", "usage", "help", "derive", "error-context"] } clap_complete = "4.4" +errno = "0.3.14" home = "0.5" ignore = "0.4" libc = "0.2" diff --git a/src/bootstrap/src/core/session.rs b/src/bootstrap/src/core/session.rs index df6c8b3958736..7222225c623e4 100644 --- a/src/bootstrap/src/core/session.rs +++ b/src/bootstrap/src/core/session.rs @@ -559,9 +559,7 @@ impl Session { #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Session::build", skip_all))] pub(crate) fn build(&mut self) { trace!("setting up job management"); - unsafe { - crate::utils::job::setup(self); - } + crate::utils::job::setup(self); // Handle hard-coded subcommands. { diff --git a/src/bootstrap/src/utils/job.rs b/src/bootstrap/src/utils/job.rs index 45cff7c716ba9..b370bed36006b 100644 --- a/src/bootstrap/src/utils/job.rs +++ b/src/bootstrap/src/utils/job.rs @@ -1,15 +1,47 @@ +#[cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))] +pub(crate) use self::for_unix::setup; #[cfg(windows)] pub(crate) use self::for_windows::setup; use crate::core::session::Session; #[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))] -pub(crate) unsafe fn setup(_sess: &Session) {} +pub(crate) fn setup(_sess: &Session) {} -#[cfg(all(unix, not(target_os = "haiku")))] -pub(crate) unsafe fn setup(sess: &Session) { - if sess.config.low_priority { - unsafe { - libc::setpriority(libc::PRIO_PGRP as _, 0, 10); +#[cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))] +mod for_unix { + use std::ffi::c_int; + use std::io; + + use libc::id_t; + + fn get_priority(which: c_int, who: id_t) -> io::Result { + // Genius design: `getpriority` can return -1 on success if the nice value is literally -1. + // Per `getpriority`'s docs, clear `errno` beforehand and check it afterward regardless of + // return value. + errno::set_errno(errno::Errno(0)); + // SAFETY: empty safety contract + let nice = unsafe { libc::getpriority(which as _, who) }; + let new_errno = errno::errno().0; + if new_errno == 0 { Ok(nice) } else { Err(io::Error::from_raw_os_error(new_errno)) } + } + fn set_priority(which: c_int, who: id_t, prio: c_int) -> io::Result<()> { + // SAFETY: empty safety contract + if unsafe { libc::setpriority(which as _, who, prio) != -1 } { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + + pub(crate) fn setup(sess: &super::Session) { + const TARGET_NICE: c_int = 10; + // The processes that spawn the build are all descendants of the + // current thread. + let (which, who) = (libc::PRIO_PROCESS as _, 0); + // Unwrap both of those to alert users to ridiculous Seccomp-BPF setups messing up their + // performance. + if sess.config.low_priority && get_priority(which, who).unwrap() < TARGET_NICE { + set_priority(which, who, TARGET_NICE).unwrap(); } } } @@ -59,7 +91,7 @@ mod for_windows { use windows::Win32::System::Threading::{BELOW_NORMAL_PRIORITY_CLASS, GetCurrentProcess}; use windows::core::PCWSTR; - pub(crate) unsafe fn setup(sess: &super::Session) { + pub(crate) fn setup(sess: &super::Session) { // SAFETY: pretty much everything below is unsafe unsafe { // Enable the Windows Error Reporting dialog which msys disables,