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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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, .. }) => {
                    self.visit_early(item.hir_id(), generics,
                        |this| intravisit::walk_item(this, item));
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
622    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
623        if let hir::ItemKind::Impl(impl_) = item.kind
624            && let Some(of_trait) = impl_.of_trait
625        {
626            self.record_late_bound_vars(of_trait.trait_ref.hir_ref_id, Vec::default());
627        }
628        match item.kind {
629            hir::ItemKind::Fn { generics, .. } => {
630                self.visit_early_late(item.hir_id(), generics, |this| {
631                    intravisit::walk_item(this, item);
632                });
633            }
634
635            hir::ItemKind::ExternCrate(..)
636            | hir::ItemKind::Use(..)
637            | hir::ItemKind::Macro(..)
638            | hir::ItemKind::Mod(..)
639            | hir::ItemKind::ForeignMod { .. }
640            | hir::ItemKind::Static(..)
641            | hir::ItemKind::GlobalAsm { .. } => {
642                // These sorts of items have no lifetime parameters at all.
643                intravisit::walk_item(self, item);
644            }
645            hir::ItemKind::TyAlias(_, generics, _)
646            | hir::ItemKind::Const(_, generics, _, _)
647            | hir::ItemKind::Enum(_, generics, _)
648            | hir::ItemKind::Struct(_, generics, _)
649            | hir::ItemKind::Union(_, generics, _)
650            | hir::ItemKind::Trait { generics, .. }
651            | hir::ItemKind::TraitAlias(_, _, generics, ..)
652            | hir::ItemKind::Impl(hir::Impl { generics, .. }) => {
653                // 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(errors::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(errors::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("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(&["ty"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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 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("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", "bounds",
                                                            "lifetime"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("TraitObject")
                                                                as &dyn Value)),
                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&bounds) as
                                                                &dyn Value)),
                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&lifetime)
                                                                as &dyn 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).cloned(),
                            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 does not write *anything*, we
793                        // use the object lifetime defaulting
794                        // rules. So e.g., `Box<dyn Debug>` becomes
795                        // `Box<dyn Debug + 'static>`.
796                        self.resolve_object_lifetime_default(&*lifetime)
797                    }
798                    LifetimeKind::Infer => {
799                        // If the user writes `'_`, we use the *ordinary* elision
800                        // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
801                        // resolved the same as the `'_` in `&'_ Foo`.
802                        //
803                        // cc #48468
804                    }
805                    LifetimeKind::Param(..) | LifetimeKind::Static => {
806                        // If the user wrote an explicit name, use that.
807                        self.visit_lifetime(&*lifetime);
808                    }
809                    LifetimeKind::Error(..) => {}
810                }
811            }
812            hir::TyKind::Ref(lifetime_ref, ref mt) => {
813                self.visit_lifetime(lifetime_ref);
814                let scope = Scope::ObjectLifetimeDefault {
815                    lifetime: self.rbv.defs.get(&lifetime_ref.hir_id.local_id).cloned(),
816                    s: self.scope,
817                };
818                self.with(scope, |this| this.visit_ty_unambig(mt.ty));
819            }
820            hir::TyKind::TraitAscription(bounds) => {
821                let scope = Scope::TraitRefBoundary { s: self.scope };
822                self.with(scope, |this| {
823                    let scope = Scope::LateBoundary {
824                        s: this.scope,
825                        what: "`impl Trait` in binding",
826                        deny_late_regions: true,
827                    };
828                    this.with(scope, |this| {
829                        for bound in bounds {
830                            this.visit_param_bound(bound);
831                        }
832                    })
833                });
834            }
835            _ => intravisit::walk_ty(self, ty),
836        }
837    }
838
839    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_pattern_type_pattern",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(839u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["p"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&p)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        { intravisit::walk_ty_pat(self, p) }
    }
}#[instrument(level = "debug", skip(self))]
840    fn visit_pattern_type_pattern(&mut self, p: &'tcx hir::TyPat<'tcx>) {
841        intravisit::walk_ty_pat(self, p)
842    }
843
844    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_trait_item",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(844u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["trait_item"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_item)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            use self::hir::ImplItemKind::*;
            match impl_item.kind {
                Fn(..) =>
                    self.visit_early_late(impl_item.hir_id(),
                        impl_item.generics,
                        |this| { intravisit::walk_impl_item(this, impl_item) }),
                Type(ty) =>
                    self.visit_early(impl_item.hir_id(), impl_item.generics,
                        |this|
                            {
                                this.visit_generics(impl_item.generics);
                                this.visit_ty_unambig(ty);
                            }),
                Const(_, _) =>
                    self.visit_early(impl_item.hir_id(), impl_item.generics,
                        |this| { intravisit::walk_impl_item(this, impl_item) }),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
871    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
872        use self::hir::ImplItemKind::*;
873        match impl_item.kind {
874            Fn(..) => self.visit_early_late(impl_item.hir_id(), impl_item.generics, |this| {
875                intravisit::walk_impl_item(this, impl_item)
876            }),
877            Type(ty) => self.visit_early(impl_item.hir_id(), impl_item.generics, |this| {
878                this.visit_generics(impl_item.generics);
879                this.visit_ty_unambig(ty);
880            }),
881            Const(_, _) => self.visit_early(impl_item.hir_id(), impl_item.generics, |this| {
882                intravisit::walk_impl_item(this, impl_item)
883            }),
884        }
885    }
886
887    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_lifetime",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(887u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime_ref"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match lifetime_ref.kind {
                hir::LifetimeKind::Static => {
                    self.insert_lifetime(lifetime_ref,
                        ResolvedArg::StaticLifetime)
                }
                hir::LifetimeKind::Param(param_def_id) => {
                    self.resolve_lifetime_ref(param_def_id, lifetime_ref)
                }
                hir::LifetimeKind::Error(guar) => {
                    self.insert_lifetime(lifetime_ref, ResolvedArg::Error(guar))
                }
                hir::LifetimeKind::ImplicitObjectLifetimeDefault |
                    hir::LifetimeKind::Infer => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
888    fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
889        match lifetime_ref.kind {
890            hir::LifetimeKind::Static => {
891                self.insert_lifetime(lifetime_ref, ResolvedArg::StaticLifetime)
892            }
893            hir::LifetimeKind::Param(param_def_id) => {
894                self.resolve_lifetime_ref(param_def_id, lifetime_ref)
895            }
896            // Keep track of lifetimes about which errors have already been reported
897            hir::LifetimeKind::Error(guar) => {
898                self.insert_lifetime(lifetime_ref, ResolvedArg::Error(guar))
899            }
900            // Those will be resolved by typechecking.
901            hir::LifetimeKind::ImplicitObjectLifetimeDefault | hir::LifetimeKind::Infer => {}
902        }
903    }
904
905    fn visit_path(&mut self, path: &hir::Path<'tcx>, hir_id: HirId) {
906        for (i, segment) in path.segments.iter().enumerate() {
907            let depth = path.segments.len() - i - 1;
908            if let Some(args) = segment.args {
909                self.visit_segment_args(path.res, depth, args);
910            }
911        }
912        if let Res::Def(DefKind::TyParam | DefKind::ConstParam, param_def_id) = path.res {
913            self.resolve_type_ref(param_def_id.expect_local(), hir_id);
914        }
915    }
916
917    fn visit_fn(
918        &mut self,
919        fk: intravisit::FnKind<'tcx>,
920        fd: &'tcx hir::FnDecl<'tcx>,
921        body_id: hir::BodyId,
922        _: Span,
923        def_id: LocalDefId,
924    ) {
925        let output = match fd.output {
926            hir::FnRetTy::DefaultReturn(_) => None,
927            hir::FnRetTy::Return(ty) => Some(ty),
928        };
929        if let Some(ty) = output
930            && let hir::TyKind::InferDelegation(hir::InferDelegation::Sig(sig_id, _)) = ty.kind
931        {
932            let bound_vars: Vec<_> =
933                self.tcx.fn_sig(sig_id).skip_binder().bound_vars().iter().collect();
934            let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
935            self.rbv.late_bound_vars.insert(hir_id.local_id, bound_vars);
936        }
937        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));
938        intravisit::walk_fn_kind(self, fk);
939        self.visit_nested_body(body_id)
940    }
941
942    fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
943        let scope = Scope::TraitRefBoundary { s: self.scope };
944        self.with(scope, |this| {
945            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);
946            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);
947        })
948    }
949
950    fn visit_where_predicate(&mut self, predicate: &'tcx hir::WherePredicate<'tcx>) {
951        let hir_id = predicate.hir_id;
952        match predicate.kind {
953            &hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
954                bounded_ty,
955                bounds,
956                bound_generic_params,
957                origin,
958                ..
959            }) => {
960                let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) =
961                    bound_generic_params
962                        .iter()
963                        .enumerate()
964                        .map(|(late_bound_idx, param)| {
965                            (
966                                (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),
967                                late_arg_as_bound_arg(param),
968                            )
969                        })
970                        .unzip();
971
972                self.record_late_bound_vars(hir_id, binders);
973
974                // If this is an RTN type in the self type, then append those to the binder.
975                self.try_append_return_type_notation_params(hir_id, bounded_ty);
976
977                // Even if there are no lifetimes defined here, we still wrap it in a binder
978                // scope. If there happens to be a nested poly trait ref (an error), that
979                // will be `Concatenating` anyways, so we don't have to worry about the depth
980                // being wrong.
981                let scope = Scope::Binder {
982                    hir_id,
983                    bound_vars,
984                    s: self.scope,
985                    scope_type: BinderScopeType::Normal,
986                    where_bound_origin: Some(origin),
987                };
988                self.with(scope, |this| {
989                    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);
990                    this.visit_ty_unambig(bounded_ty);
991                    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);
992                })
993            }
994            &hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
995                lifetime,
996                bounds,
997                ..
998            }) => {
999                self.visit_lifetime(lifetime);
1000                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);
1001            }
1002            &hir::WherePredicateKind::EqPredicate(hir::WhereEqPredicate {
1003                lhs_ty, rhs_ty, ..
1004            }) => {
1005                self.visit_ty_unambig(lhs_ty);
1006                self.visit_ty_unambig(rhs_ty);
1007            }
1008        }
1009    }
1010
1011    fn visit_poly_trait_ref(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) {
1012        self.visit_poly_trait_ref_inner(trait_ref, NonLifetimeBinderAllowed::Allow);
1013    }
1014
1015    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
1016        self.with(
1017            Scope::LateBoundary { s: self.scope, what: "constant", deny_late_regions: true },
1018            |this| {
1019                intravisit::walk_anon_const(this, c);
1020            },
1021        );
1022    }
1023
1024    fn visit_generic_param(&mut self, p: &'tcx GenericParam<'tcx>) {
1025        match p.kind {
1026            GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1027                self.resolve_type_ref(p.def_id, p.hir_id);
1028            }
1029            GenericParamKind::Lifetime { .. } => {
1030                // No need to resolve lifetime params, we don't use them for things
1031                // like implicit `?Sized` or const-param-has-ty predicates.
1032            }
1033        }
1034
1035        match p.kind {
1036            GenericParamKind::Lifetime { .. } => {}
1037            GenericParamKind::Type { default, .. } => {
1038                if let Some(ty) = default {
1039                    self.visit_ty_unambig(ty);
1040                }
1041            }
1042            GenericParamKind::Const { ty, default, .. } => {
1043                self.visit_ty_unambig(ty);
1044                if let Some(default) = default {
1045                    self.visit_const_arg_unambig(default);
1046                }
1047            }
1048        }
1049    }
1050}
1051
1052fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: LocalDefId) -> ObjectLifetimeDefault {
1053    if true {
    match (&tcx.def_kind(param_def_id), &DefKind::TyParam) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(tcx.def_kind(param_def_id), DefKind::TyParam);
1054    let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(param_def_id) else {
1055        ::rustc_middle::util::bug::bug_fmt(format_args!("expected GenericParam for object_lifetime_default"));bug!("expected GenericParam for object_lifetime_default");
1056    };
1057    match param.source {
1058        hir::GenericParamSource::Generics => {
1059            let parent_def_id = tcx.local_parent(param_def_id);
1060            let generics = tcx.hir_get_generics(parent_def_id).unwrap();
1061            let param_hir_id = tcx.local_def_id_to_hir_id(param_def_id);
1062            let param = generics.params.iter().find(|p| p.hir_id == param_hir_id).unwrap();
1063
1064            // Scan the bounds and where-clauses on parameters to extract bounds
1065            // of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1066            // for each type parameter.
1067            match param.kind {
1068                GenericParamKind::Type { .. } => {
1069                    let mut set = Set1::Empty;
1070
1071                    // Look for `type: ...` where clauses.
1072                    for bound in generics.bounds_for_param(param_def_id) {
1073                        // Ignore `for<'a> type: ...` as they can change what
1074                        // lifetimes mean (although we could "just" handle it).
1075                        if !bound.bound_generic_params.is_empty() {
1076                            continue;
1077                        }
1078
1079                        for bound in bound.bounds {
1080                            if let hir::GenericBound::Outlives(lifetime) = bound {
1081                                set.insert(lifetime.kind);
1082                            }
1083                        }
1084                    }
1085
1086                    match set {
1087                        Set1::Empty => ObjectLifetimeDefault::Empty,
1088                        Set1::One(hir::LifetimeKind::Static) => ObjectLifetimeDefault::Static,
1089                        Set1::One(hir::LifetimeKind::Param(param_def_id)) => {
1090                            ObjectLifetimeDefault::Param(param_def_id.to_def_id())
1091                        }
1092                        _ => ObjectLifetimeDefault::Ambiguous,
1093                    }
1094                }
1095                _ => {
1096                    ::rustc_middle::util::bug::bug_fmt(format_args!("object_lifetime_default_raw must only be called on a type parameter"))bug!("object_lifetime_default_raw must only be called on a type parameter")
1097                }
1098            }
1099        }
1100        hir::GenericParamSource::Binder => ObjectLifetimeDefault::Empty,
1101    }
1102}
1103
1104impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
1105    fn with<F>(&mut self, wrap_scope: Scope<'_, 'tcx>, f: F)
1106    where
1107        F: for<'b> FnOnce(&mut BoundVarContext<'b, 'tcx>),
1108    {
1109        let BoundVarContext { tcx, rbv, disambiguators, .. } = self;
1110        let nested_errors = RefCell::new(self.opaque_capture_errors.borrow_mut().take());
1111        let mut this = BoundVarContext {
1112            tcx: *tcx,
1113            rbv,
1114            disambiguators,
1115            scope: &wrap_scope,
1116            opaque_capture_errors: nested_errors,
1117        };
1118        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("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(1118u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&["scope"],
                            ::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};
                    let mut iter = meta.fields().iter();
                    meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                        ::tracing::__macro_support::Option::Some(&debug(&this.scope.debug_truncated())
                                                as &dyn Value))])
                })
    } else {
        let span =
            ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
        {};
        span
    }
}debug_span!("scope", scope = ?this.scope.debug_truncated());
1119        {
1120            let _enter = span.enter();
1121            f(&mut this);
1122        }
1123        *self.opaque_capture_errors.borrow_mut() = this.opaque_capture_errors.into_inner();
1124    }
1125
1126    fn record_late_bound_vars(&mut self, hir_id: HirId, binder: Vec<ty::BoundVariableKind<'tcx>>) {
1127        if let Some(old) = self.rbv.late_bound_vars.insert(hir_id.local_id, binder) {
1128            ::rustc_middle::util::bug::bug_fmt(format_args!("overwrote bound vars for {1:?}:\nold={2:?}\nnew={0:?}",
        self.rbv.late_bound_vars[&hir_id.local_id], hir_id, old))bug!(
1129                "overwrote bound vars for {hir_id:?}:\nold={old:?}\nnew={:?}",
1130                self.rbv.late_bound_vars[&hir_id.local_id]
1131            )
1132        }
1133    }
1134
1135    /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1136    ///
1137    /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1138    /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1139    /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1140    ///
1141    /// For example:
1142    ///
1143    ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
1144    ///
1145    /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1146    /// lifetimes may be interspersed together.
1147    ///
1148    /// If early bound lifetimes are present, we separate them into their own list (and likewise
1149    /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1150    /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1151    /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
1152    /// ordering is not important there.
1153    fn visit_early_late<F>(&mut self, hir_id: HirId, generics: &'tcx hir::Generics<'tcx>, walk: F)
1154    where
1155        F: for<'b, 'c> FnOnce(&'b mut BoundVarContext<'c, 'tcx>),
1156    {
1157        let mut named_late_bound_vars = 0;
1158        let bound_vars: FxIndexMap<LocalDefId, ResolvedArg> = generics
1159            .params
1160            .iter()
1161            .map(|param| {
1162                (
1163                    param.def_id,
1164                    match param.kind {
1165                        GenericParamKind::Lifetime { .. } => {
1166                            if self.tcx.is_late_bound(param.hir_id) {
1167                                let late_bound_idx = named_late_bound_vars;
1168                                named_late_bound_vars += 1;
1169                                ResolvedArg::late(late_bound_idx, param)
1170                            } else {
1171                                ResolvedArg::early(param)
1172                            }
1173                        }
1174                        GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1175                            ResolvedArg::early(param)
1176                        }
1177                    },
1178                )
1179            })
1180            .collect();
1181
1182        let binders: Vec<_> = generics
1183            .params
1184            .iter()
1185            .filter(|param| {
1186                #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Lifetime { .. })
1187                    && self.tcx.is_late_bound(param.hir_id)
1188            })
1189            .map(|param| late_arg_as_bound_arg(param))
1190            .collect();
1191        self.record_late_bound_vars(hir_id, binders);
1192        let scope = Scope::Binder {
1193            hir_id,
1194            bound_vars,
1195            s: self.scope,
1196            scope_type: BinderScopeType::Normal,
1197            where_bound_origin: None,
1198        };
1199        self.with(scope, walk);
1200    }
1201
1202    fn visit_early<F>(&mut self, hir_id: HirId, generics: &'tcx hir::Generics<'tcx>, walk: F)
1203    where
1204        F: for<'b, 'c> FnOnce(&'b mut BoundVarContext<'c, 'tcx>),
1205    {
1206        let bound_vars =
1207            generics.params.iter().map(|param| (param.def_id, ResolvedArg::early(param))).collect();
1208        self.record_late_bound_vars(hir_id, ::alloc::vec::Vec::new()vec![]);
1209        let scope = Scope::Binder {
1210            hir_id,
1211            bound_vars,
1212            s: self.scope,
1213            scope_type: BinderScopeType::Normal,
1214            where_bound_origin: None,
1215        };
1216        self.with(scope, |this| {
1217            let scope = Scope::TraitRefBoundary { s: this.scope };
1218            this.with(scope, walk)
1219        });
1220    }
1221
1222    #[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("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1222u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["region_def_id",
                                                    "lifetime_ref"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&region_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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::errors::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(errors::CannotCaptureLateBound::Lifetime {
                                        use_span,
                                        def_span,
                                        what,
                                    })
                            }
                            kind =>
                                ::rustc_middle::util::bug::span_bug_fmt(use_span,
                                    format_args!("did not expect to resolve lifetime to {0}",
                                        kind.descr(param_def_id.to_def_id()))),
                        };
                    def = ResolvedArg::Error(guar);
                } else if let Some(body_id) = outermost_body {
                    let fn_id = self.tcx.hir_body_owner(body_id);
                    match self.tcx.hir_node(fn_id) {
                        Node::Item(hir::Item {
                            owner_id, kind: hir::ItemKind::Fn { .. }, .. }) |
                            Node::TraitItem(hir::TraitItem {
                            owner_id, kind: hir::TraitItemKind::Fn(..), .. }) |
                            Node::ImplItem(hir::ImplItem {
                            owner_id, kind: hir::ImplItemKind::Fn(..), .. }) => {
                            def = ResolvedArg::Free(owner_id.def_id, def.id().unwrap());
                        }
                        Node::Expr(hir::Expr {
                            kind: hir::ExprKind::Closure(closure), .. }) => {
                            def = ResolvedArg::Free(closure.def_id, def.id().unwrap());
                        }
                        _ => {}
                    }
                }
                self.insert_lifetime(lifetime_ref, def);
                return;
            }
            let mut scope = self.scope;
            loop {
                match *scope {
                    Scope::Binder {
                        where_bound_origin: Some(hir::PredicateOrigin::ImplTrait),
                        .. } => {
                        self.tcx.dcx().emit_err(errors::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))]
1223    fn resolve_lifetime_ref(
1224        &mut self,
1225        region_def_id: LocalDefId,
1226        lifetime_ref: &'tcx hir::Lifetime,
1227    ) {
1228        // Walk up the scope chain, tracking the number of fn scopes
1229        // that we pass through, until we find a lifetime with the
1230        // given name or we run out of scopes.
1231        // search.
1232        let mut late_depth = 0;
1233        let mut scope = self.scope;
1234        let mut outermost_body = None;
1235        let mut crossed_late_boundary = None;
1236        let mut opaque_capture_scopes = vec![];
1237        let result = loop {
1238            match *scope {
1239                Scope::Body { id, s } => {
1240                    outermost_body = Some(id);
1241                    scope = s;
1242                }
1243
1244                Scope::Root { opt_parent_item } => {
1245                    if let Some(parent_item) = opt_parent_item
1246                        && let parent_generics = self.tcx.generics_of(parent_item)
1247                        && parent_generics
1248                            .param_def_id_to_index(self.tcx, region_def_id.to_def_id())
1249                            .is_some()
1250                    {
1251                        break Some(ResolvedArg::EarlyBound(region_def_id));
1252                    }
1253                    break None;
1254                }
1255
1256                Scope::Binder { ref bound_vars, scope_type, s, where_bound_origin, .. } => {
1257                    if let Some(&def) = bound_vars.get(&region_def_id) {
1258                        break Some(def.shifted(late_depth));
1259                    }
1260                    match scope_type {
1261                        BinderScopeType::Normal => late_depth += 1,
1262                        BinderScopeType::Concatenating => {}
1263                    }
1264                    // Fresh lifetimes in APIT used to be allowed in async fns and forbidden in
1265                    // regular fns.
1266                    if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin
1267                        && let hir::LifetimeKind::Param(param_id) = lifetime_ref.kind
1268                        && let Some(generics) =
1269                            self.tcx.hir_get_generics(self.tcx.local_parent(param_id))
1270                        && let Some(param) = generics.params.iter().find(|p| p.def_id == param_id)
1271                        && param.is_elided_lifetime()
1272                        && !self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id).is_async()
1273                        && !self.tcx.features().anonymous_lifetime_in_impl_trait()
1274                    {
1275                        let mut diag: rustc_errors::Diag<'_> = rustc_session::errors::feature_err(
1276                            &self.tcx.sess,
1277                            sym::anonymous_lifetime_in_impl_trait,
1278                            lifetime_ref.ident.span,
1279                            "anonymous lifetimes in `impl Trait` are unstable",
1280                        );
1281
1282                        if let Some(generics) =
1283                            self.tcx.hir_get_generics(lifetime_ref.hir_id.owner.def_id)
1284                        {
1285                            let new_param_sugg =
1286                                if let Some(span) = generics.span_for_lifetime_suggestion() {
1287                                    (span, "'a, ".to_owned())
1288                                } else {
1289                                    (generics.span, "<'a>".to_owned())
1290                                };
1291
1292                            let lifetime_sugg = lifetime_ref.suggestion("'a");
1293                            let suggestions = vec![lifetime_sugg, new_param_sugg];
1294
1295                            diag.span_label(
1296                                lifetime_ref.ident.span,
1297                                "expected named lifetime parameter",
1298                            );
1299                            diag.multipart_suggestion(
1300                                "consider introducing a named lifetime parameter",
1301                                suggestions,
1302                                rustc_errors::Applicability::MaybeIncorrect,
1303                            );
1304                        }
1305
1306                        diag.emit();
1307                        return;
1308                    }
1309                    scope = s;
1310                }
1311
1312                Scope::Opaque { captures, def_id, s } => {
1313                    opaque_capture_scopes.push((def_id, captures));
1314                    late_depth = 0;
1315                    scope = s;
1316                }
1317
1318                Scope::ObjectLifetimeDefault { s, .. }
1319                | Scope::Supertrait { s, .. }
1320                | Scope::TraitRefBoundary { s, .. } => {
1321                    scope = s;
1322                }
1323
1324                Scope::LateBoundary { s, what, deny_late_regions } => {
1325                    if deny_late_regions {
1326                        crossed_late_boundary = Some(what);
1327                    }
1328                    scope = s;
1329                }
1330            }
1331        };
1332
1333        if let Some(mut def) = result {
1334            def = self.remap_opaque_captures(&opaque_capture_scopes, def, lifetime_ref.ident);
1335
1336            if let ResolvedArg::EarlyBound(..) = def {
1337                // Do not free early-bound regions, only late-bound ones.
1338            } else if let ResolvedArg::LateBound(_, _, param_def_id) = def
1339                && let Some(what) = crossed_late_boundary
1340            {
1341                let use_span = lifetime_ref.ident.span;
1342                let def_span = self.tcx.def_span(param_def_id);
1343                let guar = match self.tcx.def_kind(param_def_id) {
1344                    DefKind::LifetimeParam => {
1345                        self.tcx.dcx().emit_err(errors::CannotCaptureLateBound::Lifetime {
1346                            use_span,
1347                            def_span,
1348                            what,
1349                        })
1350                    }
1351                    kind => span_bug!(
1352                        use_span,
1353                        "did not expect to resolve lifetime to {}",
1354                        kind.descr(param_def_id.to_def_id())
1355                    ),
1356                };
1357                def = ResolvedArg::Error(guar);
1358            } else if let Some(body_id) = outermost_body {
1359                let fn_id = self.tcx.hir_body_owner(body_id);
1360                match self.tcx.hir_node(fn_id) {
1361                    Node::Item(hir::Item { owner_id, kind: hir::ItemKind::Fn { .. }, .. })
1362                    | Node::TraitItem(hir::TraitItem {
1363                        owner_id,
1364                        kind: hir::TraitItemKind::Fn(..),
1365                        ..
1366                    })
1367                    | Node::ImplItem(hir::ImplItem {
1368                        owner_id,
1369                        kind: hir::ImplItemKind::Fn(..),
1370                        ..
1371                    }) => {
1372                        def = ResolvedArg::Free(owner_id.def_id, def.id().unwrap());
1373                    }
1374                    Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) => {
1375                        def = ResolvedArg::Free(closure.def_id, def.id().unwrap());
1376                    }
1377                    _ => {}
1378                }
1379            }
1380
1381            self.insert_lifetime(lifetime_ref, def);
1382            return;
1383        }
1384
1385        // We may fail to resolve higher-ranked lifetimes that are mentioned by APIT.
1386        // AST-based resolution does not care for impl-trait desugaring, which are the
1387        // responsibility of lowering. This may create a mismatch between the resolution
1388        // AST found (`region_def_id`) which points to HRTB, and what HIR allows.
1389        // ```
1390        // fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {}
1391        // ```
1392        //
1393        // In such case, walk back the binders to diagnose it properly.
1394        let mut scope = self.scope;
1395        loop {
1396            match *scope {
1397                Scope::Binder {
1398                    where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), ..
1399                } => {
1400                    self.tcx.dcx().emit_err(errors::LateBoundInApit::Lifetime {
1401                        span: lifetime_ref.ident.span,
1402                        param_span: self.tcx.def_span(region_def_id),
1403                    });
1404                    return;
1405                }
1406                Scope::Root { .. } => break,
1407                Scope::Binder { s, .. }
1408                | Scope::Body { s, .. }
1409                | Scope::Opaque { s, .. }
1410                | Scope::ObjectLifetimeDefault { s, .. }
1411                | Scope::Supertrait { s, .. }
1412                | Scope::TraitRefBoundary { s, .. }
1413                | Scope::LateBoundary { s, .. } => {
1414                    scope = s;
1415                }
1416            }
1417        }
1418
1419        self.tcx.dcx().span_delayed_bug(
1420            lifetime_ref.ident.span,
1421            format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
1422        );
1423    }
1424
1425    /// Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
1426    /// and ban them. Type variables instantiated inside binders aren't
1427    /// well-supported at the moment, so this doesn't work.
1428    /// In the future, this should be fixed and this error should be removed.
1429    fn check_lifetime_is_capturable(
1430        &self,
1431        opaque_def_id: LocalDefId,
1432        lifetime: ResolvedArg,
1433        capture_span: Span,
1434    ) -> Result<(), ErrorGuaranteed> {
1435        let ResolvedArg::LateBound(_, _, lifetime_def_id) = lifetime else { return Ok(()) };
1436        let lifetime_hir_id = self.tcx.local_def_id_to_hir_id(lifetime_def_id);
1437        let bad_place = match self.tcx.hir_node(self.tcx.parent_hir_id(lifetime_hir_id)) {
1438            // Opaques do not declare their own lifetimes, so if a lifetime comes from an opaque
1439            // it must be a reified late-bound lifetime from a trait goal.
1440            hir::Node::OpaqueTy(_) => "higher-ranked lifetime from outer `impl Trait`",
1441            // Other items are fine.
1442            hir::Node::Item(_) | hir::Node::TraitItem(_) | hir::Node::ImplItem(_) => return Ok(()),
1443            hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(_), .. }) => {
1444                "higher-ranked lifetime from function pointer"
1445            }
1446            hir::Node::Ty(hir::Ty { kind: hir::TyKind::TraitObject(..), .. }) => {
1447                "higher-ranked lifetime from `dyn` type"
1448            }
1449            _ => "higher-ranked lifetime",
1450        };
1451
1452        let decl_span = self.tcx.def_span(lifetime_def_id);
1453        let opaque_span = self.tcx.def_span(opaque_def_id);
1454
1455        let mut errors = self.opaque_capture_errors.borrow_mut();
1456        let error_info = errors.get_or_insert_with(|| OpaqueHigherRankedLifetimeCaptureErrors {
1457            bad_place,
1458            capture_spans: Vec::new(),
1459            decl_spans: Vec::new(),
1460        });
1461
1462        if error_info.capture_spans.is_empty() {
1463            error_info.capture_spans.push(opaque_span);
1464        }
1465
1466        if capture_span != decl_span && capture_span != opaque_span {
1467            error_info.capture_spans.push(capture_span);
1468        }
1469
1470        if !error_info.decl_spans.contains(&decl_span) {
1471            error_info.decl_spans.push(decl_span);
1472        }
1473
1474        // Errors should be emitted by `emit_opaque_capture_errors`.
1475        Err(self.tcx.dcx().span_delayed_bug(capture_span, "opaque capture error not emitted"))
1476    }
1477
1478    fn emit_opaque_capture_errors(&self) -> Option<ErrorGuaranteed> {
1479        let errors = self.opaque_capture_errors.borrow_mut().take()?;
1480        if errors.capture_spans.is_empty() {
1481            return None;
1482        }
1483
1484        let mut span = rustc_errors::MultiSpan::from_span(errors.capture_spans[0]);
1485        for &capture_span in &errors.capture_spans[1..] {
1486            span.push_span_label(capture_span, "");
1487        }
1488        let decl_span = rustc_errors::MultiSpan::from_spans(errors.decl_spans);
1489
1490        // Ensure that the parent of the def is an item, not HRTB
1491        let guar = self.tcx.dcx().emit_err(errors::OpaqueCapturesHigherRankedLifetime {
1492            span,
1493            label: Some(errors.capture_spans[0]),
1494            decl_span,
1495            bad_place: errors.bad_place,
1496        });
1497
1498        Some(guar)
1499    }
1500
1501    x;#[instrument(level = "trace", skip(self, opaque_capture_scopes), ret)]
1502    fn remap_opaque_captures(
1503        &mut self,
1504        opaque_capture_scopes: &Vec<(LocalDefId, &RefCell<FxIndexMap<ResolvedArg, LocalDefId>>)>,
1505        mut lifetime: ResolvedArg,
1506        ident: Ident,
1507    ) -> ResolvedArg {
1508        if let Some(&(opaque_def_id, _)) = opaque_capture_scopes.last() {
1509            if let Err(guar) =
1510                self.check_lifetime_is_capturable(opaque_def_id, lifetime, ident.span)
1511            {
1512                lifetime = ResolvedArg::Error(guar);
1513            }
1514        }
1515
1516        for &(opaque_def_id, captures) in opaque_capture_scopes.iter().rev() {
1517            let mut captures = captures.borrow_mut();
1518            let remapped = *captures.entry(lifetime).or_insert_with(|| {
1519                // `opaque_def_id` is unique to the `BoundVarContext` pass which is executed once
1520                // per `resolve_bound_vars` query. This is the only location that creates
1521                // `OpaqueLifetime` paths. `<opaque_def_id>::OpaqueLifetime(..)` is thus unique
1522                // to this query and duplicates within the query are handled by `self.disambiguator`.
1523                let feed = self.tcx.create_def(
1524                    opaque_def_id,
1525                    None,
1526                    DefKind::LifetimeParam,
1527                    Some(DefPathData::OpaqueLifetime(ident.name)),
1528                    self.disambiguators.get_or_create(opaque_def_id),
1529                );
1530                feed.def_span(ident.span);
1531                feed.def_ident_span(Some(ident.span));
1532                feed.def_id()
1533            });
1534            lifetime = ResolvedArg::EarlyBound(remapped);
1535        }
1536        lifetime
1537    }
1538
1539    fn resolve_type_ref(&mut self, param_def_id: LocalDefId, hir_id: HirId) {
1540        // Walk up the scope chain, tracking the number of fn scopes
1541        // that we pass through, until we find a lifetime with the
1542        // given name or we run out of scopes.
1543        // search.
1544        let mut late_depth = 0;
1545        let mut scope = self.scope;
1546        let mut crossed_late_boundary = None;
1547
1548        let result = loop {
1549            match *scope {
1550                Scope::Body { s, .. } => {
1551                    scope = s;
1552                }
1553
1554                Scope::Root { opt_parent_item } => {
1555                    if let Some(parent_item) = opt_parent_item
1556                        && let parent_generics = self.tcx.generics_of(parent_item)
1557                        && parent_generics
1558                            .param_def_id_to_index(self.tcx, param_def_id.to_def_id())
1559                            .is_some()
1560                    {
1561                        break Some(ResolvedArg::EarlyBound(param_def_id));
1562                    }
1563                    break None;
1564                }
1565
1566                Scope::Binder { ref bound_vars, scope_type, s, .. } => {
1567                    if let Some(&def) = bound_vars.get(&param_def_id) {
1568                        break Some(def.shifted(late_depth));
1569                    }
1570                    match scope_type {
1571                        BinderScopeType::Normal => late_depth += 1,
1572                        BinderScopeType::Concatenating => {}
1573                    }
1574                    scope = s;
1575                }
1576
1577                Scope::ObjectLifetimeDefault { s, .. }
1578                | Scope::Opaque { s, .. }
1579                | Scope::Supertrait { s, .. }
1580                | Scope::TraitRefBoundary { s, .. } => {
1581                    scope = s;
1582                }
1583
1584                Scope::LateBoundary { s, what, deny_late_regions: _ } => {
1585                    crossed_late_boundary = Some(what);
1586                    scope = s;
1587                }
1588            }
1589        };
1590
1591        if let Some(def) = result {
1592            if let ResolvedArg::LateBound(..) = def
1593                && let Some(what) = crossed_late_boundary
1594            {
1595                let use_span = self.tcx.hir_span(hir_id);
1596                let def_span = self.tcx.def_span(param_def_id);
1597                let guar = match self.tcx.def_kind(param_def_id) {
1598                    DefKind::ConstParam => {
1599                        self.tcx.dcx().emit_err(errors::CannotCaptureLateBound::Const {
1600                            use_span,
1601                            def_span,
1602                            what,
1603                        })
1604                    }
1605                    DefKind::TyParam => {
1606                        self.tcx.dcx().emit_err(errors::CannotCaptureLateBound::Type {
1607                            use_span,
1608                            def_span,
1609                            what,
1610                        })
1611                    }
1612                    kind => ::rustc_middle::util::bug::span_bug_fmt(use_span,
    format_args!("did not expect to resolve non-lifetime param to {0}",
        kind.descr(param_def_id.to_def_id())))span_bug!(
1613                        use_span,
1614                        "did not expect to resolve non-lifetime param to {}",
1615                        kind.descr(param_def_id.to_def_id())
1616                    ),
1617                };
1618                self.rbv.defs.insert(hir_id.local_id, ResolvedArg::Error(guar));
1619            } else {
1620                self.rbv.defs.insert(hir_id.local_id, def);
1621            }
1622            return;
1623        }
1624
1625        // We may fail to resolve higher-ranked ty/const vars that are mentioned by APIT.
1626        // AST-based resolution does not care for impl-trait desugaring, which are the
1627        // responsibility of lowering. This may create a mismatch between the resolution
1628        // AST found (`param_def_id`) which points to HRTB, and what HIR allows.
1629        // ```
1630        // fn foo(x: impl for<T> Trait<Assoc = impl Trait2<T>>) {}
1631        // ```
1632        //
1633        // In such case, walk back the binders to diagnose it properly.
1634        let mut scope = self.scope;
1635        loop {
1636            match *scope {
1637                Scope::Binder {
1638                    where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), ..
1639                } => {
1640                    let guar = self.tcx.dcx().emit_err(match self.tcx.def_kind(param_def_id) {
1641                        DefKind::TyParam => errors::LateBoundInApit::Type {
1642                            span: self.tcx.hir_span(hir_id),
1643                            param_span: self.tcx.def_span(param_def_id),
1644                        },
1645                        DefKind::ConstParam => errors::LateBoundInApit::Const {
1646                            span: self.tcx.hir_span(hir_id),
1647                            param_span: self.tcx.def_span(param_def_id),
1648                        },
1649                        kind => {
1650                            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected def-kind: {0}",
        kind.descr(param_def_id.to_def_id())))bug!("unexpected def-kind: {}", kind.descr(param_def_id.to_def_id()))
1651                        }
1652                    });
1653                    self.rbv.defs.insert(hir_id.local_id, ResolvedArg::Error(guar));
1654                    return;
1655                }
1656                Scope::Root { .. } => break,
1657                Scope::Binder { s, .. }
1658                | Scope::Body { s, .. }
1659                | Scope::Opaque { s, .. }
1660                | Scope::ObjectLifetimeDefault { s, .. }
1661                | Scope::Supertrait { s, .. }
1662                | Scope::TraitRefBoundary { s, .. }
1663                | Scope::LateBoundary { s, .. } => {
1664                    scope = s;
1665                }
1666            }
1667        }
1668
1669        self.tcx
1670            .dcx()
1671            .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:?}"));
1672    }
1673
1674    #[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_segment_args",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1674u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["res", "depth",
                                                    "generic_args"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&depth as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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 type_def_id =
                match res {
                    Res::Def(DefKind::AssocTy, def_id) if depth == 1 =>
                        Some(self.tcx.parent(def_id)),
                    Res::Def(DefKind::Variant, def_id) if depth == 0 =>
                        Some(self.tcx.parent(def_id)),
                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum |
                        DefKind::TyAlias | DefKind::Trait | DefKind::TraitAlias,
                        def_id) if depth == 0 => Some(def_id),
                    _ => None,
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:1709",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1709u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["type_def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&type_def_id)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let object_lifetime_defaults =
                type_def_id.map_or_else(Vec::new,
                    |def_id|
                        {
                            let in_body =
                                {
                                    let mut scope = self.scope;
                                    loop {
                                        match *scope {
                                            Scope::Root { .. } => break false,
                                            Scope::Body { .. } => break true,
                                            Scope::Binder { s, .. } | Scope::ObjectLifetimeDefault { s,
                                                .. } | Scope::Opaque { s, .. } | Scope::Supertrait { s, .. }
                                                | Scope::TraitRefBoundary { s, .. } | Scope::LateBoundary {
                                                s, .. } => {
                                                scope = s;
                                            }
                                        }
                                    }
                                };
                            let rbv = &self.rbv;
                            let generics = self.tcx.generics_of(def_id);
                            if true {
                                match (&generics.parent_count, &0) {
                                    (left_val, right_val) => {
                                        if !(*left_val == *right_val) {
                                            let kind = ::core::panicking::AssertKind::Eq;
                                            ::core::panicking::assert_failed(kind, &*left_val,
                                                &*right_val, ::core::option::Option::None);
                                        }
                                    }
                                };
                            };
                            let set_to_region =
                                |set: ObjectLifetimeDefault|
                                    match set {
                                        ObjectLifetimeDefault::Empty => {
                                            if in_body {
                                                None
                                            } else { Some(ResolvedArg::StaticLifetime) }
                                        }
                                        ObjectLifetimeDefault::Static =>
                                            Some(ResolvedArg::StaticLifetime),
                                        ObjectLifetimeDefault::Param(param_def_id) => {
                                            let index =
                                                generics.param_def_id_to_index[&param_def_id] as usize;
                                            generic_args.args.get(index).and_then(|arg|
                                                    match arg {
                                                        GenericArg::Lifetime(lt) =>
                                                            rbv.defs.get(&lt.hir_id.local_id).copied(),
                                                        _ => None,
                                                    })
                                        }
                                        ObjectLifetimeDefault::Ambiguous => None,
                                    };
                            generics.own_params.iter().filter_map(|param|
                                            {
                                                match self.tcx.def_kind(param.def_id) {
                                                    DefKind::ConstParam => Some(ObjectLifetimeDefault::Empty),
                                                    DefKind::TyParam =>
                                                        Some(self.tcx.object_lifetime_default(param.def_id)),
                                                    DefKind::LifetimeParam | DefKind::Trait |
                                                        DefKind::TraitAlias => None,
                                                    dk =>
                                                        ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected def_kind {0:?}",
                                                                dk)),
                                                }
                                            }).map(set_to_region).collect()
                        });
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:1793",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1793u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["object_lifetime_defaults"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&object_lifetime_defaults)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let mut i = 0;
            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_parameter =
                generic_args.args.iter().any(|arg|
                        #[allow(non_exhaustive_omitted_patterns)] match arg {
                            GenericArg::Lifetime(_) => true,
                            _ => false,
                        });
            for constraint in generic_args.constraints {
                let scope =
                    Scope::ObjectLifetimeDefault {
                        lifetime: if has_lifetime_parameter {
                            None
                        } else { Some(ResolvedArg::StaticLifetime) },
                        s: self.scope,
                    };
                if constraint.gen_args.parenthesized ==
                        hir::GenericArgsParentheses::ReturnTypeNotation {
                    let bound_vars =
                        if let Some(type_def_id) = type_def_id &&
                                    let DefKind::Trait | DefKind::TraitAlias =
                                        self.tcx.def_kind(type_def_id) &&
                                let Some((mut bound_vars, assoc_fn)) =
                                    BoundVarContext::supertrait_hrtb_vars(self.tcx, type_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)));
                            bound_vars.extend(self.tcx.fn_sig(assoc_fn.def_id).instantiate_identity().skip_norm_wip().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(type_def_id) = type_def_id {
                    let bound_vars =
                        BoundVarContext::supertrait_hrtb_vars(self.tcx, type_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))]
1675    fn visit_segment_args(
1676        &mut self,
1677        res: Res,
1678        depth: usize,
1679        generic_args: &'tcx hir::GenericArgs<'tcx>,
1680    ) {
1681        if let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() {
1682            self.visit_fn_like_elision(inputs, Some(output), false);
1683            return;
1684        }
1685
1686        for arg in generic_args.args {
1687            if let hir::GenericArg::Lifetime(lt) = arg {
1688                self.visit_lifetime(lt);
1689            }
1690        }
1691
1692        // Figure out if this is a type/trait segment,
1693        // which requires object lifetime defaults.
1694        let type_def_id = match res {
1695            Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(self.tcx.parent(def_id)),
1696            Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(self.tcx.parent(def_id)),
1697            Res::Def(
1698                DefKind::Struct
1699                | DefKind::Union
1700                | DefKind::Enum
1701                | DefKind::TyAlias
1702                | DefKind::Trait
1703                | DefKind::TraitAlias,
1704                def_id,
1705            ) if depth == 0 => Some(def_id),
1706            _ => None,
1707        };
1708
1709        debug!(?type_def_id);
1710
1711        // Compute a vector of defaults, one for each type parameter,
1712        // per the rules given in RFCs 599 and 1156. Example:
1713        //
1714        // ```rust
1715        // struct Foo<'a, T: 'a, U> { }
1716        // ```
1717        //
1718        // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
1719        // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
1720        // and `dyn Baz` to `dyn Baz + 'static` (because there is no
1721        // such bound).
1722        //
1723        // Therefore, we would compute `object_lifetime_defaults` to a
1724        // vector like `['x, 'static]`. Note that the vector only
1725        // includes type parameters.
1726        let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
1727            let in_body = {
1728                let mut scope = self.scope;
1729                loop {
1730                    match *scope {
1731                        Scope::Root { .. } => break false,
1732
1733                        Scope::Body { .. } => break true,
1734
1735                        Scope::Binder { s, .. }
1736                        | Scope::ObjectLifetimeDefault { s, .. }
1737                        | Scope::Opaque { s, .. }
1738                        | Scope::Supertrait { s, .. }
1739                        | Scope::TraitRefBoundary { s, .. }
1740                        | Scope::LateBoundary { s, .. } => {
1741                            scope = s;
1742                        }
1743                    }
1744                }
1745            };
1746
1747            let rbv = &self.rbv;
1748            let generics = self.tcx.generics_of(def_id);
1749
1750            // `type_def_id` points to an item, so there is nothing to inherit generics from.
1751            debug_assert_eq!(generics.parent_count, 0);
1752
1753            let set_to_region = |set: ObjectLifetimeDefault| match set {
1754                ObjectLifetimeDefault::Empty => {
1755                    if in_body {
1756                        None
1757                    } else {
1758                        Some(ResolvedArg::StaticLifetime)
1759                    }
1760                }
1761                ObjectLifetimeDefault::Static => Some(ResolvedArg::StaticLifetime),
1762                ObjectLifetimeDefault::Param(param_def_id) => {
1763                    // This index can be used with `generic_args` since `parent_count == 0`.
1764                    let index = generics.param_def_id_to_index[&param_def_id] as usize;
1765                    generic_args.args.get(index).and_then(|arg| match arg {
1766                        GenericArg::Lifetime(lt) => rbv.defs.get(&lt.hir_id.local_id).copied(),
1767                        _ => None,
1768                    })
1769                }
1770                ObjectLifetimeDefault::Ambiguous => None,
1771            };
1772            generics
1773                .own_params
1774                .iter()
1775                .filter_map(|param| {
1776                    match self.tcx.def_kind(param.def_id) {
1777                        // Generic consts don't impose any constraints.
1778                        //
1779                        // We still store a dummy value here to allow generic parameters
1780                        // in an arbitrary order.
1781                        DefKind::ConstParam => Some(ObjectLifetimeDefault::Empty),
1782                        DefKind::TyParam => Some(self.tcx.object_lifetime_default(param.def_id)),
1783                        // We may also get a `Trait` or `TraitAlias` because of how generics `Self` parameter
1784                        // works. Ignore it because it can't have a meaningful lifetime default.
1785                        DefKind::LifetimeParam | DefKind::Trait | DefKind::TraitAlias => None,
1786                        dk => bug!("unexpected def_kind {:?}", dk),
1787                    }
1788                })
1789                .map(set_to_region)
1790                .collect()
1791        });
1792
1793        debug!(?object_lifetime_defaults);
1794
1795        let mut i = 0;
1796        for arg in generic_args.args {
1797            match arg {
1798                GenericArg::Lifetime(_) => {}
1799                GenericArg::Type(ty) => {
1800                    if let Some(&lt) = object_lifetime_defaults.get(i) {
1801                        let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
1802                        self.with(scope, |this| this.visit_ty(ty));
1803                    } else {
1804                        self.visit_ty(ty);
1805                    }
1806                    i += 1;
1807                }
1808                GenericArg::Const(ct) => {
1809                    self.visit_const_arg(ct);
1810                    i += 1;
1811                }
1812                GenericArg::Infer(inf) => {
1813                    self.visit_id(inf.hir_id);
1814                    i += 1;
1815                }
1816            }
1817        }
1818
1819        // Hack: When resolving the type `XX` in an assoc ty binding like
1820        // `dyn Foo<'b, Item = XX>`, the current object-lifetime default
1821        // would be to examine the trait `Foo` to check whether it has
1822        // a lifetime bound declared on `Item`. e.g., if `Foo` is
1823        // declared like so, then the default object lifetime bound in
1824        // `XX` should be `'b`:
1825        //
1826        // ```rust
1827        // trait Foo<'a> {
1828        //   type Item: 'a;
1829        // }
1830        // ```
1831        //
1832        // but if we just have `type Item;`, then it would be
1833        // `'static`. However, we don't get all of this logic correct.
1834        //
1835        // Instead, we do something hacky: if there are no lifetime parameters
1836        // to the trait, then we simply use a default object lifetime
1837        // bound of `'static`, because there is no other possibility. On the other hand,
1838        // if there ARE lifetime parameters, then we require the user to give an
1839        // explicit bound for now.
1840        //
1841        // This is intended to leave room for us to implement the
1842        // correct behavior in the future.
1843        let has_lifetime_parameter =
1844            generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
1845
1846        // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
1847        // in the trait ref `YY<...>` in `Item: YY<...>`.
1848        for constraint in generic_args.constraints {
1849            let scope = Scope::ObjectLifetimeDefault {
1850                lifetime: if has_lifetime_parameter {
1851                    None
1852                } else {
1853                    Some(ResolvedArg::StaticLifetime)
1854                },
1855                s: self.scope,
1856            };
1857            // If the args are parenthesized, then this must be `feature(return_type_notation)`.
1858            // In that case, introduce a binder over all of the function's early and late bound vars.
1859            //
1860            // For example, given
1861            // ```
1862            // trait Foo {
1863            //     async fn x<'r, T>();
1864            // }
1865            // ```
1866            // and a bound that looks like:
1867            //    `for<'a> T::Trait<'a, x(..): for<'b> Other<'b>>`
1868            // this is going to expand to something like:
1869            //    `for<'a> for<'r> <T as Trait<'a>>::x::<'r, T>::{opaque#0}: for<'b> Other<'b>`.
1870            if constraint.gen_args.parenthesized == hir::GenericArgsParentheses::ReturnTypeNotation
1871            {
1872                let bound_vars = if let Some(type_def_id) = type_def_id
1873                    && let DefKind::Trait | DefKind::TraitAlias = self.tcx.def_kind(type_def_id)
1874                    && let Some((mut bound_vars, assoc_fn)) = BoundVarContext::supertrait_hrtb_vars(
1875                        self.tcx,
1876                        type_def_id,
1877                        constraint.ident,
1878                        ty::AssocTag::Fn,
1879                    ) {
1880                    bound_vars.extend(
1881                        self.tcx
1882                            .generics_of(assoc_fn.def_id)
1883                            .own_params
1884                            .iter()
1885                            .map(|param| generic_param_def_as_bound_arg(param)),
1886                    );
1887                    bound_vars.extend(
1888                        self.tcx
1889                            .fn_sig(assoc_fn.def_id)
1890                            .instantiate_identity()
1891                            .skip_norm_wip()
1892                            .bound_vars(),
1893                    );
1894                    bound_vars
1895                } else {
1896                    self.tcx
1897                        .dcx()
1898                        .span_delayed_bug(constraint.ident.span, "bad return type notation here");
1899                    vec![]
1900                };
1901                self.with(scope, |this| {
1902                    let scope = Scope::Supertrait { bound_vars, s: this.scope };
1903                    this.with(scope, |this| {
1904                        let (bound_vars, _) = this.poly_trait_ref_binder_info();
1905                        this.record_late_bound_vars(constraint.hir_id, bound_vars);
1906                        this.visit_assoc_item_constraint(constraint)
1907                    });
1908                });
1909            } else if let Some(type_def_id) = type_def_id {
1910                let bound_vars = BoundVarContext::supertrait_hrtb_vars(
1911                    self.tcx,
1912                    type_def_id,
1913                    constraint.ident,
1914                    ty::AssocTag::Type,
1915                )
1916                .map(|(bound_vars, _)| bound_vars);
1917                self.with(scope, |this| {
1918                    let scope = Scope::Supertrait {
1919                        bound_vars: bound_vars.unwrap_or_default(),
1920                        s: this.scope,
1921                    };
1922                    this.with(scope, |this| this.visit_assoc_item_constraint(constraint));
1923                });
1924            } else {
1925                self.with(scope, |this| this.visit_assoc_item_constraint(constraint));
1926            }
1927        }
1928    }
1929
1930    /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
1931    /// associated type name and starting trait.
1932    /// For example, imagine we have
1933    /// ```ignore (illustrative)
1934    /// trait Foo<'a, 'b> {
1935    ///   type As;
1936    /// }
1937    /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
1938    /// trait Bar: for<'b> Bar<'b> {}
1939    /// ```
1940    /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
1941    /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
1942    fn supertrait_hrtb_vars(
1943        tcx: TyCtxt<'tcx>,
1944        def_id: DefId,
1945        assoc_ident: Ident,
1946        assoc_tag: ty::AssocTag,
1947    ) -> Option<(Vec<ty::BoundVariableKind<'tcx>>, &'tcx ty::AssocItem)> {
1948        let trait_defines_associated_item_named = |trait_def_id: DefId| {
1949            tcx.associated_items(trait_def_id).find_by_ident_and_kind(
1950                tcx,
1951                assoc_ident,
1952                assoc_tag,
1953                trait_def_id,
1954            )
1955        };
1956
1957        use smallvec::{SmallVec, smallvec};
1958        let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind<'tcx>; 8]>); 8]> =
1959            {
    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![])];
1960        let mut visited: FxHashSet<DefId> = FxHashSet::default();
1961        loop {
1962            let Some((def_id, bound_vars)) = stack.pop() else {
1963                break None;
1964            };
1965            // See issue #83753. If someone writes an associated type on a non-trait, just treat it
1966            // as there being no supertrait HRTBs.
1967            match tcx.def_kind(def_id) {
1968                DefKind::Trait | DefKind::TraitAlias | DefKind::Impl { .. } => {}
1969                _ => break None,
1970            }
1971
1972            if let Some(assoc_item) = trait_defines_associated_item_named(def_id) {
1973                break Some((bound_vars.into_iter().collect(), assoc_item));
1974            }
1975            let predicates = tcx.explicit_supertraits_containing_assoc_item((def_id, assoc_ident));
1976            let obligations = predicates
1977                .iter_identity_copied()
1978                .map(Unnormalized::skip_norm_wip)
1979                .filter_map(|(pred, _)| {
1980                    let bound_predicate = pred.kind();
1981                    match bound_predicate.skip_binder() {
1982                        ty::ClauseKind::Trait(data) => {
1983                            // The order here needs to match what we would get from
1984                            // `rustc_middle::ty::predicate::Clause::instantiate_supertrait`
1985                            let pred_bound_vars = bound_predicate.bound_vars();
1986                            let mut all_bound_vars = bound_vars.clone();
1987                            all_bound_vars.extend(pred_bound_vars.iter());
1988                            let super_def_id = data.trait_ref.def_id;
1989                            Some((super_def_id, all_bound_vars))
1990                        }
1991                        _ => None,
1992                    }
1993                });
1994
1995            let obligations = obligations.filter(|o| visited.insert(o.0));
1996            stack.extend(obligations);
1997        }
1998    }
1999
2000    #[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("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2000u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["inputs", "output",
                                                    "in_closure"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&inputs)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&output)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&in_closure as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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))]
2001    fn visit_fn_like_elision(
2002        &mut self,
2003        inputs: &'tcx [hir::Ty<'tcx>],
2004        output: Option<&'tcx hir::Ty<'tcx>>,
2005        in_closure: bool,
2006    ) {
2007        self.with(
2008            Scope::ObjectLifetimeDefault {
2009                lifetime: Some(ResolvedArg::StaticLifetime),
2010                s: self.scope,
2011            },
2012            |this| {
2013                for input in inputs {
2014                    this.visit_ty_unambig(input);
2015                }
2016                if !in_closure && let Some(output) = output {
2017                    this.visit_ty_unambig(output);
2018                }
2019            },
2020        );
2021        if in_closure && let Some(output) = output {
2022            self.visit_ty_unambig(output);
2023        }
2024    }
2025
2026    #[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("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2026u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime_ref"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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))]
2027    fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2028        let mut late_depth = 0;
2029        let mut scope = self.scope;
2030        let mut opaque_capture_scopes = vec![];
2031        let mut lifetime = loop {
2032            match *scope {
2033                Scope::Binder { s, scope_type, .. } => {
2034                    match scope_type {
2035                        BinderScopeType::Normal => late_depth += 1,
2036                        BinderScopeType::Concatenating => {}
2037                    }
2038                    scope = s;
2039                }
2040
2041                Scope::Root { .. } => break ResolvedArg::StaticLifetime,
2042
2043                Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2044
2045                Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => {
2046                    break l.shifted(late_depth);
2047                }
2048
2049                Scope::Opaque { captures, def_id, s } => {
2050                    opaque_capture_scopes.push((def_id, captures));
2051                    late_depth = 0;
2052                    scope = s;
2053                }
2054
2055                Scope::Supertrait { s, .. }
2056                | Scope::TraitRefBoundary { s, .. }
2057                | Scope::LateBoundary { s, .. } => {
2058                    scope = s;
2059                }
2060            }
2061        };
2062
2063        lifetime = self.remap_opaque_captures(&opaque_capture_scopes, lifetime, lifetime_ref.ident);
2064
2065        self.insert_lifetime(lifetime_ref, lifetime);
2066    }
2067
2068    #[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("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2068u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime_ref",
                                                    "def"], ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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 compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2070",
                                    "rustc_hir_analysis::collect::resolve_bound_vars",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2070u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&lifetime_ref.ident.span)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            self.rbv.defs.insert(lifetime_ref.hir_id.local_id, def);
        }
    }
}#[instrument(level = "debug", skip(self))]
2069    fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: ResolvedArg) {
2070        debug!(span = ?lifetime_ref.ident.span);
2071        self.rbv.defs.insert(lifetime_ref.hir_id.local_id, def);
2072    }
2073
2074    // When we have a return type notation type in a where clause, like
2075    // `where <T as Trait>::method(..): Send`, we need to introduce new bound
2076    // vars to the existing where clause's binder, to represent the lifetimes
2077    // elided by the return-type-notation syntax.
2078    //
2079    // For example, given
2080    // ```
2081    // trait Foo {
2082    //     async fn x<'r>();
2083    // }
2084    // ```
2085    // and a bound that looks like:
2086    //    `for<'a, 'b> <T as Trait<'a>>::x(): Other<'b>`
2087    // this is going to expand to something like:
2088    //    `for<'a, 'b, 'r> <T as Trait<'a>>::x::<'r, T>::{opaque#0}: Other<'b>`.
2089    //
2090    // We handle this similarly for associated-type-bound style return-type-notation
2091    // in `visit_segment_args`.
2092    fn try_append_return_type_notation_params(
2093        &mut self,
2094        hir_id: HirId,
2095        hir_ty: &'tcx hir::Ty<'tcx>,
2096    ) {
2097        let hir::TyKind::Path(qpath) = hir_ty.kind else {
2098            // We only care about path types here. All other self types
2099            // (including nesting the RTN type in another type) don't do
2100            // anything.
2101            return;
2102        };
2103
2104        let (mut bound_vars, item_def_id, item_segment) = match qpath {
2105            // If we have a fully qualified method, then we don't need to do any special lookup.
2106            hir::QPath::Resolved(_, path)
2107                if let [.., item_segment] = &path.segments[..]
2108                    && item_segment.args.is_some_and(|args| {
2109                        #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
    hir::GenericArgsParentheses::ReturnTypeNotation => true,
    _ => false,
}matches!(
2110                            args.parenthesized,
2111                            hir::GenericArgsParentheses::ReturnTypeNotation
2112                        )
2113                    }) =>
2114            {
2115                match path.res {
2116                    Res::Err => return,
2117                    Res::Def(DefKind::AssocFn, item_def_id) => (::alloc::vec::Vec::new()vec![], item_def_id, item_segment),
2118                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("only expected method resolution for fully qualified RTN"))bug!("only expected method resolution for fully qualified RTN"),
2119                }
2120            }
2121
2122            // If we have a type-dependent path, then we do need to do some lookup.
2123            hir::QPath::TypeRelative(qself, item_segment)
2124                if item_segment.args.is_some_and(|args| {
2125                    #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
    hir::GenericArgsParentheses::ReturnTypeNotation => true,
    _ => false,
}matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2126                }) =>
2127            {
2128                // First, ignore a qself that isn't a type or `Self` param. Those are the
2129                // only ones that support `T::Assoc` anyways in HIR lowering.
2130                let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = qself.kind else {
2131                    return;
2132                };
2133                match path.res {
2134                    Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { trait_: _ } => {
2135                        let mut bounds =
2136                            self.for_each_trait_bound_on_res(path.res).filter_map(|trait_def_id| {
2137                                BoundVarContext::supertrait_hrtb_vars(
2138                                    self.tcx,
2139                                    trait_def_id,
2140                                    item_segment.ident,
2141                                    ty::AssocTag::Fn,
2142                                )
2143                            });
2144
2145                        let Some((bound_vars, assoc_item)) = bounds.next() else {
2146                            // This will error in HIR lowering.
2147                            self.tcx
2148                                .dcx()
2149                                .span_delayed_bug(path.span, "no resolution for RTN path");
2150                            return;
2151                        };
2152
2153                        // Don't bail if we have identical bounds, which may be collected from
2154                        // something like `T: Bound + Bound`, or via elaborating supertraits.
2155                        for (second_vars, second_assoc_item) in bounds {
2156                            if second_vars != bound_vars || second_assoc_item != assoc_item {
2157                                // This will error in HIR lowering.
2158                                self.tcx.dcx().span_delayed_bug(
2159                                    path.span,
2160                                    "ambiguous resolution for RTN path",
2161                                );
2162                                return;
2163                            }
2164                        }
2165
2166                        (bound_vars, assoc_item.def_id, item_segment)
2167                    }
2168                    // If we have a self type alias (in an impl), try to resolve an
2169                    // associated item from one of the supertraits of the impl's trait.
2170                    Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. } => {
2171                        let hir::ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) = self
2172                            .tcx
2173                            .hir_node_by_def_id(impl_def_id.expect_local())
2174                            .expect_item()
2175                            .kind
2176                        else {
2177                            return;
2178                        };
2179                        let Some(trait_def_id) = of_trait.trait_ref.trait_def_id() else {
2180                            return;
2181                        };
2182                        let Some((bound_vars, assoc_item)) = BoundVarContext::supertrait_hrtb_vars(
2183                            self.tcx,
2184                            trait_def_id,
2185                            item_segment.ident,
2186                            ty::AssocTag::Fn,
2187                        ) else {
2188                            return;
2189                        };
2190                        (bound_vars, assoc_item.def_id, item_segment)
2191                    }
2192                    _ => return,
2193                }
2194            }
2195
2196            _ => return,
2197        };
2198
2199        // Append the early-bound vars on the function, and then the late-bound ones.
2200        // We actually turn type parameters into higher-ranked types here, but we
2201        // deny them later in HIR lowering.
2202        bound_vars.extend(
2203            self.tcx
2204                .generics_of(item_def_id)
2205                .own_params
2206                .iter()
2207                .map(|param| generic_param_def_as_bound_arg(param)),
2208        );
2209        bound_vars.extend(
2210            self.tcx.fn_sig(item_def_id).instantiate_identity().skip_norm_wip().bound_vars(),
2211        );
2212
2213        // SUBTLE: Stash the old bound vars onto the *item segment* before appending
2214        // the new bound vars. We do this because we need to know how many bound vars
2215        // are present on the binder explicitly (i.e. not return-type-notation vars)
2216        // to do bound var shifting correctly in HIR lowering.
2217        //
2218        // For example, in `where for<'a> <T as Trait<'a>>::method(..): Other`,
2219        // the `late_bound_vars` of the where clause predicate (i.e. this HIR ty's
2220        // parent) will include `'a` AND all the early- and late-bound vars of the
2221        // method. But when lowering the RTN type, we just want the list of vars
2222        // we used to resolve the trait ref. We explicitly stored those back onto
2223        // the item segment, since there's no other good place to put them.
2224        //
2225        // See where these vars are used in `HirTyLowerer::lower_ty_maybe_return_type_notation`.
2226        // And this is exercised in:
2227        // `tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.rs`.
2228        let existing_bound_vars = self.rbv.late_bound_vars.get_mut(&hir_id.local_id).unwrap();
2229        let existing_bound_vars_saved = existing_bound_vars.clone();
2230        existing_bound_vars.extend(bound_vars);
2231        self.record_late_bound_vars(item_segment.hir_id, existing_bound_vars_saved);
2232    }
2233
2234    /// Walk the generics of the item for a trait bound whose self type
2235    /// corresponds to the expected res, and return the trait def id.
2236    fn for_each_trait_bound_on_res(&self, expected_res: Res) -> impl Iterator<Item = DefId> {
2237        gen move {
2238            let mut scope = self.scope;
2239            loop {
2240                let hir_id = match *scope {
2241                    Scope::Binder { hir_id, .. } => Some(hir_id),
2242                    Scope::Root { opt_parent_item: Some(parent_def_id) } => {
2243                        Some(self.tcx.local_def_id_to_hir_id(parent_def_id))
2244                    }
2245                    Scope::Body { .. }
2246                    | Scope::ObjectLifetimeDefault { .. }
2247                    | Scope::Supertrait { .. }
2248                    | Scope::TraitRefBoundary { .. }
2249                    | Scope::LateBoundary { .. }
2250                    | Scope::Opaque { .. }
2251                    | Scope::Root { opt_parent_item: None } => None,
2252                };
2253
2254                if let Some(hir_id) = hir_id {
2255                    let node = self.tcx.hir_node(hir_id);
2256                    // If this is a `Self` bound in a trait, yield the trait itself.
2257                    // Specifically, we don't need to look at any supertraits since
2258                    // we already do that in `BoundVarContext::supertrait_hrtb_vars`.
2259                    if let Res::SelfTyParam { trait_: _ } = expected_res
2260                        && let hir::Node::Item(item) = node
2261                        && let hir::ItemKind::Trait { .. } = item.kind
2262                    {
2263                        // Yield the trait's def id. Supertraits will be
2264                        // elaborated from that.
2265                        yield item.owner_id.def_id.to_def_id();
2266                    } else if let Some(generics) = node.generics() {
2267                        for pred in generics.predicates {
2268                            let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
2269                                continue;
2270                            };
2271                            let hir::TyKind::Path(hir::QPath::Resolved(None, bounded_path)) =
2272                                pred.bounded_ty.kind
2273                            else {
2274                                continue;
2275                            };
2276                            // Match the expected res.
2277                            if bounded_path.res != expected_res {
2278                                continue;
2279                            }
2280                            for pred in pred.bounds {
2281                                match pred {
2282                                    hir::GenericBound::Trait(poly_trait_ref) => {
2283                                        if let Some(def_id) =
2284                                            poly_trait_ref.trait_ref.trait_def_id()
2285                                        {
2286                                            yield def_id;
2287                                        }
2288                                    }
2289                                    hir::GenericBound::Outlives(_)
2290                                    | hir::GenericBound::Use(_, _) => {}
2291                                }
2292                            }
2293                        }
2294                    }
2295                }
2296
2297                match *scope {
2298                    Scope::Binder { s, .. }
2299                    | Scope::Body { s, .. }
2300                    | Scope::ObjectLifetimeDefault { s, .. }
2301                    | Scope::Supertrait { s, .. }
2302                    | Scope::TraitRefBoundary { s }
2303                    | Scope::LateBoundary { s, .. }
2304                    | Scope::Opaque { s, .. } => {
2305                        scope = s;
2306                    }
2307                    Scope::Root { .. } => break,
2308                }
2309            }
2310        }
2311    }
2312}
2313
2314/// Detects late-bound lifetimes and inserts them into
2315/// `late_bound`.
2316///
2317/// A region declared on a fn is **late-bound** if:
2318/// - it is constrained by an argument type;
2319/// - it does not appear in a where-clause.
2320///
2321/// "Constrained" basically means that it appears in any type but
2322/// not amongst the inputs to a projection. In other words, `<&'a
2323/// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2324fn is_late_bound_map(
2325    tcx: TyCtxt<'_>,
2326    owner_id: hir::OwnerId,
2327) -> Option<&FxIndexSet<hir::ItemLocalId>> {
2328    let sig = tcx.hir_fn_sig_by_hir_id(owner_id.into())?;
2329    let generics = tcx.hir_get_generics(owner_id.def_id)?;
2330
2331    let mut late_bound = FxIndexSet::default();
2332
2333    let mut constrained_by_input = ConstrainedCollector { regions: Default::default(), tcx };
2334    for arg_ty in sig.decl.inputs {
2335        constrained_by_input.visit_ty_unambig(arg_ty);
2336    }
2337
2338    let mut appears_in_output =
2339        AllCollector { has_fully_capturing_opaque: false, regions: Default::default() };
2340    intravisit::walk_fn_ret_ty(&mut appears_in_output, &sig.decl.output);
2341    if appears_in_output.has_fully_capturing_opaque {
2342        appears_in_output.regions.extend(generics.params.iter().map(|param| param.def_id));
2343    }
2344
2345    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2345",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2345u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&["constrained_by_input.regions"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&constrained_by_input.regions)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?constrained_by_input.regions);
2346
2347    // Walk the lifetimes that appear in where clauses.
2348    //
2349    // Subtle point: because we disallow nested bindings, we can just
2350    // ignore binders here and scrape up all names we see.
2351    let mut appears_in_where_clause =
2352        AllCollector { has_fully_capturing_opaque: true, regions: Default::default() };
2353    appears_in_where_clause.visit_generics(generics);
2354    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2354",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2354u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&["appears_in_where_clause.regions"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&appears_in_where_clause.regions)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?appears_in_where_clause.regions);
2355
2356    // Late bound regions are those that:
2357    // - appear in the inputs
2358    // - do not appear in the where-clauses
2359    // - are not implicitly captured by `impl Trait`
2360    for param in generics.params {
2361        match param.kind {
2362            hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2363
2364            // Neither types nor consts are late-bound.
2365            hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
2366        }
2367
2368        // appears in the where clauses? early-bound.
2369        if appears_in_where_clause.regions.contains(&param.def_id) {
2370            continue;
2371        }
2372
2373        // does not appear in the inputs, but appears in the return type? early-bound.
2374        if !constrained_by_input.regions.contains(&param.def_id)
2375            && appears_in_output.regions.contains(&param.def_id)
2376        {
2377            continue;
2378        }
2379
2380        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2380",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2380u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("lifetime {0:?} with id {1:?} is late-bound",
                                                    param.name.ident(), param.def_id) as &dyn Value))])
            });
    } else { ; }
};debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.def_id);
2381
2382        let inserted = late_bound.insert(param.hir_id.local_id);
2383        if !inserted {
    {
        ::core::panicking::panic_fmt(format_args!("visited lifetime {0:?} twice",
                param.def_id));
    }
};assert!(inserted, "visited lifetime {:?} twice", param.def_id);
2384    }
2385
2386    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2386",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2386u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                        ::tracing_core::field::FieldSet::new(&["late_bound"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&late_bound)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?late_bound);
2387    return Some(tcx.arena.alloc(late_bound));
2388
2389    /// Visits a `ty::Ty` collecting information about what generic parameters are constrained.
2390    ///
2391    /// The visitor does not operate on `hir::Ty` so that it can be called on the rhs of a `type Alias<...> = ...;`
2392    /// which may live in a separate crate so there would not be any hir available. Instead we use the `type_of`
2393    /// query to obtain a `ty::Ty` which will be present even in cross crate scenarios. It also naturally
2394    /// handles cycle detection as we go through the query system.
2395    ///
2396    /// This is necessary in the first place for the following case:
2397    /// ```rust,ignore (pseudo-Rust)
2398    /// type Alias<'a, T> = <T as Trait<'a>>::Assoc;
2399    /// fn foo<'a>(_: Alias<'a, ()>) -> Alias<'a, ()> { ... }
2400    /// ```
2401    ///
2402    /// If we conservatively considered `'a` unconstrained then we could break users who had written code before
2403    /// we started correctly handling aliases. If we considered `'a` constrained then it would become late bound
2404    /// causing an error during HIR ty lowering as the `'a` is not constrained by the input type `<() as Trait<'a>>::Assoc`
2405    /// but appears in the output type `<() as Trait<'a>>::Assoc`.
2406    ///
2407    /// We must therefore "look into" the `Alias` to see whether we should consider `'a` constrained or not.
2408    ///
2409    /// See #100508 #85533 #47511 for additional context
2410    struct ConstrainedCollectorPostHirTyLowering {
2411        arg_is_constrained: Box<[bool]>,
2412    }
2413
2414    use ty::Ty;
2415    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ConstrainedCollectorPostHirTyLowering {
2416        fn visit_ty(&mut self, t: Ty<'tcx>) {
2417            match t.kind() {
2418                ty::Param(param_ty) => {
2419                    self.arg_is_constrained[param_ty.index as usize] = true;
2420                }
2421                ty::Alias(ty::AliasTy {
2422                    kind: ty::Projection { .. } | ty::Inherent { .. },
2423                    ..
2424                }) => return,
2425                _ => (),
2426            }
2427            t.super_visit_with(self)
2428        }
2429
2430        fn visit_const(&mut self, _: ty::Const<'tcx>) {}
2431
2432        fn visit_region(&mut self, r: ty::Region<'tcx>) {
2433            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs:2433",
                        "rustc_hir_analysis::collect::resolve_bound_vars",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs"),
                        ::tracing_core::__macro_support::Option::Some(2433u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("r={0:?}",
                                                    r.kind()) as &dyn Value))])
            });
    } else { ; }
};debug!("r={:?}", r.kind());
2434            if let ty::RegionKind::ReEarlyParam(region) = r.kind() {
2435                self.arg_is_constrained[region.index as usize] = true;
2436            }
2437        }
2438    }
2439
2440    struct ConstrainedCollector<'tcx> {
2441        tcx: TyCtxt<'tcx>,
2442        regions: FxHashSet<LocalDefId>,
2443    }
2444
2445    impl<'v> Visitor<'v> for ConstrainedCollector<'_> {
2446        fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
2447            match ty.kind {
2448                hir::TyKind::Path(
2449                    hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
2450                ) => {
2451                    // ignore lifetimes appearing in associated type
2452                    // projections, as they are not *constrained*
2453                    // (defined above)
2454                }
2455
2456                hir::TyKind::Path(hir::QPath::Resolved(
2457                    None,
2458                    hir::Path { res: Res::Def(DefKind::TyAlias, alias_def), segments, span },
2459                )) => {
2460                    // See comments on `ConstrainedCollectorPostHirTyLowering` for why this arm does not
2461                    // just consider args to be unconstrained.
2462                    let generics = self.tcx.generics_of(*alias_def);
2463                    let mut walker = ConstrainedCollectorPostHirTyLowering {
2464                        arg_is_constrained: ::alloc::vec::from_elem(false, generics.own_params.len())vec![false; generics.own_params.len()]
2465                            .into_boxed_slice(),
2466                    };
2467                    walker.visit_ty(
2468                        self.tcx.type_of(*alias_def).instantiate_identity().skip_norm_wip(),
2469                    );
2470
2471                    match segments.last() {
2472                        Some(hir::PathSegment { args: Some(args), .. }) => {
2473                            let tcx = self.tcx;
2474                            for constrained_arg in
2475                                args.args.iter().enumerate().flat_map(|(n, arg)| {
2476                                    match walker.arg_is_constrained.get(n) {
2477                                        Some(true) => Some(arg),
2478                                        Some(false) => None,
2479                                        None => {
2480                                            tcx.dcx().span_delayed_bug(
2481                                                *span,
2482                                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Incorrect generic arg count for alias {0:?}",
                alias_def))
    })format!(
2483                                                    "Incorrect generic arg count for alias {alias_def:?}"
2484                                                ),
2485                                            );
2486                                            None
2487                                        }
2488                                    }
2489                                })
2490                            {
2491                                self.visit_generic_arg(constrained_arg);
2492                            }
2493                        }
2494                        Some(_) => (),
2495                        None => ::rustc_middle::util::bug::bug_fmt(format_args!("Path with no segments or self type"))bug!("Path with no segments or self type"),
2496                    }
2497                }
2498
2499                hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
2500                    // consider only the lifetimes on the final
2501                    // segment; I am not sure it's even currently
2502                    // valid to have them elsewhere, but even if it
2503                    // is, those would be potentially inputs to
2504                    // projections
2505                    if let Some(last_segment) = path.segments.last() {
2506                        self.visit_path_segment(last_segment);
2507                    }
2508                }
2509
2510                _ => {
2511                    intravisit::walk_ty(self, ty);
2512                }
2513            }
2514        }
2515
2516        fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2517            if let hir::LifetimeKind::Param(def_id) = lifetime_ref.kind {
2518                self.regions.insert(def_id);
2519            }
2520        }
2521    }
2522
2523    struct AllCollector {
2524        has_fully_capturing_opaque: bool,
2525        regions: FxHashSet<LocalDefId>,
2526    }
2527
2528    impl<'tcx> Visitor<'tcx> for AllCollector {
2529        fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2530            if let hir::LifetimeKind::Param(def_id) = lifetime_ref.kind {
2531                self.regions.insert(def_id);
2532            }
2533        }
2534
2535        fn visit_opaque_ty(&mut self, opaque: &'tcx hir::OpaqueTy<'tcx>) {
2536            if !self.has_fully_capturing_opaque {
2537                self.has_fully_capturing_opaque = opaque_captures_all_in_scope_lifetimes(opaque);
2538            }
2539            intravisit::walk_opaque_ty(self, opaque);
2540        }
2541    }
2542}
2543
2544fn deny_non_region_late_bound(
2545    tcx: TyCtxt<'_>,
2546    bound_vars: &mut FxIndexMap<LocalDefId, ResolvedArg>,
2547    where_: &str,
2548) {
2549    let mut first = true;
2550
2551    for (var, arg) in bound_vars {
2552        let Node::GenericParam(param) = tcx.hir_node_by_def_id(*var) else {
2553            ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(*var),
    format_args!("expected bound-var def-id to resolve to param"));span_bug!(tcx.def_span(*var), "expected bound-var def-id to resolve to param");
2554        };
2555
2556        let what = match param.kind {
2557            hir::GenericParamKind::Type { .. } => "type",
2558            hir::GenericParamKind::Const { .. } => "const",
2559            hir::GenericParamKind::Lifetime { .. } => continue,
2560        };
2561
2562        let diag = tcx.dcx().struct_span_err(
2563            param.span,
2564            ::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_}"),
2565        );
2566
2567        let guar = diag.emit_unless_delay(!tcx.features().non_lifetime_binders() || !first);
2568
2569        first = false;
2570        *arg = ResolvedArg::Error(guar);
2571    }
2572}