Skip to main content

rustc_hir_analysis/collect/
resolve_bound_vars.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.with(Scope::ObjectLifetimeDefault {
                    lifetime: Some(ResolvedArg::StaticLifetime),
                    s: self.scope,
                },
                |this|
                    {
                        for input in inputs { this.visit_ty_unambig(input); }
                        if !in_closure && let Some(output) = output {
                            this.visit_ty_unambig(output);
                        }
                    });
            if in_closure && let Some(output) = output {
                self.visit_ty_unambig(output);
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1989    fn visit_fn_like_elision(
1990        &mut self,
1991        inputs: &'tcx [hir::Ty<'tcx>],
1992        output: Option<&'tcx hir::Ty<'tcx>>,
1993        in_closure: bool,
1994    ) {
1995        self.with(
1996            Scope::ObjectLifetimeDefault {
1997                lifetime: Some(ResolvedArg::StaticLifetime),
1998                s: self.scope,
1999            },
2000            |this| {
2001                for input in inputs {
2002                    this.visit_ty_unambig(input);
2003                }
2004                if !in_closure && let Some(output) = output {
2005                    this.visit_ty_unambig(output);
2006                }
2007            },
2008        );
2009        if in_closure && let Some(output) = output {
2010            self.visit_ty_unambig(output);
2011        }
2012    }
2013
2014    #[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(2014u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut late_depth = 0;
            let mut scope = self.scope;
            let mut opaque_capture_scopes = ::alloc::vec::Vec::new();
            let mut lifetime =
                loop {
                    match *scope {
                        Scope::Binder { s, scope_type, .. } => {
                            match scope_type {
                                BinderScopeType::Normal => late_depth += 1,
                                BinderScopeType::Concatenating => {}
                            }
                            scope = s;
                        }
                        Scope::Root { .. } => break ResolvedArg::StaticLifetime,
                        Scope::Body { .. } | Scope::ObjectLifetimeDefault {
                            lifetime: None, .. } => return,
                        Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => {
                            break l.shifted(late_depth);
                        }
                        Scope::Opaque { captures, def_id, s } => {
                            opaque_capture_scopes.push((def_id, captures));
                            late_depth = 0;
                            scope = s;
                        }
                        Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s,
                            .. } | Scope::LateBoundary { s, .. } => {
                            scope = s;
                        }
                    }
                };
            lifetime =
                self.remap_opaque_captures(&opaque_capture_scopes, lifetime,
                    lifetime_ref.ident);
            self.insert_lifetime(lifetime_ref, lifetime);
        }
    }
}#[instrument(level = "debug", skip(self))]
2015    fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2016        let mut late_depth = 0;
2017        let mut scope = self.scope;
2018        let mut opaque_capture_scopes = vec![];
2019        let mut lifetime = loop {
2020            match *scope {
2021                Scope::Binder { s, scope_type, .. } => {
2022                    match scope_type {
2023                        BinderScopeType::Normal => late_depth += 1,
2024                        BinderScopeType::Concatenating => {}
2025                    }
2026                    scope = s;
2027                }
2028
2029                Scope::Root { .. } => break ResolvedArg::StaticLifetime,
2030
2031                Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2032
2033                Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => {
2034                    break l.shifted(late_depth);
2035                }
2036
2037                Scope::Opaque { captures, def_id, s } => {
2038                    opaque_capture_scopes.push((def_id, captures));
2039                    late_depth = 0;
2040                    scope = s;
2041                }
2042
2043                Scope::Supertrait { s, .. }
2044                | Scope::TraitRefBoundary { s, .. }
2045                | Scope::LateBoundary { s, .. } => {
2046                    scope = s;
2047                }
2048            }
2049        };
2050
2051        lifetime = self.remap_opaque_captures(&opaque_capture_scopes, lifetime, lifetime_ref.ident);
2052
2053        self.insert_lifetime(lifetime_ref, lifetime);
2054    }
2055
2056    #[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(2056u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::resolve_bound_vars"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime_ref",
                                                    "def"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime_ref)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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