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, 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 crate struct RegionName {
19 /// The name of the region (interned).
21 /// Where the region comes from.
22 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 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),
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.
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),
68 crate fn was_named(&self) -> bool {
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,
82 crate fn span(&self) -> Option<Span> {
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),
101 crate fn highlight_region_name(&self, diag: &mut Diagnostic) {
103 RegionNameSource::NamedFreeRegion(span)
104 | RegionNameSource::NamedEarlyBoundRegion(span) => {
105 diag.span_label(*span, format!("lifetime `{self}` defined here"));
107 RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
108 diag.span_label(*span, format!("lifetime `{self}` represents this closure's body"));
111 RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::CannotMatchHirTy(
115 diag.span_label(*span, format!("has type `{type_name}`"));
117 RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::MatchedHirTy(span))
118 | RegionNameSource::AnonRegionFromOutput(RegionNameHighlight::MatchedHirTy(span), _)
119 | RegionNameSource::AnonRegionFromAsyncFn(span) => {
122 format!("let's call the lifetime of this reference `{self}`"),
125 RegionNameSource::AnonRegionFromArgument(
126 RegionNameHighlight::MatchedAdtAndSegment(span),
128 | RegionNameSource::AnonRegionFromOutput(
129 RegionNameHighlight::MatchedAdtAndSegment(span),
132 diag.span_label(*span, format!("let's call this `{self}`"));
134 RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::Occluded(
140 format!("lifetime `{self}` appears in the type {type_name}"),
143 RegionNameSource::AnonRegionFromOutput(
144 RegionNameHighlight::Occluded(span, type_name),
150 "return type{mir_description} `{type_name}` contains a lifetime `{self}`"
154 RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
157 format!("lifetime `{self}` appears in the type of `{upvar_name}`"),
160 RegionNameSource::AnonRegionFromOutput(
161 RegionNameHighlight::CannotMatchHirTy(span, type_name),
164 diag.span_label(*span, format!("return type{mir_description} is {type_name}"));
166 RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
167 diag.span_label(*span, format!("yield type is {type_name}"));
169 RegionNameSource::Static => {}
174 impl Display for RegionName {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 write!(f, "{}", self.name)
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()
185 crate fn mir_hir_id(&self) -> hir::HirId {
186 self.infcx.tcx.hir().local_def_id_to_hir_id(self.mir_def_id())
189 /// Generate a synthetic region named `'N`, where `N` is the next value of the counter. Then,
190 /// increment the counter.
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))
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.
206 /// The names are memoized, so this is both cheap to recompute and idempotent.
208 /// Example (function arguments):
210 /// Suppose we are trying to give a name to the lifetime of the
213 /// ```ignore (pseudo-rust)
214 /// fn foo(x: &u32) { .. }
217 /// This function would create a label like this:
220 /// | fn foo(x: &u32) { .. }
221 /// ------- fully elaborated type of `x` is `&'1 u32`
224 /// and then return the name `'1` for us to use.
225 crate fn give_region_a_name(&self, fr: RegionVid) -> Option<RegionName> {
227 "give_region_a_name(fr={:?}, counter={:?})",
229 self.next_region_name.try_borrow().unwrap()
232 assert!(self.regioncx.universal_regions().is_universal_region(fr));
234 if let Some(value) = self.region_names.try_borrow_mut().unwrap().get(&fr) {
235 return Some(value.clone());
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));
245 if let Some(ref value) = value {
246 self.region_names.try_borrow_mut().unwrap().insert(fr, value.clone());
249 debug!("give_region_a_name: gave name {:?}", value);
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
257 fn give_name_from_error_region(&self, fr: RegionVid) -> Option<RegionName> {
258 let error_region = self.to_error_region(fr)?;
260 let tcx = self.infcx.tcx;
262 debug!("give_region_a_name: error_region = {:?}", error_region);
263 match *error_region {
264 ty::ReEarlyBound(ebr) => {
266 let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP);
269 source: RegionNameSource::NamedEarlyBoundRegion(span),
277 Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })
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);
285 "bound region named: {:?}, is_named: {:?}",
287 free_region.bound_region.is_named()
290 if free_region.bound_region.is_named() {
291 // A named region that is actually named.
292 Some(RegionName { name, source: RegionNameSource::NamedFreeRegion(span) })
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();
302 source: RegionNameSource::AnonRegionFromAsyncFn(span),
307 ty::BoundRegionKind::BrEnv => {
308 let def_ty = self.regioncx.universal_regions().defining_ty;
310 let DefiningTy::Closure(_, substs) = def_ty else {
311 // Can't have BrEnv in functions, constants or generators.
312 bug!("BrEnv outside of closure.");
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");
318 let region_name = self.synthesize_region_name();
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"
326 Some(ty::ClosureKind::FnMut) => {
327 "closure implements `FnMut`, so references to captured variables \
328 can't escape the closure"
330 Some(ty::ClosureKind::FnOnce) => {
331 bug!("BrEnv in a `FnOnce` closure");
333 None => bug!("Closure kind not inferred in borrow check"),
338 source: RegionNameSource::SynthesizedFreeEnvRegion(
345 ty::BoundRegionKind::BrAnon(_) => None,
350 | ty::RePlaceholder(..)
352 | ty::ReErased => None,
356 /// Finds an argument that contains `fr` and label it with a fully
357 /// elaborated type, returning something like `'1`. Result looks
361 /// | fn foo(x: &u32) { .. }
362 /// ------- fully elaborated type of `x` is `&'1 u32`
364 fn give_name_if_anonymous_region_appears_in_arguments(
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)?;
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(
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))
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)
391 name: self.synthesize_region_name(),
392 source: RegionNameSource::AnonRegionFromArgument(highlight),
396 fn get_argument_hir_ty_for_highlighting(
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,
410 _ => Some(argument_hir_ty),
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:
422 /// | | has type `&'1 u32`
423 /// | has type `&'2 u32`
425 fn highlight_if_we_cannot_match_hir_ty(
427 needle_fr: RegionVid,
431 ) -> RegionNameHighlight {
432 let mut highlight = RegionHighlightMode::new(self.infcx.tcx);
433 highlight.highlighting_region_vid(needle_fr, counter);
435 self.infcx.extract_inference_diagnostics_data(ty.into(), Some(highlight)).name;
438 "highlight_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
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)
445 RegionNameHighlight::Occluded(span, type_name)
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:
454 /// | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
455 /// | - let's call the lifetime of this reference `'1`
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.
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(
472 needle_fr: RegionVid,
474 hir_ty: &hir::Ty<'_>,
475 ) -> Option<RegionNameHighlight> {
476 let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty<'_>)> = &mut vec![(ty, hir_ty)];
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:
485 // - let's call the lifetime of this reference `'1`
487 ty::Ref(region, referent_ty, _),
488 hir::TyKind::Rptr(_lifetime, referent_hir_ty),
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);
495 return Some(RegionNameHighlight::MatchedHirTy(ampersand_span));
498 // Otherwise, let's descend into the referent types.
499 search_stack.push((*referent_ty, &referent_hir_ty.ty));
502 // Match up something like `Foo<'1>`
504 ty::Adt(_adt_def, substs),
505 hir::TyKind::Path(hir::QPath::Resolved(None, path)),
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, _) => (),
514 if let Some(last_segment) = path.segments.last() {
515 if let Some(highlight) = self.match_adt_and_segment(
521 return Some(highlight);
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));
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));
540 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
541 search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
545 // FIXME there are other cases that we could trace
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>(
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()?;
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))
578 hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Implicit => {
579 // In this case, the user left off the lifetime; so
580 // they wrote something like:
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
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>(
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 {
615 (GenericArgKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
616 search_stack.push((ty, hir_ty));
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.
625 GenericArgKind::Lifetime(_)
626 | GenericArgKind::Type(_)
627 | GenericArgKind::Const(_),
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(
634 &format!("unmatched subst and hir arg: found {:?} vs {:?}", kind, hir_arg),
643 /// Finds a closure upvar that contains `fr` and label it with a
644 /// fully elaborated type, returning something like `'1`. Result
648 /// | let x = Some(&22);
649 /// - fully elaborated type of `x` is `Option<&'1 u32>`
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(
658 let region_name = self.synthesize_region_name();
662 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
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;
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) {
680 let mir_hir_id = self.mir_hir_id();
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, _),
687 let (mut span, mut hir_ty) = match return_ty.output {
688 hir::FnRetTy::DefaultReturn(_) => {
689 (tcx.sess.source_map().end_point(*span), None)
691 hir::FnRetTy::Return(hir_ty) => (return_ty.output.span(), Some(hir_ty)),
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
701 .expect("generator lowered from async fn should be in fn")
703 span = output.span();
704 if let hir::FnRetTy::Return(ret) = output {
705 hir_ty = Some(self.get_future_inner_return_ty(*ret));
710 Some(hir::GeneratorKind::Gen) => " of generator",
711 None => " of closure",
713 (span, mir_description, hir_ty)
715 node => match node.fn_decl() {
717 let hir_ty = match fn_decl.output {
718 hir::FnRetTy::DefaultReturn(_) => None,
719 hir::FnRetTy::Return(ty) => Some(ty),
721 (fn_decl.output.span(), "", hir_ty)
723 None => (self.body.span, "", None),
727 let highlight = hir_ty
728 .and_then(|hir_ty| self.highlight_if_we_can_match_hir_ty(fr, return_ty, hir_ty))
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)
738 name: self.synthesize_region_name(),
739 source: RegionNameSource::AnonRegionFromOutput(highlight, mir_description.to_string()),
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.
746 /// e.g. given the function:
749 /// async fn foo() -> i32 { 2 }
752 /// this function, given the lowered return type of `foo`, an [`OpaqueDef`] that implements `Future<Output=i32>`,
753 /// returns the `i32`.
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();
759 let hir::TyKind::OpaqueDef(id, _) = hir_ty.kind else {
762 "lowered return type of async fn is not OpaqueDef: {:?}",
766 let opaque_ty = hir.item(id);
767 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy {
770 hir::GenericBound::LangItemTrait(
771 hir::LangItem::Future,
778 ident: Ident { name: sym::Output, .. },
780 hir::TypeBindingKind::Equality { term: hir::Term::Ty(ty) },
795 "bounds from lowered return type of async fn did not match expected format: {:?}",
801 fn give_name_if_anonymous_region_appears_in_yield_ty(
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);
810 let tcx = self.infcx.tcx;
812 if !tcx.any_free_region_meets(&yield_ty, |r| r.to_region_vid() == fr) {
816 let mut highlight = RegionHighlightMode::new(tcx);
817 highlight.highlighting_region_vid(fr, *self.next_region_name.try_borrow().unwrap());
819 self.infcx.extract_inference_diagnostics_data(yield_ty.into(), Some(highlight)).name;
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)),
829 "give_name_if_anonymous_region_appears_in_yield_ty: \
830 type_name = {:?}, yield_span = {:?}",
831 yield_span, type_name,
835 name: self.synthesize_region_name(),
836 source: RegionNameSource::AnonRegionFromYieldTy(yield_span, type_name),