]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/region_errors.rs
Remove non-descriptive boolean from search_for_structural_match_violation
[rust.git] / compiler / rustc_borrowck / src / diagnostics / region_errors.rs
1 //! Error reporting machinery for lifetime errors.
2
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,
12     },
13     error_reporting::unexpected_hidden_region_diagnostic,
14     NllRegionVariableOrigin, RelateParamBound,
15 };
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};
23 use rustc_span::Span;
24
25 use crate::borrowck_errors;
26 use crate::session_diagnostics::GenericDoesNotLiveLongEnough;
27
28 use super::{OutlivesSuggestionBuilder, RegionName};
29 use crate::region_infer::BlameConstraint;
30 use crate::{
31     nll::ConstraintDescription,
32     region_infer::{values::RegionElement, TypeTest},
33     universal_regions::DefiningTy,
34     MirBorrowckCtxt,
35 };
36
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.
40         match self {
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 => "",
59         }
60     }
61 }
62
63 /// A collection of errors encountered during region inference. This is needed to efficiently
64 /// report errors after borrow checking.
65 ///
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>>;
69
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> },
74
75     /// An unexpected hidden region for an opaque type.
76     UnexpectedHiddenRegion {
77         /// The span for the member constraint.
78         span: Span,
79         /// The hidden type.
80         hidden_ty: Ty<'tcx>,
81         /// The unexpected region.
82         member_region: ty::Region<'tcx>,
83     },
84
85     /// Higher-ranked subtyping error.
86     BoundUniversalRegionError {
87         /// The placeholder free region.
88         longer_fr: RegionVid,
89         /// The region element that erroneously must be outlived by `longer_fr`.
90         error_element: RegionElement,
91         /// The placeholder region.
92         placeholder: ty::PlaceholderRegion,
93     },
94
95     /// Any other lifetime error.
96     RegionError {
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.
105         is_reported: bool,
106     },
107 }
108
109 /// Information about the various region constraints involved in a borrow checker error.
110 #[derive(Clone, Debug)]
111 pub struct ErrorConstraintInfo<'tcx> {
112     // fr: outlived_fr
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,
117
118     // Category and span for best blame constraint
119     pub(super) category: ConstraintCategory<'tcx>,
120     pub(super) span: Span,
121 }
122
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)
132     }
133
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) {
138             Some(r)
139         } else {
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);
143
144             if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
145                 self.to_error_region_vid(upper_bound)
146             } else {
147                 None
148             }
149         }
150     }
151
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
157         {
158             return substs.as_closure().kind() == ty::ClosureKind::FnMut;
159         }
160
161         false
162     }
163
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`.
168
169         let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
170
171         for nll_error in nll_errors.into_iter() {
172             match nll_error {
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);
176
177                     let type_test_span = type_test.locations.span(&self.body);
178
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(),
184                             type_test_span,
185                             Some(origin),
186                             type_test.generic_kind,
187                             lower_bound_region,
188                         ));
189                     } else {
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,
203                             },
204                         ));
205                     }
206                 }
207
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(
212                         self.infcx.tcx,
213                         span,
214                         named_ty,
215                         named_region,
216                     ));
217                 }
218
219                 RegionErrorKind::BoundUniversalRegionError {
220                     longer_fr,
221                     placeholder,
222                     error_element,
223                 } => {
224                     let error_vid = self.regioncx.region_from_element(longer_fr, &error_element);
225
226                     // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
227                     let (_, cause) = self.regioncx.find_outlives_blame_span(
228                         &self.body,
229                         longer_fr,
230                         NllRegionVariableOrigin::Placeholder(placeholder),
231                         error_vid,
232                     );
233
234                     let universe = placeholder.universe;
235                     let universe_info = self.regioncx.universe_info(universe);
236
237                     universe_info.report_error(self, placeholder, error_element, cause);
238                 }
239
240                 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
241                     if is_reported {
242                         self.report_region_error(
243                             longer_fr,
244                             fr_origin,
245                             shorter_fr,
246                             &mut outlives_suggestion,
247                         );
248                     } else {
249                         // We only report the first error, so as not to overwhelm the user. See
250                         // `RegRegionErrorKind` docs.
251                         //
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?
255                         debug!(
256                             "Unreported region error: can't prove that {:?}: {:?}",
257                             longer_fr, shorter_fr
258                         );
259                     }
260                 }
261             }
262         }
263
264         // Emit one outlives suggestions for each MIR def we borrowck
265         outlives_suggestion.add_suggestion(self);
266     }
267
268     fn get_impl_ident_and_self_ty_from_trait(
269         &self,
270         def_id: DefId,
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, .. }),
279                         ..
280                     })) => Some((impl_item.ident, self_ty)),
281                     _ => None,
282                 }
283             }
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();
292                         match tcx
293                             .hir()
294                             .trait_impls(trait_did)
295                             .iter()
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, .. }),
300                                         ..
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);
311                                         !traits.is_empty()
312                                     }) =>
313                                     {
314                                         Some(self_ty)
315                                     }
316                                     _ => None,
317                                 }
318                             })
319                             .next()
320                         {
321                             Some(self_ty) => Some((trait_item.ident, self_ty)),
322                             _ => None,
323                         }
324                     }
325                     _ => None,
326                 }
327             }
328             _ => None,
329         }
330     }
331
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:
334     ///
335     /// ```compile_fail,E0312
336     /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
337     /// ```
338     ///
339     /// Here we would be invoked with `fr = 'a` and `outlived_fr = `'b`.
340     pub(crate) fn report_region_error(
341         &mut self,
342         fr: RegionVid,
343         fr_origin: NllRegionVariableOrigin,
344         outlived_fr: RegionVid,
345         outlives_suggestion: &mut OutlivesSuggestionBuilder,
346     ) {
347         debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
348
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)
352             });
353
354         debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);
355
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);
361                 return;
362             }
363         }
364
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),
368         );
369
370         debug!(
371             "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
372             fr_is_local, outlived_fr_is_local, category
373         );
374
375         let errci = ErrorConstraintInfo {
376             fr,
377             outlived_fr,
378             fr_is_local,
379             outlived_fr_is_local,
380             category,
381             span: cause.span,
382         };
383
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)
387             }
388             (ConstraintCategory::Assignment, true, false)
389             | (ConstraintCategory::CallArgument(_), true, false) => {
390                 let mut db = self.report_escaping_data_error(&errci);
391
392                 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
393                 outlives_suggestion.collect_constraint(fr, outlived_fr);
394
395                 db
396             }
397             _ => {
398                 let mut db = self.report_general_error(&errci);
399
400                 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
401                 outlives_suggestion.collect_constraint(fr, outlived_fr);
402
403                 db
404             }
405         };
406
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);
413                         (
414                             format!("a mutable pointer to `{}`", ty_mut.ty),
415                             "mutable pointers are invariant over their type parameter".to_string(),
416                         )
417                     }
418                     ty::Ref(_, inner_ty, mutbl) => {
419                         assert_eq!(*mutbl, rustc_hir::Mutability::Mut);
420                         (
421                             format!("a mutable reference to `{inner_ty}`"),
422                             "mutable references are invariant over their type parameter"
423                                 .to_string(),
424                         )
425                     }
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();
433
434                         let desc = format!(
435                             "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
436                         );
437                         let note = format!(
438                             "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
439                         );
440                         (desc, note)
441                     }
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}`");
447                         let note = format!(
448                             "the function `{name}` is invariant over the parameter `{}`",
449                             identity_substs[param_index as usize]
450                         );
451                         (desc, note)
452                     }
453                     _ => panic!("Unexpected type {:?}", ty),
454                 };
455                 diag.note(&format!("requirement occurs because of {desc}",));
456                 diag.note(&note);
457                 diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
458             }
459         }
460
461         self.buffer_error(diag);
462     }
463
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.
466     ///
467     /// ```text
468     /// error: captured variable cannot escape `FnMut` closure body
469     ///   --> $DIR/issue-53040.rs:15:8
470     ///    |
471     /// LL |     || &mut v;
472     ///    |     -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
473     ///    |     |
474     ///    |     inferred to be a `FnMut` closure
475     ///    |
476     ///    = note: `FnMut` closures only have access to their captured variables while they are
477     ///            executing...
478     ///    = note: ...therefore, returned references to captured variables will escape the closure
479     /// ```
480     fn report_fnmut_error(
481         &self,
482         errci: &ErrorConstraintInfo<'tcx>,
483         kind: ReturnConstraint,
484     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
485         let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
486
487         let mut diag = self
488             .infcx
489             .tcx
490             .sess
491             .struct_span_err(*span, "captured variable cannot escape `FnMut` closure body");
492
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)
496         };
497
498         debug!("report_fnmut_error: output_ty={:?}", output_ty);
499
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"
504             }
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"
508             }
509             _ => "returns a reference to a captured variable which escapes the closure body",
510         };
511
512         diag.span_label(*span, message);
513
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),
518             };
519
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),
524                 _ => None,
525             };
526
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");
533             }
534         }
535
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");
538         }
539
540         diag.note(
541             "`FnMut` closures only have access to their captured variables while they are \
542              executing...",
543         );
544         diag.note("...therefore, they cannot allow references to captured variables to escape");
545
546         diag
547     }
548
549     /// Reports an error specifically for when data is escaping a closure.
550     ///
551     /// ```text
552     /// error: borrowed data escapes outside of function
553     ///   --> $DIR/lifetime-bound-will-change-warning.rs:44:5
554     ///    |
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.
558     /// LL |     ref_obj(x)
559     ///    |     ^^^^^^^^^^ `x` escapes the function body here
560     /// ```
561     fn report_escaping_data_error(
562         &self,
563         errci: &ErrorConstraintInfo<'tcx>,
564     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
565         let ErrorConstraintInfo { span, category, .. } = errci;
566
567         let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
568             self.infcx.tcx,
569             &self.body,
570             &self.local_names,
571             &self.upvars,
572             errci.fr,
573         );
574         let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
575             self.infcx.tcx,
576             &self.body,
577             &self.local_names,
578             &self.upvars,
579             errci.outlived_fr,
580         );
581
582         let (_, escapes_from) = self
583             .infcx
584             .tcx
585             .article_and_description(self.regioncx.universal_regions().defining_ty.def_id());
586
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()
593         {
594             return self.report_general_error(&ErrorConstraintInfo {
595                 fr_is_local: true,
596                 outlived_fr_is_local: false,
597                 ..*errci
598             });
599         }
600
601         let mut diag =
602             borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
603
604         if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
605             diag.span_label(
606                 outlived_fr_span,
607                 format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
608             );
609         }
610
611         if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
612             diag.span_label(
613                 fr_span,
614                 format!(
615                     "`{fr_name}` is a reference that is only valid in the {escapes_from} body",
616                 ),
617             );
618
619             diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
620         }
621
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);
628
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);
633
634                 diag.span_label(
635                     *span,
636                     format!(
637                         "{}requires that `{}` must outlive `{}`",
638                         category.description(),
639                         fr_region_name,
640                         outlived_fr_region_name,
641                     ),
642                 );
643             }
644             _ => {}
645         }
646
647         diag
648     }
649
650     /// Reports a region inference error for the general case with named/synthesized lifetimes to
651     /// explain what is happening.
652     ///
653     /// ```text
654     /// error: unsatisfied lifetime constraints
655     ///   --> $DIR/regions-creating-enums3.rs:17:5
656     ///    |
657     /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
658     ///    |                -- -- lifetime `'b` defined here
659     ///    |                |
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`
664     /// ```
665     fn report_general_error(
666         &self,
667         errci: &ErrorConstraintInfo<'tcx>,
668     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
669         let ErrorConstraintInfo {
670             fr,
671             fr_is_local,
672             outlived_fr,
673             outlived_fr_is_local,
674             span,
675             category,
676             ..
677         } = errci;
678
679         let mut diag =
680             self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
681
682         let (_, mir_def_name) =
683             self.infcx.tcx.article_and_description(self.mir_def_id().to_def_id());
684
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);
689
690         match (category, outlived_fr_is_local, fr_is_local) {
691             (ConstraintCategory::Return(_), true, _) => {
692                 diag.span_label(
693                     *span,
694                     format!(
695                         "{mir_def_name} was supposed to return data with lifetime `{outlived_fr_name}` but it is returning \
696                          data with lifetime `{fr_name}`",
697                     ),
698                 );
699             }
700             _ => {
701                 diag.span_label(
702                     *span,
703                     format!(
704                         "{}requires that `{}` must outlive `{}`",
705                         category.description(),
706                         fr_name,
707                         outlived_fr_name,
708                     ),
709                 );
710             }
711         }
712
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);
715
716         diag
717     }
718
719     /// Adds a suggestion to errors where an `impl Trait` is returned.
720     ///
721     /// ```text
722     /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
723     ///       a constraint
724     ///    |
725     /// LL |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
726     ///    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
727     /// ```
728     fn add_static_impl_trait_suggestion(
729         &self,
730         diag: &mut Diagnostic,
731         fr: RegionVid,
732         // We need to pass `fr_name` - computing it again will label it twice.
733         fr_name: RegionName,
734         outlived_fr: RegionVid,
735     ) {
736         if let (Some(f), Some(outlived_f)) =
737             (self.to_error_region(fr), self.to_error_region(outlived_fr))
738         {
739             if *outlived_f != ty::ReStatic {
740                 return;
741             }
742
743             let fn_returns = self
744                 .infcx
745                 .tcx
746                 .is_suitable_region(f)
747                 .map(|r| self.infcx.tcx.return_type_impl_or_dyn_traits(r.def_id))
748                 .unwrap_or_default();
749
750             if fn_returns.is_empty() {
751                 return;
752             }
753
754             let param = if let Some(param) = find_param_with_region(self.infcx.tcx, f, outlived_f) {
755                 param
756             } else {
757                 return;
758             };
759
760             let lifetime = if f.has_name() { fr_name.name } else { kw::UnderscoreLifetime };
761
762             let arg = match param.param.pat.simple_ident() {
763                 Some(simple_ident) => format!("argument `{}`", simple_ident),
764                 None => "the argument".to_string(),
765             };
766             let captures = format!("captures data from {}", arg);
767
768             return nice_region_error::suggest_new_region_bound(
769                 self.infcx.tcx,
770                 diag,
771                 fn_returns,
772                 lifetime.to_string(),
773                 Some(arg),
774                 captures,
775                 Some((param.param_ty_span, param.param_ty.to_string())),
776             );
777         }
778     }
779
780     fn maybe_suggest_constrain_dyn_trait_impl(
781         &self,
782         diag: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
783         f: Region<'tcx>,
784         o: Region<'tcx>,
785         category: &ConstraintCategory<'tcx>,
786     ) {
787         if !o.is_static() {
788             return;
789         }
790
791         let tcx = self.infcx.tcx;
792
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),
796                 _ => return,
797             };
798             debug!(?fn_did, ?substs);
799
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() {
804                 return;
805             }
806
807             if let Ok(Some(instance)) = ty::Instance::resolve(
808                 tcx,
809                 self.param_env,
810                 *fn_did,
811                 self.infcx.resolve_vars_if_possible(substs),
812             ) {
813                 instance
814             } else {
815                 return;
816             }
817         } else {
818             return;
819         };
820
821         let param = match find_param_with_region(tcx, f, o) {
822             Some(param) => param,
823             None => return,
824         };
825         debug!(?param);
826
827         let mut visitor = TraitObjectVisitor(FxHashSet::default());
828         visitor.visit_ty(param.param_ty);
829
830         let Some((ident, self_ty)) =
831             self.get_impl_ident_and_self_ty_from_trait(instance.def_id(), &visitor.0) else {return};
832
833         self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
834     }
835
836     #[instrument(skip(self, err), level = "debug")]
837     fn suggest_constrain_dyn_trait_in_impl(
838         &self,
839         err: &mut Diagnostic,
840         found_dids: &FxHashSet<DefId>,
841         ident: Ident,
842         self_ty: &hir::Ty<'_>,
843     ) -> bool {
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(
854                     *span,
855                     "this has an implicit `'static` lifetime requirement".to_string(),
856                 );
857                 multi_span.push_span_label(
858                     ident.span,
859                     "calling this method introduces the `impl`'s 'static` requirement".to_string(),
860                 );
861                 err.span_note(multi_span, "the used `impl` has a `'static` requirement");
862                 err.span_suggestion_verbose(
863                     span.shrink_to_hi(),
864                     "consider relaxing the implicit `'static` requirement",
865                     " + '_",
866                     Applicability::MaybeIncorrect,
867                 );
868                 suggested = true;
869             }
870         }
871         suggested
872     }
873
874     fn suggest_adding_lifetime_params(
875         &self,
876         diag: &mut Diagnostic,
877         sub: RegionVid,
878         sup: RegionVid,
879     ) {
880         let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
881             return
882         };
883
884         let Some((ty_sub, _)) = self
885             .infcx
886             .tcx
887             .is_suitable_region(sub)
888             .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sub, &anon_reg.boundregion)) else {
889             return
890         };
891
892         let Some((ty_sup, _)) = self
893             .infcx
894             .tcx
895             .is_suitable_region(sup)
896             .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sup, &anon_reg.boundregion)) else {
897             return
898         };
899
900         suggest_adding_lifetime_params(self.infcx.tcx, sub, ty_sup, ty_sub, diag);
901     }
902 }