Skip to main content

rustc_borrowck/diagnostics/
region_name.rs

1use std::fmt::{self, Display};
2use std::iter;
3
4use rustc_data_structures::fx::IndexEntry;
5use rustc_errors::{Diag, EmissionGuarantee};
6use rustc_hir as hir;
7use rustc_hir::def::{DefKind, Res};
8use rustc_middle::ty::print::RegionHighlightMode;
9use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, RegionVid, Ty};
10use rustc_middle::{bug, span_bug};
11use rustc_span::{DUMMY_SP, Span, Symbol, kw, sym};
12use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
13use tracing::{debug, instrument};
14
15use crate::MirBorrowckCtxt;
16use crate::universal_regions::DefiningTy;
17
18/// A name for a particular region used in emitting diagnostics. This name could be a generated
19/// name like `'1`, a name used by the user like `'a`, or a name like `'static`.
20#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RegionName {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "RegionName",
            "name", &self.name, "source", &&self.source)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for RegionName {
    #[inline]
    fn clone(&self) -> RegionName {
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        let _: ::core::clone::AssertParamIsClone<RegionNameSource>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for RegionName { }Copy)]
21pub(crate) struct RegionName {
22    /// The name of the region (interned).
23    pub(crate) name: Symbol,
24    /// Where the region comes from.
25    pub(crate) source: RegionNameSource,
26}
27
28/// Denotes the source of a region that is named by a `RegionName`. For example, a free region that
29/// was named by the user would get `NamedLateParamRegion` and `'static` lifetime would get
30/// `Static`. This helps to print the right kinds of diagnostics.
31#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RegionNameSource {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RegionNameSource::NamedEarlyParamRegion(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NamedEarlyParamRegion", &__self_0),
            RegionNameSource::NamedLateParamRegion(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NamedLateParamRegion", &__self_0),
            RegionNameSource::Static =>
                ::core::fmt::Formatter::write_str(f, "Static"),
            RegionNameSource::SynthesizedFreeEnvRegion(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "SynthesizedFreeEnvRegion", __self_0, &__self_1),
            RegionNameSource::AnonRegionFromArgument(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AnonRegionFromArgument", &__self_0),
            RegionNameSource::AnonRegionFromUpvar(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AnonRegionFromUpvar", __self_0, &__self_1),
            RegionNameSource::AnonRegionFromOutput(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AnonRegionFromOutput", __self_0, &__self_1),
            RegionNameSource::AnonRegionFromYieldTy(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AnonRegionFromYieldTy", __self_0, &__self_1),
            RegionNameSource::AnonRegionFromAsyncFn(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AnonRegionFromAsyncFn", &__self_0),
            RegionNameSource::AnonRegionFromImplSignature(__self_0, __self_1)
                =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AnonRegionFromImplSignature", __self_0, &__self_1),
        }
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for RegionNameSource {
    #[inline]
    fn clone(&self) -> RegionNameSource {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<&'static str>;
        let _: ::core::clone::AssertParamIsClone<RegionNameHighlight>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        let _: ::core::clone::AssertParamIsClone<&'static str>;
        let _: ::core::clone::AssertParamIsClone<&'static str>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for RegionNameSource { }Copy)]
32pub(crate) enum RegionNameSource {
33    /// A bound (not free) region that was instantiated at the def site (not an HRTB).
34    NamedEarlyParamRegion(Span),
35    /// A free region that the user has a name (`'a`) for.
36    NamedLateParamRegion(Span),
37    /// The `'static` region.
38    Static,
39    /// The free region corresponding to the environment of a closure.
40    SynthesizedFreeEnvRegion(Span, &'static str),
41    /// The region corresponding to an argument.
42    AnonRegionFromArgument(RegionNameHighlight),
43    /// The region corresponding to a closure upvar.
44    AnonRegionFromUpvar(Span, Symbol),
45    /// The region corresponding to the return type of a closure.
46    AnonRegionFromOutput(RegionNameHighlight, &'static str),
47    /// The region from a type yielded by a coroutine.
48    AnonRegionFromYieldTy(Span, Symbol),
49    /// An anonymous region from an async fn.
50    AnonRegionFromAsyncFn(Span),
51    /// An anonymous region from an impl self type or trait
52    AnonRegionFromImplSignature(Span, &'static str),
53}
54
55/// Describes what to highlight to explain to the user that we're giving an anonymous region a
56/// synthesized name, and how to highlight it.
57#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RegionNameHighlight {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RegionNameHighlight::MatchedHirTy(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MatchedHirTy", &__self_0),
            RegionNameHighlight::MatchedAdtAndSegment(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MatchedAdtAndSegment", &__self_0),
            RegionNameHighlight::CannotMatchHirTy(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "CannotMatchHirTy", __self_0, &__self_1),
            RegionNameHighlight::Occluded(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Occluded", __self_0, &__self_1),
        }
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for RegionNameHighlight {
    #[inline]
    fn clone(&self) -> RegionNameHighlight {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for RegionNameHighlight { }Copy)]
58pub(crate) enum RegionNameHighlight {
59    /// The anonymous region corresponds to a reference that was found by traversing the type in the HIR.
60    MatchedHirTy(Span),
61    /// The anonymous region corresponds to a `'_` in the generics list of a struct/enum/union.
62    MatchedAdtAndSegment(Span),
63    /// The anonymous region corresponds to a region where the type annotation is completely missing
64    /// from the code, e.g. in a closure arguments `|x| { ... }`, where `x` is a reference.
65    CannotMatchHirTy(Span, Symbol),
66    /// The anonymous region corresponds to a region where the type annotation is completely missing
67    /// from the code, and *even if* we print out the full name of the type, the region name won't
68    /// be included. This currently occurs for opaque types like `impl Future`.
69    Occluded(Span, Symbol),
70}
71
72impl RegionName {
73    pub(crate) fn was_named(&self) -> bool {
74        match self.source {
75            RegionNameSource::NamedEarlyParamRegion(..)
76            | RegionNameSource::NamedLateParamRegion(..)
77            | RegionNameSource::Static => true,
78            RegionNameSource::SynthesizedFreeEnvRegion(..)
79            | RegionNameSource::AnonRegionFromArgument(..)
80            | RegionNameSource::AnonRegionFromUpvar(..)
81            | RegionNameSource::AnonRegionFromOutput(..)
82            | RegionNameSource::AnonRegionFromYieldTy(..)
83            | RegionNameSource::AnonRegionFromAsyncFn(..)
84            | RegionNameSource::AnonRegionFromImplSignature(..) => false,
85        }
86    }
87
88    pub(crate) fn span(&self) -> Option<Span> {
89        match self.source {
90            RegionNameSource::Static => None,
91            RegionNameSource::NamedEarlyParamRegion(span)
92            | RegionNameSource::NamedLateParamRegion(span)
93            | RegionNameSource::SynthesizedFreeEnvRegion(span, _)
94            | RegionNameSource::AnonRegionFromUpvar(span, _)
95            | RegionNameSource::AnonRegionFromYieldTy(span, _)
96            | RegionNameSource::AnonRegionFromAsyncFn(span)
97            | RegionNameSource::AnonRegionFromImplSignature(span, _) => Some(span),
98            RegionNameSource::AnonRegionFromArgument(ref highlight)
99            | RegionNameSource::AnonRegionFromOutput(ref highlight, _) => match *highlight {
100                RegionNameHighlight::MatchedHirTy(span)
101                | RegionNameHighlight::MatchedAdtAndSegment(span)
102                | RegionNameHighlight::CannotMatchHirTy(span, _)
103                | RegionNameHighlight::Occluded(span, _) => Some(span),
104            },
105        }
106    }
107
108    pub(crate) fn highlight_region_name<G: EmissionGuarantee>(&self, diag: &mut Diag<'_, G>) {
109        match &self.source {
110            RegionNameSource::NamedLateParamRegion(span)
111            | RegionNameSource::NamedEarlyParamRegion(span) => {
112                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` defined here",
                self))
    })format!("lifetime `{self}` defined here"));
113            }
114            RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
115                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` represents this closure\'s body",
                self))
    })format!("lifetime `{self}` represents this closure's body"));
116                diag.note(*note);
117            }
118            RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::CannotMatchHirTy(
119                span,
120                type_name,
121            )) => {
122                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("has type `{0}`", type_name))
    })format!("has type `{type_name}`"));
123            }
124            RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::MatchedHirTy(span))
125            | RegionNameSource::AnonRegionFromOutput(RegionNameHighlight::MatchedHirTy(span), _)
126            | RegionNameSource::AnonRegionFromAsyncFn(span) => {
127                diag.span_label(
128                    *span,
129                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let\'s call the lifetime of this reference `{0}`",
                self))
    })format!("let's call the lifetime of this reference `{self}`"),
130                );
131            }
132            RegionNameSource::AnonRegionFromArgument(
133                RegionNameHighlight::MatchedAdtAndSegment(span),
134            )
135            | RegionNameSource::AnonRegionFromOutput(
136                RegionNameHighlight::MatchedAdtAndSegment(span),
137                _,
138            ) => {
139                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let\'s call this `{0}`", self))
    })format!("let's call this `{self}`"));
140            }
141            RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::Occluded(
142                span,
143                type_name,
144            )) => {
145                diag.span_label(
146                    *span,
147                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` appears in the type {1}",
                self, type_name))
    })format!("lifetime `{self}` appears in the type {type_name}"),
148                );
149            }
150            RegionNameSource::AnonRegionFromOutput(
151                RegionNameHighlight::Occluded(span, type_name),
152                mir_description,
153            ) => {
154                diag.span_label(
155                    *span,
156                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("return type{0} `{1}` contains a lifetime `{2}`",
                mir_description, type_name, self))
    })format!(
157                        "return type{mir_description} `{type_name}` contains a lifetime `{self}`"
158                    ),
159                );
160            }
161            RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
162                diag.span_label(
163                    *span,
164                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` appears in the type of `{1}`",
                self, upvar_name))
    })format!("lifetime `{self}` appears in the type of `{upvar_name}`"),
165                );
166            }
167            RegionNameSource::AnonRegionFromOutput(
168                RegionNameHighlight::CannotMatchHirTy(span, type_name),
169                mir_description,
170            ) => {
171                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("return type{0} is {1}",
                mir_description, type_name))
    })format!("return type{mir_description} is {type_name}"));
172            }
173            RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
174                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("yield type is {0}", type_name))
    })format!("yield type is {type_name}"));
175            }
176            RegionNameSource::AnonRegionFromImplSignature(span, location) => {
177                diag.span_label(
178                    *span,
179                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` appears in the `impl`\'s {1}",
                self, location))
    })format!("lifetime `{self}` appears in the `impl`'s {location}"),
180                );
181            }
182            RegionNameSource::Static => {}
183        }
184    }
185}
186
187impl Display for RegionName {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        f.write_fmt(format_args!("{0}", self.name))write!(f, "{}", self.name)
190    }
191}
192
193impl rustc_errors::IntoDiagArg for RegionName {
194    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
195        self.to_string().into_diag_arg(path)
196    }
197}
198
199impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
200    pub(crate) fn mir_def_id(&self) -> hir::def_id::LocalDefId {
201        self.body.source.def_id().expect_local()
202    }
203
204    pub(crate) fn mir_hir_id(&self) -> hir::HirId {
205        self.infcx.tcx.local_def_id_to_hir_id(self.mir_def_id())
206    }
207
208    /// Generate a synthetic region named `'N`, where `N` is the next value of the counter. Then,
209    /// increment the counter.
210    ///
211    /// This is _not_ idempotent. Call `give_region_a_name` when possible.
212    pub(crate) fn synthesize_region_name(&self) -> Symbol {
213        let c = self.next_region_name.replace_with(|counter| *counter + 1);
214        Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0:?}", c))
    })format!("'{c:?}"))
215    }
216
217    /// Maps from an internal MIR region vid to something that we can
218    /// report to the user. In some cases, the region vids will map
219    /// directly to lifetimes that the user has a name for (e.g.,
220    /// `'static`). But frequently they will not, in which case we
221    /// have to find some way to identify the lifetime to the user. To
222    /// that end, this function takes a "diagnostic" so that it can
223    /// create auxiliary notes as needed.
224    ///
225    /// The names are memoized, so this is both cheap to recompute and idempotent.
226    ///
227    /// Example (function arguments):
228    ///
229    /// Suppose we are trying to give a name to the lifetime of the
230    /// reference `x`:
231    ///
232    /// ```ignore (pseudo-rust)
233    /// fn foo(x: &u32) { .. }
234    /// ```
235    ///
236    /// This function would create a label like this:
237    ///
238    /// ```text
239    ///  | fn foo(x: &u32) { .. }
240    ///           ------- fully elaborated type of `x` is `&'1 u32`
241    /// ```
242    ///
243    /// and then return the name `'1` for us to use.
244    pub(crate) fn give_region_a_name(&self, fr: RegionVid) -> Option<RegionName> {
245        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:245",
                        "rustc_borrowck::diagnostics::region_name",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                        ::tracing_core::__macro_support::Option::Some(245u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("give_region_a_name(fr={0:?}, counter={1:?})",
                                                    fr, self.next_region_name.try_borrow().unwrap()) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
246            "give_region_a_name(fr={:?}, counter={:?})",
247            fr,
248            self.next_region_name.try_borrow().unwrap()
249        );
250
251        if !self.regioncx.universal_regions().is_universal_region(fr) {
    ::core::panicking::panic("assertion failed: self.regioncx.universal_regions().is_universal_region(fr)")
};assert!(self.regioncx.universal_regions().is_universal_region(fr));
252
253        match self.region_names.borrow_mut().entry(fr) {
254            IndexEntry::Occupied(precomputed_name) => Some(*precomputed_name.get()),
255            IndexEntry::Vacant(slot) => {
256                let new_name = self
257                    .give_name_from_error_region(fr)
258                    .or_else(|| self.give_name_if_anonymous_region_appears_in_arguments(fr))
259                    .or_else(|| self.give_name_if_anonymous_region_appears_in_upvars(fr))
260                    .or_else(|| self.give_name_if_anonymous_region_appears_in_output(fr))
261                    .or_else(|| self.give_name_if_anonymous_region_appears_in_yield_ty(fr))
262                    .or_else(|| self.give_name_if_anonymous_region_appears_in_impl_signature(fr))
263                    .or_else(|| {
264                        self.give_name_if_anonymous_region_appears_in_arg_position_impl_trait(fr)
265                    });
266
267                if let Some(new_name) = new_name {
268                    slot.insert(new_name);
269                }
270                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:270",
                        "rustc_borrowck::diagnostics::region_name",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                        ::tracing_core::__macro_support::Option::Some(270u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("give_region_a_name: gave name {0:?}",
                                                    new_name) as &dyn Value))])
            });
    } else { ; }
};debug!("give_region_a_name: gave name {:?}", new_name);
271
272                new_name
273            }
274        }
275    }
276
277    /// Checks for the case where `fr` maps to something that the
278    /// *user* has a name for. In that case, we'll be able to map
279    /// `fr` to a `Region<'tcx>`, and that region will be one of
280    /// named variants.
281    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("give_name_from_error_region",
                                    "rustc_borrowck::diagnostics::region_name",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                                    ::tracing_core::__macro_support::Option::Some(281u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let error_region = self.to_error_region(fr)?;
            let tcx = self.infcx.tcx;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:287",
                                    "rustc_borrowck::diagnostics::region_name",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                                    ::tracing_core::__macro_support::Option::Some(287u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("give_region_a_name: error_region = {0:?}",
                                                                error_region) as &dyn Value))])
                        });
                } else { ; }
            };
            match error_region.kind() {
                ty::ReEarlyParam(ebr) =>
                    ebr.is_named().then(||
                            {
                                let def_id =
                                    tcx.generics_of(self.mir_def_id()).region_param(ebr,
                                            tcx).def_id;
                                let span =
                                    tcx.hir_span_if_local(def_id).unwrap_or(DUMMY_SP);
                                RegionName {
                                    name: ebr.name,
                                    source: RegionNameSource::NamedEarlyParamRegion(span),
                                }
                            }),
                ty::ReStatic => {
                    Some(RegionName {
                            name: kw::StaticLifetime,
                            source: RegionNameSource::Static,
                        })
                }
                ty::ReLateParam(late_param) =>
                    match late_param.kind {
                        ty::LateParamRegionKind::Named(region_def_id) => {
                            let span =
                                tcx.hir_span_if_local(region_def_id).unwrap_or(DUMMY_SP);
                            if let Some(name) = late_param.kind.get_name(tcx) {
                                Some(RegionName {
                                        name,
                                        source: RegionNameSource::NamedLateParamRegion(span),
                                    })
                            } else if tcx.asyncness(self.mir_hir_id().owner).is_async()
                                {
                                let name = self.synthesize_region_name();
                                Some(RegionName {
                                        name,
                                        source: RegionNameSource::AnonRegionFromAsyncFn(span),
                                    })
                            } else { None }
                        }
                        ty::LateParamRegionKind::ClosureEnv => {
                            let def_ty = self.regioncx.universal_regions().defining_ty;
                            let closure_kind =
                                match def_ty {
                                    DefiningTy::Closure(_, args) => args.as_closure().kind(),
                                    DefiningTy::CoroutineClosure(_, args) =>
                                        args.as_coroutine_closure().kind(),
                                    _ => {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("BrEnv outside of closure."));
                                    }
                                };
                            let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, ..
                                    }) =
                                tcx.hir_expect_expr(self.mir_hir_id()).kind else {
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("Closure is not defined by a closure expr"));
                                };
                            let region_name = self.synthesize_region_name();
                            let note =
                                match closure_kind {
                                    ty::ClosureKind::Fn => {
                                        "closure implements `Fn`, so references to captured variables \
                             can't escape the closure"
                                    }
                                    ty::ClosureKind::FnMut => {
                                        "closure implements `FnMut`, so references to captured variables \
                             can't escape the closure"
                                    }
                                    ty::ClosureKind::FnOnce => {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("BrEnv in a `FnOnce` closure"));
                                    }
                                };
                            Some(RegionName {
                                    name: region_name,
                                    source: RegionNameSource::SynthesizedFreeEnvRegion(fn_decl_span,
                                        note),
                                })
                        }
                        ty::LateParamRegionKind::Anon(_) => None,
                        ty::LateParamRegionKind::NamedAnon(_, _) =>
                            ::rustc_middle::util::bug::bug_fmt(format_args!("only used for pretty printing")),
                    },
                ty::ReBound(..) | ty::ReVar(..) | ty::RePlaceholder(..) |
                    ty::ReErased | ty::ReError(_) => None,
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
282    fn give_name_from_error_region(&self, fr: RegionVid) -> Option<RegionName> {
283        let error_region = self.to_error_region(fr)?;
284
285        let tcx = self.infcx.tcx;
286
287        debug!("give_region_a_name: error_region = {:?}", error_region);
288        match error_region.kind() {
289            ty::ReEarlyParam(ebr) => ebr.is_named().then(|| {
290                let def_id = tcx.generics_of(self.mir_def_id()).region_param(ebr, tcx).def_id;
291                let span = tcx.hir_span_if_local(def_id).unwrap_or(DUMMY_SP);
292                RegionName { name: ebr.name, source: RegionNameSource::NamedEarlyParamRegion(span) }
293            }),
294
295            ty::ReStatic => {
296                Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })
297            }
298
299            ty::ReLateParam(late_param) => match late_param.kind {
300                ty::LateParamRegionKind::Named(region_def_id) => {
301                    // Get the span to point to, even if we don't use the name.
302                    let span = tcx.hir_span_if_local(region_def_id).unwrap_or(DUMMY_SP);
303
304                    if let Some(name) = late_param.kind.get_name(tcx) {
305                        // A named region that is actually named.
306                        Some(RegionName {
307                            name,
308                            source: RegionNameSource::NamedLateParamRegion(span),
309                        })
310                    } else if tcx.asyncness(self.mir_hir_id().owner).is_async() {
311                        // If we spuriously thought that the region is named, we should let the
312                        // system generate a true name for error messages. Currently this can
313                        // happen if we have an elided name in an async fn for example: the
314                        // compiler will generate a region named `'_`, but reporting such a name is
315                        // not actually useful, so we synthesize a name for it instead.
316                        let name = self.synthesize_region_name();
317                        Some(RegionName {
318                            name,
319                            source: RegionNameSource::AnonRegionFromAsyncFn(span),
320                        })
321                    } else {
322                        None
323                    }
324                }
325
326                ty::LateParamRegionKind::ClosureEnv => {
327                    let def_ty = self.regioncx.universal_regions().defining_ty;
328
329                    let closure_kind = match def_ty {
330                        DefiningTy::Closure(_, args) => args.as_closure().kind(),
331                        DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().kind(),
332                        _ => {
333                            // Can't have BrEnv in functions, constants or coroutines.
334                            bug!("BrEnv outside of closure.");
335                        }
336                    };
337                    let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) =
338                        tcx.hir_expect_expr(self.mir_hir_id()).kind
339                    else {
340                        bug!("Closure is not defined by a closure expr");
341                    };
342                    let region_name = self.synthesize_region_name();
343                    let note = match closure_kind {
344                        ty::ClosureKind::Fn => {
345                            "closure implements `Fn`, so references to captured variables \
346                             can't escape the closure"
347                        }
348                        ty::ClosureKind::FnMut => {
349                            "closure implements `FnMut`, so references to captured variables \
350                             can't escape the closure"
351                        }
352                        ty::ClosureKind::FnOnce => {
353                            bug!("BrEnv in a `FnOnce` closure");
354                        }
355                    };
356
357                    Some(RegionName {
358                        name: region_name,
359                        source: RegionNameSource::SynthesizedFreeEnvRegion(fn_decl_span, note),
360                    })
361                }
362
363                ty::LateParamRegionKind::Anon(_) => None,
364                ty::LateParamRegionKind::NamedAnon(_, _) => bug!("only used for pretty printing"),
365            },
366
367            ty::ReBound(..)
368            | ty::ReVar(..)
369            | ty::RePlaceholder(..)
370            | ty::ReErased
371            | ty::ReError(_) => None,
372        }
373    }
374
375    /// Finds an argument that contains `fr` and label it with a fully
376    /// elaborated type, returning something like `'1`. Result looks
377    /// like:
378    ///
379    /// ```text
380    ///  | fn foo(x: &u32) { .. }
381    ///           ------- fully elaborated type of `x` is `&'1 u32`
382    /// ```
383    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("give_name_if_anonymous_region_appears_in_arguments",
                                    "rustc_borrowck::diagnostics::region_name",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                                    ::tracing_core::__macro_support::Option::Some(383u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let implicit_inputs =
                self.regioncx.universal_regions().defining_ty.implicit_inputs();
            let argument_index =
                self.regioncx.get_argument_index_for_region(self.infcx.tcx,
                        fr)?;
            let arg_ty =
                self.regioncx.universal_regions().unnormalized_input_tys[implicit_inputs
                        + argument_index];
            let (_, span) =
                self.regioncx.get_argument_name_and_span_for_region(self.body,
                    self.local_names(), argument_index);
            let highlight =
                self.get_argument_hir_ty_for_highlighting(argument_index).and_then(|arg_hir_ty|
                            self.highlight_if_we_can_match_hir_ty(fr, arg_ty,
                                arg_hir_ty)).unwrap_or_else(||
                        {
                            let counter = *self.next_region_name.try_borrow().unwrap();
                            self.highlight_if_we_cannot_match_hir_ty(fr, arg_ty, span,
                                counter)
                        });
            Some(RegionName {
                    name: self.synthesize_region_name(),
                    source: RegionNameSource::AnonRegionFromArgument(highlight),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
384    fn give_name_if_anonymous_region_appears_in_arguments(
385        &self,
386        fr: RegionVid,
387    ) -> Option<RegionName> {
388        let implicit_inputs = self.regioncx.universal_regions().defining_ty.implicit_inputs();
389        let argument_index = self.regioncx.get_argument_index_for_region(self.infcx.tcx, fr)?;
390
391        let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys
392            [implicit_inputs + argument_index];
393        let (_, span) = self.regioncx.get_argument_name_and_span_for_region(
394            self.body,
395            self.local_names(),
396            argument_index,
397        );
398
399        let highlight = self
400            .get_argument_hir_ty_for_highlighting(argument_index)
401            .and_then(|arg_hir_ty| self.highlight_if_we_can_match_hir_ty(fr, arg_ty, arg_hir_ty))
402            .unwrap_or_else(|| {
403                // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
404                // the anonymous region. If it succeeds, the `synthesize_region_name` call below
405                // will increment the counter, "reserving" the number we just used.
406                let counter = *self.next_region_name.try_borrow().unwrap();
407                self.highlight_if_we_cannot_match_hir_ty(fr, arg_ty, span, counter)
408            });
409
410        Some(RegionName {
411            name: self.synthesize_region_name(),
412            source: RegionNameSource::AnonRegionFromArgument(highlight),
413        })
414    }
415
416    fn get_argument_hir_ty_for_highlighting(
417        &self,
418        argument_index: usize,
419    ) -> Option<&hir::Ty<'tcx>> {
420        let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(self.mir_hir_id())?;
421        let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(argument_index)?;
422        match argument_hir_ty.kind {
423            // This indicates a variable with no type annotation, like
424            // `|x|`... in that case, we can't highlight the type but
425            // must highlight the variable.
426            // NOTE(eddyb) this is handled in/by the sole caller
427            // (`give_name_if_anonymous_region_appears_in_arguments`).
428            hir::TyKind::Infer(()) => None,
429
430            _ => Some(argument_hir_ty),
431        }
432    }
433
434    /// Attempts to highlight the specific part of a type in an argument
435    /// that has no type annotation.
436    /// For example, we might produce an annotation like this:
437    ///
438    /// ```text
439    ///  |     foo(|a, b| b)
440    ///  |          -  -
441    ///  |          |  |
442    ///  |          |  has type `&'1 u32`
443    ///  |          has type `&'2 u32`
444    /// ```
445    fn highlight_if_we_cannot_match_hir_ty(
446        &self,
447        needle_fr: RegionVid,
448        ty: Ty<'tcx>,
449        span: Span,
450        counter: usize,
451    ) -> RegionNameHighlight {
452        let mut highlight = RegionHighlightMode::default();
453        highlight.highlighting_region_vid(self.infcx.tcx, needle_fr, counter);
454        let type_name =
455            self.infcx.err_ctxt().extract_inference_diagnostics_data(ty.into(), highlight).name;
456
457        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:457",
                        "rustc_borrowck::diagnostics::region_name",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                        ::tracing_core::__macro_support::Option::Some(457u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("highlight_if_we_cannot_match_hir_ty: type_name={0:?} needle_fr={1:?}",
                                                    type_name, needle_fr) as &dyn Value))])
            });
    } else { ; }
};debug!(
458            "highlight_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
459            type_name, needle_fr
460        );
461        if type_name.contains(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", counter))
    })format!("'{counter}")) {
462            // Only add a label if we can confirm that a region was labelled.
463            RegionNameHighlight::CannotMatchHirTy(span, Symbol::intern(&type_name))
464        } else {
465            RegionNameHighlight::Occluded(span, Symbol::intern(&type_name))
466        }
467    }
468
469    /// Attempts to highlight the specific part of a type annotation
470    /// that contains the anonymous reference we want to give a name
471    /// to. For example, we might produce an annotation like this:
472    ///
473    /// ```text
474    ///  | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
475    ///  |                - let's call the lifetime of this reference `'1`
476    /// ```
477    ///
478    /// the way this works is that we match up `ty`, which is
479    /// a `Ty<'tcx>` (the internal form of the type) with
480    /// `hir_ty`, a `hir::Ty` (the syntax of the type
481    /// annotation). We are descending through the types stepwise,
482    /// looking in to find the region `needle_fr` in the internal
483    /// type. Once we find that, we can use the span of the `hir::Ty`
484    /// to add the highlight.
485    ///
486    /// This is a somewhat imperfect process, so along the way we also
487    /// keep track of the **closest** type we've found. If we fail to
488    /// find the exact `&` or `'_` to highlight, then we may fall back
489    /// to highlighting that closest type instead.
490    fn highlight_if_we_can_match_hir_ty(
491        &self,
492        needle_fr: RegionVid,
493        ty: Ty<'tcx>,
494        hir_ty: &hir::Ty<'_>,
495    ) -> Option<RegionNameHighlight> {
496        let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty<'_>)> = &mut <[_]>::into_vec(::alloc::boxed::box_new([(ty, hir_ty)]))vec![(ty, hir_ty)];
497
498        while let Some((ty, hir_ty)) = search_stack.pop() {
499            match (ty.kind(), &hir_ty.kind) {
500                // Check if the `ty` is `&'X ..` where `'X`
501                // is the region we are looking for -- if so, and we have a `&T`
502                // on the RHS, then we want to highlight the `&` like so:
503                //
504                //     &
505                //     - let's call the lifetime of this reference `'1`
506                (ty::Ref(region, referent_ty, _), hir::TyKind::Ref(_lifetime, referent_hir_ty)) => {
507                    if region.as_var() == needle_fr {
508                        // Just grab the first character, the `&`.
509                        let source_map = self.infcx.tcx.sess.source_map();
510                        let ampersand_span = source_map.start_point(hir_ty.span);
511
512                        return Some(RegionNameHighlight::MatchedHirTy(ampersand_span));
513                    }
514
515                    // Otherwise, let's descend into the referent types.
516                    search_stack.push((*referent_ty, referent_hir_ty.ty));
517                }
518
519                // Match up something like `Foo<'1>`
520                (ty::Adt(_adt_def, args), hir::TyKind::Path(hir::QPath::Resolved(None, path))) => {
521                    match path.res {
522                        // Type parameters of the type alias have no reason to
523                        // be the same as those of the ADT.
524                        // FIXME: We should be able to do something similar to
525                        // match_adt_and_segment in this case.
526                        Res::Def(DefKind::TyAlias, _) => (),
527                        _ => {
528                            if let Some(last_segment) = path.segments.last()
529                                && let Some(highlight) = self.match_adt_and_segment(
530                                    args,
531                                    needle_fr,
532                                    last_segment,
533                                    search_stack,
534                                )
535                            {
536                                return Some(highlight);
537                            }
538                        }
539                    }
540                }
541
542                // The following cases don't have lifetimes, so we
543                // just worry about trying to match up the rustc type
544                // with the HIR types:
545                (&ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
546                    search_stack.extend(iter::zip(elem_tys, *elem_hir_tys));
547                }
548
549                (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
550                | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
551                    search_stack.push((*elem_ty, elem_hir_ty));
552                }
553
554                (ty::RawPtr(mut_ty, _), hir::TyKind::Ptr(mut_hir_ty)) => {
555                    search_stack.push((*mut_ty, mut_hir_ty.ty));
556                }
557
558                _ => {
559                    // FIXME there are other cases that we could trace
560                }
561            }
562        }
563
564        None
565    }
566
567    /// We've found an enum/struct/union type with the generic args
568    /// `args` and -- in the HIR -- a path type with the final
569    /// segment `last_segment`. Try to find a `'_` to highlight in
570    /// the generic args (or, if not, to produce new zipped pairs of
571    /// types+hir to search through).
572    fn match_adt_and_segment<'hir>(
573        &self,
574        args: GenericArgsRef<'tcx>,
575        needle_fr: RegionVid,
576        last_segment: &'hir hir::PathSegment<'hir>,
577        search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
578    ) -> Option<RegionNameHighlight> {
579        // Did the user give explicit arguments? (e.g., `Foo<..>`)
580        let explicit_args = last_segment.args.as_ref()?;
581        let lifetime =
582            self.try_match_adt_and_generic_args(args, needle_fr, explicit_args, search_stack)?;
583        if lifetime.is_anonymous() {
584            None
585        } else {
586            Some(RegionNameHighlight::MatchedAdtAndSegment(lifetime.ident.span))
587        }
588    }
589
590    /// We've found an enum/struct/union type with the generic args
591    /// `args` and -- in the HIR -- a path with the generic
592    /// arguments `hir_args`. If `needle_fr` appears in the args, return
593    /// the `hir::Lifetime` that corresponds to it. If not, push onto
594    /// `search_stack` the types+hir to search through.
595    fn try_match_adt_and_generic_args<'hir>(
596        &self,
597        args: GenericArgsRef<'tcx>,
598        needle_fr: RegionVid,
599        hir_args: &'hir hir::GenericArgs<'hir>,
600        search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
601    ) -> Option<&'hir hir::Lifetime> {
602        for (arg, hir_arg) in iter::zip(args, hir_args.args) {
603            match (arg.kind(), hir_arg) {
604                (GenericArgKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
605                    if r.as_var() == needle_fr {
606                        return Some(lt);
607                    }
608                }
609
610                (GenericArgKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
611                    search_stack.push((ty, hir_ty.as_unambig_ty()));
612                }
613
614                (GenericArgKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
615                    // Lifetimes cannot be found in consts, so we don't need
616                    // to search anything here.
617                }
618
619                (
620                    GenericArgKind::Lifetime(_)
621                    | GenericArgKind::Type(_)
622                    | GenericArgKind::Const(_),
623                    _,
624                ) => {
625                    self.dcx().span_delayed_bug(
626                        hir_arg.span(),
627                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unmatched arg and hir arg: found {0:?} vs {1:?}",
                arg, hir_arg))
    })format!("unmatched arg and hir arg: found {arg:?} vs {hir_arg:?}"),
628                    );
629                }
630            }
631        }
632
633        None
634    }
635
636    /// Finds a closure upvar that contains `fr` and label it with a
637    /// fully elaborated type, returning something like `'1`. Result
638    /// looks like:
639    ///
640    /// ```text
641    ///  | let x = Some(&22);
642    ///        - fully elaborated type of `x` is `Option<&'1 u32>`
643    /// ```
644    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("give_name_if_anonymous_region_appears_in_upvars",
                                    "rustc_borrowck::diagnostics::region_name",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                                    ::tracing_core::__macro_support::Option::Some(644u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let upvar_index =
                self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
            let (upvar_name, upvar_span) =
                self.regioncx.get_upvar_name_and_span_for_region(self.infcx.tcx,
                    self.upvars, upvar_index);
            let region_name = self.synthesize_region_name();
            Some(RegionName {
                    name: region_name,
                    source: RegionNameSource::AnonRegionFromUpvar(upvar_span,
                        upvar_name),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
645    fn give_name_if_anonymous_region_appears_in_upvars(&self, fr: RegionVid) -> Option<RegionName> {
646        let upvar_index = self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
647        let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
648            self.infcx.tcx,
649            self.upvars,
650            upvar_index,
651        );
652        let region_name = self.synthesize_region_name();
653
654        Some(RegionName {
655            name: region_name,
656            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
657        })
658    }
659
660    /// Checks for arguments appearing in the (closure) return type. It
661    /// must be a closure since, in a free fn, such an argument would
662    /// have to either also appear in an argument (if using elision)
663    /// or be early bound (named, not in argument).
664    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("give_name_if_anonymous_region_appears_in_output",
                                    "rustc_borrowck::diagnostics::region_name",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                                    ::tracing_core::__macro_support::Option::Some(664u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.infcx.tcx;
            let return_ty =
                self.regioncx.universal_regions().unnormalized_output_ty;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:669",
                                    "rustc_borrowck::diagnostics::region_name",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                                    ::tracing_core::__macro_support::Option::Some(669u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("give_name_if_anonymous_region_appears_in_output: return_ty = {0:?}",
                                                                return_ty) as &dyn Value))])
                        });
                } else { ; }
            };
            if !tcx.any_free_region_meets(&return_ty, |r| r.as_var() == fr) {
                return None;
            }
            let mir_hir_id = self.mir_hir_id();
            let (return_span, mir_description, hir_ty) =
                match tcx.hir_node(mir_hir_id) {
                    hir::Node::Expr(&hir::Expr {
                        kind: hir::ExprKind::Closure(&hir::Closure {
                            fn_decl, kind, fn_decl_span, .. }), .. }) => {
                        let (mut span, mut hir_ty) =
                            match fn_decl.output {
                                hir::FnRetTy::DefaultReturn(_) => {
                                    (tcx.sess.source_map().end_point(fn_decl_span), None)
                                }
                                hir::FnRetTy::Return(hir_ty) =>
                                    (fn_decl.output.span(), Some(hir_ty)),
                            };
                        let mir_description =
                            match kind {
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                    hir::CoroutineSource::Block)) => " of async block",
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                    hir::CoroutineSource::Closure)) |
                                    hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
                                    => {
                                    " of async closure"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                    hir::CoroutineSource::Fn)) => {
                                    let parent_item =
                                        tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
                                    let output =
                                        &parent_item.fn_decl().expect("coroutine lowered from async fn should be in fn").output;
                                    span = output.span();
                                    if let hir::FnRetTy::Return(ret) = output {
                                        hir_ty = Some(self.get_future_inner_return_ty(ret));
                                    }
                                    " of async function"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
                                    hir::CoroutineSource::Block)) => " of gen block",
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
                                    hir::CoroutineSource::Closure)) |
                                    hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen)
                                    => {
                                    " of gen closure"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
                                    hir::CoroutineSource::Fn)) => {
                                    let parent_item =
                                        tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
                                    let output =
                                        &parent_item.fn_decl().expect("coroutine lowered from gen fn should be in fn").output;
                                    span = output.span();
                                    " of gen function"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
                                    hir::CoroutineSource::Block)) => " of async gen block",
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
                                    hir::CoroutineSource::Closure)) |
                                    hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen)
                                    => {
                                    " of async gen closure"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
                                    hir::CoroutineSource::Fn)) => {
                                    let parent_item =
                                        tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
                                    let output =
                                        &parent_item.fn_decl().expect("coroutine lowered from async gen fn should be in fn").output;
                                    span = output.span();
                                    " of async gen function"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_))
                                    => {
                                    " of coroutine"
                                }
                                hir::ClosureKind::Closure => " of closure",
                            };
                        (span, mir_description, hir_ty)
                    }
                    node =>
                        match node.fn_decl() {
                            Some(fn_decl) => {
                                let hir_ty =
                                    match fn_decl.output {
                                        hir::FnRetTy::DefaultReturn(_) => None,
                                        hir::FnRetTy::Return(ty) => Some(ty),
                                    };
                                (fn_decl.output.span(), "", hir_ty)
                            }
                            None => (self.body.span, "", None),
                        },
                };
            let highlight =
                hir_ty.and_then(|hir_ty|
                            self.highlight_if_we_can_match_hir_ty(fr, return_ty,
                                hir_ty)).unwrap_or_else(||
                        {
                            let counter = *self.next_region_name.try_borrow().unwrap();
                            self.highlight_if_we_cannot_match_hir_ty(fr, return_ty,
                                return_span, counter)
                        });
            Some(RegionName {
                    name: self.synthesize_region_name(),
                    source: RegionNameSource::AnonRegionFromOutput(highlight,
                        mir_description),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
665    fn give_name_if_anonymous_region_appears_in_output(&self, fr: RegionVid) -> Option<RegionName> {
666        let tcx = self.infcx.tcx;
667
668        let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
669        debug!("give_name_if_anonymous_region_appears_in_output: return_ty = {:?}", return_ty);
670        if !tcx.any_free_region_meets(&return_ty, |r| r.as_var() == fr) {
671            return None;
672        }
673
674        let mir_hir_id = self.mir_hir_id();
675
676        let (return_span, mir_description, hir_ty) = match tcx.hir_node(mir_hir_id) {
677            hir::Node::Expr(&hir::Expr {
678                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl, kind, fn_decl_span, .. }),
679                ..
680            }) => {
681                let (mut span, mut hir_ty) = match fn_decl.output {
682                    hir::FnRetTy::DefaultReturn(_) => {
683                        (tcx.sess.source_map().end_point(fn_decl_span), None)
684                    }
685                    hir::FnRetTy::Return(hir_ty) => (fn_decl.output.span(), Some(hir_ty)),
686                };
687                let mir_description = match kind {
688                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
689                        hir::CoroutineDesugaring::Async,
690                        hir::CoroutineSource::Block,
691                    )) => " of async block",
692
693                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
694                        hir::CoroutineDesugaring::Async,
695                        hir::CoroutineSource::Closure,
696                    ))
697                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
698                        " of async closure"
699                    }
700
701                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
702                        hir::CoroutineDesugaring::Async,
703                        hir::CoroutineSource::Fn,
704                    )) => {
705                        let parent_item =
706                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
707                        let output = &parent_item
708                            .fn_decl()
709                            .expect("coroutine lowered from async fn should be in fn")
710                            .output;
711                        span = output.span();
712                        if let hir::FnRetTy::Return(ret) = output {
713                            hir_ty = Some(self.get_future_inner_return_ty(ret));
714                        }
715                        " of async function"
716                    }
717
718                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
719                        hir::CoroutineDesugaring::Gen,
720                        hir::CoroutineSource::Block,
721                    )) => " of gen block",
722
723                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
724                        hir::CoroutineDesugaring::Gen,
725                        hir::CoroutineSource::Closure,
726                    ))
727                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => {
728                        " of gen closure"
729                    }
730
731                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
732                        hir::CoroutineDesugaring::Gen,
733                        hir::CoroutineSource::Fn,
734                    )) => {
735                        let parent_item =
736                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
737                        let output = &parent_item
738                            .fn_decl()
739                            .expect("coroutine lowered from gen fn should be in fn")
740                            .output;
741                        span = output.span();
742                        " of gen function"
743                    }
744
745                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
746                        hir::CoroutineDesugaring::AsyncGen,
747                        hir::CoroutineSource::Block,
748                    )) => " of async gen block",
749
750                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
751                        hir::CoroutineDesugaring::AsyncGen,
752                        hir::CoroutineSource::Closure,
753                    ))
754                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
755                        " of async gen closure"
756                    }
757
758                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
759                        hir::CoroutineDesugaring::AsyncGen,
760                        hir::CoroutineSource::Fn,
761                    )) => {
762                        let parent_item =
763                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
764                        let output = &parent_item
765                            .fn_decl()
766                            .expect("coroutine lowered from async gen fn should be in fn")
767                            .output;
768                        span = output.span();
769                        " of async gen function"
770                    }
771
772                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => {
773                        " of coroutine"
774                    }
775                    hir::ClosureKind::Closure => " of closure",
776                };
777                (span, mir_description, hir_ty)
778            }
779            node => match node.fn_decl() {
780                Some(fn_decl) => {
781                    let hir_ty = match fn_decl.output {
782                        hir::FnRetTy::DefaultReturn(_) => None,
783                        hir::FnRetTy::Return(ty) => Some(ty),
784                    };
785                    (fn_decl.output.span(), "", hir_ty)
786                }
787                None => (self.body.span, "", None),
788            },
789        };
790
791        let highlight = hir_ty
792            .and_then(|hir_ty| self.highlight_if_we_can_match_hir_ty(fr, return_ty, hir_ty))
793            .unwrap_or_else(|| {
794                // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
795                // the anonymous region. If it succeeds, the `synthesize_region_name` call below
796                // will increment the counter, "reserving" the number we just used.
797                let counter = *self.next_region_name.try_borrow().unwrap();
798                self.highlight_if_we_cannot_match_hir_ty(fr, return_ty, return_span, counter)
799            });
800
801        Some(RegionName {
802            name: self.synthesize_region_name(),
803            source: RegionNameSource::AnonRegionFromOutput(highlight, mir_description),
804        })
805    }
806
807    /// From the [`hir::Ty`] of an async function's lowered return type,
808    /// retrieve the `hir::Ty` representing the type the user originally wrote.
809    ///
810    /// e.g. given the function:
811    ///
812    /// ```
813    /// async fn foo() -> i32 { 2 }
814    /// ```
815    ///
816    /// this function, given the lowered return type of `foo`, an [`OpaqueDef`] that implements
817    /// `Future<Output=i32>`, returns the `i32`.
818    ///
819    /// [`OpaqueDef`]: hir::TyKind::OpaqueDef
820    fn get_future_inner_return_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
821        let hir::TyKind::OpaqueDef(opaque_ty) = hir_ty.kind else {
822            ::rustc_middle::util::bug::span_bug_fmt(hir_ty.span,
    format_args!("lowered return type of async fn is not OpaqueDef: {0:?}",
        hir_ty));span_bug!(
823                hir_ty.span,
824                "lowered return type of async fn is not OpaqueDef: {:?}",
825                hir_ty
826            );
827        };
828        if let hir::OpaqueTy { bounds: [hir::GenericBound::Trait(trait_ref)], .. } = opaque_ty
829            && let Some(segment) = trait_ref.trait_ref.path.segments.last()
830            && let Some(args) = segment.args
831            && let [constraint] = args.constraints
832            && constraint.ident.name == sym::Output
833            && let Some(ty) = constraint.ty()
834        {
835            ty
836        } else {
837            ::rustc_middle::util::bug::span_bug_fmt(hir_ty.span,
    format_args!("bounds from lowered return type of async fn did not match expected format: {0:?}",
        opaque_ty));span_bug!(
838                hir_ty.span,
839                "bounds from lowered return type of async fn did not match expected format: {opaque_ty:?}",
840            );
841        }
842    }
843
844    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("give_name_if_anonymous_region_appears_in_yield_ty",
                                    "rustc_borrowck::diagnostics::region_name",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                                    ::tracing_core::__macro_support::Option::Some(844u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let yield_ty = self.regioncx.universal_regions().yield_ty?;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:852",
                                    "rustc_borrowck::diagnostics::region_name",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                                    ::tracing_core::__macro_support::Option::Some(852u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {0:?}",
                                                                yield_ty) as &dyn Value))])
                        });
                } else { ; }
            };
            let tcx = self.infcx.tcx;
            if !tcx.any_free_region_meets(&yield_ty, |r| r.as_var() == fr) {
                return None;
            }
            let mut highlight = RegionHighlightMode::default();
            highlight.highlighting_region_vid(tcx, fr,
                *self.next_region_name.try_borrow().unwrap());
            let type_name =
                self.infcx.err_ctxt().extract_inference_diagnostics_data(yield_ty.into(),
                        highlight).name;
            let yield_span =
                match tcx.hir_node(self.mir_hir_id()) {
                    hir::Node::Expr(&hir::Expr {
                        kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span,
                            .. }), .. }) =>
                        tcx.sess.source_map().end_point(fn_decl_span),
                    _ => self.body.span,
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:876",
                                    "rustc_borrowck::diagnostics::region_name",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_name.rs"),
                                    ::tracing_core::__macro_support::Option::Some(876u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("give_name_if_anonymous_region_appears_in_yield_ty: type_name = {0:?}, yield_span = {1:?}",
                                                                yield_span, type_name) as &dyn Value))])
                        });
                } else { ; }
            };
            Some(RegionName {
                    name: self.synthesize_region_name(),
                    source: RegionNameSource::AnonRegionFromYieldTy(yield_span,
                        Symbol::intern(&type_name)),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
845    fn give_name_if_anonymous_region_appears_in_yield_ty(
846        &self,
847        fr: RegionVid,
848    ) -> Option<RegionName> {
849        // Note: coroutines from `async fn` yield `()`, so we don't have to
850        // worry about them here.
851        let yield_ty = self.regioncx.universal_regions().yield_ty?;
852        debug!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}", yield_ty);
853
854        let tcx = self.infcx.tcx;
855
856        if !tcx.any_free_region_meets(&yield_ty, |r| r.as_var() == fr) {
857            return None;
858        }
859
860        let mut highlight = RegionHighlightMode::default();
861        highlight.highlighting_region_vid(tcx, fr, *self.next_region_name.try_borrow().unwrap());
862        let type_name = self
863            .infcx
864            .err_ctxt()
865            .extract_inference_diagnostics_data(yield_ty.into(), highlight)
866            .name;
867
868        let yield_span = match tcx.hir_node(self.mir_hir_id()) {
869            hir::Node::Expr(&hir::Expr {
870                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
871                ..
872            }) => tcx.sess.source_map().end_point(fn_decl_span),
873            _ => self.body.span,
874        };
875
876        debug!(
877            "give_name_if_anonymous_region_appears_in_yield_ty: \
878             type_name = {:?}, yield_span = {:?}",
879            yield_span, type_name,
880        );
881
882        Some(RegionName {
883            name: self.synthesize_region_name(),
884            source: RegionNameSource::AnonRegionFromYieldTy(yield_span, Symbol::intern(&type_name)),
885        })
886    }
887
888    fn give_name_if_anonymous_region_appears_in_impl_signature(
889        &self,
890        fr: RegionVid,
891    ) -> Option<RegionName> {
892        let ty::ReEarlyParam(region) = self.to_error_region(fr)?.kind() else {
893            return None;
894        };
895        if region.is_named() {
896            return None;
897        };
898
899        let tcx = self.infcx.tcx;
900        let region_def = tcx.generics_of(self.mir_def_id()).region_param(region, tcx).def_id;
901        let region_parent = tcx.parent(region_def);
902        let DefKind::Impl { .. } = tcx.def_kind(region_parent) else {
903            return None;
904        };
905
906        let found = tcx
907            .any_free_region_meets(&tcx.type_of(region_parent).instantiate_identity(), |r| {
908                r.kind() == ty::ReEarlyParam(region)
909            });
910
911        Some(RegionName {
912            name: self.synthesize_region_name(),
913            source: RegionNameSource::AnonRegionFromImplSignature(
914                tcx.def_span(region_def),
915                // FIXME(compiler-errors): Does this ever actually show up
916                // anywhere other than the self type? I couldn't create an
917                // example of a `'_` in the impl's trait being referenceable.
918                if found { "self type" } else { "header" },
919            ),
920        })
921    }
922
923    fn give_name_if_anonymous_region_appears_in_arg_position_impl_trait(
924        &self,
925        fr: RegionVid,
926    ) -> Option<RegionName> {
927        let ty::ReEarlyParam(region) = self.to_error_region(fr)?.kind() else {
928            return None;
929        };
930        if region.is_named() {
931            return None;
932        };
933
934        let predicates = self
935            .infcx
936            .tcx
937            .predicates_of(self.body.source.def_id())
938            .instantiate_identity(self.infcx.tcx)
939            .predicates;
940
941        if let Some(upvar_index) = self
942            .regioncx
943            .universal_regions()
944            .defining_ty
945            .upvar_tys()
946            .iter()
947            .position(|ty| self.any_param_predicate_mentions(&predicates, ty, region))
948        {
949            let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
950                self.infcx.tcx,
951                self.upvars,
952                upvar_index,
953            );
954            let region_name = self.synthesize_region_name();
955
956            Some(RegionName {
957                name: region_name,
958                source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
959            })
960        } else if let Some(arg_index) = self
961            .regioncx
962            .universal_regions()
963            .unnormalized_input_tys
964            .iter()
965            .position(|ty| self.any_param_predicate_mentions(&predicates, *ty, region))
966        {
967            let (arg_name, arg_span) = self.regioncx.get_argument_name_and_span_for_region(
968                self.body,
969                self.local_names(),
970                arg_index,
971            );
972            let region_name = self.synthesize_region_name();
973
974            Some(RegionName {
975                name: region_name,
976                source: RegionNameSource::AnonRegionFromArgument(
977                    RegionNameHighlight::CannotMatchHirTy(arg_span, arg_name?),
978                ),
979            })
980        } else {
981            None
982        }
983    }
984
985    fn any_param_predicate_mentions(
986        &self,
987        clauses: &[ty::Clause<'tcx>],
988        ty: Ty<'tcx>,
989        region: ty::EarlyParamRegion,
990    ) -> bool {
991        let tcx = self.infcx.tcx;
992        ty.walk().any(|arg| {
993            if let ty::GenericArgKind::Type(ty) = arg.kind()
994                && let ty::Param(_) = ty.kind()
995            {
996                clauses.iter().any(|pred| {
997                    match pred.kind().skip_binder() {
998                        ty::ClauseKind::Trait(data) if data.self_ty() == ty => {}
999                        ty::ClauseKind::Projection(data)
1000                            if data.projection_term.self_ty() == ty => {}
1001                        _ => return false,
1002                    }
1003                    tcx.any_free_region_meets(pred, |r| r.kind() == ty::ReEarlyParam(region))
1004                })
1005            } else {
1006                false
1007            }
1008        })
1009    }
1010}