1 use std::fmt::{self, Display};
3 use rustc_errors::DiagnosticBuilder;
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};
12 use crate::borrow_check::{nll::ToRegionVid, universal_regions::DefiningTy, MirBorrowckCtxt};
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).
20 /// Where the region comes from.
21 crate source: RegionNameSource,
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.
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),
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.
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),
67 crate fn was_named(&self) -> bool {
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,
81 crate fn span(&self) -> Option<Span> {
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),
100 crate fn highlight_region_name(&self, diag: &mut DiagnosticBuilder<'_>) {
102 RegionNameSource::NamedFreeRegion(span)
103 | RegionNameSource::NamedEarlyBoundRegion(span) => {
104 diag.span_label(*span, format!("lifetime `{}` defined here", self));
106 RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
109 format!("lifetime `{}` represents this closure's body", self),
113 RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::CannotMatchHirTy(
117 diag.span_label(*span, format!("has type `{}`", type_name));
119 RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::MatchedHirTy(span))
120 | RegionNameSource::AnonRegionFromOutput(RegionNameHighlight::MatchedHirTy(span), _)
121 | RegionNameSource::AnonRegionFromAsyncFn(span) => {
124 format!("let's call the lifetime of this reference `{}`", self),
127 RegionNameSource::AnonRegionFromArgument(
128 RegionNameHighlight::MatchedAdtAndSegment(span),
130 | RegionNameSource::AnonRegionFromOutput(
131 RegionNameHighlight::MatchedAdtAndSegment(span),
134 diag.span_label(*span, format!("let's call this `{}`", self));
136 RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::Occluded(
142 format!("lifetime `{}` appears in the type {}", self, type_name),
145 RegionNameSource::AnonRegionFromOutput(
146 RegionNameHighlight::Occluded(span, type_name),
152 "return type{} `{}` contains a lifetime `{}`",
153 mir_description, type_name, self
157 RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
160 format!("lifetime `{}` appears in the type of `{}`", self, upvar_name),
163 RegionNameSource::AnonRegionFromOutput(
164 RegionNameHighlight::CannotMatchHirTy(span, type_name),
167 diag.span_label(*span, format!("return type{} is {}", mir_description, type_name));
169 RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
170 diag.span_label(*span, format!("yield type is {}", type_name));
172 RegionNameSource::Static => {}
177 impl Display for RegionName {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 write!(f, "{}", self.name)
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()
188 crate fn mir_hir_id(&self) -> hir::HirId {
189 self.infcx.tcx.hir().local_def_id_to_hir_id(self.mir_def_id())
192 /// Generate a synthetic region named `'N`, where `N` is the next value of the counter. Then,
193 /// increment the counter.
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))
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.
209 /// The names are memoized, so this is both cheap to recompute and idempotent.
211 /// Example (function arguments):
213 /// Suppose we are trying to give a name to the lifetime of the
217 /// fn foo(x: &u32) { .. }
220 /// This function would create a label like this:
223 /// | fn foo(x: &u32) { .. }
224 /// ------- fully elaborated type of `x` is `&'1 u32`
227 /// and then return the name `'1` for us to use.
228 crate fn give_region_a_name(&self, fr: RegionVid) -> Option<RegionName> {
230 "give_region_a_name(fr={:?}, counter={:?})",
232 self.next_region_name.try_borrow().unwrap()
235 assert!(self.regioncx.universal_regions().is_universal_region(fr));
237 if let Some(value) = self.region_names.try_borrow_mut().unwrap().get(&fr) {
238 return Some(value.clone());
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));
248 if let Some(ref value) = value {
249 self.region_names.try_borrow_mut().unwrap().insert(fr, value.clone());
252 debug!("give_region_a_name: gave name {:?}", value);
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
260 fn give_name_from_error_region(&self, fr: RegionVid) -> Option<RegionName> {
261 let error_region = self.to_error_region(fr)?;
263 let tcx = self.infcx.tcx;
265 debug!("give_region_a_name: error_region = {:?}", error_region);
267 ty::ReEarlyBound(ebr) => {
269 let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP);
272 source: RegionNameSource::NamedEarlyBoundRegion(span),
280 Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })
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);
288 "bound region named: {:?}, is_named: {:?}",
290 free_region.bound_region.is_named()
293 if free_region.bound_region.is_named() {
294 // A named region that is actually named.
295 Some(RegionName { name, source: RegionNameSource::NamedFreeRegion(span) })
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();
305 source: RegionNameSource::AnonRegionFromAsyncFn(span),
310 ty::BoundRegionKind::BrEnv => {
311 let def_ty = self.regioncx.universal_regions().defining_ty;
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
319 bug!("Closure is not defined by a closure expr");
321 let region_name = self.synthesize_region_name();
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"
329 Some(ty::ClosureKind::FnMut) => {
330 "closure implements `FnMut`, so references to captured variables \
331 can't escape the closure"
333 Some(ty::ClosureKind::FnOnce) => {
334 bug!("BrEnv in a `FnOnce` closure");
336 None => bug!("Closure kind not inferred in borrow check"),
341 source: RegionNameSource::SynthesizedFreeEnvRegion(
347 // Can't have BrEnv in functions, constants or generators.
348 bug!("BrEnv outside of closure.");
352 ty::BoundRegionKind::BrAnon(_) => None,
357 | ty::RePlaceholder(..)
359 | ty::ReErased => None,
363 /// Finds an argument that contains `fr` and label it with a fully
364 /// elaborated type, returning something like `'1`. Result looks
368 /// | fn foo(x: &u32) { .. }
369 /// ------- fully elaborated type of `x` is `&'1 u32`
371 fn give_name_if_anonymous_region_appears_in_arguments(
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)?;
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(
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))
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)
398 name: self.synthesize_region_name(),
399 source: RegionNameSource::AnonRegionFromArgument(highlight),
403 fn get_argument_hir_ty_for_highlighting(
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,
417 _ => Some(argument_hir_ty),
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:
429 /// | | has type `&'1 u32`
430 /// | has type `&'2 u32`
432 fn highlight_if_we_cannot_match_hir_ty(
434 needle_fr: RegionVid,
438 ) -> RegionNameHighlight {
439 let mut highlight = RegionHighlightMode::default();
440 highlight.highlighting_region_vid(needle_fr, counter);
442 self.infcx.extract_inference_diagnostics_data(ty.into(), Some(highlight)).name;
445 "highlight_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
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)
452 RegionNameHighlight::Occluded(span, type_name)
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:
461 /// | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
462 /// | - let's call the lifetime of this reference `'1`
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.
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(
479 needle_fr: RegionVid,
481 hir_ty: &hir::Ty<'_>,
482 ) -> Option<RegionNameHighlight> {
483 let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty<'_>)> = &mut vec![(ty, hir_ty)];
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:
492 // - let's call the lifetime of this reference `'1`
494 ty::Ref(region, referent_ty, _),
495 hir::TyKind::Rptr(_lifetime, referent_hir_ty),
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);
502 return Some(RegionNameHighlight::MatchedHirTy(ampersand_span));
505 // Otherwise, let's descend into the referent types.
506 search_stack.push((referent_ty, &referent_hir_ty.ty));
509 // Match up something like `Foo<'1>`
511 ty::Adt(_adt_def, substs),
512 hir::TyKind::Path(hir::QPath::Resolved(None, path)),
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, _) => (),
521 if let Some(last_segment) = path.segments.last() {
522 if let Some(highlight) = self.match_adt_and_segment(
528 return Some(highlight);
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));
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));
547 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
548 search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
552 // FIXME there are other cases that we could trace
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>(
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()?;
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))
585 hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Implicit => {
586 // In this case, the user left off the lifetime; so
587 // they wrote something like:
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
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>(
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 {
622 (GenericArgKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
623 search_stack.push((ty, hir_ty));
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.
632 GenericArgKind::Lifetime(_)
633 | GenericArgKind::Type(_)
634 | GenericArgKind::Const(_),
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(
641 &format!("unmatched subst and hir arg: found {:?} vs {:?}", kind, hir_arg),
650 /// Finds a closure upvar that contains `fr` and label it with a
651 /// fully elaborated type, returning something like `'1`. Result
655 /// | let x = Some(&22);
656 /// - fully elaborated type of `x` is `Option<&'1 u32>`
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(
665 let region_name = self.synthesize_region_name();
669 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
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;
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) {
687 let mir_hir_id = self.mir_hir_id();
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, _),
694 let (mut span, mut hir_ty) = match return_ty.output {
695 hir::FnRetTy::DefaultReturn(_) => {
696 (tcx.sess.source_map().end_point(*span), None)
698 hir::FnRetTy::Return(hir_ty) => (return_ty.output.span(), Some(hir_ty)),
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
708 .expect("generator lowered from async fn should be in fn")
710 span = output.span();
711 if let hir::FnRetTy::Return(ret) = output {
712 hir_ty = Some(self.get_future_inner_return_ty(*ret));
717 Some(hir::GeneratorKind::Gen) => " of generator",
718 None => " of closure",
720 (span, mir_description, hir_ty)
722 node => match node.fn_decl() {
724 let hir_ty = match fn_decl.output {
725 hir::FnRetTy::DefaultReturn(_) => None,
726 hir::FnRetTy::Return(ty) => Some(ty),
728 (fn_decl.output.span(), "", hir_ty)
730 None => (self.body.span, "", None),
734 let highlight = hir_ty
735 .and_then(|hir_ty| self.highlight_if_we_can_match_hir_ty(fr, return_ty, hir_ty))
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)
745 name: self.synthesize_region_name(),
746 source: RegionNameSource::AnonRegionFromOutput(highlight, mir_description.to_string()),
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.
753 /// e.g. given the function:
756 /// async fn foo() -> i32 {}
759 /// this function, given the lowered return type of `foo`, an [`OpaqueDef`] that implements `Future<Output=i32>`,
760 /// returns the `i32`.
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();
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 {
770 [hir::GenericBound::LangItemTrait(
771 hir::LangItem::Future,
777 ident: Ident { name: sym::Output, .. },
778 kind: hir::TypeBindingKind::Equality { ty },
791 "bounds from lowered return type of async fn did not match expected format: {:?}",
798 "lowered return type of async fn is not OpaqueDef: {:?}",
804 fn give_name_if_anonymous_region_appears_in_yield_ty(
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,);
813 let tcx = self.infcx.tcx;
815 if !tcx.any_free_region_meets(&yield_ty, |r| r.to_region_vid() == fr) {
819 let mut highlight = RegionHighlightMode::default();
820 highlight.highlighting_region_vid(fr, *self.next_region_name.try_borrow().unwrap());
822 self.infcx.extract_inference_diagnostics_data(yield_ty.into(), Some(highlight)).name;
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)),
832 "give_name_if_anonymous_region_appears_in_yield_ty: \
833 type_name = {:?}, yield_span = {:?}",
834 yield_span, type_name,
838 name: self.synthesize_region_name(),
839 source: RegionNameSource::AnonRegionFromYieldTy(yield_span, type_name),