]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/region_name.rs
Use Term in ProjectionPredicate
[rust.git] / compiler / rustc_borrowck / src / diagnostics / region_name.rs
1 use std::fmt::{self, Display};
2 use std::iter;
3
4 use rustc_errors::DiagnosticBuilder;
5 use rustc_hir as hir;
6 use rustc_hir::def::{DefKind, Res};
7 use rustc_middle::ty::print::RegionHighlightMode;
8 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
9 use rustc_middle::ty::{self, RegionVid, Ty};
10 use rustc_span::symbol::{kw, sym, Ident, Symbol};
11 use rustc_span::{Span, DUMMY_SP};
12
13 use crate::{nll::ToRegionVid, universal_regions::DefiningTy, MirBorrowckCtxt};
14
15 /// A name for a particular region used in emitting diagnostics. This name could be a generated
16 /// name like `'1`, a name used by the user like `'a`, or a name like `'static`.
17 #[derive(Debug, Clone)]
18 crate struct RegionName {
19     /// The name of the region (interned).
20     crate name: Symbol,
21     /// Where the region comes from.
22     crate source: RegionNameSource,
23 }
24
25 /// Denotes the source of a region that is named by a `RegionName`. For example, a free region that
26 /// was named by the user would get `NamedFreeRegion` and `'static` lifetime would get `Static`.
27 /// This helps to print the right kinds of diagnostics.
28 #[derive(Debug, Clone)]
29 crate enum RegionNameSource {
30     /// A bound (not free) region that was substituted at the def site (not an HRTB).
31     NamedEarlyBoundRegion(Span),
32     /// A free region that the user has a name (`'a`) for.
33     NamedFreeRegion(Span),
34     /// The `'static` region.
35     Static,
36     /// The free region corresponding to the environment of a closure.
37     SynthesizedFreeEnvRegion(Span, String),
38     /// The region corresponding to an argument.
39     AnonRegionFromArgument(RegionNameHighlight),
40     /// The region corresponding to a closure upvar.
41     AnonRegionFromUpvar(Span, String),
42     /// The region corresponding to the return type of a closure.
43     AnonRegionFromOutput(RegionNameHighlight, String),
44     /// The region from a type yielded by a generator.
45     AnonRegionFromYieldTy(Span, String),
46     /// An anonymous region from an async fn.
47     AnonRegionFromAsyncFn(Span),
48 }
49
50 /// Describes what to highlight to explain to the user that we're giving an anonymous region a
51 /// synthesized name, and how to highlight it.
52 #[derive(Debug, Clone)]
53 crate enum RegionNameHighlight {
54     /// The anonymous region corresponds to a reference that was found by traversing the type in the HIR.
55     MatchedHirTy(Span),
56     /// The anonymous region corresponds to a `'_` in the generics list of a struct/enum/union.
57     MatchedAdtAndSegment(Span),
58     /// The anonymous region corresponds to a region where the type annotation is completely missing
59     /// from the code, e.g. in a closure arguments `|x| { ... }`, where `x` is a reference.
60     CannotMatchHirTy(Span, String),
61     /// The anonymous region corresponds to a region where the type annotation is completely missing
62     /// from the code, and *even if* we print out the full name of the type, the region name won't
63     /// be included. This currently occurs for opaque types like `impl Future`.
64     Occluded(Span, String),
65 }
66
67 impl RegionName {
68     crate fn was_named(&self) -> bool {
69         match self.source {
70             RegionNameSource::NamedEarlyBoundRegion(..)
71             | RegionNameSource::NamedFreeRegion(..)
72             | RegionNameSource::Static => true,
73             RegionNameSource::SynthesizedFreeEnvRegion(..)
74             | RegionNameSource::AnonRegionFromArgument(..)
75             | RegionNameSource::AnonRegionFromUpvar(..)
76             | RegionNameSource::AnonRegionFromOutput(..)
77             | RegionNameSource::AnonRegionFromYieldTy(..)
78             | RegionNameSource::AnonRegionFromAsyncFn(..) => false,
79         }
80     }
81
82     crate fn span(&self) -> Option<Span> {
83         match self.source {
84             RegionNameSource::Static => None,
85             RegionNameSource::NamedEarlyBoundRegion(span)
86             | RegionNameSource::NamedFreeRegion(span)
87             | RegionNameSource::SynthesizedFreeEnvRegion(span, _)
88             | RegionNameSource::AnonRegionFromUpvar(span, _)
89             | RegionNameSource::AnonRegionFromYieldTy(span, _)
90             | RegionNameSource::AnonRegionFromAsyncFn(span) => Some(span),
91             RegionNameSource::AnonRegionFromArgument(ref highlight)
92             | RegionNameSource::AnonRegionFromOutput(ref highlight, _) => match *highlight {
93                 RegionNameHighlight::MatchedHirTy(span)
94                 | RegionNameHighlight::MatchedAdtAndSegment(span)
95                 | RegionNameHighlight::CannotMatchHirTy(span, _)
96                 | RegionNameHighlight::Occluded(span, _) => Some(span),
97             },
98         }
99     }
100
101     crate fn highlight_region_name(&self, diag: &mut DiagnosticBuilder<'_>) {
102         match &self.source {
103             RegionNameSource::NamedFreeRegion(span)
104             | RegionNameSource::NamedEarlyBoundRegion(span) => {
105                 diag.span_label(*span, format!("lifetime `{}` defined here", self));
106             }
107             RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
108                 diag.span_label(
109                     *span,
110                     format!("lifetime `{}` represents this closure's body", self),
111                 );
112                 diag.note(&note);
113             }
114             RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::CannotMatchHirTy(
115                 span,
116                 type_name,
117             )) => {
118                 diag.span_label(*span, format!("has type `{}`", type_name));
119             }
120             RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::MatchedHirTy(span))
121             | RegionNameSource::AnonRegionFromOutput(RegionNameHighlight::MatchedHirTy(span), _)
122             | RegionNameSource::AnonRegionFromAsyncFn(span) => {
123                 diag.span_label(
124                     *span,
125                     format!("let's call the lifetime of this reference `{}`", self),
126                 );
127             }
128             RegionNameSource::AnonRegionFromArgument(
129                 RegionNameHighlight::MatchedAdtAndSegment(span),
130             )
131             | RegionNameSource::AnonRegionFromOutput(
132                 RegionNameHighlight::MatchedAdtAndSegment(span),
133                 _,
134             ) => {
135                 diag.span_label(*span, format!("let's call this `{}`", self));
136             }
137             RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::Occluded(
138                 span,
139                 type_name,
140             )) => {
141                 diag.span_label(
142                     *span,
143                     format!("lifetime `{}` appears in the type {}", self, type_name),
144                 );
145             }
146             RegionNameSource::AnonRegionFromOutput(
147                 RegionNameHighlight::Occluded(span, type_name),
148                 mir_description,
149             ) => {
150                 diag.span_label(
151                     *span,
152                     format!(
153                         "return type{} `{}` contains a lifetime `{}`",
154                         mir_description, type_name, self
155                     ),
156                 );
157             }
158             RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
159                 diag.span_label(
160                     *span,
161                     format!("lifetime `{}` appears in the type of `{}`", self, upvar_name),
162                 );
163             }
164             RegionNameSource::AnonRegionFromOutput(
165                 RegionNameHighlight::CannotMatchHirTy(span, type_name),
166                 mir_description,
167             ) => {
168                 diag.span_label(*span, format!("return type{} is {}", mir_description, type_name));
169             }
170             RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
171                 diag.span_label(*span, format!("yield type is {}", type_name));
172             }
173             RegionNameSource::Static => {}
174         }
175     }
176 }
177
178 impl Display for RegionName {
179     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180         write!(f, "{}", self.name)
181     }
182 }
183
184 impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
185     crate fn mir_def_id(&self) -> hir::def_id::LocalDefId {
186         self.body.source.def_id().as_local().unwrap()
187     }
188
189     crate fn mir_hir_id(&self) -> hir::HirId {
190         self.infcx.tcx.hir().local_def_id_to_hir_id(self.mir_def_id())
191     }
192
193     /// Generate a synthetic region named `'N`, where `N` is the next value of the counter. Then,
194     /// increment the counter.
195     ///
196     /// This is _not_ idempotent. Call `give_region_a_name` when possible.
197     fn synthesize_region_name(&self) -> Symbol {
198         let c = self.next_region_name.replace_with(|counter| *counter + 1);
199         Symbol::intern(&format!("'{:?}", c))
200     }
201
202     /// Maps from an internal MIR region vid to something that we can
203     /// report to the user. In some cases, the region vids will map
204     /// directly to lifetimes that the user has a name for (e.g.,
205     /// `'static`). But frequently they will not, in which case we
206     /// have to find some way to identify the lifetime to the user. To
207     /// that end, this function takes a "diagnostic" so that it can
208     /// create auxiliary notes as needed.
209     ///
210     /// The names are memoized, so this is both cheap to recompute and idempotent.
211     ///
212     /// Example (function arguments):
213     ///
214     /// Suppose we are trying to give a name to the lifetime of the
215     /// reference `x`:
216     ///
217     /// ```
218     /// fn foo(x: &u32) { .. }
219     /// ```
220     ///
221     /// This function would create a label like this:
222     ///
223     /// ```text
224     ///  | fn foo(x: &u32) { .. }
225     ///           ------- fully elaborated type of `x` is `&'1 u32`
226     /// ```
227     ///
228     /// and then return the name `'1` for us to use.
229     crate fn give_region_a_name(&self, fr: RegionVid) -> Option<RegionName> {
230         debug!(
231             "give_region_a_name(fr={:?}, counter={:?})",
232             fr,
233             self.next_region_name.try_borrow().unwrap()
234         );
235
236         assert!(self.regioncx.universal_regions().is_universal_region(fr));
237
238         if let Some(value) = self.region_names.try_borrow_mut().unwrap().get(&fr) {
239             return Some(value.clone());
240         }
241
242         let value = self
243             .give_name_from_error_region(fr)
244             .or_else(|| self.give_name_if_anonymous_region_appears_in_arguments(fr))
245             .or_else(|| self.give_name_if_anonymous_region_appears_in_upvars(fr))
246             .or_else(|| self.give_name_if_anonymous_region_appears_in_output(fr))
247             .or_else(|| self.give_name_if_anonymous_region_appears_in_yield_ty(fr));
248
249         if let Some(ref value) = value {
250             self.region_names.try_borrow_mut().unwrap().insert(fr, value.clone());
251         }
252
253         debug!("give_region_a_name: gave name {:?}", value);
254         value
255     }
256
257     /// Checks for the case where `fr` maps to something that the
258     /// *user* has a name for. In that case, we'll be able to map
259     /// `fr` to a `Region<'tcx>`, and that region will be one of
260     /// named variants.
261     fn give_name_from_error_region(&self, fr: RegionVid) -> Option<RegionName> {
262         let error_region = self.to_error_region(fr)?;
263
264         let tcx = self.infcx.tcx;
265
266         debug!("give_region_a_name: error_region = {:?}", error_region);
267         match error_region {
268             ty::ReEarlyBound(ebr) => {
269                 if ebr.has_name() {
270                     let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP);
271                     Some(RegionName {
272                         name: ebr.name,
273                         source: RegionNameSource::NamedEarlyBoundRegion(span),
274                     })
275                 } else {
276                     None
277                 }
278             }
279
280             ty::ReStatic => {
281                 Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })
282             }
283
284             ty::ReFree(free_region) => match free_region.bound_region {
285                 ty::BoundRegionKind::BrNamed(region_def_id, name) => {
286                     // Get the span to point to, even if we don't use the name.
287                     let span = tcx.hir().span_if_local(region_def_id).unwrap_or(DUMMY_SP);
288                     debug!(
289                         "bound region named: {:?}, is_named: {:?}",
290                         name,
291                         free_region.bound_region.is_named()
292                     );
293
294                     if free_region.bound_region.is_named() {
295                         // A named region that is actually named.
296                         Some(RegionName { name, source: RegionNameSource::NamedFreeRegion(span) })
297                     } else {
298                         // If we spuriously thought that the region is named, we should let the
299                         // system generate a true name for error messages. Currently this can
300                         // happen if we have an elided name in an async fn for example: the
301                         // compiler will generate a region named `'_`, but reporting such a name is
302                         // not actually useful, so we synthesize a name for it instead.
303                         let name = self.synthesize_region_name();
304                         Some(RegionName {
305                             name,
306                             source: RegionNameSource::AnonRegionFromAsyncFn(span),
307                         })
308                     }
309                 }
310
311                 ty::BoundRegionKind::BrEnv => {
312                     let def_ty = self.regioncx.universal_regions().defining_ty;
313
314                     if let DefiningTy::Closure(_, substs) = def_ty {
315                         let args_span = if let hir::ExprKind::Closure(_, _, _, span, _) =
316                             tcx.hir().expect_expr(self.mir_hir_id()).kind
317                         {
318                             span
319                         } else {
320                             bug!("Closure is not defined by a closure expr");
321                         };
322                         let region_name = self.synthesize_region_name();
323
324                         let closure_kind_ty = substs.as_closure().kind_ty();
325                         let note = match closure_kind_ty.to_opt_closure_kind() {
326                             Some(ty::ClosureKind::Fn) => {
327                                 "closure implements `Fn`, so references to captured variables \
328                                  can't escape the closure"
329                             }
330                             Some(ty::ClosureKind::FnMut) => {
331                                 "closure implements `FnMut`, so references to captured variables \
332                                  can't escape the closure"
333                             }
334                             Some(ty::ClosureKind::FnOnce) => {
335                                 bug!("BrEnv in a `FnOnce` closure");
336                             }
337                             None => bug!("Closure kind not inferred in borrow check"),
338                         };
339
340                         Some(RegionName {
341                             name: region_name,
342                             source: RegionNameSource::SynthesizedFreeEnvRegion(
343                                 args_span,
344                                 note.to_string(),
345                             ),
346                         })
347                     } else {
348                         // Can't have BrEnv in functions, constants or generators.
349                         bug!("BrEnv outside of closure.");
350                     }
351                 }
352
353                 ty::BoundRegionKind::BrAnon(_) => None,
354             },
355
356             ty::ReLateBound(..)
357             | ty::ReVar(..)
358             | ty::RePlaceholder(..)
359             | ty::ReEmpty(_)
360             | ty::ReErased => None,
361         }
362     }
363
364     /// Finds an argument that contains `fr` and label it with a fully
365     /// elaborated type, returning something like `'1`. Result looks
366     /// like:
367     ///
368     /// ```text
369     ///  | fn foo(x: &u32) { .. }
370     ///           ------- fully elaborated type of `x` is `&'1 u32`
371     /// ```
372     fn give_name_if_anonymous_region_appears_in_arguments(
373         &self,
374         fr: RegionVid,
375     ) -> Option<RegionName> {
376         let implicit_inputs = self.regioncx.universal_regions().defining_ty.implicit_inputs();
377         let argument_index = self.regioncx.get_argument_index_for_region(self.infcx.tcx, fr)?;
378
379         let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys
380             [implicit_inputs + argument_index];
381         let (_, span) = self.regioncx.get_argument_name_and_span_for_region(
382             &self.body,
383             &self.local_names,
384             argument_index,
385         );
386
387         let highlight = self
388             .get_argument_hir_ty_for_highlighting(argument_index)
389             .and_then(|arg_hir_ty| self.highlight_if_we_can_match_hir_ty(fr, arg_ty, arg_hir_ty))
390             .unwrap_or_else(|| {
391                 // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
392                 // the anonymous region. If it succeeds, the `synthesize_region_name` call below
393                 // will increment the counter, "reserving" the number we just used.
394                 let counter = *self.next_region_name.try_borrow().unwrap();
395                 self.highlight_if_we_cannot_match_hir_ty(fr, arg_ty, span, counter)
396             });
397
398         Some(RegionName {
399             name: self.synthesize_region_name(),
400             source: RegionNameSource::AnonRegionFromArgument(highlight),
401         })
402     }
403
404     fn get_argument_hir_ty_for_highlighting(
405         &self,
406         argument_index: usize,
407     ) -> Option<&hir::Ty<'tcx>> {
408         let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(self.mir_hir_id())?;
409         let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(argument_index)?;
410         match argument_hir_ty.kind {
411             // This indicates a variable with no type annotation, like
412             // `|x|`... in that case, we can't highlight the type but
413             // must highlight the variable.
414             // NOTE(eddyb) this is handled in/by the sole caller
415             // (`give_name_if_anonymous_region_appears_in_arguments`).
416             hir::TyKind::Infer => None,
417
418             _ => Some(argument_hir_ty),
419         }
420     }
421
422     /// Attempts to highlight the specific part of a type in an argument
423     /// that has no type annotation.
424     /// For example, we might produce an annotation like this:
425     ///
426     /// ```text
427     ///  |     foo(|a, b| b)
428     ///  |          -  -
429     ///  |          |  |
430     ///  |          |  has type `&'1 u32`
431     ///  |          has type `&'2 u32`
432     /// ```
433     fn highlight_if_we_cannot_match_hir_ty(
434         &self,
435         needle_fr: RegionVid,
436         ty: Ty<'tcx>,
437         span: Span,
438         counter: usize,
439     ) -> RegionNameHighlight {
440         let mut highlight = RegionHighlightMode::default();
441         highlight.highlighting_region_vid(needle_fr, counter);
442         let type_name =
443             self.infcx.extract_inference_diagnostics_data(ty.into(), Some(highlight)).name;
444
445         debug!(
446             "highlight_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
447             type_name, needle_fr
448         );
449         if type_name.contains(&format!("'{}", counter)) {
450             // Only add a label if we can confirm that a region was labelled.
451             RegionNameHighlight::CannotMatchHirTy(span, type_name)
452         } else {
453             RegionNameHighlight::Occluded(span, type_name)
454         }
455     }
456
457     /// Attempts to highlight the specific part of a type annotation
458     /// that contains the anonymous reference we want to give a name
459     /// to. For example, we might produce an annotation like this:
460     ///
461     /// ```text
462     ///  | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
463     ///  |                - let's call the lifetime of this reference `'1`
464     /// ```
465     ///
466     /// the way this works is that we match up `ty`, which is
467     /// a `Ty<'tcx>` (the internal form of the type) with
468     /// `hir_ty`, a `hir::Ty` (the syntax of the type
469     /// annotation). We are descending through the types stepwise,
470     /// looking in to find the region `needle_fr` in the internal
471     /// type. Once we find that, we can use the span of the `hir::Ty`
472     /// to add the highlight.
473     ///
474     /// This is a somewhat imperfect process, so along the way we also
475     /// keep track of the **closest** type we've found. If we fail to
476     /// find the exact `&` or `'_` to highlight, then we may fall back
477     /// to highlighting that closest type instead.
478     fn highlight_if_we_can_match_hir_ty(
479         &self,
480         needle_fr: RegionVid,
481         ty: Ty<'tcx>,
482         hir_ty: &hir::Ty<'_>,
483     ) -> Option<RegionNameHighlight> {
484         let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty<'_>)> = &mut vec![(ty, hir_ty)];
485
486         while let Some((ty, hir_ty)) = search_stack.pop() {
487             match (&ty.kind(), &hir_ty.kind) {
488                 // Check if the `ty` is `&'X ..` where `'X`
489                 // is the region we are looking for -- if so, and we have a `&T`
490                 // on the RHS, then we want to highlight the `&` like so:
491                 //
492                 //     &
493                 //     - let's call the lifetime of this reference `'1`
494                 (
495                     ty::Ref(region, referent_ty, _),
496                     hir::TyKind::Rptr(_lifetime, referent_hir_ty),
497                 ) => {
498                     if region.to_region_vid() == needle_fr {
499                         // Just grab the first character, the `&`.
500                         let source_map = self.infcx.tcx.sess.source_map();
501                         let ampersand_span = source_map.start_point(hir_ty.span);
502
503                         return Some(RegionNameHighlight::MatchedHirTy(ampersand_span));
504                     }
505
506                     // Otherwise, let's descend into the referent types.
507                     search_stack.push((referent_ty, &referent_hir_ty.ty));
508                 }
509
510                 // Match up something like `Foo<'1>`
511                 (
512                     ty::Adt(_adt_def, substs),
513                     hir::TyKind::Path(hir::QPath::Resolved(None, path)),
514                 ) => {
515                     match path.res {
516                         // Type parameters of the type alias have no reason to
517                         // be the same as those of the ADT.
518                         // FIXME: We should be able to do something similar to
519                         // match_adt_and_segment in this case.
520                         Res::Def(DefKind::TyAlias, _) => (),
521                         _ => {
522                             if let Some(last_segment) = path.segments.last() {
523                                 if let Some(highlight) = self.match_adt_and_segment(
524                                     substs,
525                                     needle_fr,
526                                     last_segment,
527                                     search_stack,
528                                 ) {
529                                     return Some(highlight);
530                                 }
531                             }
532                         }
533                     }
534                 }
535
536                 // The following cases don't have lifetimes, so we
537                 // just worry about trying to match up the rustc type
538                 // with the HIR types:
539                 (ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
540                     search_stack
541                         .extend(iter::zip(elem_tys.iter().map(|k| k.expect_ty()), *elem_hir_tys));
542                 }
543
544                 (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
545                 | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
546                     search_stack.push((elem_ty, elem_hir_ty));
547                 }
548
549                 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
550                     search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
551                 }
552
553                 _ => {
554                     // FIXME there are other cases that we could trace
555                 }
556             }
557         }
558
559         None
560     }
561
562     /// We've found an enum/struct/union type with the substitutions
563     /// `substs` and -- in the HIR -- a path type with the final
564     /// segment `last_segment`. Try to find a `'_` to highlight in
565     /// the generic args (or, if not, to produce new zipped pairs of
566     /// types+hir to search through).
567     fn match_adt_and_segment<'hir>(
568         &self,
569         substs: SubstsRef<'tcx>,
570         needle_fr: RegionVid,
571         last_segment: &'hir hir::PathSegment<'hir>,
572         search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
573     ) -> Option<RegionNameHighlight> {
574         // Did the user give explicit arguments? (e.g., `Foo<..>`)
575         let args = last_segment.args.as_ref()?;
576         let lifetime =
577             self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
578         match lifetime.name {
579             hir::LifetimeName::Param(_)
580             | hir::LifetimeName::Error
581             | hir::LifetimeName::Static
582             | hir::LifetimeName::Underscore => {
583                 let lifetime_span = lifetime.span;
584                 Some(RegionNameHighlight::MatchedAdtAndSegment(lifetime_span))
585             }
586
587             hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Implicit(_) => {
588                 // In this case, the user left off the lifetime; so
589                 // they wrote something like:
590                 //
591                 // ```
592                 // x: Foo<T>
593                 // ```
594                 //
595                 // where the fully elaborated form is `Foo<'_, '1,
596                 // T>`. We don't consider this a match; instead we let
597                 // the "fully elaborated" type fallback above handle
598                 // it.
599                 None
600             }
601         }
602     }
603
604     /// We've found an enum/struct/union type with the substitutions
605     /// `substs` and -- in the HIR -- a path with the generic
606     /// arguments `args`. If `needle_fr` appears in the args, return
607     /// the `hir::Lifetime` that corresponds to it. If not, push onto
608     /// `search_stack` the types+hir to search through.
609     fn try_match_adt_and_generic_args<'hir>(
610         &self,
611         substs: SubstsRef<'tcx>,
612         needle_fr: RegionVid,
613         args: &'hir hir::GenericArgs<'hir>,
614         search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
615     ) -> Option<&'hir hir::Lifetime> {
616         for (kind, hir_arg) in iter::zip(substs, args.args) {
617             match (kind.unpack(), hir_arg) {
618                 (GenericArgKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
619                     if r.to_region_vid() == needle_fr {
620                         return Some(lt);
621                     }
622                 }
623
624                 (GenericArgKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
625                     search_stack.push((ty, hir_ty));
626                 }
627
628                 (GenericArgKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
629                     // Lifetimes cannot be found in consts, so we don't need
630                     // to search anything here.
631                 }
632
633                 (
634                     GenericArgKind::Lifetime(_)
635                     | GenericArgKind::Type(_)
636                     | GenericArgKind::Const(_),
637                     _,
638                 ) => {
639                     // HIR lowering sometimes doesn't catch this in erroneous
640                     // programs, so we need to use delay_span_bug here. See #82126.
641                     self.infcx.tcx.sess.delay_span_bug(
642                         hir_arg.span(),
643                         &format!("unmatched subst and hir arg: found {:?} vs {:?}", kind, hir_arg),
644                     );
645                 }
646             }
647         }
648
649         None
650     }
651
652     /// Finds a closure upvar that contains `fr` and label it with a
653     /// fully elaborated type, returning something like `'1`. Result
654     /// looks like:
655     ///
656     /// ```text
657     ///  | let x = Some(&22);
658     ///        - fully elaborated type of `x` is `Option<&'1 u32>`
659     /// ```
660     fn give_name_if_anonymous_region_appears_in_upvars(&self, fr: RegionVid) -> Option<RegionName> {
661         let upvar_index = self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
662         let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
663             self.infcx.tcx,
664             &self.upvars,
665             upvar_index,
666         );
667         let region_name = self.synthesize_region_name();
668
669         Some(RegionName {
670             name: region_name,
671             source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
672         })
673     }
674
675     /// Checks for arguments appearing in the (closure) return type. It
676     /// must be a closure since, in a free fn, such an argument would
677     /// have to either also appear in an argument (if using elision)
678     /// or be early bound (named, not in argument).
679     fn give_name_if_anonymous_region_appears_in_output(&self, fr: RegionVid) -> Option<RegionName> {
680         let tcx = self.infcx.tcx;
681         let hir = tcx.hir();
682
683         let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
684         debug!("give_name_if_anonymous_region_appears_in_output: return_ty = {:?}", return_ty);
685         if !tcx.any_free_region_meets(&return_ty, |r| r.to_region_vid() == fr) {
686             return None;
687         }
688
689         let mir_hir_id = self.mir_hir_id();
690
691         let (return_span, mir_description, hir_ty) = match hir.get(mir_hir_id) {
692             hir::Node::Expr(hir::Expr {
693                 kind: hir::ExprKind::Closure(_, return_ty, body_id, span, _),
694                 ..
695             }) => {
696                 let (mut span, mut hir_ty) = match return_ty.output {
697                     hir::FnRetTy::DefaultReturn(_) => {
698                         (tcx.sess.source_map().end_point(*span), None)
699                     }
700                     hir::FnRetTy::Return(hir_ty) => (return_ty.output.span(), Some(hir_ty)),
701                 };
702                 let mir_description = match hir.body(*body_id).generator_kind {
703                     Some(hir::GeneratorKind::Async(gen)) => match gen {
704                         hir::AsyncGeneratorKind::Block => " of async block",
705                         hir::AsyncGeneratorKind::Closure => " of async closure",
706                         hir::AsyncGeneratorKind::Fn => {
707                             let parent_item = hir.get_by_def_id(hir.get_parent_item(mir_hir_id));
708                             let output = &parent_item
709                                 .fn_decl()
710                                 .expect("generator lowered from async fn should be in fn")
711                                 .output;
712                             span = output.span();
713                             if let hir::FnRetTy::Return(ret) = output {
714                                 hir_ty = Some(self.get_future_inner_return_ty(*ret));
715                             }
716                             " of async function"
717                         }
718                     },
719                     Some(hir::GeneratorKind::Gen) => " of generator",
720                     None => " of closure",
721                 };
722                 (span, mir_description, hir_ty)
723             }
724             node => match node.fn_decl() {
725                 Some(fn_decl) => {
726                     let hir_ty = match fn_decl.output {
727                         hir::FnRetTy::DefaultReturn(_) => None,
728                         hir::FnRetTy::Return(ty) => Some(ty),
729                     };
730                     (fn_decl.output.span(), "", hir_ty)
731                 }
732                 None => (self.body.span, "", None),
733             },
734         };
735
736         let highlight = hir_ty
737             .and_then(|hir_ty| self.highlight_if_we_can_match_hir_ty(fr, return_ty, hir_ty))
738             .unwrap_or_else(|| {
739                 // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
740                 // the anonymous region. If it succeeds, the `synthesize_region_name` call below
741                 // will increment the counter, "reserving" the number we just used.
742                 let counter = *self.next_region_name.try_borrow().unwrap();
743                 self.highlight_if_we_cannot_match_hir_ty(fr, return_ty, return_span, counter)
744             });
745
746         Some(RegionName {
747             name: self.synthesize_region_name(),
748             source: RegionNameSource::AnonRegionFromOutput(highlight, mir_description.to_string()),
749         })
750     }
751
752     /// From the [`hir::Ty`] of an async function's lowered return type,
753     /// retrieve the `hir::Ty` representing the type the user originally wrote.
754     ///
755     /// e.g. given the function:
756     ///
757     /// ```
758     /// async fn foo() -> i32 {}
759     /// ```
760     ///
761     /// this function, given the lowered return type of `foo`, an [`OpaqueDef`] that implements `Future<Output=i32>`,
762     /// returns the `i32`.
763     ///
764     /// [`OpaqueDef`]: hir::TyKind::OpaqueDef
765     fn get_future_inner_return_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
766         let hir = self.infcx.tcx.hir();
767
768         if let hir::TyKind::OpaqueDef(id, _) = hir_ty.kind {
769             let opaque_ty = hir.item(id);
770             if let hir::ItemKind::OpaqueTy(hir::OpaqueTy {
771                 bounds:
772                     [
773                         hir::GenericBound::LangItemTrait(
774                             hir::LangItem::Future,
775                             _,
776                             _,
777                             hir::GenericArgs {
778                                 bindings:
779                                     [
780                                         hir::TypeBinding {
781                                             ident: Ident { name: sym::Output, .. },
782                                             kind:
783                                                 hir::TypeBindingKind::Equality {
784                                                     term: hir::Term::Ty(ty),
785                                                 },
786                                             ..
787                                         },
788                                     ],
789                                 ..
790                             },
791                         ),
792                     ],
793                 ..
794             }) = opaque_ty.kind
795             {
796                 ty
797             } else {
798                 span_bug!(
799                     hir_ty.span,
800                     "bounds from lowered return type of async fn did not match expected format: {:?}",
801                     opaque_ty
802                 );
803             }
804         } else {
805             span_bug!(
806                 hir_ty.span,
807                 "lowered return type of async fn is not OpaqueDef: {:?}",
808                 hir_ty
809             );
810         }
811     }
812
813     fn give_name_if_anonymous_region_appears_in_yield_ty(
814         &self,
815         fr: RegionVid,
816     ) -> Option<RegionName> {
817         // Note: generators from `async fn` yield `()`, so we don't have to
818         // worry about them here.
819         let yield_ty = self.regioncx.universal_regions().yield_ty?;
820         debug!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}", yield_ty,);
821
822         let tcx = self.infcx.tcx;
823
824         if !tcx.any_free_region_meets(&yield_ty, |r| r.to_region_vid() == fr) {
825             return None;
826         }
827
828         let mut highlight = RegionHighlightMode::default();
829         highlight.highlighting_region_vid(fr, *self.next_region_name.try_borrow().unwrap());
830         let type_name =
831             self.infcx.extract_inference_diagnostics_data(yield_ty.into(), Some(highlight)).name;
832
833         let yield_span = match tcx.hir().get(self.mir_hir_id()) {
834             hir::Node::Expr(hir::Expr {
835                 kind: hir::ExprKind::Closure(_, _, _, span, _), ..
836             }) => (tcx.sess.source_map().end_point(*span)),
837             _ => self.body.span,
838         };
839
840         debug!(
841             "give_name_if_anonymous_region_appears_in_yield_ty: \
842              type_name = {:?}, yield_span = {:?}",
843             yield_span, type_name,
844         );
845
846         Some(RegionName {
847             name: self.synthesize_region_name(),
848             source: RegionNameSource::AnonRegionFromYieldTy(yield_span, type_name),
849         })
850     }
851 }