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