1 //! Error reporting machinery for lifetime errors.
3 use rustc_data_structures::stable_set::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::sym;
23 use rustc_span::symbol::Ident;
26 use crate::borrowck_errors;
27 use crate::session_diagnostics::GenericDoesNotLiveLongEnough;
29 use super::{OutlivesSuggestionBuilder, RegionName};
30 use crate::region_infer::BlameConstraint;
32 nll::ConstraintDescription,
33 region_infer::{values::RegionElement, TypeTest},
34 universal_regions::DefiningTy,
38 impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> {
39 fn description(&self) -> &'static str {
40 // Must end with a space. Allows for empty names to be provided.
42 ConstraintCategory::Assignment => "assignment ",
43 ConstraintCategory::Return(_) => "returning this value ",
44 ConstraintCategory::Yield => "yielding this value ",
45 ConstraintCategory::UseAsConst => "using this value as a constant ",
46 ConstraintCategory::UseAsStatic => "using this value as a static ",
47 ConstraintCategory::Cast => "cast ",
48 ConstraintCategory::CallArgument(_) => "argument ",
49 ConstraintCategory::TypeAnnotation => "type annotation ",
50 ConstraintCategory::ClosureBounds => "closure body ",
51 ConstraintCategory::SizedBound => "proving this value is `Sized` ",
52 ConstraintCategory::CopyBound => "copying this value ",
53 ConstraintCategory::OpaqueType => "opaque type ",
54 ConstraintCategory::ClosureUpvar(_) => "closure capture ",
55 ConstraintCategory::Usage => "this usage ",
56 ConstraintCategory::Predicate(_)
57 | ConstraintCategory::Boring
58 | ConstraintCategory::BoringNoLocation
59 | ConstraintCategory::Internal => "",
64 /// A collection of errors encountered during region inference. This is needed to efficiently
65 /// report errors after borrow checking.
67 /// Usually we expect this to either be empty or contain a small number of items, so we can avoid
68 /// allocation most of the time.
69 pub(crate) type RegionErrors<'tcx> = Vec<RegionErrorKind<'tcx>>;
71 #[derive(Clone, Debug)]
72 pub(crate) enum RegionErrorKind<'tcx> {
73 /// A generic bound failure for a type test (`T: 'a`).
74 TypeTestError { type_test: TypeTest<'tcx> },
76 /// An unexpected hidden region for an opaque type.
77 UnexpectedHiddenRegion {
78 /// The span for the member constraint.
82 /// The unexpected region.
83 member_region: ty::Region<'tcx>,
86 /// Higher-ranked subtyping error.
87 BoundUniversalRegionError {
88 /// The placeholder free region.
90 /// The region element that erroneously must be outlived by `longer_fr`.
91 error_element: RegionElement,
92 /// The placeholder region.
93 placeholder: ty::PlaceholderRegion,
96 /// Any other lifetime error.
98 /// The origin of the region.
99 fr_origin: NllRegionVariableOrigin,
100 /// The region that should outlive `shorter_fr`.
101 longer_fr: RegionVid,
102 /// The region that should be shorter, but we can't prove it.
103 shorter_fr: RegionVid,
104 /// Indicates whether this is a reported error. We currently only report the first error
105 /// encountered and leave the rest unreported so as not to overwhelm the user.
110 /// Information about the various region constraints involved in a borrow checker error.
111 #[derive(Clone, Debug)]
112 pub struct ErrorConstraintInfo<'tcx> {
114 pub(super) fr: RegionVid,
115 pub(super) fr_is_local: bool,
116 pub(super) outlived_fr: RegionVid,
117 pub(super) outlived_fr_is_local: bool,
119 // Category and span for best blame constraint
120 pub(super) category: ConstraintCategory<'tcx>,
121 pub(super) span: Span,
124 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
125 /// Converts a region inference variable into a `ty::Region` that
126 /// we can use for error reporting. If `r` is universally bound,
127 /// then we use the name that we have on record for it. If `r` is
128 /// existentially bound, then we check its inferred value and try
129 /// to find a good name from that. Returns `None` if we can't find
130 /// one (e.g., this is just some random part of the CFG).
131 pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
132 self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
135 /// Returns the `RegionVid` corresponding to the region returned by
136 /// `to_error_region`.
137 pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
138 if self.regioncx.universal_regions().is_universal_region(r) {
141 // We just want something nameable, even if it's not
142 // actually an upper bound.
143 let upper_bound = self.regioncx.approx_universal_upper_bound(r);
145 if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
146 self.to_error_region_vid(upper_bound)
153 /// Returns `true` if a closure is inferred to be an `FnMut` closure.
154 fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
155 if let Some(ty::ReFree(free_region)) = self.to_error_region(fr).as_deref()
156 && let ty::BoundRegionKind::BrEnv = free_region.bound_region
157 && let DefiningTy::Closure(_, substs) = self.regioncx.universal_regions().defining_ty
159 return substs.as_closure().kind() == ty::ClosureKind::FnMut;
165 /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
166 pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
167 // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
168 // buffered in the `MirBorrowckCtxt`.
170 let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
172 for nll_error in nll_errors.into_iter() {
174 RegionErrorKind::TypeTestError { type_test } => {
175 // Try to convert the lower-bound region into something named we can print for the user.
176 let lower_bound_region = self.to_error_region(type_test.lower_bound);
178 let type_test_span = type_test.locations.span(&self.body);
180 if let Some(lower_bound_region) = lower_bound_region {
181 let generic_ty = type_test.generic_kind.to_ty(self.infcx.tcx);
182 let origin = RelateParamBound(type_test_span, generic_ty, None);
183 self.buffer_error(self.infcx.construct_generic_bound_failure(
186 type_test.generic_kind,
188 self.body.source.def_id().as_local(),
191 // FIXME. We should handle this case better. It
192 // indicates that we have e.g., some region variable
193 // whose value is like `'a+'b` where `'a` and `'b` are
194 // distinct unrelated universal regions that are not
195 // known to outlive one another. It'd be nice to have
196 // some examples where this arises to decide how best
197 // to report it; we could probably handle it by
198 // iterating over the universal regions and reporting
199 // an error that multiple bounds are required.
200 self.buffer_error(self.infcx.tcx.sess.create_err(
201 GenericDoesNotLiveLongEnough {
202 kind: type_test.generic_kind.to_string(),
203 span: type_test_span,
209 RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, member_region } => {
210 let named_ty = self.regioncx.name_regions(self.infcx.tcx, hidden_ty);
211 let named_region = self.regioncx.name_regions(self.infcx.tcx, member_region);
212 self.buffer_error(unexpected_hidden_region_diagnostic(
220 RegionErrorKind::BoundUniversalRegionError {
225 let error_vid = self.regioncx.region_from_element(longer_fr, &error_element);
227 // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
228 let (_, cause) = self.regioncx.find_outlives_blame_span(
231 NllRegionVariableOrigin::Placeholder(placeholder),
235 let universe = placeholder.universe;
236 let universe_info = self.regioncx.universe_info(universe);
238 universe_info.report_error(self, placeholder, error_element, cause);
241 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
243 self.report_region_error(
247 &mut outlives_suggestion,
250 // We only report the first error, so as not to overwhelm the user. See
251 // `RegRegionErrorKind` docs.
253 // FIXME: currently we do nothing with these, but perhaps we can do better?
254 // FIXME: try collecting these constraints on the outlives suggestion
255 // builder. Does it make the suggestions any better?
257 "Unreported region error: can't prove that {:?}: {:?}",
258 longer_fr, shorter_fr
265 // Emit one outlives suggestions for each MIR def we borrowck
266 outlives_suggestion.add_suggestion(self);
269 fn get_impl_ident_and_self_ty_from_trait(
272 trait_objects: &FxHashSet<DefId>,
273 ) -> Option<(Ident, &'tcx hir::Ty<'tcx>)> {
274 let tcx = self.infcx.tcx;
275 match tcx.hir().get_if_local(def_id) {
276 Some(Node::ImplItem(impl_item)) => {
277 match tcx.hir().find_by_def_id(tcx.hir().get_parent_item(impl_item.hir_id())) {
278 Some(Node::Item(Item {
279 kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
281 })) => Some((impl_item.ident, self_ty)),
285 Some(Node::TraitItem(trait_item)) => {
286 let trait_did = tcx.hir().get_parent_item(trait_item.hir_id());
287 match tcx.hir().find_by_def_id(trait_did) {
288 Some(Node::Item(Item { kind: ItemKind::Trait(..), .. })) => {
289 // The method being called is defined in the `trait`, but the `'static`
290 // obligation comes from the `impl`. Find that `impl` so that we can point
291 // at it in the suggestion.
292 let trait_did = trait_did.to_def_id();
295 .trait_impls(trait_did)
297 .filter_map(|&impl_did| {
298 match tcx.hir().get_if_local(impl_did.to_def_id()) {
299 Some(Node::Item(Item {
300 kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
302 })) if trait_objects.iter().all(|did| {
303 // FIXME: we should check `self_ty` against the receiver
304 // type in the `UnifyReceiver` context, but for now, use
305 // this imperfect proxy. This will fail if there are
306 // multiple `impl`s for the same trait like
307 // `impl Foo for Box<dyn Bar>` and `impl Foo for dyn Bar`.
308 // In that case, only the first one will get suggestions.
309 let mut traits = vec![];
310 let mut hir_v = HirTraitObjectVisitor(&mut traits, *did);
311 hir_v.visit_ty(self_ty);
322 Some(self_ty) => Some((trait_item.ident, self_ty)),
333 /// Report an error because the universal region `fr` was required to outlive
334 /// `outlived_fr` but it is not known to do so. For example:
336 /// ```compile_fail,E0312
337 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
340 /// Here we would be invoked with `fr = 'a` and `outlived_fr = `'b`.
341 pub(crate) fn report_region_error(
344 fr_origin: NllRegionVariableOrigin,
345 outlived_fr: RegionVid,
346 outlives_suggestion: &mut OutlivesSuggestionBuilder,
348 debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
350 let BlameConstraint { category, cause, variance_info, from_closure: _ } =
351 self.regioncx.best_blame_constraint(&self.body, fr, fr_origin, |r| {
352 self.regioncx.provides_universal_region(r, fr, outlived_fr)
355 debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);
357 // Check if we can use one of the "nice region errors".
358 if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
359 let nice = NiceRegionError::new_from_span(self.infcx, cause.span, o, f);
360 if let Some(diag) = nice.try_report_from_nll() {
361 self.buffer_error(diag);
366 let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
367 self.regioncx.universal_regions().is_local_free_region(fr),
368 self.regioncx.universal_regions().is_local_free_region(outlived_fr),
372 "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
373 fr_is_local, outlived_fr_is_local, category
376 let errci = ErrorConstraintInfo {
380 outlived_fr_is_local,
385 let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
386 (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
387 self.report_fnmut_error(&errci, kind)
389 (ConstraintCategory::Assignment, true, false)
390 | (ConstraintCategory::CallArgument(_), true, false) => {
391 let mut db = self.report_escaping_data_error(&errci);
393 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
394 outlives_suggestion.collect_constraint(fr, outlived_fr);
399 let mut db = self.report_general_error(&errci);
401 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
402 outlives_suggestion.collect_constraint(fr, outlived_fr);
408 match variance_info {
409 ty::VarianceDiagInfo::None => {}
410 ty::VarianceDiagInfo::Invariant { ty, param_index } => {
411 let (desc, note) = match ty.kind() {
412 ty::RawPtr(ty_mut) => {
413 assert_eq!(ty_mut.mutbl, rustc_hir::Mutability::Mut);
415 format!("a mutable pointer to `{}`", ty_mut.ty),
416 "mutable pointers are invariant over their type parameter".to_string(),
419 ty::Ref(_, inner_ty, mutbl) => {
420 assert_eq!(*mutbl, rustc_hir::Mutability::Mut);
422 format!("a mutable reference to `{inner_ty}`"),
423 "mutable references are invariant over their type parameter"
427 ty::Adt(adt, substs) => {
428 let generic_arg = substs[param_index as usize];
429 let identity_substs =
430 InternalSubsts::identity_for_item(self.infcx.tcx, adt.did());
431 let base_ty = self.infcx.tcx.mk_adt(*adt, identity_substs);
432 let base_generic_arg = identity_substs[param_index as usize];
433 let adt_desc = adt.descr();
436 "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
439 "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
443 ty::FnDef(def_id, _) => {
444 let name = self.infcx.tcx.item_name(*def_id);
445 let identity_substs =
446 InternalSubsts::identity_for_item(self.infcx.tcx, *def_id);
447 let desc = format!("a function pointer to `{name}`");
449 "the function `{name}` is invariant over the parameter `{}`",
450 identity_substs[param_index as usize]
454 _ => panic!("Unexpected type {:?}", ty),
456 diag.note(&format!("requirement occurs because of {desc}",));
458 diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
462 self.buffer_error(diag);
465 /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
466 /// This function expects `fr` to be local and `outlived_fr` to not be local.
469 /// error: captured variable cannot escape `FnMut` closure body
470 /// --> $DIR/issue-53040.rs:15:8
473 /// | -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
475 /// | inferred to be a `FnMut` closure
477 /// = note: `FnMut` closures only have access to their captured variables while they are
479 /// = note: ...therefore, returned references to captured variables will escape the closure
481 fn report_fnmut_error(
483 errci: &ErrorConstraintInfo<'tcx>,
484 kind: ReturnConstraint,
485 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
486 let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
492 .struct_span_err(*span, "captured variable cannot escape `FnMut` closure body");
494 let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
495 if let ty::Opaque(def_id, _) = *output_ty.kind() {
496 output_ty = self.infcx.tcx.type_of(def_id)
499 debug!("report_fnmut_error: output_ty={:?}", output_ty);
501 let message = match output_ty.kind() {
502 ty::Closure(_, _) => {
503 "returns a closure that contains a reference to a captured variable, which then \
504 escapes the closure body"
506 ty::Adt(def, _) if self.infcx.tcx.is_diagnostic_item(sym::gen_future, def.did()) => {
507 "returns an `async` block that contains a reference to a captured variable, which then \
508 escapes the closure body"
510 _ => "returns a reference to a captured variable which escapes the closure body",
513 diag.span_label(*span, message);
515 if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
516 let def_id = match self.regioncx.universal_regions().defining_ty {
517 DefiningTy::Closure(def_id, _) => def_id,
518 ty => bug!("unexpected DefiningTy {:?}", ty),
521 let captured_place = &self.upvars[upvar_field.index()].place;
522 let defined_hir = match captured_place.place.base {
523 PlaceBase::Local(hirid) => Some(hirid),
524 PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
528 if let Some(def_hir) = defined_hir {
529 let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
530 let upvar_def_span = self.infcx.tcx.hir().span(def_hir);
531 let upvar_span = upvars_map.get(&def_hir).unwrap().span;
532 diag.span_label(upvar_def_span, "variable defined here");
533 diag.span_label(upvar_span, "variable captured here");
537 if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
538 diag.span_label(fr_span, "inferred to be a `FnMut` closure");
542 "`FnMut` closures only have access to their captured variables while they are \
545 diag.note("...therefore, they cannot allow references to captured variables to escape");
550 /// Reports an error specifically for when data is escaping a closure.
553 /// error: borrowed data escapes outside of function
554 /// --> $DIR/lifetime-bound-will-change-warning.rs:44:5
556 /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
557 /// | - `x` is a reference that is only valid in the function body
558 /// LL | // but ref_obj will not, so warn.
560 /// | ^^^^^^^^^^ `x` escapes the function body here
562 fn report_escaping_data_error(
564 errci: &ErrorConstraintInfo<'tcx>,
565 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
566 let ErrorConstraintInfo { span, category, .. } = errci;
568 let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
575 let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
583 let (_, escapes_from) = self
586 .article_and_description(self.regioncx.universal_regions().defining_ty.def_id());
588 // Revert to the normal error in these cases.
589 // Assignments aren't "escapes" in function items.
590 if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
591 || (*category == ConstraintCategory::Assignment
592 && self.regioncx.universal_regions().defining_ty.is_fn_def())
593 || self.regioncx.universal_regions().defining_ty.is_const()
595 return self.report_general_error(&ErrorConstraintInfo {
597 outlived_fr_is_local: false,
603 borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
605 if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
608 format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
612 if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
616 "`{fr_name}` is a reference that is only valid in the {escapes_from} body",
620 diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
623 // Only show an extra note if we can find an 'error region' for both of the region
624 // variables. This avoids showing a noisy note that just mentions 'synthetic' regions
625 // that don't help the user understand the error.
626 match (self.to_error_region(errci.fr), self.to_error_region(errci.outlived_fr)) {
627 (Some(f), Some(o)) => {
628 self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
630 let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
631 fr_region_name.highlight_region_name(&mut diag);
632 let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
633 outlived_fr_region_name.highlight_region_name(&mut diag);
638 "{}requires that `{}` must outlive `{}`",
639 category.description(),
641 outlived_fr_region_name,
651 /// Reports a region inference error for the general case with named/synthesized lifetimes to
652 /// explain what is happening.
655 /// error: unsatisfied lifetime constraints
656 /// --> $DIR/regions-creating-enums3.rs:17:5
658 /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
659 /// | -- -- lifetime `'b` defined here
661 /// | lifetime `'a` defined here
662 /// LL | ast::add(x, y)
663 /// | ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
664 /// | is returning data with lifetime `'b`
666 fn report_general_error(
668 errci: &ErrorConstraintInfo<'tcx>,
669 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
670 let ErrorConstraintInfo {
674 outlived_fr_is_local,
681 self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
683 let (_, mir_def_name) =
684 self.infcx.tcx.article_and_description(self.mir_def_id().to_def_id());
686 let fr_name = self.give_region_a_name(*fr).unwrap();
687 fr_name.highlight_region_name(&mut diag);
688 let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
689 outlived_fr_name.highlight_region_name(&mut diag);
691 match (category, outlived_fr_is_local, fr_is_local) {
692 (ConstraintCategory::Return(_), true, _) => {
696 "{mir_def_name} was supposed to return data with lifetime `{outlived_fr_name}` but it is returning \
697 data with lifetime `{fr_name}`",
705 "{}requires that `{}` must outlive `{}`",
706 category.description(),
714 self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
715 self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
720 /// Adds a suggestion to errors where an `impl Trait` is returned.
723 /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
726 /// LL | fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
727 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
729 fn add_static_impl_trait_suggestion(
731 diag: &mut Diagnostic,
733 // We need to pass `fr_name` - computing it again will label it twice.
735 outlived_fr: RegionVid,
737 if let (Some(f), Some(outlived_f)) =
738 (self.to_error_region(fr), self.to_error_region(outlived_fr))
740 if *outlived_f != ty::ReStatic {
744 let fn_returns = self
747 .is_suitable_region(f)
748 .map(|r| self.infcx.tcx.return_type_impl_or_dyn_traits(r.def_id))
749 .unwrap_or_default();
751 if fn_returns.is_empty() {
755 let param = if let Some(param) = find_param_with_region(self.infcx.tcx, f, outlived_f) {
761 let lifetime = if f.has_name() { fr_name.to_string() } else { "'_".to_string() };
763 let arg = match param.param.pat.simple_ident() {
764 Some(simple_ident) => format!("argument `{}`", simple_ident),
765 None => "the argument".to_string(),
767 let captures = format!("captures data from {}", arg);
769 return nice_region_error::suggest_new_region_bound(
776 Some((param.param_ty_span, param.param_ty.to_string())),
781 fn maybe_suggest_constrain_dyn_trait_impl(
783 diag: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
786 category: &ConstraintCategory<'tcx>,
792 let tcx = self.infcx.tcx;
794 let instance = if let ConstraintCategory::CallArgument(Some(func_ty)) = category {
795 let (fn_did, substs) = match func_ty.kind() {
796 ty::FnDef(fn_did, substs) => (fn_did, substs),
799 debug!(?fn_did, ?substs);
801 // Only suggest this on function calls, not closures
802 let ty = tcx.type_of(fn_did);
803 debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
804 if let ty::Closure(_, _) = ty.kind() {
808 if let Ok(Some(instance)) = ty::Instance::resolve(
812 self.infcx.resolve_vars_if_possible(substs),
822 let param = match find_param_with_region(tcx, f, o) {
823 Some(param) => param,
828 let mut visitor = TraitObjectVisitor(FxHashSet::default());
829 visitor.visit_ty(param.param_ty);
831 let Some((ident, self_ty)) =
832 self.get_impl_ident_and_self_ty_from_trait(instance.def_id(), &visitor.0) else {return};
834 self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
837 #[instrument(skip(self, err), level = "debug")]
838 fn suggest_constrain_dyn_trait_in_impl(
840 err: &mut Diagnostic,
841 found_dids: &FxHashSet<DefId>,
843 self_ty: &hir::Ty<'_>,
845 debug!("err: {:#?}", err);
846 let mut suggested = false;
847 for found_did in found_dids {
848 let mut traits = vec![];
849 let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
850 hir_v.visit_ty(&self_ty);
851 debug!("trait spans found: {:?}", traits);
852 for span in &traits {
853 let mut multi_span: MultiSpan = vec![*span].into();
854 multi_span.push_span_label(
856 "this has an implicit `'static` lifetime requirement".to_string(),
858 multi_span.push_span_label(
860 "calling this method introduces the `impl`'s 'static` requirement".to_string(),
862 err.span_note(multi_span, "the used `impl` has a `'static` requirement");
863 err.span_suggestion_verbose(
865 "consider relaxing the implicit `'static` requirement",
867 Applicability::MaybeIncorrect,
875 fn suggest_adding_lifetime_params(
877 diag: &mut Diagnostic,
881 let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
885 let Some((ty_sub, _)) = self
888 .is_suitable_region(sub)
889 .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sub, &anon_reg.boundregion)) else {
893 let Some((ty_sup, _)) = self
896 .is_suitable_region(sup)
897 .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sup, &anon_reg.boundregion)) else {
901 suggest_adding_lifetime_params(self.infcx.tcx, sub, ty_sup, ty_sub, diag);