]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/diagnostics/region_name.rs
extract RegionNameHighlight
[rust.git] / src / librustc_mir / 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     /// Generate a synthetic region named `'N`, where `N` is the next value of the counter. Then,
151     /// increment the counter.
152     ///
153     /// This is _not_ idempotent. Call `give_region_a_name` when possible.
154     fn synthesize_region_name(&self) -> Symbol {
155         let c = self.next_region_name.replace_with(|counter| *counter + 1);
156         Symbol::intern(&format!("'{:?}", c))
157     }
158
159     /// Maps from an internal MIR region vid to something that we can
160     /// report to the user. In some cases, the region vids will map
161     /// directly to lifetimes that the user has a name for (e.g.,
162     /// `'static`). But frequently they will not, in which case we
163     /// have to find some way to identify the lifetime to the user. To
164     /// that end, this function takes a "diagnostic" so that it can
165     /// create auxiliary notes as needed.
166     ///
167     /// The names are memoized, so this is both cheap to recompute and idempotent.
168     ///
169     /// Example (function arguments):
170     ///
171     /// Suppose we are trying to give a name to the lifetime of the
172     /// reference `x`:
173     ///
174     /// ```
175     /// fn foo(x: &u32) { .. }
176     /// ```
177     ///
178     /// This function would create a label like this:
179     ///
180     /// ```text
181     ///  | fn foo(x: &u32) { .. }
182     ///           ------- fully elaborated type of `x` is `&'1 u32`
183     /// ```
184     ///
185     /// and then return the name `'1` for us to use.
186     crate fn give_region_a_name(&self, fr: RegionVid) -> Option<RegionName> {
187         debug!(
188             "give_region_a_name(fr={:?}, counter={:?})",
189             fr,
190             self.next_region_name.try_borrow().unwrap()
191         );
192
193         assert!(self.regioncx.universal_regions().is_universal_region(fr));
194
195         if let Some(value) = self.region_names.try_borrow_mut().unwrap().get(&fr) {
196             return Some(value.clone());
197         }
198
199         let value = self
200             .give_name_from_error_region(fr)
201             .or_else(|| self.give_name_if_anonymous_region_appears_in_arguments(fr))
202             .or_else(|| self.give_name_if_anonymous_region_appears_in_upvars(fr))
203             .or_else(|| self.give_name_if_anonymous_region_appears_in_output(fr))
204             .or_else(|| self.give_name_if_anonymous_region_appears_in_yield_ty(fr));
205
206         if let Some(ref value) = value {
207             self.region_names.try_borrow_mut().unwrap().insert(fr, value.clone());
208         }
209
210         debug!("give_region_a_name: gave name {:?}", value);
211         value
212     }
213
214     /// Checks for the case where `fr` maps to something that the
215     /// *user* has a name for. In that case, we'll be able to map
216     /// `fr` to a `Region<'tcx>`, and that region will be one of
217     /// named variants.
218     fn give_name_from_error_region(&self, fr: RegionVid) -> Option<RegionName> {
219         let error_region = self.to_error_region(fr)?;
220
221         let tcx = self.infcx.tcx;
222
223         debug!("give_region_a_name: error_region = {:?}", error_region);
224         match error_region {
225             ty::ReEarlyBound(ebr) => {
226                 if ebr.has_name() {
227                     let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP);
228                     Some(RegionName {
229                         name: ebr.name,
230                         source: RegionNameSource::NamedEarlyBoundRegion(span),
231                     })
232                 } else {
233                     None
234                 }
235             }
236
237             ty::ReStatic => {
238                 Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })
239             }
240
241             ty::ReFree(free_region) => match free_region.bound_region {
242                 ty::BoundRegion::BrNamed(region_def_id, name) => {
243                     // Get the span to point to, even if we don't use the name.
244                     let span = tcx.hir().span_if_local(region_def_id).unwrap_or(DUMMY_SP);
245                     debug!(
246                         "bound region named: {:?}, is_named: {:?}",
247                         name,
248                         free_region.bound_region.is_named()
249                     );
250
251                     if free_region.bound_region.is_named() {
252                         // A named region that is actually named.
253                         Some(RegionName { name, source: RegionNameSource::NamedFreeRegion(span) })
254                     } else {
255                         // If we spuriously thought that the region is named, we should let the
256                         // system generate a true name for error messages. Currently this can
257                         // happen if we have an elided name in an async fn for example: the
258                         // compiler will generate a region named `'_`, but reporting such a name is
259                         // not actually useful, so we synthesize a name for it instead.
260                         let name = self.synthesize_region_name();
261                         Some(RegionName {
262                             name,
263                             source: RegionNameSource::AnonRegionFromAsyncFn(span),
264                         })
265                     }
266                 }
267
268                 ty::BoundRegion::BrEnv => {
269                     let mir_hir_id = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id);
270                     let def_ty = self.regioncx.universal_regions().defining_ty;
271
272                     if let DefiningTy::Closure(_, substs) = def_ty {
273                         let args_span = if let hir::ExprKind::Closure(_, _, _, span, _) =
274                             tcx.hir().expect_expr(mir_hir_id).kind
275                         {
276                             span
277                         } else {
278                             bug!("Closure is not defined by a closure expr");
279                         };
280                         let region_name = self.synthesize_region_name();
281
282                         let closure_kind_ty = substs.as_closure().kind_ty();
283                         let note = match closure_kind_ty.to_opt_closure_kind() {
284                             Some(ty::ClosureKind::Fn) => {
285                                 "closure implements `Fn`, so references to captured variables \
286                                  can't escape the closure"
287                             }
288                             Some(ty::ClosureKind::FnMut) => {
289                                 "closure implements `FnMut`, so references to captured variables \
290                                  can't escape the closure"
291                             }
292                             Some(ty::ClosureKind::FnOnce) => {
293                                 bug!("BrEnv in a `FnOnce` closure");
294                             }
295                             None => bug!("Closure kind not inferred in borrow check"),
296                         };
297
298                         Some(RegionName {
299                             name: region_name,
300                             source: RegionNameSource::SynthesizedFreeEnvRegion(
301                                 args_span,
302                                 note.to_string(),
303                             ),
304                         })
305                     } else {
306                         // Can't have BrEnv in functions, constants or generators.
307                         bug!("BrEnv outside of closure.");
308                     }
309                 }
310
311                 ty::BoundRegion::BrAnon(_) => None,
312             },
313
314             ty::ReLateBound(..)
315             | ty::ReVar(..)
316             | ty::RePlaceholder(..)
317             | ty::ReEmpty(_)
318             | ty::ReErased => None,
319         }
320     }
321
322     /// Finds an argument that contains `fr` and label it with a fully
323     /// elaborated type, returning something like `'1`. Result looks
324     /// like:
325     ///
326     /// ```text
327     ///  | fn foo(x: &u32) { .. }
328     ///           ------- fully elaborated type of `x` is `&'1 u32`
329     /// ```
330     fn give_name_if_anonymous_region_appears_in_arguments(
331         &self,
332         fr: RegionVid,
333     ) -> Option<RegionName> {
334         let implicit_inputs = self.regioncx.universal_regions().defining_ty.implicit_inputs();
335         let argument_index = self.regioncx.get_argument_index_for_region(self.infcx.tcx, fr)?;
336
337         let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys
338             [implicit_inputs + argument_index];
339         if let Some(region_name) =
340             self.give_name_if_we_can_match_hir_ty_from_argument(fr, arg_ty, argument_index)
341         {
342             return Some(region_name);
343         }
344
345         self.give_name_if_we_cannot_match_hir_ty(fr, arg_ty)
346     }
347
348     fn give_name_if_we_can_match_hir_ty_from_argument(
349         &self,
350         needle_fr: RegionVid,
351         argument_ty: Ty<'tcx>,
352         argument_index: usize,
353     ) -> Option<RegionName> {
354         let mir_hir_id = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id);
355         let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(mir_hir_id)?;
356         let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(argument_index)?;
357         match argument_hir_ty.kind {
358             // This indicates a variable with no type annotation, like
359             // `|x|`... in that case, we can't highlight the type but
360             // must highlight the variable.
361             // NOTE(eddyb) this is handled in/by the sole caller
362             // (`give_name_if_anonymous_region_appears_in_arguments`).
363             hir::TyKind::Infer => None,
364
365             _ => self.give_name_if_we_can_match_hir_ty(needle_fr, argument_ty, argument_hir_ty),
366         }
367     }
368
369     /// Attempts to highlight the specific part of a type in an argument
370     /// that has no type annotation.
371     /// For example, we might produce an annotation like this:
372     ///
373     /// ```text
374     ///  |     foo(|a, b| b)
375     ///  |          -  -
376     ///  |          |  |
377     ///  |          |  has type `&'1 u32`
378     ///  |          has type `&'2 u32`
379     /// ```
380     fn give_name_if_we_cannot_match_hir_ty(
381         &self,
382         needle_fr: RegionVid,
383         argument_ty: Ty<'tcx>,
384     ) -> Option<RegionName> {
385         let counter = *self.next_region_name.try_borrow().unwrap();
386         let mut highlight = RegionHighlightMode::default();
387         highlight.highlighting_region_vid(needle_fr, counter);
388         let type_name = self.infcx.extract_type_name(&argument_ty, Some(highlight)).0;
389
390         debug!(
391             "give_name_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
392             type_name, needle_fr
393         );
394         let assigned_region_name = if type_name.find(&format!("'{}", counter)).is_some() {
395             // Only add a label if we can confirm that a region was labelled.
396             let argument_index =
397                 self.regioncx.get_argument_index_for_region(self.infcx.tcx, needle_fr)?;
398             let (_, span) = self.regioncx.get_argument_name_and_span_for_region(
399                 &self.body,
400                 &self.local_names,
401                 argument_index,
402             );
403
404             Some(RegionName {
405                 // This counter value will already have been used, so this function will increment
406                 // it so the next value will be used next and return the region name that would
407                 // have been used.
408                 name: self.synthesize_region_name(),
409                 source: RegionNameSource::AnonRegionFromArgument(
410                     RegionNameHighlight::CannotMatchHirTy(span, type_name),
411                 ),
412             })
413         } else {
414             None
415         };
416
417         assigned_region_name
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 `argument_ty`, which is
430     /// a `Ty<'tcx>` (the internal form of the type) with
431     /// `argument_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 give_name_if_we_can_match_hir_ty(
442         &self,
443         needle_fr: RegionVid,
444         argument_ty: Ty<'tcx>,
445         argument_hir_ty: &hir::Ty<'_>,
446     ) -> Option<RegionName> {
447         let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty<'_>)> =
448             &mut vec![(argument_ty, argument_hir_ty)];
449
450         while let Some((ty, hir_ty)) = search_stack.pop() {
451             match (&ty.kind, &hir_ty.kind) {
452                 // Check if the `argument_ty` is `&'X ..` where `'X`
453                 // is the region we are looking for -- if so, and we have a `&T`
454                 // on the RHS, then we want to highlight the `&` like so:
455                 //
456                 //     &
457                 //     - let's call the lifetime of this reference `'1`
458                 (
459                     ty::Ref(region, referent_ty, _),
460                     hir::TyKind::Rptr(_lifetime, referent_hir_ty),
461                 ) => {
462                     if region.to_region_vid() == needle_fr {
463                         let region_name = self.synthesize_region_name();
464
465                         // Just grab the first character, the `&`.
466                         let source_map = self.infcx.tcx.sess.source_map();
467                         let ampersand_span = source_map.start_point(hir_ty.span);
468
469                         return Some(RegionName {
470                             name: region_name,
471                             source: RegionNameSource::AnonRegionFromArgument(
472                                 RegionNameHighlight::MatchedHirTy(ampersand_span),
473                             ),
474                         });
475                     }
476
477                     // Otherwise, let's descend into the referent types.
478                     search_stack.push((referent_ty, &referent_hir_ty.ty));
479                 }
480
481                 // Match up something like `Foo<'1>`
482                 (
483                     ty::Adt(_adt_def, substs),
484                     hir::TyKind::Path(hir::QPath::Resolved(None, path)),
485                 ) => {
486                     match path.res {
487                         // Type parameters of the type alias have no reason to
488                         // be the same as those of the ADT.
489                         // FIXME: We should be able to do something similar to
490                         // match_adt_and_segment in this case.
491                         Res::Def(DefKind::TyAlias, _) => (),
492                         _ => {
493                             if let Some(last_segment) = path.segments.last() {
494                                 if let Some(name) = self.match_adt_and_segment(
495                                     substs,
496                                     needle_fr,
497                                     last_segment,
498                                     search_stack,
499                                 ) {
500                                     return Some(name);
501                                 }
502                             }
503                         }
504                     }
505                 }
506
507                 // The following cases don't have lifetimes, so we
508                 // just worry about trying to match up the rustc type
509                 // with the HIR types:
510                 (ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
511                     search_stack.extend(elem_tys.iter().map(|k| k.expect_ty()).zip(*elem_hir_tys));
512                 }
513
514                 (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
515                 | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
516                     search_stack.push((elem_ty, elem_hir_ty));
517                 }
518
519                 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
520                     search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
521                 }
522
523                 _ => {
524                     // FIXME there are other cases that we could trace
525                 }
526             }
527         }
528
529         None
530     }
531
532     /// We've found an enum/struct/union type with the substitutions
533     /// `substs` and -- in the HIR -- a path type with the final
534     /// segment `last_segment`. Try to find a `'_` to highlight in
535     /// the generic args (or, if not, to produce new zipped pairs of
536     /// types+hir to search through).
537     fn match_adt_and_segment<'hir>(
538         &self,
539         substs: SubstsRef<'tcx>,
540         needle_fr: RegionVid,
541         last_segment: &'hir hir::PathSegment<'hir>,
542         search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
543     ) -> Option<RegionName> {
544         // Did the user give explicit arguments? (e.g., `Foo<..>`)
545         let args = last_segment.args.as_ref()?;
546         let lifetime =
547             self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
548         match lifetime.name {
549             hir::LifetimeName::Param(_)
550             | hir::LifetimeName::Error
551             | hir::LifetimeName::Static
552             | hir::LifetimeName::Underscore => {
553                 let region_name = self.synthesize_region_name();
554                 let lifetime_span = lifetime.span;
555                 Some(RegionName {
556                     name: region_name,
557                     source: RegionNameSource::AnonRegionFromArgument(
558                         RegionNameHighlight::MatchedAdtAndSegment(lifetime_span),
559                     ),
560                 })
561             }
562
563             hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Implicit => {
564                 // In this case, the user left off the lifetime; so
565                 // they wrote something like:
566                 //
567                 // ```
568                 // x: Foo<T>
569                 // ```
570                 //
571                 // where the fully elaborated form is `Foo<'_, '1,
572                 // T>`. We don't consider this a match; instead we let
573                 // the "fully elaborated" type fallback above handle
574                 // it.
575                 None
576             }
577         }
578     }
579
580     /// We've found an enum/struct/union type with the substitutions
581     /// `substs` and -- in the HIR -- a path with the generic
582     /// arguments `args`. If `needle_fr` appears in the args, return
583     /// the `hir::Lifetime` that corresponds to it. If not, push onto
584     /// `search_stack` the types+hir to search through.
585     fn try_match_adt_and_generic_args<'hir>(
586         &self,
587         substs: SubstsRef<'tcx>,
588         needle_fr: RegionVid,
589         args: &'hir hir::GenericArgs<'hir>,
590         search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
591     ) -> Option<&'hir hir::Lifetime> {
592         for (kind, hir_arg) in substs.iter().zip(args.args) {
593             match (kind.unpack(), hir_arg) {
594                 (GenericArgKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
595                     if r.to_region_vid() == needle_fr {
596                         return Some(lt);
597                     }
598                 }
599
600                 (GenericArgKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
601                     search_stack.push((ty, hir_ty));
602                 }
603
604                 (GenericArgKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
605                     // Lifetimes cannot be found in consts, so we don't need
606                     // to search anything here.
607                 }
608
609                 (
610                     GenericArgKind::Lifetime(_)
611                     | GenericArgKind::Type(_)
612                     | GenericArgKind::Const(_),
613                     _,
614                 ) => {
615                     // I *think* that HIR lowering should ensure this
616                     // doesn't happen, even in erroneous
617                     // programs. Else we should use delay-span-bug.
618                     span_bug!(
619                         hir_arg.span(),
620                         "unmatched subst and hir arg: found {:?} vs {:?}",
621                         kind,
622                         hir_arg,
623                     );
624                 }
625             }
626         }
627
628         None
629     }
630
631     /// Finds a closure upvar that contains `fr` and label it with a
632     /// fully elaborated type, returning something like `'1`. Result
633     /// looks like:
634     ///
635     /// ```text
636     ///  | let x = Some(&22);
637     ///        - fully elaborated type of `x` is `Option<&'1 u32>`
638     /// ```
639     fn give_name_if_anonymous_region_appears_in_upvars(&self, fr: RegionVid) -> Option<RegionName> {
640         let upvar_index = self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
641         let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
642             self.infcx.tcx,
643             &self.upvars,
644             upvar_index,
645         );
646         let region_name = self.synthesize_region_name();
647
648         Some(RegionName {
649             name: region_name,
650             source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
651         })
652     }
653
654     /// Checks for arguments appearing in the (closure) return type. It
655     /// must be a closure since, in a free fn, such an argument would
656     /// have to either also appear in an argument (if using elision)
657     /// or be early bound (named, not in argument).
658     fn give_name_if_anonymous_region_appears_in_output(&self, fr: RegionVid) -> Option<RegionName> {
659         let tcx = self.infcx.tcx;
660
661         let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
662         debug!("give_name_if_anonymous_region_appears_in_output: return_ty = {:?}", return_ty);
663         if !tcx.any_free_region_meets(&return_ty, |r| r.to_region_vid() == fr) {
664             return None;
665         }
666
667         let mut highlight = RegionHighlightMode::default();
668         highlight.highlighting_region_vid(fr, *self.next_region_name.try_borrow().unwrap());
669         let type_name = self.infcx.extract_type_name(&return_ty, Some(highlight)).0;
670
671         let mir_hir_id = tcx.hir().as_local_hir_id(self.mir_def_id);
672
673         let (return_span, mir_description) = match tcx.hir().get(mir_hir_id) {
674             hir::Node::Expr(hir::Expr {
675                 kind: hir::ExprKind::Closure(_, return_ty, _, span, gen_move),
676                 ..
677             }) => (
678                 match return_ty.output {
679                     hir::FnRetTy::DefaultReturn(_) => tcx.sess.source_map().end_point(*span),
680                     hir::FnRetTy::Return(_) => return_ty.output.span(),
681                 },
682                 if gen_move.is_some() { " of generator" } else { " of closure" },
683             ),
684             hir::Node::ImplItem(hir::ImplItem {
685                 kind: hir::ImplItemKind::Fn(method_sig, _),
686                 ..
687             }) => (method_sig.decl.output.span(), ""),
688             _ => (self.body.span, ""),
689         };
690
691         Some(RegionName {
692             // This counter value will already have been used, so this function will increment it
693             // so the next value will be used next and return the region name that would have been
694             // used.
695             name: self.synthesize_region_name(),
696             source: RegionNameSource::AnonRegionFromOutput(
697                 return_span,
698                 mir_description.to_string(),
699                 type_name,
700             ),
701         })
702     }
703
704     fn give_name_if_anonymous_region_appears_in_yield_ty(
705         &self,
706         fr: RegionVid,
707     ) -> Option<RegionName> {
708         // Note: generators from `async fn` yield `()`, so we don't have to
709         // worry about them here.
710         let yield_ty = self.regioncx.universal_regions().yield_ty?;
711         debug!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}", yield_ty,);
712
713         let tcx = self.infcx.tcx;
714
715         if !tcx.any_free_region_meets(&yield_ty, |r| r.to_region_vid() == fr) {
716             return None;
717         }
718
719         let mut highlight = RegionHighlightMode::default();
720         highlight.highlighting_region_vid(fr, *self.next_region_name.try_borrow().unwrap());
721         let type_name = self.infcx.extract_type_name(&yield_ty, Some(highlight)).0;
722
723         let mir_hir_id = tcx.hir().as_local_hir_id(self.mir_def_id);
724
725         let yield_span = match tcx.hir().get(mir_hir_id) {
726             hir::Node::Expr(hir::Expr {
727                 kind: hir::ExprKind::Closure(_, _, _, span, _), ..
728             }) => (tcx.sess.source_map().end_point(*span)),
729             _ => self.body.span,
730         };
731
732         debug!(
733             "give_name_if_anonymous_region_appears_in_yield_ty: \
734              type_name = {:?}, yield_span = {:?}",
735             yield_span, type_name,
736         );
737
738         Some(RegionName {
739             name: self.synthesize_region_name(),
740             source: RegionNameSource::AnonRegionFromYieldTy(yield_span, type_name),
741         })
742     }
743 }