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, Unnormalized};
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().skip_norm_wip();
            let liberated_sig =
                tcx.liberate_late_bound_regions(parent_def_id, parent_fn_sig);
            let parent_param_ty = *liberated_sig.inputs().get(param_index)?;
            let upvar_nll_ty = *defining_ty.upvar_tys().get(upvar_index)?;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_name.rs: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().skip_norm_wip();
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 user_arg_index =
                self.regioncx.get_user_arg_index_for_region(self.infcx.tcx,
                        fr)?;
            let arg_ty =
                self.regioncx.universal_regions().unnormalized_input_tys[implicit_inputs
                        + user_arg_index];
            let (_, span) =
                self.regioncx.get_argument_name_and_span_for_region(self.body,
                    self.local_names(), user_arg_index);
            let highlight =
                self.get_argument_hir_ty_for_highlighting(user_arg_index).and_then(|arg_hir_ty|
                            self.highlight_if_we_can_match_hir_ty(fr, arg_ty,
                                arg_hir_ty)).unwrap_or_else(||
                        {
                            let counter = *self.next_region_name.try_borrow().unwrap();
                            self.highlight_if_we_cannot_match_hir_ty(fr, arg_ty, span,
                                counter)
                        });
            Some(RegionName {
                    name: self.synthesize_region_name(),
                    source: RegionNameSource::AnonRegionFromArgument(highlight),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
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 user_arg_index = self.regioncx.get_user_arg_index_for_region(self.infcx.tcx, fr)?;
503
504        let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys
505            [implicit_inputs + user_arg_index];
506        let (_, span) = self.regioncx.get_argument_name_and_span_for_region(
507            self.body,
508            self.local_names(),
509            user_arg_index,
510        );
511
512        let highlight = self
513            .get_argument_hir_ty_for_highlighting(user_arg_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        user_arg_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        // Closures don't have implicit self arguments in HIR, so use `user_arg_index` directly.
535        let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(user_arg_index)?;
536        match argument_hir_ty.kind {
537            // This indicates a variable with no type annotation, like
538            // `|x|`... in that case, we can't highlight the type but
539            // must highlight the variable.
540            // NOTE(eddyb) this is handled in/by the sole caller
541            // (`give_name_if_anonymous_region_appears_in_arguments`).
542            hir::TyKind::Infer(()) => None,
543
544            _ => Some(argument_hir_ty),
545        }
546    }
547
548    /// Attempts to highlight the specific part of a type in an argument
549    /// that has no type annotation.
550    /// For example, we might produce an annotation like this:
551    ///
552    /// ```text
553    ///  |     foo(|a, b| b)
554    ///  |          -  -
555    ///  |          |  |
556    ///  |          |  has type `&'1 u32`
557    ///  |          has type `&'2 u32`
558    /// ```
559    fn highlight_if_we_cannot_match_hir_ty(
560        &self,
561        needle_fr: RegionVid,
562        ty: Ty<'tcx>,
563        span: Span,
564        counter: usize,
565    ) -> RegionNameHighlight {
566        let mut highlight = RegionHighlightMode::default();
567        highlight.highlighting_region_vid(self.infcx.tcx, needle_fr, counter);
568        let type_name =
569            self.infcx.err_ctxt().extract_inference_diagnostics_data(ty.into(), highlight).name;
570
571        {
    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:571",
                        "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(571u32),
                        ::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!(
572            "highlight_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
573            type_name, needle_fr
574        );
575        if type_name.contains(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", counter))
    })format!("'{counter}")) {
576            // Only add a label if we can confirm that a region was labelled.
577            RegionNameHighlight::CannotMatchHirTy(span, Symbol::intern(&type_name))
578        } else {
579            RegionNameHighlight::Occluded(span, Symbol::intern(&type_name))
580        }
581    }
582
583    /// Attempts to highlight the specific part of a type annotation
584    /// that contains the anonymous reference we want to give a name
585    /// to. For example, we might produce an annotation like this:
586    ///
587    /// ```text
588    ///  | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
589    ///  |                - let's call the lifetime of this reference `'1`
590    /// ```
591    ///
592    /// the way this works is that we match up `ty`, which is
593    /// a `Ty<'tcx>` (the internal form of the type) with
594    /// `hir_ty`, a `hir::Ty` (the syntax of the type
595    /// annotation). We are descending through the types stepwise,
596    /// looking in to find the region `needle_fr` in the internal
597    /// type. Once we find that, we can use the span of the `hir::Ty`
598    /// to add the highlight.
599    ///
600    /// This is a somewhat imperfect process, so along the way we also
601    /// keep track of the **closest** type we've found. If we fail to
602    /// find the exact `&` or `'_` to highlight, then we may fall back
603    /// to highlighting that closest type instead.
604    fn highlight_if_we_can_match_hir_ty(
605        &self,
606        needle_fr: RegionVid,
607        ty: Ty<'tcx>,
608        hir_ty: &hir::Ty<'_>,
609    ) -> Option<RegionNameHighlight> {
610        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)];
611
612        while let Some((ty, hir_ty)) = search_stack.pop() {
613            match (ty.kind(), &hir_ty.kind) {
614                // Check if the `ty` is `&'X ..` where `'X`
615                // is the region we are looking for -- if so, and we have a `&T`
616                // on the RHS, then we want to highlight the `&` like so:
617                //
618                //     &
619                //     - let's call the lifetime of this reference `'1`
620                (ty::Ref(region, referent_ty, _), hir::TyKind::Ref(_lifetime, referent_hir_ty)) => {
621                    if region.as_var() == needle_fr {
622                        // Just grab the first character, the `&`.
623                        let source_map = self.infcx.tcx.sess.source_map();
624                        let ampersand_span = source_map.start_point(hir_ty.span);
625
626                        return Some(RegionNameHighlight::MatchedHirTy(ampersand_span));
627                    }
628
629                    // Otherwise, let's descend into the referent types.
630                    search_stack.push((*referent_ty, referent_hir_ty.ty));
631                }
632
633                // Match up something like `Foo<'1>`
634                (ty::Adt(_adt_def, args), hir::TyKind::Path(hir::QPath::Resolved(None, path))) => {
635                    match path.res {
636                        // Type parameters of the type alias have no reason to
637                        // be the same as those of the ADT.
638                        // FIXME: We should be able to do something similar to
639                        // match_adt_and_segment in this case.
640                        Res::Def(DefKind::TyAlias, _) => (),
641                        _ => {
642                            if let Some(last_segment) = path.segments.last()
643                                && let Some(highlight) = self.match_adt_and_segment(
644                                    args,
645                                    needle_fr,
646                                    last_segment,
647                                    search_stack,
648                                )
649                            {
650                                return Some(highlight);
651                            }
652                        }
653                    }
654                }
655
656                // The following cases don't have lifetimes, so we
657                // just worry about trying to match up the rustc type
658                // with the HIR types:
659                (&ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
660                    search_stack.extend(iter::zip(elem_tys, *elem_hir_tys));
661                }
662
663                (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
664                | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
665                    search_stack.push((*elem_ty, elem_hir_ty));
666                }
667
668                (ty::RawPtr(mut_ty, _), hir::TyKind::Ptr(mut_hir_ty)) => {
669                    search_stack.push((*mut_ty, mut_hir_ty.ty));
670                }
671
672                _ => {
673                    // FIXME there are other cases that we could trace
674                }
675            }
676        }
677
678        None
679    }
680
681    /// We've found an enum/struct/union type with the generic args
682    /// `args` and -- in the HIR -- a path type with the final
683    /// segment `last_segment`. Try to find a `'_` to highlight in
684    /// the generic args (or, if not, to produce new zipped pairs of
685    /// types+hir to search through).
686    fn match_adt_and_segment<'hir>(
687        &self,
688        args: GenericArgsRef<'tcx>,
689        needle_fr: RegionVid,
690        last_segment: &'hir hir::PathSegment<'hir>,
691        search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
692    ) -> Option<RegionNameHighlight> {
693        // Did the user give explicit arguments? (e.g., `Foo<..>`)
694        let explicit_args = last_segment.args.as_ref()?;
695        let lifetime =
696            self.try_match_adt_and_generic_args(args, needle_fr, explicit_args, search_stack)?;
697        if lifetime.is_anonymous() {
698            None
699        } else {
700            Some(RegionNameHighlight::MatchedAdtAndSegment(lifetime.ident.span))
701        }
702    }
703
704    /// We've found an enum/struct/union type with the generic args
705    /// `args` and -- in the HIR -- a path with the generic
706    /// arguments `hir_args`. If `needle_fr` appears in the args, return
707    /// the `hir::Lifetime` that corresponds to it. If not, push onto
708    /// `search_stack` the types+hir to search through.
709    fn try_match_adt_and_generic_args<'hir>(
710        &self,
711        args: GenericArgsRef<'tcx>,
712        needle_fr: RegionVid,
713        hir_args: &'hir hir::GenericArgs<'hir>,
714        search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>,
715    ) -> Option<&'hir hir::Lifetime> {
716        for (arg, hir_arg) in iter::zip(args, hir_args.args) {
717            match (arg.kind(), hir_arg) {
718                (GenericArgKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
719                    if r.as_var() == needle_fr {
720                        return Some(lt);
721                    }
722                }
723
724                (GenericArgKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
725                    search_stack.push((ty, hir_ty.as_unambig_ty()));
726                }
727
728                (GenericArgKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
729                    // Lifetimes cannot be found in consts, so we don't need
730                    // to search anything here.
731                }
732
733                (
734                    GenericArgKind::Lifetime(_)
735                    | GenericArgKind::Type(_)
736                    | GenericArgKind::Const(_),
737                    _,
738                ) => {
739                    self.dcx().span_delayed_bug(
740                        hir_arg.span(),
741                        ::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:?}"),
742                    );
743                }
744            }
745        }
746
747        None
748    }
749
750    /// Finds a closure upvar that contains `fr` and label it with a
751    /// fully elaborated type, returning something like `'1`. Result
752    /// looks like:
753    ///
754    /// ```text
755    ///  | let x = Some(&22);
756    ///        - fully elaborated type of `x` is `Option<&'1 u32>`
757    /// ```
758    #[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(758u32),
                                    ::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))]
759    fn give_name_if_anonymous_region_appears_in_upvars(&self, fr: RegionVid) -> Option<RegionName> {
760        let upvar_index = self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
761
762        // Before synthesizing an anonymous name like `'1`, try to find a
763        // named lifetime from the parent function's signature that matches.
764        if let Some(region_name) = self.give_name_if_we_can_match_upvar_args(fr, upvar_index) {
765            return Some(region_name);
766        }
767
768        let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
769            self.infcx.tcx,
770            self.upvars,
771            upvar_index,
772        );
773        let region_name = self.synthesize_region_name();
774
775        Some(RegionName {
776            name: region_name,
777            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
778        })
779    }
780
781    /// Checks for arguments appearing in the (closure) return type. It
782    /// must be a closure since, in a free fn, such an argument would
783    /// have to either also appear in an argument (if using elision)
784    /// or be early bound (named, not in argument).
785    #[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(785u32),
                                    ::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:790",
                                    "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(790u32),
                                    ::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))]
786    fn give_name_if_anonymous_region_appears_in_output(&self, fr: RegionVid) -> Option<RegionName> {
787        let tcx = self.infcx.tcx;
788
789        let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
790        debug!("give_name_if_anonymous_region_appears_in_output: return_ty = {:?}", return_ty);
791        if !tcx.any_free_region_meets(&return_ty, |r| r.as_var() == fr) {
792            return None;
793        }
794
795        let mir_hir_id = self.mir_hir_id();
796
797        let (return_span, mir_description, hir_ty) = match tcx.hir_node(mir_hir_id) {
798            hir::Node::Expr(&hir::Expr {
799                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl, kind, fn_decl_span, .. }),
800                ..
801            }) => {
802                let (mut span, mut hir_ty) = match fn_decl.output {
803                    hir::FnRetTy::DefaultReturn(_) => {
804                        (tcx.sess.source_map().end_point(fn_decl_span), None)
805                    }
806                    hir::FnRetTy::Return(hir_ty) => (fn_decl.output.span(), Some(hir_ty)),
807                };
808                let mir_description = match kind {
809                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
810                        hir::CoroutineDesugaring::Async,
811                        hir::CoroutineSource::Block,
812                    )) => " of async block",
813
814                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
815                        hir::CoroutineDesugaring::Async,
816                        hir::CoroutineSource::Closure,
817                    ))
818                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
819                        " of async closure"
820                    }
821
822                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
823                        hir::CoroutineDesugaring::Async,
824                        hir::CoroutineSource::Fn,
825                    )) => {
826                        let parent_item =
827                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
828                        let output = &parent_item
829                            .fn_decl()
830                            .expect("coroutine lowered from async fn should be in fn")
831                            .output;
832                        span = output.span();
833                        if let hir::FnRetTy::Return(ret) = output {
834                            hir_ty = Some(self.get_future_inner_return_ty(ret));
835                        }
836                        " of async function"
837                    }
838
839                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
840                        hir::CoroutineDesugaring::Gen,
841                        hir::CoroutineSource::Block,
842                    )) => " of gen block",
843
844                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
845                        hir::CoroutineDesugaring::Gen,
846                        hir::CoroutineSource::Closure,
847                    ))
848                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => {
849                        " of gen closure"
850                    }
851
852                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
853                        hir::CoroutineDesugaring::Gen,
854                        hir::CoroutineSource::Fn,
855                    )) => {
856                        let parent_item =
857                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
858                        let output = &parent_item
859                            .fn_decl()
860                            .expect("coroutine lowered from gen fn should be in fn")
861                            .output;
862                        span = output.span();
863                        " of gen function"
864                    }
865
866                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
867                        hir::CoroutineDesugaring::AsyncGen,
868                        hir::CoroutineSource::Block,
869                    )) => " of async gen block",
870
871                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
872                        hir::CoroutineDesugaring::AsyncGen,
873                        hir::CoroutineSource::Closure,
874                    ))
875                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
876                        " of async gen closure"
877                    }
878
879                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
880                        hir::CoroutineDesugaring::AsyncGen,
881                        hir::CoroutineSource::Fn,
882                    )) => {
883                        let parent_item =
884                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
885                        let output = &parent_item
886                            .fn_decl()
887                            .expect("coroutine lowered from async gen fn should be in fn")
888                            .output;
889                        span = output.span();
890                        " of async gen function"
891                    }
892
893                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => {
894                        " of coroutine"
895                    }
896                    hir::ClosureKind::Closure => " of closure",
897                };
898                (span, mir_description, hir_ty)
899            }
900            node => match node.fn_decl() {
901                Some(fn_decl) => {
902                    let hir_ty = match fn_decl.output {
903                        hir::FnRetTy::DefaultReturn(_) => None,
904                        hir::FnRetTy::Return(ty) => Some(ty),
905                    };
906                    (fn_decl.output.span(), "", hir_ty)
907                }
908                None => (self.body.span, "", None),
909            },
910        };
911
912        let highlight = hir_ty
913            .and_then(|hir_ty| self.highlight_if_we_can_match_hir_ty(fr, return_ty, hir_ty))
914            .unwrap_or_else(|| {
915                // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
916                // the anonymous region. If it succeeds, the `synthesize_region_name` call below
917                // will increment the counter, "reserving" the number we just used.
918                let counter = *self.next_region_name.try_borrow().unwrap();
919                self.highlight_if_we_cannot_match_hir_ty(fr, return_ty, return_span, counter)
920            });
921
922        Some(RegionName {
923            name: self.synthesize_region_name(),
924            source: RegionNameSource::AnonRegionFromOutput(highlight, mir_description),
925        })
926    }
927
928    /// From the [`hir::Ty`] of an async function's lowered return type,
929    /// retrieve the `hir::Ty` representing the type the user originally wrote.
930    ///
931    /// e.g. given the function:
932    ///
933    /// ```
934    /// async fn foo() -> i32 { 2 }
935    /// ```
936    ///
937    /// this function, given the lowered return type of `foo`, an [`OpaqueDef`] that implements
938    /// `Future<Output=i32>`, returns the `i32`.
939    ///
940    /// [`OpaqueDef`]: hir::TyKind::OpaqueDef
941    fn get_future_inner_return_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
942        let hir::TyKind::OpaqueDef(opaque_ty) = hir_ty.kind else {
943            ::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!(
944                hir_ty.span,
945                "lowered return type of async fn is not OpaqueDef: {:?}",
946                hir_ty
947            );
948        };
949        if let hir::OpaqueTy { bounds: [hir::GenericBound::Trait(trait_ref)], .. } = opaque_ty
950            && let Some(segment) = trait_ref.trait_ref.path.segments.last()
951            && let Some(args) = segment.args
952            && let [constraint] = args.constraints
953            && constraint.ident.name == sym::Output
954            && let Some(ty) = constraint.ty()
955        {
956            ty
957        } else {
958            ::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!(
959                hir_ty.span,
960                "bounds from lowered return type of async fn did not match expected format: {opaque_ty:?}",
961            );
962        }
963    }
964
965    #[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(965u32),
                                    ::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:973",
                                    "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(973u32),
                                    ::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:997",
                                    "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(997u32),
                                    ::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))]
966    fn give_name_if_anonymous_region_appears_in_yield_ty(
967        &self,
968        fr: RegionVid,
969    ) -> Option<RegionName> {
970        // Note: coroutines from `async fn` yield `()`, so we don't have to
971        // worry about them here.
972        let yield_ty = self.regioncx.universal_regions().yield_ty?;
973        debug!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}", yield_ty);
974
975        let tcx = self.infcx.tcx;
976
977        if !tcx.any_free_region_meets(&yield_ty, |r| r.as_var() == fr) {
978            return None;
979        }
980
981        let mut highlight = RegionHighlightMode::default();
982        highlight.highlighting_region_vid(tcx, fr, *self.next_region_name.try_borrow().unwrap());
983        let type_name = self
984            .infcx
985            .err_ctxt()
986            .extract_inference_diagnostics_data(yield_ty.into(), highlight)
987            .name;
988
989        let yield_span = match tcx.hir_node(self.mir_hir_id()) {
990            hir::Node::Expr(&hir::Expr {
991                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
992                ..
993            }) => tcx.sess.source_map().end_point(fn_decl_span),
994            _ => self.body.span,
995        };
996
997        debug!(
998            "give_name_if_anonymous_region_appears_in_yield_ty: \
999             type_name = {:?}, yield_span = {:?}",
1000            yield_span, type_name,
1001        );
1002
1003        Some(RegionName {
1004            name: self.synthesize_region_name(),
1005            source: RegionNameSource::AnonRegionFromYieldTy(yield_span, Symbol::intern(&type_name)),
1006        })
1007    }
1008
1009    fn give_name_if_anonymous_region_appears_in_impl_signature(
1010        &self,
1011        fr: RegionVid,
1012    ) -> Option<RegionName> {
1013        let ty::ReEarlyParam(region) = self.to_error_region(fr)?.kind() else {
1014            return None;
1015        };
1016        if region.is_named() {
1017            return None;
1018        };
1019
1020        let tcx = self.infcx.tcx;
1021        let region_def = tcx.generics_of(self.mir_def_id()).region_param(region, tcx).def_id;
1022        let region_parent = tcx.parent(region_def);
1023        let DefKind::Impl { .. } = tcx.def_kind(region_parent) else {
1024            return None;
1025        };
1026
1027        let found = tcx.any_free_region_meets(
1028            &tcx.type_of(region_parent).instantiate_identity().skip_norm_wip(),
1029            |r| r.kind() == ty::ReEarlyParam(region),
1030        );
1031
1032        Some(RegionName {
1033            name: self.synthesize_region_name(),
1034            source: RegionNameSource::AnonRegionFromImplSignature(
1035                tcx.def_span(region_def),
1036                // FIXME(compiler-errors): Does this ever actually show up
1037                // anywhere other than the self type? I couldn't create an
1038                // example of a `'_` in the impl's trait being referenceable.
1039                if found { "self type" } else { "header" },
1040            ),
1041        })
1042    }
1043
1044    fn give_name_if_anonymous_region_appears_in_arg_position_impl_trait(
1045        &self,
1046        fr: RegionVid,
1047    ) -> Option<RegionName> {
1048        let ty::ReEarlyParam(region) = self.to_error_region(fr)?.kind() else {
1049            return None;
1050        };
1051        if region.is_named() {
1052            return None;
1053        };
1054
1055        let predicates: Vec<_> = self
1056            .infcx
1057            .tcx
1058            .predicates_of(self.body.source.def_id())
1059            .instantiate_identity(self.infcx.tcx)
1060            .predicates
1061            .into_iter()
1062            .map(Unnormalized::skip_norm_wip)
1063            .collect();
1064
1065        if let Some(upvar_index) = self
1066            .regioncx
1067            .universal_regions()
1068            .defining_ty
1069            .upvar_tys()
1070            .iter()
1071            .position(|ty| self.any_param_predicate_mentions(&predicates, ty, region))
1072        {
1073            let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
1074                self.infcx.tcx,
1075                self.upvars,
1076                upvar_index,
1077            );
1078            let region_name = self.synthesize_region_name();
1079
1080            Some(RegionName {
1081                name: region_name,
1082                source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
1083            })
1084        } else if let Some(arg_index) = self
1085            .regioncx
1086            .universal_regions()
1087            .unnormalized_input_tys
1088            .iter()
1089            .position(|ty| self.any_param_predicate_mentions(&predicates, *ty, region))
1090        {
1091            let (arg_name, arg_span) = self.regioncx.get_argument_name_and_span_for_region(
1092                self.body,
1093                self.local_names(),
1094                arg_index,
1095            );
1096            let region_name = self.synthesize_region_name();
1097
1098            Some(RegionName {
1099                name: region_name,
1100                source: RegionNameSource::AnonRegionFromArgument(
1101                    RegionNameHighlight::CannotMatchHirTy(arg_span, arg_name?),
1102                ),
1103            })
1104        } else {
1105            None
1106        }
1107    }
1108
1109    fn any_param_predicate_mentions(
1110        &self,
1111        clauses: &[ty::Clause<'tcx>],
1112        ty: Ty<'tcx>,
1113        region: ty::EarlyParamRegion,
1114    ) -> bool {
1115        let tcx = self.infcx.tcx;
1116        ty.walk().any(|arg| {
1117            if let ty::GenericArgKind::Type(ty) = arg.kind()
1118                && let ty::Param(_) = ty.kind()
1119            {
1120                clauses.iter().any(|pred| {
1121                    match pred.kind().skip_binder() {
1122                        ty::ClauseKind::Trait(data) if data.self_ty() == ty => {}
1123                        ty::ClauseKind::Projection(data)
1124                            if data.projection_term.self_ty() == ty => {}
1125                        _ => return false,
1126                    }
1127                    tcx.any_free_region_meets(pred, |r| r.kind() == ty::ReEarlyParam(region))
1128                })
1129            } else {
1130                false
1131            }
1132        })
1133    }
1134}