]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/region_errors.rs
Improve `AdtDef` interning.
[rust.git] / compiler / rustc_borrowck / src / diagnostics / region_errors.rs
1 //! Error reporting machinery for lifetime errors.
2
3 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
4 use rustc_infer::infer::{
5     error_reporting::nice_region_error::NiceRegionError,
6     error_reporting::unexpected_hidden_region_diagnostic, NllRegionVariableOrigin,
7 };
8 use rustc_middle::hir::place::PlaceBase;
9 use rustc_middle::mir::{ConstraintCategory, ReturnConstraint};
10 use rustc_middle::ty::subst::{InternalSubsts, Subst};
11 use rustc_middle::ty::{self, RegionVid, Ty};
12 use rustc_span::symbol::{kw, sym};
13 use rustc_span::{BytePos, Span};
14
15 use crate::borrowck_errors;
16
17 use super::{OutlivesSuggestionBuilder, RegionName};
18 use crate::region_infer::BlameConstraint;
19 use crate::{
20     nll::ConstraintDescription,
21     region_infer::{values::RegionElement, TypeTest},
22     universal_regions::DefiningTy,
23     MirBorrowckCtxt,
24 };
25
26 impl ConstraintDescription for ConstraintCategory {
27     fn description(&self) -> &'static str {
28         // Must end with a space. Allows for empty names to be provided.
29         match self {
30             ConstraintCategory::Assignment => "assignment ",
31             ConstraintCategory::Return(_) => "returning this value ",
32             ConstraintCategory::Yield => "yielding this value ",
33             ConstraintCategory::UseAsConst => "using this value as a constant ",
34             ConstraintCategory::UseAsStatic => "using this value as a static ",
35             ConstraintCategory::Cast => "cast ",
36             ConstraintCategory::CallArgument => "argument ",
37             ConstraintCategory::TypeAnnotation => "type annotation ",
38             ConstraintCategory::ClosureBounds => "closure body ",
39             ConstraintCategory::SizedBound => "proving this value is `Sized` ",
40             ConstraintCategory::CopyBound => "copying this value ",
41             ConstraintCategory::OpaqueType => "opaque type ",
42             ConstraintCategory::ClosureUpvar(_) => "closure capture ",
43             ConstraintCategory::Usage => "this usage ",
44             ConstraintCategory::Predicate(_)
45             | ConstraintCategory::Boring
46             | ConstraintCategory::BoringNoLocation
47             | ConstraintCategory::Internal => "",
48         }
49     }
50 }
51
52 /// A collection of errors encountered during region inference. This is needed to efficiently
53 /// report errors after borrow checking.
54 ///
55 /// Usually we expect this to either be empty or contain a small number of items, so we can avoid
56 /// allocation most of the time.
57 crate type RegionErrors<'tcx> = Vec<RegionErrorKind<'tcx>>;
58
59 #[derive(Clone, Debug)]
60 crate enum RegionErrorKind<'tcx> {
61     /// A generic bound failure for a type test (`T: 'a`).
62     TypeTestError { type_test: TypeTest<'tcx> },
63
64     /// An unexpected hidden region for an opaque type.
65     UnexpectedHiddenRegion {
66         /// The span for the member constraint.
67         span: Span,
68         /// The hidden type.
69         hidden_ty: Ty<'tcx>,
70         /// The unexpected region.
71         member_region: ty::Region<'tcx>,
72     },
73
74     /// Higher-ranked subtyping error.
75     BoundUniversalRegionError {
76         /// The placeholder free region.
77         longer_fr: RegionVid,
78         /// The region element that erroneously must be outlived by `longer_fr`.
79         error_element: RegionElement,
80         /// The placeholder region.
81         placeholder: ty::PlaceholderRegion,
82     },
83
84     /// Any other lifetime error.
85     RegionError {
86         /// The origin of the region.
87         fr_origin: NllRegionVariableOrigin,
88         /// The region that should outlive `shorter_fr`.
89         longer_fr: RegionVid,
90         /// The region that should be shorter, but we can't prove it.
91         shorter_fr: RegionVid,
92         /// Indicates whether this is a reported error. We currently only report the first error
93         /// encountered and leave the rest unreported so as not to overwhelm the user.
94         is_reported: bool,
95     },
96 }
97
98 /// Information about the various region constraints involved in a borrow checker error.
99 #[derive(Clone, Debug)]
100 pub struct ErrorConstraintInfo {
101     // fr: outlived_fr
102     pub(super) fr: RegionVid,
103     pub(super) fr_is_local: bool,
104     pub(super) outlived_fr: RegionVid,
105     pub(super) outlived_fr_is_local: bool,
106
107     // Category and span for best blame constraint
108     pub(super) category: ConstraintCategory,
109     pub(super) span: Span,
110 }
111
112 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
113     /// Converts a region inference variable into a `ty::Region` that
114     /// we can use for error reporting. If `r` is universally bound,
115     /// then we use the name that we have on record for it. If `r` is
116     /// existentially bound, then we check its inferred value and try
117     /// to find a good name from that. Returns `None` if we can't find
118     /// one (e.g., this is just some random part of the CFG).
119     pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
120         self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
121     }
122
123     /// Returns the `RegionVid` corresponding to the region returned by
124     /// `to_error_region`.
125     pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
126         if self.regioncx.universal_regions().is_universal_region(r) {
127             Some(r)
128         } else {
129             // We just want something nameable, even if it's not
130             // actually an upper bound.
131             let upper_bound = self.regioncx.approx_universal_upper_bound(r);
132
133             if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
134                 self.to_error_region_vid(upper_bound)
135             } else {
136                 None
137             }
138         }
139     }
140
141     /// Returns `true` if a closure is inferred to be an `FnMut` closure.
142     fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
143         if let Some(ty::ReFree(free_region)) = self.to_error_region(fr).as_deref()
144             && let ty::BoundRegionKind::BrEnv = free_region.bound_region
145             && let DefiningTy::Closure(_, substs) = self.regioncx.universal_regions().defining_ty
146         {
147             return substs.as_closure().kind() == ty::ClosureKind::FnMut;
148         }
149
150         false
151     }
152
153     /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
154     pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
155         // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
156         // buffered in the `MirBorrowckCtxt`.
157
158         let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
159
160         for nll_error in nll_errors.into_iter() {
161             match nll_error {
162                 RegionErrorKind::TypeTestError { type_test } => {
163                     // Try to convert the lower-bound region into something named we can print for the user.
164                     let lower_bound_region = self.to_error_region(type_test.lower_bound);
165
166                     let type_test_span = type_test.locations.span(&self.body);
167
168                     if let Some(lower_bound_region) = lower_bound_region {
169                         self.buffer_error(self.infcx.construct_generic_bound_failure(
170                             type_test_span,
171                             None,
172                             type_test.generic_kind,
173                             lower_bound_region,
174                         ));
175                     } else {
176                         // FIXME. We should handle this case better. It
177                         // indicates that we have e.g., some region variable
178                         // whose value is like `'a+'b` where `'a` and `'b` are
179                         // distinct unrelated univesal regions that are not
180                         // known to outlive one another. It'd be nice to have
181                         // some examples where this arises to decide how best
182                         // to report it; we could probably handle it by
183                         // iterating over the universal regions and reporting
184                         // an error that multiple bounds are required.
185                         self.buffer_error(self.infcx.tcx.sess.struct_span_err(
186                             type_test_span,
187                             &format!("`{}` does not live long enough", type_test.generic_kind),
188                         ));
189                     }
190                 }
191
192                 RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, member_region } => {
193                     let named_ty = self.regioncx.name_regions(self.infcx.tcx, hidden_ty);
194                     let named_region = self.regioncx.name_regions(self.infcx.tcx, member_region);
195                     self.buffer_error(unexpected_hidden_region_diagnostic(
196                         self.infcx.tcx,
197                         span,
198                         named_ty,
199                         named_region,
200                     ));
201                 }
202
203                 RegionErrorKind::BoundUniversalRegionError {
204                     longer_fr,
205                     placeholder,
206                     error_element,
207                 } => {
208                     let error_vid = self.regioncx.region_from_element(longer_fr, &error_element);
209
210                     // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
211                     let (_, cause) = self.regioncx.find_outlives_blame_span(
212                         &self.body,
213                         longer_fr,
214                         NllRegionVariableOrigin::Placeholder(placeholder),
215                         error_vid,
216                     );
217
218                     let universe = placeholder.universe;
219                     let universe_info = self.regioncx.universe_info(universe);
220
221                     universe_info.report_error(self, placeholder, error_element, cause);
222                 }
223
224                 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
225                     if is_reported {
226                         self.report_region_error(
227                             longer_fr,
228                             fr_origin,
229                             shorter_fr,
230                             &mut outlives_suggestion,
231                         );
232                     } else {
233                         // We only report the first error, so as not to overwhelm the user. See
234                         // `RegRegionErrorKind` docs.
235                         //
236                         // FIXME: currently we do nothing with these, but perhaps we can do better?
237                         // FIXME: try collecting these constraints on the outlives suggestion
238                         // builder. Does it make the suggestions any better?
239                         debug!(
240                             "Unreported region error: can't prove that {:?}: {:?}",
241                             longer_fr, shorter_fr
242                         );
243                     }
244                 }
245             }
246         }
247
248         // Emit one outlives suggestions for each MIR def we borrowck
249         outlives_suggestion.add_suggestion(self);
250     }
251
252     /// Report an error because the universal region `fr` was required to outlive
253     /// `outlived_fr` but it is not known to do so. For example:
254     ///
255     /// ```
256     /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
257     /// ```
258     ///
259     /// Here we would be invoked with `fr = 'a` and `outlived_fr = `'b`.
260     pub(crate) fn report_region_error(
261         &mut self,
262         fr: RegionVid,
263         fr_origin: NllRegionVariableOrigin,
264         outlived_fr: RegionVid,
265         outlives_suggestion: &mut OutlivesSuggestionBuilder,
266     ) {
267         debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
268
269         let BlameConstraint { category, cause, variance_info, from_closure: _ } =
270             self.regioncx.best_blame_constraint(&self.body, fr, fr_origin, |r| {
271                 self.regioncx.provides_universal_region(r, fr, outlived_fr)
272             });
273
274         debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);
275         // Check if we can use one of the "nice region errors".
276         if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
277             let nice = NiceRegionError::new_from_span(self.infcx, cause.span, o, f);
278             if let Some(diag) = nice.try_report_from_nll() {
279                 self.buffer_error(diag);
280                 return;
281             }
282         }
283
284         let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
285             self.regioncx.universal_regions().is_local_free_region(fr),
286             self.regioncx.universal_regions().is_local_free_region(outlived_fr),
287         );
288
289         debug!(
290             "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
291             fr_is_local, outlived_fr_is_local, category
292         );
293
294         let errci = ErrorConstraintInfo {
295             fr,
296             outlived_fr,
297             fr_is_local,
298             outlived_fr_is_local,
299             category,
300             span: cause.span,
301         };
302
303         let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
304             (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
305                 self.report_fnmut_error(&errci, kind)
306             }
307             (ConstraintCategory::Assignment, true, false)
308             | (ConstraintCategory::CallArgument, true, false) => {
309                 let mut db = self.report_escaping_data_error(&errci);
310
311                 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
312                 outlives_suggestion.collect_constraint(fr, outlived_fr);
313
314                 db
315             }
316             _ => {
317                 let mut db = self.report_general_error(&errci);
318
319                 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
320                 outlives_suggestion.collect_constraint(fr, outlived_fr);
321
322                 db
323             }
324         };
325
326         match variance_info {
327             ty::VarianceDiagInfo::None => {}
328             ty::VarianceDiagInfo::Invariant { ty, param_index } => {
329                 let (desc, note) = match ty.kind() {
330                     ty::RawPtr(ty_mut) => {
331                         assert_eq!(ty_mut.mutbl, rustc_hir::Mutability::Mut);
332                         (
333                             format!("a mutable pointer to {}", ty_mut.ty),
334                             "mutable pointers are invariant over their type parameter".to_string(),
335                         )
336                     }
337                     ty::Ref(_, inner_ty, mutbl) => {
338                         assert_eq!(*mutbl, rustc_hir::Mutability::Mut);
339                         (
340                             format!("a mutable reference to {}", inner_ty),
341                             "mutable references are invariant over their type parameter"
342                                 .to_string(),
343                         )
344                     }
345                     ty::Adt(adt, substs) => {
346                         let generic_arg = substs[param_index as usize];
347                         let identity_substs =
348                             InternalSubsts::identity_for_item(self.infcx.tcx, adt.did());
349                         let base_ty = self.infcx.tcx.mk_adt(*adt, identity_substs);
350                         let base_generic_arg = identity_substs[param_index as usize];
351                         let adt_desc = adt.descr();
352
353                         let desc = format!(
354                             "the type {ty}, which makes the generic argument {generic_arg} invariant"
355                         );
356                         let note = format!(
357                             "the {adt_desc} {base_ty} is invariant over the parameter {base_generic_arg}"
358                         );
359                         (desc, note)
360                     }
361                     _ => panic!("Unexpected type {:?}", ty),
362                 };
363                 diag.note(&format!("requirement occurs because of {desc}",));
364                 diag.note(&note);
365                 diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
366             }
367         }
368
369         self.buffer_error(diag);
370     }
371
372     /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
373     /// This function expects `fr` to be local and `outlived_fr` to not be local.
374     ///
375     /// ```text
376     /// error: captured variable cannot escape `FnMut` closure body
377     ///   --> $DIR/issue-53040.rs:15:8
378     ///    |
379     /// LL |     || &mut v;
380     ///    |     -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
381     ///    |     |
382     ///    |     inferred to be a `FnMut` closure
383     ///    |
384     ///    = note: `FnMut` closures only have access to their captured variables while they are
385     ///            executing...
386     ///    = note: ...therefore, returned references to captured variables will escape the closure
387     /// ```
388     fn report_fnmut_error(
389         &self,
390         errci: &ErrorConstraintInfo,
391         kind: ReturnConstraint,
392     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
393         let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
394
395         let mut diag = self
396             .infcx
397             .tcx
398             .sess
399             .struct_span_err(*span, "captured variable cannot escape `FnMut` closure body");
400
401         let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
402         if let ty::Opaque(def_id, _) = *output_ty.kind() {
403             output_ty = self.infcx.tcx.type_of(def_id)
404         };
405
406         debug!("report_fnmut_error: output_ty={:?}", output_ty);
407
408         let message = match output_ty.kind() {
409             ty::Closure(_, _) => {
410                 "returns a closure that contains a reference to a captured variable, which then \
411                  escapes the closure body"
412             }
413             ty::Adt(def, _) if self.infcx.tcx.is_diagnostic_item(sym::gen_future, def.did()) => {
414                 "returns an `async` block that contains a reference to a captured variable, which then \
415                  escapes the closure body"
416             }
417             _ => "returns a reference to a captured variable which escapes the closure body",
418         };
419
420         diag.span_label(*span, message);
421
422         if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
423             let def_id = match self.regioncx.universal_regions().defining_ty {
424                 DefiningTy::Closure(def_id, _) => def_id,
425                 ty => bug!("unexpected DefiningTy {:?}", ty),
426             };
427
428             let captured_place = &self.upvars[upvar_field.index()].place;
429             let defined_hir = match captured_place.place.base {
430                 PlaceBase::Local(hirid) => Some(hirid),
431                 PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
432                 _ => None,
433             };
434
435             if defined_hir.is_some() {
436                 let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
437                 let upvar_def_span = self.infcx.tcx.hir().span(defined_hir.unwrap());
438                 let upvar_span = upvars_map.get(&defined_hir.unwrap()).unwrap().span;
439                 diag.span_label(upvar_def_span, "variable defined here");
440                 diag.span_label(upvar_span, "variable captured here");
441             }
442         }
443
444         if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
445             diag.span_label(fr_span, "inferred to be a `FnMut` closure");
446         }
447
448         diag.note(
449             "`FnMut` closures only have access to their captured variables while they are \
450              executing...",
451         );
452         diag.note("...therefore, they cannot allow references to captured variables to escape");
453
454         diag
455     }
456
457     /// Reports an error specifically for when data is escaping a closure.
458     ///
459     /// ```text
460     /// error: borrowed data escapes outside of function
461     ///   --> $DIR/lifetime-bound-will-change-warning.rs:44:5
462     ///    |
463     /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
464     ///    |              - `x` is a reference that is only valid in the function body
465     /// LL |     // but ref_obj will not, so warn.
466     /// LL |     ref_obj(x)
467     ///    |     ^^^^^^^^^^ `x` escapes the function body here
468     /// ```
469     fn report_escaping_data_error(
470         &self,
471         errci: &ErrorConstraintInfo,
472     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
473         let ErrorConstraintInfo { span, category, .. } = errci;
474
475         let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
476             self.infcx.tcx,
477             &self.body,
478             &self.local_names,
479             &self.upvars,
480             errci.fr,
481         );
482         let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
483             self.infcx.tcx,
484             &self.body,
485             &self.local_names,
486             &self.upvars,
487             errci.outlived_fr,
488         );
489
490         let (_, escapes_from) = self
491             .infcx
492             .tcx
493             .article_and_description(self.regioncx.universal_regions().defining_ty.def_id());
494
495         // Revert to the normal error in these cases.
496         // Assignments aren't "escapes" in function items.
497         if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
498             || (*category == ConstraintCategory::Assignment
499                 && self.regioncx.universal_regions().defining_ty.is_fn_def())
500             || self.regioncx.universal_regions().defining_ty.is_const()
501         {
502             return self.report_general_error(&ErrorConstraintInfo {
503                 fr_is_local: true,
504                 outlived_fr_is_local: false,
505                 ..*errci
506             });
507         }
508
509         let mut diag =
510             borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
511
512         if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
513             diag.span_label(
514                 outlived_fr_span,
515                 format!(
516                     "`{}` declared here, outside of the {} body",
517                     outlived_fr_name, escapes_from
518                 ),
519             );
520         }
521
522         if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
523             diag.span_label(
524                 fr_span,
525                 format!(
526                     "`{}` is a reference that is only valid in the {} body",
527                     fr_name, escapes_from
528                 ),
529             );
530
531             diag.span_label(*span, format!("`{}` escapes the {} body here", fr_name, escapes_from));
532         }
533
534         // Only show an extra note if we can find an 'error region' for both of the region
535         // variables. This avoids showing a noisy note that just mentions 'synthetic' regions
536         // that don't help the user understand the error.
537         if self.to_error_region(errci.fr).is_some()
538             && self.to_error_region(errci.outlived_fr).is_some()
539         {
540             let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
541             fr_region_name.highlight_region_name(&mut diag);
542             let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
543             outlived_fr_region_name.highlight_region_name(&mut diag);
544
545             diag.span_label(
546                 *span,
547                 format!(
548                     "{}requires that `{}` must outlive `{}`",
549                     category.description(),
550                     fr_region_name,
551                     outlived_fr_region_name,
552                 ),
553             );
554         }
555         diag
556     }
557
558     /// Reports a region inference error for the general case with named/synthesized lifetimes to
559     /// explain what is happening.
560     ///
561     /// ```text
562     /// error: unsatisfied lifetime constraints
563     ///   --> $DIR/regions-creating-enums3.rs:17:5
564     ///    |
565     /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
566     ///    |                -- -- lifetime `'b` defined here
567     ///    |                |
568     ///    |                lifetime `'a` defined here
569     /// LL |     ast::add(x, y)
570     ///    |     ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
571     ///    |                    is returning data with lifetime `'b`
572     /// ```
573     fn report_general_error(
574         &self,
575         errci: &ErrorConstraintInfo,
576     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
577         let ErrorConstraintInfo {
578             fr,
579             fr_is_local,
580             outlived_fr,
581             outlived_fr_is_local,
582             span,
583             category,
584             ..
585         } = errci;
586
587         let mut diag =
588             self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
589
590         let (_, mir_def_name) =
591             self.infcx.tcx.article_and_description(self.mir_def_id().to_def_id());
592
593         let fr_name = self.give_region_a_name(*fr).unwrap();
594         fr_name.highlight_region_name(&mut diag);
595         let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
596         outlived_fr_name.highlight_region_name(&mut diag);
597
598         match (category, outlived_fr_is_local, fr_is_local) {
599             (ConstraintCategory::Return(_), true, _) => {
600                 diag.span_label(
601                     *span,
602                     format!(
603                         "{} was supposed to return data with lifetime `{}` but it is returning \
604                          data with lifetime `{}`",
605                         mir_def_name, outlived_fr_name, fr_name
606                     ),
607                 );
608             }
609             _ => {
610                 diag.span_label(
611                     *span,
612                     format!(
613                         "{}requires that `{}` must outlive `{}`",
614                         category.description(),
615                         fr_name,
616                         outlived_fr_name,
617                     ),
618                 );
619             }
620         }
621
622         self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
623
624         diag
625     }
626
627     /// Adds a suggestion to errors where an `impl Trait` is returned.
628     ///
629     /// ```text
630     /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
631     ///       a constraint
632     ///    |
633     /// LL |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
634     ///    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
635     /// ```
636     fn add_static_impl_trait_suggestion(
637         &self,
638         diag: &mut Diagnostic,
639         fr: RegionVid,
640         // We need to pass `fr_name` - computing it again will label it twice.
641         fr_name: RegionName,
642         outlived_fr: RegionVid,
643     ) {
644         if let (Some(f), Some(ty::ReStatic)) =
645             (self.to_error_region(fr), self.to_error_region(outlived_fr).as_deref())
646         {
647             if let Some(&ty::Opaque(did, substs)) = self
648                 .infcx
649                 .tcx
650                 .is_suitable_region(f)
651                 .map(|r| r.def_id)
652                 .and_then(|id| self.infcx.tcx.return_type_impl_trait(id))
653                 .map(|(ty, _)| ty.kind())
654             {
655                 // Check whether or not the impl trait return type is intended to capture
656                 // data with the static lifetime.
657                 //
658                 // eg. check for `impl Trait + 'static` instead of `impl Trait`.
659                 let has_static_predicate = {
660                     let bounds = self.infcx.tcx.explicit_item_bounds(did);
661
662                     let mut found = false;
663                     for (bound, _) in bounds {
664                         if let ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_, r)) =
665                             bound.kind().skip_binder()
666                         {
667                             let r = r.subst(self.infcx.tcx, substs);
668                             if r.is_static() {
669                                 found = true;
670                                 break;
671                             } else {
672                                 // If there's already a lifetime bound, don't
673                                 // suggest anything.
674                                 return;
675                             }
676                         }
677                     }
678
679                     found
680                 };
681
682                 debug!(
683                     "add_static_impl_trait_suggestion: has_static_predicate={:?}",
684                     has_static_predicate
685                 );
686                 let static_str = kw::StaticLifetime;
687                 // If there is a static predicate, then the only sensible suggestion is to replace
688                 // fr with `'static`.
689                 if has_static_predicate {
690                     diag.help(&format!("consider replacing `{}` with `{}`", fr_name, static_str));
691                 } else {
692                     // Otherwise, we should suggest adding a constraint on the return type.
693                     let span = self.infcx.tcx.def_span(did);
694                     if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
695                         let suggestable_fr_name = if fr_name.was_named() {
696                             fr_name.to_string()
697                         } else {
698                             "'_".to_string()
699                         };
700                         let span = if snippet.ends_with(';') {
701                             // `type X = impl Trait;`
702                             span.with_hi(span.hi() - BytePos(1))
703                         } else {
704                             span
705                         };
706                         let suggestion = format!(" + {}", suggestable_fr_name);
707                         let span = span.shrink_to_hi();
708                         diag.span_suggestion(
709                             span,
710                             &format!(
711                                 "to allow this `impl Trait` to capture borrowed data with lifetime \
712                                  `{}`, add `{}` as a bound",
713                                 fr_name, suggestable_fr_name,
714                             ),
715                             suggestion,
716                             Applicability::MachineApplicable,
717                         );
718                     }
719                 }
720             }
721         }
722     }
723 }