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