Skip to main content

rustc_hir_analysis/collect/
resolve_bound_vars.rs

1//! Resolution of early vs late bound lifetimes.
2//!
3//! Name resolution for lifetimes is performed on the AST and embedded into HIR. From this
4//! information, typechecking needs to transform the lifetime parameters into bound lifetimes.
5//! Lifetimes can be early-bound or late-bound. Construction of typechecking terms needs to visit
6//! the types in HIR to identify late-bound lifetimes and assign their Debruijn indices. This file
7//! is also responsible for assigning their semantics to implicit lifetimes in trait objects.
8
9use std::cell::RefCell;
10use std::fmt;
11use std::ops::ControlFlow;
12
13use rustc_ast::visit::walk_list;
14use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
15use rustc_errors::ErrorGuaranteed;
16use rustc_hir::def::{DefKind, Res};
17use rustc_hir::def_id::LocalDefIdMap;
18use rustc_hir::definitions::{DefPathData, PerParentDisambiguatorsMap};
19use rustc_hir::intravisit::{self, InferKind, Visitor};
20use rustc_hir::{
21    self as hir, AmbigArg, GenericArg, GenericParam, GenericParamKind, HirId, LifetimeKind, Node,
22};
23use rustc_macros::extension;
24use rustc_middle::hir::nested_filter;
25use rustc_middle::middle::resolve_bound_vars::*;
26use rustc_middle::query::Providers;
27use rustc_middle::ty::{self, TyCtxt, TypeSuperVisitable, TypeVisitor, Unnormalized};
28use rustc_middle::{bug, span_bug};
29use rustc_span::def_id::{DefId, LocalDefId};
30use rustc_span::{Ident, Span, sym};
31use tracing::{debug, debug_span, instrument};
32
33use crate::diagnostics;
34use crate::hir::definitions::PerParentDisambiguatorState;
35
36trait ResolvedArgExt {
    fn early(param: &GenericParam<'_>)
    -> ResolvedArg;
    fn late(idx: u32, param: &GenericParam<'_>)
    -> ResolvedArg;
    fn id(&self)
    -> Option<LocalDefId>;
    fn shifted(self, amount: u32)
    -> ResolvedArg;
}
impl ResolvedArgExt for ResolvedArg {
    fn early(param: &GenericParam<'_>) -> ResolvedArg {
        ResolvedArg::EarlyBound(param.def_id)
    }
    fn late(idx: u32, param: &GenericParam<'_>) -> ResolvedArg {
        ResolvedArg::LateBound(ty::INNERMOST, idx, param.def_id)
    }
    fn id(&self) -> Option<LocalDefId> {
        match *self {
            ResolvedArg::StaticLifetime | ResolvedArg::Error(_) => None,
            ResolvedArg::EarlyBound(id) | ResolvedArg::LateBound(_, _, id) |
                ResolvedArg::Free(_, id) => Some(id),
        }
    }
    fn shifted(self, amount: u32) -> ResolvedArg {
        match self {
            ResolvedArg::LateBound(debruijn, idx, id) => {
                ResolvedArg::LateBound(debruijn.shifted_in(amount), idx, id)
            }
            _ => self,
        }
    }
}#[extension(trait ResolvedArgExt)]
37impl ResolvedArg {
38    fn early(param: &GenericParam<'_>) -> ResolvedArg {
39        ResolvedArg::EarlyBound(param.def_id)
40    }
41
42    fn late(idx: u32, param: &GenericParam<'_>) -> ResolvedArg {
43        ResolvedArg::LateBound(ty::INNERMOST, idx, param.def_id)
44    }
45
46    fn id(&self) -> Option<LocalDefId> {
47        match *self {
48            ResolvedArg::StaticLifetime | ResolvedArg::Error(_) => None,
49
50            ResolvedArg::EarlyBound(id)
51            | ResolvedArg::LateBound(_, _, id)
52            | ResolvedArg::Free(_, id) => Some(id),
53        }
54    }
55
56    fn shifted(self, amount: u32) -> ResolvedArg {
57        match self {
58            ResolvedArg::LateBound(debruijn, idx, id) => {
59                ResolvedArg::LateBound(debruijn.shifted_in(amount), idx, id)
60            }
61            _ => self,
62        }
63    }
64}
65
66struct BoundVarContext<'a, 'tcx> {
67    tcx: TyCtxt<'tcx>,
68    rbv: &'a mut ResolveBoundVars<'tcx>,
69    disambiguators: &'a mut LocalDefIdMap<PerParentDisambiguatorState>,
70    scope: ScopeRef<'a, 'tcx>,
71    opaque_capture_errors: RefCell<Option<OpaqueHigherRankedLifetimeCaptureErrors>>,
72}
73
74struct OpaqueHigherRankedLifetimeCaptureErrors {
75    bad_place: &'static str,
76    capture_spans: Vec<Span>,
77    decl_spans: Vec<Span>,
78}
79
80#[derive(#[automatically_derived]
impl<'a, 'tcx> ::core::fmt::Debug for Scope<'a, 'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Scope::Binder {
                bound_vars: __self_0,
                scope_type: __self_1,
                hir_id: __self_2,
                s: __self_3,
                where_bound_origin: __self_4 } =>
                ::core::fmt::Formatter::debug_struct_field5_finish(f,
                    "Binder", "bound_vars", __self_0, "scope_type", __self_1,
                    "hir_id", __self_2, "s", __self_3, "where_bound_origin",
                    &__self_4),
            Scope::Body { id: __self_0, s: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Body",
                    "id", __self_0, "s", &__self_1),
            Scope::ObjectLifetimeDefault { lifetime: __self_0, s: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ObjectLifetimeDefault", "lifetime", __self_0, "s",
                    &__self_1),
            Scope::Supertrait { bound_vars: __self_0, s: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Supertrait", "bound_vars", __self_0, "s", &__self_1),
            Scope::TraitRefBoundary { s: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TraitRefBoundary", "s", &__self_0),
            Scope::Opaque { def_id: __self_0, captures: __self_1, s: __self_2
                } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "Opaque", "def_id", __self_0, "captures", __self_1, "s",
                    &__self_2),
            Scope::LateBoundary {
                s: __self_0, what: __self_1, deny_late_regions: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "LateBoundary", "s", __self_0, "what", __self_1,
                    "deny_late_regions", &__self_2),
            Scope::Root { opt_parent_item: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Root",
                    "opt_parent_item", &__self_0),
        }
    }
}Debug)]
81enum Scope<'a, 'tcx> {
82    /// Declares lifetimes, and each can be early-bound or late-bound.
83    /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
84    /// it should be shifted by the number of `Binder`s in between the
85    /// declaration `Binder` and the location it's referenced from.
86    Binder {
87        /// We use an IndexMap here because we want these lifetimes in order
88        /// for diagnostics.
89        bound_vars: FxIndexMap<LocalDefId, ResolvedArg>,
90
91        scope_type: BinderScopeType,
92
93        /// The late bound vars for a given item are stored by `HirId` to be
94        /// queried later. However, if we enter an elision scope, we have to
95        /// later append the elided bound vars to the list and need to know what
96        /// to append to.
97        hir_id: HirId,
98
99        s: ScopeRef<'a, 'tcx>,
100
101        /// If this binder comes from a where clause, specify how it was created.
102        /// This is used to diagnose inaccessible lifetimes in APIT:
103        /// ```ignore (illustrative)
104        /// fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {}
105        /// ```
106        where_bound_origin: Option<hir::PredicateOrigin>,
107    },
108
109    /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
110    /// if this is a fn body, otherwise the original definitions are used.
111    /// Unspecified lifetimes are inferred, unless an elision scope is nested,
112    /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
113    Body {
114        id: hir::BodyId,
115        s: ScopeRef<'a, 'tcx>,
116    },
117
118    /// Use a specific lifetime (if `Some`) or leave it unset (to be
119    /// inferred in a function body or potentially error outside one),
120    /// for the default choice of lifetime in a trait object type.
121    ObjectLifetimeDefault {
122        lifetime: Option<ResolvedArg>,
123        s: ScopeRef<'a, 'tcx>,
124    },
125
126    /// When we have nested trait refs, we concatenate late bound vars for inner
127    /// trait refs from outer ones. But we also need to include any HRTB
128    /// lifetimes encountered when identifying the trait that an associated type
129    /// is declared on.
130    Supertrait {
131        bound_vars: Vec<ty::BoundVariableKind<'tcx>>,
132        s: ScopeRef<'a, 'tcx>,
133    },
134
135    TraitRefBoundary {
136        s: ScopeRef<'a, 'tcx>,
137    },
138
139    /// Remap lifetimes that appear in opaque types to fresh lifetime parameters. Given:
140    /// `fn foo<'a>() -> impl MyTrait<'a> { ... }`
141    ///
142    /// HIR tells us that `'a` refer to the lifetime bound on `foo`.
143    /// However, typeck and borrowck for opaques work based on using a new generic type.
144    /// `type MyAnonTy<'b> = impl MyTrait<'b>;`
145    ///
146    /// This scope collects the mapping `'a -> 'b`.
147    Opaque {
148        /// The opaque type we are traversing.
149        def_id: LocalDefId,
150        /// Mapping from each captured lifetime `'a` to the duplicate generic parameter `'b`.
151        captures: &'a RefCell<FxIndexMap<ResolvedArg, LocalDefId>>,
152
153        s: ScopeRef<'a, 'tcx>,
154    },
155
156    /// Disallows capturing late-bound vars from parent scopes.
157    ///
158    /// This is necessary for something like `for<T> [(); { /* references T */ }]:`,
159    /// since we don't do something more correct like replacing any captured
160    /// late-bound vars with early-bound params in the const's own generics.
161    LateBoundary {
162        s: ScopeRef<'a, 'tcx>,
163        what: &'static str,
164        deny_late_regions: bool,
165    },
166
167    Root {
168        opt_parent_item: Option<LocalDefId>,
169    },
170}
171
172impl<'a, 'tcx> Scope<'a, 'tcx> {
173    // A helper for debugging scopes without printing parent scopes
174    fn debug_truncated(&self) -> impl fmt::Debug {
175        fmt::from_fn(move |f| match self {
176            Self::Binder { bound_vars, scope_type, hir_id, where_bound_origin, s: _ } => f
177                .debug_struct("Binder")
178                .field("bound_vars", bound_vars)
179                .field("scope_type", scope_type)
180                .field("hir_id", hir_id)
181                .field("where_bound_origin", where_bound_origin)
182                .field("s", &"..")
183                .finish(),
184            Self::Opaque { captures, def_id, s: _ } => f
185                .debug_struct("Opaque")
186                .field("def_id", def_id)
187                .field("captures", &captures.borrow())
188                .field("s", &"..")
189                .finish(),
190            Self::Body { id, s: _ } => {
191                f.debug_struct("Body").field("id", id).field("s", &"..").finish()
192            }
193            Self::ObjectLifetimeDefault { lifetime, s: _ } => f
194                .debug_struct("ObjectLifetimeDefault")
195                .field("lifetime", lifetime)
196                .field("s", &"..")
197                .finish(),
198            Self::Supertrait { bound_vars, s: _ } => f
199                .debug_struct("Supertrait")
200                .field("bound_vars", bound_vars)
201                .field("s", &"..")
202                .finish(),
203            Self::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
204            Self::LateBoundary { s: _, what, deny_late_regions } => f
205                .debug_struct("LateBoundary")
206                .field("what", what)
207                .field("deny_late_regions", deny_late_regions)
208                .finish(),
209            Self::Root { opt_parent_item } => {
210                f.debug_struct("Root").field("opt_parent_item", &opt_parent_item).finish()
211            }
212        })
213    }
214}
215
216#[derive(#[automatically_derived]
impl ::core::marker::Copy for BinderScopeType { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BinderScopeType { }
#[automatically_derived]
impl ::core::clone::Clone for BinderScopeType {
    #[inline]
    fn clone(&self) -> BinderScopeType { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for BinderScopeType {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                BinderScopeType::Normal => "Normal",
                BinderScopeType::Concatenating => "Concatenating",
            })
    }
}Debug)]
217enum BinderScopeType {
218    /// Any non-concatenating binder scopes.
219    Normal,
220    /// Within a syntactic trait ref, there may be multiple poly trait refs that
221    /// are nested (under the `associated_type_bounds` feature). The binders of
222    /// the inner poly trait refs are extended from the outer poly trait refs
223    /// and don't increase the late bound depth. If you had
224    /// `T: for<'a>  Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
225    /// would be `Concatenating`. This also used in trait refs in where clauses
226    /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
227    /// out any lifetimes because they aren't needed to show the two scopes).
228    /// The inner `for<>` has a scope of `Concatenating`.
229    Concatenating,
230}
231
232type ScopeRef<'a, 'tcx> = &'a Scope<'a, 'tcx>;
233
234/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]
235pub(crate) fn provide(providers: &mut Providers) {
236    *providers = Providers {
237        resolve_bound_vars,
238
239        named_variable_map: |tcx, id| &tcx.resolve_bound_vars(id).defs,
240        is_late_bound_map,
241        object_lifetime_default,
242        late_bound_vars_map: |tcx, id| &tcx.resolve_bound_vars(id).late_bound_vars,
243        opaque_captured_lifetimes: |tcx, id| {
244            &tcx.resolve_bound_vars(tcx.local_def_id_to_hir_id(id).owner)
245                .opaque_captured_lifetimes
246                .get(&id)
247                .map_or(&[][..], |x| &x[..])
248        },
249
250        ..*providers
251    };
252}
253
254/// Computes the `ResolveBoundVars` map that contains data for an entire `Item`.
255/// You should not read the result of this query directly, but rather use
256/// `named_variable_map`, `late_bound_vars_map`, etc.
257{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("resolve_bound_vars",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(257u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("local_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("local_def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local_def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ResolveBoundVars<'_> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut rbv = ResolveBoundVars::default();
            let mut visitor =
                BoundVarContext {
                    tcx,
                    rbv: &mut rbv,
                    scope: &Scope::Root { opt_parent_item: None },
                    disambiguators: &mut Default::default(),
                    opaque_capture_errors: RefCell::new(None),
                };
            match tcx.hir_owner_node(local_def_id) {
                hir::OwnerNode::Item(item) => visitor.visit_item(item),
                hir::OwnerNode::ForeignItem(item) =>
                    visitor.visit_foreign_item(item),
                hir::OwnerNode::TraitItem(item) => {
                    let scope =
                        Scope::Root {
                            opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)),
                        };
                    visitor.scope = &scope;
                    visitor.visit_trait_item(item)
                }
                hir::OwnerNode::ImplItem(item) => {
                    let scope =
                        Scope::Root {
                            opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)),
                        };
                    visitor.scope = &scope;
                    visitor.visit_impl_item(item)
                }
                hir::OwnerNode::Crate(_) => {}
                hir::OwnerNode::Synthetic =>
                    ::core::panicking::panic("internal error: entered unreachable code"),
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:286",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(286u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rbv.defs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rbv.defs");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rbv.defs)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:287",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(287u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rbv.late_bound_vars")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rbv.late_bound_vars");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rbv.late_bound_vars)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:288",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(288u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rbv.opaque_captured_lifetimes")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rbv.opaque_captured_lifetimes");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rbv.opaque_captured_lifetimes)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            rbv
        }
    }
}#[instrument(level = "debug", skip(tcx))]
258fn resolve_bound_vars(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveBoundVars<'_> {
259    let mut rbv = ResolveBoundVars::default();
260    let mut visitor = BoundVarContext {
261        tcx,
262        rbv: &mut rbv,
263        scope: &Scope::Root { opt_parent_item: None },
264        disambiguators: &mut Default::default(),
265        opaque_capture_errors: RefCell::new(None),
266    };
267    match tcx.hir_owner_node(local_def_id) {
268        hir::OwnerNode::Item(item) => visitor.visit_item(item),
269        hir::OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
270        hir::OwnerNode::TraitItem(item) => {
271            let scope =
272                Scope::Root { opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)) };
273            visitor.scope = &scope;
274            visitor.visit_trait_item(item)
275        }
276        hir::OwnerNode::ImplItem(item) => {
277            let scope =
278                Scope::Root { opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)) };
279            visitor.scope = &scope;
280            visitor.visit_impl_item(item)
281        }
282        hir::OwnerNode::Crate(_) => {}
283        hir::OwnerNode::Synthetic => unreachable!(),
284    }
285
286    debug!(?rbv.defs);
287    debug!(?rbv.late_bound_vars);
288    debug!(?rbv.opaque_captured_lifetimes);
289    rbv
290}
291
292fn late_arg_as_bound_arg<'tcx>(param: &GenericParam<'tcx>) -> ty::BoundVariableKind<'tcx> {
293    let def_id = param.def_id.to_def_id();
294    match param.kind {
295        GenericParamKind::Lifetime { .. } => {
296            ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id))
297        }
298        GenericParamKind::Type { .. } => ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)),
299        GenericParamKind::Const { .. } => ty::BoundVariableKind::Const,
300    }
301}
302
303/// Turn a [`ty::GenericParamDef`] into a bound arg. Generally, this should only
304/// be used when turning early-bound vars into late-bound vars when lowering
305/// return type notation.
306fn generic_param_def_as_bound_arg<'tcx>(
307    param: &ty::GenericParamDef,
308) -> ty::BoundVariableKind<'tcx> {
309    match param.kind {
310        ty::GenericParamDefKind::Lifetime => {
311            ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(param.def_id))
312        }
313        ty::GenericParamDefKind::Type { .. } => {
314            ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(param.def_id))
315        }
316        ty::GenericParamDefKind::Const { .. } => ty::BoundVariableKind::Const,
317    }
318}
319
320/// Whether this opaque always captures lifetimes in scope.
321/// Right now, this is all RPITIT and TAITs, and when the opaque
322/// is coming from a span corresponding to edition 2024.
323fn opaque_captures_all_in_scope_lifetimes<'tcx>(opaque: &'tcx hir::OpaqueTy<'tcx>) -> bool {
324    match opaque.origin {
325        // if the opaque has the `use<...>` syntax, the user is telling us that they only want
326        // to account for those lifetimes, so do not try to be clever.
327        _ if opaque.bounds.iter().any(|bound| #[allow(non_exhaustive_omitted_patterns)] match bound {
    hir::GenericBound::Use(..) => true,
    _ => false,
}matches!(bound, hir::GenericBound::Use(..))) => false,
328        hir::OpaqueTyOrigin::AsyncFn { .. } | hir::OpaqueTyOrigin::TyAlias { .. } => true,
329        _ if opaque.span.at_least_rust_2024() => true,
330        hir::OpaqueTyOrigin::FnReturn { in_trait_or_impl, .. } => in_trait_or_impl.is_some(),
331    }
332}
333
334impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
335    /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
336    fn poly_trait_ref_binder_info(
337        &mut self,
338    ) -> (Vec<ty::BoundVariableKind<'tcx>>, BinderScopeType) {
339        let mut scope = self.scope;
340        let mut supertrait_bound_vars = ::alloc::vec::Vec::new()vec![];
341        loop {
342            match scope {
343                Scope::Body { .. } | Scope::Root { .. } => {
344                    break (::alloc::vec::Vec::new()vec![], BinderScopeType::Normal);
345                }
346
347                Scope::Opaque { s, .. }
348                | Scope::ObjectLifetimeDefault { s, .. }
349                | Scope::LateBoundary { s, .. } => {
350                    scope = s;
351                }
352
353                Scope::Supertrait { s, bound_vars } => {
354                    supertrait_bound_vars = bound_vars.clone();
355                    scope = s;
356                }
357
358                Scope::TraitRefBoundary { .. } => {
359                    // We should only see super trait lifetimes if there is a `Binder` above
360                    // though this may happen when we call `poly_trait_ref_binder_info` with
361                    // an (erroneous, #113423) associated return type bound in an impl header.
362                    if !supertrait_bound_vars.is_empty() {
363                        self.tcx.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("found supertrait lifetimes without a binder to append them to: {0:?}",
                supertrait_bound_vars))
    })format!(
364                            "found supertrait lifetimes without a binder to append \
365                                them to: {supertrait_bound_vars:?}"
366                        ));
367                    }
368                    break (::alloc::vec::Vec::new()vec![], BinderScopeType::Normal);
369                }
370
371                Scope::Binder { hir_id, .. } => {
372                    // Nested poly trait refs have the binders concatenated
373                    let mut full_binders: Vec<ty::BoundVariableKind<'tcx>> =
374                        self.rbv.late_bound_vars.get_mut_or_insert_default(hir_id.local_id).clone();
375                    full_binders.extend(supertrait_bound_vars);
376                    break (full_binders, BinderScopeType::Concatenating);
377                }
378            }
379        }
380    }
381
382    fn visit_poly_trait_ref_inner(
383        &mut self,
384        trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
385        non_lifetime_binder_allowed: NonLifetimeBinderAllowed,
386    ) {
387        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:387",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(387u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_poly_trait_ref(trait_ref={0:?})",
                                                    trait_ref) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
388
389        let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
390
391        let initial_bound_vars = binders.len() as u32;
392        let mut bound_vars: FxIndexMap<LocalDefId, ResolvedArg> = FxIndexMap::default();
393        let binders_iter =
394            trait_ref.bound_generic_params.iter().enumerate().map(|(late_bound_idx, param)| {
395                let arg = ResolvedArg::late(initial_bound_vars + late_bound_idx as u32, param);
396                bound_vars.insert(param.def_id, arg);
397                late_arg_as_bound_arg(param)
398            });
399        binders.extend(binders_iter);
400
401        if let NonLifetimeBinderAllowed::Deny(where_) = non_lifetime_binder_allowed {
402            deny_non_region_late_bound(self.tcx, &mut bound_vars, where_);
403        }
404
405        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:405",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(405u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("binders")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("binders");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&binders)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?binders);
406        self.record_late_bound_vars(trait_ref.trait_ref.hir_ref_id, binders);
407
408        // Always introduce a scope here, even if this is in a where clause and
409        // we introduced the binders around the bounded Ty. In that case, we
410        // just reuse the concatenation functionality also present in nested trait
411        // refs.
412        let scope = Scope::Binder {
413            hir_id: trait_ref.trait_ref.hir_ref_id,
414            bound_vars,
415            s: self.scope,
416            scope_type,
417            where_bound_origin: None,
418        };
419        self.with(scope, |this| {
420            for elem in trait_ref.bound_generic_params {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_generic_param(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
421            this.visit_trait_ref(&trait_ref.trait_ref);
422        });
423    }
424}
425
426enum NonLifetimeBinderAllowed {
427    Deny(&'static str),
428    Allow,
429}
430
431impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {
432    type NestedFilter = nested_filter::OnlyBodies;
433
434    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
435        self.tcx
436    }
437
438    fn visit_nested_body(&mut self, body: hir::BodyId) {
439        let body = self.tcx.hir_body(body);
440        self.with(Scope::Body { id: body.id(), s: self.scope }, |this| {
441            this.visit_body(body);
442        });
443    }
444
445    fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
446        if let hir::ExprKind::Closure(hir::Closure {
447            binder, bound_generic_params, fn_decl, ..
448        }) = e.kind
449        {
450            if let &hir::ClosureBinder::For { span: for_sp, .. } = binder {
451                fn span_of_infer(ty: &hir::Ty<'_>) -> Option<Span> {
452                    /// Look for `_` anywhere in the signature of a `for<> ||` closure.
453                    /// This is currently disallowed.
454                    struct FindInferInClosureWithBinder;
455                    impl<'v> Visitor<'v> for FindInferInClosureWithBinder {
456                        type Result = ControlFlow<Span>;
457
458                        fn visit_infer(
459                            &mut self,
460                            _inf_id: HirId,
461                            inf_span: Span,
462                            _kind: InferKind<'v>,
463                        ) -> Self::Result {
464                            ControlFlow::Break(inf_span)
465                        }
466                    }
467                    FindInferInClosureWithBinder.visit_ty_unambig(ty).break_value()
468                }
469
470                let infer_in_rt_sp = match fn_decl.output {
471                    hir::FnRetTy::DefaultReturn(sp) => Some(sp),
472                    hir::FnRetTy::Return(ty) => span_of_infer(ty),
473                };
474
475                let infer_spans = fn_decl
476                    .inputs
477                    .into_iter()
478                    .filter_map(span_of_infer)
479                    .chain(infer_in_rt_sp)
480                    .collect::<Vec<_>>();
481
482                if !infer_spans.is_empty() {
483                    self.tcx
484                        .dcx()
485                        .emit_err(diagnostics::ClosureImplicitHrtb { spans: infer_spans, for_sp });
486                }
487            }
488
489            let (mut bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) =
490                bound_generic_params
491                    .iter()
492                    .enumerate()
493                    .map(|(late_bound_idx, param)| {
494                        (
495                            (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
496                            late_arg_as_bound_arg(param),
497                        )
498                    })
499                    .unzip();
500
501            deny_non_region_late_bound(self.tcx, &mut bound_vars, "closures");
502
503            self.record_late_bound_vars(e.hir_id, binders);
504            let scope = Scope::Binder {
505                hir_id: e.hir_id,
506                bound_vars,
507                s: self.scope,
508                scope_type: BinderScopeType::Normal,
509                where_bound_origin: None,
510            };
511
512            self.with(scope, |this| {
513                // a closure has no bounds, so everything
514                // contained within is scoped within its binder.
515                intravisit::walk_expr(this, e)
516            });
517        } else {
518            intravisit::walk_expr(self, e)
519        }
520    }
521
522    /// Resolve the lifetimes inside the opaque type, and save them into
523    /// `opaque_captured_lifetimes`.
524    ///
525    /// This method has special handling for opaques that capture all lifetimes,
526    /// like async desugaring.
527    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_opaque_ty",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(527u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("opaque")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("opaque");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opaque)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let captures = RefCell::new(FxIndexMap::default());
            let capture_all_in_scope_lifetimes =
                opaque_captures_all_in_scope_lifetimes(opaque);
            if capture_all_in_scope_lifetimes {
                let tcx = self.tcx;
                let lifetime_ident =
                    |def_id: LocalDefId|
                        {
                            let name = tcx.item_name(def_id.to_def_id());
                            let span = tcx.def_span(def_id);
                            Ident::new(name, span)
                        };
                let mut late_depth = 0;
                let mut scope = self.scope;
                let mut opaque_capture_scopes =
                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                            [(opaque.def_id, &captures)]));
                loop {
                    match *scope {
                        Scope::Binder { ref bound_vars, scope_type, s, .. } => {
                            for (&original_lifetime, &def) in bound_vars.iter().rev() {
                                if let DefKind::LifetimeParam =
                                        self.tcx.def_kind(original_lifetime) {
                                    let def = def.shifted(late_depth);
                                    let ident = lifetime_ident(original_lifetime);
                                    self.remap_opaque_captures(&opaque_capture_scopes, def,
                                        ident);
                                }
                            }
                            match scope_type {
                                BinderScopeType::Normal => late_depth += 1,
                                BinderScopeType::Concatenating => {}
                            }
                            scope = s;
                        }
                        Scope::Root { mut opt_parent_item } => {
                            while let Some(parent_item) = opt_parent_item {
                                let parent_generics = self.tcx.generics_of(parent_item);
                                for param in parent_generics.own_params.iter().rev() {
                                    if let ty::GenericParamDefKind::Lifetime = param.kind {
                                        let def =
                                            ResolvedArg::EarlyBound(param.def_id.expect_local());
                                        let ident = lifetime_ident(param.def_id.expect_local());
                                        self.remap_opaque_captures(&opaque_capture_scopes, def,
                                            ident);
                                    }
                                }
                                opt_parent_item =
                                    parent_generics.parent.and_then(DefId::as_local);
                            }
                            break;
                        }
                        Scope::Opaque { captures, def_id, s } => {
                            opaque_capture_scopes.push((def_id, captures));
                            late_depth = 0;
                            scope = s;
                        }
                        Scope::Body { .. } => {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?}",
                                    scope))
                        }
                        Scope::ObjectLifetimeDefault { s, .. } | Scope::Supertrait {
                            s, .. } | Scope::TraitRefBoundary { s, .. } |
                            Scope::LateBoundary { s, .. } => {
                            scope = s;
                        }
                    }
                }
                captures.borrow_mut().reverse();
            }
            let scope =
                Scope::Opaque {
                    captures: &captures,
                    def_id: opaque.def_id,
                    s: self.scope,
                };
            self.with(scope,
                |this|
                    {
                        let scope = Scope::TraitRefBoundary { s: this.scope };
                        this.with(scope,
                            |this|
                                {
                                    let scope =
                                        Scope::LateBoundary {
                                            s: this.scope,
                                            what: "nested `impl Trait`",
                                            deny_late_regions: false,
                                        };
                                    this.with(scope,
                                        |this| intravisit::walk_opaque_ty(this, opaque))
                                })
                    });
            self.emit_opaque_capture_errors();
            let captures = captures.into_inner().into_iter().collect();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:617",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(617u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("captures")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("captures");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&captures)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            self.rbv.opaque_captured_lifetimes.insert(opaque.def_id,
                captures);
        }
    }
}#[instrument(level = "debug", skip(self))]
528    fn visit_opaque_ty(&mut self, opaque: &'tcx rustc_hir::OpaqueTy<'tcx>) {
529        let captures = RefCell::new(FxIndexMap::default());
530
531        let capture_all_in_scope_lifetimes = opaque_captures_all_in_scope_lifetimes(opaque);
532        if capture_all_in_scope_lifetimes {
533            let tcx = self.tcx;
534            let lifetime_ident = |def_id: LocalDefId| {
535                let name = tcx.item_name(def_id.to_def_id());
536                let span = tcx.def_span(def_id);
537                Ident::new(name, span)
538            };
539
540            // We list scopes outwards, this causes us to see lifetime parameters in reverse
541            // declaration order. In order to make it consistent with what `generics_of` might
542            // give, we will reverse the IndexMap after early captures.
543            let mut late_depth = 0;
544            let mut scope = self.scope;
545            let mut opaque_capture_scopes = vec![(opaque.def_id, &captures)];
546            loop {
547                match *scope {
548                    Scope::Binder { ref bound_vars, scope_type, s, .. } => {
549                        for (&original_lifetime, &def) in bound_vars.iter().rev() {
550                            if let DefKind::LifetimeParam = self.tcx.def_kind(original_lifetime) {
551                                let def = def.shifted(late_depth);
552                                let ident = lifetime_ident(original_lifetime);
553                                self.remap_opaque_captures(&opaque_capture_scopes, def, ident);
554                            }
555                        }
556                        match scope_type {
557                            BinderScopeType::Normal => late_depth += 1,
558                            BinderScopeType::Concatenating => {}
559                        }
560                        scope = s;
561                    }
562
563                    Scope::Root { mut opt_parent_item } => {
564                        while let Some(parent_item) = opt_parent_item {
565                            let parent_generics = self.tcx.generics_of(parent_item);
566                            for param in parent_generics.own_params.iter().rev() {
567                                if let ty::GenericParamDefKind::Lifetime = param.kind {
568                                    let def = ResolvedArg::EarlyBound(param.def_id.expect_local());
569                                    let ident = lifetime_ident(param.def_id.expect_local());
570                                    self.remap_opaque_captures(&opaque_capture_scopes, def, ident);
571                                }
572                            }
573                            opt_parent_item = parent_generics.parent.and_then(DefId::as_local);
574                        }
575                        break;
576                    }
577
578                    Scope::Opaque { captures, def_id, s } => {
579                        opaque_capture_scopes.push((def_id, captures));
580                        late_depth = 0;
581                        scope = s;
582                    }
583
584                    Scope::Body { .. } => {
585                        bug!("{:?}", scope)
586                    }
587
588                    Scope::ObjectLifetimeDefault { s, .. }
589                    | Scope::Supertrait { s, .. }
590                    | Scope::TraitRefBoundary { s, .. }
591                    | Scope::LateBoundary { s, .. } => {
592                        scope = s;
593                    }
594                }
595            }
596            captures.borrow_mut().reverse();
597        }
598
599        let scope = Scope::Opaque { captures: &captures, def_id: opaque.def_id, s: self.scope };
600        self.with(scope, |this| {
601            let scope = Scope::TraitRefBoundary { s: this.scope };
602            this.with(scope, |this| {
603                let scope = Scope::LateBoundary {
604                    s: this.scope,
605                    what: "nested `impl Trait`",
606                    // We can capture late-bound regions; we just don't duplicate
607                    // lifetime or const params, so we can't allow those.
608                    deny_late_regions: false,
609                };
610                this.with(scope, |this| intravisit::walk_opaque_ty(this, opaque))
611            })
612        });
613
614        self.emit_opaque_capture_errors();
615
616        let captures = captures.into_inner().into_iter().collect();
617        debug!(?captures);
618        self.rbv.opaque_captured_lifetimes.insert(opaque.def_id, captures);
619    }
620
621    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_item",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(621u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let hir::ItemKind::Impl(impl_) = item.kind &&
                    let Some(of_trait) = impl_.of_trait {
                self.record_late_bound_vars(of_trait.trait_ref.hir_ref_id,
                    Vec::default());
            }
            match item.kind {
                hir::ItemKind::Fn { generics, .. } => {
                    self.visit_early_late(item.hir_id(), generics,
                        |this| { intravisit::walk_item(this, item); });
                }
                hir::ItemKind::ExternCrate(..) | hir::ItemKind::Use(..) |
                    hir::ItemKind::Macro(..) | hir::ItemKind::Mod(..) |
                    hir::ItemKind::ForeignMod { .. } | hir::ItemKind::Static(..)
                    | hir::ItemKind::GlobalAsm { .. } => {
                    intravisit::walk_item(self, item);
                }
                hir::ItemKind::TyAlias(_, generics, _) |
                    hir::ItemKind::Const(_, generics, _, _) |
                    hir::ItemKind::Enum(_, generics, _) |
                    hir::ItemKind::Struct(_, generics, _) |
                    hir::ItemKind::Union(_, generics, _) |
                    hir::ItemKind::Trait { generics, .. } |
                    hir::ItemKind::TraitAlias(_, _, generics, ..) |
                    hir::ItemKind::Impl(hir::Impl { generics, .. }) |
                    hir::ItemKind::TestBinderConstraints { generics, .. } => {
                    self.visit_early(item.hir_id(), generics,
                        |this| intravisit::walk_item(this, item));
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
622    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
623        if let hir::ItemKind::Impl(impl_) = item.kind
624            && let Some(of_trait) = impl_.of_trait
625        {
626            self.record_late_bound_vars(of_trait.trait_ref.hir_ref_id, Vec::default());
627        }
628        match item.kind {
629            hir::ItemKind::Fn { generics, .. } => {
630                self.visit_early_late(item.hir_id(), generics, |this| {
631                    intravisit::walk_item(this, item);
632                });
633            }
634
635            hir::ItemKind::ExternCrate(..)
636            | hir::ItemKind::Use(..)
637            | hir::ItemKind::Macro(..)
638            | hir::ItemKind::Mod(..)
639            | hir::ItemKind::ForeignMod { .. }
640            | hir::ItemKind::Static(..)
641            | hir::ItemKind::GlobalAsm { .. } => {
642                // These sorts of items have no lifetime parameters at all.
643                intravisit::walk_item(self, item);
644            }
645            hir::ItemKind::TyAlias(_, generics, _)
646            | hir::ItemKind::Const(_, generics, _, _)
647            | hir::ItemKind::Enum(_, generics, _)
648            | hir::ItemKind::Struct(_, generics, _)
649            | hir::ItemKind::Union(_, generics, _)
650            | hir::ItemKind::Trait { generics, .. }
651            | hir::ItemKind::TraitAlias(_, _, generics, ..)
652            | hir::ItemKind::Impl(hir::Impl { generics, .. })
653            | hir::ItemKind::TestBinderConstraints { generics, .. } => {
654                // These kinds of items have only early-bound lifetime parameters.
655                self.visit_early(item.hir_id(), generics, |this| intravisit::walk_item(this, item));
656            }
657        }
658    }
659
660    fn visit_precise_capturing_arg(
661        &mut self,
662        arg: &'tcx hir::PreciseCapturingArg<'tcx>,
663    ) -> Self::Result {
664        match *arg {
665            hir::PreciseCapturingArg::Lifetime(lt) => match lt.kind {
666                LifetimeKind::Param(def_id) => {
667                    self.resolve_lifetime_ref(def_id, lt);
668                }
669                LifetimeKind::Error(..) => {}
670                LifetimeKind::ImplicitObjectLifetimeDefault
671                | LifetimeKind::Infer
672                | LifetimeKind::Static => {
673                    self.tcx.dcx().emit_err(diagnostics::BadPreciseCapture {
674                        span: lt.ident.span,
675                        kind: "lifetime",
676                        found: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", lt.ident.name))
    })format!("`{}`", lt.ident.name),
677                    });
678                }
679            },
680            hir::PreciseCapturingArg::Param(param) => match param.res {
681                Res::Def(DefKind::TyParam | DefKind::ConstParam, def_id)
682                | Res::SelfTyParam { trait_: def_id } => {
683                    self.resolve_type_ref(def_id.expect_local(), param.hir_id);
684                }
685                Res::SelfTyAlias { alias_to, .. } => {
686                    self.tcx.dcx().emit_err(diagnostics::PreciseCaptureSelfAlias {
687                        span: param.ident.span,
688                        self_span: self.tcx.def_span(alias_to),
689                        what: self.tcx.def_descr(alias_to),
690                    });
691                }
692                res => {
693                    self.tcx.dcx().span_delayed_bug(
694                        param.ident.span,
695                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected type or const param, found {0:?}",
                res))
    })format!("expected type or const param, found {res:?}"),
696                    );
697                }
698            },
699        }
700    }
701
702    fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
703        match item.kind {
704            hir::ForeignItemKind::Fn(_, _, generics) => {
705                self.visit_early_late(item.hir_id(), generics, |this| {
706                    intravisit::walk_foreign_item(this, item);
707                })
708            }
709            hir::ForeignItemKind::Static(..) => {
710                intravisit::walk_foreign_item(self, item);
711            }
712            hir::ForeignItemKind::Type => {
713                intravisit::walk_foreign_item(self, item);
714            }
715        }
716    }
717
718    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_ty",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(718u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match ty.kind {
                hir::TyKind::FnPtr(c) => {
                    let (mut bound_vars, binders):
                            (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) =
                        c.generic_params.iter().enumerate().map(|(late_bound_idx,
                                        param)|
                                    {
                                        ((param.def_id,
                                                ResolvedArg::late(late_bound_idx as u32, param)),
                                            late_arg_as_bound_arg(param))
                                    }).unzip();
                    deny_non_region_late_bound(self.tcx, &mut bound_vars,
                        "function pointer types");
                    self.record_late_bound_vars(ty.hir_id, binders);
                    let scope =
                        Scope::Binder {
                            hir_id: ty.hir_id,
                            bound_vars,
                            s: self.scope,
                            scope_type: BinderScopeType::Normal,
                            where_bound_origin: None,
                        };
                    self.with(scope, |this| { intravisit::walk_ty(this, ty); });
                }
                hir::TyKind::UnsafeBinder(binder) => {
                    let (mut bound_vars, binders):
                            (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) =
                        binder.generic_params.iter().enumerate().map(|(late_bound_idx,
                                        param)|
                                    {
                                        ((param.def_id,
                                                ResolvedArg::late(late_bound_idx as u32, param)),
                                            late_arg_as_bound_arg(param))
                                    }).unzip();
                    deny_non_region_late_bound(self.tcx, &mut bound_vars,
                        "function pointer types");
                    self.record_late_bound_vars(ty.hir_id, binders);
                    let scope =
                        Scope::Binder {
                            hir_id: ty.hir_id,
                            bound_vars,
                            s: self.scope,
                            scope_type: BinderScopeType::Normal,
                            where_bound_origin: None,
                        };
                    self.with(scope, |this| { intravisit::walk_ty(this, ty); });
                }
                hir::TyKind::TraitObject(bounds, lifetime) => {
                    let lifetime = lifetime.pointer();
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:781",
                                            "rustc_hir_analysis::collect::resolve_bound_vars",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                            ::tracing_core::__macro_support::Option::Some(781u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                            ::tracing_core::field::FieldSet::new(&["message",
                                                            {
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("bounds")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("bounds");
                                                                NAME.as_str()
                                                            },
                                                            {
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("lifetime")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("lifetime");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("TraitObject")
                                                                as &dyn ::tracing::field::Value)),
                                                    (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bounds)
                                                                as &dyn ::tracing::field::Value)),
                                                    (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let scope = Scope::TraitRefBoundary { s: self.scope };
                    self.with(scope,
                        |this|
                            {
                                for bound in bounds {
                                    this.visit_poly_trait_ref_inner(bound,
                                        NonLifetimeBinderAllowed::Deny("trait object types"));
                                }
                            });
                    match lifetime.kind {
                        LifetimeKind::ImplicitObjectLifetimeDefault => {
                            self.resolve_object_lifetime_default(&*lifetime);
                        }
                        LifetimeKind::Infer => {}
                        LifetimeKind::Param(..) | LifetimeKind::Static => {
                            self.visit_lifetime(&*lifetime);
                        }
                        LifetimeKind::Error(..) => {}
                    }
                }
                hir::TyKind::Ref(lifetime_ref, ref mt) => {
                    self.visit_lifetime(lifetime_ref);
                    let scope =
                        Scope::ObjectLifetimeDefault {
                            lifetime: self.rbv.defs.get(&lifetime_ref.hir_id.local_id).copied(),
                            s: self.scope,
                        };
                    self.with(scope, |this| this.visit_ty_unambig(mt.ty));
                }
                hir::TyKind::TraitAscription(bounds) => {
                    let scope = Scope::TraitRefBoundary { s: self.scope };
                    self.with(scope,
                        |this|
                            {
                                let scope =
                                    Scope::LateBoundary {
                                        s: this.scope,
                                        what: "`impl Trait` in binding",
                                        deny_late_regions: true,
                                    };
                                this.with(scope,
                                    |this|
                                        { for bound in bounds { this.visit_param_bound(bound); } })
                            });
                }
                _ => intravisit::walk_ty(self, ty),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
719    fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
720        match ty.kind {
721            hir::TyKind::FnPtr(c) => {
722                let (mut bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = c
723                    .generic_params
724                    .iter()
725                    .enumerate()
726                    .map(|(late_bound_idx, param)| {
727                        (
728                            (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
729                            late_arg_as_bound_arg(param),
730                        )
731                    })
732                    .unzip();
733
734                deny_non_region_late_bound(self.tcx, &mut bound_vars, "function pointer types");
735
736                self.record_late_bound_vars(ty.hir_id, binders);
737                let scope = Scope::Binder {
738                    hir_id: ty.hir_id,
739                    bound_vars,
740                    s: self.scope,
741                    scope_type: BinderScopeType::Normal,
742                    where_bound_origin: None,
743                };
744                self.with(scope, |this| {
745                    // a FnPtr has no bounds, so everything within is scoped within its binder
746                    intravisit::walk_ty(this, ty);
747                });
748            }
749            hir::TyKind::UnsafeBinder(binder) => {
750                let (mut bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) =
751                    binder
752                        .generic_params
753                        .iter()
754                        .enumerate()
755                        .map(|(late_bound_idx, param)| {
756                            (
757                                (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
758                                late_arg_as_bound_arg(param),
759                            )
760                        })
761                        .unzip();
762
763                deny_non_region_late_bound(self.tcx, &mut bound_vars, "function pointer types");
764
765                self.record_late_bound_vars(ty.hir_id, binders);
766                let scope = Scope::Binder {
767                    hir_id: ty.hir_id,
768                    bound_vars,
769                    s: self.scope,
770                    scope_type: BinderScopeType::Normal,
771                    where_bound_origin: None,
772                };
773                self.with(scope, |this| {
774                    // everything within is scoped within its binder
775                    intravisit::walk_ty(this, ty);
776                });
777            }
778            hir::TyKind::TraitObject(bounds, lifetime) => {
779                let lifetime = lifetime.pointer();
780
781                debug!(?bounds, ?lifetime, "TraitObject");
782                let scope = Scope::TraitRefBoundary { s: self.scope };
783                self.with(scope, |this| {
784                    for bound in bounds {
785                        this.visit_poly_trait_ref_inner(
786                            bound,
787                            NonLifetimeBinderAllowed::Deny("trait object types"),
788                        );
789                    }
790                });
791                match lifetime.kind {
792                    LifetimeKind::ImplicitObjectLifetimeDefault => {
793                        // If the user doesn't write *anything*, we apply the
794                        // trait object lifetime defaulting rules.
795                        // E.g., `Box<dyn Debug>` becomes `Box<dyn Debug + 'static>`.
796                        self.resolve_object_lifetime_default(&*lifetime);
797                    }
798                    LifetimeKind::Infer => {
799                        // If the user writes `'_`, we use the *ordinary* elision
800                        // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
801                        // resolved the same as the `'_` in `&'_ Foo`.
802                        //
803                        // cc #48468
804                    }
805                    LifetimeKind::Param(..) | LifetimeKind::Static => {
806                        // If the user wrote an explicit name, use that.
807                        self.visit_lifetime(&*lifetime);
808                    }
809                    LifetimeKind::Error(..) => {}
810                }
811            }
812            hir::TyKind::Ref(lifetime_ref, ref mt) => {
813                self.visit_lifetime(lifetime_ref);
814                let scope = Scope::ObjectLifetimeDefault {
815                    lifetime: self.rbv.defs.get(&lifetime_ref.hir_id.local_id).copied(),
816                    s: self.scope,
817                };
818                self.with(scope, |this| this.visit_ty_unambig(mt.ty));
819            }
820            hir::TyKind::TraitAscription(bounds) => {
821                let scope = Scope::TraitRefBoundary { s: self.scope };
822                self.with(scope, |this| {
823                    let scope = Scope::LateBoundary {
824                        s: this.scope,
825                        what: "`impl Trait` in binding",
826                        deny_late_regions: true,
827                    };
828                    this.with(scope, |this| {
829                        for bound in bounds {
830                            this.visit_param_bound(bound);
831                        }
832                    })
833                });
834            }
835            _ => intravisit::walk_ty(self, ty),
836        }
837    }
838
839    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_pattern_type_pattern",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(839u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("p")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("p");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&p)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        { intravisit::walk_ty_pat(self, p) }
    }
}#[instrument(level = "debug", skip(self))]
840    fn visit_pattern_type_pattern(&mut self, p: &'tcx hir::TyPat<'tcx>) {
841        intravisit::walk_ty_pat(self, p)
842    }
843
844    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_trait_item",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(844u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_item")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_item");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_item)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            use self::hir::TraitItemKind::*;
            match trait_item.kind {
                Fn(_, _) => {
                    self.visit_early_late(trait_item.hir_id(),
                        trait_item.generics,
                        |this| { intravisit::walk_trait_item(this, trait_item) });
                }
                Type(bounds, ty) => {
                    self.visit_early(trait_item.hir_id(), trait_item.generics,
                        |this|
                            {
                                this.visit_generics(trait_item.generics);
                                for bound in bounds { this.visit_param_bound(bound); }
                                if let Some(ty) = ty { this.visit_ty_unambig(ty); }
                            })
                }
                Const(_, _) =>
                    self.visit_early(trait_item.hir_id(), trait_item.generics,
                        |this| { intravisit::walk_trait_item(this, trait_item) }),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
845    fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
846        use self::hir::TraitItemKind::*;
847        match trait_item.kind {
848            Fn(_, _) => {
849                self.visit_early_late(trait_item.hir_id(), trait_item.generics, |this| {
850                    intravisit::walk_trait_item(this, trait_item)
851                });
852            }
853            Type(bounds, ty) => {
854                self.visit_early(trait_item.hir_id(), trait_item.generics, |this| {
855                    this.visit_generics(trait_item.generics);
856                    for bound in bounds {
857                        this.visit_param_bound(bound);
858                    }
859                    if let Some(ty) = ty {
860                        this.visit_ty_unambig(ty);
861                    }
862                })
863            }
864            Const(_, _) => self.visit_early(trait_item.hir_id(), trait_item.generics, |this| {
865                intravisit::walk_trait_item(this, trait_item)
866            }),
867        }
868    }
869
870    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_impl_item",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(870u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_item")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_item");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_item)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            use self::hir::ImplItemKind::*;
            match impl_item.kind {
                Fn(..) =>
                    self.visit_early_late(impl_item.hir_id(),
                        impl_item.generics,
                        |this| { intravisit::walk_impl_item(this, impl_item) }),
                Type(ty) =>
                    self.visit_early(impl_item.hir_id(), impl_item.generics,
                        |this|
                            {
                                this.visit_generics(impl_item.generics);
                                this.visit_ty_unambig(ty);
                            }),
                Const(_, _) =>
                    self.visit_early(impl_item.hir_id(), impl_item.generics,
                        |this| { intravisit::walk_impl_item(this, impl_item) }),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
871    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
872        use self::hir::ImplItemKind::*;
873        match impl_item.kind {
874            Fn(..) => self.visit_early_late(impl_item.hir_id(), impl_item.generics, |this| {
875                intravisit::walk_impl_item(this, impl_item)
876            }),
877            Type(ty) => self.visit_early(impl_item.hir_id(), impl_item.generics, |this| {
878                this.visit_generics(impl_item.generics);
879                this.visit_ty_unambig(ty);
880            }),
881            Const(_, _) => self.visit_early(impl_item.hir_id(), impl_item.generics, |this| {
882                intravisit::walk_impl_item(this, impl_item)
883            }),
884        }
885    }
886
887    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_lifetime",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(887u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match lifetime_ref.kind {
                hir::LifetimeKind::Static => {
                    self.insert_lifetime(lifetime_ref,
                        ResolvedArg::StaticLifetime)
                }
                hir::LifetimeKind::Param(param_def_id) => {
                    self.resolve_lifetime_ref(param_def_id, lifetime_ref)
                }
                hir::LifetimeKind::Error(guar) => {
                    self.insert_lifetime(lifetime_ref, ResolvedArg::Error(guar))
                }
                hir::LifetimeKind::ImplicitObjectLifetimeDefault |
                    hir::LifetimeKind::Infer => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
888    fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
889        match lifetime_ref.kind {
890            hir::LifetimeKind::Static => {
891                self.insert_lifetime(lifetime_ref, ResolvedArg::StaticLifetime)
892            }
893            hir::LifetimeKind::Param(param_def_id) => {
894                self.resolve_lifetime_ref(param_def_id, lifetime_ref)
895            }
896            // Keep track of lifetimes about which errors have already been reported
897            hir::LifetimeKind::Error(guar) => {
898                self.insert_lifetime(lifetime_ref, ResolvedArg::Error(guar))
899            }
900            // Those will be resolved by typechecking.
901            hir::LifetimeKind::ImplicitObjectLifetimeDefault | hir::LifetimeKind::Infer => {}
902        }
903    }
904
905    fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: HirId, _: Span) {
906        match qpath {
907            hir::QPath::Resolved(maybe_qself, path) => {
908                // Visit the path before the self type since computing the trait object lifetime
909                // default for the latter requires all lifetime arguments of the trait ref to be
910                // already resolved.
911                self.visit_path(path, id);
912                if let Some(qself) = maybe_qself {
913                    let container =
914                        self.eligible_container(path, RevSegIdx(1).reverse(path.segments));
915
916                    let object_lifetime_defaults =
917                        container.map_or(Vec::new(), |(def_id, segs)| {
918                            let generics = self.tcx.generics_of(def_id);
919                            self.compute_object_lifetime_defaults(generics, segs)
920                        });
921
922                    if let Some(&lt) = object_lifetime_defaults.first() {
923                        let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
924                        self.with(scope, |this| this.visit_ty_unambig(qself));
925                    } else {
926                        self.visit_ty_unambig(qself);
927                    }
928                }
929            }
930            hir::QPath::TypeRelative(qself, segment) => {
931                // Computing the trait object lifetime defaults that are induced by type-relative
932                // paths would require full type-dependent resolution as performed by HIR ty
933                // lowering whose results we don't have access to here (esp. in ItemCtxts which
934                // don't "persist" any resolutions during lowering).
935                // For maximum forward compatibility, in ItemCtxts we make HIR ty lowering reject
936                // implicit trait object lifetime bounds inside such paths on grounds of
937                // the default being *indeterminate*.
938                // FIXME: Figure out if there's a feasible way to obtain the map of type-dependent
939                //        definitions here / interleave RBV and HIR ty lowering.
940                let scope = Scope::ObjectLifetimeDefault { lifetime: None, s: self.scope };
941                self.with(scope, |this| {
942                    this.visit_ty_unambig(qself);
943                    this.visit_path_segment(segment)
944                });
945            }
946        }
947    }
948
949    fn visit_path(&mut self, path: &hir::Path<'tcx>, hir_id: HirId) {
950        for (index, segment) in path.segments.iter().enumerate() {
951            if let Some(args) = segment.args {
952                self.visit_path_segment_args(args, SegIdx(index), path);
953            }
954        }
955        if let Res::Def(DefKind::TyParam | DefKind::ConstParam, param_def_id) = path.res {
956            self.resolve_type_ref(param_def_id.expect_local(), hir_id);
957        }
958    }
959
960    fn visit_fn(
961        &mut self,
962        fk: intravisit::FnKind<'tcx>,
963        fd: &'tcx hir::FnDecl<'tcx>,
964        body_id: hir::BodyId,
965        _: Span,
966        def_id: LocalDefId,
967    ) {
968        let output = match fd.output {
969            hir::FnRetTy::DefaultReturn(_) => None,
970            hir::FnRetTy::Return(ty) => Some(ty),
971        };
972        if let Some(ty) = output
973            && let hir::TyKind::InferDelegation(hir::InferDelegation::Sig(sig_id, _)) = ty.kind
974        {
975            let bound_vars: Vec<_> =
976                self.tcx.fn_sig(sig_id).skip_binder().bound_vars().iter().collect();
977            let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
978            self.rbv.late_bound_vars.insert(hir_id.local_id, bound_vars);
979        }
980        self.visit_fn_like_elision(fd.inputs, output, #[allow(non_exhaustive_omitted_patterns)] match fk {
    intravisit::FnKind::Closure => true,
    _ => false,
}matches!(fk, intravisit::FnKind::Closure));
981        intravisit::walk_fn_kind(self, fk);
982        self.visit_nested_body(body_id)
983    }
984
985    fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
986        let scope = Scope::TraitRefBoundary { s: self.scope };
987        self.with(scope, |this| {
988            for elem in generics.params {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_generic_param(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(this, visit_generic_param, generics.params);
989            for elem in generics.predicates {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_where_predicate(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(this, visit_where_predicate, generics.predicates);
990        })
991    }
992
993    fn visit_where_predicate(&mut self, predicate: &'tcx hir::WherePredicate<'tcx>) {
994        let hir_id = predicate.hir_id;
995        match predicate.kind {
996            &hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
997                bounded_ty,
998                bounds,
999                bound_generic_params,
1000                origin,
1001                ..
1002            }) => {
1003                let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) =
1004                    bound_generic_params
1005                        .iter()
1006                        .enumerate()
1007                        .map(|(late_bound_idx, param)| {
1008                            (
1009                                (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
1010                                late_arg_as_bound_arg(param),
1011                            )
1012                        })
1013                        .unzip();
1014
1015                self.record_late_bound_vars(hir_id, binders);
1016
1017                // If this is an RTN type in the self type, then append those to the binder.
1018                self.try_append_return_type_notation_params(hir_id, bounded_ty);
1019
1020                // Even if there are no lifetimes defined here, we still wrap it in a binder
1021                // scope. If there happens to be a nested poly trait ref (an error), that
1022                // will be `Concatenating` anyways, so we don't have to worry about the depth
1023                // being wrong.
1024                let scope = Scope::Binder {
1025                    hir_id,
1026                    bound_vars,
1027                    s: self.scope,
1028                    scope_type: BinderScopeType::Normal,
1029                    where_bound_origin: Some(origin),
1030                };
1031                self.with(scope, |this| {
1032                    for elem in bound_generic_params {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_generic_param(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(this, visit_generic_param, bound_generic_params);
1033                    this.visit_ty_unambig(bounded_ty);
1034                    for elem in bounds {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_param_bound(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(this, visit_param_bound, bounds);
1035                })
1036            }
1037            &hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1038                lifetime,
1039                bounds,
1040                ..
1041            }) => {
1042                self.visit_lifetime(lifetime);
1043                for elem in bounds {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_param_bound(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(self, visit_param_bound, bounds);
1044            }
1045        }
1046    }
1047
1048    fn visit_poly_trait_ref(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) {
1049        self.visit_poly_trait_ref_inner(trait_ref, NonLifetimeBinderAllowed::Allow);
1050    }
1051
1052    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
1053        self.with(
1054            Scope::LateBoundary { s: self.scope, what: "constant", deny_late_regions: true },
1055            |this| {
1056                intravisit::walk_anon_const(this, c);
1057            },
1058        );
1059    }
1060
1061    fn visit_generic_param(&mut self, p: &'tcx GenericParam<'tcx>) {
1062        match p.kind {
1063            GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1064                self.resolve_type_ref(p.def_id, p.hir_id);
1065            }
1066            GenericParamKind::Lifetime { .. } => {
1067                // No need to resolve lifetime params, we don't use them for things
1068                // like implicit `?Sized` or const-param-has-ty predicates.
1069            }
1070        }
1071
1072        match p.kind {
1073            GenericParamKind::Lifetime { .. } => {}
1074            GenericParamKind::Type { default, .. } => {
1075                if let Some(ty) = default {
1076                    self.visit_ty_unambig(ty);
1077                }
1078            }
1079            GenericParamKind::Const { ty, default, .. } => {
1080                self.visit_ty_unambig(ty);
1081                if let Some(default) = default {
1082                    self.visit_const_arg_unambig(default);
1083                }
1084            }
1085        }
1086    }
1087
1088    fn visit_test_binder_forall(
1089        &mut self,
1090        forall: &'tcx hir::TestBinderForall<'tcx>,
1091    ) -> Self::Result {
1092        let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = forall
1093            .generics
1094            .params
1095            .iter()
1096            .enumerate()
1097            .map(|(late_bound_idx, param)| {
1098                (
1099                    (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
1100                    late_arg_as_bound_arg(param),
1101                )
1102            })
1103            .unzip();
1104        self.record_late_bound_vars(forall.hir_id, binders);
1105        let scope = Scope::Binder {
1106            hir_id: forall.hir_id,
1107            bound_vars,
1108            s: self.scope,
1109            scope_type: BinderScopeType::Normal,
1110            where_bound_origin: None,
1111        };
1112        self.with(scope, |this| {
1113            this.visit_generics(forall.generics);
1114            this.visit_test_binder_body(forall.body);
1115        });
1116        // exit assertions don't have the bound vars in scope
1117        if let Some(assert_on_exit) = forall.assert_on_exit {
1118            self.visit_test_binder_constraint(assert_on_exit);
1119        }
1120    }
1121
1122    fn visit_test_binder_exists(
1123        &mut self,
1124        exists: &'tcx hir::TestBinderExists<'tcx>,
1125    ) -> Self::Result {
1126        let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = exists
1127            .params
1128            .iter()
1129            .enumerate()
1130            .map(|(late_bound_idx, param)| {
1131                (
1132                    (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
1133                    late_arg_as_bound_arg(param),
1134                )
1135            })
1136            .unzip();
1137        self.record_late_bound_vars(exists.hir_id, binders);
1138        let scope = Scope::Binder {
1139            hir_id: exists.hir_id,
1140            bound_vars,
1141            s: self.scope,
1142            scope_type: BinderScopeType::Normal,
1143            where_bound_origin: None,
1144        };
1145        self.with(scope, |this| {
1146            for param in exists.params {
1147                this.visit_generic_param(param);
1148            }
1149            this.visit_test_binder_body(exists.body);
1150        });
1151    }
1152
1153    fn visit_test_binder_bound_type_constraint(
1154        &mut self,
1155        bound_type: &'tcx hir::TestBinderBoundTypeConstraint<'tcx>,
1156    ) -> Self::Result {
1157        let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = bound_type
1158            .params
1159            .iter()
1160            .enumerate()
1161            .map(|(late_bound_idx, param)| {
1162                (
1163                    (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
1164                    late_arg_as_bound_arg(param),
1165                )
1166            })
1167            .unzip();
1168        self.record_late_bound_vars(bound_type.hir_id, binders);
1169        let scope = Scope::Binder {
1170            hir_id: bound_type.hir_id,
1171            bound_vars,
1172            s: self.scope,
1173            scope_type: BinderScopeType::Normal,
1174            where_bound_origin: None,
1175        };
1176        self.with(scope, |this| {
1177            intravisit::walk_test_binder_bound_type_constraint(this, bound_type);
1178        });
1179    }
1180}
1181
1182fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: LocalDefId) -> ObjectLifetimeDefault {
1183    // Scan the bounds and where-clauses on parameters to extract bounds of the form `T: 'a`
1184    // so as to determine the `ObjectLifetimeDefault` for each type parameter.
1185
1186    let Ok((generics, bounds)) = (match tcx.hir_node_by_def_id(param_def_id) {
1187        hir::Node::GenericParam(param) => match param.source {
1188            hir::GenericParamSource::Generics => match param.kind {
1189                GenericParamKind::Type { .. } => {
1190                    Ok((tcx.hir_get_generics(tcx.local_parent(param_def_id)).unwrap(), &[][..]))
1191                }
1192                _ => Err(()),
1193            },
1194            hir::GenericParamSource::Binder => return ObjectLifetimeDefault::Empty,
1195        },
1196        // For `Self` type parameters
1197        hir::Node::Item(&hir::Item {
1198            kind: hir::ItemKind::Trait { generics, bounds, .. }, ..
1199        }) => Ok((generics, bounds)),
1200        _ => Err(()),
1201    }) else {
1202        ::rustc_middle::util::bug::bug_fmt(format_args!("`object_lifetime_default` must only be called on type parameters"))bug!("`object_lifetime_default` must only be called on type parameters")
1203    };
1204
1205    let mut set = Set1::Empty;
1206
1207    let mut add_outlives_bounds = |bounds: &[hir::GenericBound<'_>]| {
1208        for bound in bounds {
1209            if let hir::GenericBound::Outlives(lifetime) = bound {
1210                set.insert(lifetime.kind);
1211            }
1212        }
1213    };
1214
1215    add_outlives_bounds(bounds);
1216
1217    // Look for `Type: ...` where clauses.
1218    for bound in generics.bounds_for_param(param_def_id) {
1219        // Ignore `for<'a> Type: ...` as they can change what
1220        // lifetimes mean (although we could "just" handle it).
1221        if bound.bound_generic_params.is_empty() {
1222            add_outlives_bounds(&bound.bounds);
1223        }
1224    }
1225
1226    match set {
1227        Set1::Empty => ObjectLifetimeDefault::Empty,
1228        Set1::One(hir::LifetimeKind::Static) => ObjectLifetimeDefault::Static,
1229        Set1::One(hir::LifetimeKind::Param(param_def_id)) => {
1230            ObjectLifetimeDefault::Param(param_def_id.to_def_id())
1231        }
1232        _ => ObjectLifetimeDefault::Ambiguous,
1233    }
1234}
1235
1236impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
1237    fn with<F>(&mut self, wrap_scope: Scope<'_, 'tcx>, f: F)
1238    where
1239        F: for<'b> FnOnce(&mut BoundVarContext<'b, 'tcx>),
1240    {
1241        let BoundVarContext { tcx, rbv, disambiguators, .. } = self;
1242        let nested_errors = RefCell::new(self.opaque_capture_errors.borrow_mut().take());
1243        let mut this = BoundVarContext {
1244            tcx: *tcx,
1245            rbv,
1246            disambiguators,
1247            scope: &wrap_scope,
1248            opaque_capture_errors: nested_errors,
1249        };
1250        let span = {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("scope",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(1250u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("scope")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("scope");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::SPAN)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let mut interest = ::tracing::subscriber::Interest::never();
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                    &&
                    ::tracing::Level::DEBUG <=
                        ::tracing::level_filters::LevelFilter::current() &&
                { interest = __CALLSITE.interest(); !interest.is_never() } &&
            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                interest) {
        let meta = __CALLSITE.metadata();
        ::tracing::Span::new(meta,
            &{
                    #[allow(unused_imports)]
                    use ::tracing::field::{debug, display, Value};
                    meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&this.scope.debug_truncated())
                                                as &dyn ::tracing::field::Value))])
                })
    } else {
        let span =
            ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
        {};
        span
    }
}debug_span!("scope", scope = ?this.scope.debug_truncated());
1251        {
1252            let _enter = span.enter();
1253            f(&mut this);
1254        }
1255        *self.opaque_capture_errors.borrow_mut() = this.opaque_capture_errors.into_inner();
1256    }
1257
1258    fn record_late_bound_vars(&mut self, hir_id: HirId, binder: Vec<ty::BoundVariableKind<'tcx>>) {
1259        if let Some(old) = self.rbv.late_bound_vars.insert(hir_id.local_id, binder) {
1260            ::rustc_middle::util::bug::bug_fmt(format_args!("overwrote bound vars for {1:?}:\nold={2:?}\nnew={0:?}",
        self.rbv.late_bound_vars[&hir_id.local_id], hir_id, old))bug!(
1261                "overwrote bound vars for {hir_id:?}:\nold={old:?}\nnew={:?}",
1262                self.rbv.late_bound_vars[&hir_id.local_id]
1263            )
1264        }
1265    }
1266
1267    /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1268    ///
1269    /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1270    /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1271    /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1272    ///
1273    /// For example:
1274    ///
1275    ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
1276    ///
1277    /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1278    /// lifetimes may be interspersed together.
1279    ///
1280    /// If early bound lifetimes are present, we separate them into their own list (and likewise
1281    /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1282    /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1283    /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1284    /// ordering is not important there.
1285    fn visit_early_late<F>(&mut self, hir_id: HirId, generics: &'tcx hir::Generics<'tcx>, walk: F)
1286    where
1287        F: for<'b, 'c> FnOnce(&'b mut BoundVarContext<'c, 'tcx>),
1288    {
1289        let mut named_late_bound_vars = 0;
1290        let bound_vars: FxIndexMap<LocalDefId, ResolvedArg> = generics
1291            .params
1292            .iter()
1293            .map(|param| {
1294                (
1295                    param.def_id,
1296                    match param.kind {
1297                        GenericParamKind::Lifetime { .. } => {
1298                            if self.tcx.is_late_bound(param.hir_id) {
1299                                let late_bound_idx = named_late_bound_vars;
1300                                named_late_bound_vars += 1;
1301                                ResolvedArg::late(late_bound_idx, param)
1302                            } else {
1303                                ResolvedArg::early(param)
1304                            }
1305                        }
1306                        GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1307                            ResolvedArg::early(param)
1308                        }
1309                    },
1310                )
1311            })
1312            .collect();
1313
1314        let binders: Vec<_> = generics
1315            .params
1316            .iter()
1317            .filter(|param| {
1318                #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Lifetime { .. })
1319                    && self.tcx.is_late_bound(param.hir_id)
1320            })
1321            .map(|param| late_arg_as_bound_arg(param))
1322            .collect();
1323        self.record_late_bound_vars(hir_id, binders);
1324        let scope = Scope::Binder {
1325            hir_id,
1326            bound_vars,
1327            s: self.scope,
1328            scope_type: BinderScopeType::Normal,
1329            where_bound_origin: None,
1330        };
1331        self.with(scope, walk);
1332    }
1333
1334    fn visit_early<F>(&mut self, hir_id: HirId, generics: &'tcx hir::Generics<'tcx>, walk: F)
1335    where
1336        F: for<'b, 'c> FnOnce(&'b mut BoundVarContext<'c, 'tcx>),
1337    {
1338        let bound_vars =
1339            generics.params.iter().map(|param| (param.def_id, ResolvedArg::early(param))).collect();
1340        self.record_late_bound_vars(hir_id, ::alloc::vec::Vec::new()vec![]);
1341        let scope = Scope::Binder {
1342            hir_id,
1343            bound_vars,
1344            s: self.scope,
1345            scope_type: BinderScopeType::Normal,
1346            where_bound_origin: None,
1347        };
1348        self.with(scope, |this| {
1349            let scope = Scope::TraitRefBoundary { s: this.scope };
1350            this.with(scope, walk)
1351        });
1352    }
1353
1354    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("resolve_lifetime_ref",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1354u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("region_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("region_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&region_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut late_depth = 0;
            let mut scope = self.scope;
            let mut outermost_body = None;
            let mut crossed_late_boundary = None;
            let mut opaque_capture_scopes = ::alloc::vec::Vec::new();
            let result =
                loop {
                    match *scope {
                        Scope::Body { id, s } => {
                            outermost_body = Some(id);
                            scope = s;
                        }
                        Scope::Root { opt_parent_item } => {
                            if let Some(parent_item) = opt_parent_item &&
                                        let parent_generics = self.tcx.generics_of(parent_item) &&
                                    parent_generics.param_def_id_to_index(self.tcx,
                                            region_def_id.to_def_id()).is_some() {
                                break Some(ResolvedArg::EarlyBound(region_def_id));
                            }
                            break None;
                        }
                        Scope::Binder {
                            ref bound_vars, scope_type, s, where_bound_origin, .. } => {
                            if let Some(&def) = bound_vars.get(&region_def_id) {
                                break Some(def.shifted(late_depth));
                            }
                            match scope_type {
                                BinderScopeType::Normal => late_depth += 1,
                                BinderScopeType::Concatenating => {}
                            }
                            if let Some(hir::PredicateOrigin::ImplTrait) =
                                                            where_bound_origin &&
                                                        let hir::LifetimeKind::Param(param_id) = lifetime_ref.kind
                                                    &&
                                                    let Some(generics) =
                                                        self.tcx.hir_get_generics(self.tcx.local_parent(param_id))
                                                &&
                                                let Some(param) =
                                                    generics.params.iter().find(|p| p.def_id == param_id) &&
                                            param.is_elided_lifetime() &&
                                        !self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id).is_async()
                                    && !self.tcx.features().anonymous_lifetime_in_impl_trait() {
                                let mut diag: rustc_errors::Diag<'_> =
                                    rustc_session::diagnostics::feature_err(&self.tcx.sess,
                                        sym::anonymous_lifetime_in_impl_trait,
                                        lifetime_ref.ident.span,
                                        "anonymous lifetimes in `impl Trait` are unstable");
                                if let Some(generics) =
                                        self.tcx.hir_get_generics(lifetime_ref.hir_id.owner.def_id)
                                    {
                                    let new_param_sugg =
                                        if let Some(span) = generics.span_for_lifetime_suggestion()
                                            {
                                            (span, "'a, ".to_owned())
                                        } else { (generics.span, "<'a>".to_owned()) };
                                    let lifetime_sugg = lifetime_ref.suggestion("'a");
                                    let suggestions =
                                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [lifetime_sugg, new_param_sugg]));
                                    diag.span_label(lifetime_ref.ident.span,
                                        "expected named lifetime parameter");
                                    diag.multipart_suggestion("consider introducing a named lifetime parameter",
                                        suggestions, rustc_errors::Applicability::MaybeIncorrect);
                                }
                                diag.emit();
                                return;
                            }
                            scope = s;
                        }
                        Scope::Opaque { captures, def_id, s } => {
                            opaque_capture_scopes.push((def_id, captures));
                            late_depth = 0;
                            scope = s;
                        }
                        Scope::ObjectLifetimeDefault { s, .. } | Scope::Supertrait {
                            s, .. } | Scope::TraitRefBoundary { s, .. } => {
                            scope = s;
                        }
                        Scope::LateBoundary { s, what, deny_late_regions } => {
                            if deny_late_regions { crossed_late_boundary = Some(what); }
                            scope = s;
                        }
                    }
                };
            if let Some(mut def) = result {
                def =
                    self.remap_opaque_captures(&opaque_capture_scopes, def,
                        lifetime_ref.ident);
                if let ResolvedArg::EarlyBound(..) = def
                    {} else if let ResolvedArg::LateBound(_, _, param_def_id) =
                            def && let Some(what) = crossed_late_boundary {
                    let use_span = lifetime_ref.ident.span;
                    let def_span = self.tcx.def_span(param_def_id);
                    let guar =
                        match self.tcx.def_kind(param_def_id) {
                            DefKind::LifetimeParam => {
                                self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Lifetime {
                                        use_span,
                                        def_span,
                                        what,
                                    })
                            }
                            kind =>
                                ::rustc_middle::util::bug::span_bug_fmt(use_span,
                                    format_args!("did not expect to resolve lifetime to {0}",
                                        kind.descr(param_def_id.to_def_id()))),
                        };
                    def = ResolvedArg::Error(guar);
                } else if let Some(body_id) = outermost_body {
                    let fn_id = self.tcx.hir_body_owner(body_id);
                    match self.tcx.hir_node(fn_id) {
                        Node::Item(hir::Item {
                            owner_id, kind: hir::ItemKind::Fn { .. }, .. }) |
                            Node::TraitItem(hir::TraitItem {
                            owner_id, kind: hir::TraitItemKind::Fn(..), .. }) |
                            Node::ImplItem(hir::ImplItem {
                            owner_id, kind: hir::ImplItemKind::Fn(..), .. }) => {
                            def = ResolvedArg::Free(owner_id.def_id, def.id().unwrap());
                        }
                        Node::Expr(hir::Expr {
                            kind: hir::ExprKind::Closure(closure), .. }) => {
                            def = ResolvedArg::Free(closure.def_id, def.id().unwrap());
                        }
                        _ => {}
                    }
                }
                self.insert_lifetime(lifetime_ref, def);
                return;
            }
            let mut scope = self.scope;
            loop {
                match *scope {
                    Scope::Binder {
                        where_bound_origin: Some(hir::PredicateOrigin::ImplTrait),
                        .. } => {
                        self.tcx.dcx().emit_err(diagnostics::LateBoundInApit::Lifetime {
                                span: lifetime_ref.ident.span,
                                param_span: self.tcx.def_span(region_def_id),
                            });
                        return;
                    }
                    Scope::Root { .. } => break,
                    Scope::Binder { s, .. } | Scope::Body { s, .. } |
                        Scope::Opaque { s, .. } | Scope::ObjectLifetimeDefault { s,
                        .. } | Scope::Supertrait { s, .. } |
                        Scope::TraitRefBoundary { s, .. } | Scope::LateBoundary { s,
                        .. } => {
                        scope = s;
                    }
                }
            }
            self.tcx.dcx().span_delayed_bug(lifetime_ref.ident.span,
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("Could not resolve {0:?} in scope {1:#?}",
                                lifetime_ref, self.scope))
                    }));
        }
    }
}#[instrument(level = "debug", skip(self))]
1355    fn resolve_lifetime_ref(
1356        &mut self,
1357        region_def_id: LocalDefId,
1358        lifetime_ref: &'tcx hir::Lifetime,
1359    ) {
1360        // Walk up the scope chain, tracking the number of fn scopes
1361        // that we pass through, until we find a lifetime with the
1362        // given name or we run out of scopes.
1363        // search.
1364        let mut late_depth = 0;
1365        let mut scope = self.scope;
1366        let mut outermost_body = None;
1367        let mut crossed_late_boundary = None;
1368        let mut opaque_capture_scopes = vec![];
1369        let result = loop {
1370            match *scope {
1371                Scope::Body { id, s } => {
1372                    outermost_body = Some(id);
1373                    scope = s;
1374                }
1375
1376                Scope::Root { opt_parent_item } => {
1377                    if let Some(parent_item) = opt_parent_item
1378                        && let parent_generics = self.tcx.generics_of(parent_item)
1379                        && parent_generics
1380                            .param_def_id_to_index(self.tcx, region_def_id.to_def_id())
1381                            .is_some()
1382                    {
1383                        break Some(ResolvedArg::EarlyBound(region_def_id));
1384                    }
1385                    break None;
1386                }
1387
1388                Scope::Binder { ref bound_vars, scope_type, s, where_bound_origin, .. } => {
1389                    if let Some(&def) = bound_vars.get(&region_def_id) {
1390                        break Some(def.shifted(late_depth));
1391                    }
1392                    match scope_type {
1393                        BinderScopeType::Normal => late_depth += 1,
1394                        BinderScopeType::Concatenating => {}
1395                    }
1396                    // Fresh lifetimes in APIT used to be allowed in async fns and forbidden in
1397                    // regular fns.
1398                    if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin
1399                        && let hir::LifetimeKind::Param(param_id) = lifetime_ref.kind
1400                        && let Some(generics) =
1401                            self.tcx.hir_get_generics(self.tcx.local_parent(param_id))
1402                        && let Some(param) = generics.params.iter().find(|p| p.def_id == param_id)
1403                        && param.is_elided_lifetime()
1404                        && !self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id).is_async()
1405                        && !self.tcx.features().anonymous_lifetime_in_impl_trait()
1406                    {
1407                        let mut diag: rustc_errors::Diag<'_> =
1408                            rustc_session::diagnostics::feature_err(
1409                                &self.tcx.sess,
1410                                sym::anonymous_lifetime_in_impl_trait,
1411                                lifetime_ref.ident.span,
1412                                "anonymous lifetimes in `impl Trait` are unstable",
1413                            );
1414
1415                        if let Some(generics) =
1416                            self.tcx.hir_get_generics(lifetime_ref.hir_id.owner.def_id)
1417                        {
1418                            let new_param_sugg =
1419                                if let Some(span) = generics.span_for_lifetime_suggestion() {
1420                                    (span, "'a, ".to_owned())
1421                                } else {
1422                                    (generics.span, "<'a>".to_owned())
1423                                };
1424
1425                            let lifetime_sugg = lifetime_ref.suggestion("'a");
1426                            let suggestions = vec![lifetime_sugg, new_param_sugg];
1427
1428                            diag.span_label(
1429                                lifetime_ref.ident.span,
1430                                "expected named lifetime parameter",
1431                            );
1432                            diag.multipart_suggestion(
1433                                "consider introducing a named lifetime parameter",
1434                                suggestions,
1435                                rustc_errors::Applicability::MaybeIncorrect,
1436                            );
1437                        }
1438
1439                        diag.emit();
1440                        return;
1441                    }
1442                    scope = s;
1443                }
1444
1445                Scope::Opaque { captures, def_id, s } => {
1446                    opaque_capture_scopes.push((def_id, captures));
1447                    late_depth = 0;
1448                    scope = s;
1449                }
1450
1451                Scope::ObjectLifetimeDefault { s, .. }
1452                | Scope::Supertrait { s, .. }
1453                | Scope::TraitRefBoundary { s, .. } => {
1454                    scope = s;
1455                }
1456
1457                Scope::LateBoundary { s, what, deny_late_regions } => {
1458                    if deny_late_regions {
1459                        crossed_late_boundary = Some(what);
1460                    }
1461                    scope = s;
1462                }
1463            }
1464        };
1465
1466        if let Some(mut def) = result {
1467            def = self.remap_opaque_captures(&opaque_capture_scopes, def, lifetime_ref.ident);
1468
1469            if let ResolvedArg::EarlyBound(..) = def {
1470                // Do not free early-bound regions, only late-bound ones.
1471            } else if let ResolvedArg::LateBound(_, _, param_def_id) = def
1472                && let Some(what) = crossed_late_boundary
1473            {
1474                let use_span = lifetime_ref.ident.span;
1475                let def_span = self.tcx.def_span(param_def_id);
1476                let guar = match self.tcx.def_kind(param_def_id) {
1477                    DefKind::LifetimeParam => {
1478                        self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Lifetime {
1479                            use_span,
1480                            def_span,
1481                            what,
1482                        })
1483                    }
1484                    kind => span_bug!(
1485                        use_span,
1486                        "did not expect to resolve lifetime to {}",
1487                        kind.descr(param_def_id.to_def_id())
1488                    ),
1489                };
1490                def = ResolvedArg::Error(guar);
1491            } else if let Some(body_id) = outermost_body {
1492                let fn_id = self.tcx.hir_body_owner(body_id);
1493                match self.tcx.hir_node(fn_id) {
1494                    Node::Item(hir::Item { owner_id, kind: hir::ItemKind::Fn { .. }, .. })
1495                    | Node::TraitItem(hir::TraitItem {
1496                        owner_id,
1497                        kind: hir::TraitItemKind::Fn(..),
1498                        ..
1499                    })
1500                    | Node::ImplItem(hir::ImplItem {
1501                        owner_id,
1502                        kind: hir::ImplItemKind::Fn(..),
1503                        ..
1504                    }) => {
1505                        def = ResolvedArg::Free(owner_id.def_id, def.id().unwrap());
1506                    }
1507                    Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) => {
1508                        def = ResolvedArg::Free(closure.def_id, def.id().unwrap());
1509                    }
1510                    _ => {}
1511                }
1512            }
1513
1514            self.insert_lifetime(lifetime_ref, def);
1515            return;
1516        }
1517
1518        // We may fail to resolve higher-ranked lifetimes that are mentioned by APIT.
1519        // AST-based resolution does not care for impl-trait desugaring, which are the
1520        // responsibility of lowering. This may create a mismatch between the resolution
1521        // AST found (`region_def_id`) which points to HRTB, and what HIR allows.
1522        // ```
1523        // fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {}
1524        // ```
1525        //
1526        // In such case, walk back the binders to diagnose it properly.
1527        let mut scope = self.scope;
1528        loop {
1529            match *scope {
1530                Scope::Binder {
1531                    where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), ..
1532                } => {
1533                    self.tcx.dcx().emit_err(diagnostics::LateBoundInApit::Lifetime {
1534                        span: lifetime_ref.ident.span,
1535                        param_span: self.tcx.def_span(region_def_id),
1536                    });
1537                    return;
1538                }
1539                Scope::Root { .. } => break,
1540                Scope::Binder { s, .. }
1541                | Scope::Body { s, .. }
1542                | Scope::Opaque { s, .. }
1543                | Scope::ObjectLifetimeDefault { s, .. }
1544                | Scope::Supertrait { s, .. }
1545                | Scope::TraitRefBoundary { s, .. }
1546                | Scope::LateBoundary { s, .. } => {
1547                    scope = s;
1548                }
1549            }
1550        }
1551
1552        self.tcx.dcx().span_delayed_bug(
1553            lifetime_ref.ident.span,
1554            format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
1555        );
1556    }
1557
1558    /// Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
1559    /// and ban them. Type variables instantiated inside binders aren't
1560    /// well-supported at the moment, so this doesn't work.
1561    /// In the future, this should be fixed and this error should be removed.
1562    fn check_lifetime_is_capturable(
1563        &self,
1564        opaque_def_id: LocalDefId,
1565        lifetime: ResolvedArg,
1566        capture_span: Span,
1567    ) -> Result<(), ErrorGuaranteed> {
1568        let ResolvedArg::LateBound(_, _, lifetime_def_id) = lifetime else { return Ok(()) };
1569        let lifetime_hir_id = self.tcx.local_def_id_to_hir_id(lifetime_def_id);
1570        let bad_place = match self.tcx.hir_node(self.tcx.parent_hir_id(lifetime_hir_id)) {
1571            // Opaques do not declare their own lifetimes, so if a lifetime comes from an opaque
1572            // it must be a reified late-bound lifetime from a trait goal.
1573            hir::Node::OpaqueTy(_) => "higher-ranked lifetime from outer `impl Trait`",
1574            // Other items are fine.
1575            hir::Node::Item(_) | hir::Node::TraitItem(_) | hir::Node::ImplItem(_) => return Ok(()),
1576            hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(_), .. }) => {
1577                "higher-ranked lifetime from function pointer"
1578            }
1579            hir::Node::Ty(hir::Ty { kind: hir::TyKind::TraitObject(..), .. }) => {
1580                "higher-ranked lifetime from `dyn` type"
1581            }
1582            _ => "higher-ranked lifetime",
1583        };
1584
1585        let decl_span = self.tcx.def_span(lifetime_def_id);
1586        let opaque_span = self.tcx.def_span(opaque_def_id);
1587
1588        let mut errors = self.opaque_capture_errors.borrow_mut();
1589        let error_info = errors.get_or_insert_with(|| OpaqueHigherRankedLifetimeCaptureErrors {
1590            bad_place,
1591            capture_spans: Vec::new(),
1592            decl_spans: Vec::new(),
1593        });
1594
1595        if error_info.capture_spans.is_empty() {
1596            error_info.capture_spans.push(opaque_span);
1597        }
1598
1599        if capture_span != decl_span && capture_span != opaque_span {
1600            error_info.capture_spans.push(capture_span);
1601        }
1602
1603        if !error_info.decl_spans.contains(&decl_span) {
1604            error_info.decl_spans.push(decl_span);
1605        }
1606
1607        // Errors should be emitted by `emit_opaque_capture_errors`.
1608        Err(self.tcx.dcx().span_delayed_bug(capture_span, "opaque capture error not emitted"))
1609    }
1610
1611    fn emit_opaque_capture_errors(&self) -> Option<ErrorGuaranteed> {
1612        let errors = self.opaque_capture_errors.borrow_mut().take()?;
1613        if errors.capture_spans.is_empty() {
1614            return None;
1615        }
1616
1617        let mut span = rustc_errors::MultiSpan::from_span(errors.capture_spans[0]);
1618        for &capture_span in &errors.capture_spans[1..] {
1619            span.push_span_label(capture_span, "");
1620        }
1621        let decl_span = rustc_errors::MultiSpan::from_spans(errors.decl_spans);
1622
1623        // Ensure that the parent of the def is an item, not HRTB
1624        let guar = self.tcx.dcx().emit_err(diagnostics::OpaqueCapturesHigherRankedLifetime {
1625            span,
1626            label: Some(errors.capture_spans[0]),
1627            decl_span,
1628            bad_place: errors.bad_place,
1629        });
1630
1631        Some(guar)
1632    }
1633
1634    {}
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("remap_opaque_captures",
                                "rustc_hir_analysis::collect::resolve_bound_vars",
                                ::tracing::Level::TRACE,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                ::tracing_core::__macro_support::Option::Some(1634u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("lifetime")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("lifetime");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("ident")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("ident");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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: ResolvedArg = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if let Some(&(opaque_def_id, _)) =
                                opaque_capture_scopes.last() {
                            if let Err(guar) =
                                    self.check_lifetime_is_capturable(opaque_def_id, lifetime,
                                        ident.span) {
                                lifetime = ResolvedArg::Error(guar);
                            }
                        }
                        for &(opaque_def_id, captures) in
                            opaque_capture_scopes.iter().rev() {
                            let mut captures = captures.borrow_mut();
                            let remapped =
                                *captures.entry(lifetime).or_insert_with(||
                                            {
                                                let feed =
                                                    self.tcx.create_def(opaque_def_id, None,
                                                        DefKind::LifetimeParam,
                                                        Some(DefPathData::OpaqueLifetime(ident.name)),
                                                        self.disambiguators.get_or_create(opaque_def_id));
                                                feed.def_span(ident.span);
                                                feed.def_ident_span(Some(ident.span));
                                                feed.def_id()
                                            });
                            lifetime = ResolvedArg::EarlyBound(remapped);
                        }
                        lifetime
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:1634",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(1634u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "trace", skip(self, opaque_capture_scopes), ret)]
1635    fn remap_opaque_captures(
1636        &mut self,
1637        opaque_capture_scopes: &Vec<(LocalDefId, &RefCell<FxIndexMap<ResolvedArg, LocalDefId>>)>,
1638        mut lifetime: ResolvedArg,
1639        ident: Ident,
1640    ) -> ResolvedArg {
1641        if let Some(&(opaque_def_id, _)) = opaque_capture_scopes.last() {
1642            if let Err(guar) =
1643                self.check_lifetime_is_capturable(opaque_def_id, lifetime, ident.span)
1644            {
1645                lifetime = ResolvedArg::Error(guar);
1646            }
1647        }
1648
1649        for &(opaque_def_id, captures) in opaque_capture_scopes.iter().rev() {
1650            let mut captures = captures.borrow_mut();
1651            let remapped = *captures.entry(lifetime).or_insert_with(|| {
1652                // `opaque_def_id` is unique to the `BoundVarContext` pass which is executed once
1653                // per `resolve_bound_vars` query. This is the only location that creates
1654                // `OpaqueLifetime` paths. `<opaque_def_id>::OpaqueLifetime(..)` is thus unique
1655                // to this query and duplicates within the query are handled by `self.disambiguator`.
1656                let feed = self.tcx.create_def(
1657                    opaque_def_id,
1658                    None,
1659                    DefKind::LifetimeParam,
1660                    Some(DefPathData::OpaqueLifetime(ident.name)),
1661                    self.disambiguators.get_or_create(opaque_def_id),
1662                );
1663                feed.def_span(ident.span);
1664                feed.def_ident_span(Some(ident.span));
1665                feed.def_id()
1666            });
1667            lifetime = ResolvedArg::EarlyBound(remapped);
1668        }
1669        lifetime
1670    }
1671
1672    fn resolve_type_ref(&mut self, param_def_id: LocalDefId, hir_id: HirId) {
1673        // Walk up the scope chain, tracking the number of fn scopes
1674        // that we pass through, until we find a lifetime with the
1675        // given name or we run out of scopes.
1676        // search.
1677        let mut late_depth = 0;
1678        let mut scope = self.scope;
1679        let mut crossed_late_boundary = None;
1680
1681        let result = loop {
1682            match *scope {
1683                Scope::Body { s, .. } => {
1684                    scope = s;
1685                }
1686
1687                Scope::Root { opt_parent_item } => {
1688                    if let Some(parent_item) = opt_parent_item
1689                        && let parent_generics = self.tcx.generics_of(parent_item)
1690                        && parent_generics
1691                            .param_def_id_to_index(self.tcx, param_def_id.to_def_id())
1692                            .is_some()
1693                    {
1694                        break Some(ResolvedArg::EarlyBound(param_def_id));
1695                    }
1696                    break None;
1697                }
1698
1699                Scope::Binder { ref bound_vars, scope_type, s, .. } => {
1700                    if let Some(&def) = bound_vars.get(&param_def_id) {
1701                        break Some(def.shifted(late_depth));
1702                    }
1703                    match scope_type {
1704                        BinderScopeType::Normal => late_depth += 1,
1705                        BinderScopeType::Concatenating => {}
1706                    }
1707                    scope = s;
1708                }
1709
1710                Scope::ObjectLifetimeDefault { s, .. }
1711                | Scope::Opaque { s, .. }
1712                | Scope::Supertrait { s, .. }
1713                | Scope::TraitRefBoundary { s, .. } => {
1714                    scope = s;
1715                }
1716
1717                Scope::LateBoundary { s, what, deny_late_regions: _ } => {
1718                    crossed_late_boundary = Some(what);
1719                    scope = s;
1720                }
1721            }
1722        };
1723
1724        if let Some(def) = result {
1725            if let ResolvedArg::LateBound(..) = def
1726                && let Some(what) = crossed_late_boundary
1727            {
1728                let use_span = self.tcx.hir_span(hir_id);
1729                let def_span = self.tcx.def_span(param_def_id);
1730                let guar = match self.tcx.def_kind(param_def_id) {
1731                    DefKind::ConstParam => {
1732                        self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Const {
1733                            use_span,
1734                            def_span,
1735                            what,
1736                        })
1737                    }
1738                    DefKind::TyParam => {
1739                        self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Type {
1740                            use_span,
1741                            def_span,
1742                            what,
1743                        })
1744                    }
1745                    kind => ::rustc_middle::util::bug::span_bug_fmt(use_span,
    format_args!("did not expect to resolve non-lifetime param to {0}",
        kind.descr(param_def_id.to_def_id())))span_bug!(
1746                        use_span,
1747                        "did not expect to resolve non-lifetime param to {}",
1748                        kind.descr(param_def_id.to_def_id())
1749                    ),
1750                };
1751                self.rbv.defs.insert(hir_id.local_id, ResolvedArg::Error(guar));
1752            } else {
1753                self.rbv.defs.insert(hir_id.local_id, def);
1754            }
1755            return;
1756        }
1757
1758        // We may fail to resolve higher-ranked ty/const vars that are mentioned by APIT.
1759        // AST-based resolution does not care for impl-trait desugaring, which are the
1760        // responsibility of lowering. This may create a mismatch between the resolution
1761        // AST found (`param_def_id`) which points to HRTB, and what HIR allows.
1762        // ```
1763        // fn foo(x: impl for<T> Trait<Assoc = impl Trait2<T>>) {}
1764        // ```
1765        //
1766        // In such case, walk back the binders to diagnose it properly.
1767        let mut scope = self.scope;
1768        loop {
1769            match *scope {
1770                Scope::Binder {
1771                    where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), ..
1772                } => {
1773                    let guar = self.tcx.dcx().emit_err(match self.tcx.def_kind(param_def_id) {
1774                        DefKind::TyParam => diagnostics::LateBoundInApit::Type {
1775                            span: self.tcx.hir_span(hir_id),
1776                            param_span: self.tcx.def_span(param_def_id),
1777                        },
1778                        DefKind::ConstParam => diagnostics::LateBoundInApit::Const {
1779                            span: self.tcx.hir_span(hir_id),
1780                            param_span: self.tcx.def_span(param_def_id),
1781                        },
1782                        kind => {
1783                            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected def-kind: {0}",
        kind.descr(param_def_id.to_def_id())))bug!("unexpected def-kind: {}", kind.descr(param_def_id.to_def_id()))
1784                        }
1785                    });
1786                    self.rbv.defs.insert(hir_id.local_id, ResolvedArg::Error(guar));
1787                    return;
1788                }
1789                Scope::Root { .. } => break,
1790                Scope::Binder { s, .. }
1791                | Scope::Body { s, .. }
1792                | Scope::Opaque { s, .. }
1793                | Scope::ObjectLifetimeDefault { s, .. }
1794                | Scope::Supertrait { s, .. }
1795                | Scope::TraitRefBoundary { s, .. }
1796                | Scope::LateBoundary { s, .. } => {
1797                    scope = s;
1798                }
1799            }
1800        }
1801
1802        self.tcx
1803            .dcx()
1804            .span_bug(self.tcx.hir_span(hir_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("could not resolve {0:?}",
                param_def_id))
    })format!("could not resolve {param_def_id:?}"));
1805    }
1806
1807    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_path_segment_args",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1807u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("generic_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("generic_args");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("seg_idx")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("seg_idx");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_args)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&seg_idx)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some((inputs, output)) =
                    generic_args.paren_sugar_inputs_output() {
                self.visit_fn_like_elision(inputs, Some(output), false);
                return;
            }
            for arg in generic_args.args {
                if let hir::GenericArg::Lifetime(lt) = arg {
                    self.visit_lifetime(lt);
                }
            }
            let container = self.eligible_container(path, seg_idx);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:1828",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1828u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("container")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("container");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&container)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let (has_self, object_lifetime_defaults) =
                container.map(|(def_id, segs)|
                            {
                                let generics = self.tcx.generics_of(def_id);
                                let defaults =
                                    self.compute_object_lifetime_defaults(generics, segs);
                                (generics.has_own_self(), defaults)
                            }).unwrap_or_default();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:1838",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1838u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("object_lifetime_defaults")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("object_lifetime_defaults");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&object_lifetime_defaults)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let mut i = has_self as usize;
            for arg in generic_args.args {
                match arg {
                    GenericArg::Lifetime(_) => {}
                    GenericArg::Type(ty) => {
                        if let Some(&lt) = object_lifetime_defaults.get(i) {
                            let scope =
                                Scope::ObjectLifetimeDefault {
                                    lifetime: lt,
                                    s: self.scope,
                                };
                            self.with(scope, |this| this.visit_ty(ty));
                        } else { self.visit_ty(ty); }
                        i += 1;
                    }
                    GenericArg::Const(ct) => {
                        self.visit_const_arg(ct);
                        i += 1;
                    }
                    GenericArg::Infer(inf) => {
                        self.visit_id(inf.hir_id);
                        i += 1;
                    }
                }
            }
            let has_lifetime_args = generic_args.has_lifetime_args();
            for constraint in generic_args.constraints {
                let scope =
                    Scope::ObjectLifetimeDefault {
                        lifetime: if has_lifetime_args ||
                                constraint.gen_args.has_lifetime_args() {
                            None
                        } else { Some(ResolvedArg::StaticLifetime) },
                        s: self.scope,
                    };
                if constraint.gen_args.parenthesized ==
                        hir::GenericArgsParentheses::ReturnTypeNotation {
                    let bound_vars =
                        if let Some((container_def_id, _)) = container &&
                                    let DefKind::Trait | DefKind::TraitAlias =
                                        self.tcx.def_kind(container_def_id) &&
                                let Some((mut bound_vars, assoc_fn)) =
                                    BoundVarContext::supertrait_hrtb_vars(self.tcx,
                                        container_def_id, constraint.ident, ty::AssocTag::Fn) {
                            bound_vars.extend(self.tcx.generics_of(assoc_fn.def_id).own_params.iter().map(|param|
                                        generic_param_def_as_bound_arg(param)));
                            let fn_bound_vars =
                                if assoc_fn.def_id == constraint.hir_id.owner.to_def_id() {
                                    let fn_hir_id =
                                        self.tcx.local_def_id_to_hir_id(assoc_fn.def_id.expect_local());
                                    self.rbv.late_bound_vars.get(&fn_hir_id.local_id).expect("late-bound vars for the current function were not recorded").clone()
                                } else {
                                    self.tcx.fn_sig(assoc_fn.def_id).instantiate_identity().skip_norm_wip().bound_vars().to_vec()
                                };
                            bound_vars.extend(fn_bound_vars);
                            bound_vars
                        } else {
                            self.tcx.dcx().span_delayed_bug(constraint.ident.span,
                                "bad return type notation here");
                            ::alloc::vec::Vec::new()
                        };
                    self.with(scope,
                        |this|
                            {
                                let scope = Scope::Supertrait { bound_vars, s: this.scope };
                                this.with(scope,
                                    |this|
                                        {
                                            let (bound_vars, _) = this.poly_trait_ref_binder_info();
                                            this.record_late_bound_vars(constraint.hir_id, bound_vars);
                                            this.visit_assoc_item_constraint(constraint)
                                        });
                            });
                } else if let Some((container_def_id, _)) = container {
                    let bound_vars =
                        BoundVarContext::supertrait_hrtb_vars(self.tcx,
                                container_def_id, constraint.ident,
                                ty::AssocTag::Type).map(|(bound_vars, _)| bound_vars);
                    self.with(scope,
                        |this|
                            {
                                let scope =
                                    Scope::Supertrait {
                                        bound_vars: bound_vars.unwrap_or_default(),
                                        s: this.scope,
                                    };
                                this.with(scope,
                                    |this| this.visit_assoc_item_constraint(constraint));
                            });
                } else {
                    self.with(scope,
                        |this| this.visit_assoc_item_constraint(constraint));
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1808    fn visit_path_segment_args(
1809        &mut self,
1810        generic_args: &'tcx hir::GenericArgs<'tcx>,
1811        seg_idx: SegIdx,
1812        path: &hir::Path<'tcx>,
1813    ) {
1814        if let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() {
1815            self.visit_fn_like_elision(inputs, Some(output), false);
1816            return;
1817        }
1818
1819        // Let's first resolve all lifetime arguments because we need their
1820        // resolution for computing the trait object lifetime defaults.
1821        for arg in generic_args.args {
1822            if let hir::GenericArg::Lifetime(lt) = arg {
1823                self.visit_lifetime(lt);
1824            }
1825        }
1826
1827        let container = self.eligible_container(path, seg_idx);
1828        debug!(?container);
1829
1830        let (has_self, object_lifetime_defaults) = container
1831            .map(|(def_id, segs)| {
1832                let generics = self.tcx.generics_of(def_id);
1833                let defaults = self.compute_object_lifetime_defaults(generics, segs);
1834                (generics.has_own_self(), defaults)
1835            })
1836            .unwrap_or_default();
1837
1838        debug!(?object_lifetime_defaults);
1839
1840        let mut i = has_self as usize;
1841        for arg in generic_args.args {
1842            match arg {
1843                // We've already visited all lifetime arguments at the start.
1844                GenericArg::Lifetime(_) => {}
1845                GenericArg::Type(ty) => {
1846                    if let Some(&lt) = object_lifetime_defaults.get(i) {
1847                        let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
1848                        self.with(scope, |this| this.visit_ty(ty));
1849                    } else {
1850                        self.visit_ty(ty);
1851                    }
1852                    i += 1;
1853                }
1854                GenericArg::Const(ct) => {
1855                    self.visit_const_arg(ct);
1856                    i += 1;
1857                }
1858                GenericArg::Infer(inf) => {
1859                    self.visit_id(inf.hir_id);
1860                    i += 1;
1861                }
1862            }
1863        }
1864
1865        let has_lifetime_args = generic_args.has_lifetime_args();
1866
1867        for constraint in generic_args.constraints {
1868            let scope = Scope::ObjectLifetimeDefault {
1869                // FIXME: Ideally we would consider the *item bounds* of assoc types when deducing
1870                //        the trait object lifetime default for the RHS of assoc type bindings.
1871                //        For example, given
1872                //
1873                //            trait TraitA<'a> { type AssocTy: ?Sized + 'a; }
1874                //            trait TraitB { type AssocTy<'a>: ?Sized + 'a; }
1875                //
1876                //        we would elaborate the `dyn Bound` in `TraitA<'r, AssocTy = dyn Bound>`
1877                //        and `TraitB<AssocTy<'r> = dyn Bound>` to `dyn Bound + 'r`.
1878                //
1879                // FIXME: Moreover, ideally GAT args in bindings could induce
1880                //        trait object lifetime defaults. For example, given
1881                //
1882                //           trait TraitA<'a> { type AssocTy<T: ?Sized + 'a>; }
1883                //           trait TraitB { type AssocTy<'a, T: ?Sized + 'a>; }
1884                //
1885                //        we would elab the `dyn Bound` in `TraitA<'r, AssocTy<dyn Bound> = ()>`
1886                //        and `TraitB<AssocTy<'r, dyn Bound> = ()>` to `dyn Bound + 'r`.
1887                //
1888                // HACK: For now however, if the user passes any lifetime arguments to the trait or
1889                //       the (generic) assoc type, we will treat the trait object lifetime default
1890                //       as indeterminate thus forcing the user to explicitly specify the lifetime.
1891                //
1892                //       If the trait or the assoc type have lifetime parameters, it's *possible*
1893                //       that they occur in the predicates or item bounds of the assoc type, so we
1894                //       conservatively reject such cases to allow us to implement the correct
1895                //       behavior in the future (here we assume that the number of arguments equals
1896                //       the number of parameters which is fine since a mismatch would get rejected
1897                //       later anyway).
1898                //
1899                //       If the items don't have any lifetime parameters we can safely use `'static`
1900                //       since there is no other possibility.
1901                lifetime: if has_lifetime_args || constraint.gen_args.has_lifetime_args() {
1902                    None
1903                } else {
1904                    Some(ResolvedArg::StaticLifetime)
1905                },
1906                s: self.scope,
1907            };
1908            // If the args are parenthesized, then this must be `feature(return_type_notation)`.
1909            // In that case, introduce a binder over all of the function's early and late bound vars.
1910            //
1911            // For example, given
1912            // ```
1913            // trait Foo {
1914            //     async fn x<'r, T>();
1915            // }
1916            // ```
1917            // and a bound that looks like:
1918            //    `for<'a> T::Trait<'a, x(..): for<'b> Other<'b>>`
1919            // this is going to expand to something like:
1920            //    `for<'a> for<'r> <T as Trait<'a>>::x::<'r, T>::{opaque#0}: for<'b> Other<'b>`.
1921            if constraint.gen_args.parenthesized == hir::GenericArgsParentheses::ReturnTypeNotation
1922            {
1923                let bound_vars = if let Some((container_def_id, _)) = container
1924                    && let DefKind::Trait | DefKind::TraitAlias =
1925                        self.tcx.def_kind(container_def_id)
1926                    && let Some((mut bound_vars, assoc_fn)) = BoundVarContext::supertrait_hrtb_vars(
1927                        self.tcx,
1928                        container_def_id,
1929                        constraint.ident,
1930                        ty::AssocTag::Fn,
1931                    ) {
1932                    bound_vars.extend(
1933                        self.tcx
1934                            .generics_of(assoc_fn.def_id)
1935                            .own_params
1936                            .iter()
1937                            .map(|param| generic_param_def_as_bound_arg(param)),
1938                    );
1939                    // `resolve_bound_vars` is computed per HIR owner. `visit_early_late`
1940                    // records this associated function's binder before walking its signature,
1941                    // so reuse that in-progress binder instead of recursively querying `fn_sig`.
1942                    let fn_bound_vars = if assoc_fn.def_id == constraint.hir_id.owner.to_def_id() {
1943                        let fn_hir_id =
1944                            self.tcx.local_def_id_to_hir_id(assoc_fn.def_id.expect_local());
1945                        self.rbv
1946                            .late_bound_vars
1947                            .get(&fn_hir_id.local_id)
1948                            .expect("late-bound vars for the current function were not recorded")
1949                            .clone()
1950                    } else {
1951                        self.tcx
1952                            .fn_sig(assoc_fn.def_id)
1953                            .instantiate_identity()
1954                            .skip_norm_wip()
1955                            .bound_vars()
1956                            .to_vec()
1957                    };
1958                    bound_vars.extend(fn_bound_vars);
1959                    bound_vars
1960                } else {
1961                    self.tcx
1962                        .dcx()
1963                        .span_delayed_bug(constraint.ident.span, "bad return type notation here");
1964                    vec![]
1965                };
1966                self.with(scope, |this| {
1967                    let scope = Scope::Supertrait { bound_vars, s: this.scope };
1968                    this.with(scope, |this| {
1969                        let (bound_vars, _) = this.poly_trait_ref_binder_info();
1970                        this.record_late_bound_vars(constraint.hir_id, bound_vars);
1971                        this.visit_assoc_item_constraint(constraint)
1972                    });
1973                });
1974            } else if let Some((container_def_id, _)) = container {
1975                let bound_vars = BoundVarContext::supertrait_hrtb_vars(
1976                    self.tcx,
1977                    container_def_id,
1978                    constraint.ident,
1979                    ty::AssocTag::Type,
1980                )
1981                .map(|(bound_vars, _)| bound_vars);
1982                self.with(scope, |this| {
1983                    let scope = Scope::Supertrait {
1984                        bound_vars: bound_vars.unwrap_or_default(),
1985                        s: this.scope,
1986                    };
1987                    this.with(scope, |this| this.visit_assoc_item_constraint(constraint));
1988                });
1989            } else {
1990                self.with(scope, |this| this.visit_assoc_item_constraint(constraint));
1991            }
1992        }
1993    }
1994
1995    /// Return the eligible container for the path segment given by the index if applicable.
1996    ///
1997    /// Such a container induces lifetime defaults for trait object types contained
1998    /// in any of the type arguments passed to it (any inner containers will of course
1999    /// end up shadowing that default).
2000    fn eligible_container<'b>(
2001        &self,
2002        path: &'b hir::Path<'tcx>,
2003        seg_idx: SegIdx,
2004    ) -> Option<(DefId, &'b [hir::PathSegment<'tcx>])> {
2005        let RevSegIdx(rev_seg_idx) = seg_idx.reverse(path.segments);
2006        let SegIdx(seg_idx) = seg_idx;
2007
2008        // NOTE: We don't need to care about definition kinds that may have generics if they
2009        // can only ever appear in positions where we can perform type inference (i.e., bodies).
2010
2011        // FIXME(mgca, #151649): Type-level free/assoc consts, const&fn ctors should also qualify.
2012        // FIXME(return_type_notation, #151662): Assoc fns should also qualify.
2013
2014        let (kind, def_id) = match path.res {
2015            Res::Def(kind, def_id) => (kind, def_id),
2016            Res::PrimTy(..)
2017            | Res::SelfTyParam { .. }
2018            | Res::SelfTyAlias { .. }
2019            | Res::SelfCtor(_)
2020            | Res::Local(_)
2021            | Res::ToolMod
2022            | Res::OpenMod(_)
2023            | Res::NonMacroAttr(_)
2024            | Res::Err => return None, // see NOTE above!
2025        };
2026
2027        match kind {
2028            DefKind::AssocTy => match rev_seg_idx {
2029                0 => Some((def_id, path.segments)),
2030                // We're looking at the trait ref of an assoc type projection.
2031                // E.g., the `TraitRef<…>` in `<… as path::to::TraitRef<…>>::AssocTy<…>`.
2032                1 => Some((self.tcx.parent(def_id), &path.segments[..=seg_idx])),
2033                _ => None,
2034            },
2035            DefKind::Variant => match rev_seg_idx {
2036                // We're looking at the `Variant::<…>` in `path::to::Variant::<…> { … }`.
2037                // Even if it's the variant segment that has the generic args and not the
2038                // enum segment, it's the enum that has the corresponding generic params.
2039                0 => Some((self.tcx.parent(def_id), path.segments)),
2040                // We're looking at the `Enum::<…>` in `path::to::Enum::<…>::Variant { … }`.
2041                1 => Some((self.tcx.parent(def_id), &path.segments[..=seg_idx])),
2042                _ => None,
2043            },
2044            DefKind::Enum
2045            | DefKind::Struct
2046            | DefKind::Trait
2047            | DefKind::TraitAlias
2048            | DefKind::TyAlias
2049            | DefKind::Union => match rev_seg_idx {
2050                0 => Some((def_id, path.segments)),
2051                _ => None,
2052            },
2053            DefKind::AnonConst
2054            | DefKind::AssocConst { .. }
2055            | DefKind::AssocFn
2056            | DefKind::Closure
2057            | DefKind::Const { .. }
2058            | DefKind::ConstParam
2059            | DefKind::Ctor(..)
2060            | DefKind::ExternCrate
2061            | DefKind::Field
2062            | DefKind::Fn
2063            | DefKind::ForeignMod
2064            | DefKind::ForeignTy
2065            | DefKind::GlobalAsm
2066            | DefKind::Impl { .. }
2067            | DefKind::LifetimeParam
2068            | DefKind::Macro(_)
2069            | DefKind::Mod
2070            | DefKind::OpaqueTy
2071            | DefKind::Static { .. }
2072            | DefKind::SyntheticCoroutineBody
2073            | DefKind::TyParam
2074            | DefKind::Use
2075            | DefKind::TestBinderConstraints => None, // see NOTE above!
2076        }
2077    }
2078
2079    /// Compute a list of trait object lifetime defaults, one for each type parameter,
2080    /// per the rules initially given in RFCs [599] and [1156]. Example:
2081    ///
2082    /// ```
2083    /// struct Foo<'a, T: 'a + ?Sized, U: ?Sized>(&'a T, &'a U);
2084    /// ```
2085    ///
2086    /// If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to elaborate
2087    /// * `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound) and
2088    /// * `dyn Baz` to `dyn Baz + 'static` (because there is no such bound).
2089    ///
2090    /// Therefore, we would compute a list like `['x, 'static]`. Note that the list only
2091    /// includes entries for type and const parameters, not for lifetime parameters.
2092    ///
2093    /// [599]: https://rust-lang.github.io/rfcs/0599-default-object-bound.html
2094    /// [1156]: https://rust-lang.github.io/rfcs/1156-adjust-default-object-bounds.html
2095    fn compute_object_lifetime_defaults(
2096        &self,
2097        generics: &ty::Generics,
2098        segments: &[hir::PathSegment<'_>],
2099    ) -> Vec<Option<ResolvedArg>> {
2100        let in_body = {
2101            let mut scope = self.scope;
2102            loop {
2103                match *scope {
2104                    Scope::Root { .. } => break false,
2105
2106                    Scope::Body { .. } => break true,
2107
2108                    Scope::Binder { s, .. }
2109                    | Scope::ObjectLifetimeDefault { s, .. }
2110                    | Scope::Opaque { s, .. }
2111                    | Scope::Supertrait { s, .. }
2112                    | Scope::TraitRefBoundary { s, .. }
2113                    | Scope::LateBoundary { s, .. } => {
2114                        scope = s;
2115                    }
2116                }
2117            }
2118        };
2119
2120        let set_to_region = |set: ObjectLifetimeDefault| match set {
2121            ObjectLifetimeDefault::Empty => {
2122                if in_body {
2123                    None
2124                } else {
2125                    Some(ResolvedArg::StaticLifetime)
2126                }
2127            }
2128            ObjectLifetimeDefault::Static => Some(ResolvedArg::StaticLifetime),
2129            ObjectLifetimeDefault::Param(param_def_id) => {
2130                struct ArgIdx(usize);
2131
2132                fn resolve_param(
2133                    param_def_id: DefId,
2134                    generics: &ty::Generics,
2135                    tcx: TyCtxt<'_>,
2136                ) -> (RevSegIdx, ArgIdx) {
2137                    if let Some(&index) = generics.param_def_id_to_index.get(&param_def_id) {
2138                        let has_self = generics.has_own_self();
2139                        let index = index as usize - generics.parent_count - has_self as usize;
2140                        (RevSegIdx(0), ArgIdx(index))
2141                    } else if let Some(parent) = generics.parent {
2142                        let parent_generics = tcx.generics_of(parent);
2143                        let (RevSegIdx(rev_seg_idx), arg_idx) =
2144                            resolve_param(param_def_id, parent_generics, tcx);
2145                        (RevSegIdx(rev_seg_idx + 1), arg_idx)
2146                    } else {
2147                        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2148                    }
2149                }
2150
2151                let (rev_seg_idx, ArgIdx(arg_idx)) =
2152                    resolve_param(param_def_id, generics, self.tcx);
2153
2154                let SegIdx(seg_idx) = rev_seg_idx.reverse(segments);
2155
2156                segments[seg_idx].args.and_then(|args| args.args.get(arg_idx)).and_then(|arg| {
2157                    match arg {
2158                        GenericArg::Lifetime(lt) => self.rbv.defs.get(&lt.hir_id.local_id).copied(),
2159                        _ => None,
2160                    }
2161                })
2162            }
2163            ObjectLifetimeDefault::Ambiguous => None,
2164        };
2165        generics
2166            .own_params
2167            .iter()
2168            .filter_map(|param| {
2169                // NB: `Self` type params share the `DefId` with the corresponding trait (alias).
2170                //
2171                // Since trait aliases can't be used as the qself of fully qualified paths, the
2172                // trait object lifetime default for their `Self` type param is never needed.
2173                // Thus, we don't even try to compute it.
2174                //
2175                // We still need to map const params & trait aliases to *some* default to make it
2176                // easy & predictable for the caller how to map the defaults back to generic args.
2177                // As they can't tell if a given inferred arg refers to a type or a const at this
2178                // stage of analysis, they can't skip it and thus we need to provide (dummy)
2179                // defaults for const args. Otherwise, they wouldn't properly align.
2180
2181                match self.tcx.def_kind(param.def_id) {
2182                    DefKind::TyParam | DefKind::Trait => {
2183                        Some(self.tcx.object_lifetime_default(param.def_id))
2184                    }
2185                    DefKind::ConstParam | DefKind::TraitAlias => Some(ObjectLifetimeDefault::Empty),
2186                    DefKind::LifetimeParam => None,
2187                    kind => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected def kind {0:?}",
        kind))bug!("unexpected def kind {kind:?}"),
2188                }
2189            })
2190            .map(set_to_region)
2191            .collect()
2192    }
2193
2194    /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
2195    /// associated type name and starting trait.
2196    /// For example, imagine we have
2197    /// ```ignore (illustrative)
2198    /// trait Foo<'a, 'b> {
2199    ///   type As;
2200    /// }
2201    /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
2202    /// trait Bar: for<'b> Bar<'b> {}
2203    /// ```
2204    /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
2205    /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
2206    fn supertrait_hrtb_vars(
2207        tcx: TyCtxt<'tcx>,
2208        def_id: DefId,
2209        assoc_ident: Ident,
2210        assoc_tag: ty::AssocTag,
2211    ) -> Option<(Vec<ty::BoundVariableKind<'tcx>>, &'tcx ty::AssocItem)> {
2212        let trait_defines_associated_item_named = |trait_def_id: DefId| {
2213            tcx.associated_items(trait_def_id).find_by_ident_and_kind(
2214                tcx,
2215                assoc_ident,
2216                assoc_tag,
2217                trait_def_id,
2218            )
2219        };
2220
2221        use smallvec::{SmallVec, smallvec};
2222        let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind<'tcx>; 8]>); 8]> =
2223            {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((def_id, ::smallvec::SmallVec::new()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(def_id, ::smallvec::SmallVec::new())])))
    }
}smallvec![(def_id, smallvec![])];
2224        let mut visited: FxHashSet<DefId> = FxHashSet::default();
2225        loop {
2226            let Some((def_id, bound_vars)) = stack.pop() else {
2227                break None;
2228            };
2229            // See issue #83753. If someone writes an associated type on a non-trait, just treat it
2230            // as there being no supertrait HRTBs.
2231            match tcx.def_kind(def_id) {
2232                DefKind::Trait | DefKind::TraitAlias | DefKind::Impl { .. } => {}
2233                _ => break None,
2234            }
2235
2236            if let Some(assoc_item) = trait_defines_associated_item_named(def_id) {
2237                break Some((bound_vars.into_iter().collect(), assoc_item));
2238            }
2239            let predicates = tcx.explicit_supertraits_containing_assoc_item((def_id, assoc_ident));
2240            let obligations = predicates
2241                .iter_identity_copied()
2242                .map(Unnormalized::skip_norm_wip)
2243                .filter_map(|(pred, _)| {
2244                    let bound_predicate = pred.kind();
2245                    match bound_predicate.skip_binder() {
2246                        ty::ClauseKind::Trait(data) => {
2247                            // The order here needs to match what we would get from
2248                            // `rustc_middle::ty::predicate::Clause::instantiate_supertrait`
2249                            let pred_bound_vars = bound_predicate.bound_vars();
2250                            let mut all_bound_vars = bound_vars.clone();
2251                            all_bound_vars.extend(pred_bound_vars.iter());
2252                            let super_def_id = data.trait_ref.def_id;
2253                            Some((super_def_id, all_bound_vars))
2254                        }
2255                        _ => None,
2256                    }
2257                });
2258
2259            let obligations = obligations.filter(|o| visited.insert(o.0));
2260            stack.extend(obligations);
2261        }
2262    }
2263
2264    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_fn_like_elision",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2264u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("inputs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("inputs");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("output")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("output");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("in_closure")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("in_closure");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&inputs)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&output)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&in_closure as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.with(Scope::ObjectLifetimeDefault {
                    lifetime: Some(ResolvedArg::StaticLifetime),
                    s: self.scope,
                },
                |this|
                    {
                        for input in inputs { this.visit_ty_unambig(input); }
                        if !in_closure && let Some(output) = output {
                            this.visit_ty_unambig(output);
                        }
                    });
            if in_closure && let Some(output) = output {
                self.visit_ty_unambig(output);
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2265    fn visit_fn_like_elision(
2266        &mut self,
2267        inputs: &'tcx [hir::Ty<'tcx>],
2268        output: Option<&'tcx hir::Ty<'tcx>>,
2269        in_closure: bool,
2270    ) {
2271        self.with(
2272            Scope::ObjectLifetimeDefault {
2273                lifetime: Some(ResolvedArg::StaticLifetime),
2274                s: self.scope,
2275            },
2276            |this| {
2277                for input in inputs {
2278                    this.visit_ty_unambig(input);
2279                }
2280                if !in_closure && let Some(output) = output {
2281                    this.visit_ty_unambig(output);
2282                }
2283            },
2284        );
2285        if in_closure && let Some(output) = output {
2286            self.visit_ty_unambig(output);
2287        }
2288    }
2289
2290    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("resolve_object_lifetime_default",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2290u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut late_depth = 0;
            let mut scope = self.scope;
            let mut opaque_capture_scopes = ::alloc::vec::Vec::new();
            let mut lifetime =
                loop {
                    match *scope {
                        Scope::Binder { s, scope_type, .. } => {
                            match scope_type {
                                BinderScopeType::Normal => late_depth += 1,
                                BinderScopeType::Concatenating => {}
                            }
                            scope = s;
                        }
                        Scope::Root { .. } => break ResolvedArg::StaticLifetime,
                        Scope::Body { .. } | Scope::ObjectLifetimeDefault {
                            lifetime: None, .. } => return,
                        Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => {
                            break l.shifted(late_depth);
                        }
                        Scope::Opaque { captures, def_id, s } => {
                            opaque_capture_scopes.push((def_id, captures));
                            late_depth = 0;
                            scope = s;
                        }
                        Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s,
                            .. } | Scope::LateBoundary { s, .. } => {
                            scope = s;
                        }
                    }
                };
            lifetime =
                self.remap_opaque_captures(&opaque_capture_scopes, lifetime,
                    lifetime_ref.ident);
            self.insert_lifetime(lifetime_ref, lifetime);
        }
    }
}#[instrument(level = "debug", skip(self))]
2291    fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2292        let mut late_depth = 0;
2293        let mut scope = self.scope;
2294        let mut opaque_capture_scopes = vec![];
2295        let mut lifetime = loop {
2296            match *scope {
2297                Scope::Binder { s, scope_type, .. } => {
2298                    match scope_type {
2299                        BinderScopeType::Normal => late_depth += 1,
2300                        BinderScopeType::Concatenating => {}
2301                    }
2302                    scope = s;
2303                }
2304
2305                Scope::Root { .. } => break ResolvedArg::StaticLifetime,
2306
2307                Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2308
2309                Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => {
2310                    break l.shifted(late_depth);
2311                }
2312
2313                Scope::Opaque { captures, def_id, s } => {
2314                    opaque_capture_scopes.push((def_id, captures));
2315                    late_depth = 0;
2316                    scope = s;
2317                }
2318
2319                Scope::Supertrait { s, .. }
2320                | Scope::TraitRefBoundary { s, .. }
2321                | Scope::LateBoundary { s, .. } => {
2322                    scope = s;
2323                }
2324            }
2325        };
2326
2327        lifetime = self.remap_opaque_captures(&opaque_capture_scopes, lifetime, lifetime_ref.ident);
2328
2329        self.insert_lifetime(lifetime_ref, lifetime);
2330    }
2331
2332    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("insert_lifetime",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2332u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime_ref");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2334",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2334u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref.ident.span)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            self.rbv.defs.insert(lifetime_ref.hir_id.local_id, def);
        }
    }
}#[instrument(level = "debug", skip(self))]
2333    fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: ResolvedArg) {
2334        debug!(span = ?lifetime_ref.ident.span);
2335        self.rbv.defs.insert(lifetime_ref.hir_id.local_id, def);
2336    }
2337
2338    // When we have a return type notation type in a where clause, like
2339    // `where <T as Trait>::method(..): Send`, we need to introduce new bound
2340    // vars to the existing where clause's binder, to represent the lifetimes
2341    // elided by the return-type-notation syntax.
2342    //
2343    // For example, given
2344    // ```
2345    // trait Foo {
2346    //     async fn x<'r>();
2347    // }
2348    // ```
2349    // and a bound that looks like:
2350    //    `for<'a, 'b> <T as Trait<'a>>::x(): Other<'b>`
2351    // this is going to expand to something like:
2352    //    `for<'a, 'b, 'r> <T as Trait<'a>>::x::<'r, T>::{opaque#0}: Other<'b>`.
2353    //
2354    // We handle this similarly for associated-type-bound style return-type-notation
2355    // in `visit_path_segment_args`.
2356    fn try_append_return_type_notation_params(
2357        &mut self,
2358        hir_id: HirId,
2359        hir_ty: &'tcx hir::Ty<'tcx>,
2360    ) {
2361        let hir::TyKind::Path(qpath) = hir_ty.kind else {
2362            // We only care about path types here. All other self types
2363            // (including nesting the RTN type in another type) don't do
2364            // anything.
2365            return;
2366        };
2367
2368        let (mut bound_vars, item_def_id, item_segment) = match qpath {
2369            // If we have a fully qualified method, then we don't need to do any special lookup.
2370            hir::QPath::Resolved(_, path)
2371                if let [.., item_segment] = &path.segments[..]
2372                    && item_segment.args.is_some_and(|args| {
2373                        #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
    hir::GenericArgsParentheses::ReturnTypeNotation => true,
    _ => false,
}matches!(
2374                            args.parenthesized,
2375                            hir::GenericArgsParentheses::ReturnTypeNotation
2376                        )
2377                    }) =>
2378            {
2379                match path.res {
2380                    Res::Err => return,
2381                    Res::Def(DefKind::AssocFn, item_def_id) => (::alloc::vec::Vec::new()vec![], item_def_id, item_segment),
2382                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("only expected method resolution for fully qualified RTN"))bug!("only expected method resolution for fully qualified RTN"),
2383                }
2384            }
2385
2386            // If we have a type-dependent path, then we do need to do some lookup.
2387            hir::QPath::TypeRelative(qself, item_segment)
2388                if item_segment.args.is_some_and(|args| {
2389                    #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
    hir::GenericArgsParentheses::ReturnTypeNotation => true,
    _ => false,
}matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2390                }) =>
2391            {
2392                // First, ignore a qself that isn't a type or `Self` param. Those are the
2393                // only ones that support `T::Assoc` anyways in HIR lowering.
2394                let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = qself.kind else {
2395                    return;
2396                };
2397                match path.res {
2398                    Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { trait_: _ } => {
2399                        let mut bounds =
2400                            self.for_each_trait_bound_on_res(path.res).filter_map(|trait_def_id| {
2401                                BoundVarContext::supertrait_hrtb_vars(
2402                                    self.tcx,
2403                                    trait_def_id,
2404                                    item_segment.ident,
2405                                    ty::AssocTag::Fn,
2406                                )
2407                            });
2408
2409                        let Some((bound_vars, assoc_item)) = bounds.next() else {
2410                            // This will error in HIR lowering.
2411                            self.tcx
2412                                .dcx()
2413                                .span_delayed_bug(path.span, "no resolution for RTN path");
2414                            return;
2415                        };
2416
2417                        // Don't bail if we have identical bounds, which may be collected from
2418                        // something like `T: Bound + Bound`, or via elaborating supertraits.
2419                        for (second_vars, second_assoc_item) in bounds {
2420                            if second_vars != bound_vars || second_assoc_item != assoc_item {
2421                                // This will error in HIR lowering.
2422                                self.tcx.dcx().span_delayed_bug(
2423                                    path.span,
2424                                    "ambiguous resolution for RTN path",
2425                                );
2426                                return;
2427                            }
2428                        }
2429
2430                        (bound_vars, assoc_item.def_id, item_segment)
2431                    }
2432                    // If we have a self type alias (in an impl), try to resolve an
2433                    // associated item from one of the supertraits of the impl's trait.
2434                    Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. } => {
2435                        let hir::ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) = self
2436                            .tcx
2437                            .hir_node_by_def_id(impl_def_id.expect_local())
2438                            .expect_item()
2439                            .kind
2440                        else {
2441                            return;
2442                        };
2443                        let Some(trait_def_id) = of_trait.trait_ref.trait_def_id() else {
2444                            return;
2445                        };
2446                        let Some((bound_vars, assoc_item)) = BoundVarContext::supertrait_hrtb_vars(
2447                            self.tcx,
2448                            trait_def_id,
2449                            item_segment.ident,
2450                            ty::AssocTag::Fn,
2451                        ) else {
2452                            return;
2453                        };
2454                        (bound_vars, assoc_item.def_id, item_segment)
2455                    }
2456                    _ => return,
2457                }
2458            }
2459
2460            _ => return,
2461        };
2462
2463        // Append the early-bound vars on the function, and then the late-bound ones.
2464        // We actually turn type parameters into higher-ranked types here, but we
2465        // deny them later in HIR lowering.
2466        bound_vars.extend(
2467            self.tcx
2468                .generics_of(item_def_id)
2469                .own_params
2470                .iter()
2471                .map(|param| generic_param_def_as_bound_arg(param)),
2472        );
2473        bound_vars.extend(
2474            self.tcx.fn_sig(item_def_id).instantiate_identity().skip_norm_wip().bound_vars(),
2475        );
2476
2477        // SUBTLE: Stash the old bound vars onto the *item segment* before appending
2478        // the new bound vars. We do this because we need to know how many bound vars
2479        // are present on the binder explicitly (i.e. not return-type-notation vars)
2480        // to do bound var shifting correctly in HIR lowering.
2481        //
2482        // For example, in `where for<'a> <T as Trait<'a>>::method(..): Other`,
2483        // the `late_bound_vars` of the where clause predicate (i.e. this HIR ty's
2484        // parent) will include `'a` AND all the early- and late-bound vars of the
2485        // method. But when lowering the RTN type, we just want the list of vars
2486        // we used to resolve the trait ref. We explicitly stored those back onto
2487        // the item segment, since there's no other good place to put them.
2488        //
2489        // See where these vars are used in `HirTyLowerer::lower_ty_maybe_return_type_notation`.
2490        // And this is exercised in:
2491        // `tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.rs`.
2492        let existing_bound_vars = self.rbv.late_bound_vars.get_mut(&hir_id.local_id).unwrap();
2493        let existing_bound_vars_saved = existing_bound_vars.clone();
2494        existing_bound_vars.extend(bound_vars);
2495        self.record_late_bound_vars(item_segment.hir_id, existing_bound_vars_saved);
2496    }
2497
2498    /// Walk the generics of the item for a trait bound whose self type
2499    /// corresponds to the expected res, and return the trait def id.
2500    fn for_each_trait_bound_on_res(&self, expected_res: Res) -> impl Iterator<Item = DefId> {
2501        gen move {
2502            let mut scope = self.scope;
2503            loop {
2504                let hir_id = match *scope {
2505                    Scope::Binder { hir_id, .. } => Some(hir_id),
2506                    Scope::Root { opt_parent_item: Some(parent_def_id) } => {
2507                        Some(self.tcx.local_def_id_to_hir_id(parent_def_id))
2508                    }
2509                    Scope::Body { .. }
2510                    | Scope::ObjectLifetimeDefault { .. }
2511                    | Scope::Supertrait { .. }
2512                    | Scope::TraitRefBoundary { .. }
2513                    | Scope::LateBoundary { .. }
2514                    | Scope::Opaque { .. }
2515                    | Scope::Root { opt_parent_item: None } => None,
2516                };
2517
2518                if let Some(hir_id) = hir_id {
2519                    let node = self.tcx.hir_node(hir_id);
2520                    // If this is a `Self` bound in a trait, yield the trait itself.
2521                    // Specifically, we don't need to look at any supertraits since
2522                    // we already do that in `BoundVarContext::supertrait_hrtb_vars`.
2523                    if let Res::SelfTyParam { trait_: _ } = expected_res
2524                        && let hir::Node::Item(item) = node
2525                        && let hir::ItemKind::Trait { .. } = item.kind
2526                    {
2527                        // Yield the trait's def id. Supertraits will be
2528                        // elaborated from that.
2529                        yield item.owner_id.def_id.to_def_id();
2530                    } else if let Some(generics) = node.generics() {
2531                        for pred in generics.predicates {
2532                            let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
2533                                continue;
2534                            };
2535                            let hir::TyKind::Path(hir::QPath::Resolved(None, bounded_path)) =
2536                                pred.bounded_ty.kind
2537                            else {
2538                                continue;
2539                            };
2540                            // Match the expected res.
2541                            if bounded_path.res != expected_res {
2542                                continue;
2543                            }
2544                            for pred in pred.bounds {
2545                                match pred {
2546                                    hir::GenericBound::Trait(poly_trait_ref) => {
2547                                        if let Some(def_id) =
2548                                            poly_trait_ref.trait_ref.trait_def_id()
2549                                        {
2550                                            yield def_id;
2551                                        }
2552                                    }
2553                                    hir::GenericBound::Outlives(_)
2554                                    | hir::GenericBound::Use(_, _) => {}
2555                                }
2556                            }
2557                        }
2558                    }
2559                }
2560
2561                match *scope {
2562                    Scope::Binder { s, .. }
2563                    | Scope::Body { s, .. }
2564                    | Scope::ObjectLifetimeDefault { s, .. }
2565                    | Scope::Supertrait { s, .. }
2566                    | Scope::TraitRefBoundary { s }
2567                    | Scope::LateBoundary { s, .. }
2568                    | Scope::Opaque { s, .. } => {
2569                        scope = s;
2570                    }
2571                    Scope::Root { .. } => break,
2572                }
2573            }
2574        }
2575    }
2576}
2577
2578/// Detects late-bound lifetimes and inserts them into
2579/// `late_bound`.
2580///
2581/// A region declared on a fn is **late-bound** if:
2582/// - it is constrained by an argument type;
2583/// - it does not appear in a where-clause.
2584///
2585/// "Constrained" basically means that it appears in any type but
2586/// not amongst the inputs to a projection. In other words, `<&'a
2587/// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2588fn is_late_bound_map(
2589    tcx: TyCtxt<'_>,
2590    owner_id: hir::OwnerId,
2591) -> Option<&FxIndexSet<hir::ItemLocalId>> {
2592    let sig = tcx.hir_fn_sig_by_hir_id(owner_id.into())?;
2593    let generics = tcx.hir_get_generics(owner_id.def_id)?;
2594
2595    let mut late_bound = FxIndexSet::default();
2596
2597    let mut constrained_by_input = ConstrainedCollector { regions: Default::default(), tcx };
2598    for arg_ty in sig.decl.inputs {
2599        constrained_by_input.visit_ty_unambig(arg_ty);
2600    }
2601
2602    let mut appears_in_output =
2603        AllCollector { has_fully_capturing_opaque: false, regions: Default::default() };
2604    intravisit::walk_fn_ret_ty(&mut appears_in_output, &sig.decl.output);
2605    if appears_in_output.has_fully_capturing_opaque {
2606        appears_in_output.regions.extend(generics.params.iter().map(|param| param.def_id));
2607    }
2608
2609    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2609",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2609u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("constrained_by_input.regions")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("constrained_by_input.regions");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constrained_by_input.regions)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?constrained_by_input.regions);
2610
2611    // Walk the lifetimes that appear in where clauses.
2612    //
2613    // Subtle point: because we disallow nested bindings, we can just
2614    // ignore binders here and scrape up all names we see.
2615    let mut appears_in_where_clause =
2616        AllCollector { has_fully_capturing_opaque: true, regions: Default::default() };
2617    appears_in_where_clause.visit_generics(generics);
2618    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2618",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2618u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("appears_in_where_clause.regions")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("appears_in_where_clause.regions");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&appears_in_where_clause.regions)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?appears_in_where_clause.regions);
2619
2620    // Late bound regions are those that:
2621    // - appear in the inputs
2622    // - do not appear in the where-clauses
2623    // - are not implicitly captured by `impl Trait`
2624    for param in generics.params {
2625        match param.kind {
2626            hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2627
2628            // Neither types nor consts are late-bound.
2629            hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
2630        }
2631
2632        // appears in the where clauses? early-bound.
2633        if appears_in_where_clause.regions.contains(&param.def_id) {
2634            continue;
2635        }
2636
2637        // does not appear in the inputs, but appears in the return type? early-bound.
2638        if !constrained_by_input.regions.contains(&param.def_id)
2639            && appears_in_output.regions.contains(&param.def_id)
2640        {
2641            continue;
2642        }
2643
2644        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2644",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2644u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("lifetime {0:?} with id {1:?} is late-bound",
                                                    param.name.ident(), param.def_id) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.def_id);
2645
2646        let inserted = late_bound.insert(param.hir_id.local_id);
2647        if !inserted {
    {
        ::core::panicking::panic_fmt(format_args!("visited lifetime {0:?} twice",
                param.def_id));
    }
};assert!(inserted, "visited lifetime {:?} twice", param.def_id);
2648    }
2649
2650    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2650",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2650u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("late_bound")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("late_bound");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&late_bound)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?late_bound);
2651    return Some(tcx.arena.alloc(late_bound));
2652
2653    /// Visits a `ty::Ty` collecting information about what generic parameters are constrained.
2654    ///
2655    /// The visitor does not operate on `hir::Ty` so that it can be called on the rhs of a `type Alias<...> = ...;`
2656    /// which may live in a separate crate so there would not be any hir available. Instead we use the `type_of`
2657    /// query to obtain a `ty::Ty` which will be present even in cross crate scenarios. It also naturally
2658    /// handles cycle detection as we go through the query system.
2659    ///
2660    /// This is necessary in the first place for the following case:
2661    /// ```rust,ignore (pseudo-Rust)
2662    /// type Alias<'a, T> = <T as Trait<'a>>::Assoc;
2663    /// fn foo<'a>(_: Alias<'a, ()>) -> Alias<'a, ()> { ... }
2664    /// ```
2665    ///
2666    /// If we conservatively considered `'a` unconstrained then we could break users who had written code before
2667    /// we started correctly handling aliases. If we considered `'a` constrained then it would become late bound
2668    /// causing an error during HIR ty lowering as the `'a` is not constrained by the input type `<() as Trait<'a>>::Assoc`
2669    /// but appears in the output type `<() as Trait<'a>>::Assoc`.
2670    ///
2671    /// We must therefore "look into" the `Alias` to see whether we should consider `'a` constrained or not.
2672    ///
2673    /// See #100508 #85533 #47511 for additional context
2674    struct ConstrainedCollectorPostHirTyLowering {
2675        arg_is_constrained: Box<[bool]>,
2676    }
2677
2678    use ty::Ty;
2679    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ConstrainedCollectorPostHirTyLowering {
2680        fn visit_ty(&mut self, t: Ty<'tcx>) {
2681            match t.kind() {
2682                ty::Param(param_ty) => {
2683                    self.arg_is_constrained[param_ty.index as usize] = true;
2684                }
2685                ty::Alias(
2686                    _,
2687                    ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. },
2688                ) => return,
2689                _ => (),
2690            }
2691            t.super_visit_with(self)
2692        }
2693
2694        fn visit_const(&mut self, _: ty::Const<'tcx>) {}
2695
2696        fn visit_region(&mut self, r: ty::Region<'tcx>) {
2697            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2697",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2697u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("r={0:?}",
                                                    r.kind()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("r={:?}", r.kind());
2698            if let ty::RegionKind::ReEarlyParam(region) = r.kind() {
2699                self.arg_is_constrained[region.index as usize] = true;
2700            }
2701        }
2702    }
2703
2704    struct ConstrainedCollector<'tcx> {
2705        tcx: TyCtxt<'tcx>,
2706        regions: FxHashSet<LocalDefId>,
2707    }
2708
2709    impl<'v> Visitor<'v> for ConstrainedCollector<'_> {
2710        fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
2711            match ty.kind {
2712                hir::TyKind::Path(
2713                    hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
2714                ) => {
2715                    // ignore lifetimes appearing in associated type
2716                    // projections, as they are not *constrained*
2717                    // (defined above)
2718                }
2719
2720                hir::TyKind::Path(hir::QPath::Resolved(
2721                    None,
2722                    hir::Path { res: Res::Def(DefKind::TyAlias, alias_def), segments, span },
2723                )) => {
2724                    // See comments on `ConstrainedCollectorPostHirTyLowering` for why this arm does not
2725                    // just consider args to be unconstrained.
2726                    let generics = self.tcx.generics_of(*alias_def);
2727                    let mut walker = ConstrainedCollectorPostHirTyLowering {
2728                        arg_is_constrained: ::alloc::vec::from_elem(false, generics.own_params.len())vec![false; generics.own_params.len()]
2729                            .into_boxed_slice(),
2730                    };
2731                    walker.visit_ty(
2732                        self.tcx.type_of(*alias_def).instantiate_identity().skip_norm_wip(),
2733                    );
2734
2735                    match segments.last() {
2736                        Some(hir::PathSegment { args: Some(args), .. }) => {
2737                            let tcx = self.tcx;
2738                            for constrained_arg in
2739                                args.args.iter().enumerate().flat_map(|(n, arg)| {
2740                                    match walker.arg_is_constrained.get(n) {
2741                                        Some(true) => Some(arg),
2742                                        Some(false) => None,
2743                                        None => {
2744                                            tcx.dcx().span_delayed_bug(
2745                                                *span,
2746                                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Incorrect generic arg count for alias {0:?}",
                alias_def))
    })format!(
2747                                                    "Incorrect generic arg count for alias {alias_def:?}"
2748                                                ),
2749                                            );
2750                                            None
2751                                        }
2752                                    }
2753                                })
2754                            {
2755                                self.visit_generic_arg(constrained_arg);
2756                            }
2757                        }
2758                        Some(_) => (),
2759                        None => ::rustc_middle::util::bug::bug_fmt(format_args!("Path with no segments or self type"))bug!("Path with no segments or self type"),
2760                    }
2761                }
2762
2763                hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
2764                    // consider only the lifetimes on the final
2765                    // segment; I am not sure it's even currently
2766                    // valid to have them elsewhere, but even if it
2767                    // is, those would be potentially inputs to
2768                    // projections
2769                    if let Some(last_segment) = path.segments.last() {
2770                        self.visit_path_segment(last_segment);
2771                    }
2772                }
2773
2774                _ => {
2775                    intravisit::walk_ty(self, ty);
2776                }
2777            }
2778        }
2779
2780        fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2781            if let hir::LifetimeKind::Param(def_id) = lifetime_ref.kind {
2782                self.regions.insert(def_id);
2783            }
2784        }
2785    }
2786
2787    struct AllCollector {
2788        has_fully_capturing_opaque: bool,
2789        regions: FxHashSet<LocalDefId>,
2790    }
2791
2792    impl<'tcx> Visitor<'tcx> for AllCollector {
2793        fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2794            if let hir::LifetimeKind::Param(def_id) = lifetime_ref.kind {
2795                self.regions.insert(def_id);
2796            }
2797        }
2798
2799        fn visit_opaque_ty(&mut self, opaque: &'tcx hir::OpaqueTy<'tcx>) {
2800            if !self.has_fully_capturing_opaque {
2801                self.has_fully_capturing_opaque = opaque_captures_all_in_scope_lifetimes(opaque);
2802            }
2803            intravisit::walk_opaque_ty(self, opaque);
2804        }
2805    }
2806}
2807
2808fn deny_non_region_late_bound(
2809    tcx: TyCtxt<'_>,
2810    bound_vars: &mut FxIndexMap<LocalDefId, ResolvedArg>,
2811    where_: &str,
2812) {
2813    let mut first = true;
2814
2815    for (var, arg) in bound_vars {
2816        let Node::GenericParam(param) = tcx.hir_node_by_def_id(*var) else {
2817            ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(*var),
    format_args!("expected bound-var def-id to resolve to param"));span_bug!(tcx.def_span(*var), "expected bound-var def-id to resolve to param");
2818        };
2819
2820        let what = match param.kind {
2821            hir::GenericParamKind::Type { .. } => "type",
2822            hir::GenericParamKind::Const { .. } => "const",
2823            hir::GenericParamKind::Lifetime { .. } => continue,
2824        };
2825
2826        let diag = tcx.dcx().struct_span_err(
2827            param.span,
2828            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("late-bound {0} parameter not allowed on {1}",
                what, where_))
    })format!("late-bound {what} parameter not allowed on {where_}"),
2829        );
2830
2831        let guar = diag.emit_unless_delay(!tcx.features().non_lifetime_binders() || !first);
2832
2833        first = false;
2834        *arg = ResolvedArg::Error(guar);
2835    }
2836}
2837
2838/// A path segment index.
2839#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SegIdx { }
#[automatically_derived]
impl ::core::clone::Clone for SegIdx {
    #[inline]
    fn clone(&self) -> SegIdx {
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SegIdx { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for SegIdx {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "SegIdx",
            &&self.0)
    }
}Debug)]
2840struct SegIdx(usize);
2841
2842impl SegIdx {
2843    fn reverse(self, segments: &[hir::PathSegment<'_>]) -> RevSegIdx {
2844        let SegIdx(seg_idx) = self;
2845        RevSegIdx(segments.len() - seg_idx - 1)
2846    }
2847}
2848
2849/// A reversed path segment index.
2850///
2851/// E.g., for qualified path `<() as path::to::TraitRef<…>>::AssocTy<…>` the mapping from reversed
2852/// index to path segment would look like 3 ↦ `path`, 2 ↦ `to`, 1 ↦ `TraitRef<…>`, 0 ↦ `AssocTy<…>`.
2853struct RevSegIdx(usize);
2854
2855impl RevSegIdx {
2856    fn reverse(self, segments: &[hir::PathSegment<'_>]) -> SegIdx {
2857        let RevSegIdx(rev_seg_idx) = self;
2858        SegIdx(segments.len() - rev_seg_idx - 1)
2859    }
2860}