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