From e451490bc1b271243dc559431c740886951a92bf Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Thu, 12 Nov 2026 17:50:55 +0000 Subject: [PATCH 01/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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 80b557c7eacb165db0345f355a4cb303803959ce Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Wed, 18 Nov 2026 22:35:03 +0100 Subject: [PATCH 11/13] 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 12/13] 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 13/13] 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", ) => {