diff --git a/compiler/rustc_infer/src/traits/error_reporting/mod.rs b/compiler/rustc_infer/src/traits/error_reporting/mod.rs index ed543ba991edf..32966011932d1 100644 --- a/compiler/rustc_infer/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/traits/error_reporting/mod.rs @@ -123,9 +123,24 @@ pub fn report_object_safety_error<'tcx>( } else { vec![] }; + let externally_visible = if !impls.is_empty() + && let Some(def_id) = trait_def_id.as_local() + && tcx.effective_visibilities(()).is_exported(def_id) + { + true + } else { + false + }; match &impls[..] { [] => {} _ if impls.len() > 9 => {} + [only] if externally_visible => { + err.help(with_no_trimmed_paths!(format!( + "only type `{}` is seen to implement the trait in this crate, consider using it \ + directly instead", + tcx.type_of(*only).instantiate_identity(), + ))); + } [only] => { err.help(with_no_trimmed_paths!(format!( "only type `{}` implements the trait, consider using it directly instead", @@ -148,6 +163,12 @@ pub fn report_object_safety_error<'tcx>( )); } } + if externally_visible { + err.note(format!( + "`{trait_str}` can be implemented in other crates; if you want to support your users \ + passing their own types here, you can't refer to a specific type", + )); + } err } diff --git a/tests/ui/generic-associated-types/issue-76535.base.stderr b/tests/ui/generic-associated-types/issue-76535.base.stderr index 875bc50630b28..bb14e297174a6 100644 --- a/tests/ui/generic-associated-types/issue-76535.base.stderr +++ b/tests/ui/generic-associated-types/issue-76535.base.stderr @@ -28,7 +28,8 @@ LL | pub trait SuperTrait { LL | type SubType<'a>: SubTrait where Self: 'a; | ^^^^^^^ ...because it contains the generic associated type `SubType` = help: consider moving `SubType` to another trait - = help: only type `SuperStruct` implements the trait, consider using it directly instead + = help: only type `SuperStruct` is seen to implement the trait in this crate, consider using it directly instead + = note: `SuperTrait` can be implemented in other crates; if you want to support your users passing their own types here, you can't refer to a specific type error[E0038]: the trait `SuperTrait` cannot be made into an object --> $DIR/issue-76535.rs:39:57 @@ -44,7 +45,8 @@ LL | pub trait SuperTrait { LL | type SubType<'a>: SubTrait where Self: 'a; | ^^^^^^^ ...because it contains the generic associated type `SubType` = help: consider moving `SubType` to another trait - = help: only type `SuperStruct` implements the trait, consider using it directly instead + = help: only type `SuperStruct` is seen to implement the trait in this crate, consider using it directly instead + = note: `SuperTrait` can be implemented in other crates; if you want to support your users passing their own types here, you can't refer to a specific type = note: required for the cast from `Box` to `Box>>` error: aborting due to 3 previous errors