1 use std::fmt::{self, Display};
4 use rustc_errors::Diagnostic;
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, DefIdTree, RegionVid, Ty};
10 use rustc_span::symbol::{kw, sym, Ident, Symbol};
11 use rustc_span::{Span, DUMMY_SP};
13 use crate::{nll::ToRegionVid, universal_regions::DefiningTy, MirBorrowckCtxt};
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 pub(crate) struct RegionName {
19 /// The name of the region (interned).
20 pub(crate) name: Symbol,
21 /// Where the region comes from.
22 pub(crate) source: RegionNameSource,
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 pub(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.
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 /// An anonymous region from an impl self type or trait
49 AnonRegionFromImplSignature(Span, &'static str),
52 /// Describes what to highlight to explain to the user that we're giving an anonymous region a
53 /// synthesized name, and how to highlight it.
54 #[derive(Debug, Clone)]
55 pub(crate) enum RegionNameHighlight {
56 /// The anonymous region corresponds to a reference that was found by traversing the type in the HIR.
58 /// The anonymous region corresponds to a `'_` in the generics list of a struct/enum/union.
59 MatchedAdtAndSegment(Span),
60 /// The anonymous region corresponds to a region where the type annotation is completely missing
61 /// from the code, e.g. in a closure arguments `|x| { ... }`, where `x` is a reference.
62 CannotMatchHirTy(Span, String),
63 /// The anonymous region corresponds to a region where the type annotation is completely missing
64 /// from the code, and *even if* we print out the full name of the type, the region name won't
65 /// be included. This currently occurs for opaque types like `impl Future`.
66 Occluded(Span, String),
70 pub(crate) fn was_named(&self) -> bool {
72 RegionNameSource::NamedEarlyBoundRegion(..)
73 | RegionNameSource::NamedFreeRegion(..)
74 | RegionNameSource::Static => true,
75 RegionNameSource::SynthesizedFreeEnvRegion(..)
76 | RegionNameSource::AnonRegionFromArgument(..)
77 | RegionNameSource::AnonRegionFromUpvar(..)
78 | RegionNameSource::AnonRegionFromOutput(..)
79 | RegionNameSource::AnonRegionFromYieldTy(..)
80 | RegionNameSource::AnonRegionFromAsyncFn(..)
81 | RegionNameSource::AnonRegionFromImplSignature(..) => false,
85 pub(crate) fn span(&self) -> Option<Span> {
87 RegionNameSource::Static => None,
88 RegionNameSource::NamedEarlyBoundRegion(span)
89 | RegionNameSource::NamedFreeRegion(span)
90 | RegionNameSource::SynthesizedFreeEnvRegion(span, _)
91 | RegionNameSource::AnonRegionFromUpvar(span, _)
92 | RegionNameSource::AnonRegionFromYieldTy(span, _)
93 | RegionNameSource::AnonRegionFromAsyncFn(span)
94 | RegionNameSource::AnonRegionFromImplSignature(span, _) => Some(span),
95 RegionNameSource::AnonRegionFromArgument(ref highlight)
96 | RegionNameSource::AnonRegionFromOutput(ref highlight, _) => match *highlight {
97 RegionNameHighlight::MatchedHirTy(span)
98 | RegionNameHighlight::MatchedAdtAndSegment(span)
99 | RegionNameHighlight::CannotMatchHirTy(span, _)
100 | RegionNameHighlight::Occluded(span, _) => Some(span),
105 pub(crate) fn highlight_region_name(&self, diag: &mut Diagnostic) {
107 RegionNameSource::NamedFreeRegion(span)
108 | RegionNameSource::NamedEarlyBoundRegion(span) => {
109 diag.span_label(*span, format!("lifetime `{self}` defined here"));
111 RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
112 diag.span_label(*span, format!("lifetime `{self}` represents this closure's body"));
115 RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::CannotMatchHirTy(
119 diag.span_label(*span, format!("has type `{type_name}`"));
121 RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::MatchedHirTy(span))
122 | RegionNameSource::AnonRegionFromOutput(RegionNameHighlight::MatchedHirTy(span), _)
123 | RegionNameSource::AnonRegionFromAsyncFn(span) => {
126 format!("let's call the lifetime of this reference `{self}`"),
129 RegionNameSource::AnonRegionFromArgument(
130 RegionNameHighlight::MatchedAdtAndSegment(span),
132 | RegionNameSource::AnonRegionFromOutput(
133 RegionNameHighlight::MatchedAdtAndSegment(span),
136 diag.span_label(*span, format!("let's call this `{self}`"));
138 RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::Occluded(
144 format!("lifetime `{self}` appears in the type {type_name}"),
147 RegionNameSource::AnonRegionFromOutput(
148 RegionNameHighlight::Occluded(span, type_name),
154 "return type{mir_description} `{type_name}` contains a lifetime `{self}`"
158 RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
161 format!("lifetime `{self}` appears in the type of `{upvar_name}`"),
164 RegionNameSource::AnonRegionFromOutput(
165 RegionNameHighlight::CannotMatchHirTy(span, type_name),
168 diag.span_label(*span, format!("return type{mir_description} is {type_name}"));
170 RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
171 diag.span_label(*span, format!("yield type is {type_name}"));
173 RegionNameSource::AnonRegionFromImplSignature(span, location) => {
176 format!("lifetime `{self}` appears in the `impl`'s {location}"),
179 RegionNameSource::Static => {}
184 impl Display for RegionName {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 write!(f, "{}", self.name)
190 impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
191 pub(crate) fn mir_def_id(&self) -> hir::def_id::LocalDefId {
192 self.body.source.def_id().as_local().unwrap()
195 pub(crate) fn mir_hir_id(&self) -> hir::HirId {
196 self.infcx.tcx.hir().local_def_id_to_hir_id(self.mir_def_id())
199 /// Generate a synthetic region named `'N`, where `N` is the next value of the counter. Then,
200 /// increment the counter.
202 /// This is _not_ idempotent. Call `give_region_a_name` when possible.
203 fn synthesize_region_name(&self) -> Symbol {
204 let c = self.next_region_name.replace_with(|counter| *counter + 1);
205 Symbol::intern(&format!("'{:?}", c))
208 /// Maps from an internal MIR region vid to something that we can
209 /// report to the user. In some cases, the region vids will map
210 /// directly to lifetimes that the user has a name for (e.g.,
211 /// `'static`). But frequently they will not, in which case we
212 /// have to find some way to identify the lifetime to the user. To
213 /// that end, this function takes a "diagnostic" so that it can
214 /// create auxiliary notes as needed.
216 /// The names are memoized, so this is both cheap to recompute and idempotent.
218 /// Example (function arguments):
220 /// Suppose we are trying to give a name to the lifetime of the
223 /// ```ignore (pseudo-rust)
224 /// fn foo(x: &u32) { .. }
227 /// This function would create a label like this:
230 /// | fn foo(x: &u32) { .. }
231 /// ------- fully elaborated type of `x` is `&'1 u32`
234 /// and then return the name `'1` for us to use.
235 pub(crate) fn give_region_a_name(&self, fr: RegionVid) -> Option<RegionName> {
237 "give_region_a_name(fr={:?}, counter={:?})",
239 self.next_region_name.try_borrow().unwrap()
242 assert!(self.regioncx.universal_regions().is_universal_region(fr));
244 if let Some(value) = self.region_names.try_borrow_mut().unwrap().get(&fr) {
245 return Some(value.clone());
249 .give_name_from_error_region(fr)
250 .or_else(|| self.give_name_if_anonymous_region_appears_in_arguments(fr))
251 .or_else(|| self.give_name_if_anonymous_region_appears_in_upvars(fr))
252 .or_else(|| self.give_name_if_anonymous_region_appears_in_output(fr))
253 .or_else(|| self.give_name_if_anonymous_region_appears_in_yield_ty(fr))
254 .or_else(|| self.give_name_if_anonymous_region_appears_in_impl_signature(fr));
256 if let Some(ref value) = value {
257 self.region_names.try_borrow_mut().unwrap().insert(fr, value.clone());
260 debug!("give_region_a_name: gave name {:?}", value);
264 /// Checks for the case where `fr` maps to something that the
265 /// *user* has a name for. In that case, we'll be able to map
266 /// `fr` to a `Region<'tcx>`, and that region will be one of
268 #[tracing::instrument(level = "trace", skip(self))]
269 fn give_name_from_error_region(&self, fr: RegionVid) -> Option<RegionName> {
270 let error_region = self.to_error_region(fr)?;
272 let tcx = self.infcx.tcx;
274 debug!("give_region_a_name: error_region = {:?}", error_region);
275 match *error_region {
276 ty::ReEarlyBound(ebr) => {
278 let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP);
281 source: RegionNameSource::NamedEarlyBoundRegion(span),
289 Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })
292 ty::ReFree(free_region) => match free_region.bound_region {
293 ty::BoundRegionKind::BrNamed(region_def_id, name) => {
294 // Get the span to point to, even if we don't use the name.
295 let span = tcx.hir().span_if_local(region_def_id).unwrap_or(DUMMY_SP);
297 "bound region named: {:?}, is_named: {:?}",
299 free_region.bound_region.is_named()
302 if free_region.bound_region.is_named() {
303 // A named region that is actually named.
304 Some(RegionName { name, source: RegionNameSource::NamedFreeRegion(span) })
305 } else if let hir::IsAsync::Async = tcx.asyncness(self.mir_hir_id().owner) {
306 // If we spuriously thought that the region is named, we should let the
307 // system generate a true name for error messages. Currently this can
308 // happen if we have an elided name in an async fn for example: the
309 // compiler will generate a region named `'_`, but reporting such a name is
310 // not actually useful, so we synthesize a name for it instead.
311 let name = self.synthesize_region_name();
314 source: RegionNameSource::AnonRegionFromAsyncFn(span),
321 ty::BoundRegionKind::BrEnv => {
322 let def_ty = self.regioncx.universal_regions().defining_ty;
324 let DefiningTy::Closure(_, substs) = def_ty else {
325 // Can't have BrEnv in functions, constants or generators.
326 bug!("BrEnv outside of closure.");
328 let hir::ExprKind::Closure { fn_decl_span, .. }
329 = tcx.hir().expect_expr(self.mir_hir_id()).kind
331 bug!("Closure is not defined by a closure expr");
333 let region_name = self.synthesize_region_name();
335 let closure_kind_ty = substs.as_closure().kind_ty();
336 let note = match closure_kind_ty.to_opt_closure_kind() {
337 Some(ty::ClosureKind::Fn) => {
338 "closure implements `Fn`, so references to captured variables \
339 can't escape the closure"
341 Some(ty::ClosureKind::FnMut) => {
342 "closure implements `FnMut`, so references to captured variables \
343 can't escape the closure"
345 Some(ty::ClosureKind::FnOnce) => {
346 bug!("BrEnv in a `FnOnce` closure");
348 None => bug!("Closure kind not inferred in borrow check"),
353 source: RegionNameSource::SynthesizedFreeEnvRegion(
360 ty::BoundRegionKind::BrAnon(_) => None,
365 | ty::RePlaceholder(..)
367 | ty::ReErased => None,
371 /// Finds an argument that contains `fr` and label it with a fully
372 /// elaborated type, returning something like `'1`. Result looks
376 /// | fn foo(x: &u32) { .. }
377 /// ------- fully elaborated type of `x` is `&'1 u32`
379 #[tracing::instrument(level = "trace", skip(self))]
380 fn give_name_if_anonymous_region_appears_in_arguments(
383 ) -> Option<RegionName> {
384 let implicit_inputs = self.regioncx.universal_regions().defining_ty.implicit_inputs();
385 let argument_index = self.regioncx.get_argument_index_for_region(self.infcx.tcx, fr)?;
387 let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys
388 [implicit_inputs + argument_index];
389 let (_, span) = self.regioncx.get_argument_name_and_span_for_region(
396 .get_argument_hir_ty_for_highlighting(argument_index)
397 .and_then(|arg_hir_ty| self.highlight_if_we_can_match_hir_ty(fr, arg_ty, arg_hir_ty))
399 // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
400 // the anonymous region. If it succeeds, the `synthesize_region_name` call below
401 // will increment the counter, "reserving" the number we just used.
402 let counter = *self.next_region_name.try_borrow().unwrap();
403 self.highlight_if_we_cannot_match_hir_ty(fr, arg_ty, span, counter)
407 name: self.synthesize_region_name(),
408 source: RegionNameSource::AnonRegionFromArgument(highlight),
412 fn get_argument_hir_ty_for_highlighting(
414 argument_index: usize,
415 ) -> Option<&hir::Ty<'tcx>> {
416 let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(self.mir_hir_id())?;
417 let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(argument_index)?;
418 match argument_hir_ty.kind {
419 // This indicates a variable with no type annotation, like
420 // `|x|`... in that case, we can't highlight the type but
421 // must highlight the variable.
422 // NOTE(eddyb) this is handled in/by the sole caller
423 // (`give_name_if_anonymous_region_appears_in_arguments`).
424 hir::TyKind::Infer => None,
426 _ => Some(argument_hir_ty),
430 /// Attempts to highlight the specific part of a type in an argument
431 /// that has no type annotation.
432 /// For example, we might produce an annotation like this:
438 /// | | has type `&'1 u32`
439 /// | has type `&'2 u32`
441 fn highlight_if_we_cannot_match_hir_ty(
443 needle_fr: RegionVid,
447 ) -> RegionNameHighlight {
448 let mut highlight = RegionHighlightMode::new(self.infcx.tcx);
449 highlight.highlighting_region_vid(needle_fr, counter);
451 self.infcx.extract_inference_diagnostics_data(ty.into(), Some(highlight)).name;
454 "highlight_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
457 if type_name.contains(&format!("'{counter}")) {
458 // Only add a label if we can confirm that a region was labelled.
459 RegionNameHighlight::CannotMatchHirTy(span, type_name)
461 RegionNameHighlight::Occluded(span, type_name)
465 /// Attempts to highlight the specific part of a type annotation
466 /// that contains the anonymous reference we want to give a name
467 /// to. For example, we might produce an annotation like this:
470 /// | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
471 /// | - let's call the lifetime of this reference `'1`
474 /// the way this works is that we match up `ty`, which is
475 /// a `Ty<'tcx>` (the internal form of the type) with
476 /// `hir_ty`, a `hir::Ty` (the syntax of the type
477 /// annotation). We are descending through the types stepwise,
478 /// looking in to find the region `needle_fr` in the internal
479 /// type. Once we find that, we can use the span of the `hir::Ty`
480 /// to add the highlight.
482 /// This is a somewhat imperfect process, so along the way we also
483 /// keep track of the **closest** type we've found. If we fail to
484 /// find the exact `&` or `'_` to highlight, then we may fall back
485 /// to highlighting that closest type instead.
486 fn highlight_if_we_can_match_hir_ty(
488 needle_fr: RegionVid,
490 hir_ty: &hir::Ty<'_>,
491 ) -> Option<RegionNameHighlight> {
492 let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty<'_>)> = &mut vec![(ty, hir_ty)];
494 while let Some((ty, hir_ty)) = search_stack.pop() {
495 match (ty.kind(), &hir_ty.kind) {
496 // Check if the `ty` is `&'X ..` where `'X`
497 // is the region we are looking for -- if so, and we have a `&T`
498 // on the RHS, then we want to highlight the `&` like so:
501 // - let's call the lifetime of this reference `'1`
503 ty::Ref(region, referent_ty, _),
504 hir::TyKind::Rptr(_lifetime, referent_hir_ty),
506 if region.to_region_vid() == needle_fr {
507 // Just grab the first character, the `&`.
508 let source_map = self.infcx.tcx.sess.source_map();
509 let ampersand_span = source_map.start_point(hir_ty.span);
511 return Some(RegionNameHighlight::MatchedHirTy(ampersand_span));
514 // Otherwise, let's descend into the referent types.
515 search_stack.push((*referent_ty, &referent_hir_ty.ty));
518 // Match up something like `Foo<'1>`
520 ty::Adt(_adt_def, substs),
521 hir::TyKind::Path(hir::QPath::Resolved(None, path)),
524 // Type parameters of the type alias have no reason to
525 // be the same as those of the ADT.
526 // FIXME: We should be able to do something similar to
527 // match_adt_and_segment in this case.
528 Res::Def(DefKind::TyAlias, _) => (),
530 if let Some(last_segment) = path.segments.last() {
531 if let Some(highlight) = self.match_adt_and_segment(
537 return Some(highlight);
544 // The following cases don't have lifetimes, so we
545 // just worry about trying to match up the rustc type
546 // with the HIR types:
547 (&ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
548 search_stack.extend(iter::zip(elem_tys, *elem_hir_tys));
551 (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
552 | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
553 search_stack.push((*elem_ty, elem_hir_ty));
556 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
557 search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
561 // FIXME there are other cases that we could trace
569 /// We've found an enum/struct/union type with the substitutions
570 /// `substs` and -- in the HIR -- a path type with the final
571 /// segment `last_segment`. Try to find a `'_` to highlight in
572 /// the generic args (or, if not, to produce new zipped pairs of
573 /// types+hir to search through).
574 fn match_adt_and_segment<'hir>(
576 substs: SubstsRef<'tcx>,
577 needle_fr: RegionVid,
578 last_segment: &'hir hir::PathSegment<'hir>,
579 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
580 ) -> Option<RegionNameHighlight> {
581 // Did the user give explicit arguments? (e.g., `Foo<..>`)
582 let args = last_segment.args.as_ref()?;
584 self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
585 match lifetime.name {
586 hir::LifetimeName::Param(_, hir::ParamName::Plain(_) | hir::ParamName::Error)
587 | hir::LifetimeName::Error
588 | hir::LifetimeName::Static => {
589 let lifetime_span = lifetime.span;
590 Some(RegionNameHighlight::MatchedAdtAndSegment(lifetime_span))
593 hir::LifetimeName::Param(_, hir::ParamName::Fresh)
594 | hir::LifetimeName::ImplicitObjectLifetimeDefault
595 | hir::LifetimeName::Implicit
596 | hir::LifetimeName::Underscore => {
597 // In this case, the user left off the lifetime; so
598 // they wrote something like:
604 // where the fully elaborated form is `Foo<'_, '1,
605 // T>`. We don't consider this a match; instead we let
606 // the "fully elaborated" type fallback above handle
613 /// We've found an enum/struct/union type with the substitutions
614 /// `substs` and -- in the HIR -- a path with the generic
615 /// arguments `args`. If `needle_fr` appears in the args, return
616 /// the `hir::Lifetime` that corresponds to it. If not, push onto
617 /// `search_stack` the types+hir to search through.
618 fn try_match_adt_and_generic_args<'hir>(
620 substs: SubstsRef<'tcx>,
621 needle_fr: RegionVid,
622 args: &'hir hir::GenericArgs<'hir>,
623 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
624 ) -> Option<&'hir hir::Lifetime> {
625 for (kind, hir_arg) in iter::zip(substs, args.args) {
626 match (kind.unpack(), hir_arg) {
627 (GenericArgKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
628 if r.to_region_vid() == needle_fr {
633 (GenericArgKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
634 search_stack.push((ty, hir_ty));
637 (GenericArgKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
638 // Lifetimes cannot be found in consts, so we don't need
639 // to search anything here.
643 GenericArgKind::Lifetime(_)
644 | GenericArgKind::Type(_)
645 | GenericArgKind::Const(_),
648 // HIR lowering sometimes doesn't catch this in erroneous
649 // programs, so we need to use delay_span_bug here. See #82126.
650 self.infcx.tcx.sess.delay_span_bug(
652 &format!("unmatched subst and hir arg: found {:?} vs {:?}", kind, hir_arg),
661 /// Finds a closure upvar that contains `fr` and label it with a
662 /// fully elaborated type, returning something like `'1`. Result
666 /// | let x = Some(&22);
667 /// - fully elaborated type of `x` is `Option<&'1 u32>`
669 #[tracing::instrument(level = "trace", skip(self))]
670 fn give_name_if_anonymous_region_appears_in_upvars(&self, fr: RegionVid) -> Option<RegionName> {
671 let upvar_index = self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
672 let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
677 let region_name = self.synthesize_region_name();
681 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
685 /// Checks for arguments appearing in the (closure) return type. It
686 /// must be a closure since, in a free fn, such an argument would
687 /// have to either also appear in an argument (if using elision)
688 /// or be early bound (named, not in argument).
689 #[tracing::instrument(level = "trace", skip(self))]
690 fn give_name_if_anonymous_region_appears_in_output(&self, fr: RegionVid) -> Option<RegionName> {
691 let tcx = self.infcx.tcx;
694 let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
695 debug!("give_name_if_anonymous_region_appears_in_output: return_ty = {:?}", return_ty);
696 if !tcx.any_free_region_meets(&return_ty, |r| r.to_region_vid() == fr) {
700 let mir_hir_id = self.mir_hir_id();
702 let (return_span, mir_description, hir_ty) = match hir.get(mir_hir_id) {
703 hir::Node::Expr(hir::Expr {
704 kind: hir::ExprKind::Closure { fn_decl, body, fn_decl_span, .. },
707 let (mut span, mut hir_ty) = match fn_decl.output {
708 hir::FnRetTy::DefaultReturn(_) => {
709 (tcx.sess.source_map().end_point(*fn_decl_span), None)
711 hir::FnRetTy::Return(hir_ty) => (fn_decl.output.span(), Some(hir_ty)),
713 let mir_description = match hir.body(*body).generator_kind {
714 Some(hir::GeneratorKind::Async(gen)) => match gen {
715 hir::AsyncGeneratorKind::Block => " of async block",
716 hir::AsyncGeneratorKind::Closure => " of async closure",
717 hir::AsyncGeneratorKind::Fn => {
718 let parent_item = hir.get_by_def_id(hir.get_parent_item(mir_hir_id));
719 let output = &parent_item
721 .expect("generator lowered from async fn should be in fn")
723 span = output.span();
724 if let hir::FnRetTy::Return(ret) = output {
725 hir_ty = Some(self.get_future_inner_return_ty(*ret));
730 Some(hir::GeneratorKind::Gen) => " of generator",
731 None => " of closure",
733 (span, mir_description, hir_ty)
735 node => match node.fn_decl() {
737 let hir_ty = match fn_decl.output {
738 hir::FnRetTy::DefaultReturn(_) => None,
739 hir::FnRetTy::Return(ty) => Some(ty),
741 (fn_decl.output.span(), "", hir_ty)
743 None => (self.body.span, "", None),
747 let highlight = hir_ty
748 .and_then(|hir_ty| self.highlight_if_we_can_match_hir_ty(fr, return_ty, hir_ty))
750 // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
751 // the anonymous region. If it succeeds, the `synthesize_region_name` call below
752 // will increment the counter, "reserving" the number we just used.
753 let counter = *self.next_region_name.try_borrow().unwrap();
754 self.highlight_if_we_cannot_match_hir_ty(fr, return_ty, return_span, counter)
758 name: self.synthesize_region_name(),
759 source: RegionNameSource::AnonRegionFromOutput(highlight, mir_description.to_string()),
763 /// From the [`hir::Ty`] of an async function's lowered return type,
764 /// retrieve the `hir::Ty` representing the type the user originally wrote.
766 /// e.g. given the function:
769 /// async fn foo() -> i32 { 2 }
772 /// this function, given the lowered return type of `foo`, an [`OpaqueDef`] that implements `Future<Output=i32>`,
773 /// returns the `i32`.
775 /// [`OpaqueDef`]: hir::TyKind::OpaqueDef
776 fn get_future_inner_return_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
777 let hir = self.infcx.tcx.hir();
779 let hir::TyKind::OpaqueDef(id, _) = hir_ty.kind else {
782 "lowered return type of async fn is not OpaqueDef: {:?}",
786 let opaque_ty = hir.item(id);
787 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy {
790 hir::GenericBound::LangItemTrait(
791 hir::LangItem::Future,
798 ident: Ident { name: sym::Output, .. },
800 hir::TypeBindingKind::Equality { term: hir::Term::Ty(ty) },
815 "bounds from lowered return type of async fn did not match expected format: {:?}",
821 #[tracing::instrument(level = "trace", skip(self))]
822 fn give_name_if_anonymous_region_appears_in_yield_ty(
825 ) -> Option<RegionName> {
826 // Note: generators from `async fn` yield `()`, so we don't have to
827 // worry about them here.
828 let yield_ty = self.regioncx.universal_regions().yield_ty?;
829 debug!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}", yield_ty);
831 let tcx = self.infcx.tcx;
833 if !tcx.any_free_region_meets(&yield_ty, |r| r.to_region_vid() == fr) {
837 let mut highlight = RegionHighlightMode::new(tcx);
838 highlight.highlighting_region_vid(fr, *self.next_region_name.try_borrow().unwrap());
840 self.infcx.extract_inference_diagnostics_data(yield_ty.into(), Some(highlight)).name;
842 let yield_span = match tcx.hir().get(self.mir_hir_id()) {
843 hir::Node::Expr(hir::Expr {
844 kind: hir::ExprKind::Closure { fn_decl_span, .. },
846 }) => (tcx.sess.source_map().end_point(*fn_decl_span)),
851 "give_name_if_anonymous_region_appears_in_yield_ty: \
852 type_name = {:?}, yield_span = {:?}",
853 yield_span, type_name,
857 name: self.synthesize_region_name(),
858 source: RegionNameSource::AnonRegionFromYieldTy(yield_span, type_name),
862 fn give_name_if_anonymous_region_appears_in_impl_signature(
865 ) -> Option<RegionName> {
866 let ty::ReEarlyBound(region) = *self.to_error_region(fr)? else {
869 if region.has_name() {
873 let tcx = self.infcx.tcx;
874 let body_parent_did = tcx.opt_parent(self.mir_def_id().to_def_id())?;
875 if tcx.parent(region.def_id) != body_parent_did
876 || tcx.def_kind(body_parent_did) != DefKind::Impl
881 let mut found = false;
882 tcx.fold_regions(tcx.type_of(body_parent_did), |r: ty::Region<'tcx>, _| {
883 if *r == ty::ReEarlyBound(region) {
890 name: self.synthesize_region_name(),
891 source: RegionNameSource::AnonRegionFromImplSignature(
892 tcx.def_span(region.def_id),
893 // FIXME(compiler-errors): Does this ever actually show up
894 // anywhere other than the self type? I couldn't create an
895 // example of a `'_` in the impl's trait being referenceable.
896 if found { "self type" } else { "header" },