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