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_span::def_id::{DefId, LocalDefId};
29use rustc_span::{Ident, Span, bug, span_bug, sym};
30use tracing::{debug, debug_span, instrument};
31
32use crate::diagnostics;
33use crate::hir::definitions::PerParentDisambiguatorState;
34
35trait 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)]
36impl ResolvedArg {
37    fn early(param: &GenericParam<'_>) -> ResolvedArg {
38        ResolvedArg::EarlyBound(param.def_id)
39    }
40
41    fn late(idx: u32, param: &GenericParam<'_>) -> ResolvedArg {
42        ResolvedArg::LateBound(ty::INNERMOST, idx, param.def_id)
43    }
44
45    fn id(&self) -> Option<LocalDefId> {
46        match *self {
47            ResolvedArg::StaticLifetime | ResolvedArg::Error(_) => None,
48
49            ResolvedArg::EarlyBound(id)
50            | ResolvedArg::LateBound(_, _, id)
51            | ResolvedArg::Free(_, id) => Some(id),
52        }
53    }
54
55    fn shifted(self, amount: u32) -> ResolvedArg {
56        match self {
57            ResolvedArg::LateBound(debruijn, idx, id) => {
58                ResolvedArg::LateBound(debruijn.shifted_in(amount), idx, id)
59            }
60            _ => self,
61        }
62    }
63}
64
65struct BoundVarContext<'a, 'tcx> {
66    tcx: TyCtxt<'tcx>,
67    rbv: &'a mut ResolveBoundVars<'tcx>,
68    disambiguators: &'a mut LocalDefIdMap<PerParentDisambiguatorState>,
69    scope: ScopeRef<'a, 'tcx>,
70    opaque_capture_errors: RefCell<Option<OpaqueHigherRankedLifetimeCaptureErrors>>,
71}
72
73struct OpaqueHigherRankedLifetimeCaptureErrors {
74    bad_place: &'static str,
75    capture_spans: Vec<Span>,
76    decl_spans: Vec<Span>,
77}
78
79#[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)]
80enum Scope<'a, 'tcx> {
81    /// Declares lifetimes, and each can be early-bound or late-bound.
82    /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
83    /// it should be shifted by the number of `Binder`s in between the
84    /// declaration `Binder` and the location it's referenced from.
85    Binder {
86        /// We use an IndexMap here because we want these lifetimes in order
87        /// for diagnostics.
88        bound_vars: FxIndexMap<LocalDefId, ResolvedArg>,
89
90        scope_type: BinderScopeType,
91
92        /// The late bound vars for a given item are stored by `HirId` to be
93        /// queried later. However, if we enter an elision scope, we have to
94        /// later append the elided bound vars to the list and need to know what
95        /// to append to.
96        hir_id: HirId,
97
98        s: ScopeRef<'a, 'tcx>,
99
100        /// If this binder comes from a where clause, specify how it was created.
101        /// This is used to diagnose inaccessible lifetimes in APIT:
102        /// ```ignore (illustrative)
103        /// fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {}
104        /// ```
105        where_bound_origin: Option<hir::PredicateOrigin>,
106    },
107
108    /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
109    /// if this is a fn body, otherwise the original definitions are used.
110    /// Unspecified lifetimes are inferred, unless an elision scope is nested,
111    /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
112    Body {
113        id: hir::BodyId,
114        s: ScopeRef<'a, 'tcx>,
115    },
116
117    /// Use a specific lifetime (if `Some`) or leave it unset (to be
118    /// inferred in a function body or potentially error outside one),
119    /// for the default choice of lifetime in a trait object type.
120    ObjectLifetimeDefault {
121        lifetime: Option<ResolvedArg>,
122        s: ScopeRef<'a, 'tcx>,
123    },
124
125    /// When we have nested trait refs, we concatenate late bound vars for inner
126    /// trait refs from outer ones. But we also need to include any HRTB
127    /// lifetimes encountered when identifying the trait that an associated type
128    /// is declared on.
129    Supertrait {
130        bound_vars: Vec<ty::BoundVariableKind<'tcx>>,
131        s: ScopeRef<'a, 'tcx>,
132    },
133
134    TraitRefBoundary {
135        s: ScopeRef<'a, 'tcx>,
136    },
137
138    /// Remap lifetimes that appear in opaque types to fresh lifetime parameters. Given:
139    /// `fn foo<'a>() -> impl MyTrait<'a> { ... }`
140    ///
141    /// HIR tells us that `'a` refer to the lifetime bound on `foo`.
142    /// However, typeck and borrowck for opaques work based on using a new generic type.
143    /// `type MyAnonTy<'b> = impl MyTrait<'b>;`
144    ///
145    /// This scope collects the mapping `'a -> 'b`.
146    Opaque {
147        /// The opaque type we are traversing.
148        def_id: LocalDefId,
149        /// Mapping from each captured lifetime `'a` to the duplicate generic parameter `'b`.
150        captures: &'a RefCell<FxIndexMap<ResolvedArg, LocalDefId>>,
151
152        s: ScopeRef<'a, 'tcx>,
153    },
154
155    /// Disallows capturing late-bound vars from parent scopes.
156    ///
157    /// This is necessary for something like `for<T> [(); { /* references T */ }]:`,
158    /// since we don't do something more correct like replacing any captured
159    /// late-bound vars with early-bound params in the const's own generics.
160    LateBoundary {
161        s: ScopeRef<'a, 'tcx>,
162        what: &'static str,
163        deny_late_regions: bool,
164    },
165
166    Root {
167        opt_parent_item: Option<LocalDefId>,
168    },
169}
170
171impl<'a, 'tcx> Scope<'a, 'tcx> {
172    // A helper for debugging scopes without printing parent scopes
173    fn debug_truncated(&self) -> impl fmt::Debug {
174        fmt::from_fn(move |f| match self {
175            Self::Binder { bound_vars, scope_type, hir_id, where_bound_origin, s: _ } => f
176                .debug_struct("Binder")
177                .field("bound_vars", bound_vars)
178                .field("scope_type", scope_type)
179                .field("hir_id", hir_id)
180                .field("where_bound_origin", where_bound_origin)
181                .field("s", &"..")
182                .finish(),
183            Self::Opaque { captures, def_id, s: _ } => f
184                .debug_struct("Opaque")
185                .field("def_id", def_id)
186                .field("captures", &captures.borrow())
187                .field("s", &"..")
188                .finish(),
189            Self::Body { id, s: _ } => {
190                f.debug_struct("Body").field("id", id).field("s", &"..").finish()
191            }
192            Self::ObjectLifetimeDefault { lifetime, s: _ } => f
193                .debug_struct("ObjectLifetimeDefault")
194                .field("lifetime", lifetime)
195                .field("s", &"..")
196                .finish(),
197            Self::Supertrait { bound_vars, s: _ } => f
198                .debug_struct("Supertrait")
199                .field("bound_vars", bound_vars)
200                .field("s", &"..")
201                .finish(),
202            Self::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
203            Self::LateBoundary { s: _, what, deny_late_regions } => f
204                .debug_struct("LateBoundary")
205                .field("what", what)
206                .field("deny_late_regions", deny_late_regions)
207                .finish(),
208            Self::Root { opt_parent_item } => {
209                f.debug_struct("Root").field("opt_parent_item", &opt_parent_item).finish()
210            }
211        })
212    }
213}
214
215#[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)]
216enum BinderScopeType {
217    /// Any non-concatenating binder scopes.
218    Normal,
219    /// Within a syntactic trait ref, there may be multiple poly trait refs that
220    /// are nested (under the `associated_type_bounds` feature). The binders of
221    /// the inner poly trait refs are extended from the outer poly trait refs
222    /// and don't increase the late bound depth. If you had
223    /// `T: for<'a>  Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
224    /// would be `Concatenating`. This also used in trait refs in where clauses
225    /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
226    /// out any lifetimes because they aren't needed to show the two scopes).
227    /// The inner `for<>` has a scope of `Concatenating`.
228    Concatenating,
229}
230
231type ScopeRef<'a, 'tcx> = &'a Scope<'a, 'tcx>;
232
233/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]
234pub(crate) fn provide(providers: &mut Providers) {
235    *providers = Providers {
236        resolve_bound_vars,
237
238        named_variable_map: |tcx, id| &tcx.resolve_bound_vars(id).defs,
239        is_late_bound_map,
240        object_lifetime_default,
241        late_bound_vars_map: |tcx, id| &tcx.resolve_bound_vars(id).late_bound_vars,
242        opaque_captured_lifetimes: |tcx, id| {
243            &tcx.resolve_bound_vars(tcx.local_def_id_to_hir_id(id).owner)
244                .opaque_captured_lifetimes
245                .get(&id)
246                .map_or(&[][..], |x| &x[..])
247        },
248
249        ..*providers
250    };
251}
252
253/// Computes the `ResolveBoundVars` map that contains data for an entire `Item`.
254/// You should not read the result of this query directly, but rather use
255/// `named_variable_map`, `late_bound_vars_map`, etc.
256{}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(256u32),
                                    ::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:285",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(285u32),
                                    ::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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.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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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.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))]
257fn resolve_bound_vars(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveBoundVars<'_> {
258    let mut rbv = ResolveBoundVars::default();
259    let mut visitor = BoundVarContext {
260        tcx,
261        rbv: &mut rbv,
262        scope: &Scope::Root { opt_parent_item: None },
263        disambiguators: &mut Default::default(),
264        opaque_capture_errors: RefCell::new(None),
265    };
266    match tcx.hir_owner_node(local_def_id) {
267        hir::OwnerNode::Item(item) => visitor.visit_item(item),
268        hir::OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
269        hir::OwnerNode::TraitItem(item) => {
270            let scope =
271                Scope::Root { opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)) };
272            visitor.scope = &scope;
273            visitor.visit_trait_item(item)
274        }
275        hir::OwnerNode::ImplItem(item) => {
276            let scope =
277                Scope::Root { opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)) };
278            visitor.scope = &scope;
279            visitor.visit_impl_item(item)
280        }
281        hir::OwnerNode::Crate(_) => {}
282        hir::OwnerNode::Synthetic => unreachable!(),
283    }
284
285    debug!(?rbv.defs);
286    debug!(?rbv.late_bound_vars);
287    debug!(?rbv.opaque_captured_lifetimes);
288    rbv
289}
290
291fn late_arg_as_bound_arg<'tcx>(param: &GenericParam<'tcx>) -> ty::BoundVariableKind<'tcx> {
292    let def_id = param.def_id.to_def_id();
293    match param.kind {
294        GenericParamKind::Lifetime { .. } => {
295            ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id))
296        }
297        GenericParamKind::Type { .. } => ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)),
298        GenericParamKind::Const { .. } => ty::BoundVariableKind::Const,
299    }
300}
301
302/// Turn a [`ty::GenericParamDef`] into a bound arg. Generally, this should only
303/// be used when turning early-bound vars into late-bound vars when lowering
304/// return type notation.
305fn generic_param_def_as_bound_arg<'tcx>(
306    param: &ty::GenericParamDef,
307) -> ty::BoundVariableKind<'tcx> {
308    match param.kind {
309        ty::GenericParamDefKind::Lifetime => {
310            ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(param.def_id))
311        }
312        ty::GenericParamDefKind::Type { .. } => {
313            ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(param.def_id))
314        }
315        ty::GenericParamDefKind::Const { .. } => ty::BoundVariableKind::Const,
316    }
317}
318
319/// Whether this opaque always captures lifetimes in scope.
320/// Right now, this is all RPITIT and TAITs, and when the opaque
321/// is coming from a span corresponding to edition 2024.
322fn opaque_captures_all_in_scope_lifetimes<'tcx>(opaque: &'tcx hir::OpaqueTy<'tcx>) -> bool {
323    match opaque.origin {
324        // if the opaque has the `use<...>` syntax, the user is telling us that they only want
325        // to account for those lifetimes, so do not try to be clever.
326        _ if opaque.bounds.iter().any(|bound| #[allow(non_exhaustive_omitted_patterns)] match bound {
    hir::GenericBound::Use(..) => true,
    _ => false,
}matches!(bound, hir::GenericBound::Use(..))) => false,
327        hir::OpaqueTyOrigin::AsyncFn { .. } | hir::OpaqueTyOrigin::TyAlias { .. } => true,
328        _ if opaque.span.at_least_rust_2024() => true,
329        hir::OpaqueTyOrigin::FnReturn { in_trait_or_impl, .. } => in_trait_or_impl.is_some(),
330    }
331}
332
333impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
334    /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
335    fn poly_trait_ref_binder_info(
336        &mut self,
337    ) -> (Vec<ty::BoundVariableKind<'tcx>>, BinderScopeType) {
338        let mut scope = self.scope;
339        let mut supertrait_bound_vars = ::alloc::vec::Vec::new()vec![];
340        loop {
341            match scope {
342                Scope::Body { .. } | Scope::Root { .. } => {
343                    break (::alloc::vec::Vec::new()vec![], BinderScopeType::Normal);
344                }
345
346                Scope::Opaque { s, .. }
347                | Scope::ObjectLifetimeDefault { s, .. }
348                | Scope::LateBoundary { s, .. } => {
349                    scope = s;
350                }
351
352                Scope::Supertrait { s, bound_vars } => {
353                    supertrait_bound_vars = bound_vars.clone();
354                    scope = s;
355                }
356
357                Scope::TraitRefBoundary { .. } => {
358                    // We should only see super trait lifetimes if there is a `Binder` above
359                    // though this may happen when we call `poly_trait_ref_binder_info` with
360                    // an (erroneous, #113423) associated return type bound in an impl header.
361                    if !supertrait_bound_vars.is_empty() {
362                        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!(
363                            "found supertrait lifetimes without a binder to append \
364                                them to: {supertrait_bound_vars:?}"
365                        ));
366                    }
367                    break (::alloc::vec::Vec::new()vec![], BinderScopeType::Normal);
368                }
369
370                Scope::Binder { hir_id, .. } => {
371                    // Nested poly trait refs have the binders concatenated
372                    let mut full_binders: Vec<ty::BoundVariableKind<'tcx>> =
373                        self.rbv.late_bound_vars.get_mut_or_insert_default(hir_id.local_id).clone();
374                    full_binders.extend(supertrait_bound_vars);
375                    break (full_binders, BinderScopeType::Concatenating);
376                }
377            }
378        }
379    }
380
381    fn visit_poly_trait_ref_inner(
382        &mut self,
383        trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
384        non_lifetime_binder_allowed: NonLifetimeBinderAllowed,
385    ) {
386        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:386",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(386u32),
                        ::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);
387
388        let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
389
390        let initial_bound_vars = binders.len() as u32;
391        let mut bound_vars: FxIndexMap<LocalDefId, ResolvedArg> = FxIndexMap::default();
392        let binders_iter =
393            trait_ref.bound_generic_params.iter().enumerate().map(|(late_bound_idx, param)| {
394                let arg = ResolvedArg::late(initial_bound_vars + late_bound_idx as u32, param);
395                bound_vars.insert(param.def_id, arg);
396                late_arg_as_bound_arg(param)
397            });
398        binders.extend(binders_iter);
399
400        if let NonLifetimeBinderAllowed::Deny(where_) = non_lifetime_binder_allowed {
401            deny_non_region_late_bound(self.tcx, &mut bound_vars, where_);
402        }
403
404        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:404",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(404u32),
                        ::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);
405        self.record_late_bound_vars(trait_ref.trait_ref.hir_ref_id, binders);
406
407        // Always introduce a scope here, even if this is in a where clause and
408        // we introduced the binders around the bounded Ty. In that case, we
409        // just reuse the concatenation functionality also present in nested trait
410        // refs.
411        let scope = Scope::Binder {
412            hir_id: trait_ref.trait_ref.hir_ref_id,
413            bound_vars,
414            s: self.scope,
415            scope_type,
416            where_bound_origin: None,
417        };
418        self.with(scope, |this| {
419            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);
420            this.visit_trait_ref(&trait_ref.trait_ref);
421        });
422    }
423}
424
425enum NonLifetimeBinderAllowed {
426    Deny(&'static str),
427    Allow,
428}
429
430impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {
431    type NestedFilter = nested_filter::OnlyBodies;
432
433    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
434        self.tcx
435    }
436
437    fn visit_nested_body(&mut self, body: hir::BodyId) {
438        let body = self.tcx.hir_body(body);
439        self.with(Scope::Body { id: body.id(), s: self.scope }, |this| {
440            this.visit_body(body);
441        });
442    }
443
444    fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
445        if let hir::ExprKind::Closure(hir::Closure {
446            binder, bound_generic_params, fn_decl, ..
447        }) = e.kind
448        {
449            if let &hir::ClosureBinder::For { span: for_sp, .. } = binder {
450                fn span_of_infer(ty: &hir::Ty<'_>) -> Option<Span> {
451                    /// Look for `_` anywhere in the signature of a `for<> ||` closure.
452                    /// This is currently disallowed.
453                    struct FindInferInClosureWithBinder;
454                    impl<'v> Visitor<'v> for FindInferInClosureWithBinder {
455                        type Result = ControlFlow<Span>;
456
457                        fn visit_infer(
458                            &mut self,
459                            _inf_id: HirId,
460                            inf_span: Span,
461                            _kind: InferKind<'v>,
462                        ) -> Self::Result {
463                            ControlFlow::Break(inf_span)
464                        }
465                    }
466                    FindInferInClosureWithBinder.visit_ty_unambig(ty).break_value()
467                }
468
469                let infer_in_rt_sp = match fn_decl.output {
470                    hir::FnRetTy::DefaultReturn(sp) => Some(sp),
471                    hir::FnRetTy::Return(ty) => span_of_infer(ty),
472                };
473
474                let infer_spans = fn_decl
475                    .inputs
476                    .into_iter()
477                    .filter_map(span_of_infer)
478                    .chain(infer_in_rt_sp)
479                    .collect::<Vec<_>>();
480
481                if !infer_spans.is_empty() {
482                    self.tcx
483                        .dcx()
484                        .emit_err(diagnostics::ClosureImplicitHrtb { spans: infer_spans, for_sp });
485                }
486            }
487
488            let (mut bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) =
489                bound_generic_params
490                    .iter()
491                    .enumerate()
492                    .map(|(late_bound_idx, param)| {
493                        (
494                            (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
495                            late_arg_as_bound_arg(param),
496                        )
497                    })
498                    .unzip();
499
500            deny_non_region_late_bound(self.tcx, &mut bound_vars, "closures");
501
502            self.record_late_bound_vars(e.hir_id, binders);
503            let scope = Scope::Binder {
504                hir_id: e.hir_id,
505                bound_vars,
506                s: self.scope,
507                scope_type: BinderScopeType::Normal,
508                where_bound_origin: None,
509            };
510
511            self.with(scope, |this| {
512                // a closure has no bounds, so everything
513                // contained within is scoped within its binder.
514                intravisit::walk_expr(this, e)
515            });
516        } else {
517            intravisit::walk_expr(self, e)
518        }
519    }
520
521    /// Resolve the lifetimes inside the opaque type, and save them into
522    /// `opaque_captured_lifetimes`.
523    ///
524    /// This method has special handling for opaques that capture all lifetimes,
525    /// like async desugaring.
526    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(526u32),
                                    ::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 { .. } => {
                            bug_impl(None, format_args!("{0:?}", scope),
                                Location::caller())
                        }
                        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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:616",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(616u32),
                                    ::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))]
527    fn visit_opaque_ty(&mut self, opaque: &'tcx rustc_hir::OpaqueTy<'tcx>) {
528        let captures = RefCell::new(FxIndexMap::default());
529
530        let capture_all_in_scope_lifetimes = opaque_captures_all_in_scope_lifetimes(opaque);
531        if capture_all_in_scope_lifetimes {
532            let tcx = self.tcx;
533            let lifetime_ident = |def_id: LocalDefId| {
534                let name = tcx.item_name(def_id.to_def_id());
535                let span = tcx.def_span(def_id);
536                Ident::new(name, span)
537            };
538
539            // We list scopes outwards, this causes us to see lifetime parameters in reverse
540            // declaration order. In order to make it consistent with what `generics_of` might
541            // give, we will reverse the IndexMap after early captures.
542            let mut late_depth = 0;
543            let mut scope = self.scope;
544            let mut opaque_capture_scopes = vec![(opaque.def_id, &captures)];
545            loop {
546                match *scope {
547                    Scope::Binder { ref bound_vars, scope_type, s, .. } => {
548                        for (&original_lifetime, &def) in bound_vars.iter().rev() {
549                            if let DefKind::LifetimeParam = self.tcx.def_kind(original_lifetime) {
550                                let def = def.shifted(late_depth);
551                                let ident = lifetime_ident(original_lifetime);
552                                self.remap_opaque_captures(&opaque_capture_scopes, def, ident);
553                            }
554                        }
555                        match scope_type {
556                            BinderScopeType::Normal => late_depth += 1,
557                            BinderScopeType::Concatenating => {}
558                        }
559                        scope = s;
560                    }
561
562                    Scope::Root { mut opt_parent_item } => {
563                        while let Some(parent_item) = opt_parent_item {
564                            let parent_generics = self.tcx.generics_of(parent_item);
565                            for param in parent_generics.own_params.iter().rev() {
566                                if let ty::GenericParamDefKind::Lifetime = param.kind {
567                                    let def = ResolvedArg::EarlyBound(param.def_id.expect_local());
568                                    let ident = lifetime_ident(param.def_id.expect_local());
569                                    self.remap_opaque_captures(&opaque_capture_scopes, def, ident);
570                                }
571                            }
572                            opt_parent_item = parent_generics.parent.and_then(DefId::as_local);
573                        }
574                        break;
575                    }
576
577                    Scope::Opaque { captures, def_id, s } => {
578                        opaque_capture_scopes.push((def_id, captures));
579                        late_depth = 0;
580                        scope = s;
581                    }
582
583                    Scope::Body { .. } => {
584                        bug!("{:?}", scope)
585                    }
586
587                    Scope::ObjectLifetimeDefault { s, .. }
588                    | Scope::Supertrait { s, .. }
589                    | Scope::TraitRefBoundary { s, .. }
590                    | Scope::LateBoundary { s, .. } => {
591                        scope = s;
592                    }
593                }
594            }
595            captures.borrow_mut().reverse();
596        }
597
598        let scope = Scope::Opaque { captures: &captures, def_id: opaque.def_id, s: self.scope };
599        self.with(scope, |this| {
600            let scope = Scope::TraitRefBoundary { s: this.scope };
601            this.with(scope, |this| {
602                let scope = Scope::LateBoundary {
603                    s: this.scope,
604                    what: "nested `impl Trait`",
605                    // We can capture late-bound regions; we just don't duplicate
606                    // lifetime or const params, so we can't allow those.
607                    deny_late_regions: false,
608                };
609                this.with(scope, |this| intravisit::walk_opaque_ty(this, opaque))
610            })
611        });
612
613        self.emit_opaque_capture_errors();
614
615        let captures = captures.into_inner().into_iter().collect();
616        debug!(?captures);
617        self.rbv.opaque_captured_lifetimes.insert(opaque.def_id, captures);
618    }
619
620    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(620u32),
                                    ::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))]
621    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
622        if let hir::ItemKind::Impl(impl_) = item.kind
623            && let Some(of_trait) = impl_.of_trait
624        {
625            self.record_late_bound_vars(of_trait.trait_ref.hir_ref_id, Vec::default());
626        }
627        match item.kind {
628            hir::ItemKind::Fn { generics, .. } => {
629                self.visit_early_late(item.hir_id(), generics, |this| {
630                    intravisit::walk_item(this, item);
631                });
632            }
633
634            hir::ItemKind::ExternCrate(..)
635            | hir::ItemKind::Use(..)
636            | hir::ItemKind::Macro(..)
637            | hir::ItemKind::Mod(..)
638            | hir::ItemKind::ForeignMod { .. }
639            | hir::ItemKind::Static(..)
640            | hir::ItemKind::GlobalAsm { .. } => {
641                // These sorts of items have no lifetime parameters at all.
642                intravisit::walk_item(self, item);
643            }
644            hir::ItemKind::TyAlias(_, generics, _)
645            | hir::ItemKind::Const(_, generics, _, _)
646            | hir::ItemKind::Enum(_, generics, _)
647            | hir::ItemKind::Struct(_, generics, _)
648            | hir::ItemKind::Union(_, generics, _)
649            | hir::ItemKind::Trait { generics, .. }
650            | hir::ItemKind::TraitAlias(_, _, generics, ..)
651            | hir::ItemKind::Impl(hir::Impl { generics, .. })
652            | hir::ItemKind::TestBinderConstraints { generics, .. } => {
653                // These kinds of items have only early-bound lifetime parameters.
654                self.visit_early(item.hir_id(), generics, |this| intravisit::walk_item(this, item));
655            }
656        }
657    }
658
659    fn visit_precise_capturing_arg(
660        &mut self,
661        arg: &'tcx hir::PreciseCapturingArg<'tcx>,
662    ) -> Self::Result {
663        match *arg {
664            hir::PreciseCapturingArg::Lifetime(lt) => match lt.kind {
665                LifetimeKind::Param(def_id) => {
666                    self.resolve_lifetime_ref(def_id, lt);
667                }
668                LifetimeKind::Error(..) => {}
669                LifetimeKind::ImplicitObjectLifetimeDefault
670                | LifetimeKind::Infer
671                | LifetimeKind::Static => {
672                    self.tcx.dcx().emit_err(diagnostics::BadPreciseCapture {
673                        span: lt.ident.span,
674                        kind: "lifetime",
675                        found: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", lt.ident.name))
    })format!("`{}`", lt.ident.name),
676                    });
677                }
678            },
679            hir::PreciseCapturingArg::Param(param) => match param.res {
680                Res::Def(DefKind::TyParam | DefKind::ConstParam, def_id)
681                | Res::SelfTyParam { trait_: def_id } => {
682                    self.resolve_type_ref(def_id.expect_local(), param.hir_id);
683                }
684                Res::SelfTyAlias { alias_to, .. } => {
685                    self.tcx.dcx().emit_err(diagnostics::PreciseCaptureSelfAlias {
686                        span: param.ident.span,
687                        self_span: self.tcx.def_span(alias_to),
688                        what: self.tcx.def_descr(alias_to),
689                    });
690                }
691                res => {
692                    self.tcx.dcx().span_delayed_bug(
693                        param.ident.span,
694                        ::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:?}"),
695                    );
696                }
697            },
698        }
699    }
700
701    fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
702        match item.kind {
703            hir::ForeignItemKind::Fn(_, _, generics) => {
704                self.visit_early_late(item.hir_id(), generics, |this| {
705                    intravisit::walk_foreign_item(this, item);
706                })
707            }
708            hir::ForeignItemKind::Static(..) => {
709                intravisit::walk_foreign_item(self, item);
710            }
711            hir::ForeignItemKind::Type => {
712                intravisit::walk_foreign_item(self, item);
713            }
714        }
715    }
716
717    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(717u32),
                                    ::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:780",
                                            "rustc_hir_analysis::collect::resolve_bound_vars",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                            ::tracing_core::__macro_support::Option::Some(780u32),
                                            ::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))]
718    fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
719        match ty.kind {
720            hir::TyKind::FnPtr(c) => {
721                let (mut bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = c
722                    .generic_params
723                    .iter()
724                    .enumerate()
725                    .map(|(late_bound_idx, param)| {
726                        (
727                            (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
728                            late_arg_as_bound_arg(param),
729                        )
730                    })
731                    .unzip();
732
733                deny_non_region_late_bound(self.tcx, &mut bound_vars, "function pointer types");
734
735                self.record_late_bound_vars(ty.hir_id, binders);
736                let scope = Scope::Binder {
737                    hir_id: ty.hir_id,
738                    bound_vars,
739                    s: self.scope,
740                    scope_type: BinderScopeType::Normal,
741                    where_bound_origin: None,
742                };
743                self.with(scope, |this| {
744                    // a FnPtr has no bounds, so everything within is scoped within its binder
745                    intravisit::walk_ty(this, ty);
746                });
747            }
748            hir::TyKind::UnsafeBinder(binder) => {
749                let (mut bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) =
750                    binder
751                        .generic_params
752                        .iter()
753                        .enumerate()
754                        .map(|(late_bound_idx, param)| {
755                            (
756                                (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
757                                late_arg_as_bound_arg(param),
758                            )
759                        })
760                        .unzip();
761
762                deny_non_region_late_bound(self.tcx, &mut bound_vars, "function pointer types");
763
764                self.record_late_bound_vars(ty.hir_id, binders);
765                let scope = Scope::Binder {
766                    hir_id: ty.hir_id,
767                    bound_vars,
768                    s: self.scope,
769                    scope_type: BinderScopeType::Normal,
770                    where_bound_origin: None,
771                };
772                self.with(scope, |this| {
773                    // everything within is scoped within its binder
774                    intravisit::walk_ty(this, ty);
775                });
776            }
777            hir::TyKind::TraitObject(bounds, lifetime) => {
778                let lifetime = lifetime.pointer();
779
780                debug!(?bounds, ?lifetime, "TraitObject");
781                let scope = Scope::TraitRefBoundary { s: self.scope };
782                self.with(scope, |this| {
783                    for bound in bounds {
784                        this.visit_poly_trait_ref_inner(
785                            bound,
786                            NonLifetimeBinderAllowed::Deny("trait object types"),
787                        );
788                    }
789                });
790                match lifetime.kind {
791                    LifetimeKind::ImplicitObjectLifetimeDefault => {
792                        // If the user doesn't write *anything*, we apply the
793                        // trait object lifetime defaulting rules.
794                        // E.g., `Box<dyn Debug>` becomes `Box<dyn Debug + 'static>`.
795                        self.resolve_object_lifetime_default(&*lifetime);
796                    }
797                    LifetimeKind::Infer => {
798                        // If the user writes `'_`, we use the *ordinary* elision
799                        // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
800                        // resolved the same as the `'_` in `&'_ Foo`.
801                        //
802                        // cc #48468
803                    }
804                    LifetimeKind::Param(..) | LifetimeKind::Static => {
805                        // If the user wrote an explicit name, use that.
806                        self.visit_lifetime(&*lifetime);
807                    }
808                    LifetimeKind::Error(..) => {}
809                }
810            }
811            hir::TyKind::Ref(lifetime_ref, ref mt) => {
812                self.visit_lifetime(lifetime_ref);
813                let scope = Scope::ObjectLifetimeDefault {
814                    lifetime: self.rbv.defs.get(&lifetime_ref.hir_id.local_id).copied(),
815                    s: self.scope,
816                };
817                self.with(scope, |this| this.visit_ty_unambig(mt.ty));
818            }
819            hir::TyKind::TraitAscription(bounds) => {
820                let scope = Scope::TraitRefBoundary { s: self.scope };
821                self.with(scope, |this| {
822                    let scope = Scope::LateBoundary {
823                        s: this.scope,
824                        what: "`impl Trait` in binding",
825                        deny_late_regions: true,
826                    };
827                    this.with(scope, |this| {
828                        for bound in bounds {
829                            this.visit_param_bound(bound);
830                        }
831                    })
832                });
833            }
834            _ => intravisit::walk_ty(self, ty),
835        }
836    }
837
838    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(838u32),
                                    ::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))]
839    fn visit_pattern_type_pattern(&mut self, p: &'tcx hir::TyPat<'tcx>) {
840        intravisit::walk_ty_pat(self, p)
841    }
842
843    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(843u32),
                                    ::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))]
844    fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
845        use self::hir::TraitItemKind::*;
846        match trait_item.kind {
847            Fn(_, _) => {
848                self.visit_early_late(trait_item.hir_id(), trait_item.generics, |this| {
849                    intravisit::walk_trait_item(this, trait_item)
850                });
851            }
852            Type(bounds, ty) => {
853                self.visit_early(trait_item.hir_id(), trait_item.generics, |this| {
854                    this.visit_generics(trait_item.generics);
855                    for bound in bounds {
856                        this.visit_param_bound(bound);
857                    }
858                    if let Some(ty) = ty {
859                        this.visit_ty_unambig(ty);
860                    }
861                })
862            }
863            Const(_, _) => self.visit_early(trait_item.hir_id(), trait_item.generics, |this| {
864                intravisit::walk_trait_item(this, trait_item)
865            }),
866        }
867    }
868
869    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(869u32),
                                    ::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))]
870    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
871        use self::hir::ImplItemKind::*;
872        match impl_item.kind {
873            Fn(..) => self.visit_early_late(impl_item.hir_id(), impl_item.generics, |this| {
874                intravisit::walk_impl_item(this, impl_item)
875            }),
876            Type(ty) => self.visit_early(impl_item.hir_id(), impl_item.generics, |this| {
877                this.visit_generics(impl_item.generics);
878                this.visit_ty_unambig(ty);
879            }),
880            Const(_, _) => self.visit_early(impl_item.hir_id(), impl_item.generics, |this| {
881                intravisit::walk_impl_item(this, impl_item)
882            }),
883        }
884    }
885
886    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(886u32),
                                    ::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))]
887    fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
888        match lifetime_ref.kind {
889            hir::LifetimeKind::Static => {
890                self.insert_lifetime(lifetime_ref, ResolvedArg::StaticLifetime)
891            }
892            hir::LifetimeKind::Param(param_def_id) => {
893                self.resolve_lifetime_ref(param_def_id, lifetime_ref)
894            }
895            // Keep track of lifetimes about which errors have already been reported
896            hir::LifetimeKind::Error(guar) => {
897                self.insert_lifetime(lifetime_ref, ResolvedArg::Error(guar))
898            }
899            // Those will be resolved by typechecking.
900            hir::LifetimeKind::ImplicitObjectLifetimeDefault | hir::LifetimeKind::Infer => {}
901        }
902    }
903
904    fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: HirId, _: Span) {
905        match qpath {
906            hir::QPath::Resolved(maybe_qself, path) => {
907                // Visit the path before the self type since computing the trait object lifetime
908                // default for the latter requires all lifetime arguments of the trait ref to be
909                // already resolved.
910                self.visit_path(path, id);
911                if let Some(qself) = maybe_qself {
912                    let container =
913                        self.eligible_container(path, RevSegIdx(1).reverse(path.segments));
914
915                    let object_lifetime_defaults =
916                        container.map_or(Vec::new(), |(def_id, segs)| {
917                            let generics = self.tcx.generics_of(def_id);
918                            self.compute_object_lifetime_defaults(generics, segs)
919                        });
920
921                    if let Some(&lt) = object_lifetime_defaults.first() {
922                        let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
923                        self.with(scope, |this| this.visit_ty_unambig(qself));
924                    } else {
925                        self.visit_ty_unambig(qself);
926                    }
927                }
928            }
929            hir::QPath::TypeRelative(qself, segment) => {
930                // Computing the trait object lifetime defaults that are induced by type-relative
931                // paths would require full type-dependent resolution as performed by HIR ty
932                // lowering whose results we don't have access to here (esp. in ItemCtxts which
933                // don't "persist" any resolutions during lowering).
934                // For maximum forward compatibility, in ItemCtxts we make HIR ty lowering reject
935                // implicit trait object lifetime bounds inside such paths on grounds of
936                // the default being *indeterminate*.
937                // FIXME: Figure out if there's a feasible way to obtain the map of type-dependent
938                //        definitions here / interleave RBV and HIR ty lowering.
939                let scope = Scope::ObjectLifetimeDefault { lifetime: None, s: self.scope };
940                self.with(scope, |this| {
941                    this.visit_ty_unambig(qself);
942                    this.visit_path_segment(segment)
943                });
944            }
945        }
946    }
947
948    fn visit_path(&mut self, path: &hir::Path<'tcx>, hir_id: HirId) {
949        for (index, segment) in path.segments.iter().enumerate() {
950            if let Some(args) = segment.args {
951                self.visit_path_segment_args(args, SegIdx(index), path);
952            }
953        }
954        if let Res::Def(DefKind::TyParam | DefKind::ConstParam, param_def_id) = path.res {
955            self.resolve_type_ref(param_def_id.expect_local(), hir_id);
956        }
957    }
958
959    fn visit_fn(
960        &mut self,
961        fk: intravisit::FnKind<'tcx>,
962        fd: &'tcx hir::FnDecl<'tcx>,
963        body_id: hir::BodyId,
964        _: Span,
965        def_id: LocalDefId,
966    ) {
967        let output = match fd.output {
968            hir::FnRetTy::DefaultReturn(_) => None,
969            hir::FnRetTy::Return(ty) => Some(ty),
970        };
971        if let Some(ty) = output
972            && let hir::TyKind::InferDelegation(hir::InferDelegation::Sig(sig_id, _)) = ty.kind
973        {
974            let bound_vars: Vec<_> =
975                self.tcx.fn_sig(sig_id).skip_binder().bound_vars().iter().collect();
976            let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
977            self.rbv.late_bound_vars.insert(hir_id.local_id, bound_vars);
978        }
979        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));
980        intravisit::walk_fn_kind(self, fk);
981        self.visit_nested_body(body_id)
982    }
983
984    fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
985        let scope = Scope::TraitRefBoundary { s: self.scope };
986        self.with(scope, |this| {
987            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);
988            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);
989        })
990    }
991
992    fn visit_where_predicate(&mut self, predicate: &'tcx hir::WherePredicate<'tcx>) {
993        let hir_id = predicate.hir_id;
994        match predicate.kind {
995            &hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
996                bounded_ty,
997                bounds,
998                bound_generic_params,
999                origin,
1000                ..
1001            }) => {
1002                let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) =
1003                    bound_generic_params
1004                        .iter()
1005                        .enumerate()
1006                        .map(|(late_bound_idx, param)| {
1007                            (
1008                                (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
1009                                late_arg_as_bound_arg(param),
1010                            )
1011                        })
1012                        .unzip();
1013
1014                self.record_late_bound_vars(hir_id, binders);
1015
1016                // If this is an RTN type in the self type, then append those to the binder.
1017                self.try_append_return_type_notation_params(hir_id, bounded_ty);
1018
1019                // Even if there are no lifetimes defined here, we still wrap it in a binder
1020                // scope. If there happens to be a nested poly trait ref (an error), that
1021                // will be `Concatenating` anyways, so we don't have to worry about the depth
1022                // being wrong.
1023                let scope = Scope::Binder {
1024                    hir_id,
1025                    bound_vars,
1026                    s: self.scope,
1027                    scope_type: BinderScopeType::Normal,
1028                    where_bound_origin: Some(origin),
1029                };
1030                self.with(scope, |this| {
1031                    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);
1032                    this.visit_ty_unambig(bounded_ty);
1033                    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);
1034                })
1035            }
1036            &hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1037                lifetime,
1038                bounds,
1039                ..
1040            }) => {
1041                self.visit_lifetime(lifetime);
1042                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);
1043            }
1044        }
1045    }
1046
1047    fn visit_poly_trait_ref(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) {
1048        self.visit_poly_trait_ref_inner(trait_ref, NonLifetimeBinderAllowed::Allow);
1049    }
1050
1051    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
1052        self.with(
1053            Scope::LateBoundary { s: self.scope, what: "constant", deny_late_regions: true },
1054            |this| {
1055                intravisit::walk_anon_const(this, c);
1056            },
1057        );
1058    }
1059
1060    fn visit_generic_param(&mut self, p: &'tcx GenericParam<'tcx>) {
1061        match p.kind {
1062            GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1063                self.resolve_type_ref(p.def_id, p.hir_id);
1064            }
1065            GenericParamKind::Lifetime { .. } => {
1066                // No need to resolve lifetime params, we don't use them for things
1067                // like implicit `?Sized` or const-param-has-ty predicates.
1068            }
1069        }
1070
1071        match p.kind {
1072            GenericParamKind::Lifetime { .. } => {}
1073            GenericParamKind::Type { default, .. } => {
1074                if let Some(ty) = default {
1075                    self.visit_ty_unambig(ty);
1076                }
1077            }
1078            GenericParamKind::Const { ty, default, .. } => {
1079                self.visit_ty_unambig(ty);
1080                if let Some(default) = default {
1081                    self.visit_const_arg_unambig(default);
1082                }
1083            }
1084        }
1085    }
1086
1087    fn visit_test_binder_forall(
1088        &mut self,
1089        forall: &'tcx hir::TestBinderForall<'tcx>,
1090    ) -> Self::Result {
1091        let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = forall
1092            .generics
1093            .params
1094            .iter()
1095            .enumerate()
1096            .map(|(late_bound_idx, param)| {
1097                (
1098                    (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
1099                    late_arg_as_bound_arg(param),
1100                )
1101            })
1102            .unzip();
1103        self.record_late_bound_vars(forall.hir_id, binders);
1104        let scope = Scope::Binder {
1105            hir_id: forall.hir_id,
1106            bound_vars,
1107            s: self.scope,
1108            scope_type: BinderScopeType::Normal,
1109            where_bound_origin: None,
1110        };
1111        self.with(scope, |this| {
1112            this.visit_generics(forall.generics);
1113            this.visit_test_binder_body(forall.body);
1114        });
1115        // exit assertions don't have the bound vars in scope
1116        if let Some(assert_on_exit) = forall.assert_on_exit {
1117            self.visit_test_binder_constraint(assert_on_exit);
1118        }
1119    }
1120
1121    fn visit_test_binder_exists(
1122        &mut self,
1123        exists: &'tcx hir::TestBinderExists<'tcx>,
1124    ) -> Self::Result {
1125        let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = exists
1126            .params
1127            .iter()
1128            .enumerate()
1129            .map(|(late_bound_idx, param)| {
1130                (
1131                    (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
1132                    late_arg_as_bound_arg(param),
1133                )
1134            })
1135            .unzip();
1136        self.record_late_bound_vars(exists.hir_id, binders);
1137        let scope = Scope::Binder {
1138            hir_id: exists.hir_id,
1139            bound_vars,
1140            s: self.scope,
1141            scope_type: BinderScopeType::Normal,
1142            where_bound_origin: None,
1143        };
1144        self.with(scope, |this| {
1145            for param in exists.params {
1146                this.visit_generic_param(param);
1147            }
1148            this.visit_test_binder_body(exists.body);
1149        });
1150    }
1151
1152    fn visit_test_binder_bound_type_constraint(
1153        &mut self,
1154        bound_type: &'tcx hir::TestBinderBoundTypeConstraint<'tcx>,
1155    ) -> Self::Result {
1156        let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = bound_type
1157            .params
1158            .iter()
1159            .enumerate()
1160            .map(|(late_bound_idx, param)| {
1161                (
1162                    (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
1163                    late_arg_as_bound_arg(param),
1164                )
1165            })
1166            .unzip();
1167        self.record_late_bound_vars(bound_type.hir_id, binders);
1168        let scope = Scope::Binder {
1169            hir_id: bound_type.hir_id,
1170            bound_vars,
1171            s: self.scope,
1172            scope_type: BinderScopeType::Normal,
1173            where_bound_origin: None,
1174        };
1175        self.with(scope, |this| {
1176            intravisit::walk_test_binder_bound_type_constraint(this, bound_type);
1177        });
1178    }
1179}
1180
1181fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: LocalDefId) -> ObjectLifetimeDefault {
1182    // Scan the bounds and where-clauses on parameters to extract bounds of the form `T: 'a`
1183    // so as to determine the `ObjectLifetimeDefault` for each type parameter.
1184
1185    let Ok((generics, bounds)) = (match tcx.hir_node_by_def_id(param_def_id) {
1186        hir::Node::GenericParam(param) => match param.source {
1187            hir::GenericParamSource::Generics => match param.kind {
1188                GenericParamKind::Type { .. } => {
1189                    Ok((tcx.hir_get_generics(tcx.local_parent(param_def_id)).unwrap(), &[][..]))
1190                }
1191                _ => Err(()),
1192            },
1193            hir::GenericParamSource::Binder => return ObjectLifetimeDefault::Empty,
1194        },
1195        // For `Self` type parameters
1196        hir::Node::Item(&hir::Item {
1197            kind: hir::ItemKind::Trait { generics, bounds, .. }, ..
1198        }) => Ok((generics, bounds)),
1199        _ => Err(()),
1200    }) else {
1201        bug_impl(None,
    format_args!("`object_lifetime_default` must only be called on type parameters"),
    Location::caller())bug!("`object_lifetime_default` must only be called on type parameters")
1202    };
1203
1204    let mut set = Set1::Empty;
1205
1206    let mut add_outlives_bounds = |bounds: &[hir::GenericBound<'_>]| {
1207        for bound in bounds {
1208            if let hir::GenericBound::Outlives(lifetime) = bound {
1209                set.insert(lifetime.kind);
1210            }
1211        }
1212    };
1213
1214    add_outlives_bounds(bounds);
1215
1216    // Look for `Type: ...` where clauses.
1217    for bound in generics.bounds_for_param(param_def_id) {
1218        // Ignore `for<'a> Type: ...` as they can change what
1219        // lifetimes mean (although we could "just" handle it).
1220        if bound.bound_generic_params.is_empty() {
1221            add_outlives_bounds(&bound.bounds);
1222        }
1223    }
1224
1225    match set {
1226        Set1::Empty => ObjectLifetimeDefault::Empty,
1227        Set1::One(hir::LifetimeKind::Static) => ObjectLifetimeDefault::Static,
1228        Set1::One(hir::LifetimeKind::Param(param_def_id)) => {
1229            ObjectLifetimeDefault::Param(param_def_id.to_def_id())
1230        }
1231        _ => ObjectLifetimeDefault::Ambiguous,
1232    }
1233}
1234
1235impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
1236    fn with<F>(&mut self, wrap_scope: Scope<'_, 'tcx>, f: F)
1237    where
1238        F: for<'b> FnOnce(&mut BoundVarContext<'b, 'tcx>),
1239    {
1240        let BoundVarContext { tcx, rbv, disambiguators, .. } = self;
1241        let nested_errors = RefCell::new(self.opaque_capture_errors.borrow_mut().take());
1242        let mut this = BoundVarContext {
1243            tcx: *tcx,
1244            rbv,
1245            disambiguators,
1246            scope: &wrap_scope,
1247            opaque_capture_errors: nested_errors,
1248        };
1249        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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(1249u32),
                        ::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());
1250        {
1251            let _enter = span.enter();
1252            f(&mut this);
1253        }
1254        *self.opaque_capture_errors.borrow_mut() = this.opaque_capture_errors.into_inner();
1255    }
1256
1257    fn record_late_bound_vars(&mut self, hir_id: HirId, binder: Vec<ty::BoundVariableKind<'tcx>>) {
1258        if let Some(old) = self.rbv.late_bound_vars.insert(hir_id.local_id, binder) {
1259            bug_impl(None,
    format_args!("overwrote bound vars for {1:?}:\nold={2:?}\nnew={0:?}",
        self.rbv.late_bound_vars[&hir_id.local_id], hir_id, old),
    Location::caller())bug!(
1260                "overwrote bound vars for {hir_id:?}:\nold={old:?}\nnew={:?}",
1261                self.rbv.late_bound_vars[&hir_id.local_id]
1262            )
1263        }
1264    }
1265
1266    /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1267    ///
1268    /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1269    /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1270    /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1271    ///
1272    /// For example:
1273    ///
1274    ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
1275    ///
1276    /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1277    /// lifetimes may be interspersed together.
1278    ///
1279    /// If early bound lifetimes are present, we separate them into their own list (and likewise
1280    /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1281    /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1282    /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1283    /// ordering is not important there.
1284    fn visit_early_late<F>(&mut self, hir_id: HirId, generics: &'tcx hir::Generics<'tcx>, walk: F)
1285    where
1286        F: for<'b, 'c> FnOnce(&'b mut BoundVarContext<'c, 'tcx>),
1287    {
1288        let mut named_late_bound_vars = 0;
1289        let bound_vars: FxIndexMap<LocalDefId, ResolvedArg> = generics
1290            .params
1291            .iter()
1292            .map(|param| {
1293                (
1294                    param.def_id,
1295                    match param.kind {
1296                        GenericParamKind::Lifetime { .. } => {
1297                            if self.tcx.is_late_bound(param.hir_id) {
1298                                let late_bound_idx = named_late_bound_vars;
1299                                named_late_bound_vars += 1;
1300                                ResolvedArg::late(late_bound_idx, param)
1301                            } else {
1302                                ResolvedArg::early(param)
1303                            }
1304                        }
1305                        GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1306                            ResolvedArg::early(param)
1307                        }
1308                    },
1309                )
1310            })
1311            .collect();
1312
1313        let binders: Vec<_> = generics
1314            .params
1315            .iter()
1316            .filter(|param| {
1317                #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Lifetime { .. })
1318                    && self.tcx.is_late_bound(param.hir_id)
1319            })
1320            .map(|param| late_arg_as_bound_arg(param))
1321            .collect();
1322        self.record_late_bound_vars(hir_id, binders);
1323        let scope = Scope::Binder {
1324            hir_id,
1325            bound_vars,
1326            s: self.scope,
1327            scope_type: BinderScopeType::Normal,
1328            where_bound_origin: None,
1329        };
1330        self.with(scope, walk);
1331    }
1332
1333    fn visit_early<F>(&mut self, hir_id: HirId, generics: &'tcx hir::Generics<'tcx>, walk: F)
1334    where
1335        F: for<'b, 'c> FnOnce(&'b mut BoundVarContext<'c, 'tcx>),
1336    {
1337        let bound_vars =
1338            generics.params.iter().map(|param| (param.def_id, ResolvedArg::early(param))).collect();
1339        self.record_late_bound_vars(hir_id, ::alloc::vec::Vec::new()vec![]);
1340        let scope = Scope::Binder {
1341            hir_id,
1342            bound_vars,
1343            s: self.scope,
1344            scope_type: BinderScopeType::Normal,
1345            where_bound_origin: None,
1346        };
1347        self.with(scope, |this| {
1348            let scope = Scope::TraitRefBoundary { s: this.scope };
1349            this.with(scope, walk)
1350        });
1351    }
1352
1353    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1353u32),
                                    ::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 =>
                                bug_impl(Some(use_span),
                                    format_args!("did not expect to resolve lifetime to {0}",
                                        kind.descr(param_def_id.to_def_id())), Location::caller()),
                        };
                    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))]
1354    fn resolve_lifetime_ref(
1355        &mut self,
1356        region_def_id: LocalDefId,
1357        lifetime_ref: &'tcx hir::Lifetime,
1358    ) {
1359        // Walk up the scope chain, tracking the number of fn scopes
1360        // that we pass through, until we find a lifetime with the
1361        // given name or we run out of scopes.
1362        // search.
1363        let mut late_depth = 0;
1364        let mut scope = self.scope;
1365        let mut outermost_body = None;
1366        let mut crossed_late_boundary = None;
1367        let mut opaque_capture_scopes = vec![];
1368        let result = loop {
1369            match *scope {
1370                Scope::Body { id, s } => {
1371                    outermost_body = Some(id);
1372                    scope = s;
1373                }
1374
1375                Scope::Root { opt_parent_item } => {
1376                    if let Some(parent_item) = opt_parent_item
1377                        && let parent_generics = self.tcx.generics_of(parent_item)
1378                        && parent_generics
1379                            .param_def_id_to_index(self.tcx, region_def_id.to_def_id())
1380                            .is_some()
1381                    {
1382                        break Some(ResolvedArg::EarlyBound(region_def_id));
1383                    }
1384                    break None;
1385                }
1386
1387                Scope::Binder { ref bound_vars, scope_type, s, where_bound_origin, .. } => {
1388                    if let Some(&def) = bound_vars.get(&region_def_id) {
1389                        break Some(def.shifted(late_depth));
1390                    }
1391                    match scope_type {
1392                        BinderScopeType::Normal => late_depth += 1,
1393                        BinderScopeType::Concatenating => {}
1394                    }
1395                    // Fresh lifetimes in APIT used to be allowed in async fns and forbidden in
1396                    // regular fns.
1397                    if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin
1398                        && let hir::LifetimeKind::Param(param_id) = lifetime_ref.kind
1399                        && let Some(generics) =
1400                            self.tcx.hir_get_generics(self.tcx.local_parent(param_id))
1401                        && let Some(param) = generics.params.iter().find(|p| p.def_id == param_id)
1402                        && param.is_elided_lifetime()
1403                        && !self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id).is_async()
1404                        && !self.tcx.features().anonymous_lifetime_in_impl_trait()
1405                    {
1406                        let mut diag: rustc_errors::Diag<'_> =
1407                            rustc_session::diagnostics::feature_err(
1408                                &self.tcx.sess,
1409                                sym::anonymous_lifetime_in_impl_trait,
1410                                lifetime_ref.ident.span,
1411                                "anonymous lifetimes in `impl Trait` are unstable",
1412                            );
1413
1414                        if let Some(generics) =
1415                            self.tcx.hir_get_generics(lifetime_ref.hir_id.owner.def_id)
1416                        {
1417                            let new_param_sugg =
1418                                if let Some(span) = generics.span_for_lifetime_suggestion() {
1419                                    (span, "'a, ".to_owned())
1420                                } else {
1421                                    (generics.span, "<'a>".to_owned())
1422                                };
1423
1424                            let lifetime_sugg = lifetime_ref.suggestion("'a");
1425                            let suggestions = vec![lifetime_sugg, new_param_sugg];
1426
1427                            diag.span_label(
1428                                lifetime_ref.ident.span,
1429                                "expected named lifetime parameter",
1430                            );
1431                            diag.multipart_suggestion(
1432                                "consider introducing a named lifetime parameter",
1433                                suggestions,
1434                                rustc_errors::Applicability::MaybeIncorrect,
1435                            );
1436                        }
1437
1438                        diag.emit();
1439                        return;
1440                    }
1441                    scope = s;
1442                }
1443
1444                Scope::Opaque { captures, def_id, s } => {
1445                    opaque_capture_scopes.push((def_id, captures));
1446                    late_depth = 0;
1447                    scope = s;
1448                }
1449
1450                Scope::ObjectLifetimeDefault { s, .. }
1451                | Scope::Supertrait { s, .. }
1452                | Scope::TraitRefBoundary { s, .. } => {
1453                    scope = s;
1454                }
1455
1456                Scope::LateBoundary { s, what, deny_late_regions } => {
1457                    if deny_late_regions {
1458                        crossed_late_boundary = Some(what);
1459                    }
1460                    scope = s;
1461                }
1462            }
1463        };
1464
1465        if let Some(mut def) = result {
1466            def = self.remap_opaque_captures(&opaque_capture_scopes, def, lifetime_ref.ident);
1467
1468            if let ResolvedArg::EarlyBound(..) = def {
1469                // Do not free early-bound regions, only late-bound ones.
1470            } else if let ResolvedArg::LateBound(_, _, param_def_id) = def
1471                && let Some(what) = crossed_late_boundary
1472            {
1473                let use_span = lifetime_ref.ident.span;
1474                let def_span = self.tcx.def_span(param_def_id);
1475                let guar = match self.tcx.def_kind(param_def_id) {
1476                    DefKind::LifetimeParam => {
1477                        self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Lifetime {
1478                            use_span,
1479                            def_span,
1480                            what,
1481                        })
1482                    }
1483                    kind => span_bug!(
1484                        use_span,
1485                        "did not expect to resolve lifetime to {}",
1486                        kind.descr(param_def_id.to_def_id())
1487                    ),
1488                };
1489                def = ResolvedArg::Error(guar);
1490            } else if let Some(body_id) = outermost_body {
1491                let fn_id = self.tcx.hir_body_owner(body_id);
1492                match self.tcx.hir_node(fn_id) {
1493                    Node::Item(hir::Item { owner_id, kind: hir::ItemKind::Fn { .. }, .. })
1494                    | Node::TraitItem(hir::TraitItem {
1495                        owner_id,
1496                        kind: hir::TraitItemKind::Fn(..),
1497                        ..
1498                    })
1499                    | Node::ImplItem(hir::ImplItem {
1500                        owner_id,
1501                        kind: hir::ImplItemKind::Fn(..),
1502                        ..
1503                    }) => {
1504                        def = ResolvedArg::Free(owner_id.def_id, def.id().unwrap());
1505                    }
1506                    Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) => {
1507                        def = ResolvedArg::Free(closure.def_id, def.id().unwrap());
1508                    }
1509                    _ => {}
1510                }
1511            }
1512
1513            self.insert_lifetime(lifetime_ref, def);
1514            return;
1515        }
1516
1517        // We may fail to resolve higher-ranked lifetimes that are mentioned by APIT.
1518        // AST-based resolution does not care for impl-trait desugaring, which are the
1519        // responsibility of lowering. This may create a mismatch between the resolution
1520        // AST found (`region_def_id`) which points to HRTB, and what HIR allows.
1521        // ```
1522        // fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {}
1523        // ```
1524        //
1525        // In such case, walk back the binders to diagnose it properly.
1526        let mut scope = self.scope;
1527        loop {
1528            match *scope {
1529                Scope::Binder {
1530                    where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), ..
1531                } => {
1532                    self.tcx.dcx().emit_err(diagnostics::LateBoundInApit::Lifetime {
1533                        span: lifetime_ref.ident.span,
1534                        param_span: self.tcx.def_span(region_def_id),
1535                    });
1536                    return;
1537                }
1538                Scope::Root { .. } => break,
1539                Scope::Binder { s, .. }
1540                | Scope::Body { s, .. }
1541                | Scope::Opaque { s, .. }
1542                | Scope::ObjectLifetimeDefault { s, .. }
1543                | Scope::Supertrait { s, .. }
1544                | Scope::TraitRefBoundary { s, .. }
1545                | Scope::LateBoundary { s, .. } => {
1546                    scope = s;
1547                }
1548            }
1549        }
1550
1551        self.tcx.dcx().span_delayed_bug(
1552            lifetime_ref.ident.span,
1553            format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
1554        );
1555    }
1556
1557    /// Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
1558    /// and ban them. Type variables instantiated inside binders aren't
1559    /// well-supported at the moment, so this doesn't work.
1560    /// In the future, this should be fixed and this error should be removed.
1561    fn check_lifetime_is_capturable(
1562        &self,
1563        opaque_def_id: LocalDefId,
1564        lifetime: ResolvedArg,
1565        capture_span: Span,
1566    ) -> Result<(), ErrorGuaranteed> {
1567        let ResolvedArg::LateBound(_, _, lifetime_def_id) = lifetime else { return Ok(()) };
1568        let lifetime_hir_id = self.tcx.local_def_id_to_hir_id(lifetime_def_id);
1569        let bad_place = match self.tcx.hir_node(self.tcx.parent_hir_id(lifetime_hir_id)) {
1570            // Opaques do not declare their own lifetimes, so if a lifetime comes from an opaque
1571            // it must be a reified late-bound lifetime from a trait goal.
1572            hir::Node::OpaqueTy(_) => "higher-ranked lifetime from outer `impl Trait`",
1573            // Other items are fine.
1574            hir::Node::Item(_) | hir::Node::TraitItem(_) | hir::Node::ImplItem(_) => return Ok(()),
1575            hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(_), .. }) => {
1576                "higher-ranked lifetime from function pointer"
1577            }
1578            hir::Node::Ty(hir::Ty { kind: hir::TyKind::TraitObject(..), .. }) => {
1579                "higher-ranked lifetime from `dyn` type"
1580            }
1581            _ => "higher-ranked lifetime",
1582        };
1583
1584        let decl_span = self.tcx.def_span(lifetime_def_id);
1585        let opaque_span = self.tcx.def_span(opaque_def_id);
1586
1587        let mut errors = self.opaque_capture_errors.borrow_mut();
1588        let error_info = errors.get_or_insert_with(|| OpaqueHigherRankedLifetimeCaptureErrors {
1589            bad_place,
1590            capture_spans: Vec::new(),
1591            decl_spans: Vec::new(),
1592        });
1593
1594        if error_info.capture_spans.is_empty() {
1595            error_info.capture_spans.push(opaque_span);
1596        }
1597
1598        if capture_span != decl_span && capture_span != opaque_span {
1599            error_info.capture_spans.push(capture_span);
1600        }
1601
1602        if !error_info.decl_spans.contains(&decl_span) {
1603            error_info.decl_spans.push(decl_span);
1604        }
1605
1606        // Errors should be emitted by `emit_opaque_capture_errors`.
1607        Err(self.tcx.dcx().span_delayed_bug(capture_span, "opaque capture error not emitted"))
1608    }
1609
1610    fn emit_opaque_capture_errors(&self) -> Option<ErrorGuaranteed> {
1611        let errors = self.opaque_capture_errors.borrow_mut().take()?;
1612        if errors.capture_spans.is_empty() {
1613            return None;
1614        }
1615
1616        let mut span = rustc_errors::MultiSpan::from_span(errors.capture_spans[0]);
1617        for &capture_span in &errors.capture_spans[1..] {
1618            span.push_span_label(capture_span, "");
1619        }
1620        let decl_span = rustc_errors::MultiSpan::from_spans(errors.decl_spans);
1621
1622        // Ensure that the parent of the def is an item, not HRTB
1623        let guar = self.tcx.dcx().emit_err(diagnostics::OpaqueCapturesHigherRankedLifetime {
1624            span,
1625            label: Some(errors.capture_spans[0]),
1626            decl_span,
1627            bad_place: errors.bad_place,
1628        });
1629
1630        Some(guar)
1631    }
1632
1633    {}
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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                ::tracing_core::__macro_support::Option::Some(1633u32),
                                ::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:1633",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(1633u32),
                        ::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)]
1634    fn remap_opaque_captures(
1635        &mut self,
1636        opaque_capture_scopes: &Vec<(LocalDefId, &RefCell<FxIndexMap<ResolvedArg, LocalDefId>>)>,
1637        mut lifetime: ResolvedArg,
1638        ident: Ident,
1639    ) -> ResolvedArg {
1640        if let Some(&(opaque_def_id, _)) = opaque_capture_scopes.last() {
1641            if let Err(guar) =
1642                self.check_lifetime_is_capturable(opaque_def_id, lifetime, ident.span)
1643            {
1644                lifetime = ResolvedArg::Error(guar);
1645            }
1646        }
1647
1648        for &(opaque_def_id, captures) in opaque_capture_scopes.iter().rev() {
1649            let mut captures = captures.borrow_mut();
1650            let remapped = *captures.entry(lifetime).or_insert_with(|| {
1651                // `opaque_def_id` is unique to the `BoundVarContext` pass which is executed once
1652                // per `resolve_bound_vars` query. This is the only location that creates
1653                // `OpaqueLifetime` paths. `<opaque_def_id>::OpaqueLifetime(..)` is thus unique
1654                // to this query and duplicates within the query are handled by `self.disambiguator`.
1655                let feed = self.tcx.create_def(
1656                    opaque_def_id,
1657                    None,
1658                    DefKind::LifetimeParam,
1659                    Some(DefPathData::OpaqueLifetime(ident.name)),
1660                    self.disambiguators.get_or_create(opaque_def_id),
1661                );
1662                feed.def_span(ident.span);
1663                feed.def_ident_span(Some(ident.span));
1664                feed.def_id()
1665            });
1666            lifetime = ResolvedArg::EarlyBound(remapped);
1667        }
1668        lifetime
1669    }
1670
1671    fn resolve_type_ref(&mut self, param_def_id: LocalDefId, hir_id: HirId) {
1672        // Walk up the scope chain, tracking the number of fn scopes
1673        // that we pass through, until we find a lifetime with the
1674        // given name or we run out of scopes.
1675        // search.
1676        let mut late_depth = 0;
1677        let mut scope = self.scope;
1678        let mut crossed_late_boundary = None;
1679
1680        let result = loop {
1681            match *scope {
1682                Scope::Body { s, .. } => {
1683                    scope = s;
1684                }
1685
1686                Scope::Root { opt_parent_item } => {
1687                    if let Some(parent_item) = opt_parent_item
1688                        && let parent_generics = self.tcx.generics_of(parent_item)
1689                        && parent_generics
1690                            .param_def_id_to_index(self.tcx, param_def_id.to_def_id())
1691                            .is_some()
1692                    {
1693                        break Some(ResolvedArg::EarlyBound(param_def_id));
1694                    }
1695                    break None;
1696                }
1697
1698                Scope::Binder { ref bound_vars, scope_type, s, .. } => {
1699                    if let Some(&def) = bound_vars.get(&param_def_id) {
1700                        break Some(def.shifted(late_depth));
1701                    }
1702                    match scope_type {
1703                        BinderScopeType::Normal => late_depth += 1,
1704                        BinderScopeType::Concatenating => {}
1705                    }
1706                    scope = s;
1707                }
1708
1709                Scope::ObjectLifetimeDefault { s, .. }
1710                | Scope::Opaque { s, .. }
1711                | Scope::Supertrait { s, .. }
1712                | Scope::TraitRefBoundary { s, .. } => {
1713                    scope = s;
1714                }
1715
1716                Scope::LateBoundary { s, what, deny_late_regions: _ } => {
1717                    crossed_late_boundary = Some(what);
1718                    scope = s;
1719                }
1720            }
1721        };
1722
1723        if let Some(def) = result {
1724            if let ResolvedArg::LateBound(..) = def
1725                && let Some(what) = crossed_late_boundary
1726            {
1727                let use_span = self.tcx.hir_span(hir_id);
1728                let def_span = self.tcx.def_span(param_def_id);
1729                let guar = match self.tcx.def_kind(param_def_id) {
1730                    DefKind::ConstParam => {
1731                        self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Const {
1732                            use_span,
1733                            def_span,
1734                            what,
1735                        })
1736                    }
1737                    DefKind::TyParam => {
1738                        self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Type {
1739                            use_span,
1740                            def_span,
1741                            what,
1742                        })
1743                    }
1744                    kind => bug_impl(Some(use_span),
    format_args!("did not expect to resolve non-lifetime param to {0}",
        kind.descr(param_def_id.to_def_id())), Location::caller())span_bug!(
1745                        use_span,
1746                        "did not expect to resolve non-lifetime param to {}",
1747                        kind.descr(param_def_id.to_def_id())
1748                    ),
1749                };
1750                self.rbv.defs.insert(hir_id.local_id, ResolvedArg::Error(guar));
1751            } else {
1752                self.rbv.defs.insert(hir_id.local_id, def);
1753            }
1754            return;
1755        }
1756
1757        // We may fail to resolve higher-ranked ty/const vars that are mentioned by APIT.
1758        // AST-based resolution does not care for impl-trait desugaring, which are the
1759        // responsibility of lowering. This may create a mismatch between the resolution
1760        // AST found (`param_def_id`) which points to HRTB, and what HIR allows.
1761        // ```
1762        // fn foo(x: impl for<T> Trait<Assoc = impl Trait2<T>>) {}
1763        // ```
1764        //
1765        // In such case, walk back the binders to diagnose it properly.
1766        let mut scope = self.scope;
1767        loop {
1768            match *scope {
1769                Scope::Binder {
1770                    where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), ..
1771                } => {
1772                    let guar = self.tcx.dcx().emit_err(match self.tcx.def_kind(param_def_id) {
1773                        DefKind::TyParam => diagnostics::LateBoundInApit::Type {
1774                            span: self.tcx.hir_span(hir_id),
1775                            param_span: self.tcx.def_span(param_def_id),
1776                        },
1777                        DefKind::ConstParam => diagnostics::LateBoundInApit::Const {
1778                            span: self.tcx.hir_span(hir_id),
1779                            param_span: self.tcx.def_span(param_def_id),
1780                        },
1781                        kind => {
1782                            bug_impl(None,
    format_args!("unexpected def-kind: {0}",
        kind.descr(param_def_id.to_def_id())), Location::caller())bug!("unexpected def-kind: {}", kind.descr(param_def_id.to_def_id()))
1783                        }
1784                    });
1785                    self.rbv.defs.insert(hir_id.local_id, ResolvedArg::Error(guar));
1786                    return;
1787                }
1788                Scope::Root { .. } => break,
1789                Scope::Binder { s, .. }
1790                | Scope::Body { s, .. }
1791                | Scope::Opaque { s, .. }
1792                | Scope::ObjectLifetimeDefault { s, .. }
1793                | Scope::Supertrait { s, .. }
1794                | Scope::TraitRefBoundary { s, .. }
1795                | Scope::LateBoundary { s, .. } => {
1796                    scope = s;
1797                }
1798            }
1799        }
1800
1801        self.tcx
1802            .dcx()
1803            .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:?}"));
1804    }
1805
1806    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1806u32),
                                    ::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:1827",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1827u32),
                                    ::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:1837",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1837u32),
                                    ::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))]
1807    fn visit_path_segment_args(
1808        &mut self,
1809        generic_args: &'tcx hir::GenericArgs<'tcx>,
1810        seg_idx: SegIdx,
1811        path: &hir::Path<'tcx>,
1812    ) {
1813        if let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() {
1814            self.visit_fn_like_elision(inputs, Some(output), false);
1815            return;
1816        }
1817
1818        // Let's first resolve all lifetime arguments because we need their
1819        // resolution for computing the trait object lifetime defaults.
1820        for arg in generic_args.args {
1821            if let hir::GenericArg::Lifetime(lt) = arg {
1822                self.visit_lifetime(lt);
1823            }
1824        }
1825
1826        let container = self.eligible_container(path, seg_idx);
1827        debug!(?container);
1828
1829        let (has_self, object_lifetime_defaults) = container
1830            .map(|(def_id, segs)| {
1831                let generics = self.tcx.generics_of(def_id);
1832                let defaults = self.compute_object_lifetime_defaults(generics, segs);
1833                (generics.has_own_self(), defaults)
1834            })
1835            .unwrap_or_default();
1836
1837        debug!(?object_lifetime_defaults);
1838
1839        let mut i = has_self as usize;
1840        for arg in generic_args.args {
1841            match arg {
1842                // We've already visited all lifetime arguments at the start.
1843                GenericArg::Lifetime(_) => {}
1844                GenericArg::Type(ty) => {
1845                    if let Some(&lt) = object_lifetime_defaults.get(i) {
1846                        let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
1847                        self.with(scope, |this| this.visit_ty(ty));
1848                    } else {
1849                        self.visit_ty(ty);
1850                    }
1851                    i += 1;
1852                }
1853                GenericArg::Const(ct) => {
1854                    self.visit_const_arg(ct);
1855                    i += 1;
1856                }
1857                GenericArg::Infer(inf) => {
1858                    self.visit_id(inf.hir_id);
1859                    i += 1;
1860                }
1861            }
1862        }
1863
1864        let has_lifetime_args = generic_args.has_lifetime_args();
1865
1866        for constraint in generic_args.constraints {
1867            let scope = Scope::ObjectLifetimeDefault {
1868                // FIXME: Ideally we would consider the *item bounds* of assoc types when deducing
1869                //        the trait object lifetime default for the RHS of assoc type bindings.
1870                //        For example, given
1871                //
1872                //            trait TraitA<'a> { type AssocTy: ?Sized + 'a; }
1873                //            trait TraitB { type AssocTy<'a>: ?Sized + 'a; }
1874                //
1875                //        we would elaborate the `dyn Bound` in `TraitA<'r, AssocTy = dyn Bound>`
1876                //        and `TraitB<AssocTy<'r> = dyn Bound>` to `dyn Bound + 'r`.
1877                //
1878                // FIXME: Moreover, ideally GAT args in bindings could induce
1879                //        trait object lifetime defaults. For example, given
1880                //
1881                //           trait TraitA<'a> { type AssocTy<T: ?Sized + 'a>; }
1882                //           trait TraitB { type AssocTy<'a, T: ?Sized + 'a>; }
1883                //
1884                //        we would elab the `dyn Bound` in `TraitA<'r, AssocTy<dyn Bound> = ()>`
1885                //        and `TraitB<AssocTy<'r, dyn Bound> = ()>` to `dyn Bound + 'r`.
1886                //
1887                // HACK: For now however, if the user passes any lifetime arguments to the trait or
1888                //       the (generic) assoc type, we will treat the trait object lifetime default
1889                //       as indeterminate thus forcing the user to explicitly specify the lifetime.
1890                //
1891                //       If the trait or the assoc type have lifetime parameters, it's *possible*
1892                //       that they occur in the predicates or item bounds of the assoc type, so we
1893                //       conservatively reject such cases to allow us to implement the correct
1894                //       behavior in the future (here we assume that the number of arguments equals
1895                //       the number of parameters which is fine since a mismatch would get rejected
1896                //       later anyway).
1897                //
1898                //       If the items don't have any lifetime parameters we can safely use `'static`
1899                //       since there is no other possibility.
1900                lifetime: if has_lifetime_args || constraint.gen_args.has_lifetime_args() {
1901                    None
1902                } else {
1903                    Some(ResolvedArg::StaticLifetime)
1904                },
1905                s: self.scope,
1906            };
1907            // If the args are parenthesized, then this must be `feature(return_type_notation)`.
1908            // In that case, introduce a binder over all of the function's early and late bound vars.
1909            //
1910            // For example, given
1911            // ```
1912            // trait Foo {
1913            //     async fn x<'r, T>();
1914            // }
1915            // ```
1916            // and a bound that looks like:
1917            //    `for<'a> T::Trait<'a, x(..): for<'b> Other<'b>>`
1918            // this is going to expand to something like:
1919            //    `for<'a> for<'r> <T as Trait<'a>>::x::<'r, T>::{opaque#0}: for<'b> Other<'b>`.
1920            if constraint.gen_args.parenthesized == hir::GenericArgsParentheses::ReturnTypeNotation
1921            {
1922                let bound_vars = if let Some((container_def_id, _)) = container
1923                    && let DefKind::Trait | DefKind::TraitAlias =
1924                        self.tcx.def_kind(container_def_id)
1925                    && let Some((mut bound_vars, assoc_fn)) = BoundVarContext::supertrait_hrtb_vars(
1926                        self.tcx,
1927                        container_def_id,
1928                        constraint.ident,
1929                        ty::AssocTag::Fn,
1930                    ) {
1931                    bound_vars.extend(
1932                        self.tcx
1933                            .generics_of(assoc_fn.def_id)
1934                            .own_params
1935                            .iter()
1936                            .map(|param| generic_param_def_as_bound_arg(param)),
1937                    );
1938                    // `resolve_bound_vars` is computed per HIR owner. `visit_early_late`
1939                    // records this associated function's binder before walking its signature,
1940                    // so reuse that in-progress binder instead of recursively querying `fn_sig`.
1941                    let fn_bound_vars = if assoc_fn.def_id == constraint.hir_id.owner.to_def_id() {
1942                        let fn_hir_id =
1943                            self.tcx.local_def_id_to_hir_id(assoc_fn.def_id.expect_local());
1944                        self.rbv
1945                            .late_bound_vars
1946                            .get(&fn_hir_id.local_id)
1947                            .expect("late-bound vars for the current function were not recorded")
1948                            .clone()
1949                    } else {
1950                        self.tcx
1951                            .fn_sig(assoc_fn.def_id)
1952                            .instantiate_identity()
1953                            .skip_norm_wip()
1954                            .bound_vars()
1955                            .to_vec()
1956                    };
1957                    bound_vars.extend(fn_bound_vars);
1958                    bound_vars
1959                } else {
1960                    self.tcx
1961                        .dcx()
1962                        .span_delayed_bug(constraint.ident.span, "bad return type notation here");
1963                    vec![]
1964                };
1965                self.with(scope, |this| {
1966                    let scope = Scope::Supertrait { bound_vars, s: this.scope };
1967                    this.with(scope, |this| {
1968                        let (bound_vars, _) = this.poly_trait_ref_binder_info();
1969                        this.record_late_bound_vars(constraint.hir_id, bound_vars);
1970                        this.visit_assoc_item_constraint(constraint)
1971                    });
1972                });
1973            } else if let Some((container_def_id, _)) = container {
1974                let bound_vars = BoundVarContext::supertrait_hrtb_vars(
1975                    self.tcx,
1976                    container_def_id,
1977                    constraint.ident,
1978                    ty::AssocTag::Type,
1979                )
1980                .map(|(bound_vars, _)| bound_vars);
1981                self.with(scope, |this| {
1982                    let scope = Scope::Supertrait {
1983                        bound_vars: bound_vars.unwrap_or_default(),
1984                        s: this.scope,
1985                    };
1986                    this.with(scope, |this| this.visit_assoc_item_constraint(constraint));
1987                });
1988            } else {
1989                self.with(scope, |this| this.visit_assoc_item_constraint(constraint));
1990            }
1991        }
1992    }
1993
1994    /// Return the eligible container for the path segment given by the index if applicable.
1995    ///
1996    /// Such a container induces lifetime defaults for trait object types contained
1997    /// in any of the type arguments passed to it (any inner containers will of course
1998    /// end up shadowing that default).
1999    fn eligible_container<'b>(
2000        &self,
2001        path: &'b hir::Path<'tcx>,
2002        seg_idx: SegIdx,
2003    ) -> Option<(DefId, &'b [hir::PathSegment<'tcx>])> {
2004        let RevSegIdx(rev_seg_idx) = seg_idx.reverse(path.segments);
2005        let SegIdx(seg_idx) = seg_idx;
2006
2007        // NOTE: We don't need to care about definition kinds that may have generics if they
2008        // can only ever appear in positions where we can perform type inference (i.e., bodies).
2009
2010        // FIXME(mgca, #151649): Type-level free/assoc consts, const&fn ctors should also qualify.
2011        // FIXME(return_type_notation, #151662): Assoc fns should also qualify.
2012
2013        let (kind, def_id) = match path.res {
2014            Res::Def(kind, def_id) => (kind, def_id),
2015            Res::PrimTy(..)
2016            | Res::SelfTyParam { .. }
2017            | Res::SelfTyAlias { .. }
2018            | Res::SelfCtor(_)
2019            | Res::Local(_)
2020            | Res::ToolMod
2021            | Res::OpenMod(_)
2022            | Res::NonMacroAttr(_)
2023            | Res::Err => return None, // see NOTE above!
2024        };
2025
2026        match kind {
2027            DefKind::AssocTy => match rev_seg_idx {
2028                0 => Some((def_id, path.segments)),
2029                // We're looking at the trait ref of an assoc type projection.
2030                // E.g., the `TraitRef<…>` in `<… as path::to::TraitRef<…>>::AssocTy<…>`.
2031                1 => Some((self.tcx.parent(def_id), &path.segments[..=seg_idx])),
2032                _ => None,
2033            },
2034            DefKind::Variant => match rev_seg_idx {
2035                // We're looking at the `Variant::<…>` in `path::to::Variant::<…> { … }`.
2036                // Even if it's the variant segment that has the generic args and not the
2037                // enum segment, it's the enum that has the corresponding generic params.
2038                0 => Some((self.tcx.parent(def_id), path.segments)),
2039                // We're looking at the `Enum::<…>` in `path::to::Enum::<…>::Variant { … }`.
2040                1 => Some((self.tcx.parent(def_id), &path.segments[..=seg_idx])),
2041                _ => None,
2042            },
2043            DefKind::Enum
2044            | DefKind::Struct
2045            | DefKind::Trait
2046            | DefKind::TraitAlias
2047            | DefKind::TyAlias
2048            | DefKind::Union => match rev_seg_idx {
2049                0 => Some((def_id, path.segments)),
2050                _ => None,
2051            },
2052            DefKind::AnonConst
2053            | DefKind::AssocConst
2054            | DefKind::AssocFn
2055            | DefKind::Closure
2056            | DefKind::Const
2057            | DefKind::ConstParam
2058            | DefKind::Ctor(..)
2059            | DefKind::ExternCrate
2060            | DefKind::Field
2061            | DefKind::Fn
2062            | DefKind::ForeignMod
2063            | DefKind::ForeignTy
2064            | DefKind::GlobalAsm
2065            | DefKind::Impl { .. }
2066            | DefKind::LifetimeParam
2067            | DefKind::Macro(_)
2068            | DefKind::Mod
2069            | DefKind::OpaqueTy
2070            | DefKind::Static { .. }
2071            | DefKind::SyntheticCoroutineBody
2072            | DefKind::TyParam
2073            | DefKind::Use
2074            | DefKind::TestBinderConstraints => None, // see NOTE above!
2075        }
2076    }
2077
2078    /// Compute a list of trait object lifetime defaults, one for each type parameter,
2079    /// per the rules initially given in RFCs [599] and [1156]. Example:
2080    ///
2081    /// ```
2082    /// struct Foo<'a, T: 'a + ?Sized, U: ?Sized>(&'a T, &'a U);
2083    /// ```
2084    ///
2085    /// If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to elaborate
2086    /// * `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound) and
2087    /// * `dyn Baz` to `dyn Baz + 'static` (because there is no such bound).
2088    ///
2089    /// Therefore, we would compute a list like `['x, 'static]`. Note that the list only
2090    /// includes entries for type and const parameters, not for lifetime parameters.
2091    ///
2092    /// [599]: https://rust-lang.github.io/rfcs/0599-default-object-bound.html
2093    /// [1156]: https://rust-lang.github.io/rfcs/1156-adjust-default-object-bounds.html
2094    fn compute_object_lifetime_defaults(
2095        &self,
2096        generics: &ty::Generics,
2097        segments: &[hir::PathSegment<'_>],
2098    ) -> Vec<Option<ResolvedArg>> {
2099        let in_body = {
2100            let mut scope = self.scope;
2101            loop {
2102                match *scope {
2103                    Scope::Root { .. } => break false,
2104
2105                    Scope::Body { .. } => break true,
2106
2107                    Scope::Binder { s, .. }
2108                    | Scope::ObjectLifetimeDefault { s, .. }
2109                    | Scope::Opaque { s, .. }
2110                    | Scope::Supertrait { s, .. }
2111                    | Scope::TraitRefBoundary { s, .. }
2112                    | Scope::LateBoundary { s, .. } => {
2113                        scope = s;
2114                    }
2115                }
2116            }
2117        };
2118
2119        let set_to_region = |set: ObjectLifetimeDefault| match set {
2120            ObjectLifetimeDefault::Empty => {
2121                if in_body {
2122                    None
2123                } else {
2124                    Some(ResolvedArg::StaticLifetime)
2125                }
2126            }
2127            ObjectLifetimeDefault::Static => Some(ResolvedArg::StaticLifetime),
2128            ObjectLifetimeDefault::Param(param_def_id) => {
2129                struct ArgIdx(usize);
2130
2131                fn resolve_param(
2132                    param_def_id: DefId,
2133                    generics: &ty::Generics,
2134                    tcx: TyCtxt<'_>,
2135                ) -> (RevSegIdx, ArgIdx) {
2136                    if let Some(&index) = generics.param_def_id_to_index.get(&param_def_id) {
2137                        let has_self = generics.has_own_self();
2138                        let index = index as usize - generics.parent_count - has_self as usize;
2139                        (RevSegIdx(0), ArgIdx(index))
2140                    } else if let Some(parent) = generics.parent {
2141                        let parent_generics = tcx.generics_of(parent);
2142                        let (RevSegIdx(rev_seg_idx), arg_idx) =
2143                            resolve_param(param_def_id, parent_generics, tcx);
2144                        (RevSegIdx(rev_seg_idx + 1), arg_idx)
2145                    } else {
2146                        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2147                    }
2148                }
2149
2150                let (rev_seg_idx, ArgIdx(arg_idx)) =
2151                    resolve_param(param_def_id, generics, self.tcx);
2152
2153                let SegIdx(seg_idx) = rev_seg_idx.reverse(segments);
2154
2155                segments[seg_idx].args.and_then(|args| args.args.get(arg_idx)).and_then(|arg| {
2156                    match arg {
2157                        GenericArg::Lifetime(lt) => self.rbv.defs.get(&lt.hir_id.local_id).copied(),
2158                        _ => None,
2159                    }
2160                })
2161            }
2162            ObjectLifetimeDefault::Ambiguous => None,
2163        };
2164        generics
2165            .own_params
2166            .iter()
2167            .filter_map(|param| {
2168                // NB: `Self` type params share the `DefId` with the corresponding trait (alias).
2169                //
2170                // Since trait aliases can't be used as the qself of fully qualified paths, the
2171                // trait object lifetime default for their `Self` type param is never needed.
2172                // Thus, we don't even try to compute it.
2173                //
2174                // We still need to map const params & trait aliases to *some* default to make it
2175                // easy & predictable for the caller how to map the defaults back to generic args.
2176                // As they can't tell if a given inferred arg refers to a type or a const at this
2177                // stage of analysis, they can't skip it and thus we need to provide (dummy)
2178                // defaults for const args. Otherwise, they wouldn't properly align.
2179
2180                match self.tcx.def_kind(param.def_id) {
2181                    DefKind::TyParam | DefKind::Trait => {
2182                        Some(self.tcx.object_lifetime_default(param.def_id))
2183                    }
2184                    DefKind::ConstParam | DefKind::TraitAlias => Some(ObjectLifetimeDefault::Empty),
2185                    DefKind::LifetimeParam => None,
2186                    kind => bug_impl(None, format_args!("unexpected def kind {0:?}", kind),
    Location::caller())bug!("unexpected def kind {kind:?}"),
2187                }
2188            })
2189            .map(set_to_region)
2190            .collect()
2191    }
2192
2193    /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
2194    /// associated type name and starting trait.
2195    /// For example, imagine we have
2196    /// ```ignore (illustrative)
2197    /// trait Foo<'a, 'b> {
2198    ///   type As;
2199    /// }
2200    /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
2201    /// trait Bar: for<'b> Bar<'b> {}
2202    /// ```
2203    /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
2204    /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
2205    fn supertrait_hrtb_vars(
2206        tcx: TyCtxt<'tcx>,
2207        def_id: DefId,
2208        assoc_ident: Ident,
2209        assoc_tag: ty::AssocTag,
2210    ) -> Option<(Vec<ty::BoundVariableKind<'tcx>>, &'tcx ty::AssocItem)> {
2211        let trait_defines_associated_item_named = |trait_def_id: DefId| {
2212            tcx.associated_items(trait_def_id).find_by_ident_and_kind(
2213                tcx,
2214                assoc_ident,
2215                assoc_tag,
2216                trait_def_id,
2217            )
2218        };
2219
2220        use smallvec::{SmallVec, smallvec};
2221        let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind<'tcx>; 8]>); 8]> =
2222            {
    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![])];
2223        let mut visited: FxHashSet<DefId> = FxHashSet::default();
2224        loop {
2225            let Some((def_id, bound_vars)) = stack.pop() else {
2226                break None;
2227            };
2228            // See issue #83753. If someone writes an associated type on a non-trait, just treat it
2229            // as there being no supertrait HRTBs.
2230            match tcx.def_kind(def_id) {
2231                DefKind::Trait | DefKind::TraitAlias | DefKind::Impl { .. } => {}
2232                _ => break None,
2233            }
2234
2235            if let Some(assoc_item) = trait_defines_associated_item_named(def_id) {
2236                break Some((bound_vars.into_iter().collect(), assoc_item));
2237            }
2238            let predicates = tcx.explicit_supertraits_containing_assoc_item((def_id, assoc_ident));
2239            let obligations = predicates
2240                .iter_identity_copied()
2241                .map(Unnormalized::skip_norm_wip)
2242                .filter_map(|(pred, _)| {
2243                    let bound_predicate = pred.kind();
2244                    match bound_predicate.skip_binder() {
2245                        ty::ClauseKind::Trait(data) => {
2246                            // The order here needs to match what we would get from
2247                            // `rustc_middle::ty::predicate::Clause::instantiate_supertrait`
2248                            let pred_bound_vars = bound_predicate.bound_vars();
2249                            let mut all_bound_vars = bound_vars.clone();
2250                            all_bound_vars.extend(pred_bound_vars.iter());
2251                            let super_def_id = data.trait_ref.def_id;
2252                            Some((super_def_id, all_bound_vars))
2253                        }
2254                        _ => None,
2255                    }
2256                });
2257
2258            let obligations = obligations.filter(|o| visited.insert(o.0));
2259            stack.extend(obligations);
2260        }
2261    }
2262
2263    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2263u32),
                                    ::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))]
2264    fn visit_fn_like_elision(
2265        &mut self,
2266        inputs: &'tcx [hir::Ty<'tcx>],
2267        output: Option<&'tcx hir::Ty<'tcx>>,
2268        in_closure: bool,
2269    ) {
2270        self.with(
2271            Scope::ObjectLifetimeDefault {
2272                lifetime: Some(ResolvedArg::StaticLifetime),
2273                s: self.scope,
2274            },
2275            |this| {
2276                for input in inputs {
2277                    this.visit_ty_unambig(input);
2278                }
2279                if !in_closure && let Some(output) = output {
2280                    this.visit_ty_unambig(output);
2281                }
2282            },
2283        );
2284        if in_closure && let Some(output) = output {
2285            self.visit_ty_unambig(output);
2286        }
2287    }
2288
2289    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2289u32),
                                    ::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))]
2290    fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2291        let mut late_depth = 0;
2292        let mut scope = self.scope;
2293        let mut opaque_capture_scopes = vec![];
2294        let mut lifetime = loop {
2295            match *scope {
2296                Scope::Binder { s, scope_type, .. } => {
2297                    match scope_type {
2298                        BinderScopeType::Normal => late_depth += 1,
2299                        BinderScopeType::Concatenating => {}
2300                    }
2301                    scope = s;
2302                }
2303
2304                Scope::Root { .. } => break ResolvedArg::StaticLifetime,
2305
2306                Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2307
2308                Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => {
2309                    break l.shifted(late_depth);
2310                }
2311
2312                Scope::Opaque { captures, def_id, s } => {
2313                    opaque_capture_scopes.push((def_id, captures));
2314                    late_depth = 0;
2315                    scope = s;
2316                }
2317
2318                Scope::Supertrait { s, .. }
2319                | Scope::TraitRefBoundary { s, .. }
2320                | Scope::LateBoundary { s, .. } => {
2321                    scope = s;
2322                }
2323            }
2324        };
2325
2326        lifetime = self.remap_opaque_captures(&opaque_capture_scopes, lifetime, lifetime_ref.ident);
2327
2328        self.insert_lifetime(lifetime_ref, lifetime);
2329    }
2330
2331    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2331u32),
                                    ::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2333",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2333u32),
                                    ::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))]
2332    fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: ResolvedArg) {
2333        debug!(span = ?lifetime_ref.ident.span);
2334        self.rbv.defs.insert(lifetime_ref.hir_id.local_id, def);
2335    }
2336
2337    // When we have a return type notation type in a where clause, like
2338    // `where <T as Trait>::method(..): Send`, we need to introduce new bound
2339    // vars to the existing where clause's binder, to represent the lifetimes
2340    // elided by the return-type-notation syntax.
2341    //
2342    // For example, given
2343    // ```
2344    // trait Foo {
2345    //     async fn x<'r>();
2346    // }
2347    // ```
2348    // and a bound that looks like:
2349    //    `for<'a, 'b> <T as Trait<'a>>::x(): Other<'b>`
2350    // this is going to expand to something like:
2351    //    `for<'a, 'b, 'r> <T as Trait<'a>>::x::<'r, T>::{opaque#0}: Other<'b>`.
2352    //
2353    // We handle this similarly for associated-type-bound style return-type-notation
2354    // in `visit_path_segment_args`.
2355    fn try_append_return_type_notation_params(
2356        &mut self,
2357        hir_id: HirId,
2358        hir_ty: &'tcx hir::Ty<'tcx>,
2359    ) {
2360        let hir::TyKind::Path(qpath) = hir_ty.kind else {
2361            // We only care about path types here. All other self types
2362            // (including nesting the RTN type in another type) don't do
2363            // anything.
2364            return;
2365        };
2366
2367        let (mut bound_vars, item_def_id, item_segment) = match qpath {
2368            // If we have a fully qualified method, then we don't need to do any special lookup.
2369            hir::QPath::Resolved(_, path)
2370                if let [.., item_segment] = &path.segments[..]
2371                    && item_segment.args.is_some_and(|args| {
2372                        #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
    hir::GenericArgsParentheses::ReturnTypeNotation => true,
    _ => false,
}matches!(
2373                            args.parenthesized,
2374                            hir::GenericArgsParentheses::ReturnTypeNotation
2375                        )
2376                    }) =>
2377            {
2378                match path.res {
2379                    Res::Err => return,
2380                    Res::Def(DefKind::AssocFn, item_def_id) => (::alloc::vec::Vec::new()vec![], item_def_id, item_segment),
2381                    _ => bug_impl(None,
    format_args!("only expected method resolution for fully qualified RTN"),
    Location::caller())bug!("only expected method resolution for fully qualified RTN"),
2382                }
2383            }
2384
2385            // If we have a type-dependent path, then we do need to do some lookup.
2386            hir::QPath::TypeRelative(qself, item_segment)
2387                if item_segment.args.is_some_and(|args| {
2388                    #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
    hir::GenericArgsParentheses::ReturnTypeNotation => true,
    _ => false,
}matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2389                }) =>
2390            {
2391                // First, ignore a qself that isn't a type or `Self` param. Those are the
2392                // only ones that support `T::Assoc` anyways in HIR lowering.
2393                let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = qself.kind else {
2394                    return;
2395                };
2396                match path.res {
2397                    Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { trait_: _ } => {
2398                        let mut bounds =
2399                            self.for_each_trait_bound_on_res(path.res).filter_map(|trait_def_id| {
2400                                BoundVarContext::supertrait_hrtb_vars(
2401                                    self.tcx,
2402                                    trait_def_id,
2403                                    item_segment.ident,
2404                                    ty::AssocTag::Fn,
2405                                )
2406                            });
2407
2408                        let Some((bound_vars, assoc_item)) = bounds.next() else {
2409                            // This will error in HIR lowering.
2410                            self.tcx
2411                                .dcx()
2412                                .span_delayed_bug(path.span, "no resolution for RTN path");
2413                            return;
2414                        };
2415
2416                        // Don't bail if we have identical bounds, which may be collected from
2417                        // something like `T: Bound + Bound`, or via elaborating supertraits.
2418                        for (second_vars, second_assoc_item) in bounds {
2419                            if second_vars != bound_vars || second_assoc_item != assoc_item {
2420                                // This will error in HIR lowering.
2421                                self.tcx.dcx().span_delayed_bug(
2422                                    path.span,
2423                                    "ambiguous resolution for RTN path",
2424                                );
2425                                return;
2426                            }
2427                        }
2428
2429                        (bound_vars, assoc_item.def_id, item_segment)
2430                    }
2431                    // If we have a self type alias (in an impl), try to resolve an
2432                    // associated item from one of the supertraits of the impl's trait.
2433                    Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. } => {
2434                        let hir::ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) = self
2435                            .tcx
2436                            .hir_node_by_def_id(impl_def_id.expect_local())
2437                            .expect_item()
2438                            .kind
2439                        else {
2440                            return;
2441                        };
2442                        let Some(trait_def_id) = of_trait.trait_ref.trait_def_id() else {
2443                            return;
2444                        };
2445                        let Some((bound_vars, assoc_item)) = BoundVarContext::supertrait_hrtb_vars(
2446                            self.tcx,
2447                            trait_def_id,
2448                            item_segment.ident,
2449                            ty::AssocTag::Fn,
2450                        ) else {
2451                            return;
2452                        };
2453                        (bound_vars, assoc_item.def_id, item_segment)
2454                    }
2455                    _ => return,
2456                }
2457            }
2458
2459            _ => return,
2460        };
2461
2462        // Append the early-bound vars on the function, and then the late-bound ones.
2463        // We actually turn type parameters into higher-ranked types here, but we
2464        // deny them later in HIR lowering.
2465        bound_vars.extend(
2466            self.tcx
2467                .generics_of(item_def_id)
2468                .own_params
2469                .iter()
2470                .map(|param| generic_param_def_as_bound_arg(param)),
2471        );
2472        bound_vars.extend(
2473            self.tcx.fn_sig(item_def_id).instantiate_identity().skip_norm_wip().bound_vars(),
2474        );
2475
2476        // SUBTLE: Stash the old bound vars onto the *item segment* before appending
2477        // the new bound vars. We do this because we need to know how many bound vars
2478        // are present on the binder explicitly (i.e. not return-type-notation vars)
2479        // to do bound var shifting correctly in HIR lowering.
2480        //
2481        // For example, in `where for<'a> <T as Trait<'a>>::method(..): Other`,
2482        // the `late_bound_vars` of the where clause predicate (i.e. this HIR ty's
2483        // parent) will include `'a` AND all the early- and late-bound vars of the
2484        // method. But when lowering the RTN type, we just want the list of vars
2485        // we used to resolve the trait ref. We explicitly stored those back onto
2486        // the item segment, since there's no other good place to put them.
2487        //
2488        // See where these vars are used in `HirTyLowerer::lower_ty_maybe_return_type_notation`.
2489        // And this is exercised in:
2490        // `tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.rs`.
2491        let existing_bound_vars = self.rbv.late_bound_vars.get_mut(&hir_id.local_id).unwrap();
2492        let existing_bound_vars_saved = existing_bound_vars.clone();
2493        existing_bound_vars.extend(bound_vars);
2494        self.record_late_bound_vars(item_segment.hir_id, existing_bound_vars_saved);
2495    }
2496
2497    /// Walk the generics of the item for a trait bound whose self type
2498    /// corresponds to the expected res, and return the trait def id.
2499    fn for_each_trait_bound_on_res(&self, expected_res: Res) -> impl Iterator<Item = DefId> {
2500        gen move {
2501            let mut scope = self.scope;
2502            loop {
2503                let hir_id = match *scope {
2504                    Scope::Binder { hir_id, .. } => Some(hir_id),
2505                    Scope::Root { opt_parent_item: Some(parent_def_id) } => {
2506                        Some(self.tcx.local_def_id_to_hir_id(parent_def_id))
2507                    }
2508                    Scope::Body { .. }
2509                    | Scope::ObjectLifetimeDefault { .. }
2510                    | Scope::Supertrait { .. }
2511                    | Scope::TraitRefBoundary { .. }
2512                    | Scope::LateBoundary { .. }
2513                    | Scope::Opaque { .. }
2514                    | Scope::Root { opt_parent_item: None } => None,
2515                };
2516
2517                if let Some(hir_id) = hir_id {
2518                    let node = self.tcx.hir_node(hir_id);
2519                    // If this is a `Self` bound in a trait, yield the trait itself.
2520                    // Specifically, we don't need to look at any supertraits since
2521                    // we already do that in `BoundVarContext::supertrait_hrtb_vars`.
2522                    if let Res::SelfTyParam { trait_: _ } = expected_res
2523                        && let hir::Node::Item(item) = node
2524                        && let hir::ItemKind::Trait { .. } = item.kind
2525                    {
2526                        // Yield the trait's def id. Supertraits will be
2527                        // elaborated from that.
2528                        yield item.owner_id.def_id.to_def_id();
2529                    } else if let Some(generics) = node.generics() {
2530                        for pred in generics.predicates {
2531                            let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
2532                                continue;
2533                            };
2534                            let hir::TyKind::Path(hir::QPath::Resolved(None, bounded_path)) =
2535                                pred.bounded_ty.kind
2536                            else {
2537                                continue;
2538                            };
2539                            // Match the expected res.
2540                            if bounded_path.res != expected_res {
2541                                continue;
2542                            }
2543                            for pred in pred.bounds {
2544                                match pred {
2545                                    hir::GenericBound::Trait(poly_trait_ref) => {
2546                                        if let Some(def_id) =
2547                                            poly_trait_ref.trait_ref.trait_def_id()
2548                                        {
2549                                            yield def_id;
2550                                        }
2551                                    }
2552                                    hir::GenericBound::Outlives(_)
2553                                    | hir::GenericBound::Use(_, _) => {}
2554                                }
2555                            }
2556                        }
2557                    }
2558                }
2559
2560                match *scope {
2561                    Scope::Binder { s, .. }
2562                    | Scope::Body { s, .. }
2563                    | Scope::ObjectLifetimeDefault { s, .. }
2564                    | Scope::Supertrait { s, .. }
2565                    | Scope::TraitRefBoundary { s }
2566                    | Scope::LateBoundary { s, .. }
2567                    | Scope::Opaque { s, .. } => {
2568                        scope = s;
2569                    }
2570                    Scope::Root { .. } => break,
2571                }
2572            }
2573        }
2574    }
2575}
2576
2577/// Detects late-bound lifetimes and inserts them into
2578/// `late_bound`.
2579///
2580/// A region declared on a fn is **late-bound** if:
2581/// - it is constrained by an argument type;
2582/// - it does not appear in a where-clause.
2583///
2584/// "Constrained" basically means that it appears in any type but
2585/// not amongst the inputs to a projection. In other words, `<&'a
2586/// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2587fn is_late_bound_map(
2588    tcx: TyCtxt<'_>,
2589    owner_id: hir::OwnerId,
2590) -> Option<&FxIndexSet<hir::ItemLocalId>> {
2591    let sig = tcx.hir_fn_sig_by_hir_id(owner_id.into())?;
2592    let generics = tcx.hir_get_generics(owner_id.def_id)?;
2593
2594    let mut late_bound = FxIndexSet::default();
2595
2596    let mut constrained_by_input = ConstrainedCollector { regions: Default::default(), tcx };
2597    for arg_ty in sig.decl.inputs {
2598        constrained_by_input.visit_ty_unambig(arg_ty);
2599    }
2600
2601    let mut appears_in_output =
2602        AllCollector { has_fully_capturing_opaque: false, regions: Default::default() };
2603    intravisit::walk_fn_ret_ty(&mut appears_in_output, &sig.decl.output);
2604    if appears_in_output.has_fully_capturing_opaque {
2605        appears_in_output.regions.extend(generics.params.iter().map(|param| param.def_id));
2606    }
2607
2608    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2608",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2608u32),
                        ::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);
2609
2610    // Walk the lifetimes that appear in where clauses.
2611    //
2612    // Subtle point: because we disallow nested bindings, we can just
2613    // ignore binders here and scrape up all names we see.
2614    let mut appears_in_where_clause =
2615        AllCollector { has_fully_capturing_opaque: true, regions: Default::default() };
2616    appears_in_where_clause.visit_generics(generics);
2617    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2617",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2617u32),
                        ::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);
2618
2619    // Late bound regions are those that:
2620    // - appear in the inputs
2621    // - do not appear in the where-clauses
2622    // - are not implicitly captured by `impl Trait`
2623    for param in generics.params {
2624        match param.kind {
2625            hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2626
2627            // Neither types nor consts are late-bound.
2628            hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
2629        }
2630
2631        // appears in the where clauses? early-bound.
2632        if appears_in_where_clause.regions.contains(&param.def_id) {
2633            continue;
2634        }
2635
2636        // does not appear in the inputs, but appears in the return type? early-bound.
2637        if !constrained_by_input.regions.contains(&param.def_id)
2638            && appears_in_output.regions.contains(&param.def_id)
2639        {
2640            continue;
2641        }
2642
2643        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2643",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2643u32),
                        ::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);
2644
2645        let inserted = late_bound.insert(param.hir_id.local_id);
2646        if !inserted {
    {
        ::core::panicking::panic_fmt(format_args!("visited lifetime {0:?} twice",
                param.def_id));
    }
};assert!(inserted, "visited lifetime {:?} twice", param.def_id);
2647    }
2648
2649    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2649",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2649u32),
                        ::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);
2650    return Some(tcx.arena.alloc(late_bound));
2651
2652    /// Visits a `ty::Ty` collecting information about what generic parameters are constrained.
2653    ///
2654    /// The visitor does not operate on `hir::Ty` so that it can be called on the rhs of a `type Alias<...> = ...;`
2655    /// which may live in a separate crate so there would not be any hir available. Instead we use the `type_of`
2656    /// query to obtain a `ty::Ty` which will be present even in cross crate scenarios. It also naturally
2657    /// handles cycle detection as we go through the query system.
2658    ///
2659    /// This is necessary in the first place for the following case:
2660    /// ```rust,ignore (pseudo-Rust)
2661    /// type Alias<'a, T> = <T as Trait<'a>>::Assoc;
2662    /// fn foo<'a>(_: Alias<'a, ()>) -> Alias<'a, ()> { ... }
2663    /// ```
2664    ///
2665    /// If we conservatively considered `'a` unconstrained then we could break users who had written code before
2666    /// we started correctly handling aliases. If we considered `'a` constrained then it would become late bound
2667    /// causing an error during HIR ty lowering as the `'a` is not constrained by the input type `<() as Trait<'a>>::Assoc`
2668    /// but appears in the output type `<() as Trait<'a>>::Assoc`.
2669    ///
2670    /// We must therefore "look into" the `Alias` to see whether we should consider `'a` constrained or not.
2671    ///
2672    /// See #100508 #85533 #47511 for additional context
2673    struct ConstrainedCollectorPostHirTyLowering {
2674        arg_is_constrained: Box<[bool]>,
2675    }
2676
2677    use ty::Ty;
2678    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ConstrainedCollectorPostHirTyLowering {
2679        fn visit_ty(&mut self, t: Ty<'tcx>) {
2680            match t.kind() {
2681                ty::Param(param_ty) => {
2682                    self.arg_is_constrained[param_ty.index as usize] = true;
2683                }
2684                ty::Alias(
2685                    _,
2686                    ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. },
2687                ) => return,
2688                _ => (),
2689            }
2690            t.super_visit_with(self)
2691        }
2692
2693        fn visit_const(&mut self, _: ty::Const<'tcx>) {}
2694
2695        fn visit_region(&mut self, r: ty::Region<'tcx>) {
2696            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2696",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2696u32),
                        ::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());
2697            if let ty::RegionKind::ReEarlyParam(region) = r.kind() {
2698                self.arg_is_constrained[region.index as usize] = true;
2699            }
2700        }
2701    }
2702
2703    struct ConstrainedCollector<'tcx> {
2704        tcx: TyCtxt<'tcx>,
2705        regions: FxHashSet<LocalDefId>,
2706    }
2707
2708    impl<'v> Visitor<'v> for ConstrainedCollector<'_> {
2709        fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
2710            match ty.kind {
2711                hir::TyKind::Path(
2712                    hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
2713                ) => {
2714                    // ignore lifetimes appearing in associated type
2715                    // projections, as they are not *constrained*
2716                    // (defined above)
2717                }
2718
2719                hir::TyKind::Path(hir::QPath::Resolved(
2720                    None,
2721                    hir::Path { res: Res::Def(DefKind::TyAlias, alias_def), segments, span },
2722                )) => {
2723                    // See comments on `ConstrainedCollectorPostHirTyLowering` for why this arm does not
2724                    // just consider args to be unconstrained.
2725                    let generics = self.tcx.generics_of(*alias_def);
2726                    let mut walker = ConstrainedCollectorPostHirTyLowering {
2727                        arg_is_constrained: ::alloc::vec::from_elem(false, generics.own_params.len())vec![false; generics.own_params.len()]
2728                            .into_boxed_slice(),
2729                    };
2730                    walker.visit_ty(
2731                        self.tcx.type_of(*alias_def).instantiate_identity().skip_norm_wip(),
2732                    );
2733
2734                    match segments.last() {
2735                        Some(hir::PathSegment { args: Some(args), .. }) => {
2736                            let tcx = self.tcx;
2737                            for constrained_arg in
2738                                args.args.iter().enumerate().flat_map(|(n, arg)| {
2739                                    match walker.arg_is_constrained.get(n) {
2740                                        Some(true) => Some(arg),
2741                                        Some(false) => None,
2742                                        None => {
2743                                            tcx.dcx().span_delayed_bug(
2744                                                *span,
2745                                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Incorrect generic arg count for alias {0:?}",
                alias_def))
    })format!(
2746                                                    "Incorrect generic arg count for alias {alias_def:?}"
2747                                                ),
2748                                            );
2749                                            None
2750                                        }
2751                                    }
2752                                })
2753                            {
2754                                self.visit_generic_arg(constrained_arg);
2755                            }
2756                        }
2757                        Some(_) => (),
2758                        None => bug_impl(None, format_args!("Path with no segments or self type"),
    Location::caller())bug!("Path with no segments or self type"),
2759                    }
2760                }
2761
2762                hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
2763                    // consider only the lifetimes on the final
2764                    // segment; I am not sure it's even currently
2765                    // valid to have them elsewhere, but even if it
2766                    // is, those would be potentially inputs to
2767                    // projections
2768                    if let Some(last_segment) = path.segments.last() {
2769                        self.visit_path_segment(last_segment);
2770                    }
2771                }
2772
2773                _ => {
2774                    intravisit::walk_ty(self, ty);
2775                }
2776            }
2777        }
2778
2779        fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2780            if let hir::LifetimeKind::Param(def_id) = lifetime_ref.kind {
2781                self.regions.insert(def_id);
2782            }
2783        }
2784    }
2785
2786    struct AllCollector {
2787        has_fully_capturing_opaque: bool,
2788        regions: FxHashSet<LocalDefId>,
2789    }
2790
2791    impl<'tcx> Visitor<'tcx> for AllCollector {
2792        fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2793            if let hir::LifetimeKind::Param(def_id) = lifetime_ref.kind {
2794                self.regions.insert(def_id);
2795            }
2796        }
2797
2798        fn visit_opaque_ty(&mut self, opaque: &'tcx hir::OpaqueTy<'tcx>) {
2799            if !self.has_fully_capturing_opaque {
2800                self.has_fully_capturing_opaque = opaque_captures_all_in_scope_lifetimes(opaque);
2801            }
2802            intravisit::walk_opaque_ty(self, opaque);
2803        }
2804    }
2805}
2806
2807fn deny_non_region_late_bound(
2808    tcx: TyCtxt<'_>,
2809    bound_vars: &mut FxIndexMap<LocalDefId, ResolvedArg>,
2810    where_: &str,
2811) {
2812    let mut first = true;
2813
2814    for (var, arg) in bound_vars {
2815        let Node::GenericParam(param) = tcx.hir_node_by_def_id(*var) else {
2816            bug_impl(Some(tcx.def_span(*var)),
    format_args!("expected bound-var def-id to resolve to param"),
    Location::caller());span_bug!(tcx.def_span(*var), "expected bound-var def-id to resolve to param");
2817        };
2818
2819        let what = match param.kind {
2820            hir::GenericParamKind::Type { .. } => "type",
2821            hir::GenericParamKind::Const { .. } => "const",
2822            hir::GenericParamKind::Lifetime { .. } => continue,
2823        };
2824
2825        let diag = tcx.dcx().struct_span_err(
2826            param.span,
2827            ::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_}"),
2828        );
2829
2830        let guar = diag.emit_unless_delay(!tcx.features().non_lifetime_binders() || !first);
2831
2832        first = false;
2833        *arg = ResolvedArg::Error(guar);
2834    }
2835}
2836
2837/// A path segment index.
2838#[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)]
2839struct SegIdx(usize);
2840
2841impl SegIdx {
2842    fn reverse(self, segments: &[hir::PathSegment<'_>]) -> RevSegIdx {
2843        let SegIdx(seg_idx) = self;
2844        RevSegIdx(segments.len() - seg_idx - 1)
2845    }
2846}
2847
2848/// A reversed path segment index.
2849///
2850/// E.g., for qualified path `<() as path::to::TraitRef<…>>::AssocTy<…>` the mapping from reversed
2851/// index to path segment would look like 3 ↦ `path`, 2 ↦ `to`, 1 ↦ `TraitRef<…>`, 0 ↦ `AssocTy<…>`.
2852struct RevSegIdx(usize);
2853
2854impl RevSegIdx {
2855    fn reverse(self, segments: &[hir::PathSegment<'_>]) -> SegIdx {
2856        let RevSegIdx(rev_seg_idx) = self;
2857        SegIdx(segments.len() - rev_seg_idx - 1)
2858    }
2859}