]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/region_errors.rs
Rollup merge of #94212 - scottmcm:swapper, r=dtolnay
[rust.git] / compiler / rustc_borrowck / src / diagnostics / region_errors.rs
1 //! Error reporting machinery for lifetime errors.
2
3 use rustc_errors::{Applicability, DiagnosticBuilder};
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> {
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(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
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(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
574         let ErrorConstraintInfo {
575             fr,
576             fr_is_local,
577             outlived_fr,
578             outlived_fr_is_local,
579             span,
580             category,
581             ..
582         } = errci;
583
584         let mut diag =
585             self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
586
587         let (_, mir_def_name) =
588             self.infcx.tcx.article_and_description(self.mir_def_id().to_def_id());
589
590         let fr_name = self.give_region_a_name(*fr).unwrap();
591         fr_name.highlight_region_name(&mut diag);
592         let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
593         outlived_fr_name.highlight_region_name(&mut diag);
594
595         match (category, outlived_fr_is_local, fr_is_local) {
596             (ConstraintCategory::Return(_), true, _) => {
597                 diag.span_label(
598                     *span,
599                     format!(
600                         "{} was supposed to return data with lifetime `{}` but it is returning \
601                          data with lifetime `{}`",
602                         mir_def_name, outlived_fr_name, fr_name
603                     ),
604                 );
605             }
606             _ => {
607                 diag.span_label(
608                     *span,
609                     format!(
610                         "{}requires that `{}` must outlive `{}`",
611                         category.description(),
612                         fr_name,
613                         outlived_fr_name,
614                     ),
615                 );
616             }
617         }
618
619         self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
620
621         diag
622     }
623
624     /// Adds a suggestion to errors where an `impl Trait` is returned.
625     ///
626     /// ```text
627     /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
628     ///       a constraint
629     ///    |
630     /// LL |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
631     ///    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
632     /// ```
633     fn add_static_impl_trait_suggestion(
634         &self,
635         diag: &mut DiagnosticBuilder<'tcx>,
636         fr: RegionVid,
637         // We need to pass `fr_name` - computing it again will label it twice.
638         fr_name: RegionName,
639         outlived_fr: RegionVid,
640     ) {
641         if let (Some(f), Some(ty::ReStatic)) =
642             (self.to_error_region(fr), self.to_error_region(outlived_fr).as_deref())
643         {
644             if let Some(&ty::Opaque(did, substs)) = self
645                 .infcx
646                 .tcx
647                 .is_suitable_region(f)
648                 .map(|r| r.def_id)
649                 .and_then(|id| self.infcx.tcx.return_type_impl_trait(id))
650                 .map(|(ty, _)| ty.kind())
651             {
652                 // Check whether or not the impl trait return type is intended to capture
653                 // data with the static lifetime.
654                 //
655                 // eg. check for `impl Trait + 'static` instead of `impl Trait`.
656                 let has_static_predicate = {
657                     let bounds = self.infcx.tcx.explicit_item_bounds(did);
658
659                     let mut found = false;
660                     for (bound, _) in bounds {
661                         if let ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_, r)) =
662                             bound.kind().skip_binder()
663                         {
664                             let r = r.subst(self.infcx.tcx, substs);
665                             if r.is_static() {
666                                 found = true;
667                                 break;
668                             } else {
669                                 // If there's already a lifetime bound, don't
670                                 // suggest anything.
671                                 return;
672                             }
673                         }
674                     }
675
676                     found
677                 };
678
679                 debug!(
680                     "add_static_impl_trait_suggestion: has_static_predicate={:?}",
681                     has_static_predicate
682                 );
683                 let static_str = kw::StaticLifetime;
684                 // If there is a static predicate, then the only sensible suggestion is to replace
685                 // fr with `'static`.
686                 if has_static_predicate {
687                     diag.help(&format!("consider replacing `{}` with `{}`", fr_name, static_str));
688                 } else {
689                     // Otherwise, we should suggest adding a constraint on the return type.
690                     let span = self.infcx.tcx.def_span(did);
691                     if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
692                         let suggestable_fr_name = if fr_name.was_named() {
693                             fr_name.to_string()
694                         } else {
695                             "'_".to_string()
696                         };
697                         let span = if snippet.ends_with(';') {
698                             // `type X = impl Trait;`
699                             span.with_hi(span.hi() - BytePos(1))
700                         } else {
701                             span
702                         };
703                         let suggestion = format!(" + {}", suggestable_fr_name);
704                         let span = span.shrink_to_hi();
705                         diag.span_suggestion(
706                             span,
707                             &format!(
708                                 "to allow this `impl Trait` to capture borrowed data with lifetime \
709                                  `{}`, add `{}` as a bound",
710                                 fr_name, suggestable_fr_name,
711                             ),
712                             suggestion,
713                             Applicability::MachineApplicable,
714                         );
715                     }
716                 }
717             }
718         }
719     }
720 }