Skip to main content

rustc_borrowck/diagnostics/
region_name.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.infcx.tcx;
            let 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();
            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:428",
                                    "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(428u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("give_name_if_we_can_match_upvar_args: parent_param_ty={0:?}, upvar_nll_ty={1:?}",
                                                                parent_param_ty, upvar_nll_ty) as &dyn 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:445",
                                        "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(445u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("give_name_if_we_can_match_upvar_args: region count mismatch ({0} vs {1})",
                                                                    parent_regions.len(), nll_regions.len()) as &dyn 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))]
386    fn give_name_if_we_can_match_upvar_args(
387        &self,
388        fr: RegionVid,
389        upvar_index: usize,
390    ) -> Option<RegionName> {
391        let tcx = self.infcx.tcx;
392        let defining_ty = self.regioncx.universal_regions().defining_ty;
393
394        let closure_def_id = match defining_ty {
395            DefiningTy::Closure(def_id, _)
396            | DefiningTy::Coroutine(def_id, _)
397            | DefiningTy::CoroutineClosure(def_id, _) => def_id,
398            _ => return None,
399        };
400
401        let parent_def_id = tcx.parent(closure_def_id);
402
403        // Only works if the parent is a function with a fn_sig.
404        if !matches!(tcx.def_kind(parent_def_id), DefKind::Fn | DefKind::AssocFn) {
405            return None;
406        }
407
408        // Find which parameter index this upvar corresponds to by matching
409        // the captured variable's HirId against the parent's parameter patterns.
410        // This only matches simple bindings (not destructuring patterns) and
411        // only when the upvar is a direct parameter (not a local variable).
412        let captured_place = self.upvars.get(upvar_index)?;
413        let upvar_hir_id = captured_place.get_root_variable();
414        let parent_local_def_id = parent_def_id.as_local()?;
415        let parent_body = tcx.hir_body_owned_by(parent_local_def_id);
416        let param_index =
417            parent_body.params.iter().position(|param| param.pat.hir_id == upvar_hir_id)?;
418
419        // Get the parent fn's signature with liberated late-bound regions,
420        // so we have `ReLateParam` instead of `ReBound`.
421        let parent_fn_sig = tcx.fn_sig(parent_def_id).instantiate_identity();
422        let liberated_sig = tcx.liberate_late_bound_regions(parent_def_id, parent_fn_sig);
423        let parent_param_ty = *liberated_sig.inputs().get(param_index)?;
424
425        // Get the upvar's NLL type (with ReVar regions from renumbering).
426        let upvar_nll_ty = *defining_ty.upvar_tys().get(upvar_index)?;
427
428        debug!(
429            "give_name_if_we_can_match_upvar_args: parent_param_ty={:?}, upvar_nll_ty={:?}",
430            parent_param_ty, upvar_nll_ty
431        );
432
433        // Collect free regions from both types in structural order.
434        // This only works when both types have the same structure, i.e.
435        // the upvar captures the whole variable, not a partial place like
436        // `x.field`. Bail out if the region counts differ, since that means
437        // the types diverged and positional correspondence is unreliable.
438        let mut parent_regions = vec![];
439        tcx.for_each_free_region(&parent_param_ty, |r| parent_regions.push(r));
440
441        let mut nll_regions = vec![];
442        tcx.for_each_free_region(&upvar_nll_ty, |r| nll_regions.push(r));
443
444        if parent_regions.len() != nll_regions.len() {
445            debug!(
446                "give_name_if_we_can_match_upvar_args: region count mismatch ({} vs {})",
447                parent_regions.len(),
448                nll_regions.len()
449            );
450            return None;
451        }
452
453        for (parent_r, nll_r) in iter::zip(&parent_regions, &nll_regions) {
454            if nll_r.as_var() == fr {
455                match parent_r.kind() {
456                    ty::ReLateParam(late_param) => {
457                        if let Some(name) = late_param.kind.get_name(tcx) {
458                            let span = late_param
459                                .kind
460                                .get_id()
461                                .and_then(|id| tcx.hir_span_if_local(id))
462                                .unwrap_or(DUMMY_SP);
463                            return Some(RegionName {
464                                name,
465                                source: RegionNameSource::NamedLateParamRegion(span),
466                            });
467                        }
468                    }
469                    ty::ReEarlyParam(ebr) => {
470                        if ebr.is_named() {
471                            let def_id =
472                                tcx.generics_of(parent_def_id).region_param(ebr, tcx).def_id;
473                            let span = tcx.hir_span_if_local(def_id).unwrap_or(DUMMY_SP);
474                            return Some(RegionName {
475                                name: ebr.name,
476                                source: RegionNameSource::NamedEarlyParamRegion(span),
477                            });
478                        }
479                    }
480                    _ => {}
481                }
482            }
483        }
484
485        None
486    }
487
488    /// Finds an argument that contains `fr` and label it with a fully
489    /// elaborated type, returning something like `'1`. Result looks
490    /// like:
491    ///
492    /// ```text
493    ///  | fn foo(x: &u32) { .. }
494    ///           ------- fully elaborated type of `x` is `&'1 u32`
495    /// ```
496    #[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(496u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let implicit_inputs =
                self.regioncx.universal_regions().defining_ty.implicit_inputs();
            let argument_index =
                self.regioncx.get_argument_index_for_region(self.infcx.tcx,
                        fr)?;
            let arg_ty =
                self.regioncx.universal_regions().unnormalized_input_tys[implicit_inputs
                        + argument_index];
            let (_, span) =
                self.regioncx.get_argument_name_and_span_for_region(self.body,
                    self.local_names(), argument_index);
            let highlight =
                self.get_argument_hir_ty_for_highlighting(argument_index).and_then(|arg_hir_ty|
                            self.highlight_if_we_can_match_hir_ty(fr, arg_ty,
                                arg_hir_ty)).unwrap_or_else(||
                        {
                            let counter = *self.next_region_name.try_borrow().unwrap();
                            self.highlight_if_we_cannot_match_hir_ty(fr, arg_ty, span,
                                counter)
                        });
            Some(RegionName {
                    name: self.synthesize_region_name(),
                    source: RegionNameSource::AnonRegionFromArgument(highlight),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
497    fn give_name_if_anonymous_region_appears_in_arguments(
498        &self,
499        fr: RegionVid,
500    ) -> Option<RegionName> {
501        let implicit_inputs = self.regioncx.universal_regions().defining_ty.implicit_inputs();
502        let argument_index = self.regioncx.get_argument_index_for_region(self.infcx.tcx, fr)?;
503
504        let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys
505            [implicit_inputs + argument_index];
506        let (_, span) = self.regioncx.get_argument_name_and_span_for_region(
507            self.body,
508            self.local_names(),
509            argument_index,
510        );
511
512        let highlight = self
513            .get_argument_hir_ty_for_highlighting(argument_index)
514            .and_then(|arg_hir_ty| self.highlight_if_we_can_match_hir_ty(fr, arg_ty, arg_hir_ty))
515            .unwrap_or_else(|| {
516                // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
517                // the anonymous region. If it succeeds, the `synthesize_region_name` call below
518                // will increment the counter, "reserving" the number we just used.
519                let counter = *self.next_region_name.try_borrow().unwrap();
520                self.highlight_if_we_cannot_match_hir_ty(fr, arg_ty, span, counter)
521            });
522
523        Some(RegionName {
524            name: self.synthesize_region_name(),
525            source: RegionNameSource::AnonRegionFromArgument(highlight),
526        })
527    }
528
529    fn get_argument_hir_ty_for_highlighting(
530        &self,
531        argument_index: usize,
532    ) -> Option<&hir::Ty<'tcx>> {
533        let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(self.mir_hir_id())?;
534        let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(argument_index)?;
535        match argument_hir_ty.kind {
536            // This indicates a variable with no type annotation, like
537            // `|x|`... in that case, we can't highlight the type but
538            // must highlight the variable.
539            // NOTE(eddyb) this is handled in/by the sole caller
540            // (`give_name_if_anonymous_region_appears_in_arguments`).
541            hir::TyKind::Infer(()) => None,
542
543            _ => Some(argument_hir_ty),
544        }
545    }
546
547    /// Attempts to highlight the specific part of a type in an argument
548    /// that has no type annotation.
549    /// For example, we might produce an annotation like this:
550    ///
551    /// ```text
552    ///  |     foo(|a, b| b)
553    ///  |          -  -
554    ///  |          |  |
555    ///  |          |  has type `&'1 u32`
556    ///  |          has type `&'2 u32`
557    /// ```
558    fn highlight_if_we_cannot_match_hir_ty(
559        &self,
560        needle_fr: RegionVid,
561        ty: Ty<'tcx>,
562        span: Span,
563        counter: usize,
564    ) -> RegionNameHighlight {
565        let mut highlight = RegionHighlightMode::default();
566        highlight.highlighting_region_vid(self.infcx.tcx, needle_fr, counter);
567        let type_name =
568            self.infcx.err_ctxt().extract_inference_diagnostics_data(ty.into(), highlight).name;
569
570        {
    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:570",
                        "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(570u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("highlight_if_we_cannot_match_hir_ty: type_name={0:?} needle_fr={1:?}",
                                                    type_name, needle_fr) as &dyn Value))])
            });
    } else { ; }
};debug!(
571            "highlight_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
572            type_name, needle_fr
573        );
574        if type_name.contains(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", counter))
    })format!("'{counter}")) {
575            // Only add a label if we can confirm that a region was labelled.
576            RegionNameHighlight::CannotMatchHirTy(span, Symbol::intern(&type_name))
577        } else {
578            RegionNameHighlight::Occluded(span, Symbol::intern(&type_name))
579        }
580    }
581
582    /// Attempts to highlight the specific part of a type annotation
583    /// that contains the anonymous reference we want to give a name
584    /// to. For example, we might produce an annotation like this:
585    ///
586    /// ```text
587    ///  | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
588    ///  |                - let's call the lifetime of this reference `'1`
589    /// ```
590    ///
591    /// the way this works is that we match up `ty`, which is
592    /// a `Ty<'tcx>` (the internal form of the type) with
593    /// `hir_ty`, a `hir::Ty` (the syntax of the type
594    /// annotation). We are descending through the types stepwise,
595    /// looking in to find the region `needle_fr` in the internal
596    /// type. Once we find that, we can use the span of the `hir::Ty`
597    /// to add the highlight.
598    ///
599    /// This is a somewhat imperfect process, so along the way we also
600    /// keep track of the **closest** type we've found. If we fail to
601    /// find the exact `&` or `'_` to highlight, then we may fall back
602    /// to highlighting that closest type instead.
603    fn highlight_if_we_can_match_hir_ty(
604        &self,
605        needle_fr: RegionVid,
606        ty: Ty<'tcx>,
607        hir_ty: &hir::Ty<'_>,
608    ) -> Option<RegionNameHighlight> {
609        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)];
610
611        while let Some((ty, hir_ty)) = search_stack.pop() {
612            match (ty.kind(), &hir_ty.kind) {
613                // Check if the `ty` is `&'X ..` where `'X`
614                // is the region we are looking for -- if so, and we have a `&T`
615                // on the RHS, then we want to highlight the `&` like so:
616                //
617                //     &
618                //     - let's call the lifetime of this reference `'1`
619                (ty::Ref(region, referent_ty, _), hir::TyKind::Ref(_lifetime, referent_hir_ty)) => {
620                    if region.as_var() == needle_fr {
621                        // Just grab the first character, the `&`.
622                        let source_map = self.infcx.tcx.sess.source_map();
623                        let ampersand_span = source_map.start_point(hir_ty.span);
624
625                        return Some(RegionNameHighlight::MatchedHirTy(ampersand_span));
626                    }
627
628                    // Otherwise, let's descend into the referent types.
629                    search_stack.push((*referent_ty, referent_hir_ty.ty));
630                }
631
632                // Match up something like `Foo<'1>`
633                (ty::Adt(_adt_def, args), hir::TyKind::Path(hir::QPath::Resolved(None, path))) => {
634                    match path.res {
635                        // Type parameters of the type alias have no reason to
636                        // be the same as those of the ADT.
637                        // FIXME: We should be able to do something similar to
638                        // match_adt_and_segment in this case.
639                        Res::Def(DefKind::TyAlias, _) => (),
640                        _ => {
641                            if let Some(last_segment) = path.segments.last()
642                                && let Some(highlight) = self.match_adt_and_segment(
643                                    args,
644                                    needle_fr,
645                                    last_segment,
646                                    search_stack,
647                                )
648                            {
649                                return Some(highlight);
650                            }
651                        }
652                    }
653                }
654
655                // The following cases don't have lifetimes, so we
656                // just worry about trying to match up the rustc type
657                // with the HIR types:
658                (&ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
659                    search_stack.extend(iter::zip(elem_tys, *elem_hir_tys));
660                }
661
662                (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
663                | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
664                    search_stack.push((*elem_ty, elem_hir_ty));
665                }
666
667                (ty::RawPtr(mut_ty, _), hir::TyKind::Ptr(mut_hir_ty)) => {
668                    search_stack.push((*mut_ty, mut_hir_ty.ty));
669                }
670
671                _ => {
672                    // FIXME there are other cases that we could trace
673                }
674            }
675        }
676
677        None
678    }
679
680    /// We've found an enum/struct/union type with the generic args
681    /// `args` and -- in the HIR -- a path type with the final
682    /// segment `last_segment`. Try to find a `'_` to highlight in
683    /// the generic args (or, if not, to produce new zipped pairs of
684    /// types+hir to search through).
685    fn match_adt_and_segment<'hir>(
686        &self,
687        args: GenericArgsRef<'tcx>,
688        needle_fr: RegionVid,
689        last_segment: &'hir hir::PathSegment<'hir>,
690        search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
691    ) -> Option<RegionNameHighlight> {
692        // Did the user give explicit arguments? (e.g., `Foo<..>`)
693        let explicit_args = last_segment.args.as_ref()?;
694        let lifetime =
695            self.try_match_adt_and_generic_args(args, needle_fr, explicit_args, search_stack)?;
696        if lifetime.is_anonymous() {
697            None
698        } else {
699            Some(RegionNameHighlight::MatchedAdtAndSegment(lifetime.ident.span))
700        }
701    }
702
703    /// We've found an enum/struct/union type with the generic args
704    /// `args` and -- in the HIR -- a path with the generic
705    /// arguments `hir_args`. If `needle_fr` appears in the args, return
706    /// the `hir::Lifetime` that corresponds to it. If not, push onto
707    /// `search_stack` the types+hir to search through.
708    fn try_match_adt_and_generic_args<'hir>(
709        &self,
710        args: GenericArgsRef<'tcx>,
711        needle_fr: RegionVid,
712        hir_args: &'hir hir::GenericArgs<'hir>,
713        search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
714    ) -> Option<&'hir hir::Lifetime> {
715        for (arg, hir_arg) in iter::zip(args, hir_args.args) {
716            match (arg.kind(), hir_arg) {
717                (GenericArgKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
718                    if r.as_var() == needle_fr {
719                        return Some(lt);
720                    }
721                }
722
723                (GenericArgKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
724                    search_stack.push((ty, hir_ty.as_unambig_ty()));
725                }
726
727                (GenericArgKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
728                    // Lifetimes cannot be found in consts, so we don't need
729                    // to search anything here.
730                }
731
732                (
733                    GenericArgKind::Lifetime(_)
734                    | GenericArgKind::Type(_)
735                    | GenericArgKind::Const(_),
736                    _,
737                ) => {
738                    self.dcx().span_delayed_bug(
739                        hir_arg.span(),
740                        ::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:?}"),
741                    );
742                }
743            }
744        }
745
746        None
747    }
748
749    /// Finds a closure upvar that contains `fr` and label it with a
750    /// fully elaborated type, returning something like `'1`. Result
751    /// looks like:
752    ///
753    /// ```text
754    ///  | let x = Some(&22);
755    ///        - fully elaborated type of `x` is `Option<&'1 u32>`
756    /// ```
757    #[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(757u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let upvar_index =
                self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
            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))]
758    fn give_name_if_anonymous_region_appears_in_upvars(&self, fr: RegionVid) -> Option<RegionName> {
759        let upvar_index = self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
760
761        // Before synthesizing an anonymous name like `'1`, try to find a
762        // named lifetime from the parent function's signature that matches.
763        if let Some(region_name) = self.give_name_if_we_can_match_upvar_args(fr, upvar_index) {
764            return Some(region_name);
765        }
766
767        let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
768            self.infcx.tcx,
769            self.upvars,
770            upvar_index,
771        );
772        let region_name = self.synthesize_region_name();
773
774        Some(RegionName {
775            name: region_name,
776            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
777        })
778    }
779
780    /// Checks for arguments appearing in the (closure) return type. It
781    /// must be a closure since, in a free fn, such an argument would
782    /// have to either also appear in an argument (if using elision)
783    /// or be early bound (named, not in argument).
784    #[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(784u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.infcx.tcx;
            let return_ty =
                self.regioncx.universal_regions().unnormalized_output_ty;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:789",
                                    "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(789u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("give_name_if_anonymous_region_appears_in_output: return_ty = {0:?}",
                                                                return_ty) as &dyn Value))])
                        });
                } else { ; }
            };
            if !tcx.any_free_region_meets(&return_ty, |r| r.as_var() == fr) {
                return None;
            }
            let mir_hir_id = self.mir_hir_id();
            let (return_span, mir_description, hir_ty) =
                match tcx.hir_node(mir_hir_id) {
                    hir::Node::Expr(&hir::Expr {
                        kind: hir::ExprKind::Closure(&hir::Closure {
                            fn_decl, kind, fn_decl_span, .. }), .. }) => {
                        let (mut span, mut hir_ty) =
                            match fn_decl.output {
                                hir::FnRetTy::DefaultReturn(_) => {
                                    (tcx.sess.source_map().end_point(fn_decl_span), None)
                                }
                                hir::FnRetTy::Return(hir_ty) =>
                                    (fn_decl.output.span(), Some(hir_ty)),
                            };
                        let mir_description =
                            match kind {
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                    hir::CoroutineSource::Block)) => " of async block",
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                    hir::CoroutineSource::Closure)) |
                                    hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
                                    => {
                                    " of async closure"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                    hir::CoroutineSource::Fn)) => {
                                    let parent_item =
                                        tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
                                    let output =
                                        &parent_item.fn_decl().expect("coroutine lowered from async fn should be in fn").output;
                                    span = output.span();
                                    if let hir::FnRetTy::Return(ret) = output {
                                        hir_ty = Some(self.get_future_inner_return_ty(ret));
                                    }
                                    " of async function"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
                                    hir::CoroutineSource::Block)) => " of gen block",
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
                                    hir::CoroutineSource::Closure)) |
                                    hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen)
                                    => {
                                    " of gen closure"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
                                    hir::CoroutineSource::Fn)) => {
                                    let parent_item =
                                        tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
                                    let output =
                                        &parent_item.fn_decl().expect("coroutine lowered from gen fn should be in fn").output;
                                    span = output.span();
                                    " of gen function"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
                                    hir::CoroutineSource::Block)) => " of async gen block",
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
                                    hir::CoroutineSource::Closure)) |
                                    hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen)
                                    => {
                                    " of async gen closure"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
                                    hir::CoroutineSource::Fn)) => {
                                    let parent_item =
                                        tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
                                    let output =
                                        &parent_item.fn_decl().expect("coroutine lowered from async gen fn should be in fn").output;
                                    span = output.span();
                                    " of async gen function"
                                }
                                hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_))
                                    => {
                                    " of coroutine"
                                }
                                hir::ClosureKind::Closure => " of closure",
                            };
                        (span, mir_description, hir_ty)
                    }
                    node =>
                        match node.fn_decl() {
                            Some(fn_decl) => {
                                let hir_ty =
                                    match fn_decl.output {
                                        hir::FnRetTy::DefaultReturn(_) => None,
                                        hir::FnRetTy::Return(ty) => Some(ty),
                                    };
                                (fn_decl.output.span(), "", hir_ty)
                            }
                            None => (self.body.span, "", None),
                        },
                };
            let highlight =
                hir_ty.and_then(|hir_ty|
                            self.highlight_if_we_can_match_hir_ty(fr, return_ty,
                                hir_ty)).unwrap_or_else(||
                        {
                            let counter = *self.next_region_name.try_borrow().unwrap();
                            self.highlight_if_we_cannot_match_hir_ty(fr, return_ty,
                                return_span, counter)
                        });
            Some(RegionName {
                    name: self.synthesize_region_name(),
                    source: RegionNameSource::AnonRegionFromOutput(highlight,
                        mir_description),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
785    fn give_name_if_anonymous_region_appears_in_output(&self, fr: RegionVid) -> Option<RegionName> {
786        let tcx = self.infcx.tcx;
787
788        let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
789        debug!("give_name_if_anonymous_region_appears_in_output: return_ty = {:?}", return_ty);
790        if !tcx.any_free_region_meets(&return_ty, |r| r.as_var() == fr) {
791            return None;
792        }
793
794        let mir_hir_id = self.mir_hir_id();
795
796        let (return_span, mir_description, hir_ty) = match tcx.hir_node(mir_hir_id) {
797            hir::Node::Expr(&hir::Expr {
798                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl, kind, fn_decl_span, .. }),
799                ..
800            }) => {
801                let (mut span, mut hir_ty) = match fn_decl.output {
802                    hir::FnRetTy::DefaultReturn(_) => {
803                        (tcx.sess.source_map().end_point(fn_decl_span), None)
804                    }
805                    hir::FnRetTy::Return(hir_ty) => (fn_decl.output.span(), Some(hir_ty)),
806                };
807                let mir_description = match kind {
808                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
809                        hir::CoroutineDesugaring::Async,
810                        hir::CoroutineSource::Block,
811                    )) => " of async block",
812
813                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
814                        hir::CoroutineDesugaring::Async,
815                        hir::CoroutineSource::Closure,
816                    ))
817                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
818                        " of async closure"
819                    }
820
821                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
822                        hir::CoroutineDesugaring::Async,
823                        hir::CoroutineSource::Fn,
824                    )) => {
825                        let parent_item =
826                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
827                        let output = &parent_item
828                            .fn_decl()
829                            .expect("coroutine lowered from async fn should be in fn")
830                            .output;
831                        span = output.span();
832                        if let hir::FnRetTy::Return(ret) = output {
833                            hir_ty = Some(self.get_future_inner_return_ty(ret));
834                        }
835                        " of async function"
836                    }
837
838                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
839                        hir::CoroutineDesugaring::Gen,
840                        hir::CoroutineSource::Block,
841                    )) => " of gen block",
842
843                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
844                        hir::CoroutineDesugaring::Gen,
845                        hir::CoroutineSource::Closure,
846                    ))
847                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => {
848                        " of gen closure"
849                    }
850
851                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
852                        hir::CoroutineDesugaring::Gen,
853                        hir::CoroutineSource::Fn,
854                    )) => {
855                        let parent_item =
856                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
857                        let output = &parent_item
858                            .fn_decl()
859                            .expect("coroutine lowered from gen fn should be in fn")
860                            .output;
861                        span = output.span();
862                        " of gen function"
863                    }
864
865                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
866                        hir::CoroutineDesugaring::AsyncGen,
867                        hir::CoroutineSource::Block,
868                    )) => " of async gen block",
869
870                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
871                        hir::CoroutineDesugaring::AsyncGen,
872                        hir::CoroutineSource::Closure,
873                    ))
874                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
875                        " of async gen closure"
876                    }
877
878                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
879                        hir::CoroutineDesugaring::AsyncGen,
880                        hir::CoroutineSource::Fn,
881                    )) => {
882                        let parent_item =
883                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
884                        let output = &parent_item
885                            .fn_decl()
886                            .expect("coroutine lowered from async gen fn should be in fn")
887                            .output;
888                        span = output.span();
889                        " of async gen function"
890                    }
891
892                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => {
893                        " of coroutine"
894                    }
895                    hir::ClosureKind::Closure => " of closure",
896                };
897                (span, mir_description, hir_ty)
898            }
899            node => match node.fn_decl() {
900                Some(fn_decl) => {
901                    let hir_ty = match fn_decl.output {
902                        hir::FnRetTy::DefaultReturn(_) => None,
903                        hir::FnRetTy::Return(ty) => Some(ty),
904                    };
905                    (fn_decl.output.span(), "", hir_ty)
906                }
907                None => (self.body.span, "", None),
908            },
909        };
910
911        let highlight = hir_ty
912            .and_then(|hir_ty| self.highlight_if_we_can_match_hir_ty(fr, return_ty, hir_ty))
913            .unwrap_or_else(|| {
914                // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
915                // the anonymous region. If it succeeds, the `synthesize_region_name` call below
916                // will increment the counter, "reserving" the number we just used.
917                let counter = *self.next_region_name.try_borrow().unwrap();
918                self.highlight_if_we_cannot_match_hir_ty(fr, return_ty, return_span, counter)
919            });
920
921        Some(RegionName {
922            name: self.synthesize_region_name(),
923            source: RegionNameSource::AnonRegionFromOutput(highlight, mir_description),
924        })
925    }
926
927    /// From the [`hir::Ty`] of an async function's lowered return type,
928    /// retrieve the `hir::Ty` representing the type the user originally wrote.
929    ///
930    /// e.g. given the function:
931    ///
932    /// ```
933    /// async fn foo() -> i32 { 2 }
934    /// ```
935    ///
936    /// this function, given the lowered return type of `foo`, an [`OpaqueDef`] that implements
937    /// `Future<Output=i32>`, returns the `i32`.
938    ///
939    /// [`OpaqueDef`]: hir::TyKind::OpaqueDef
940    fn get_future_inner_return_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
941        let hir::TyKind::OpaqueDef(opaque_ty) = hir_ty.kind else {
942            ::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!(
943                hir_ty.span,
944                "lowered return type of async fn is not OpaqueDef: {:?}",
945                hir_ty
946            );
947        };
948        if let hir::OpaqueTy { bounds: [hir::GenericBound::Trait(trait_ref)], .. } = opaque_ty
949            && let Some(segment) = trait_ref.trait_ref.path.segments.last()
950            && let Some(args) = segment.args
951            && let [constraint] = args.constraints
952            && constraint.ident.name == sym::Output
953            && let Some(ty) = constraint.ty()
954        {
955            ty
956        } else {
957            ::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!(
958                hir_ty.span,
959                "bounds from lowered return type of async fn did not match expected format: {opaque_ty:?}",
960            );
961        }
962    }
963
964    #[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(964u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let yield_ty = self.regioncx.universal_regions().yield_ty?;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:972",
                                    "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(972u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {0:?}",
                                                                yield_ty) as &dyn Value))])
                        });
                } else { ; }
            };
            let tcx = self.infcx.tcx;
            if !tcx.any_free_region_meets(&yield_ty, |r| r.as_var() == fr) {
                return None;
            }
            let mut highlight = RegionHighlightMode::default();
            highlight.highlighting_region_vid(tcx, fr,
                *self.next_region_name.try_borrow().unwrap());
            let type_name =
                self.infcx.err_ctxt().extract_inference_diagnostics_data(yield_ty.into(),
                        highlight).name;
            let yield_span =
                match tcx.hir_node(self.mir_hir_id()) {
                    hir::Node::Expr(&hir::Expr {
                        kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span,
                            .. }), .. }) =>
                        tcx.sess.source_map().end_point(fn_decl_span),
                    _ => self.body.span,
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs:996",
                                    "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(996u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("give_name_if_anonymous_region_appears_in_yield_ty: type_name = {0:?}, yield_span = {1:?}",
                                                                yield_span, type_name) as &dyn Value))])
                        });
                } else { ; }
            };
            Some(RegionName {
                    name: self.synthesize_region_name(),
                    source: RegionNameSource::AnonRegionFromYieldTy(yield_span,
                        Symbol::intern(&type_name)),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
965    fn give_name_if_anonymous_region_appears_in_yield_ty(
966        &self,
967        fr: RegionVid,
968    ) -> Option<RegionName> {
969        // Note: coroutines from `async fn` yield `()`, so we don't have to
970        // worry about them here.
971        let yield_ty = self.regioncx.universal_regions().yield_ty?;
972        debug!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}", yield_ty);
973
974        let tcx = self.infcx.tcx;
975
976        if !tcx.any_free_region_meets(&yield_ty, |r| r.as_var() == fr) {
977            return None;
978        }
979
980        let mut highlight = RegionHighlightMode::default();
981        highlight.highlighting_region_vid(tcx, fr, *self.next_region_name.try_borrow().unwrap());
982        let type_name = self
983            .infcx
984            .err_ctxt()
985            .extract_inference_diagnostics_data(yield_ty.into(), highlight)
986            .name;
987
988        let yield_span = match tcx.hir_node(self.mir_hir_id()) {
989            hir::Node::Expr(&hir::Expr {
990                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
991                ..
992            }) => tcx.sess.source_map().end_point(fn_decl_span),
993            _ => self.body.span,
994        };
995
996        debug!(
997            "give_name_if_anonymous_region_appears_in_yield_ty: \
998             type_name = {:?}, yield_span = {:?}",
999            yield_span, type_name,
1000        );
1001
1002        Some(RegionName {
1003            name: self.synthesize_region_name(),
1004            source: RegionNameSource::AnonRegionFromYieldTy(yield_span, Symbol::intern(&type_name)),
1005        })
1006    }
1007
1008    fn give_name_if_anonymous_region_appears_in_impl_signature(
1009        &self,
1010        fr: RegionVid,
1011    ) -> Option<RegionName> {
1012        let ty::ReEarlyParam(region) = self.to_error_region(fr)?.kind() else {
1013            return None;
1014        };
1015        if region.is_named() {
1016            return None;
1017        };
1018
1019        let tcx = self.infcx.tcx;
1020        let region_def = tcx.generics_of(self.mir_def_id()).region_param(region, tcx).def_id;
1021        let region_parent = tcx.parent(region_def);
1022        let DefKind::Impl { .. } = tcx.def_kind(region_parent) else {
1023            return None;
1024        };
1025
1026        let found = tcx
1027            .any_free_region_meets(&tcx.type_of(region_parent).instantiate_identity(), |r| {
1028                r.kind() == ty::ReEarlyParam(region)
1029            });
1030
1031        Some(RegionName {
1032            name: self.synthesize_region_name(),
1033            source: RegionNameSource::AnonRegionFromImplSignature(
1034                tcx.def_span(region_def),
1035                // FIXME(compiler-errors): Does this ever actually show up
1036                // anywhere other than the self type? I couldn't create an
1037                // example of a `'_` in the impl's trait being referenceable.
1038                if found { "self type" } else { "header" },
1039            ),
1040        })
1041    }
1042
1043    fn give_name_if_anonymous_region_appears_in_arg_position_impl_trait(
1044        &self,
1045        fr: RegionVid,
1046    ) -> Option<RegionName> {
1047        let ty::ReEarlyParam(region) = self.to_error_region(fr)?.kind() else {
1048            return None;
1049        };
1050        if region.is_named() {
1051            return None;
1052        };
1053
1054        let predicates = self
1055            .infcx
1056            .tcx
1057            .predicates_of(self.body.source.def_id())
1058            .instantiate_identity(self.infcx.tcx)
1059            .predicates;
1060
1061        if let Some(upvar_index) = self
1062            .regioncx
1063            .universal_regions()
1064            .defining_ty
1065            .upvar_tys()
1066            .iter()
1067            .position(|ty| self.any_param_predicate_mentions(&predicates, ty, region))
1068        {
1069            let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
1070                self.infcx.tcx,
1071                self.upvars,
1072                upvar_index,
1073            );
1074            let region_name = self.synthesize_region_name();
1075
1076            Some(RegionName {
1077                name: region_name,
1078                source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
1079            })
1080        } else if let Some(arg_index) = self
1081            .regioncx
1082            .universal_regions()
1083            .unnormalized_input_tys
1084            .iter()
1085            .position(|ty| self.any_param_predicate_mentions(&predicates, *ty, region))
1086        {
1087            let (arg_name, arg_span) = self.regioncx.get_argument_name_and_span_for_region(
1088                self.body,
1089                self.local_names(),
1090                arg_index,
1091            );
1092            let region_name = self.synthesize_region_name();
1093
1094            Some(RegionName {
1095                name: region_name,
1096                source: RegionNameSource::AnonRegionFromArgument(
1097                    RegionNameHighlight::CannotMatchHirTy(arg_span, arg_name?),
1098                ),
1099            })
1100        } else {
1101            None
1102        }
1103    }
1104
1105    fn any_param_predicate_mentions(
1106        &self,
1107        clauses: &[ty::Clause<'tcx>],
1108        ty: Ty<'tcx>,
1109        region: ty::EarlyParamRegion,
1110    ) -> bool {
1111        let tcx = self.infcx.tcx;
1112        ty.walk().any(|arg| {
1113            if let ty::GenericArgKind::Type(ty) = arg.kind()
1114                && let ty::Param(_) = ty.kind()
1115            {
1116                clauses.iter().any(|pred| {
1117                    match pred.kind().skip_binder() {
1118                        ty::ClauseKind::Trait(data) if data.self_ty() == ty => {}
1119                        ty::ClauseKind::Projection(data)
1120                            if data.projection_term.self_ty() == ty => {}
1121                        _ => return false,
1122                    }
1123                    tcx.any_free_region_meets(pred, |r| r.kind() == ty::ReEarlyParam(region))
1124                })
1125            } else {
1126                false
1127            }
1128        })
1129    }
1130}