summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_infer/src/infer/error_reporting/nice_region_error
diff options
context:
space:
mode:
Diffstat (limited to 'compiler/rustc_infer/src/infer/error_reporting/nice_region_error')
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs234
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs234
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs102
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mod.rs77
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs116
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs501
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs577
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs176
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs167
9 files changed, 2184 insertions, 0 deletions
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs
new file mode 100644
index 000000000..9a2ab3e32
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs
@@ -0,0 +1,234 @@
+//! Error Reporting for Anonymous Region Lifetime Errors
+//! where both the regions are anonymous.
+
+use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
+use crate::infer::error_reporting::nice_region_error::util::AnonymousParamInfo;
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::SubregionOrigin;
+use crate::infer::TyCtxt;
+
+use rustc_errors::{struct_span_err, Applicability, Diagnostic, ErrorGuaranteed};
+use rustc_hir as hir;
+use rustc_hir::{GenericParamKind, Ty};
+use rustc_middle::ty::Region;
+use rustc_span::symbol::kw;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ /// Print the error message for lifetime errors when both the concerned regions are anonymous.
+ ///
+ /// Consider a case where we have
+ ///
+ /// ```compile_fail,E0623
+ /// fn foo(x: &mut Vec<&u8>, y: &u8) {
+ /// x.push(y);
+ /// }
+ /// ```
+ ///
+ /// The example gives
+ ///
+ /// ```text
+ /// fn foo(x: &mut Vec<&u8>, y: &u8) {
+ /// --- --- these references are declared with different lifetimes...
+ /// x.push(y);
+ /// ^ ...but data from `y` flows into `x` here
+ /// ```
+ ///
+ /// It has been extended for the case of structs too.
+ ///
+ /// Consider the example
+ ///
+ /// ```no_run
+ /// struct Ref<'a> { x: &'a u32 }
+ /// ```
+ ///
+ /// ```text
+ /// fn foo(mut x: Vec<Ref>, y: Ref) {
+ /// --- --- these structs are declared with different lifetimes...
+ /// x.push(y);
+ /// ^ ...but data from `y` flows into `x` here
+ /// }
+ /// ```
+ ///
+ /// It will later be extended to trait objects.
+ pub(super) fn try_report_anon_anon_conflict(&self) -> Option<ErrorGuaranteed> {
+ let (span, sub, sup) = self.regions()?;
+
+ if let Some(RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::ReferenceOutlivesReferent(..),
+ ..,
+ )) = self.error
+ {
+ // This error doesn't make much sense in this case.
+ return None;
+ }
+
+ // Determine whether the sub and sup consist of both anonymous (elided) regions.
+ let anon_reg_sup = self.tcx().is_suitable_region(sup)?;
+
+ let anon_reg_sub = self.tcx().is_suitable_region(sub)?;
+ let scope_def_id_sup = anon_reg_sup.def_id;
+ let bregion_sup = anon_reg_sup.boundregion;
+ let scope_def_id_sub = anon_reg_sub.def_id;
+ let bregion_sub = anon_reg_sub.boundregion;
+
+ let ty_sup = find_anon_type(self.tcx(), sup, &bregion_sup)?;
+
+ let ty_sub = find_anon_type(self.tcx(), sub, &bregion_sub)?;
+
+ debug!(
+ "try_report_anon_anon_conflict: found_param1={:?} sup={:?} br1={:?}",
+ ty_sub, sup, bregion_sup
+ );
+ debug!(
+ "try_report_anon_anon_conflict: found_param2={:?} sub={:?} br2={:?}",
+ ty_sup, sub, bregion_sub
+ );
+
+ let (ty_sup, ty_fndecl_sup) = ty_sup;
+ let (ty_sub, ty_fndecl_sub) = ty_sub;
+
+ let AnonymousParamInfo { param: anon_param_sup, .. } =
+ self.find_param_with_region(sup, sup)?;
+ let AnonymousParamInfo { param: anon_param_sub, .. } =
+ self.find_param_with_region(sub, sub)?;
+
+ let sup_is_ret_type =
+ self.is_return_type_anon(scope_def_id_sup, bregion_sup, ty_fndecl_sup);
+ let sub_is_ret_type =
+ self.is_return_type_anon(scope_def_id_sub, bregion_sub, ty_fndecl_sub);
+
+ let span_label_var1 = match anon_param_sup.pat.simple_ident() {
+ Some(simple_ident) => format!(" from `{}`", simple_ident),
+ None => String::new(),
+ };
+
+ let span_label_var2 = match anon_param_sub.pat.simple_ident() {
+ Some(simple_ident) => format!(" into `{}`", simple_ident),
+ None => String::new(),
+ };
+
+ debug!(
+ "try_report_anon_anon_conflict: sub_is_ret_type={:?} sup_is_ret_type={:?}",
+ sub_is_ret_type, sup_is_ret_type
+ );
+
+ let mut err = struct_span_err!(self.tcx().sess, span, E0623, "lifetime mismatch");
+
+ match (sup_is_ret_type, sub_is_ret_type) {
+ (ret_capture @ Some(ret_span), _) | (_, ret_capture @ Some(ret_span)) => {
+ let param_span =
+ if sup_is_ret_type == ret_capture { ty_sub.span } else { ty_sup.span };
+
+ err.span_label(
+ param_span,
+ "this parameter and the return type are declared with different lifetimes...",
+ );
+ err.span_label(ret_span, "");
+ err.span_label(span, format!("...but data{} is returned here", span_label_var1));
+ }
+
+ (None, None) => {
+ if ty_sup.hir_id == ty_sub.hir_id {
+ err.span_label(ty_sup.span, "this type is declared with multiple lifetimes...");
+ err.span_label(ty_sub.span, "");
+ err.span_label(span, "...but data with one lifetime flows into the other here");
+ } else {
+ err.span_label(
+ ty_sup.span,
+ "these two types are declared with different lifetimes...",
+ );
+ err.span_label(ty_sub.span, "");
+ err.span_label(
+ span,
+ format!("...but data{} flows{} here", span_label_var1, span_label_var2),
+ );
+ }
+ }
+ }
+
+ if suggest_adding_lifetime_params(self.tcx(), sub, ty_sup, ty_sub, &mut err) {
+ err.note("each elided lifetime in input position becomes a distinct lifetime");
+ }
+
+ let reported = err.emit();
+ Some(reported)
+ }
+}
+
+pub fn suggest_adding_lifetime_params<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ sub: Region<'tcx>,
+ ty_sup: &Ty<'_>,
+ ty_sub: &Ty<'_>,
+ err: &mut Diagnostic,
+) -> bool {
+ let (
+ hir::Ty { kind: hir::TyKind::Rptr(lifetime_sub, _), .. },
+ hir::Ty { kind: hir::TyKind::Rptr(lifetime_sup, _), .. },
+ ) = (ty_sub, ty_sup) else {
+ return false;
+ };
+
+ if !lifetime_sub.name.is_anonymous() || !lifetime_sup.name.is_anonymous() {
+ return false;
+ };
+
+ let Some(anon_reg) = tcx.is_suitable_region(sub) else {
+ return false;
+ };
+
+ let hir_id = tcx.hir().local_def_id_to_hir_id(anon_reg.def_id);
+
+ let node = tcx.hir().get(hir_id);
+ let is_impl = matches!(&node, hir::Node::ImplItem(_));
+ let generics = match node {
+ hir::Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, ref generics, ..), .. })
+ | hir::Node::TraitItem(&hir::TraitItem { ref generics, .. })
+ | hir::Node::ImplItem(&hir::ImplItem { ref generics, .. }) => generics,
+ _ => return false,
+ };
+
+ let suggestion_param_name = generics
+ .params
+ .iter()
+ .filter(|p| matches!(p.kind, GenericParamKind::Lifetime { .. }))
+ .map(|p| p.name.ident().name)
+ .find(|i| *i != kw::UnderscoreLifetime);
+ let introduce_new = suggestion_param_name.is_none();
+ let suggestion_param_name =
+ suggestion_param_name.map(|n| n.to_string()).unwrap_or_else(|| "'a".to_owned());
+
+ debug!(?lifetime_sup.span);
+ debug!(?lifetime_sub.span);
+ let make_suggestion = |span: rustc_span::Span| {
+ if span.is_empty() {
+ (span, format!("{}, ", suggestion_param_name))
+ } else if let Ok("&") = tcx.sess.source_map().span_to_snippet(span).as_deref() {
+ (span.shrink_to_hi(), format!("{} ", suggestion_param_name))
+ } else {
+ (span, suggestion_param_name.clone())
+ }
+ };
+ let mut suggestions =
+ vec![make_suggestion(lifetime_sub.span), make_suggestion(lifetime_sup.span)];
+
+ if introduce_new {
+ let new_param_suggestion =
+ if let Some(first) = generics.params.iter().find(|p| !p.name.ident().span.is_empty()) {
+ (first.span.shrink_to_lo(), format!("{}, ", suggestion_param_name))
+ } else {
+ (generics.span, format!("<{}>", suggestion_param_name))
+ };
+
+ suggestions.push(new_param_suggestion);
+ }
+
+ let mut sugg = String::from("consider introducing a named lifetime parameter");
+ if is_impl {
+ sugg.push_str(" and update trait if needed");
+ }
+ err.multipart_suggestion(sugg, suggestions, Applicability::MaybeIncorrect);
+
+ true
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs
new file mode 100644
index 000000000..c1b201da6
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs
@@ -0,0 +1,234 @@
+use rustc_hir as hir;
+use rustc_hir::intravisit::{self, Visitor};
+use rustc_middle::hir::map::Map;
+use rustc_middle::hir::nested_filter;
+use rustc_middle::middle::resolve_lifetime as rl;
+use rustc_middle::ty::{self, Region, TyCtxt};
+
+/// This function calls the `visit_ty` method for the parameters
+/// corresponding to the anonymous regions. The `nested_visitor.found_type`
+/// contains the anonymous type.
+///
+/// # Arguments
+/// region - the anonymous region corresponding to the anon_anon conflict
+/// br - the bound region corresponding to the above region which is of type `BrAnon(_)`
+///
+/// # Example
+/// ```compile_fail,E0623
+/// fn foo(x: &mut Vec<&u8>, y: &u8)
+/// { x.push(y); }
+/// ```
+/// The function returns the nested type corresponding to the anonymous region
+/// for e.g., `&u8` and `Vec<&u8>`.
+pub fn find_anon_type<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ region: Region<'tcx>,
+ br: &ty::BoundRegionKind,
+) -> Option<(&'tcx hir::Ty<'tcx>, &'tcx hir::FnSig<'tcx>)> {
+ let anon_reg = tcx.is_suitable_region(region)?;
+ let hir_id = tcx.hir().local_def_id_to_hir_id(anon_reg.def_id);
+ let fn_sig = tcx.hir().get(hir_id).fn_sig()?;
+
+ fn_sig
+ .decl
+ .inputs
+ .iter()
+ .find_map(|arg| find_component_for_bound_region(tcx, arg, br))
+ .map(|ty| (ty, fn_sig))
+}
+
+// This method creates a FindNestedTypeVisitor which returns the type corresponding
+// to the anonymous region.
+fn find_component_for_bound_region<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ arg: &'tcx hir::Ty<'tcx>,
+ br: &ty::BoundRegionKind,
+) -> Option<&'tcx hir::Ty<'tcx>> {
+ let mut nested_visitor = FindNestedTypeVisitor {
+ tcx,
+ bound_region: *br,
+ found_type: None,
+ current_index: ty::INNERMOST,
+ };
+ nested_visitor.visit_ty(arg);
+ nested_visitor.found_type
+}
+
+// The FindNestedTypeVisitor captures the corresponding `hir::Ty` of the
+// anonymous region. The example above would lead to a conflict between
+// the two anonymous lifetimes for &u8 in x and y respectively. This visitor
+// would be invoked twice, once for each lifetime, and would
+// walk the types like &mut Vec<&u8> and &u8 looking for the HIR
+// where that lifetime appears. This allows us to highlight the
+// specific part of the type in the error message.
+struct FindNestedTypeVisitor<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ // The bound_region corresponding to the Refree(freeregion)
+ // associated with the anonymous region we are looking for.
+ bound_region: ty::BoundRegionKind,
+ // The type where the anonymous lifetime appears
+ // for e.g., Vec<`&u8`> and <`&u8`>
+ found_type: Option<&'tcx hir::Ty<'tcx>>,
+ current_index: ty::DebruijnIndex,
+}
+
+impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> {
+ type NestedFilter = nested_filter::OnlyBodies;
+
+ fn nested_visit_map(&mut self) -> Self::Map {
+ self.tcx.hir()
+ }
+
+ fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
+ match arg.kind {
+ hir::TyKind::BareFn(_) => {
+ self.current_index.shift_in(1);
+ intravisit::walk_ty(self, arg);
+ self.current_index.shift_out(1);
+ return;
+ }
+
+ hir::TyKind::TraitObject(bounds, ..) => {
+ for bound in bounds {
+ self.current_index.shift_in(1);
+ self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
+ self.current_index.shift_out(1);
+ }
+ }
+
+ hir::TyKind::Rptr(ref lifetime, _) => {
+ // the lifetime of the TyRptr
+ let hir_id = lifetime.hir_id;
+ match (self.tcx.named_region(hir_id), self.bound_region) {
+ // Find the index of the named region that was part of the
+ // error. We will then search the function parameters for a bound
+ // region at the right depth with the same index
+ (Some(rl::Region::EarlyBound(_, id)), ty::BrNamed(def_id, _)) => {
+ debug!("EarlyBound id={:?} def_id={:?}", id, def_id);
+ if id == def_id {
+ self.found_type = Some(arg);
+ return; // we can stop visiting now
+ }
+ }
+
+ // Find the index of the named region that was part of the
+ // error. We will then search the function parameters for a bound
+ // region at the right depth with the same index
+ (
+ Some(rl::Region::LateBound(debruijn_index, _, id)),
+ ty::BrNamed(def_id, _),
+ ) => {
+ debug!(
+ "FindNestedTypeVisitor::visit_ty: LateBound depth = {:?}",
+ debruijn_index
+ );
+ debug!("LateBound id={:?} def_id={:?}", id, def_id);
+ if debruijn_index == self.current_index && id == def_id {
+ self.found_type = Some(arg);
+ return; // we can stop visiting now
+ }
+ }
+
+ (
+ Some(
+ rl::Region::Static
+ | rl::Region::Free(_, _)
+ | rl::Region::EarlyBound(_, _)
+ | rl::Region::LateBound(_, _, _),
+ )
+ | None,
+ _,
+ ) => {
+ debug!("no arg found");
+ }
+ }
+ }
+ // Checks if it is of type `hir::TyKind::Path` which corresponds to a struct.
+ hir::TyKind::Path(_) => {
+ let subvisitor = &mut TyPathVisitor {
+ tcx: self.tcx,
+ found_it: false,
+ bound_region: self.bound_region,
+ current_index: self.current_index,
+ };
+ intravisit::walk_ty(subvisitor, arg); // call walk_ty; as visit_ty is empty,
+ // this will visit only outermost type
+ if subvisitor.found_it {
+ self.found_type = Some(arg);
+ }
+ }
+ _ => {}
+ }
+ // walk the embedded contents: e.g., if we are visiting `Vec<&Foo>`,
+ // go on to visit `&Foo`
+ intravisit::walk_ty(self, arg);
+ }
+}
+
+// The visitor captures the corresponding `hir::Ty` of the anonymous region
+// in the case of structs ie. `hir::TyKind::Path`.
+// This visitor would be invoked for each lifetime corresponding to a struct,
+// and would walk the types like Vec<Ref> in the above example and Ref looking for the HIR
+// where that lifetime appears. This allows us to highlight the
+// specific part of the type in the error message.
+struct TyPathVisitor<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ found_it: bool,
+ bound_region: ty::BoundRegionKind,
+ current_index: ty::DebruijnIndex,
+}
+
+impl<'tcx> Visitor<'tcx> for TyPathVisitor<'tcx> {
+ type NestedFilter = nested_filter::OnlyBodies;
+
+ fn nested_visit_map(&mut self) -> Map<'tcx> {
+ self.tcx.hir()
+ }
+
+ fn visit_lifetime(&mut self, lifetime: &hir::Lifetime) {
+ match (self.tcx.named_region(lifetime.hir_id), self.bound_region) {
+ // the lifetime of the TyPath!
+ (Some(rl::Region::EarlyBound(_, id)), ty::BrNamed(def_id, _)) => {
+ debug!("EarlyBound id={:?} def_id={:?}", id, def_id);
+ if id == def_id {
+ self.found_it = true;
+ return; // we can stop visiting now
+ }
+ }
+
+ (Some(rl::Region::LateBound(debruijn_index, _, id)), ty::BrNamed(def_id, _)) => {
+ debug!("FindNestedTypeVisitor::visit_ty: LateBound depth = {:?}", debruijn_index,);
+ debug!("id={:?}", id);
+ debug!("def_id={:?}", def_id);
+ if debruijn_index == self.current_index && id == def_id {
+ self.found_it = true;
+ return; // we can stop visiting now
+ }
+ }
+
+ (
+ Some(
+ rl::Region::Static
+ | rl::Region::EarlyBound(_, _)
+ | rl::Region::LateBound(_, _, _)
+ | rl::Region::Free(_, _),
+ )
+ | None,
+ _,
+ ) => {
+ debug!("no arg found");
+ }
+ }
+ }
+
+ fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
+ // ignore nested types
+ //
+ // If you have a type like `Foo<'a, &Ty>` we
+ // are only interested in the immediate lifetimes ('a).
+ //
+ // Making `visit_ty` empty will ignore the `&Ty` embedded
+ // inside, it will get reached by the outer visitor.
+ debug!("`Ty` corresponding to a struct is {:?}", arg);
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs
new file mode 100644
index 000000000..893ca3cf7
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs
@@ -0,0 +1,102 @@
+//! Error Reporting for when the lifetime for a type doesn't match the `impl` selected for a predicate
+//! to hold.
+
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::error_reporting::note_and_explain_region;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::{SubregionOrigin, TypeTrace};
+use crate::traits::ObligationCauseCode;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
+use rustc_hir as hir;
+use rustc_hir::intravisit::Visitor;
+use rustc_middle::ty::TypeVisitor;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ pub(super) fn try_report_mismatched_static_lifetime(&self) -> Option<ErrorGuaranteed> {
+ let error = self.error.as_ref()?;
+ debug!("try_report_mismatched_static_lifetime {:?}", error);
+
+ let RegionResolutionError::ConcreteFailure(origin, sub, sup) = error.clone() else {
+ return None;
+ };
+ if !sub.is_static() {
+ return None;
+ }
+ let SubregionOrigin::Subtype(box TypeTrace { ref cause, .. }) = origin else {
+ return None;
+ };
+ // If we added a "points at argument expression" obligation, we remove it here, we care
+ // about the original obligation only.
+ let code = match cause.code() {
+ ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => &*parent_code,
+ code => code,
+ };
+ let ObligationCauseCode::MatchImpl(parent, impl_def_id) = code else {
+ return None;
+ };
+ let ObligationCauseCode::BindingObligation(_def_id, binding_span) = *parent.code() else {
+ return None;
+ };
+ let mut err = self.tcx().sess.struct_span_err(cause.span, "incompatible lifetime on type");
+ // FIXME: we should point at the lifetime
+ let mut multi_span: MultiSpan = vec![binding_span].into();
+ multi_span.push_span_label(binding_span, "introduces a `'static` lifetime requirement");
+ err.span_note(multi_span, "because this has an unmet lifetime requirement");
+ note_and_explain_region(self.tcx(), &mut err, "", sup, "...", Some(binding_span));
+ if let Some(impl_node) = self.tcx().hir().get_if_local(*impl_def_id) {
+ // If an impl is local, then maybe this isn't what they want. Try to
+ // be as helpful as possible with implicit lifetimes.
+
+ // First, let's get the hir self type of the impl
+ let hir::Node::Item(hir::Item {
+ kind: hir::ItemKind::Impl(hir::Impl { self_ty: impl_self_ty, .. }),
+ ..
+ }) = impl_node else {
+ bug!("Node not an impl.");
+ };
+
+ // Next, let's figure out the set of trait objects with implicit static bounds
+ let ty = self.tcx().type_of(*impl_def_id);
+ let mut v = super::static_impl_trait::TraitObjectVisitor(FxHashSet::default());
+ v.visit_ty(ty);
+ let mut traits = vec![];
+ for matching_def_id in v.0 {
+ let mut hir_v =
+ super::static_impl_trait::HirTraitObjectVisitor(&mut traits, matching_def_id);
+ hir_v.visit_ty(&impl_self_ty);
+ }
+
+ if traits.is_empty() {
+ // If there are no trait object traits to point at, either because
+ // there aren't trait objects or because none are implicit, then just
+ // write a single note on the impl itself.
+
+ let impl_span = self.tcx().def_span(*impl_def_id);
+ err.span_note(impl_span, "...does not necessarily outlive the static lifetime introduced by the compatible `impl`");
+ } else {
+ // Otherwise, point at all implicit static lifetimes
+
+ err.note("...does not necessarily outlive the static lifetime introduced by the compatible `impl`");
+ for span in &traits {
+ err.span_note(*span, "this has an implicit `'static` lifetime requirement");
+ // It would be nice to put this immediately under the above note, but they get
+ // pushed to the end.
+ err.span_suggestion_verbose(
+ span.shrink_to_hi(),
+ "consider relaxing the implicit `'static` requirement",
+ " + '_",
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ } else {
+ // Otherwise just point out the impl.
+
+ let impl_span = self.tcx().def_span(*impl_def_id);
+ err.span_note(impl_span, "...does not necessarily outlive the static lifetime introduced by the compatible `impl`");
+ }
+ let reported = err.emit();
+ Some(reported)
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mod.rs
new file mode 100644
index 000000000..53d9acf7d
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mod.rs
@@ -0,0 +1,77 @@
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError::*;
+use crate::infer::InferCtxt;
+use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed};
+use rustc_middle::ty::{self, TyCtxt};
+use rustc_span::source_map::Span;
+
+mod different_lifetimes;
+pub mod find_anon_type;
+mod mismatched_static_lifetime;
+mod named_anon_conflict;
+mod placeholder_error;
+mod static_impl_trait;
+mod trait_impl_difference;
+mod util;
+
+pub use different_lifetimes::suggest_adding_lifetime_params;
+pub use find_anon_type::find_anon_type;
+pub use static_impl_trait::{suggest_new_region_bound, HirTraitObjectVisitor, TraitObjectVisitor};
+pub use util::find_param_with_region;
+
+impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
+ pub fn try_report_nice_region_error(&self, error: &RegionResolutionError<'tcx>) -> bool {
+ NiceRegionError::new(self, error.clone()).try_report().is_some()
+ }
+}
+
+pub struct NiceRegionError<'cx, 'tcx> {
+ infcx: &'cx InferCtxt<'cx, 'tcx>,
+ error: Option<RegionResolutionError<'tcx>>,
+ regions: Option<(Span, ty::Region<'tcx>, ty::Region<'tcx>)>,
+}
+
+impl<'cx, 'tcx> NiceRegionError<'cx, 'tcx> {
+ pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>, error: RegionResolutionError<'tcx>) -> Self {
+ Self { infcx, error: Some(error), regions: None }
+ }
+
+ pub fn new_from_span(
+ infcx: &'cx InferCtxt<'cx, 'tcx>,
+ span: Span,
+ sub: ty::Region<'tcx>,
+ sup: ty::Region<'tcx>,
+ ) -> Self {
+ Self { infcx, error: None, regions: Some((span, sub, sup)) }
+ }
+
+ fn tcx(&self) -> TyCtxt<'tcx> {
+ self.infcx.tcx
+ }
+
+ pub fn try_report_from_nll(&self) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
+ // Due to the improved diagnostics returned by the MIR borrow checker, only a subset of
+ // the nice region errors are required when running under the MIR borrow checker.
+ self.try_report_named_anon_conflict().or_else(|| self.try_report_placeholder_conflict())
+ }
+
+ pub fn try_report(&self) -> Option<ErrorGuaranteed> {
+ self.try_report_from_nll()
+ .map(|mut diag| diag.emit())
+ .or_else(|| self.try_report_impl_not_conforming_to_trait())
+ .or_else(|| self.try_report_anon_anon_conflict())
+ .or_else(|| self.try_report_static_impl_trait())
+ .or_else(|| self.try_report_mismatched_static_lifetime())
+ }
+
+ pub(super) fn regions(&self) -> Option<(Span, ty::Region<'tcx>, ty::Region<'tcx>)> {
+ match (&self.error, self.regions) {
+ (Some(ConcreteFailure(origin, sub, sup)), None) => Some((origin.span(), *sub, *sup)),
+ (Some(SubSupConflict(_, _, origin, sub, _, sup, _)), None) => {
+ Some((origin.span(), *sub, *sup))
+ }
+ (None, Some((span, sub, sup))) => Some((span, sub, sup)),
+ _ => None,
+ }
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs
new file mode 100644
index 000000000..76cb76d9f
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs
@@ -0,0 +1,116 @@
+//! Error Reporting for Anonymous Region Lifetime Errors
+//! where one region is named and the other is anonymous.
+use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
+use rustc_middle::ty;
+use rustc_span::symbol::kw;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ /// When given a `ConcreteFailure` for a function with parameters containing a named region and
+ /// an anonymous region, emit an descriptive diagnostic error.
+ pub(super) fn try_report_named_anon_conflict(
+ &self,
+ ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
+ let (span, sub, sup) = self.regions()?;
+
+ debug!(
+ "try_report_named_anon_conflict(sub={:?}, sup={:?}, error={:?})",
+ sub, sup, self.error,
+ );
+
+ // Determine whether the sub and sup consist of one named region ('a)
+ // and one anonymous (elided) region. If so, find the parameter arg
+ // where the anonymous region appears (there must always be one; we
+ // only introduced anonymous regions in parameters) as well as a
+ // version new_ty of its type where the anonymous region is replaced
+ // with the named one.
+ let (named, anon, anon_param_info, region_info) = if sub.has_name()
+ && self.tcx().is_suitable_region(sup).is_some()
+ && self.find_param_with_region(sup, sub).is_some()
+ {
+ (
+ sub,
+ sup,
+ self.find_param_with_region(sup, sub).unwrap(),
+ self.tcx().is_suitable_region(sup).unwrap(),
+ )
+ } else if sup.has_name()
+ && self.tcx().is_suitable_region(sub).is_some()
+ && self.find_param_with_region(sub, sup).is_some()
+ {
+ (
+ sup,
+ sub,
+ self.find_param_with_region(sub, sup).unwrap(),
+ self.tcx().is_suitable_region(sub).unwrap(),
+ )
+ } else {
+ return None; // inapplicable
+ };
+
+ // Suggesting to add a `'static` lifetime to a parameter is nearly always incorrect,
+ // and can steer users down the wrong path.
+ if named.is_static() {
+ return None;
+ }
+
+ debug!("try_report_named_anon_conflict: named = {:?}", named);
+ debug!("try_report_named_anon_conflict: anon_param_info = {:?}", anon_param_info);
+ debug!("try_report_named_anon_conflict: region_info = {:?}", region_info);
+
+ let param = anon_param_info.param;
+ let new_ty = anon_param_info.param_ty;
+ let new_ty_span = anon_param_info.param_ty_span;
+ let br = anon_param_info.bound_region;
+ let is_first = anon_param_info.is_first;
+ let scope_def_id = region_info.def_id;
+ let is_impl_item = region_info.is_impl_item;
+
+ match br {
+ ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) => {}
+ _ => {
+ /* not an anonymous region */
+ debug!("try_report_named_anon_conflict: not an anonymous region");
+ return None;
+ }
+ }
+
+ if is_impl_item {
+ debug!("try_report_named_anon_conflict: impl item, bail out");
+ return None;
+ }
+
+ if find_anon_type(self.tcx(), anon, &br).is_some()
+ && self.is_self_anon(is_first, scope_def_id)
+ {
+ return None;
+ }
+
+ let (error_var, span_label_var) = match param.pat.simple_ident() {
+ Some(simple_ident) => (
+ format!("the type of `{}`", simple_ident),
+ format!("the type of `{}`", simple_ident),
+ ),
+ None => ("parameter type".to_owned(), "type".to_owned()),
+ };
+
+ let mut diag = struct_span_err!(
+ self.tcx().sess,
+ span,
+ E0621,
+ "explicit lifetime required in {}",
+ error_var
+ );
+
+ diag.span_label(span, format!("lifetime `{}` required", named));
+ diag.span_suggestion(
+ new_ty_span,
+ &format!("add explicit lifetime `{}` to {}", named, span_label_var),
+ new_ty,
+ Applicability::Unspecified,
+ );
+
+ Some(diag)
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs
new file mode 100644
index 000000000..998699158
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs
@@ -0,0 +1,501 @@
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::ValuePairs;
+use crate::infer::{SubregionOrigin, TypeTrace};
+use crate::traits::{ObligationCause, ObligationCauseCode};
+use rustc_data_structures::intern::Interned;
+use rustc_errors::{Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
+use rustc_hir::def::Namespace;
+use rustc_hir::def_id::DefId;
+use rustc_middle::ty::error::ExpectedFound;
+use rustc_middle::ty::print::{FmtPrinter, Print, RegionHighlightMode};
+use rustc_middle::ty::subst::SubstsRef;
+use rustc_middle::ty::{self, RePlaceholder, ReVar, Region, TyCtxt};
+
+use std::fmt::{self, Write};
+
+impl<'tcx> NiceRegionError<'_, 'tcx> {
+ /// When given a `ConcreteFailure` for a function with arguments containing a named region and
+ /// an anonymous region, emit a descriptive diagnostic error.
+ pub(super) fn try_report_placeholder_conflict(
+ &self,
+ ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
+ match &self.error {
+ ///////////////////////////////////////////////////////////////////////////
+ // NB. The ordering of cases in this match is very
+ // sensitive, because we are often matching against
+ // specific cases and then using an `_` to match all
+ // others.
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Check for errors from comparing trait failures -- first
+ // with two placeholders, then with one.
+ Some(RegionResolutionError::SubSupConflict(
+ vid,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ Some(*sub_placeholder),
+ Some(*sup_placeholder),
+ values,
+ ),
+
+ Some(RegionResolutionError::SubSupConflict(
+ vid,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ _,
+ _,
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ Some(*sub_placeholder),
+ None,
+ values,
+ ),
+
+ Some(RegionResolutionError::SubSupConflict(
+ vid,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ _,
+ _,
+ sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ None,
+ Some(*sup_placeholder),
+ values,
+ ),
+
+ Some(RegionResolutionError::SubSupConflict(
+ vid,
+ _,
+ _,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ None,
+ Some(*sup_placeholder),
+ values,
+ ),
+
+ Some(RegionResolutionError::UpperBoundUniverseConflict(
+ vid,
+ _,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ None,
+ Some(*sup_placeholder),
+ values,
+ ),
+
+ Some(RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_region @ Region(Interned(RePlaceholder(_), _)),
+ sup_region @ Region(Interned(RePlaceholder(_), _)),
+ )) => self.try_report_trait_placeholder_mismatch(
+ None,
+ cause,
+ Some(*sub_region),
+ Some(*sup_region),
+ values,
+ ),
+
+ Some(RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_region @ Region(Interned(RePlaceholder(_), _)),
+ sup_region,
+ )) => self.try_report_trait_placeholder_mismatch(
+ (!sup_region.has_name()).then_some(*sup_region),
+ cause,
+ Some(*sub_region),
+ None,
+ values,
+ ),
+
+ Some(RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_region,
+ sup_region @ Region(Interned(RePlaceholder(_), _)),
+ )) => self.try_report_trait_placeholder_mismatch(
+ (!sub_region.has_name()).then_some(*sub_region),
+ cause,
+ None,
+ Some(*sup_region),
+ values,
+ ),
+
+ _ => None,
+ }
+ }
+
+ fn try_report_trait_placeholder_mismatch(
+ &self,
+ vid: Option<Region<'tcx>>,
+ cause: &ObligationCause<'tcx>,
+ sub_placeholder: Option<Region<'tcx>>,
+ sup_placeholder: Option<Region<'tcx>>,
+ value_pairs: &ValuePairs<'tcx>,
+ ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
+ let (expected_substs, found_substs, trait_def_id) = match value_pairs {
+ ValuePairs::TraitRefs(ExpectedFound { expected, found })
+ if expected.def_id == found.def_id =>
+ {
+ (expected.substs, found.substs, expected.def_id)
+ }
+ ValuePairs::PolyTraitRefs(ExpectedFound { expected, found })
+ if expected.def_id() == found.def_id() =>
+ {
+ // It's possible that the placeholders come from a binder
+ // outside of this value pair. Use `no_bound_vars` as a
+ // simple heuristic for that.
+ (expected.no_bound_vars()?.substs, found.no_bound_vars()?.substs, expected.def_id())
+ }
+ _ => return None,
+ };
+
+ Some(self.report_trait_placeholder_mismatch(
+ vid,
+ cause,
+ sub_placeholder,
+ sup_placeholder,
+ trait_def_id,
+ expected_substs,
+ found_substs,
+ ))
+ }
+
+ // error[E0308]: implementation of `Foo` does not apply to enough lifetimes
+ // --> /home/nmatsakis/tmp/foo.rs:12:5
+ // |
+ // 12 | all::<&'static u32>();
+ // | ^^^^^^^^^^^^^^^^^^^ lifetime mismatch
+ // |
+ // = note: Due to a where-clause on the function `all`,
+ // = note: `T` must implement `...` for any two lifetimes `'1` and `'2`.
+ // = note: However, the type `T` only implements `...` for some specific lifetime `'2`.
+ #[instrument(level = "debug", skip(self))]
+ fn report_trait_placeholder_mismatch(
+ &self,
+ vid: Option<Region<'tcx>>,
+ cause: &ObligationCause<'tcx>,
+ sub_placeholder: Option<Region<'tcx>>,
+ sup_placeholder: Option<Region<'tcx>>,
+ trait_def_id: DefId,
+ expected_substs: SubstsRef<'tcx>,
+ actual_substs: SubstsRef<'tcx>,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ let span = cause.span();
+ let msg = format!(
+ "implementation of `{}` is not general enough",
+ self.tcx().def_path_str(trait_def_id),
+ );
+ let mut err = self.tcx().sess.struct_span_err(span, &msg);
+
+ let leading_ellipsis = if let ObligationCauseCode::ItemObligation(def_id) = *cause.code() {
+ err.span_label(span, "doesn't satisfy where-clause");
+ err.span_label(
+ self.tcx().def_span(def_id),
+ &format!("due to a where-clause on `{}`...", self.tcx().def_path_str(def_id)),
+ );
+ true
+ } else {
+ err.span_label(span, &msg);
+ false
+ };
+
+ let expected_trait_ref = self.infcx.resolve_vars_if_possible(ty::TraitRef {
+ def_id: trait_def_id,
+ substs: expected_substs,
+ });
+ let actual_trait_ref = self
+ .infcx
+ .resolve_vars_if_possible(ty::TraitRef { def_id: trait_def_id, substs: actual_substs });
+
+ // Search the expected and actual trait references to see (a)
+ // whether the sub/sup placeholders appear in them (sometimes
+ // you have a trait ref like `T: Foo<fn(&u8)>`, where the
+ // placeholder was created as part of an inner type) and (b)
+ // whether the inference variable appears. In each case,
+ // assign a counter value in each case if so.
+ let mut counter = 0;
+ let mut has_sub = None;
+ let mut has_sup = None;
+
+ let mut actual_has_vid = None;
+ let mut expected_has_vid = None;
+
+ self.tcx().for_each_free_region(&expected_trait_ref, |r| {
+ if Some(r) == sub_placeholder && has_sub.is_none() {
+ has_sub = Some(counter);
+ counter += 1;
+ } else if Some(r) == sup_placeholder && has_sup.is_none() {
+ has_sup = Some(counter);
+ counter += 1;
+ }
+
+ if Some(r) == vid && expected_has_vid.is_none() {
+ expected_has_vid = Some(counter);
+ counter += 1;
+ }
+ });
+
+ self.tcx().for_each_free_region(&actual_trait_ref, |r| {
+ if Some(r) == vid && actual_has_vid.is_none() {
+ actual_has_vid = Some(counter);
+ counter += 1;
+ }
+ });
+
+ let actual_self_ty_has_vid =
+ self.tcx().any_free_region_meets(&actual_trait_ref.self_ty(), |r| Some(r) == vid);
+
+ let expected_self_ty_has_vid =
+ self.tcx().any_free_region_meets(&expected_trait_ref.self_ty(), |r| Some(r) == vid);
+
+ let any_self_ty_has_vid = actual_self_ty_has_vid || expected_self_ty_has_vid;
+
+ debug!(
+ ?actual_has_vid,
+ ?expected_has_vid,
+ ?has_sub,
+ ?has_sup,
+ ?actual_self_ty_has_vid,
+ ?expected_self_ty_has_vid,
+ );
+
+ self.explain_actual_impl_that_was_found(
+ &mut err,
+ sub_placeholder,
+ sup_placeholder,
+ has_sub,
+ has_sup,
+ expected_trait_ref,
+ actual_trait_ref,
+ vid,
+ expected_has_vid,
+ actual_has_vid,
+ any_self_ty_has_vid,
+ leading_ellipsis,
+ );
+
+ err
+ }
+
+ /// Add notes with details about the expected and actual trait refs, with attention to cases
+ /// when placeholder regions are involved: either the trait or the self type containing
+ /// them needs to be mentioned the closest to the placeholders.
+ /// This makes the error messages read better, however at the cost of some complexity
+ /// due to the number of combinations we have to deal with.
+ fn explain_actual_impl_that_was_found(
+ &self,
+ err: &mut Diagnostic,
+ sub_placeholder: Option<Region<'tcx>>,
+ sup_placeholder: Option<Region<'tcx>>,
+ has_sub: Option<usize>,
+ has_sup: Option<usize>,
+ expected_trait_ref: ty::TraitRef<'tcx>,
+ actual_trait_ref: ty::TraitRef<'tcx>,
+ vid: Option<Region<'tcx>>,
+ expected_has_vid: Option<usize>,
+ actual_has_vid: Option<usize>,
+ any_self_ty_has_vid: bool,
+ leading_ellipsis: bool,
+ ) {
+ // HACK(eddyb) maybe move this in a more central location.
+ #[derive(Copy, Clone)]
+ struct Highlighted<'tcx, T> {
+ tcx: TyCtxt<'tcx>,
+ highlight: RegionHighlightMode<'tcx>,
+ value: T,
+ }
+
+ impl<'tcx, T> Highlighted<'tcx, T> {
+ fn map<U>(self, f: impl FnOnce(T) -> U) -> Highlighted<'tcx, U> {
+ Highlighted { tcx: self.tcx, highlight: self.highlight, value: f(self.value) }
+ }
+ }
+
+ impl<'tcx, T> fmt::Display for Highlighted<'tcx, T>
+ where
+ T: for<'a> Print<
+ 'tcx,
+ FmtPrinter<'a, 'tcx>,
+ Error = fmt::Error,
+ Output = FmtPrinter<'a, 'tcx>,
+ >,
+ {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS);
+ printer.region_highlight_mode = self.highlight;
+
+ let s = self.value.print(printer)?.into_buffer();
+ f.write_str(&s)
+ }
+ }
+
+ // The weird thing here with the `maybe_highlighting_region` calls and the
+ // the match inside is meant to be like this:
+ //
+ // - The match checks whether the given things (placeholders, etc) appear
+ // in the types are about to print
+ // - Meanwhile, the `maybe_highlighting_region` calls set up
+ // highlights so that, if they do appear, we will replace
+ // them `'0` and whatever. (This replacement takes place
+ // inside the closure given to `maybe_highlighting_region`.)
+ //
+ // There is some duplication between the calls -- i.e., the
+ // `maybe_highlighting_region` checks if (e.g.) `has_sub` is
+ // None, an then we check again inside the closure, but this
+ // setup sort of minimized the number of calls and so form.
+
+ let highlight_trait_ref = |trait_ref| Highlighted {
+ tcx: self.tcx(),
+ highlight: RegionHighlightMode::new(self.tcx()),
+ value: trait_ref,
+ };
+
+ let same_self_type = actual_trait_ref.self_ty() == expected_trait_ref.self_ty();
+
+ let mut expected_trait_ref = highlight_trait_ref(expected_trait_ref);
+ expected_trait_ref.highlight.maybe_highlighting_region(sub_placeholder, has_sub);
+ expected_trait_ref.highlight.maybe_highlighting_region(sup_placeholder, has_sup);
+ err.note(&{
+ let passive_voice = match (has_sub, has_sup) {
+ (Some(_), _) | (_, Some(_)) => any_self_ty_has_vid,
+ (None, None) => {
+ expected_trait_ref.highlight.maybe_highlighting_region(vid, expected_has_vid);
+ match expected_has_vid {
+ Some(_) => true,
+ None => any_self_ty_has_vid,
+ }
+ }
+ };
+
+ let mut note = if same_self_type {
+ let mut self_ty = expected_trait_ref.map(|tr| tr.self_ty());
+ self_ty.highlight.maybe_highlighting_region(vid, actual_has_vid);
+
+ if self_ty.value.is_closure()
+ && self
+ .tcx()
+ .fn_trait_kind_from_lang_item(expected_trait_ref.value.def_id)
+ .is_some()
+ {
+ let closure_sig = self_ty.map(|closure| {
+ if let ty::Closure(_, substs) = closure.kind() {
+ self.tcx().signature_unclosure(
+ substs.as_closure().sig(),
+ rustc_hir::Unsafety::Normal,
+ )
+ } else {
+ bug!("type is not longer closure");
+ }
+ });
+
+ format!(
+ "{}closure with signature `{}` must implement `{}`",
+ if leading_ellipsis { "..." } else { "" },
+ closure_sig,
+ expected_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ } else {
+ format!(
+ "{}`{}` must implement `{}`",
+ if leading_ellipsis { "..." } else { "" },
+ self_ty,
+ expected_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ }
+ } else if passive_voice {
+ format!(
+ "{}`{}` would have to be implemented for the type `{}`",
+ if leading_ellipsis { "..." } else { "" },
+ expected_trait_ref.map(|tr| tr.print_only_trait_path()),
+ expected_trait_ref.map(|tr| tr.self_ty()),
+ )
+ } else {
+ format!(
+ "{}`{}` must implement `{}`",
+ if leading_ellipsis { "..." } else { "" },
+ expected_trait_ref.map(|tr| tr.self_ty()),
+ expected_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ };
+
+ match (has_sub, has_sup) {
+ (Some(n1), Some(n2)) => {
+ let _ = write!(
+ note,
+ ", for any two lifetimes `'{}` and `'{}`...",
+ std::cmp::min(n1, n2),
+ std::cmp::max(n1, n2),
+ );
+ }
+ (Some(n), _) | (_, Some(n)) => {
+ let _ = write!(note, ", for any lifetime `'{}`...", n,);
+ }
+ (None, None) => {
+ if let Some(n) = expected_has_vid {
+ let _ = write!(note, ", for some specific lifetime `'{}`...", n,);
+ }
+ }
+ }
+
+ note
+ });
+
+ let mut actual_trait_ref = highlight_trait_ref(actual_trait_ref);
+ actual_trait_ref.highlight.maybe_highlighting_region(vid, actual_has_vid);
+ err.note(&{
+ let passive_voice = match actual_has_vid {
+ Some(_) => any_self_ty_has_vid,
+ None => true,
+ };
+
+ let mut note = if same_self_type {
+ format!(
+ "...but it actually implements `{}`",
+ actual_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ } else if passive_voice {
+ format!(
+ "...but `{}` is actually implemented for the type `{}`",
+ actual_trait_ref.map(|tr| tr.print_only_trait_path()),
+ actual_trait_ref.map(|tr| tr.self_ty()),
+ )
+ } else {
+ format!(
+ "...but `{}` actually implements `{}`",
+ actual_trait_ref.map(|tr| tr.self_ty()),
+ actual_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ };
+
+ if let Some(n) = actual_has_vid {
+ let _ = write!(note, ", for some specific lifetime `'{}`", n);
+ }
+
+ note
+ });
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs
new file mode 100644
index 000000000..9886c572a
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs
@@ -0,0 +1,577 @@
+//! Error Reporting for static impl Traits.
+
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::{SubregionOrigin, TypeTrace};
+use crate::traits::{ObligationCauseCode, UnifyReceiverContext};
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::{struct_span_err, Applicability, Diagnostic, ErrorGuaranteed, MultiSpan};
+use rustc_hir::def_id::DefId;
+use rustc_hir::intravisit::{walk_ty, Visitor};
+use rustc_hir::{self as hir, GenericBound, Item, ItemKind, Lifetime, LifetimeName, Node, TyKind};
+use rustc_middle::ty::{
+ self, AssocItemContainer, StaticLifetimeVisitor, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor,
+};
+use rustc_span::symbol::Ident;
+use rustc_span::Span;
+
+use std::ops::ControlFlow;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ /// Print the error message for lifetime errors when the return type is a static `impl Trait`,
+ /// `dyn Trait` or if a method call on a trait object introduces a static requirement.
+ pub(super) fn try_report_static_impl_trait(&self) -> Option<ErrorGuaranteed> {
+ debug!("try_report_static_impl_trait(error={:?})", self.error);
+ let tcx = self.tcx();
+ let (var_origin, sub_origin, sub_r, sup_origin, sup_r, spans) = match self.error.as_ref()? {
+ RegionResolutionError::SubSupConflict(
+ _,
+ var_origin,
+ sub_origin,
+ sub_r,
+ sup_origin,
+ sup_r,
+ spans,
+ ) if sub_r.is_static() => (var_origin, sub_origin, sub_r, sup_origin, sup_r, spans),
+ RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::Subtype(box TypeTrace { cause, .. }),
+ sub_r,
+ sup_r,
+ ) if sub_r.is_static() => {
+ // This is for an implicit `'static` requirement coming from `impl dyn Trait {}`.
+ if let ObligationCauseCode::UnifyReceiver(ctxt) = cause.code() {
+ // This may have a closure and it would cause ICE
+ // through `find_param_with_region` (#78262).
+ let anon_reg_sup = tcx.is_suitable_region(*sup_r)?;
+ let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.def_id);
+ if fn_returns.is_empty() {
+ return None;
+ }
+
+ let param = self.find_param_with_region(*sup_r, *sub_r)?;
+ let lifetime = if sup_r.has_name() {
+ format!("lifetime `{}`", sup_r)
+ } else {
+ "an anonymous lifetime `'_`".to_string()
+ };
+ let mut err = struct_span_err!(
+ tcx.sess,
+ cause.span,
+ E0772,
+ "{} has {} but calling `{}` introduces an implicit `'static` lifetime \
+ requirement",
+ param
+ .param
+ .pat
+ .simple_ident()
+ .map(|s| format!("`{}`", s))
+ .unwrap_or_else(|| "`fn` parameter".to_string()),
+ lifetime,
+ ctxt.assoc_item.name,
+ );
+ err.span_label(param.param_ty_span, &format!("this data with {}...", lifetime));
+ err.span_label(
+ cause.span,
+ &format!(
+ "...is used and required to live as long as `'static` here \
+ because of an implicit lifetime bound on the {}",
+ match ctxt.assoc_item.container {
+ AssocItemContainer::TraitContainer => {
+ let id = ctxt.assoc_item.container_id(tcx);
+ format!("`impl` of `{}`", tcx.def_path_str(id))
+ }
+ AssocItemContainer::ImplContainer => "inherent `impl`".to_string(),
+ },
+ ),
+ );
+ if self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt) {
+ let reported = err.emit();
+ return Some(reported);
+ } else {
+ err.cancel();
+ }
+ }
+ return None;
+ }
+ _ => return None,
+ };
+ debug!(
+ "try_report_static_impl_trait(var={:?}, sub={:?} {:?} sup={:?} {:?})",
+ var_origin, sub_origin, sub_r, sup_origin, sup_r
+ );
+ let anon_reg_sup = tcx.is_suitable_region(*sup_r)?;
+ debug!("try_report_static_impl_trait: anon_reg_sup={:?}", anon_reg_sup);
+ let sp = var_origin.span();
+ let return_sp = sub_origin.span();
+ let param = self.find_param_with_region(*sup_r, *sub_r)?;
+ let (lifetime_name, lifetime) = if sup_r.has_name() {
+ (sup_r.to_string(), format!("lifetime `{}`", sup_r))
+ } else {
+ ("'_".to_owned(), "an anonymous lifetime `'_`".to_string())
+ };
+ let param_name = param
+ .param
+ .pat
+ .simple_ident()
+ .map(|s| format!("`{}`", s))
+ .unwrap_or_else(|| "`fn` parameter".to_string());
+ let mut err = struct_span_err!(
+ tcx.sess,
+ sp,
+ E0759,
+ "{} has {} but it needs to satisfy a `'static` lifetime requirement",
+ param_name,
+ lifetime,
+ );
+
+ let (mention_influencer, influencer_point) =
+ if sup_origin.span().overlaps(param.param_ty_span) {
+ // Account for `async fn` like in `async-await/issues/issue-62097.rs`.
+ // The desugaring of `async `fn`s causes `sup_origin` and `param` to point at the same
+ // place (but with different `ctxt`, hence `overlaps` instead of `==` above).
+ //
+ // This avoids the following:
+ //
+ // LL | pub async fn run_dummy_fn(&self) {
+ // | ^^^^^
+ // | |
+ // | this data with an anonymous lifetime `'_`...
+ // | ...is captured here...
+ (false, sup_origin.span())
+ } else {
+ (!sup_origin.span().overlaps(return_sp), param.param_ty_span)
+ };
+ err.span_label(influencer_point, &format!("this data with {}...", lifetime));
+
+ debug!("try_report_static_impl_trait: param_info={:?}", param);
+
+ let mut spans = spans.clone();
+
+ if mention_influencer {
+ spans.push(sup_origin.span());
+ }
+ // We dedup the spans *ignoring* expansion context.
+ spans.sort();
+ spans.dedup_by_key(|span| (span.lo(), span.hi()));
+
+ // We try to make the output have fewer overlapping spans if possible.
+ let require_msg = if spans.is_empty() {
+ "...is used and required to live as long as `'static` here"
+ } else {
+ "...and is required to live as long as `'static` here"
+ };
+ let require_span =
+ if sup_origin.span().overlaps(return_sp) { sup_origin.span() } else { return_sp };
+
+ for span in &spans {
+ err.span_label(*span, "...is used here...");
+ }
+
+ if spans.iter().any(|sp| sp.overlaps(return_sp) || *sp > return_sp) {
+ // If any of the "captured here" labels appears on the same line or after
+ // `require_span`, we put it on a note to ensure the text flows by appearing
+ // always at the end.
+ err.span_note(require_span, require_msg);
+ } else {
+ // We don't need a note, it's already at the end, it can be shown as a `span_label`.
+ err.span_label(require_span, require_msg);
+ }
+
+ if let SubregionOrigin::RelateParamBound(_, _, Some(bound)) = sub_origin {
+ err.span_note(*bound, "`'static` lifetime requirement introduced by this bound");
+ }
+ if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = sub_origin {
+ if let ObligationCauseCode::ReturnValue(hir_id)
+ | ObligationCauseCode::BlockTailExpression(hir_id) = cause.code()
+ {
+ let parent_id = tcx.hir().get_parent_item(*hir_id);
+ let parent_id = tcx.hir().local_def_id_to_hir_id(parent_id);
+ if let Some(fn_decl) = tcx.hir().fn_decl_by_hir_id(parent_id) {
+ let mut span: MultiSpan = fn_decl.output.span().into();
+ let mut add_label = true;
+ if let hir::FnRetTy::Return(ty) = fn_decl.output {
+ let mut v = StaticLifetimeVisitor(vec![], tcx.hir());
+ v.visit_ty(ty);
+ if !v.0.is_empty() {
+ span = v.0.clone().into();
+ for sp in v.0 {
+ span.push_span_label(sp, "`'static` requirement introduced here");
+ }
+ add_label = false;
+ }
+ }
+ if add_label {
+ span.push_span_label(
+ fn_decl.output.span(),
+ "requirement introduced by this return type",
+ );
+ }
+ span.push_span_label(cause.span, "because of this returned expression");
+ err.span_note(
+ span,
+ "`'static` lifetime requirement introduced by the return type",
+ );
+ }
+ }
+ }
+
+ let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.def_id);
+
+ let mut override_error_code = None;
+ if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sup_origin
+ && let ObligationCauseCode::UnifyReceiver(ctxt) = cause.code()
+ // Handle case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a
+ // `'static` lifetime when called as a method on a binding: `bar.qux()`.
+ && self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt)
+ {
+ override_error_code = Some(ctxt.assoc_item.name);
+ }
+
+ if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sub_origin
+ && let code = match cause.code() {
+ ObligationCauseCode::MatchImpl(parent, ..) => parent.code(),
+ _ => cause.code(),
+ }
+ && let (&ObligationCauseCode::ItemObligation(item_def_id), None) = (code, override_error_code)
+ {
+ // Same case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a `'static`
+ // lifetime as above, but called using a fully-qualified path to the method:
+ // `Foo::qux(bar)`.
+ let mut v = TraitObjectVisitor(FxHashSet::default());
+ v.visit_ty(param.param_ty);
+ if let Some((ident, self_ty)) =
+ self.get_impl_ident_and_self_ty_from_trait(item_def_id, &v.0)
+ && self.suggest_constrain_dyn_trait_in_impl(&mut err, &v.0, ident, self_ty)
+ {
+ override_error_code = Some(ident.name);
+ }
+ }
+ if let (Some(ident), true) = (override_error_code, fn_returns.is_empty()) {
+ // Provide a more targeted error code and description.
+ err.code(rustc_errors::error_code!(E0772));
+ err.set_primary_message(&format!(
+ "{} has {} but calling `{}` introduces an implicit `'static` lifetime \
+ requirement",
+ param_name, lifetime, ident,
+ ));
+ }
+
+ let arg = match param.param.pat.simple_ident() {
+ Some(simple_ident) => format!("argument `{}`", simple_ident),
+ None => "the argument".to_string(),
+ };
+ let captures = format!("captures data from {}", arg);
+ suggest_new_region_bound(
+ tcx,
+ &mut err,
+ fn_returns,
+ lifetime_name,
+ Some(arg),
+ captures,
+ Some((param.param_ty_span, param.param_ty.to_string())),
+ );
+
+ let reported = err.emit();
+ Some(reported)
+ }
+}
+
+pub fn suggest_new_region_bound(
+ tcx: TyCtxt<'_>,
+ err: &mut Diagnostic,
+ fn_returns: Vec<&rustc_hir::Ty<'_>>,
+ lifetime_name: String,
+ arg: Option<String>,
+ captures: String,
+ param: Option<(Span, String)>,
+) {
+ debug!("try_report_static_impl_trait: fn_return={:?}", fn_returns);
+ // FIXME: account for the need of parens in `&(dyn Trait + '_)`
+ let consider = "consider changing the";
+ let declare = "to declare that the";
+ let explicit = format!("you can add an explicit `{}` lifetime bound", lifetime_name);
+ let explicit_static =
+ arg.map(|arg| format!("explicit `'static` bound to the lifetime of {}", arg));
+ let add_static_bound = "alternatively, add an explicit `'static` bound to this reference";
+ let plus_lt = format!(" + {}", lifetime_name);
+ for fn_return in fn_returns {
+ if fn_return.span.desugaring_kind().is_some() {
+ // Skip `async` desugaring `impl Future`.
+ continue;
+ }
+ match fn_return.kind {
+ TyKind::OpaqueDef(item_id, _) => {
+ let item = tcx.hir().item(item_id);
+ let ItemKind::OpaqueTy(opaque) = &item.kind else {
+ return;
+ };
+
+ if let Some(span) = opaque
+ .bounds
+ .iter()
+ .filter_map(|arg| match arg {
+ GenericBound::Outlives(Lifetime {
+ name: LifetimeName::Static,
+ span,
+ ..
+ }) => Some(*span),
+ _ => None,
+ })
+ .next()
+ {
+ if let Some(explicit_static) = &explicit_static {
+ err.span_suggestion_verbose(
+ span,
+ &format!("{} `impl Trait`'s {}", consider, explicit_static),
+ &lifetime_name,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ if let Some((param_span, param_ty)) = param.clone() {
+ err.span_suggestion_verbose(
+ param_span,
+ add_static_bound,
+ param_ty,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ } else if opaque
+ .bounds
+ .iter()
+ .filter_map(|arg| match arg {
+ GenericBound::Outlives(Lifetime { name, span, .. })
+ if name.ident().to_string() == lifetime_name =>
+ {
+ Some(*span)
+ }
+ _ => None,
+ })
+ .next()
+ .is_some()
+ {
+ } else {
+ err.span_suggestion_verbose(
+ fn_return.span.shrink_to_hi(),
+ &format!(
+ "{declare} `impl Trait` {captures}, {explicit}",
+ declare = declare,
+ captures = captures,
+ explicit = explicit,
+ ),
+ &plus_lt,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ TyKind::TraitObject(_, lt, _) => match lt.name {
+ LifetimeName::ImplicitObjectLifetimeDefault => {
+ err.span_suggestion_verbose(
+ fn_return.span.shrink_to_hi(),
+ &format!(
+ "{declare} trait object {captures}, {explicit}",
+ declare = declare,
+ captures = captures,
+ explicit = explicit,
+ ),
+ &plus_lt,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ name if name.ident().to_string() != lifetime_name => {
+ // With this check we avoid suggesting redundant bounds. This
+ // would happen if there are nested impl/dyn traits and only
+ // one of them has the bound we'd suggest already there, like
+ // in `impl Foo<X = dyn Bar> + '_`.
+ if let Some(explicit_static) = &explicit_static {
+ err.span_suggestion_verbose(
+ lt.span,
+ &format!("{} trait object's {}", consider, explicit_static),
+ &lifetime_name,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ if let Some((param_span, param_ty)) = param.clone() {
+ err.span_suggestion_verbose(
+ param_span,
+ add_static_bound,
+ param_ty,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ _ => {}
+ },
+ _ => {}
+ }
+ }
+}
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ fn get_impl_ident_and_self_ty_from_trait(
+ &self,
+ def_id: DefId,
+ trait_objects: &FxHashSet<DefId>,
+ ) -> Option<(Ident, &'tcx hir::Ty<'tcx>)> {
+ let tcx = self.tcx();
+ match tcx.hir().get_if_local(def_id) {
+ Some(Node::ImplItem(impl_item)) => {
+ match tcx.hir().find_by_def_id(tcx.hir().get_parent_item(impl_item.hir_id())) {
+ Some(Node::Item(Item {
+ kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
+ ..
+ })) => Some((impl_item.ident, self_ty)),
+ _ => None,
+ }
+ }
+ Some(Node::TraitItem(trait_item)) => {
+ let trait_did = tcx.hir().get_parent_item(trait_item.hir_id());
+ match tcx.hir().find_by_def_id(trait_did) {
+ Some(Node::Item(Item { kind: ItemKind::Trait(..), .. })) => {
+ // The method being called is defined in the `trait`, but the `'static`
+ // obligation comes from the `impl`. Find that `impl` so that we can point
+ // at it in the suggestion.
+ let trait_did = trait_did.to_def_id();
+ match tcx
+ .hir()
+ .trait_impls(trait_did)
+ .iter()
+ .filter_map(|&impl_did| {
+ match tcx.hir().get_if_local(impl_did.to_def_id()) {
+ Some(Node::Item(Item {
+ kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
+ ..
+ })) if trait_objects.iter().all(|did| {
+ // FIXME: we should check `self_ty` against the receiver
+ // type in the `UnifyReceiver` context, but for now, use
+ // this imperfect proxy. This will fail if there are
+ // multiple `impl`s for the same trait like
+ // `impl Foo for Box<dyn Bar>` and `impl Foo for dyn Bar`.
+ // In that case, only the first one will get suggestions.
+ let mut traits = vec![];
+ let mut hir_v = HirTraitObjectVisitor(&mut traits, *did);
+ hir_v.visit_ty(self_ty);
+ !traits.is_empty()
+ }) =>
+ {
+ Some(self_ty)
+ }
+ _ => None,
+ }
+ })
+ .next()
+ {
+ Some(self_ty) => Some((trait_item.ident, self_ty)),
+ _ => None,
+ }
+ }
+ _ => None,
+ }
+ }
+ _ => None,
+ }
+ }
+
+ /// When we call a method coming from an `impl Foo for dyn Bar`, `dyn Bar` introduces a default
+ /// `'static` obligation. Suggest relaxing that implicit bound.
+ fn find_impl_on_dyn_trait(
+ &self,
+ err: &mut Diagnostic,
+ ty: Ty<'_>,
+ ctxt: &UnifyReceiverContext<'tcx>,
+ ) -> bool {
+ let tcx = self.tcx();
+
+ // Find the method being called.
+ let Ok(Some(instance)) = ty::Instance::resolve(
+ tcx,
+ ctxt.param_env,
+ ctxt.assoc_item.def_id,
+ self.infcx.resolve_vars_if_possible(ctxt.substs),
+ ) else {
+ return false;
+ };
+
+ let mut v = TraitObjectVisitor(FxHashSet::default());
+ v.visit_ty(ty);
+
+ // Get the `Ident` of the method being called and the corresponding `impl` (to point at
+ // `Bar` in `impl Foo for dyn Bar {}` and the definition of the method being called).
+ let Some((ident, self_ty)) = self.get_impl_ident_and_self_ty_from_trait(instance.def_id(), &v.0) else {
+ return false;
+ };
+
+ // Find the trait object types in the argument, so we point at *only* the trait object.
+ self.suggest_constrain_dyn_trait_in_impl(err, &v.0, ident, self_ty)
+ }
+
+ fn suggest_constrain_dyn_trait_in_impl(
+ &self,
+ err: &mut Diagnostic,
+ found_dids: &FxHashSet<DefId>,
+ ident: Ident,
+ self_ty: &hir::Ty<'_>,
+ ) -> bool {
+ let mut suggested = false;
+ for found_did in found_dids {
+ let mut traits = vec![];
+ let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
+ hir_v.visit_ty(&self_ty);
+ for span in &traits {
+ let mut multi_span: MultiSpan = vec![*span].into();
+ multi_span
+ .push_span_label(*span, "this has an implicit `'static` lifetime requirement");
+ multi_span.push_span_label(
+ ident.span,
+ "calling this method introduces the `impl`'s 'static` requirement",
+ );
+ err.span_note(multi_span, "the used `impl` has a `'static` requirement");
+ err.span_suggestion_verbose(
+ span.shrink_to_hi(),
+ "consider relaxing the implicit `'static` requirement",
+ " + '_",
+ Applicability::MaybeIncorrect,
+ );
+ suggested = true;
+ }
+ }
+ suggested
+ }
+}
+
+/// Collect all the trait objects in a type that could have received an implicit `'static` lifetime.
+pub struct TraitObjectVisitor(pub FxHashSet<DefId>);
+
+impl<'tcx> TypeVisitor<'tcx> for TraitObjectVisitor {
+ fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
+ match t.kind() {
+ ty::Dynamic(preds, re) if re.is_static() => {
+ if let Some(def_id) = preds.principal_def_id() {
+ self.0.insert(def_id);
+ }
+ ControlFlow::CONTINUE
+ }
+ _ => t.super_visit_with(self),
+ }
+ }
+}
+
+/// Collect all `hir::Ty<'_>` `Span`s for trait objects with an implicit lifetime.
+pub struct HirTraitObjectVisitor<'a>(pub &'a mut Vec<Span>, pub DefId);
+
+impl<'a, 'tcx> Visitor<'tcx> for HirTraitObjectVisitor<'a> {
+ fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
+ if let TyKind::TraitObject(
+ poly_trait_refs,
+ Lifetime { name: LifetimeName::ImplicitObjectLifetimeDefault, .. },
+ _,
+ ) = t.kind
+ {
+ for ptr in poly_trait_refs {
+ if Some(self.1) == ptr.trait_ref.trait_def_id() {
+ self.0.push(ptr.span);
+ }
+ }
+ }
+ walk_ty(self, t);
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs
new file mode 100644
index 000000000..da465a764
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs
@@ -0,0 +1,176 @@
+//! Error Reporting for `impl` items that do not match the obligations from their `trait`.
+
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::Subtype;
+use crate::traits::ObligationCauseCode::CompareImplItemObligation;
+use rustc_errors::{ErrorGuaranteed, MultiSpan};
+use rustc_hir as hir;
+use rustc_hir::def::Res;
+use rustc_hir::def_id::DefId;
+use rustc_hir::intravisit::Visitor;
+use rustc_middle::hir::nested_filter;
+use rustc_middle::ty::print::RegionHighlightMode;
+use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor};
+use rustc_span::Span;
+
+use std::ops::ControlFlow;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ /// Print the error message for lifetime errors when the `impl` doesn't conform to the `trait`.
+ pub(super) fn try_report_impl_not_conforming_to_trait(&self) -> Option<ErrorGuaranteed> {
+ let error = self.error.as_ref()?;
+ debug!("try_report_impl_not_conforming_to_trait {:?}", error);
+ if let RegionResolutionError::SubSupConflict(
+ _,
+ var_origin,
+ sub_origin,
+ _sub,
+ sup_origin,
+ _sup,
+ _,
+ ) = error.clone()
+ && let (Subtype(sup_trace), Subtype(sub_trace)) = (&sup_origin, &sub_origin)
+ && let sub_expected_found @ Some((sub_expected, sub_found)) = sub_trace.values.ty()
+ && let sup_expected_found @ Some(_) = sup_trace.values.ty()
+ && let CompareImplItemObligation { trait_item_def_id, .. } = sub_trace.cause.code()
+ && sup_expected_found == sub_expected_found
+ {
+ let guar =
+ self.emit_err(var_origin.span(), sub_expected, sub_found, *trait_item_def_id);
+ return Some(guar);
+ }
+ None
+ }
+
+ fn emit_err(
+ &self,
+ sp: Span,
+ expected: Ty<'tcx>,
+ found: Ty<'tcx>,
+ trait_def_id: DefId,
+ ) -> ErrorGuaranteed {
+ let trait_sp = self.tcx().def_span(trait_def_id);
+ let mut err = self
+ .tcx()
+ .sess
+ .struct_span_err(sp, "`impl` item signature doesn't match `trait` item signature");
+
+ // Mark all unnamed regions in the type with a number.
+ // This diagnostic is called in response to lifetime errors, so be informative.
+ struct HighlightBuilder<'tcx> {
+ highlight: RegionHighlightMode<'tcx>,
+ counter: usize,
+ }
+
+ impl<'tcx> HighlightBuilder<'tcx> {
+ fn build(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> RegionHighlightMode<'tcx> {
+ let mut builder =
+ HighlightBuilder { highlight: RegionHighlightMode::new(tcx), counter: 1 };
+ builder.visit_ty(ty);
+ builder.highlight
+ }
+ }
+
+ impl<'tcx> ty::visit::TypeVisitor<'tcx> for HighlightBuilder<'tcx> {
+ fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
+ if !r.has_name() && self.counter <= 3 {
+ self.highlight.highlighting_region(r, self.counter);
+ self.counter += 1;
+ }
+ r.super_visit_with(self)
+ }
+ }
+
+ let expected_highlight = HighlightBuilder::build(self.tcx(), expected);
+ let expected = self
+ .infcx
+ .extract_inference_diagnostics_data(expected.into(), Some(expected_highlight))
+ .name;
+ let found_highlight = HighlightBuilder::build(self.tcx(), found);
+ let found =
+ self.infcx.extract_inference_diagnostics_data(found.into(), Some(found_highlight)).name;
+
+ err.span_label(sp, &format!("found `{}`", found));
+ err.span_label(trait_sp, &format!("expected `{}`", expected));
+
+ // Get the span of all the used type parameters in the method.
+ let assoc_item = self.tcx().associated_item(trait_def_id);
+ let mut visitor = TypeParamSpanVisitor { tcx: self.tcx(), types: vec![] };
+ match assoc_item.kind {
+ ty::AssocKind::Fn => {
+ let hir = self.tcx().hir();
+ if let Some(hir_id) =
+ assoc_item.def_id.as_local().map(|id| hir.local_def_id_to_hir_id(id))
+ {
+ if let Some(decl) = hir.fn_decl_by_hir_id(hir_id) {
+ visitor.visit_fn_decl(decl);
+ }
+ }
+ }
+ _ => {}
+ }
+ let mut type_param_span: MultiSpan = visitor.types.to_vec().into();
+ for &span in &visitor.types {
+ type_param_span
+ .push_span_label(span, "consider borrowing this type parameter in the trait");
+ }
+
+ err.note(&format!("expected `{}`\n found `{}`", expected, found));
+
+ err.span_help(
+ type_param_span,
+ "the lifetime requirements from the `impl` do not correspond to the requirements in \
+ the `trait`",
+ );
+ if visitor.types.is_empty() {
+ err.help(
+ "verify the lifetime relationships in the `trait` and `impl` between the `self` \
+ argument, the other inputs and its output",
+ );
+ }
+ err.emit()
+ }
+}
+
+struct TypeParamSpanVisitor<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ types: Vec<Span>,
+}
+
+impl<'tcx> Visitor<'tcx> for TypeParamSpanVisitor<'tcx> {
+ type NestedFilter = nested_filter::OnlyBodies;
+
+ fn nested_visit_map(&mut self) -> Self::Map {
+ self.tcx.hir()
+ }
+
+ fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
+ match arg.kind {
+ hir::TyKind::Rptr(_, ref mut_ty) => {
+ // We don't want to suggest looking into borrowing `&T` or `&Self`.
+ hir::intravisit::walk_ty(self, mut_ty.ty);
+ return;
+ }
+ hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
+ [segment]
+ if segment
+ .res
+ .map(|res| {
+ matches!(
+ res,
+ Res::SelfTy { trait_: _, alias_to: _ }
+ | Res::Def(hir::def::DefKind::TyParam, _)
+ )
+ })
+ .unwrap_or(false) =>
+ {
+ self.types.push(path.span);
+ }
+ _ => {}
+ },
+ _ => {}
+ }
+ hir::intravisit::walk_ty(self, arg);
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs
new file mode 100644
index 000000000..3e9d491af
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs
@@ -0,0 +1,167 @@
+//! Helper functions corresponding to lifetime errors due to
+//! anonymous regions.
+
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::TyCtxt;
+use rustc_hir as hir;
+use rustc_hir::def_id::LocalDefId;
+use rustc_middle::ty::{self, Binder, DefIdTree, Region, Ty, TypeVisitable};
+use rustc_span::Span;
+
+/// Information about the anonymous region we are searching for.
+#[derive(Debug)]
+pub struct AnonymousParamInfo<'tcx> {
+ /// The parameter corresponding to the anonymous region.
+ pub param: &'tcx hir::Param<'tcx>,
+ /// The type corresponding to the anonymous region parameter.
+ pub param_ty: Ty<'tcx>,
+ /// The ty::BoundRegionKind corresponding to the anonymous region.
+ pub bound_region: ty::BoundRegionKind,
+ /// The `Span` of the parameter type.
+ pub param_ty_span: Span,
+ /// Signals that the argument is the first parameter in the declaration.
+ pub is_first: bool,
+}
+
+// This method walks the Type of the function body parameters using
+// `fold_regions()` function and returns the
+// &hir::Param of the function parameter corresponding to the anonymous
+// region and the Ty corresponding to the named region.
+// Currently only the case where the function declaration consists of
+// one named region and one anonymous region is handled.
+// Consider the example `fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32`
+// Here, we would return the hir::Param for y, we return the type &'a
+// i32, which is the type of y but with the anonymous region replaced
+// with 'a, the corresponding bound region and is_first which is true if
+// the hir::Param is the first parameter in the function declaration.
+#[instrument(skip(tcx), level = "debug")]
+pub fn find_param_with_region<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ anon_region: Region<'tcx>,
+ replace_region: Region<'tcx>,
+) -> Option<AnonymousParamInfo<'tcx>> {
+ let (id, bound_region) = match *anon_region {
+ ty::ReFree(ref free_region) => (free_region.scope, free_region.bound_region),
+ ty::ReEarlyBound(ebr) => {
+ (tcx.parent(ebr.def_id), ty::BoundRegionKind::BrNamed(ebr.def_id, ebr.name))
+ }
+ _ => return None, // not a free region
+ };
+
+ let hir = &tcx.hir();
+ let def_id = id.as_local()?;
+ let hir_id = hir.local_def_id_to_hir_id(def_id);
+
+ // FIXME: use def_kind
+ // Don't perform this on closures
+ match hir.get(hir_id) {
+ hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
+ return None;
+ }
+ _ => {}
+ }
+
+ let body_id = hir.maybe_body_owned_by(def_id)?;
+
+ let owner_id = hir.body_owner(body_id);
+ let fn_decl = hir.fn_decl_by_hir_id(owner_id).unwrap();
+ let poly_fn_sig = tcx.fn_sig(id);
+
+ let fn_sig = tcx.liberate_late_bound_regions(id, poly_fn_sig);
+ let body = hir.body(body_id);
+ body.params
+ .iter()
+ .take(if fn_sig.c_variadic {
+ fn_sig.inputs().len()
+ } else {
+ assert_eq!(fn_sig.inputs().len(), body.params.len());
+ body.params.len()
+ })
+ .enumerate()
+ .find_map(|(index, param)| {
+ // May return None; sometimes the tables are not yet populated.
+ let ty = fn_sig.inputs()[index];
+ let mut found_anon_region = false;
+ let new_param_ty = tcx.fold_regions(ty, |r, _| {
+ if r == anon_region {
+ found_anon_region = true;
+ replace_region
+ } else {
+ r
+ }
+ });
+ if found_anon_region {
+ let ty_hir_id = fn_decl.inputs[index].hir_id;
+ let param_ty_span = hir.span(ty_hir_id);
+ let is_first = index == 0;
+ Some(AnonymousParamInfo {
+ param,
+ param_ty: new_param_ty,
+ param_ty_span,
+ bound_region,
+ is_first,
+ })
+ } else {
+ None
+ }
+ })
+}
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ pub(super) fn find_param_with_region(
+ &self,
+ anon_region: Region<'tcx>,
+ replace_region: Region<'tcx>,
+ ) -> Option<AnonymousParamInfo<'tcx>> {
+ find_param_with_region(self.tcx(), anon_region, replace_region)
+ }
+
+ // Here, we check for the case where the anonymous region
+ // is in the return type as written by the user.
+ // FIXME(#42703) - Need to handle certain cases here.
+ pub(super) fn is_return_type_anon(
+ &self,
+ scope_def_id: LocalDefId,
+ br: ty::BoundRegionKind,
+ hir_sig: &hir::FnSig<'_>,
+ ) -> Option<Span> {
+ let fn_ty = self.tcx().type_of(scope_def_id);
+ if let ty::FnDef(_, _) = fn_ty.kind() {
+ let ret_ty = fn_ty.fn_sig(self.tcx()).output();
+ let span = hir_sig.decl.output.span();
+ let future_output = if hir_sig.header.is_async() {
+ ret_ty.map_bound(|ty| self.infcx.get_impl_future_output_ty(ty)).transpose()
+ } else {
+ None
+ };
+ return match future_output {
+ Some(output) if self.includes_region(output, br) => Some(span),
+ None if self.includes_region(ret_ty, br) => Some(span),
+ _ => None,
+ };
+ }
+ None
+ }
+
+ fn includes_region(
+ &self,
+ ty: Binder<'tcx, impl TypeVisitable<'tcx>>,
+ region: ty::BoundRegionKind,
+ ) -> bool {
+ let late_bound_regions = self.tcx().collect_referenced_late_bound_regions(&ty);
+ late_bound_regions.iter().any(|r| *r == region)
+ }
+
+ // Here we check for the case where anonymous region
+ // corresponds to self and if yes, we display E0312.
+ // FIXME(#42700) - Need to format self properly to
+ // enable E0621 for it.
+ pub(super) fn is_self_anon(&self, is_first: bool, scope_def_id: LocalDefId) -> bool {
+ is_first
+ && self
+ .tcx()
+ .opt_associated_item(scope_def_id.to_def_id())
+ .map(|i| i.fn_has_self_parameter)
+ == Some(true)
+ }
+}