1 //! Error reporting machinery for lifetime errors.
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan};
5 use rustc_hir::def_id::DefId;
6 use rustc_hir::intravisit::Visitor;
7 use rustc_hir::{self as hir, Item, ItemKind, Node};
8 use rustc_infer::infer::{
9 error_reporting::nice_region_error::{
10 self, find_anon_type, find_param_with_region, suggest_adding_lifetime_params,
11 HirTraitObjectVisitor, NiceRegionError, TraitObjectVisitor,
13 error_reporting::unexpected_hidden_region_diagnostic,
14 NllRegionVariableOrigin, RelateParamBound,
16 use rustc_middle::hir::place::PlaceBase;
17 use rustc_middle::mir::{ConstraintCategory, ReturnConstraint};
18 use rustc_middle::ty::subst::InternalSubsts;
19 use rustc_middle::ty::Region;
20 use rustc_middle::ty::TypeVisitor;
21 use rustc_middle::ty::{self, RegionVid, Ty};
22 use rustc_span::symbol::{kw, sym, Ident};
25 use crate::borrowck_errors;
26 use crate::session_diagnostics::GenericDoesNotLiveLongEnough;
28 use super::{OutlivesSuggestionBuilder, RegionName};
29 use crate::region_infer::BlameConstraint;
31 nll::ConstraintDescription,
32 region_infer::{values::RegionElement, TypeTest},
33 universal_regions::DefiningTy,
37 impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> {
38 fn description(&self) -> &'static str {
39 // Must end with a space. Allows for empty names to be provided.
41 ConstraintCategory::Assignment => "assignment ",
42 ConstraintCategory::Return(_) => "returning this value ",
43 ConstraintCategory::Yield => "yielding this value ",
44 ConstraintCategory::UseAsConst => "using this value as a constant ",
45 ConstraintCategory::UseAsStatic => "using this value as a static ",
46 ConstraintCategory::Cast => "cast ",
47 ConstraintCategory::CallArgument(_) => "argument ",
48 ConstraintCategory::TypeAnnotation => "type annotation ",
49 ConstraintCategory::ClosureBounds => "closure body ",
50 ConstraintCategory::SizedBound => "proving this value is `Sized` ",
51 ConstraintCategory::CopyBound => "copying this value ",
52 ConstraintCategory::OpaqueType => "opaque type ",
53 ConstraintCategory::ClosureUpvar(_) => "closure capture ",
54 ConstraintCategory::Usage => "this usage ",
55 ConstraintCategory::Predicate(_)
56 | ConstraintCategory::Boring
57 | ConstraintCategory::BoringNoLocation
58 | ConstraintCategory::Internal => "",
63 /// A collection of errors encountered during region inference. This is needed to efficiently
64 /// report errors after borrow checking.
66 /// Usually we expect this to either be empty or contain a small number of items, so we can avoid
67 /// allocation most of the time.
68 pub(crate) type RegionErrors<'tcx> = Vec<RegionErrorKind<'tcx>>;
70 #[derive(Clone, Debug)]
71 pub(crate) enum RegionErrorKind<'tcx> {
72 /// A generic bound failure for a type test (`T: 'a`).
73 TypeTestError { type_test: TypeTest<'tcx> },
75 /// An unexpected hidden region for an opaque type.
76 UnexpectedHiddenRegion {
77 /// The span for the member constraint.
81 /// The unexpected region.
82 member_region: ty::Region<'tcx>,
85 /// Higher-ranked subtyping error.
86 BoundUniversalRegionError {
87 /// The placeholder free region.
89 /// The region element that erroneously must be outlived by `longer_fr`.
90 error_element: RegionElement,
91 /// The placeholder region.
92 placeholder: ty::PlaceholderRegion,
95 /// Any other lifetime error.
97 /// The origin of the region.
98 fr_origin: NllRegionVariableOrigin,
99 /// The region that should outlive `shorter_fr`.
100 longer_fr: RegionVid,
101 /// The region that should be shorter, but we can't prove it.
102 shorter_fr: RegionVid,
103 /// Indicates whether this is a reported error. We currently only report the first error
104 /// encountered and leave the rest unreported so as not to overwhelm the user.
109 /// Information about the various region constraints involved in a borrow checker error.
110 #[derive(Clone, Debug)]
111 pub struct ErrorConstraintInfo<'tcx> {
113 pub(super) fr: RegionVid,
114 pub(super) fr_is_local: bool,
115 pub(super) outlived_fr: RegionVid,
116 pub(super) outlived_fr_is_local: bool,
118 // Category and span for best blame constraint
119 pub(super) category: ConstraintCategory<'tcx>,
120 pub(super) span: Span,
123 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
124 /// Converts a region inference variable into a `ty::Region` that
125 /// we can use for error reporting. If `r` is universally bound,
126 /// then we use the name that we have on record for it. If `r` is
127 /// existentially bound, then we check its inferred value and try
128 /// to find a good name from that. Returns `None` if we can't find
129 /// one (e.g., this is just some random part of the CFG).
130 pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
131 self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
134 /// Returns the `RegionVid` corresponding to the region returned by
135 /// `to_error_region`.
136 pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
137 if self.regioncx.universal_regions().is_universal_region(r) {
140 // We just want something nameable, even if it's not
141 // actually an upper bound.
142 let upper_bound = self.regioncx.approx_universal_upper_bound(r);
144 if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
145 self.to_error_region_vid(upper_bound)
152 /// Returns `true` if a closure is inferred to be an `FnMut` closure.
153 fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
154 if let Some(ty::ReFree(free_region)) = self.to_error_region(fr).as_deref()
155 && let ty::BoundRegionKind::BrEnv = free_region.bound_region
156 && let DefiningTy::Closure(_, substs) = self.regioncx.universal_regions().defining_ty
158 return substs.as_closure().kind() == ty::ClosureKind::FnMut;
164 /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
165 pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
166 // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
167 // buffered in the `MirBorrowckCtxt`.
169 let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
171 for nll_error in nll_errors.into_iter() {
173 RegionErrorKind::TypeTestError { type_test } => {
174 // Try to convert the lower-bound region into something named we can print for the user.
175 let lower_bound_region = self.to_error_region(type_test.lower_bound);
177 let type_test_span = type_test.locations.span(&self.body);
179 if let Some(lower_bound_region) = lower_bound_region {
180 let generic_ty = type_test.generic_kind.to_ty(self.infcx.tcx);
181 let origin = RelateParamBound(type_test_span, generic_ty, None);
182 self.buffer_error(self.infcx.construct_generic_bound_failure(
183 self.body.source.def_id().expect_local(),
186 type_test.generic_kind,
190 // FIXME. We should handle this case better. It
191 // indicates that we have e.g., some region variable
192 // whose value is like `'a+'b` where `'a` and `'b` are
193 // distinct unrelated universal regions that are not
194 // known to outlive one another. It'd be nice to have
195 // some examples where this arises to decide how best
196 // to report it; we could probably handle it by
197 // iterating over the universal regions and reporting
198 // an error that multiple bounds are required.
199 self.buffer_error(self.infcx.tcx.sess.create_err(
200 GenericDoesNotLiveLongEnough {
201 kind: type_test.generic_kind.to_string(),
202 span: type_test_span,
208 RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, member_region } => {
209 let named_ty = self.regioncx.name_regions(self.infcx.tcx, hidden_ty);
210 let named_region = self.regioncx.name_regions(self.infcx.tcx, member_region);
211 self.buffer_error(unexpected_hidden_region_diagnostic(
219 RegionErrorKind::BoundUniversalRegionError {
224 let error_vid = self.regioncx.region_from_element(longer_fr, &error_element);
226 // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
227 let (_, cause) = self.regioncx.find_outlives_blame_span(
230 NllRegionVariableOrigin::Placeholder(placeholder),
234 let universe = placeholder.universe;
235 let universe_info = self.regioncx.universe_info(universe);
237 universe_info.report_error(self, placeholder, error_element, cause);
240 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
242 self.report_region_error(
246 &mut outlives_suggestion,
249 // We only report the first error, so as not to overwhelm the user. See
250 // `RegRegionErrorKind` docs.
252 // FIXME: currently we do nothing with these, but perhaps we can do better?
253 // FIXME: try collecting these constraints on the outlives suggestion
254 // builder. Does it make the suggestions any better?
256 "Unreported region error: can't prove that {:?}: {:?}",
257 longer_fr, shorter_fr
264 // Emit one outlives suggestions for each MIR def we borrowck
265 outlives_suggestion.add_suggestion(self);
268 fn get_impl_ident_and_self_ty_from_trait(
271 trait_objects: &FxHashSet<DefId>,
272 ) -> Option<(Ident, &'tcx hir::Ty<'tcx>)> {
273 let tcx = self.infcx.tcx;
274 match tcx.hir().get_if_local(def_id) {
275 Some(Node::ImplItem(impl_item)) => {
276 match tcx.hir().find_by_def_id(tcx.hir().get_parent_item(impl_item.hir_id())) {
277 Some(Node::Item(Item {
278 kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
280 })) => Some((impl_item.ident, self_ty)),
284 Some(Node::TraitItem(trait_item)) => {
285 let trait_did = tcx.hir().get_parent_item(trait_item.hir_id());
286 match tcx.hir().find_by_def_id(trait_did) {
287 Some(Node::Item(Item { kind: ItemKind::Trait(..), .. })) => {
288 // The method being called is defined in the `trait`, but the `'static`
289 // obligation comes from the `impl`. Find that `impl` so that we can point
290 // at it in the suggestion.
291 let trait_did = trait_did.to_def_id();
294 .trait_impls(trait_did)
296 .filter_map(|&impl_did| {
297 match tcx.hir().get_if_local(impl_did.to_def_id()) {
298 Some(Node::Item(Item {
299 kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
301 })) if trait_objects.iter().all(|did| {
302 // FIXME: we should check `self_ty` against the receiver
303 // type in the `UnifyReceiver` context, but for now, use
304 // this imperfect proxy. This will fail if there are
305 // multiple `impl`s for the same trait like
306 // `impl Foo for Box<dyn Bar>` and `impl Foo for dyn Bar`.
307 // In that case, only the first one will get suggestions.
308 let mut traits = vec![];
309 let mut hir_v = HirTraitObjectVisitor(&mut traits, *did);
310 hir_v.visit_ty(self_ty);
321 Some(self_ty) => Some((trait_item.ident, self_ty)),
332 /// Report an error because the universal region `fr` was required to outlive
333 /// `outlived_fr` but it is not known to do so. For example:
335 /// ```compile_fail,E0312
336 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
339 /// Here we would be invoked with `fr = 'a` and `outlived_fr = `'b`.
340 pub(crate) fn report_region_error(
343 fr_origin: NllRegionVariableOrigin,
344 outlived_fr: RegionVid,
345 outlives_suggestion: &mut OutlivesSuggestionBuilder,
347 debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
349 let BlameConstraint { category, cause, variance_info, from_closure: _ } =
350 self.regioncx.best_blame_constraint(&self.body, fr, fr_origin, |r| {
351 self.regioncx.provides_universal_region(r, fr, outlived_fr)
354 debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);
356 // Check if we can use one of the "nice region errors".
357 if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
358 let nice = NiceRegionError::new_from_span(self.infcx, cause.span, o, f);
359 if let Some(diag) = nice.try_report_from_nll() {
360 self.buffer_error(diag);
365 let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
366 self.regioncx.universal_regions().is_local_free_region(fr),
367 self.regioncx.universal_regions().is_local_free_region(outlived_fr),
371 "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
372 fr_is_local, outlived_fr_is_local, category
375 let errci = ErrorConstraintInfo {
379 outlived_fr_is_local,
384 let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
385 (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
386 self.report_fnmut_error(&errci, kind)
388 (ConstraintCategory::Assignment, true, false)
389 | (ConstraintCategory::CallArgument(_), true, false) => {
390 let mut db = self.report_escaping_data_error(&errci);
392 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
393 outlives_suggestion.collect_constraint(fr, outlived_fr);
398 let mut db = self.report_general_error(&errci);
400 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
401 outlives_suggestion.collect_constraint(fr, outlived_fr);
407 match variance_info {
408 ty::VarianceDiagInfo::None => {}
409 ty::VarianceDiagInfo::Invariant { ty, param_index } => {
410 let (desc, note) = match ty.kind() {
411 ty::RawPtr(ty_mut) => {
412 assert_eq!(ty_mut.mutbl, rustc_hir::Mutability::Mut);
414 format!("a mutable pointer to `{}`", ty_mut.ty),
415 "mutable pointers are invariant over their type parameter".to_string(),
418 ty::Ref(_, inner_ty, mutbl) => {
419 assert_eq!(*mutbl, rustc_hir::Mutability::Mut);
421 format!("a mutable reference to `{inner_ty}`"),
422 "mutable references are invariant over their type parameter"
426 ty::Adt(adt, substs) => {
427 let generic_arg = substs[param_index as usize];
428 let identity_substs =
429 InternalSubsts::identity_for_item(self.infcx.tcx, adt.did());
430 let base_ty = self.infcx.tcx.mk_adt(*adt, identity_substs);
431 let base_generic_arg = identity_substs[param_index as usize];
432 let adt_desc = adt.descr();
435 "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
438 "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
442 ty::FnDef(def_id, _) => {
443 let name = self.infcx.tcx.item_name(*def_id);
444 let identity_substs =
445 InternalSubsts::identity_for_item(self.infcx.tcx, *def_id);
446 let desc = format!("a function pointer to `{name}`");
448 "the function `{name}` is invariant over the parameter `{}`",
449 identity_substs[param_index as usize]
453 _ => panic!("Unexpected type {:?}", ty),
455 diag.note(&format!("requirement occurs because of {desc}",));
457 diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
461 self.buffer_error(diag);
464 /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
465 /// This function expects `fr` to be local and `outlived_fr` to not be local.
468 /// error: captured variable cannot escape `FnMut` closure body
469 /// --> $DIR/issue-53040.rs:15:8
472 /// | -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
474 /// | inferred to be a `FnMut` closure
476 /// = note: `FnMut` closures only have access to their captured variables while they are
478 /// = note: ...therefore, returned references to captured variables will escape the closure
480 fn report_fnmut_error(
482 errci: &ErrorConstraintInfo<'tcx>,
483 kind: ReturnConstraint,
484 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
485 let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
491 .struct_span_err(*span, "captured variable cannot escape `FnMut` closure body");
493 let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
494 if let ty::Opaque(def_id, _) = *output_ty.kind() {
495 output_ty = self.infcx.tcx.type_of(def_id)
498 debug!("report_fnmut_error: output_ty={:?}", output_ty);
500 let message = match output_ty.kind() {
501 ty::Closure(_, _) => {
502 "returns a closure that contains a reference to a captured variable, which then \
503 escapes the closure body"
505 ty::Adt(def, _) if self.infcx.tcx.is_diagnostic_item(sym::gen_future, def.did()) => {
506 "returns an `async` block that contains a reference to a captured variable, which then \
507 escapes the closure body"
509 _ => "returns a reference to a captured variable which escapes the closure body",
512 diag.span_label(*span, message);
514 if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
515 let def_id = match self.regioncx.universal_regions().defining_ty {
516 DefiningTy::Closure(def_id, _) => def_id,
517 ty => bug!("unexpected DefiningTy {:?}", ty),
520 let captured_place = &self.upvars[upvar_field.index()].place;
521 let defined_hir = match captured_place.place.base {
522 PlaceBase::Local(hirid) => Some(hirid),
523 PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
527 if let Some(def_hir) = defined_hir {
528 let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
529 let upvar_def_span = self.infcx.tcx.hir().span(def_hir);
530 let upvar_span = upvars_map.get(&def_hir).unwrap().span;
531 diag.span_label(upvar_def_span, "variable defined here");
532 diag.span_label(upvar_span, "variable captured here");
536 if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
537 diag.span_label(fr_span, "inferred to be a `FnMut` closure");
541 "`FnMut` closures only have access to their captured variables while they are \
544 diag.note("...therefore, they cannot allow references to captured variables to escape");
549 /// Reports an error specifically for when data is escaping a closure.
552 /// error: borrowed data escapes outside of function
553 /// --> $DIR/lifetime-bound-will-change-warning.rs:44:5
555 /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
556 /// | - `x` is a reference that is only valid in the function body
557 /// LL | // but ref_obj will not, so warn.
559 /// | ^^^^^^^^^^ `x` escapes the function body here
561 fn report_escaping_data_error(
563 errci: &ErrorConstraintInfo<'tcx>,
564 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
565 let ErrorConstraintInfo { span, category, .. } = errci;
567 let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
574 let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
582 let (_, escapes_from) = self
585 .article_and_description(self.regioncx.universal_regions().defining_ty.def_id());
587 // Revert to the normal error in these cases.
588 // Assignments aren't "escapes" in function items.
589 if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
590 || (*category == ConstraintCategory::Assignment
591 && self.regioncx.universal_regions().defining_ty.is_fn_def())
592 || self.regioncx.universal_regions().defining_ty.is_const()
594 return self.report_general_error(&ErrorConstraintInfo {
596 outlived_fr_is_local: false,
602 borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
604 if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
607 format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
611 if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
615 "`{fr_name}` is a reference that is only valid in the {escapes_from} body",
619 diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
622 // Only show an extra note if we can find an 'error region' for both of the region
623 // variables. This avoids showing a noisy note that just mentions 'synthetic' regions
624 // that don't help the user understand the error.
625 match (self.to_error_region(errci.fr), self.to_error_region(errci.outlived_fr)) {
626 (Some(f), Some(o)) => {
627 self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
629 let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
630 fr_region_name.highlight_region_name(&mut diag);
631 let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
632 outlived_fr_region_name.highlight_region_name(&mut diag);
637 "{}requires that `{}` must outlive `{}`",
638 category.description(),
640 outlived_fr_region_name,
650 /// Reports a region inference error for the general case with named/synthesized lifetimes to
651 /// explain what is happening.
654 /// error: unsatisfied lifetime constraints
655 /// --> $DIR/regions-creating-enums3.rs:17:5
657 /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
658 /// | -- -- lifetime `'b` defined here
660 /// | lifetime `'a` defined here
661 /// LL | ast::add(x, y)
662 /// | ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
663 /// | is returning data with lifetime `'b`
665 fn report_general_error(
667 errci: &ErrorConstraintInfo<'tcx>,
668 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
669 let ErrorConstraintInfo {
673 outlived_fr_is_local,
680 self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
682 let (_, mir_def_name) =
683 self.infcx.tcx.article_and_description(self.mir_def_id().to_def_id());
685 let fr_name = self.give_region_a_name(*fr).unwrap();
686 fr_name.highlight_region_name(&mut diag);
687 let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
688 outlived_fr_name.highlight_region_name(&mut diag);
690 match (category, outlived_fr_is_local, fr_is_local) {
691 (ConstraintCategory::Return(_), true, _) => {
695 "{mir_def_name} was supposed to return data with lifetime `{outlived_fr_name}` but it is returning \
696 data with lifetime `{fr_name}`",
704 "{}requires that `{}` must outlive `{}`",
705 category.description(),
713 self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
714 self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
719 /// Adds a suggestion to errors where an `impl Trait` is returned.
722 /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
725 /// LL | fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
726 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
728 fn add_static_impl_trait_suggestion(
730 diag: &mut Diagnostic,
732 // We need to pass `fr_name` - computing it again will label it twice.
734 outlived_fr: RegionVid,
736 if let (Some(f), Some(outlived_f)) =
737 (self.to_error_region(fr), self.to_error_region(outlived_fr))
739 if *outlived_f != ty::ReStatic {
743 let fn_returns = self
746 .is_suitable_region(f)
747 .map(|r| self.infcx.tcx.return_type_impl_or_dyn_traits(r.def_id))
748 .unwrap_or_default();
750 if fn_returns.is_empty() {
754 let param = if let Some(param) = find_param_with_region(self.infcx.tcx, f, outlived_f) {
760 let lifetime = if f.has_name() { fr_name.name } else { kw::UnderscoreLifetime };
762 let arg = match param.param.pat.simple_ident() {
763 Some(simple_ident) => format!("argument `{}`", simple_ident),
764 None => "the argument".to_string(),
766 let captures = format!("captures data from {}", arg);
768 return nice_region_error::suggest_new_region_bound(
772 lifetime.to_string(),
775 Some((param.param_ty_span, param.param_ty.to_string())),
780 fn maybe_suggest_constrain_dyn_trait_impl(
782 diag: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
785 category: &ConstraintCategory<'tcx>,
791 let tcx = self.infcx.tcx;
793 let instance = if let ConstraintCategory::CallArgument(Some(func_ty)) = category {
794 let (fn_did, substs) = match func_ty.kind() {
795 ty::FnDef(fn_did, substs) => (fn_did, substs),
798 debug!(?fn_did, ?substs);
800 // Only suggest this on function calls, not closures
801 let ty = tcx.type_of(fn_did);
802 debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
803 if let ty::Closure(_, _) = ty.kind() {
807 if let Ok(Some(instance)) = ty::Instance::resolve(
811 self.infcx.resolve_vars_if_possible(substs),
821 let param = match find_param_with_region(tcx, f, o) {
822 Some(param) => param,
827 let mut visitor = TraitObjectVisitor(FxHashSet::default());
828 visitor.visit_ty(param.param_ty);
830 let Some((ident, self_ty)) =
831 self.get_impl_ident_and_self_ty_from_trait(instance.def_id(), &visitor.0) else {return};
833 self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
836 #[instrument(skip(self, err), level = "debug")]
837 fn suggest_constrain_dyn_trait_in_impl(
839 err: &mut Diagnostic,
840 found_dids: &FxHashSet<DefId>,
842 self_ty: &hir::Ty<'_>,
844 debug!("err: {:#?}", err);
845 let mut suggested = false;
846 for found_did in found_dids {
847 let mut traits = vec![];
848 let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
849 hir_v.visit_ty(&self_ty);
850 debug!("trait spans found: {:?}", traits);
851 for span in &traits {
852 let mut multi_span: MultiSpan = vec![*span].into();
853 multi_span.push_span_label(
855 "this has an implicit `'static` lifetime requirement".to_string(),
857 multi_span.push_span_label(
859 "calling this method introduces the `impl`'s 'static` requirement".to_string(),
861 err.span_note(multi_span, "the used `impl` has a `'static` requirement");
862 err.span_suggestion_verbose(
864 "consider relaxing the implicit `'static` requirement",
866 Applicability::MaybeIncorrect,
874 fn suggest_adding_lifetime_params(
876 diag: &mut Diagnostic,
880 let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
884 let Some((ty_sub, _)) = self
887 .is_suitable_region(sub)
888 .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sub, &anon_reg.boundregion)) else {
892 let Some((ty_sup, _)) = self
895 .is_suitable_region(sup)
896 .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sup, &anon_reg.boundregion)) else {
900 suggest_adding_lifetime_params(self.infcx.tcx, sub, ty_sup, ty_sub, diag);