Skip to main content

rustc_hir_analysis/collect/
resolve_bound_vars.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.with(Scope::ObjectLifetimeDefault {
                    lifetime: Some(ResolvedArg::StaticLifetime),
                    s: self.scope,
                },
                |this|
                    {
                        for input in inputs { this.visit_ty_unambig(input); }
                        if !in_closure && let Some(output) = output {
                            this.visit_ty_unambig(output);
                        }
                    });
            if in_closure && let Some(output) = output {
                self.visit_ty_unambig(output);
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2170    fn visit_fn_like_elision(
2171        &mut self,
2172        inputs: &'tcx [hir::Ty<'tcx>],
2173        output: Option<&'tcx hir::Ty<'tcx>>,
2174        in_closure: bool,
2175    ) {
2176        self.with(
2177            Scope::ObjectLifetimeDefault {
2178                lifetime: Some(ResolvedArg::StaticLifetime),
2179                s: self.scope,
2180            },
2181            |this| {
2182                for input in inputs {
2183                    this.visit_ty_unambig(input);
2184                }
2185                if !in_closure && let Some(output) = output {
2186                    this.visit_ty_unambig(output);
2187                }
2188            },
2189        );
2190        if in_closure && let Some(output) = output {
2191            self.visit_ty_unambig(output);
2192        }
2193    }
2194
2195    #[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(2195u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut late_depth = 0;
            let mut scope = self.scope;
            let mut opaque_capture_scopes = ::alloc::vec::Vec::new();
            let mut lifetime =
                loop {
                    match *scope {
                        Scope::Binder { s, scope_type, .. } => {
                            match scope_type {
                                BinderScopeType::Normal => late_depth += 1,
                                BinderScopeType::Concatenating => {}
                            }
                            scope = s;
                        }
                        Scope::Root { .. } => break ResolvedArg::StaticLifetime,
                        Scope::Body { .. } | Scope::ObjectLifetimeDefault {
                            lifetime: None, .. } => return,
                        Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => {
                            break l.shifted(late_depth);
                        }
                        Scope::Opaque { captures, def_id, s } => {
                            opaque_capture_scopes.push((def_id, captures));
                            late_depth = 0;
                            scope = s;
                        }
                        Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s,
                            .. } | Scope::LateBoundary { s, .. } => {
                            scope = s;
                        }
                    }
                };
            lifetime =
                self.remap_opaque_captures(&opaque_capture_scopes, lifetime,
                    lifetime_ref.ident);
            self.insert_lifetime(lifetime_ref, lifetime);
        }
    }
}#[instrument(level = "debug", skip(self))]
2196    fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2197        let mut late_depth = 0;
2198        let mut scope = self.scope;
2199        let mut opaque_capture_scopes = vec![];
2200        let mut lifetime = loop {
2201            match *scope {
2202                Scope::Binder { s, scope_type, .. } => {
2203                    match scope_type {
2204                        BinderScopeType::Normal => late_depth += 1,
2205                        BinderScopeType::Concatenating => {}
2206                    }
2207                    scope = s;
2208                }
2209
2210                Scope::Root { .. } => break ResolvedArg::StaticLifetime,
2211
2212                Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2213
2214                Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => {
2215                    break l.shifted(late_depth);
2216                }
2217
2218                Scope::Opaque { captures, def_id, s } => {
2219                    opaque_capture_scopes.push((def_id, captures));
2220                    late_depth = 0;
2221                    scope = s;
2222                }
2223
2224                Scope::Supertrait { s, .. }
2225                | Scope::TraitRefBoundary { s, .. }
2226                | Scope::LateBoundary { s, .. } => {
2227                    scope = s;
2228                }
2229            }
2230        };
2231
2232        lifetime = self.remap_opaque_captures(&opaque_capture_scopes, lifetime, lifetime_ref.ident);
2233
2234        self.insert_lifetime(lifetime_ref, lifetime);
2235    }
2236
2237    #[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(2237u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime_ref");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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