From e451490bc1b271243dc559431c740886951a92bf Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Thu, 12 Nov 2026 17:50:55 +0000 Subject: [PATCH 01/19] 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 02/19] 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 9fe76f21ffa3b2b152f22bbae612ee1bf4ee1475 Mon Sep 17 00:00:00 2001 From: panstromek Date: Fri, 13 Nov 2026 20:01:49 +0100 Subject: [PATCH 03/19] 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 04/19] 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 05/19] 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 ec54b14a5dd225081fe1af280437c81791161229 Mon Sep 17 00:00:00 2001 From: David Walker Date: Tue, 17 Nov 2026 18:02:05 -0800 Subject: [PATCH 06/19] 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 1dd5f239fc3ba53ea36492f4decd11151ad76cae Mon Sep 17 00:00:00 2001 From: Jed McKenna Date: Wed, 18 Nov 2026 15:36:55 +1100 Subject: [PATCH 07/19] 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 08/19] 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 09/19] 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 bb05ffd5fac77857f7ea21c06e526b4a6ec9a934 Mon Sep 17 00:00:00 2001 From: Tess4552 Date: Mon, 26 Oct 2026 14:47:24 +0100 Subject: [PATCH 10/19] 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 aee0a6974423c26c7df40b44779052c30f41cc3e Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 19 Nov 2026 13:39:42 +1100 Subject: [PATCH 11/19] 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 12/19] 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 13/19] 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 14/19] 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 15/19] 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 80b557c7eacb165db0345f355a4cb303803959ce Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Wed, 18 Nov 2026 22:35:03 +0100 Subject: [PATCH 16/19] 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 17/19] 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 18/19] 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 739b0b54a44c96770965cf5a8a95a19bb17bf3a3 Mon Sep 17 00:00:00 2001 From: Abhinav Srivastav Date: Sat, 14 Nov 2026 13:12:00 +0000 Subject: [PATCH 19/19] fix: nondeterministic temporary object paths in linker maps --- compiler/rustc_codegen_ssa/src/back/link.rs | 45 +++++++--- tests/run-make/comment-section/rmake.rs | 9 +- tests/run-make/linker-map-determinism/lib.rs | 3 + .../run-make/linker-map-determinism/rmake.rs | 86 +++++++++++++++++++ tests/run-make/linker-warning/rmake.rs | 1 - tests/run-make/linker-warning/short-error.txt | 2 +- 6 files changed, 129 insertions(+), 17 deletions(-) create mode 100644 tests/run-make/linker-map-determinism/lib.rs create mode 100644 tests/run-make/linker-map-determinism/rmake.rs diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 1ce6421693dd1..9b910015ff222 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -395,6 +395,7 @@ pub fn link_binary( &crate_info, &metadata, path.as_ref(), + outputs, codegen_backend, ); } @@ -1239,6 +1240,7 @@ fn link_natively( crate_info: &CrateInfo, metadata: &EncodedMetadata, tmpdir: &Path, + outputs: &OutputFilenames, codegen_backend: &'static str, ) { info!("preparing {:?} to {:?}", crate_type, out_filename); @@ -1254,6 +1256,18 @@ fn link_natively( should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so")); let temp_filename = archive_member.as_deref().unwrap_or(out_filename); + // Follow the same naming convention as regular codegen objects. + let metadata_object = outputs.temp_path_for_cgu(OutputType::Object, "rustc_link_metadata"); + let symbols_object = outputs.temp_path_for_cgu(OutputType::Object, "rustc_link_symbols"); + + // Clean up the generated linker inputs even if linking fails. + let _cleanup = rustc_data_structures::defer(|| { + if !sess.opts.cg.save_temps { + ensure_removed(sess.dcx(), &metadata_object); + ensure_removed(sess.dcx(), &symbols_object); + } + }); + let (mut cmd, jobserver_tokens) = linker_with_args( &linker_path, flavor, @@ -1262,6 +1276,8 @@ fn link_natively( rmeta_link_cache, crate_type, tmpdir, + &metadata_object, + &symbols_object, temp_filename, compiled_modules, crate_info, @@ -2537,7 +2553,7 @@ fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor fn add_linked_symbol_object( cmd: &mut dyn Linker, sess: &Session, - tmpdir: &Path, + symbols_path: &Path, crate_type: CrateType, linked_symbols: &[(String, SymbolExportKind)], exported_symbols: &[SymbolExport], @@ -2672,12 +2688,11 @@ fn add_linked_symbol_object( file.append_section_data(section, drectve.as_bytes(), 1); } - let path = tmpdir.join("symbols.o"); - let result = std::fs::write(&path, file.write().unwrap()); - if let Err(error) = result { - sess.dcx().emit_fatal(diagnostics::FailedToWrite { path, error }); - } - cmd.add_object(&path); + fs::write(symbols_path, file.write().unwrap()).unwrap_or_else(|error| { + sess.dcx() + .emit_fatal(diagnostics::FailedToWrite { path: symbols_path.to_path_buf(), error }) + }); + cmd.add_object(symbols_path); } /// Add object files containing code from the current crate. @@ -2717,7 +2732,7 @@ fn add_local_crate_metadata_objects( sess: &Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, crate_type: CrateType, - tmpdir: &Path, + metadata_path: &Path, crate_info: &CrateInfo, metadata: &EncodedMetadata, ) { @@ -2730,9 +2745,11 @@ fn add_local_crate_metadata_objects( &metadata, &crate_info.metadata_symbol, ); - let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o"); - - cmd.add_object(&obj); + fs::write(metadata_path, data).unwrap_or_else(|error| { + sess.dcx() + .emit_fatal(diagnostics::FailedToWrite { path: metadata_path.to_path_buf(), error }) + }); + cmd.add_object(metadata_path); } } @@ -2915,6 +2932,8 @@ fn linker_with_args( rmeta_link_cache: &mut RmetaLinkCache, crate_type: CrateType, tmpdir: &Path, + metadata_object: &Path, + symbols_object: &Path, out_filename: &Path, compiled_modules: &CompiledModules, crate_info: &CrateInfo, @@ -2975,7 +2994,7 @@ fn linker_with_args( add_linked_symbol_object( cmd, sess, - tmpdir, + symbols_object, crate_type, &crate_info.linked_symbols[&crate_type], &export_symbols, @@ -3017,7 +3036,7 @@ fn linker_with_args( sess, archive_builder_builder, crate_type, - tmpdir, + metadata_object, crate_info, metadata, ); diff --git a/tests/run-make/comment-section/rmake.rs b/tests/run-make/comment-section/rmake.rs index 22b0e2b3b3fb9..a5a33e9989a82 100644 --- a/tests/run-make/comment-section/rmake.rs +++ b/tests/run-make/comment-section/rmake.rs @@ -29,10 +29,15 @@ fn main() { .run() .assert_stdout_contains("rustc version 1."); - // Check all object files (including temporary outputs) have a `.comment` + // Check codegen object files (including temporary outputs) have a `.comment` // section with the expected content. rfs::read_dir_entries(cwd(), |f| { - if !f.extension().is_some_and(|ext| ext == "o") { + // Synthetic linker inputs are not codegen objects and have no `.comment`. + let name = f.file_name().unwrap().to_string_lossy(); + if !f.extension().is_some_and(|ext| ext == "o") + || name.contains(".rustc_link_metadata.") + || name.contains(".rustc_link_symbols.") + { return; } diff --git a/tests/run-make/linker-map-determinism/lib.rs b/tests/run-make/linker-map-determinism/lib.rs new file mode 100644 index 0000000000000..432593368f902 --- /dev/null +++ b/tests/run-make/linker-map-determinism/lib.rs @@ -0,0 +1,3 @@ +pub fn answer() -> u32 { + 42 +} diff --git a/tests/run-make/linker-map-determinism/rmake.rs b/tests/run-make/linker-map-determinism/rmake.rs new file mode 100644 index 0000000000000..d5d927fde11ea --- /dev/null +++ b/tests/run-make/linker-map-determinism/rmake.rs @@ -0,0 +1,86 @@ +// Repeated dylib links must produce identical linker maps. +// +// Regression test for #142989: rustc used to pass a metadata object +// from a randomly named temporary directory to the linker, leaking +// that directory name into the map file. +// +//@ only-linux +//@ ignore-cross-compile +//@ ignore-backends: gcc + +use std::fs; + +use run_make_support::rustc; + +fn main() { + let build = |map: &str| -> Vec { + let map_arg = format!("-Wl,-Map={map}"); + + rustc().input("lib.rs").crate_type("dylib").output("libfoo.so").link_arg(&map_arg).run(); + + fs::read("libfoo.so").unwrap() + }; + + let first_binary = build("first.map"); + let second_binary = build("second.map"); + + // GNU ld records paths to both metadata and linked-symbol objects. + // Neither pathname should vary between otherwise identical builds. + assert!( + fs::read("first.map").unwrap() == fs::read("second.map").unwrap(), + "complete linker maps differ between identical builds" + ); + + let metadata_input = |map: &str| -> String { + let map = fs::read_to_string(map).unwrap(); + map.lines() + .find(|line| line.trim_start().starts_with(".rustc ") && line.contains(".o")) + .expect("metadata object missing from linker map") + .to_owned() + }; + + assert_eq!( + metadata_input("first.map"), + metadata_input("second.map"), + "metadata object path differs between identical builds" + ); + + // Both synthetic linker inputs must use regular object filenames. + let metadata = "libfoo.rustc_link_metadata.rcgu.o"; + let symbols = "libfoo.rustc_link_symbols.rcgu.o"; + + for map in ["first.map", "second.map"] { + let contents = fs::read_to_string(map).unwrap(); + assert!(contents.contains(metadata), "metadata object missing from {map}"); + assert!(contents.contains(symbols), "symbols object missing from {map}"); + } + + assert_eq!(first_binary, second_binary, "linked dylibs differ between identical builds"); + + // Normal linking removes synthetic objects. + assert!(!fs::exists(metadata).unwrap()); + assert!(!fs::exists(symbols).unwrap()); + + // -C save-temps retains them. + rustc().input("lib.rs").crate_type("dylib").output("libfoo.so").arg("-Csave-temps").run(); + + assert!(fs::exists(metadata).unwrap()); + assert!(fs::exists(symbols).unwrap()); + + // A subsequent normal build removes them again. + rustc().input("lib.rs").crate_type("dylib").output("libfoo.so").run(); + + assert!(!fs::exists(metadata).unwrap()); + assert!(!fs::exists(symbols).unwrap()); + + // A linker failure must also clean up the generated objects. + rustc() + .input("lib.rs") + .crate_type("dylib") + .output("libfoo.so") + .arg("-Clink-arg=-Wl,--invalid-linker-map-test-option") + .run_fail(); + + assert!(!fs::exists(metadata).unwrap()); + assert!(!fs::exists(symbols).unwrap()); +} diff --git a/tests/run-make/linker-warning/rmake.rs b/tests/run-make/linker-warning/rmake.rs index 8b0c22b0fb940..0c42ee0455319 100644 --- a/tests/run-make/linker-warning/rmake.rs +++ b/tests/run-make/linker-warning/rmake.rs @@ -82,7 +82,6 @@ fn main() { "/build-root", ) .normalize("libpanic_abort", "libpanic_unwind") - .normalize(r#""[^"]*\/symbols.o""#, "\"/symbols.o\"") .normalize(r#""[^"]*\/raw-dylibs""#, "\"/raw-dylibs\"") .normalize("\"-fno-lto\" ", "") .run(); diff --git a/tests/run-make/linker-warning/short-error.txt b/tests/run-make/linker-warning/short-error.txt index 31b8254162180..6441a378d8eb1 100644 --- a/tests/run-make/linker-warning/short-error.txt +++ b/tests/run-make/linker-warning/short-error.txt @@ -1,6 +1,6 @@ error: linking with `./fake-linker` failed: exit status: 1 | - = note: "./fake-linker" "-m64" "/symbols.o" "<2 object files omitted>" "-Wl,--as-needed" "-Wl,-Bstatic" "/build-root/test/run-make/linker-warning/rmake_out/{libfoo,libbar}.rlib" "/lib/rustlib/x86_64-unknown-linux-gnu/lib/{libstd-*,libpanic_unwind-*,libobject-*,libmemchr-*,libaddr2line-*,libgimli-*,libcfg_if-*,librustc_demangle-*,libstd_detect-*,libhashbrown-*,librustc_std_workspace_alloc-*,libminiz_oxide-*,libadler2-*,libunwind-*,liblibc-*,librustc_std_workspace_core-*,liballoc-*,libcore-*,libcompiler_builtins-*}.rlib" "-Wl,-Bdynamic" "-lgcc_s" "-lutil" "-lrt" "-lpthread" "-lm" "-ldl" "-lc" "-L" "/raw-dylibs" "-Wl,--eh-frame-hdr" "-Wl,-z,noexecstack" "-L" "/build-root/test/run-make/linker-warning/rmake_out" "-L" "/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-o" "main" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-nodefaultlibs" "run_make_error" + = note: "./fake-linker" "-m64" "<3 object files omitted>" "-Wl,--as-needed" "-Wl,-Bstatic" "/build-root/test/run-make/linker-warning/rmake_out/{libfoo,libbar}.rlib" "/lib/rustlib/x86_64-unknown-linux-gnu/lib/{libstd-*,libpanic_unwind-*,libobject-*,libmemchr-*,libaddr2line-*,libgimli-*,libcfg_if-*,librustc_demangle-*,libstd_detect-*,libhashbrown-*,librustc_std_workspace_alloc-*,libminiz_oxide-*,libadler2-*,libunwind-*,liblibc-*,librustc_std_workspace_core-*,liballoc-*,libcore-*,libcompiler_builtins-*}.rlib" "-Wl,-Bdynamic" "-lgcc_s" "-lutil" "-lrt" "-lpthread" "-lm" "-ldl" "-lc" "-L" "/raw-dylibs" "-Wl,--eh-frame-hdr" "-Wl,-z,noexecstack" "-L" "/build-root/test/run-make/linker-warning/rmake_out" "-L" "/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-o" "main" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-nodefaultlibs" "run_make_error" = note: some arguments are omitted. use `--verbose` to show all linker arguments = note: error: baz