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::{
10    self, GenericArgKind, GenericArgsRef, RegionUtilitiesExt, RegionVid, Ty, Unnormalized,
11};
12use rustc_middle::{bug, span_bug};
13use rustc_span::{DUMMY_SP, Span, Symbol, kw, sym};
14use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
15use tracing::{debug, instrument};
16
17use crate::MirBorrowckCtxt;
18use crate::universal_regions::DefiningTy;
19
20/// A name for a particular region used in emitting diagnostics. This name could be a generated
21/// name like `'1`, a name used by the user like `'a`, or a name like `'static`.
22#[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)]
23pub(crate) struct RegionName {
24    /// The name of the region (interned).
25    pub(crate) name: Symbol,
26    /// Where the region comes from.
27    pub(crate) source: RegionNameSource,
28}
29
30/// Denotes the source of a region that is named by a `RegionName`. For example, a free region that
31/// was named by the user would get `NamedLateParamRegion` and `'static` lifetime would get
32/// `Static`. This helps to print the right kinds of diagnostics.
33#[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)]
34pub(crate) enum RegionNameSource {
35    /// A bound (not free) region that was instantiated at the def site (not an HRTB).
36    NamedEarlyParamRegion(Span),
37    /// A free region that the user has a name (`'a`) for.
38    NamedLateParamRegion(Span),
39    /// The `'static` region.
40    Static,
41    /// The free region corresponding to the environment of a closure.
42    SynthesizedFreeEnvRegion(Span, &'static str),
43    /// The region corresponding to an argument.
44    AnonRegionFromArgument(RegionNameHighlight),
45    /// The region corresponding to a closure upvar.
46    AnonRegionFromUpvar(Span, Symbol),
47    /// The region corresponding to the return type of a closure.
48    AnonRegionFromOutput(RegionNameHighlight, &'static str),
49    /// The region from a type yielded by a coroutine.
50    AnonRegionFromYieldTy(Span, Symbol),
51    /// An anonymous region from an async fn.
52    AnonRegionFromAsyncFn(Span),
53    /// An anonymous region from an impl self type or trait
54    AnonRegionFromImplSignature(Span, &'static str),
55}
56
57/// Describes what to highlight to explain to the user that we're giving an anonymous region a
58/// synthesized name, and how to highlight it.
59#[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)]
60pub(crate) enum RegionNameHighlight {
61    /// The anonymous region corresponds to a reference that was found by traversing the type in the HIR.
62    MatchedHirTy(Span),
63    /// The anonymous region corresponds to a `'_` in the generics list of a struct/enum/union.
64    MatchedAdtAndSegment(Span),
65    /// The anonymous region corresponds to a region where the type annotation is completely missing
66    /// from the code, e.g. in a closure arguments `|x| { ... }`, where `x` is a reference.
67    CannotMatchHirTy(Span, Symbol),
68    /// The anonymous region corresponds to a region where the type annotation is completely missing
69    /// from the code, and *even if* we print out the full name of the type, the region name won't
70    /// be included. This currently occurs for opaque types like `impl Future`.
71    Occluded(Span, Symbol),
72}
73
74impl RegionName {
75    pub(crate) fn was_named(&self) -> bool {
76        match self.source {
77            RegionNameSource::NamedEarlyParamRegion(..)
78            | RegionNameSource::NamedLateParamRegion(..)
79            | RegionNameSource::Static => true,
80            RegionNameSource::SynthesizedFreeEnvRegion(..)
81            | RegionNameSource::AnonRegionFromArgument(..)
82            | RegionNameSource::AnonRegionFromUpvar(..)
83            | RegionNameSource::AnonRegionFromOutput(..)
84            | RegionNameSource::AnonRegionFromYieldTy(..)
85            | RegionNameSource::AnonRegionFromAsyncFn(..)
86            | RegionNameSource::AnonRegionFromImplSignature(..) => false,
87        }
88    }
89
90    pub(crate) fn span(&self) -> Option<Span> {
91        match self.source {
92            RegionNameSource::Static => None,
93            RegionNameSource::NamedEarlyParamRegion(span)
94            | RegionNameSource::NamedLateParamRegion(span)
95            | RegionNameSource::SynthesizedFreeEnvRegion(span, _)
96            | RegionNameSource::AnonRegionFromUpvar(span, _)
97            | RegionNameSource::AnonRegionFromYieldTy(span, _)
98            | RegionNameSource::AnonRegionFromAsyncFn(span)
99            | RegionNameSource::AnonRegionFromImplSignature(span, _) => Some(span),
100            RegionNameSource::AnonRegionFromArgument(ref highlight)
101            | RegionNameSource::AnonRegionFromOutput(ref highlight, _) => match *highlight {
102                RegionNameHighlight::MatchedHirTy(span)
103                | RegionNameHighlight::MatchedAdtAndSegment(span)
104                | RegionNameHighlight::CannotMatchHirTy(span, _)
105                | RegionNameHighlight::Occluded(span, _) => Some(span),
106            },
107        }
108    }
109
110    pub(crate) fn highlight_region_name<G: EmissionGuarantee>(&self, diag: &mut Diag<'_, G>) {
111        match &self.source {
112            RegionNameSource::NamedLateParamRegion(span)
113            | RegionNameSource::NamedEarlyParamRegion(span) => {
114                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` defined here",
                self))
    })format!("lifetime `{self}` defined here"));
115            }
116            RegionNameSource::SynthesizedFreeEnvRegion(span, closure_trait) => {
117                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"));
118                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("closure implements `{0}`, so references to captured variables can\'t escape the closure",
                closure_trait))
    })format!(
119                    "closure implements `{closure_trait}`, so references to captured variables \
120                     can't escape the closure"
121                ));
122            }
123            RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::CannotMatchHirTy(
124                span,
125                type_name,
126            )) => {
127                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("has type `{0}`", type_name))
    })format!("has type `{type_name}`"));
128            }
129            RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::MatchedHirTy(span))
130            | RegionNameSource::AnonRegionFromOutput(RegionNameHighlight::MatchedHirTy(span), _)
131            | RegionNameSource::AnonRegionFromAsyncFn(span) => {
132                diag.span_label(
133                    *span,
134                    ::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}`"),
135                );
136            }
137            RegionNameSource::AnonRegionFromArgument(
138                RegionNameHighlight::MatchedAdtAndSegment(span),
139            )
140            | RegionNameSource::AnonRegionFromOutput(
141                RegionNameHighlight::MatchedAdtAndSegment(span),
142                _,
143            ) => {
144                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}`"));
145            }
146            RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::Occluded(
147                span,
148                type_name,
149            )) => {
150                diag.span_label(
151                    *span,
152                    ::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}`"),
153                );
154            }
155            RegionNameSource::AnonRegionFromOutput(
156                RegionNameHighlight::Occluded(span, type_name),
157                mir_description,
158            ) => {
159                diag.span_label(
160                    *span,
161                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("return type{0} `{1}` contains a lifetime `{2}`",
                mir_description, type_name, self))
    })format!(
162                        "return type{mir_description} `{type_name}` contains a lifetime `{self}`"
163                    ),
164                );
165            }
166            RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
167                diag.span_label(
168                    *span,
169                    ::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}`"),
170                );
171            }
172            RegionNameSource::AnonRegionFromOutput(
173                RegionNameHighlight::CannotMatchHirTy(span, type_name),
174                mir_description,
175            ) => {
176                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}"));
177            }
178            RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
179                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}"));
180            }
181            RegionNameSource::AnonRegionFromImplSignature(span, location) => {
182                diag.span_label(
183                    *span,
184                    ::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}"),
185                );
186            }
187            RegionNameSource::Static => {}
188        }
189    }
190}
191
192impl Display for RegionName {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        f.write_fmt(format_args!("{0}", self.name))write!(f, "{}", self.name)
195    }
196}
197
198impl rustc_errors::IntoDiagArg for RegionName {
199    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
200        self.to_string().into_diag_arg(path)
201    }
202}
203
204impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
205    pub(crate) fn mir_def_id(&self) -> hir::def_id::LocalDefId {
206        self.body.source.def_id().expect_local()
207    }
208
209    pub(crate) fn mir_hir_id(&self) -> hir::HirId {
210        self.infcx.tcx.local_def_id_to_hir_id(self.mir_def_id())
211    }
212
213    /// Generate a synthetic region named `'N`, where `N` is the next value of the counter. Then,
214    /// increment the counter.
215    ///
216    /// This is _not_ idempotent. Call `give_region_a_name` when possible.
217    pub(crate) fn synthesize_region_name(&self) -> Symbol {
218        let c = self.next_region_name.replace_with(|counter| *counter + 1);
219        Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0:?}", c))
    })format!("'{c:?}"))
220    }
221
222    /// Maps from an internal MIR region vid to something that we can
223    /// report to the user. In some cases, the region vids will map
224    /// directly to lifetimes that the user has a name for (e.g.,
225    /// `'static`). But frequently they will not, in which case we
226    /// have to find some way to identify the lifetime to the user. To
227    /// that end, this function takes a "diagnostic" so that it can
228    /// create auxiliary notes as needed.
229    ///
230    /// The names are memoized, so this is both cheap to recompute and idempotent.
231    ///
232    /// Example (function arguments):
233    ///
234    /// Suppose we are trying to give a name to the lifetime of the
235    /// reference `x`:
236    ///
237    /// ```ignore (pseudo-rust)
238    /// fn foo(x: &u32) { .. }
239    /// ```
240    ///
241    /// This function would create a label like this:
242    ///
243    /// ```text
244    ///  | fn foo(x: &u32) { .. }
245    ///           ------- fully elaborated type of `x` is `&'1 u32`
246    /// ```
247    ///
248    /// and then return the name `'1` for us to use.
249    pub(crate) fn give_region_a_name(&self, fr: RegionVid) -> Option<RegionName> {
250        {
    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:250",
                        "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(250u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
251            "give_region_a_name(fr={:?}, counter={:?})",
252            fr,
253            self.next_region_name.try_borrow().unwrap()
254        );
255
256        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));
257
258        match self.region_names.borrow_mut().entry(fr) {
259            IndexEntry::Occupied(precomputed_name) => Some(*precomputed_name.get()),
260            IndexEntry::Vacant(slot) => {
261                let new_name = self
262                    .give_name_from_error_region(fr)
263                    .or_else(|| self.give_name_if_anonymous_region_appears_in_arguments(fr))
264                    .or_else(|| self.give_name_if_anonymous_region_appears_in_upvars(fr))
265                    .or_else(|| self.give_name_if_anonymous_region_appears_in_output(fr))
266                    .or_else(|| self.give_name_if_anonymous_region_appears_in_yield_ty(fr))
267                    .or_else(|| self.give_name_if_anonymous_region_appears_in_impl_signature(fr))
268                    .or_else(|| {
269                        self.give_name_if_anonymous_region_appears_in_arg_position_impl_trait(fr)
270                    });
271
272                if let Some(new_name) = new_name {
273                    slot.insert(new_name);
274                }
275                {
    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:275",
                        "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(275u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("give_region_a_name: gave name {0:?}",
                                                    new_name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("give_region_a_name: gave name {:?}", new_name);
276
277                new_name
278            }
279        }
280    }
281
282    /// Checks for the case where `fr` maps to something that the
283    /// *user* has a name for. In that case, we'll be able to map
284    /// `fr` to a `Region<'tcx>`, and that region will be one of
285    /// named variants.
286    #[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(286u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fr");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn ::tracing::field::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.regioncx.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:292",
                                    "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(292u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("give_region_a_name: error_region = {0:?}",
                                                                error_region) as &dyn ::tracing::field::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 (is_lending_coroutine_closure, closure_kind) =
                                match def_ty {
                                    DefiningTy::Closure(_, args) =>
                                        (false, args.as_closure().kind()),
                                    DefiningTy::CoroutineClosure(_, args) => {
                                        let args = args.as_coroutine_closure();
                                        (!args.tupled_upvars_ty().is_ty_var() &&
                                                args.has_self_borrows(), args.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 closure_trait =
                                match (is_lending_coroutine_closure, closure_kind) {
                                    (false, kind) => kind.as_str(),
                                    (true, ty::ClosureKind::Fn) => "AsyncFn",
                                    (true, ty::ClosureKind::FnMut) => "AsyncFnMut",
                                    (true, ty::ClosureKind::FnOnce) => "AsyncFnOnce",
                                };
                            Some(RegionName {
                                    name: region_name,
                                    source: RegionNameSource::SynthesizedFreeEnvRegion(fn_decl_span,
                                        closure_trait),
                                })
                        }
                        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))]
287    fn give_name_from_error_region(&self, fr: RegionVid) -> Option<RegionName> {
288        let error_region = self.regioncx.to_error_region(fr)?;
289
290        let tcx = self.infcx.tcx;
291
292        debug!("give_region_a_name: error_region = {:?}", error_region);
293        match error_region.kind() {
294            ty::ReEarlyParam(ebr) => ebr.is_named().then(|| {
295                let def_id = tcx.generics_of(self.mir_def_id()).region_param(ebr, tcx).def_id;
296                let span = tcx.hir_span_if_local(def_id).unwrap_or(DUMMY_SP);
297                RegionName { name: ebr.name, source: RegionNameSource::NamedEarlyParamRegion(span) }
298            }),
299
300            ty::ReStatic => {
301                Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })
302            }
303
304            ty::ReLateParam(late_param) => match late_param.kind {
305                ty::LateParamRegionKind::Named(region_def_id) => {
306                    // Get the span to point to, even if we don't use the name.
307                    let span = tcx.hir_span_if_local(region_def_id).unwrap_or(DUMMY_SP);
308
309                    if let Some(name) = late_param.kind.get_name(tcx) {
310                        // A named region that is actually named.
311                        Some(RegionName {
312                            name,
313                            source: RegionNameSource::NamedLateParamRegion(span),
314                        })
315                    } else if tcx.asyncness(self.mir_hir_id().owner).is_async() {
316                        // If we spuriously thought that the region is named, we should let the
317                        // system generate a true name for error messages. Currently this can
318                        // happen if we have an elided name in an async fn for example: the
319                        // compiler will generate a region named `'_`, but reporting such a name is
320                        // not actually useful, so we synthesize a name for it instead.
321                        let name = self.synthesize_region_name();
322                        Some(RegionName {
323                            name,
324                            source: RegionNameSource::AnonRegionFromAsyncFn(span),
325                        })
326                    } else {
327                        None
328                    }
329                }
330
331                ty::LateParamRegionKind::ClosureEnv => {
332                    let def_ty = self.regioncx.universal_regions().defining_ty;
333
334                    let (is_lending_coroutine_closure, closure_kind) = match def_ty {
335                        DefiningTy::Closure(_, args) => (false, args.as_closure().kind()),
336                        DefiningTy::CoroutineClosure(_, args) => {
337                            let args = args.as_coroutine_closure();
338                            (
339                                !args.tupled_upvars_ty().is_ty_var() && args.has_self_borrows(),
340                                args.kind(),
341                            )
342                        }
343                        _ => {
344                            // Can't have BrEnv in functions, constants or coroutines.
345                            bug!("BrEnv outside of closure.");
346                        }
347                    };
348                    let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) =
349                        tcx.hir_expect_expr(self.mir_hir_id()).kind
350                    else {
351                        bug!("Closure is not defined by a closure expr");
352                    };
353                    let region_name = self.synthesize_region_name();
354                    let closure_trait = match (is_lending_coroutine_closure, closure_kind) {
355                        (false, kind) => kind.as_str(),
356                        (true, ty::ClosureKind::Fn) => "AsyncFn",
357                        (true, ty::ClosureKind::FnMut) => "AsyncFnMut",
358                        (true, ty::ClosureKind::FnOnce) => "AsyncFnOnce",
359                    };
360
361                    Some(RegionName {
362                        name: region_name,
363                        source: RegionNameSource::SynthesizedFreeEnvRegion(
364                            fn_decl_span,
365                            closure_trait,
366                        ),
367                    })
368                }
369
370                ty::LateParamRegionKind::Anon(_) => None,
371                ty::LateParamRegionKind::NamedAnon(_, _) => bug!("only used for pretty printing"),
372            },
373
374            ty::ReBound(..)
375            | ty::ReVar(..)
376            | ty::RePlaceholder(..)
377            | ty::ReErased
378            | ty::ReError(_) => None,
379        }
380    }
381
382    /// For closure/coroutine upvar regions, attempts to find a named lifetime
383    /// from the parent function's signature that corresponds to the anonymous
384    /// region `fr`. This handles cases where a parent function's named lifetime
385    /// (like `'a`) appears in a captured variable's type but gets assigned a
386    /// separate `RegionVid` without an `external_name` during region renumbering.
387    ///
388    /// Works by getting the parent function's parameter type (with real named
389    /// lifetimes via `liberate_late_bound_regions`), then structurally walking
390    /// both the parent's parameter type and the closure's upvar type to find
391    /// where `fr` appears and what named lifetime is at the same position.
392    #[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_we_can_match_upvar_args",
                                    "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(392u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("upvar_index")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("upvar_index");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&upvar_index as
                                                            &dyn ::tracing::field::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 defining_ty = self.regioncx.universal_regions().defining_ty;
            let closure_def_id =
                match defining_ty {
                    DefiningTy::Closure(def_id, _) |
                        DefiningTy::Coroutine(def_id, _) |
                        DefiningTy::CoroutineClosure(def_id, _) => def_id,
                    _ => return None,
                };
            let parent_def_id = tcx.parent(closure_def_id);
            if !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(parent_def_id)
                        {
                        DefKind::Fn | DefKind::AssocFn => true,
                        _ => false,
                    } {
                return None;
            }
            let captured_place = self.upvars.get(upvar_index)?;
            let upvar_hir_id = captured_place.get_root_variable();
            let parent_local_def_id = parent_def_id.as_local()?;
            let parent_body = tcx.hir_body_owned_by(parent_local_def_id);
            let param_index =
                parent_body.params.iter().position(|param|
                            param.pat.hir_id == upvar_hir_id)?;
            let parent_fn_sig =
                tcx.fn_sig(parent_def_id).instantiate_identity().skip_norm_wip();
            let liberated_sig =
                tcx.liberate_late_bound_regions(parent_def_id, parent_fn_sig);
            let parent_param_ty = *liberated_sig.inputs().get(param_index)?;
            let upvar_nll_ty = *defining_ty.upvar_tys().get(upvar_index)?;
            {
                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:435",
                                    "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(435u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("give_name_if_we_can_match_upvar_args: parent_param_ty={0:?}, upvar_nll_ty={1:?}",
                                                                parent_param_ty, upvar_nll_ty) as
                                                        &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let mut parent_regions = ::alloc::vec::Vec::new();
            tcx.for_each_free_region(&parent_param_ty,
                |r| parent_regions.push(r));
            let mut nll_regions = ::alloc::vec::Vec::new();
            tcx.for_each_free_region(&upvar_nll_ty, |r| nll_regions.push(r));
            if parent_regions.len() != nll_regions.len() {
                {
                    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:452",
                                        "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(452u32),
                                        ::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};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("give_name_if_we_can_match_upvar_args: region count mismatch ({0} vs {1})",
                                                                    parent_regions.len(), nll_regions.len()) as
                                                            &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return None;
            }
            for (parent_r, nll_r) in iter::zip(&parent_regions, &nll_regions)
                {
                if nll_r.as_var() == fr {
                    match parent_r.kind() {
                        ty::ReLateParam(late_param) => {
                            if let Some(name) = late_param.kind.get_name(tcx) {
                                let span =
                                    late_param.kind.get_id().and_then(|id|
                                                tcx.hir_span_if_local(id)).unwrap_or(DUMMY_SP);
                                return Some(RegionName {
                                            name,
                                            source: RegionNameSource::NamedLateParamRegion(span),
                                        });
                            }
                        }
                        ty::ReEarlyParam(ebr) => {
                            if ebr.is_named() {
                                let def_id =
                                    tcx.generics_of(parent_def_id).region_param(ebr,
                                            tcx).def_id;
                                let span =
                                    tcx.hir_span_if_local(def_id).unwrap_or(DUMMY_SP);
                                return Some(RegionName {
                                            name: ebr.name,
                                            source: RegionNameSource::NamedEarlyParamRegion(span),
                                        });
                            }
                        }
                        _ => {}
                    }
                }
            }
            None
        }
    }
}#[instrument(level = "trace", skip(self))]
393    fn give_name_if_we_can_match_upvar_args(
394        &self,
395        fr: RegionVid,
396        upvar_index: usize,
397    ) -> Option<RegionName> {
398        let tcx = self.infcx.tcx;
399        let defining_ty = self.regioncx.universal_regions().defining_ty;
400
401        let closure_def_id = match defining_ty {
402            DefiningTy::Closure(def_id, _)
403            | DefiningTy::Coroutine(def_id, _)
404            | DefiningTy::CoroutineClosure(def_id, _) => def_id,
405            _ => return None,
406        };
407
408        let parent_def_id = tcx.parent(closure_def_id);
409
410        // Only works if the parent is a function with a fn_sig.
411        if !matches!(tcx.def_kind(parent_def_id), DefKind::Fn | DefKind::AssocFn) {
412            return None;
413        }
414
415        // Find which parameter index this upvar corresponds to by matching
416        // the captured variable's HirId against the parent's parameter patterns.
417        // This only matches simple bindings (not destructuring patterns) and
418        // only when the upvar is a direct parameter (not a local variable).
419        let captured_place = self.upvars.get(upvar_index)?;
420        let upvar_hir_id = captured_place.get_root_variable();
421        let parent_local_def_id = parent_def_id.as_local()?;
422        let parent_body = tcx.hir_body_owned_by(parent_local_def_id);
423        let param_index =
424            parent_body.params.iter().position(|param| param.pat.hir_id == upvar_hir_id)?;
425
426        // Get the parent fn's signature with liberated late-bound regions,
427        // so we have `ReLateParam` instead of `ReBound`.
428        let parent_fn_sig = tcx.fn_sig(parent_def_id).instantiate_identity().skip_norm_wip();
429        let liberated_sig = tcx.liberate_late_bound_regions(parent_def_id, parent_fn_sig);
430        let parent_param_ty = *liberated_sig.inputs().get(param_index)?;
431
432        // Get the upvar's NLL type (with ReVar regions from renumbering).
433        let upvar_nll_ty = *defining_ty.upvar_tys().get(upvar_index)?;
434
435        debug!(
436            "give_name_if_we_can_match_upvar_args: parent_param_ty={:?}, upvar_nll_ty={:?}",
437            parent_param_ty, upvar_nll_ty
438        );
439
440        // Collect free regions from both types in structural order.
441        // This only works when both types have the same structure, i.e.
442        // the upvar captures the whole variable, not a partial place like
443        // `x.field`. Bail out if the region counts differ, since that means
444        // the types diverged and positional correspondence is unreliable.
445        let mut parent_regions = vec![];
446        tcx.for_each_free_region(&parent_param_ty, |r| parent_regions.push(r));
447
448        let mut nll_regions = vec![];
449        tcx.for_each_free_region(&upvar_nll_ty, |r| nll_regions.push(r));
450
451        if parent_regions.len() != nll_regions.len() {
452            debug!(
453                "give_name_if_we_can_match_upvar_args: region count mismatch ({} vs {})",
454                parent_regions.len(),
455                nll_regions.len()
456            );
457            return None;
458        }
459
460        for (parent_r, nll_r) in iter::zip(&parent_regions, &nll_regions) {
461            if nll_r.as_var() == fr {
462                match parent_r.kind() {
463                    ty::ReLateParam(late_param) => {
464                        if let Some(name) = late_param.kind.get_name(tcx) {
465                            let span = late_param
466                                .kind
467                                .get_id()
468                                .and_then(|id| tcx.hir_span_if_local(id))
469                                .unwrap_or(DUMMY_SP);
470                            return Some(RegionName {
471                                name,
472                                source: RegionNameSource::NamedLateParamRegion(span),
473                            });
474                        }
475                    }
476                    ty::ReEarlyParam(ebr) => {
477                        if ebr.is_named() {
478                            let def_id =
479                                tcx.generics_of(parent_def_id).region_param(ebr, tcx).def_id;
480                            let span = tcx.hir_span_if_local(def_id).unwrap_or(DUMMY_SP);
481                            return Some(RegionName {
482                                name: ebr.name,
483                                source: RegionNameSource::NamedEarlyParamRegion(span),
484                            });
485                        }
486                    }
487                    _ => {}
488                }
489            }
490        }
491
492        None
493    }
494
495    /// Finds an argument that contains `fr` and label it with a fully
496    /// elaborated type, returning something like `'1`. Result looks
497    /// like:
498    ///
499    /// ```text
500    ///  | fn foo(x: &u32) { .. }
501    ///           ------- fully elaborated type of `x` is `&'1 u32`
502    /// ```
503    #[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(503u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fr");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn ::tracing::field::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 user_arg_index =
                self.regioncx.get_user_arg_index_for_region(self.infcx.tcx,
                        fr)?;
            let arg_ty =
                self.regioncx.universal_regions().unnormalized_input_tys[implicit_inputs
                        + user_arg_index];
            let (_, span) =
                self.regioncx.get_argument_name_and_span_for_region(self.body,
                    self.local_names(), user_arg_index);
            let highlight =
                self.get_argument_hir_ty_for_highlighting(user_arg_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))]
504    fn give_name_if_anonymous_region_appears_in_arguments(
505        &self,
506        fr: RegionVid,
507    ) -> Option<RegionName> {
508        let implicit_inputs = self.regioncx.universal_regions().defining_ty.implicit_inputs();
509        let user_arg_index = self.regioncx.get_user_arg_index_for_region(self.infcx.tcx, fr)?;
510
511        let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys
512            [implicit_inputs + user_arg_index];
513        let (_, span) = self.regioncx.get_argument_name_and_span_for_region(
514            self.body,
515            self.local_names(),
516            user_arg_index,
517        );
518
519        let highlight = self
520            .get_argument_hir_ty_for_highlighting(user_arg_index)
521            .and_then(|arg_hir_ty| self.highlight_if_we_can_match_hir_ty(fr, arg_ty, arg_hir_ty))
522            .unwrap_or_else(|| {
523                // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
524                // the anonymous region. If it succeeds, the `synthesize_region_name` call below
525                // will increment the counter, "reserving" the number we just used.
526                let counter = *self.next_region_name.try_borrow().unwrap();
527                self.highlight_if_we_cannot_match_hir_ty(fr, arg_ty, span, counter)
528            });
529
530        Some(RegionName {
531            name: self.synthesize_region_name(),
532            source: RegionNameSource::AnonRegionFromArgument(highlight),
533        })
534    }
535
536    fn get_argument_hir_ty_for_highlighting(
537        &self,
538        user_arg_index: usize,
539    ) -> Option<&hir::Ty<'tcx>> {
540        let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(self.mir_hir_id())?;
541        // Closures don't have implicit self arguments in HIR, so use `user_arg_index` directly.
542        let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(user_arg_index)?;
543        match argument_hir_ty.kind {
544            // This indicates a variable with no type annotation, like
545            // `|x|`... in that case, we can't highlight the type but
546            // must highlight the variable.
547            // NOTE(eddyb) this is handled in/by the sole caller
548            // (`give_name_if_anonymous_region_appears_in_arguments`).
549            hir::TyKind::Infer(()) => None,
550
551            _ => Some(argument_hir_ty),
552        }
553    }
554
555    /// Attempts to highlight the specific part of a type in an argument
556    /// that has no type annotation.
557    /// For example, we might produce an annotation like this:
558    ///
559    /// ```text
560    ///  |     foo(|a, b| b)
561    ///  |          -  -
562    ///  |          |  |
563    ///  |          |  has type `&'1 u32`
564    ///  |          has type `&'2 u32`
565    /// ```
566    fn highlight_if_we_cannot_match_hir_ty(
567        &self,
568        needle_fr: RegionVid,
569        ty: Ty<'tcx>,
570        span: Span,
571        counter: usize,
572    ) -> RegionNameHighlight {
573        let mut highlight = RegionHighlightMode::default();
574        highlight.highlighting_region_vid(self.infcx.tcx, needle_fr, counter);
575        let type_name =
576            self.infcx.err_ctxt().extract_inference_diagnostics_data(ty.into(), highlight).name;
577
578        {
    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:578",
                        "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(578u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
579            "highlight_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
580            type_name, needle_fr
581        );
582        if type_name.contains(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", counter))
    })format!("'{counter}")) {
583            // Only add a label if we can confirm that a region was labelled.
584            RegionNameHighlight::CannotMatchHirTy(span, Symbol::intern(&type_name))
585        } else {
586            RegionNameHighlight::Occluded(span, Symbol::intern(&type_name))
587        }
588    }
589
590    /// Attempts to highlight the specific part of a type annotation
591    /// that contains the anonymous reference we want to give a name
592    /// to. For example, we might produce an annotation like this:
593    ///
594    /// ```text
595    ///  | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
596    ///  |                - let's call the lifetime of this reference `'1`
597    /// ```
598    ///
599    /// the way this works is that we match up `ty`, which is
600    /// a `Ty<'tcx>` (the internal form of the type) with
601    /// `hir_ty`, a `hir::Ty` (the syntax of the type
602    /// annotation). We are descending through the types stepwise,
603    /// looking in to find the region `needle_fr` in the internal
604    /// type. Once we find that, we can use the span of the `hir::Ty`
605    /// to add the highlight.
606    ///
607    /// This is a somewhat imperfect process, so along the way we also
608    /// keep track of the **closest** type we've found. If we fail to
609    /// find the exact `&` or `'_` to highlight, then we may fall back
610    /// to highlighting that closest type instead.
611    fn highlight_if_we_can_match_hir_ty(
612        &self,
613        needle_fr: RegionVid,
614        ty: Ty<'tcx>,
615        hir_ty: &hir::Ty<'_>,
616    ) -> Option<RegionNameHighlight> {
617        let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty<'_>)> = &mut ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ty, hir_ty)]))vec![(ty, hir_ty)];
618
619        while let Some((ty, hir_ty)) = search_stack.pop() {
620            match (ty.kind(), &hir_ty.kind) {
621                // Check if the `ty` is `&'X ..` where `'X`
622                // is the region we are looking for -- if so, and we have a `&T`
623                // on the RHS, then we want to highlight the `&` like so:
624                //
625                //     &
626                //     - let's call the lifetime of this reference `'1`
627                (ty::Ref(region, referent_ty, _), hir::TyKind::Ref(_lifetime, referent_hir_ty)) => {
628                    if region.as_var() == needle_fr {
629                        // Just grab the first character, the `&`.
630                        let source_map = self.infcx.tcx.sess.source_map();
631                        let ampersand_span = source_map.start_point(hir_ty.span);
632
633                        return Some(RegionNameHighlight::MatchedHirTy(ampersand_span));
634                    }
635
636                    // Otherwise, let's descend into the referent types.
637                    search_stack.push((*referent_ty, referent_hir_ty.ty));
638                }
639
640                // Match up something like `Foo<'1>`
641                (ty::Adt(_adt_def, args), hir::TyKind::Path(hir::QPath::Resolved(None, path))) => {
642                    match path.res {
643                        // Type parameters of the type alias have no reason to
644                        // be the same as those of the ADT.
645                        // FIXME: We should be able to do something similar to
646                        // match_adt_and_segment in this case.
647                        Res::Def(DefKind::TyAlias, _) => (),
648                        _ => {
649                            if let Some(last_segment) = path.segments.last()
650                                && let Some(highlight) = self.match_adt_and_segment(
651                                    args,
652                                    needle_fr,
653                                    last_segment,
654                                    search_stack,
655                                )
656                            {
657                                return Some(highlight);
658                            }
659                        }
660                    }
661                }
662
663                // The following cases don't have lifetimes, so we
664                // just worry about trying to match up the rustc type
665                // with the HIR types:
666                (&ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
667                    search_stack.extend(iter::zip(elem_tys, *elem_hir_tys));
668                }
669
670                (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
671                | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
672                    search_stack.push((*elem_ty, elem_hir_ty));
673                }
674
675                (ty::RawPtr(mut_ty, _), hir::TyKind::Ptr(mut_hir_ty)) => {
676                    search_stack.push((*mut_ty, mut_hir_ty.ty));
677                }
678
679                _ => {
680                    // FIXME there are other cases that we could trace
681                }
682            }
683        }
684
685        None
686    }
687
688    /// We've found an enum/struct/union type with the generic args
689    /// `args` and -- in the HIR -- a path type with the final
690    /// segment `last_segment`. Try to find a `'_` to highlight in
691    /// the generic args (or, if not, to produce new zipped pairs of
692    /// types+hir to search through).
693    fn match_adt_and_segment<'hir>(
694        &self,
695        args: GenericArgsRef<'tcx>,
696        needle_fr: RegionVid,
697        last_segment: &'hir hir::PathSegment<'hir>,
698        search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
699    ) -> Option<RegionNameHighlight> {
700        // Did the user give explicit arguments? (e.g., `Foo<..>`)
701        let explicit_args = last_segment.args.as_ref()?;
702        let lifetime =
703            self.try_match_adt_and_generic_args(args, needle_fr, explicit_args, search_stack)?;
704        if lifetime.is_anonymous() {
705            None
706        } else {
707            Some(RegionNameHighlight::MatchedAdtAndSegment(lifetime.ident.span))
708        }
709    }
710
711    /// We've found an enum/struct/union type with the generic args
712    /// `args` and -- in the HIR -- a path with the generic
713    /// arguments `hir_args`. If `needle_fr` appears in the args, return
714    /// the `hir::Lifetime` that corresponds to it. If not, push onto
715    /// `search_stack` the types+hir to search through.
716    fn try_match_adt_and_generic_args<'hir>(
717        &self,
718        args: GenericArgsRef<'tcx>,
719        needle_fr: RegionVid,
720        hir_args: &'hir hir::GenericArgs<'hir>,
721        search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
722    ) -> Option<&'hir hir::Lifetime> {
723        for (arg, hir_arg) in iter::zip(args, hir_args.args) {
724            match (arg.kind(), hir_arg) {
725                (GenericArgKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
726                    if r.as_var() == needle_fr {
727                        return Some(lt);
728                    }
729                }
730
731                (GenericArgKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
732                    search_stack.push((ty, hir_ty.as_unambig_ty()));
733                }
734
735                (GenericArgKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
736                    // Lifetimes cannot be found in consts, so we don't need
737                    // to search anything here.
738                }
739
740                (
741                    GenericArgKind::Lifetime(_)
742                    | GenericArgKind::Type(_)
743                    | GenericArgKind::Const(_),
744                    _,
745                ) => {
746                    self.dcx().span_delayed_bug(
747                        hir_arg.span(),
748                        ::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:?}"),
749                    );
750                }
751            }
752        }
753
754        None
755    }
756
757    /// Finds a closure upvar that contains `fr` and label it with a
758    /// fully elaborated type, returning something like `'1`. Result
759    /// looks like:
760    ///
761    /// ```text
762    ///  | let x = Some(&22);
763    ///        - fully elaborated type of `x` is `Option<&'1 u32>`
764    /// ```
765    #[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(765u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fr");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn ::tracing::field::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)?;
            if let Some(region_name) =
                    self.give_name_if_we_can_match_upvar_args(fr, upvar_index) {
                return Some(region_name);
            }
            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))]
766    fn give_name_if_anonymous_region_appears_in_upvars(&self, fr: RegionVid) -> Option<RegionName> {
767        let upvar_index = self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
768
769        // Before synthesizing an anonymous name like `'1`, try to find a
770        // named lifetime from the parent function's signature that matches.
771        if let Some(region_name) = self.give_name_if_we_can_match_upvar_args(fr, upvar_index) {
772            return Some(region_name);
773        }
774
775        let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
776            self.infcx.tcx,
777            self.upvars,
778            upvar_index,
779        );
780        let region_name = self.synthesize_region_name();
781
782        Some(RegionName {
783            name: region_name,
784            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
785        })
786    }
787
788    /// Checks for arguments appearing in the (closure) return type. It
789    /// must be a closure since, in a free fn, such an argument would
790    /// have to either also appear in an argument (if using elision)
791    /// or be early bound (named, not in argument).
792    #[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(792u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fr");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn ::tracing::field::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 mut 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:797",
                                    "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(797u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("give_name_if_anonymous_region_appears_in_output: return_ty = {0:?}",
                                                                return_ty) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if !tcx.any_free_region_meets(&return_ty, |r| r.as_var() == fr) {
                return None;
            }
            if let ty::Coroutine(_, args) = return_ty.kind() {
                return_ty = args.as_coroutine().return_ty();
            }
            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))]
793    fn give_name_if_anonymous_region_appears_in_output(&self, fr: RegionVid) -> Option<RegionName> {
794        let tcx = self.infcx.tcx;
795
796        let mut return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
797        debug!("give_name_if_anonymous_region_appears_in_output: return_ty = {:?}", return_ty);
798        if !tcx.any_free_region_meets(&return_ty, |r| r.as_var() == fr) {
799            return None;
800        }
801
802        if let ty::Coroutine(_, args) = return_ty.kind() {
803            // When the return type is identified to be `{async closure body}`, we instead care
804            // about the actual return type of that coroutine.
805            return_ty = args.as_coroutine().return_ty();
806        }
807
808        let mir_hir_id = self.mir_hir_id();
809
810        let (return_span, mir_description, hir_ty) = match tcx.hir_node(mir_hir_id) {
811            hir::Node::Expr(&hir::Expr {
812                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl, kind, fn_decl_span, .. }),
813                ..
814            }) => {
815                let (mut span, mut hir_ty) = match fn_decl.output {
816                    hir::FnRetTy::DefaultReturn(_) => {
817                        (tcx.sess.source_map().end_point(fn_decl_span), None)
818                    }
819                    hir::FnRetTy::Return(hir_ty) => (fn_decl.output.span(), Some(hir_ty)),
820                };
821                let mir_description = match kind {
822                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
823                        hir::CoroutineDesugaring::Async,
824                        hir::CoroutineSource::Block,
825                    )) => " of async block",
826
827                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
828                        hir::CoroutineDesugaring::Async,
829                        hir::CoroutineSource::Closure,
830                    ))
831                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
832                        " of async closure"
833                    }
834
835                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
836                        hir::CoroutineDesugaring::Async,
837                        hir::CoroutineSource::Fn,
838                    )) => {
839                        let parent_item =
840                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
841                        let output = &parent_item
842                            .fn_decl()
843                            .expect("coroutine lowered from async fn should be in fn")
844                            .output;
845                        span = output.span();
846                        if let hir::FnRetTy::Return(ret) = output {
847                            hir_ty = Some(self.get_future_inner_return_ty(ret));
848                        }
849                        " of async function"
850                    }
851
852                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
853                        hir::CoroutineDesugaring::Gen,
854                        hir::CoroutineSource::Block,
855                    )) => " of gen block",
856
857                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
858                        hir::CoroutineDesugaring::Gen,
859                        hir::CoroutineSource::Closure,
860                    ))
861                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => {
862                        " of gen closure"
863                    }
864
865                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
866                        hir::CoroutineDesugaring::Gen,
867                        hir::CoroutineSource::Fn,
868                    )) => {
869                        let parent_item =
870                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
871                        let output = &parent_item
872                            .fn_decl()
873                            .expect("coroutine lowered from gen fn should be in fn")
874                            .output;
875                        span = output.span();
876                        " of gen function"
877                    }
878
879                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
880                        hir::CoroutineDesugaring::AsyncGen,
881                        hir::CoroutineSource::Block,
882                    )) => " of async gen block",
883
884                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
885                        hir::CoroutineDesugaring::AsyncGen,
886                        hir::CoroutineSource::Closure,
887                    ))
888                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
889                        " of async gen closure"
890                    }
891
892                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
893                        hir::CoroutineDesugaring::AsyncGen,
894                        hir::CoroutineSource::Fn,
895                    )) => {
896                        let parent_item =
897                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
898                        let output = &parent_item
899                            .fn_decl()
900                            .expect("coroutine lowered from async gen fn should be in fn")
901                            .output;
902                        span = output.span();
903                        " of async gen function"
904                    }
905
906                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => {
907                        " of coroutine"
908                    }
909                    hir::ClosureKind::Closure => " of closure",
910                };
911                (span, mir_description, hir_ty)
912            }
913            node => match node.fn_decl() {
914                Some(fn_decl) => {
915                    let hir_ty = match fn_decl.output {
916                        hir::FnRetTy::DefaultReturn(_) => None,
917                        hir::FnRetTy::Return(ty) => Some(ty),
918                    };
919                    (fn_decl.output.span(), "", hir_ty)
920                }
921                None => (self.body.span, "", None),
922            },
923        };
924
925        let highlight = hir_ty
926            .and_then(|hir_ty| self.highlight_if_we_can_match_hir_ty(fr, return_ty, hir_ty))
927            .unwrap_or_else(|| {
928                // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
929                // the anonymous region. If it succeeds, the `synthesize_region_name` call below
930                // will increment the counter, "reserving" the number we just used.
931                let counter = *self.next_region_name.try_borrow().unwrap();
932                self.highlight_if_we_cannot_match_hir_ty(fr, return_ty, return_span, counter)
933            });
934
935        Some(RegionName {
936            name: self.synthesize_region_name(),
937            source: RegionNameSource::AnonRegionFromOutput(highlight, mir_description),
938        })
939    }
940
941    /// From the [`hir::Ty`] of an async function's lowered return type,
942    /// retrieve the `hir::Ty` representing the type the user originally wrote.
943    ///
944    /// e.g. given the function:
945    ///
946    /// ```
947    /// async fn foo() -> i32 { 2 }
948    /// ```
949    ///
950    /// this function, given the lowered return type of `foo`, an [`OpaqueDef`] that implements
951    /// `Future<Output=i32>`, returns the `i32`.
952    ///
953    /// [`OpaqueDef`]: hir::TyKind::OpaqueDef
954    fn get_future_inner_return_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
955        let hir::TyKind::OpaqueDef(opaque_ty) = hir_ty.kind else {
956            ::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!(
957                hir_ty.span,
958                "lowered return type of async fn is not OpaqueDef: {:?}",
959                hir_ty
960            );
961        };
962        if let hir::OpaqueTy { bounds: [hir::GenericBound::Trait(trait_ref)], .. } = opaque_ty
963            && let Some(segment) = trait_ref.trait_ref.path.segments.last()
964            && let Some(args) = segment.args
965            && let [constraint] = args.constraints
966            && constraint.ident.name == sym::Output
967            && let Some(ty) = constraint.ty()
968        {
969            ty
970        } else {
971            ::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!(
972                hir_ty.span,
973                "bounds from lowered return type of async fn did not match expected format: {opaque_ty:?}",
974            );
975        }
976    }
977
978    #[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(978u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fr");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn ::tracing::field::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:986",
                                    "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(986u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {0:?}",
                                                                yield_ty) as &dyn ::tracing::field::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:1010",
                                    "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(1010u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
                        });
                } else { ; }
            };
            Some(RegionName {
                    name: self.synthesize_region_name(),
                    source: RegionNameSource::AnonRegionFromYieldTy(yield_span,
                        Symbol::intern(&type_name)),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
979    fn give_name_if_anonymous_region_appears_in_yield_ty(
980        &self,
981        fr: RegionVid,
982    ) -> Option<RegionName> {
983        // Note: coroutines from `async fn` yield `()`, so we don't have to
984        // worry about them here.
985        let yield_ty = self.regioncx.universal_regions().yield_ty?;
986        debug!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}", yield_ty);
987
988        let tcx = self.infcx.tcx;
989
990        if !tcx.any_free_region_meets(&yield_ty, |r| r.as_var() == fr) {
991            return None;
992        }
993
994        let mut highlight = RegionHighlightMode::default();
995        highlight.highlighting_region_vid(tcx, fr, *self.next_region_name.try_borrow().unwrap());
996        let type_name = self
997            .infcx
998            .err_ctxt()
999            .extract_inference_diagnostics_data(yield_ty.into(), highlight)
1000            .name;
1001
1002        let yield_span = match tcx.hir_node(self.mir_hir_id()) {
1003            hir::Node::Expr(&hir::Expr {
1004                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
1005                ..
1006            }) => tcx.sess.source_map().end_point(fn_decl_span),
1007            _ => self.body.span,
1008        };
1009
1010        debug!(
1011            "give_name_if_anonymous_region_appears_in_yield_ty: \
1012             type_name = {:?}, yield_span = {:?}",
1013            yield_span, type_name,
1014        );
1015
1016        Some(RegionName {
1017            name: self.synthesize_region_name(),
1018            source: RegionNameSource::AnonRegionFromYieldTy(yield_span, Symbol::intern(&type_name)),
1019        })
1020    }
1021
1022    fn give_name_if_anonymous_region_appears_in_impl_signature(
1023        &self,
1024        fr: RegionVid,
1025    ) -> Option<RegionName> {
1026        let ty::ReEarlyParam(region) = self.regioncx.to_error_region(fr)?.kind() else {
1027            return None;
1028        };
1029        if region.is_named() {
1030            return None;
1031        };
1032
1033        let tcx = self.infcx.tcx;
1034        let region_def = tcx.generics_of(self.mir_def_id()).region_param(region, tcx).def_id;
1035        let region_parent = tcx.parent(region_def);
1036        let DefKind::Impl { .. } = tcx.def_kind(region_parent) else {
1037            return None;
1038        };
1039
1040        let found = tcx.any_free_region_meets(
1041            &tcx.type_of(region_parent).instantiate_identity().skip_norm_wip(),
1042            |r| r.kind() == ty::ReEarlyParam(region),
1043        );
1044
1045        Some(RegionName {
1046            name: self.synthesize_region_name(),
1047            source: RegionNameSource::AnonRegionFromImplSignature(
1048                tcx.def_span(region_def),
1049                // FIXME(compiler-errors): Does this ever actually show up
1050                // anywhere other than the self type? I couldn't create an
1051                // example of a `'_` in the impl's trait being referenceable.
1052                if found { "self type" } else { "header" },
1053            ),
1054        })
1055    }
1056
1057    fn give_name_if_anonymous_region_appears_in_arg_position_impl_trait(
1058        &self,
1059        fr: RegionVid,
1060    ) -> Option<RegionName> {
1061        let ty::ReEarlyParam(region) = self.regioncx.to_error_region(fr)?.kind() else {
1062            return None;
1063        };
1064        if region.is_named() {
1065            return None;
1066        };
1067
1068        let predicates: Vec<_> = self
1069            .infcx
1070            .tcx
1071            .predicates_of(self.body.source.def_id())
1072            .instantiate_identity(self.infcx.tcx)
1073            .predicates
1074            .into_iter()
1075            .map(Unnormalized::skip_norm_wip)
1076            .collect();
1077
1078        if let Some(upvar_index) = self
1079            .regioncx
1080            .universal_regions()
1081            .defining_ty
1082            .upvar_tys()
1083            .iter()
1084            .position(|ty| self.any_param_predicate_mentions(&predicates, ty, region))
1085        {
1086            let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
1087                self.infcx.tcx,
1088                self.upvars,
1089                upvar_index,
1090            );
1091            let region_name = self.synthesize_region_name();
1092
1093            Some(RegionName {
1094                name: region_name,
1095                source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
1096            })
1097        } else if let Some(arg_index) = self
1098            .regioncx
1099            .universal_regions()
1100            .unnormalized_input_tys
1101            .iter()
1102            .position(|ty| self.any_param_predicate_mentions(&predicates, *ty, region))
1103        {
1104            let (arg_name, arg_span) = self.regioncx.get_argument_name_and_span_for_region(
1105                self.body,
1106                self.local_names(),
1107                arg_index,
1108            );
1109            let region_name = self.synthesize_region_name();
1110
1111            Some(RegionName {
1112                name: region_name,
1113                source: RegionNameSource::AnonRegionFromArgument(
1114                    RegionNameHighlight::CannotMatchHirTy(arg_span, arg_name?),
1115                ),
1116            })
1117        } else {
1118            None
1119        }
1120    }
1121
1122    fn any_param_predicate_mentions(
1123        &self,
1124        clauses: &[ty::Clause<'tcx>],
1125        ty: Ty<'tcx>,
1126        region: ty::EarlyParamRegion,
1127    ) -> bool {
1128        let tcx = self.infcx.tcx;
1129        ty.walk().any(|arg| {
1130            if let ty::GenericArgKind::Type(ty) = arg.kind()
1131                && let ty::Param(_) = ty.kind()
1132            {
1133                clauses.iter().any(|pred| {
1134                    match pred.kind().skip_binder() {
1135                        ty::ClauseKind::Trait(data) if data.self_ty() == ty => {}
1136                        ty::ClauseKind::Projection(data)
1137                            if data.projection_term.self_ty() == ty => {}
1138                        _ => return false,
1139                    }
1140                    tcx.any_free_region_meets(pred, |r| r.kind() == ty::ReEarlyParam(region))
1141                })
1142            } else {
1143                false
1144            }
1145        })
1146    }
1147}