rustc_borrowck/diagnostics/
region_name.rs

1#![allow(rustc::diagnostic_outside_of_impl)]
2#![allow(rustc::untranslatable_diagnostic)]
3
4use std::fmt::{self, Display};
5use std::iter;
6
7use rustc_data_structures::fx::IndexEntry;
8use rustc_errors::{Diag, EmissionGuarantee};
9use rustc_hir as hir;
10use rustc_hir::def::{DefKind, Res};
11use rustc_middle::ty::print::RegionHighlightMode;
12use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, RegionVid, Ty};
13use rustc_middle::{bug, span_bug};
14use rustc_span::{DUMMY_SP, Span, Symbol, kw, sym};
15use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
16use tracing::{debug, instrument};
17
18use crate::MirBorrowckCtxt;
19use crate::universal_regions::DefiningTy;
20
21/// A name for a particular region used in emitting diagnostics. This name could be a generated
22/// name like `'1`, a name used by the user like `'a`, or a name like `'static`.
23#[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)]
24pub(crate) struct RegionName {
25    /// The name of the region (interned).
26    pub(crate) name: Symbol,
27    /// Where the region comes from.
28    pub(crate) source: RegionNameSource,
29}
30
31/// Denotes the source of a region that is named by a `RegionName`. For example, a free region that
32/// was named by the user would get `NamedLateParamRegion` and `'static` lifetime would get
33/// `Static`. This helps to print the right kinds of diagnostics.
34#[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)]
35pub(crate) enum RegionNameSource {
36    /// A bound (not free) region that was instantiated at the def site (not an HRTB).
37    NamedEarlyParamRegion(Span),
38    /// A free region that the user has a name (`'a`) for.
39    NamedLateParamRegion(Span),
40    /// The `'static` region.
41    Static,
42    /// The free region corresponding to the environment of a closure.
43    SynthesizedFreeEnvRegion(Span, &'static str),
44    /// The region corresponding to an argument.
45    AnonRegionFromArgument(RegionNameHighlight),
46    /// The region corresponding to a closure upvar.
47    AnonRegionFromUpvar(Span, Symbol),
48    /// The region corresponding to the return type of a closure.
49    AnonRegionFromOutput(RegionNameHighlight, &'static str),
50    /// The region from a type yielded by a coroutine.
51    AnonRegionFromYieldTy(Span, Symbol),
52    /// An anonymous region from an async fn.
53    AnonRegionFromAsyncFn(Span),
54    /// An anonymous region from an impl self type or trait
55    AnonRegionFromImplSignature(Span, &'static str),
56}
57
58/// Describes what to highlight to explain to the user that we're giving an anonymous region a
59/// synthesized name, and how to highlight it.
60#[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)]
61pub(crate) enum RegionNameHighlight {
62    /// The anonymous region corresponds to a reference that was found by traversing the type in the HIR.
63    MatchedHirTy(Span),
64    /// The anonymous region corresponds to a `'_` in the generics list of a struct/enum/union.
65    MatchedAdtAndSegment(Span),
66    /// The anonymous region corresponds to a region where the type annotation is completely missing
67    /// from the code, e.g. in a closure arguments `|x| { ... }`, where `x` is a reference.
68    CannotMatchHirTy(Span, Symbol),
69    /// The anonymous region corresponds to a region where the type annotation is completely missing
70    /// from the code, and *even if* we print out the full name of the type, the region name won't
71    /// be included. This currently occurs for opaque types like `impl Future`.
72    Occluded(Span, Symbol),
73}
74
75impl RegionName {
76    pub(crate) fn was_named(&self) -> bool {
77        match self.source {
78            RegionNameSource::NamedEarlyParamRegion(..)
79            | RegionNameSource::NamedLateParamRegion(..)
80            | RegionNameSource::Static => true,
81            RegionNameSource::SynthesizedFreeEnvRegion(..)
82            | RegionNameSource::AnonRegionFromArgument(..)
83            | RegionNameSource::AnonRegionFromUpvar(..)
84            | RegionNameSource::AnonRegionFromOutput(..)
85            | RegionNameSource::AnonRegionFromYieldTy(..)
86            | RegionNameSource::AnonRegionFromAsyncFn(..)
87            | RegionNameSource::AnonRegionFromImplSignature(..) => false,
88        }
89    }
90
91    pub(crate) fn span(&self) -> Option<Span> {
92        match self.source {
93            RegionNameSource::Static => None,
94            RegionNameSource::NamedEarlyParamRegion(span)
95            | RegionNameSource::NamedLateParamRegion(span)
96            | RegionNameSource::SynthesizedFreeEnvRegion(span, _)
97            | RegionNameSource::AnonRegionFromUpvar(span, _)
98            | RegionNameSource::AnonRegionFromYieldTy(span, _)
99            | RegionNameSource::AnonRegionFromAsyncFn(span)
100            | RegionNameSource::AnonRegionFromImplSignature(span, _) => Some(span),
101            RegionNameSource::AnonRegionFromArgument(ref highlight)
102            | RegionNameSource::AnonRegionFromOutput(ref highlight, _) => match *highlight {
103                RegionNameHighlight::MatchedHirTy(span)
104                | RegionNameHighlight::MatchedAdtAndSegment(span)
105                | RegionNameHighlight::CannotMatchHirTy(span, _)
106                | RegionNameHighlight::Occluded(span, _) => Some(span),
107            },
108        }
109    }
110
111    pub(crate) fn highlight_region_name<G: EmissionGuarantee>(&self, diag: &mut Diag<'_, G>) {
112        match &self.source {
113            RegionNameSource::NamedLateParamRegion(span)
114            | RegionNameSource::NamedEarlyParamRegion(span) => {
115                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` defined here",
                self))
    })format!("lifetime `{self}` defined here"));
116            }
117            RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
118                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"));
119                diag.note(*note);
120            }
121            RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::CannotMatchHirTy(
122                span,
123                type_name,
124            )) => {
125                diag.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("has type `{0}`", type_name))
    })format!("has type `{type_name}`"));
126            }
127            RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::MatchedHirTy(span))
128            | RegionNameSource::AnonRegionFromOutput(RegionNameHighlight::MatchedHirTy(span), _)
129            | RegionNameSource::AnonRegionFromAsyncFn(span) => {
130                diag.span_label(
131                    *span,
132                    ::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}`"),
133                );
134            }
135            RegionNameSource::AnonRegionFromArgument(
136                RegionNameHighlight::MatchedAdtAndSegment(span),
137            )
138            | RegionNameSource::AnonRegionFromOutput(
139                RegionNameHighlight::MatchedAdtAndSegment(span),
140                _,
141            ) => {
142                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}`"));
143            }
144            RegionNameSource::AnonRegionFromArgument(RegionNameHighlight::Occluded(
145                span,
146                type_name,
147            )) => {
148                diag.span_label(
149                    *span,
150                    ::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}"),
151                );
152            }
153            RegionNameSource::AnonRegionFromOutput(
154                RegionNameHighlight::Occluded(span, type_name),
155                mir_description,
156            ) => {
157                diag.span_label(
158                    *span,
159                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("return type{0} `{1}` contains a lifetime `{2}`",
                mir_description, type_name, self))
    })format!(
160                        "return type{mir_description} `{type_name}` contains a lifetime `{self}`"
161                    ),
162                );
163            }
164            RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
165                diag.span_label(
166                    *span,
167                    ::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}`"),
168                );
169            }
170            RegionNameSource::AnonRegionFromOutput(
171                RegionNameHighlight::CannotMatchHirTy(span, type_name),
172                mir_description,
173            ) => {
174                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}"));
175            }
176            RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
177                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}"));
178            }
179            RegionNameSource::AnonRegionFromImplSignature(span, location) => {
180                diag.span_label(
181                    *span,
182                    ::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}"),
183                );
184            }
185            RegionNameSource::Static => {}
186        }
187    }
188}
189
190impl Display for RegionName {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        f.write_fmt(format_args!("{0}", self.name))write!(f, "{}", self.name)
193    }
194}
195
196impl rustc_errors::IntoDiagArg for RegionName {
197    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
198        self.to_string().into_diag_arg(path)
199    }
200}
201
202impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
203    pub(crate) fn mir_def_id(&self) -> hir::def_id::LocalDefId {
204        self.body.source.def_id().expect_local()
205    }
206
207    pub(crate) fn mir_hir_id(&self) -> hir::HirId {
208        self.infcx.tcx.local_def_id_to_hir_id(self.mir_def_id())
209    }
210
211    /// Generate a synthetic region named `'N`, where `N` is the next value of the counter. Then,
212    /// increment the counter.
213    ///
214    /// This is _not_ idempotent. Call `give_region_a_name` when possible.
215    pub(crate) fn synthesize_region_name(&self) -> Symbol {
216        let c = self.next_region_name.replace_with(|counter| *counter + 1);
217        Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0:?}", c))
    })format!("'{c:?}"))
218    }
219
220    /// Maps from an internal MIR region vid to something that we can
221    /// report to the user. In some cases, the region vids will map
222    /// directly to lifetimes that the user has a name for (e.g.,
223    /// `'static`). But frequently they will not, in which case we
224    /// have to find some way to identify the lifetime to the user. To
225    /// that end, this function takes a "diagnostic" so that it can
226    /// create auxiliary notes as needed.
227    ///
228    /// The names are memoized, so this is both cheap to recompute and idempotent.
229    ///
230    /// Example (function arguments):
231    ///
232    /// Suppose we are trying to give a name to the lifetime of the
233    /// reference `x`:
234    ///
235    /// ```ignore (pseudo-rust)
236    /// fn foo(x: &u32) { .. }
237    /// ```
238    ///
239    /// This function would create a label like this:
240    ///
241    /// ```text
242    ///  | fn foo(x: &u32) { .. }
243    ///           ------- fully elaborated type of `x` is `&'1 u32`
244    /// ```
245    ///
246    /// and then return the name `'1` for us to use.
247    pub(crate) fn give_region_a_name(&self, fr: RegionVid) -> Option<RegionName> {
248        {
    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:248",
                        "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(248u32),
                        ::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!(
249            "give_region_a_name(fr={:?}, counter={:?})",
250            fr,
251            self.next_region_name.try_borrow().unwrap()
252        );
253
254        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));
255
256        match self.region_names.borrow_mut().entry(fr) {
257            IndexEntry::Occupied(precomputed_name) => Some(*precomputed_name.get()),
258            IndexEntry::Vacant(slot) => {
259                let new_name = self
260                    .give_name_from_error_region(fr)
261                    .or_else(|| self.give_name_if_anonymous_region_appears_in_arguments(fr))
262                    .or_else(|| self.give_name_if_anonymous_region_appears_in_upvars(fr))
263                    .or_else(|| self.give_name_if_anonymous_region_appears_in_output(fr))
264                    .or_else(|| self.give_name_if_anonymous_region_appears_in_yield_ty(fr))
265                    .or_else(|| self.give_name_if_anonymous_region_appears_in_impl_signature(fr))
266                    .or_else(|| {
267                        self.give_name_if_anonymous_region_appears_in_arg_position_impl_trait(fr)
268                    });
269
270                if let Some(new_name) = new_name {
271                    slot.insert(new_name);
272                }
273                {
    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:273",
                        "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(273u32),
                        ::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);
274
275                new_name
276            }
277        }
278    }
279
280    /// Checks for the case where `fr` maps to something that the
281    /// *user* has a name for. In that case, we'll be able to map
282    /// `fr` to a `Region<'tcx>`, and that region will be one of
283    /// named variants.
284    #[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(284u32),
                                    ::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:290",
                                    "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(290u32),
                                    ::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))]
285    fn give_name_from_error_region(&self, fr: RegionVid) -> Option<RegionName> {
286        let error_region = self.to_error_region(fr)?;
287
288        let tcx = self.infcx.tcx;
289
290        debug!("give_region_a_name: error_region = {:?}", error_region);
291        match error_region.kind() {
292            ty::ReEarlyParam(ebr) => ebr.is_named().then(|| {
293                let def_id = tcx.generics_of(self.mir_def_id()).region_param(ebr, tcx).def_id;
294                let span = tcx.hir_span_if_local(def_id).unwrap_or(DUMMY_SP);
295                RegionName { name: ebr.name, source: RegionNameSource::NamedEarlyParamRegion(span) }
296            }),
297
298            ty::ReStatic => {
299                Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })
300            }
301
302            ty::ReLateParam(late_param) => match late_param.kind {
303                ty::LateParamRegionKind::Named(region_def_id) => {
304                    // Get the span to point to, even if we don't use the name.
305                    let span = tcx.hir_span_if_local(region_def_id).unwrap_or(DUMMY_SP);
306
307                    if let Some(name) = late_param.kind.get_name(tcx) {
308                        // A named region that is actually named.
309                        Some(RegionName {
310                            name,
311                            source: RegionNameSource::NamedLateParamRegion(span),
312                        })
313                    } else if tcx.asyncness(self.mir_hir_id().owner).is_async() {
314                        // If we spuriously thought that the region is named, we should let the
315                        // system generate a true name for error messages. Currently this can
316                        // happen if we have an elided name in an async fn for example: the
317                        // compiler will generate a region named `'_`, but reporting such a name is
318                        // not actually useful, so we synthesize a name for it instead.
319                        let name = self.synthesize_region_name();
320                        Some(RegionName {
321                            name,
322                            source: RegionNameSource::AnonRegionFromAsyncFn(span),
323                        })
324                    } else {
325                        None
326                    }
327                }
328
329                ty::LateParamRegionKind::ClosureEnv => {
330                    let def_ty = self.regioncx.universal_regions().defining_ty;
331
332                    let closure_kind = match def_ty {
333                        DefiningTy::Closure(_, args) => args.as_closure().kind(),
334                        DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().kind(),
335                        _ => {
336                            // Can't have BrEnv in functions, constants or coroutines.
337                            bug!("BrEnv outside of closure.");
338                        }
339                    };
340                    let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) =
341                        tcx.hir_expect_expr(self.mir_hir_id()).kind
342                    else {
343                        bug!("Closure is not defined by a closure expr");
344                    };
345                    let region_name = self.synthesize_region_name();
346                    let note = match closure_kind {
347                        ty::ClosureKind::Fn => {
348                            "closure implements `Fn`, so references to captured variables \
349                             can't escape the closure"
350                        }
351                        ty::ClosureKind::FnMut => {
352                            "closure implements `FnMut`, so references to captured variables \
353                             can't escape the closure"
354                        }
355                        ty::ClosureKind::FnOnce => {
356                            bug!("BrEnv in a `FnOnce` closure");
357                        }
358                    };
359
360                    Some(RegionName {
361                        name: region_name,
362                        source: RegionNameSource::SynthesizedFreeEnvRegion(fn_decl_span, note),
363                    })
364                }
365
366                ty::LateParamRegionKind::Anon(_) => None,
367                ty::LateParamRegionKind::NamedAnon(_, _) => bug!("only used for pretty printing"),
368            },
369
370            ty::ReBound(..)
371            | ty::ReVar(..)
372            | ty::RePlaceholder(..)
373            | ty::ReErased
374            | ty::ReError(_) => None,
375        }
376    }
377
378    /// Finds an argument that contains `fr` and label it with a fully
379    /// elaborated type, returning something like `'1`. Result looks
380    /// like:
381    ///
382    /// ```text
383    ///  | fn foo(x: &u32) { .. }
384    ///           ------- fully elaborated type of `x` is `&'1 u32`
385    /// ```
386    #[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(386u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_name"),
                                    ::tracing_core::field::FieldSet::new(&["fr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<RegionName> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let upvar_index =
                self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
            let (upvar_name, upvar_span) =
                self.regioncx.get_upvar_name_and_span_for_region(self.infcx.tcx,
                    self.upvars, upvar_index);
            let region_name = self.synthesize_region_name();
            Some(RegionName {
                    name: region_name,
                    source: RegionNameSource::AnonRegionFromUpvar(upvar_span,
                        upvar_name),
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
648    fn give_name_if_anonymous_region_appears_in_upvars(&self, fr: RegionVid) -> Option<RegionName> {
649        let upvar_index = self.regioncx.get_upvar_index_for_region(self.infcx.tcx, fr)?;
650        let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
651            self.infcx.tcx,
652            self.upvars,
653            upvar_index,
654        );
655        let region_name = self.synthesize_region_name();
656
657        Some(RegionName {
658            name: region_name,
659            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
660        })
661    }
662
663    /// Checks for arguments appearing in the (closure) return type. It
664    /// must be a closure since, in a free fn, such an argument would
665    /// have to either also appear in an argument (if using elision)
666    /// or be early bound (named, not in argument).
667    #[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(667u32),
                                    ::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:672",
                                    "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(672u32),
                                    ::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))]
668    fn give_name_if_anonymous_region_appears_in_output(&self, fr: RegionVid) -> Option<RegionName> {
669        let tcx = self.infcx.tcx;
670
671        let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
672        debug!("give_name_if_anonymous_region_appears_in_output: return_ty = {:?}", return_ty);
673        if !tcx.any_free_region_meets(&return_ty, |r| r.as_var() == fr) {
674            return None;
675        }
676
677        let mir_hir_id = self.mir_hir_id();
678
679        let (return_span, mir_description, hir_ty) = match tcx.hir_node(mir_hir_id) {
680            hir::Node::Expr(&hir::Expr {
681                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl, kind, fn_decl_span, .. }),
682                ..
683            }) => {
684                let (mut span, mut hir_ty) = match fn_decl.output {
685                    hir::FnRetTy::DefaultReturn(_) => {
686                        (tcx.sess.source_map().end_point(fn_decl_span), None)
687                    }
688                    hir::FnRetTy::Return(hir_ty) => (fn_decl.output.span(), Some(hir_ty)),
689                };
690                let mir_description = match kind {
691                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
692                        hir::CoroutineDesugaring::Async,
693                        hir::CoroutineSource::Block,
694                    )) => " of async block",
695
696                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
697                        hir::CoroutineDesugaring::Async,
698                        hir::CoroutineSource::Closure,
699                    ))
700                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
701                        " of async closure"
702                    }
703
704                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
705                        hir::CoroutineDesugaring::Async,
706                        hir::CoroutineSource::Fn,
707                    )) => {
708                        let parent_item =
709                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
710                        let output = &parent_item
711                            .fn_decl()
712                            .expect("coroutine lowered from async fn should be in fn")
713                            .output;
714                        span = output.span();
715                        if let hir::FnRetTy::Return(ret) = output {
716                            hir_ty = Some(self.get_future_inner_return_ty(ret));
717                        }
718                        " of async function"
719                    }
720
721                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
722                        hir::CoroutineDesugaring::Gen,
723                        hir::CoroutineSource::Block,
724                    )) => " of gen block",
725
726                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
727                        hir::CoroutineDesugaring::Gen,
728                        hir::CoroutineSource::Closure,
729                    ))
730                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => {
731                        " of gen closure"
732                    }
733
734                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
735                        hir::CoroutineDesugaring::Gen,
736                        hir::CoroutineSource::Fn,
737                    )) => {
738                        let parent_item =
739                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
740                        let output = &parent_item
741                            .fn_decl()
742                            .expect("coroutine lowered from gen fn should be in fn")
743                            .output;
744                        span = output.span();
745                        " of gen function"
746                    }
747
748                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
749                        hir::CoroutineDesugaring::AsyncGen,
750                        hir::CoroutineSource::Block,
751                    )) => " of async gen block",
752
753                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
754                        hir::CoroutineDesugaring::AsyncGen,
755                        hir::CoroutineSource::Closure,
756                    ))
757                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
758                        " of async gen closure"
759                    }
760
761                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
762                        hir::CoroutineDesugaring::AsyncGen,
763                        hir::CoroutineSource::Fn,
764                    )) => {
765                        let parent_item =
766                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(mir_hir_id).def_id);
767                        let output = &parent_item
768                            .fn_decl()
769                            .expect("coroutine lowered from async gen fn should be in fn")
770                            .output;
771                        span = output.span();
772                        " of async gen function"
773                    }
774
775                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => {
776                        " of coroutine"
777                    }
778                    hir::ClosureKind::Closure => " of closure",
779                };
780                (span, mir_description, hir_ty)
781            }
782            node => match node.fn_decl() {
783                Some(fn_decl) => {
784                    let hir_ty = match fn_decl.output {
785                        hir::FnRetTy::DefaultReturn(_) => None,
786                        hir::FnRetTy::Return(ty) => Some(ty),
787                    };
788                    (fn_decl.output.span(), "", hir_ty)
789                }
790                None => (self.body.span, "", None),
791            },
792        };
793
794        let highlight = hir_ty
795            .and_then(|hir_ty| self.highlight_if_we_can_match_hir_ty(fr, return_ty, hir_ty))
796            .unwrap_or_else(|| {
797                // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
798                // the anonymous region. If it succeeds, the `synthesize_region_name` call below
799                // will increment the counter, "reserving" the number we just used.
800                let counter = *self.next_region_name.try_borrow().unwrap();
801                self.highlight_if_we_cannot_match_hir_ty(fr, return_ty, return_span, counter)
802            });
803
804        Some(RegionName {
805            name: self.synthesize_region_name(),
806            source: RegionNameSource::AnonRegionFromOutput(highlight, mir_description),
807        })
808    }
809
810    /// From the [`hir::Ty`] of an async function's lowered return type,
811    /// retrieve the `hir::Ty` representing the type the user originally wrote.
812    ///
813    /// e.g. given the function:
814    ///
815    /// ```
816    /// async fn foo() -> i32 { 2 }
817    /// ```
818    ///
819    /// this function, given the lowered return type of `foo`, an [`OpaqueDef`] that implements
820    /// `Future<Output=i32>`, returns the `i32`.
821    ///
822    /// [`OpaqueDef`]: hir::TyKind::OpaqueDef
823    fn get_future_inner_return_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
824        let hir::TyKind::OpaqueDef(opaque_ty) = hir_ty.kind else {
825            ::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!(
826                hir_ty.span,
827                "lowered return type of async fn is not OpaqueDef: {:?}",
828                hir_ty
829            );
830        };
831        if let hir::OpaqueTy { bounds: [hir::GenericBound::Trait(trait_ref)], .. } = opaque_ty
832            && let Some(segment) = trait_ref.trait_ref.path.segments.last()
833            && let Some(args) = segment.args
834            && let [constraint] = args.constraints
835            && constraint.ident.name == sym::Output
836            && let Some(ty) = constraint.ty()
837        {
838            ty
839        } else {
840            ::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!(
841                hir_ty.span,
842                "bounds from lowered return type of async fn did not match expected format: {opaque_ty:?}",
843            );
844        }
845    }
846
847    #[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(847u32),
                                    ::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:855",
                                    "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(855u32),
                                    ::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:879",
                                    "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(879u32),
                                    ::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))]
848    fn give_name_if_anonymous_region_appears_in_yield_ty(
849        &self,
850        fr: RegionVid,
851    ) -> Option<RegionName> {
852        // Note: coroutines from `async fn` yield `()`, so we don't have to
853        // worry about them here.
854        let yield_ty = self.regioncx.universal_regions().yield_ty?;
855        debug!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}", yield_ty);
856
857        let tcx = self.infcx.tcx;
858
859        if !tcx.any_free_region_meets(&yield_ty, |r| r.as_var() == fr) {
860            return None;
861        }
862
863        let mut highlight = RegionHighlightMode::default();
864        highlight.highlighting_region_vid(tcx, fr, *self.next_region_name.try_borrow().unwrap());
865        let type_name = self
866            .infcx
867            .err_ctxt()
868            .extract_inference_diagnostics_data(yield_ty.into(), highlight)
869            .name;
870
871        let yield_span = match tcx.hir_node(self.mir_hir_id()) {
872            hir::Node::Expr(&hir::Expr {
873                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
874                ..
875            }) => tcx.sess.source_map().end_point(fn_decl_span),
876            _ => self.body.span,
877        };
878
879        debug!(
880            "give_name_if_anonymous_region_appears_in_yield_ty: \
881             type_name = {:?}, yield_span = {:?}",
882            yield_span, type_name,
883        );
884
885        Some(RegionName {
886            name: self.synthesize_region_name(),
887            source: RegionNameSource::AnonRegionFromYieldTy(yield_span, Symbol::intern(&type_name)),
888        })
889    }
890
891    fn give_name_if_anonymous_region_appears_in_impl_signature(
892        &self,
893        fr: RegionVid,
894    ) -> Option<RegionName> {
895        let ty::ReEarlyParam(region) = self.to_error_region(fr)?.kind() else {
896            return None;
897        };
898        if region.is_named() {
899            return None;
900        };
901
902        let tcx = self.infcx.tcx;
903        let region_def = tcx.generics_of(self.mir_def_id()).region_param(region, tcx).def_id;
904        let region_parent = tcx.parent(region_def);
905        let DefKind::Impl { .. } = tcx.def_kind(region_parent) else {
906            return None;
907        };
908
909        let found = tcx
910            .any_free_region_meets(&tcx.type_of(region_parent).instantiate_identity(), |r| {
911                r.kind() == ty::ReEarlyParam(region)
912            });
913
914        Some(RegionName {
915            name: self.synthesize_region_name(),
916            source: RegionNameSource::AnonRegionFromImplSignature(
917                tcx.def_span(region_def),
918                // FIXME(compiler-errors): Does this ever actually show up
919                // anywhere other than the self type? I couldn't create an
920                // example of a `'_` in the impl's trait being referenceable.
921                if found { "self type" } else { "header" },
922            ),
923        })
924    }
925
926    fn give_name_if_anonymous_region_appears_in_arg_position_impl_trait(
927        &self,
928        fr: RegionVid,
929    ) -> Option<RegionName> {
930        let ty::ReEarlyParam(region) = self.to_error_region(fr)?.kind() else {
931            return None;
932        };
933        if region.is_named() {
934            return None;
935        };
936
937        let predicates = self
938            .infcx
939            .tcx
940            .predicates_of(self.body.source.def_id())
941            .instantiate_identity(self.infcx.tcx)
942            .predicates;
943
944        if let Some(upvar_index) = self
945            .regioncx
946            .universal_regions()
947            .defining_ty
948            .upvar_tys()
949            .iter()
950            .position(|ty| self.any_param_predicate_mentions(&predicates, ty, region))
951        {
952            let (upvar_name, upvar_span) = self.regioncx.get_upvar_name_and_span_for_region(
953                self.infcx.tcx,
954                self.upvars,
955                upvar_index,
956            );
957            let region_name = self.synthesize_region_name();
958
959            Some(RegionName {
960                name: region_name,
961                source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
962            })
963        } else if let Some(arg_index) = self
964            .regioncx
965            .universal_regions()
966            .unnormalized_input_tys
967            .iter()
968            .position(|ty| self.any_param_predicate_mentions(&predicates, *ty, region))
969        {
970            let (arg_name, arg_span) = self.regioncx.get_argument_name_and_span_for_region(
971                self.body,
972                self.local_names(),
973                arg_index,
974            );
975            let region_name = self.synthesize_region_name();
976
977            Some(RegionName {
978                name: region_name,
979                source: RegionNameSource::AnonRegionFromArgument(
980                    RegionNameHighlight::CannotMatchHirTy(arg_span, arg_name?),
981                ),
982            })
983        } else {
984            None
985        }
986    }
987
988    fn any_param_predicate_mentions(
989        &self,
990        clauses: &[ty::Clause<'tcx>],
991        ty: Ty<'tcx>,
992        region: ty::EarlyParamRegion,
993    ) -> bool {
994        let tcx = self.infcx.tcx;
995        ty.walk().any(|arg| {
996            if let ty::GenericArgKind::Type(ty) = arg.kind()
997                && let ty::Param(_) = ty.kind()
998            {
999                clauses.iter().any(|pred| {
1000                    match pred.kind().skip_binder() {
1001                        ty::ClauseKind::Trait(data) if data.self_ty() == ty => {}
1002                        ty::ClauseKind::Projection(data)
1003                            if data.projection_term.self_ty() == ty => {}
1004                        _ => return false,
1005                    }
1006                    tcx.any_free_region_meets(pred, |r| r.kind() == ty::ReEarlyParam(region))
1007                })
1008            } else {
1009                false
1010            }
1011        })
1012    }
1013}