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