Skip to main content

rustc_hir_analysis/collect/
generics_of.rs

1use std::assert_matches;
2use std::ops::ControlFlow;
3
4use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level};
5use rustc_hir::def::DefKind;
6use rustc_hir::def_id::LocalDefId;
7use rustc_hir::intravisit::{self, Visitor};
8use rustc_hir::{self as hir, AmbigArg, GenericParamKind, HirId, Node};
9use rustc_lint_defs::builtin::INVALID_TYPE_PARAM_DEFAULT;
10use rustc_middle::span_bug;
11use rustc_middle::ty::{self, TyCtxt};
12use rustc_span::{Span, kw, sym};
13use tracing::{debug, instrument};
14
15use crate::middle::resolve_bound_vars as rbv;
16
17{}
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("generics_of",
                                "rustc_hir_analysis::collect::generics_of",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs"),
                                ::tracing_core::__macro_support::Option::Some(17u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::generics_of"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("def_id");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: ty::Generics = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        use rustc_hir::*;
                        struct GenericParametersForbiddenHere {
                            msg: &'static str,
                        }
                        impl<'a> Diagnostic<'a, ()> for
                            GenericParametersForbiddenHere {
                            fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level)
                                -> Diag<'a, ()> {
                                let Self { msg } = self;
                                Diag::new(dcx, level, msg)
                            }
                        }
                        if let Some(ty::ImplTraitInTraitData::Trait {
                                fn_def_id, opaque_def_id }) =
                                tcx.opt_rpitit_info(def_id.to_def_id()) {
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs:37",
                                                    "rustc_hir_analysis::collect::generics_of",
                                                    ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(37u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::generics_of"),
                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::EVENT)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let enabled =
                                    ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        {
                                            let interest = __CALLSITE.interest();
                                            !interest.is_never() &&
                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                    interest)
                                        };
                                if enabled {
                                    (|value_set: ::tracing::field::ValueSet|
                                                {
                                                    let meta = __CALLSITE.metadata();
                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                    ;
                                                })({
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("RPITIT fn_def_id={0:?} opaque_def_id={1:?}",
                                                                                fn_def_id, opaque_def_id) as
                                                                        &dyn ::tracing::field::Value))])
                                        });
                                } else { ; }
                            };
                            let trait_def_id = tcx.parent(fn_def_id);
                            let opaque_ty_generics = tcx.generics_of(opaque_def_id);
                            let opaque_ty_parent_count =
                                opaque_ty_generics.parent_count;
                            let mut own_params = opaque_ty_generics.own_params.clone();
                            let parent_generics = tcx.generics_of(trait_def_id);
                            let parent_count =
                                parent_generics.parent_count +
                                    parent_generics.own_params.len();
                            let mut trait_fn_params =
                                tcx.generics_of(fn_def_id).own_params.clone();
                            for param in &mut own_params {
                                param.index =
                                    param.index + parent_count as u32 +
                                            trait_fn_params.len() as u32 -
                                        opaque_ty_parent_count as u32;
                            }
                            trait_fn_params.extend(own_params);
                            own_params = trait_fn_params;
                            let param_def_id_to_index =
                                own_params.iter().map(|param|
                                            (param.def_id, param.index)).collect();
                            return ty::Generics {
                                    parent: Some(trait_def_id),
                                    parent_count,
                                    own_params,
                                    param_def_id_to_index,
                                    has_self: opaque_ty_generics.has_self,
                                    has_late_bound_regions: opaque_ty_generics.has_late_bound_regions,
                                };
                        }
                        let hir_id = tcx.local_def_id_to_hir_id(def_id);
                        let node = tcx.hir_node(hir_id);
                        let parent_def_id =
                            match node {
                                Node::ImplItem(_) | Node::TraitItem(_) | Node::Variant(_) |
                                    Node::Ctor(..) | Node::Field(_) => {
                                    let parent_id = tcx.hir_get_parent_item(hir_id);
                                    Some(parent_id.def_id)
                                }
                                Node::AnonConst(_) => {
                                    let parent_did = tcx.local_parent(def_id);
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs:85",
                                                            "rustc_hir_analysis::collect::generics_of",
                                                            ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(85u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::generics_of"),
                                                            ::tracing_core::field::FieldSet::new(&[{
                                                                                const NAME:
                                                                                    ::tracing::__macro_support::FieldName<{
                                                                                        ::tracing::__macro_support::FieldName::len("parent_did")
                                                                                    }> =
                                                                                    ::tracing::__macro_support::FieldName::new("parent_did");
                                                                                NAME.as_str()
                                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_did)
                                                                                as &dyn ::tracing::field::Value))])
                                                });
                                        } else { ; }
                                    };
                                    let mut in_param_ty = false;
                                    for (_parent, node) in tcx.hir_parent_iter(hir_id) {
                                        if let Some(generics) = node.generics() {
                                            let mut visitor =
                                                AnonConstInParamTyDetector {
                                                    in_param_ty: false,
                                                    ct: hir_id,
                                                };
                                            in_param_ty = visitor.visit_generics(generics).is_break();
                                            break;
                                        }
                                    }
                                    match tcx.anon_const_kind(def_id) {
                                        ty::AnonConstKind::MCG => None,
                                        ty::AnonConstKind::RepeatExprCount => Some(parent_did),
                                        ty::AnonConstKind::GCE if in_param_ty => None,
                                        ty::AnonConstKind::GCE if
                                            let Some(param_id) =
                                                tcx.hir_opt_const_param_default_param_def_id(hir_id) => {
                                            let parent_def_id = tcx.local_parent(param_id);
                                            let generics = tcx.generics_of(parent_def_id);
                                            let param_def_idx =
                                                generics.param_def_id_to_index[&param_id.to_def_id()];
                                            let own_params =
                                                generics.params_to(param_def_idx as usize, tcx).to_owned();
                                            let param_def_id_to_index =
                                                own_params.iter().map(|param|
                                                            (param.def_id, param.index)).collect();
                                            return ty::Generics {
                                                    parent: generics.parent,
                                                    parent_count: generics.parent_count,
                                                    own_params,
                                                    param_def_id_to_index,
                                                    has_self: generics.has_self,
                                                    has_late_bound_regions: generics.has_late_bound_regions,
                                                };
                                        }
                                        ty::AnonConstKind::GCE => Some(parent_did),
                                        ty::AnonConstKind::NonTypeSystemAnon if
                                            #[allow(non_exhaustive_omitted_patterns)] match tcx.parent_hir_node(hir_id)
                                                {
                                                Node::TyPat(_) | Node::Field(_) => true,
                                                _ => false,
                                            } => {
                                            Some(parent_did)
                                        }
                                        ty::AnonConstKind::NonTypeSystemAnon => None,
                                        ty::AnonConstKind::NonTypeSystemInline =>
                                            ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
                                                format_args!("a DefKind::AnonConst with a HIR parent of hir::Node::AnonConst should never be an AnonConstKind::NonTypeSystemInline")),
                                    }
                                }
                                Node::ConstBlock(_) |
                                    Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. },
                                    .. }) => {
                                    Some(tcx.typeck_root_def_id_local(def_id))
                                }
                                Node::OpaqueTy(&hir::OpaqueTy {
                                    origin: hir::OpaqueTyOrigin::FnReturn {
                                        parent: fn_def_id, in_trait_or_impl } |
                                        hir::OpaqueTyOrigin::AsyncFn {
                                        parent: fn_def_id, in_trait_or_impl }, .. }) => {
                                    if in_trait_or_impl.is_some() {
                                        {
                                            match tcx.def_kind(fn_def_id) {
                                                DefKind::AssocFn => {}
                                                ref left_val => {
                                                    ::core::panicking::assert_matches_failed(left_val,
                                                        "DefKind::AssocFn", ::core::option::Option::None);
                                                }
                                            }
                                        };
                                    } else {
                                        {
                                            match tcx.def_kind(fn_def_id) {
                                                DefKind::AssocFn | DefKind::Fn => {}
                                                ref left_val => {
                                                    ::core::panicking::assert_matches_failed(left_val,
                                                        "DefKind::AssocFn | DefKind::Fn",
                                                        ::core::option::Option::None);
                                                }
                                            }
                                        };
                                    }
                                    Some(fn_def_id)
                                }
                                Node::OpaqueTy(&hir::OpaqueTy {
                                    origin: hir::OpaqueTyOrigin::TyAlias {
                                        parent, in_assoc_ty
                                        }, .. }) => {
                                    if in_assoc_ty {
                                        {
                                            match tcx.def_kind(parent) {
                                                DefKind::AssocTy => {}
                                                ref left_val => {
                                                    ::core::panicking::assert_matches_failed(left_val,
                                                        "DefKind::AssocTy", ::core::option::Option::None);
                                                }
                                            }
                                        };
                                    } else {
                                        {
                                            match tcx.def_kind(parent) {
                                                DefKind::TyAlias => {}
                                                ref left_val => {
                                                    ::core::panicking::assert_matches_failed(left_val,
                                                        "DefKind::TyAlias", ::core::option::Option::None);
                                                }
                                            }
                                        };
                                    }
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs:205",
                                                            "rustc_hir_analysis::collect::generics_of",
                                                            ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(205u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::generics_of"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("generics_of: parent of opaque ty {0:?} is {1:?}",
                                                                                        def_id, parent) as &dyn ::tracing::field::Value))])
                                                });
                                        } else { ; }
                                    };
                                    Some(parent)
                                }
                                Node::Item(_) | Node::ForeignItem(_) => None,
                                Node::GenericParam(_) => None,
                                Node::Synthetic =>
                                    ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
                                        format_args!("synthetic HIR should have its `generics_of` explicitly fed")),
                                Node::ConstArg(..) |
                                    Node::Infer(hir::InferArg { kind: hir::InferArgKind::Const,
                                    .. }) => {
                                    if true {
                                        if !tcx.features().min_generic_const_args() {
                                            ::core::panicking::panic("assertion failed: tcx.features().min_generic_const_args()")
                                        };
                                    };
                                    Some(tcx.local_parent(def_id))
                                }
                                _ =>
                                    ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
                                        format_args!("generics_of: unexpected node kind {0:?}",
                                            node)),
                            };
                        let opt_self =
                            if let Node::Item(item) = node &&
                                    let ItemKind::Trait { .. } | ItemKind::TraitAlias(..) =
                                        item.kind {
                                Some(ty::GenericParamDef {
                                        index: 0,
                                        name: kw::SelfUpper,
                                        def_id: def_id.to_def_id(),
                                        pure_wrt_drop: false,
                                        kind: ty::GenericParamDefKind::Type {
                                            has_default: false,
                                            synthetic: false,
                                        },
                                    })
                            } else { None };
                        let param_default_policy = param_default_policy(node);
                        let hir_generics =
                            node.generics().unwrap_or(hir::Generics::empty());
                        let has_self = opt_self.is_some();
                        let mut parent_has_self = false;
                        let mut own_start = has_self as u32;
                        let parent_count =
                            parent_def_id.map_or(0,
                                |def_id|
                                    {
                                        let generics = tcx.generics_of(def_id);
                                        if !!has_self {
                                            ::core::panicking::panic("assertion failed: !has_self")
                                        };
                                        parent_has_self = generics.has_self;
                                        let count = generics.count();
                                        own_start = count as u32;
                                        count
                                    });
                        let mut own_params: Vec<_> =
                            Vec::with_capacity(hir_generics.params.len() +
                                    has_self as usize);
                        if let Some(opt_self) = opt_self {
                            own_params.push(opt_self);
                        }
                        let early_lifetimes =
                            super::early_bound_lifetimes_from_generics(tcx,
                                hir_generics);
                        own_params.extend(early_lifetimes.enumerate().map(|(i,
                                        param)|
                                    ty::GenericParamDef {
                                        name: param.name.ident().name,
                                        index: own_start + i as u32,
                                        def_id: param.def_id.to_def_id(),
                                        pure_wrt_drop: param.pure_wrt_drop,
                                        kind: ty::GenericParamDefKind::Lifetime,
                                    }));
                        let type_start =
                            own_start - has_self as u32 + own_params.len() as u32;
                        let mut i: u32 = 0;
                        let mut next_index =
                            || { let prev = i; i += 1; prev + type_start };
                        own_params.extend(hir_generics.params.iter().filter_map(|param|
                                    {
                                        const MESSAGE: &str =
                                            "defaults for generic parameters are not allowed here";
                                        let kind =
                                            match param.kind {
                                                GenericParamKind::Lifetime { .. } => return None,
                                                GenericParamKind::Type { default, synthetic } => {
                                                    if default.is_some() {
                                                        match param_default_policy.expect("no policy for generic param default")
                                                            {
                                                            ParamDefaultPolicy::Allowed => {}
                                                            ParamDefaultPolicy::FutureCompatForbidden => {
                                                                tcx.emit_node_span_lint(INVALID_TYPE_PARAM_DEFAULT,
                                                                    param.hir_id, param.span,
                                                                    GenericParametersForbiddenHere { msg: MESSAGE });
                                                            }
                                                            ParamDefaultPolicy::Forbidden => {
                                                                tcx.dcx().span_err(param.span, MESSAGE);
                                                            }
                                                        }
                                                    }
                                                    ty::GenericParamDefKind::Type {
                                                        has_default: default.is_some(),
                                                        synthetic,
                                                    }
                                                }
                                                GenericParamKind::Const { ty: _, default } => {
                                                    if default.is_some() {
                                                        match param_default_policy.expect("no policy for generic param default")
                                                            {
                                                            ParamDefaultPolicy::Allowed => {}
                                                            ParamDefaultPolicy::FutureCompatForbidden |
                                                                ParamDefaultPolicy::Forbidden => {
                                                                tcx.dcx().span_err(param.span, MESSAGE);
                                                            }
                                                        }
                                                    }
                                                    ty::GenericParamDefKind::Const {
                                                        has_default: default.is_some(),
                                                    }
                                                }
                                            };
                                        Some(ty::GenericParamDef {
                                                index: next_index(),
                                                name: param.name.ident().name,
                                                def_id: param.def_id.to_def_id(),
                                                pure_wrt_drop: param.pure_wrt_drop,
                                                kind,
                                            })
                                    }));
                        if let Node::Expr(&hir::Expr {
                                kind: hir::ExprKind::Closure(hir::Closure { kind, .. }), ..
                                }) = node {
                            let len =
                                match kind {
                                    ClosureKind::Closure => 3,
                                    ClosureKind::Coroutine(_) => 5,
                                    ClosureKind::CoroutineClosure(_) => 4,
                                };
                            own_params.extend((0..len).map(|_|
                                        ty::GenericParamDef {
                                            index: next_index(),
                                            name: sym::empty,
                                            def_id: def_id.to_def_id(),
                                            pure_wrt_drop: false,
                                            kind: ty::GenericParamDefKind::Type {
                                                has_default: false,
                                                synthetic: false,
                                            },
                                        }));
                        }
                        if let Node::ConstBlock(_) = node {
                            own_params.push(ty::GenericParamDef {
                                    index: next_index(),
                                    name: rustc_span::sym::const_ty_placeholder,
                                    def_id: def_id.to_def_id(),
                                    pure_wrt_drop: false,
                                    kind: ty::GenericParamDefKind::Type {
                                        has_default: false,
                                        synthetic: false,
                                    },
                                });
                        }
                        if let Node::OpaqueTy(&hir::OpaqueTy { .. }) = node {
                            if !own_params.is_empty() {
                                ::core::panicking::panic("assertion failed: own_params.is_empty()")
                            };
                            let lifetimes = tcx.opaque_captured_lifetimes(def_id);
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs:379",
                                                    "rustc_hir_analysis::collect::generics_of",
                                                    ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(379u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::generics_of"),
                                                    ::tracing_core::field::FieldSet::new(&[{
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("lifetimes")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("lifetimes");
                                                                        NAME.as_str()
                                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::EVENT)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let enabled =
                                    ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        {
                                            let interest = __CALLSITE.interest();
                                            !interest.is_never() &&
                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                    interest)
                                        };
                                if enabled {
                                    (|value_set: ::tracing::field::ValueSet|
                                                {
                                                    let meta = __CALLSITE.metadata();
                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                    ;
                                                })({
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetimes)
                                                                        as &dyn ::tracing::field::Value))])
                                        });
                                } else { ; }
                            };
                            own_params.extend(lifetimes.iter().map(|&(_, param)|
                                        ty::GenericParamDef {
                                            name: tcx.item_name(param.to_def_id()),
                                            index: next_index(),
                                            def_id: param.to_def_id(),
                                            pure_wrt_drop: false,
                                            kind: ty::GenericParamDefKind::Lifetime,
                                        }))
                        }
                        let param_def_id_to_index =
                            own_params.iter().map(|param|
                                        (param.def_id, param.index)).collect();
                        ty::Generics {
                            parent: parent_def_id.map(LocalDefId::to_def_id),
                            parent_count,
                            own_params,
                            param_def_id_to_index,
                            has_self: has_self || parent_has_self,
                            has_late_bound_regions: has_late_bound_regions(tcx, node),
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs:17",
                        "rustc_hir_analysis::collect::generics_of",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect/generics_of.rs"),
                        ::tracing_core::__macro_support::Option::Some(17u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::generics_of"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
18pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
19    use rustc_hir::*;
20
21    struct GenericParametersForbiddenHere {
22        msg: &'static str,
23    }
24
25    impl<'a> Diagnostic<'a, ()> for GenericParametersForbiddenHere {
26        fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
27            let Self { msg } = self;
28            Diag::new(dcx, level, msg)
29        }
30    }
31
32    // For an RPITIT, synthesize generics which are equal to the opaque's generics
33    // and parent fn's generics compressed into one list.
34    if let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
35        tcx.opt_rpitit_info(def_id.to_def_id())
36    {
37        debug!("RPITIT fn_def_id={fn_def_id:?} opaque_def_id={opaque_def_id:?}");
38        let trait_def_id = tcx.parent(fn_def_id);
39        let opaque_ty_generics = tcx.generics_of(opaque_def_id);
40        let opaque_ty_parent_count = opaque_ty_generics.parent_count;
41        let mut own_params = opaque_ty_generics.own_params.clone();
42
43        let parent_generics = tcx.generics_of(trait_def_id);
44        let parent_count = parent_generics.parent_count + parent_generics.own_params.len();
45
46        let mut trait_fn_params = tcx.generics_of(fn_def_id).own_params.clone();
47
48        for param in &mut own_params {
49            param.index = param.index + parent_count as u32 + trait_fn_params.len() as u32
50                - opaque_ty_parent_count as u32;
51        }
52
53        trait_fn_params.extend(own_params);
54        own_params = trait_fn_params;
55
56        let param_def_id_to_index =
57            own_params.iter().map(|param| (param.def_id, param.index)).collect();
58
59        return ty::Generics {
60            parent: Some(trait_def_id),
61            parent_count,
62            own_params,
63            param_def_id_to_index,
64            has_self: opaque_ty_generics.has_self,
65            has_late_bound_regions: opaque_ty_generics.has_late_bound_regions,
66        };
67    }
68
69    let hir_id = tcx.local_def_id_to_hir_id(def_id);
70    let node = tcx.hir_node(hir_id);
71
72    let parent_def_id = match node {
73        Node::ImplItem(_)
74        | Node::TraitItem(_)
75        | Node::Variant(_)
76        | Node::Ctor(..)
77        | Node::Field(_) => {
78            let parent_id = tcx.hir_get_parent_item(hir_id);
79            Some(parent_id.def_id)
80        }
81        // FIXME(#43408) always enable this once `lazy_normalization` is
82        // stable enough and does not need a feature gate anymore.
83        Node::AnonConst(_) => {
84            let parent_did = tcx.local_parent(def_id);
85            debug!(?parent_did);
86
87            let mut in_param_ty = false;
88            for (_parent, node) in tcx.hir_parent_iter(hir_id) {
89                if let Some(generics) = node.generics() {
90                    let mut visitor = AnonConstInParamTyDetector { in_param_ty: false, ct: hir_id };
91
92                    in_param_ty = visitor.visit_generics(generics).is_break();
93                    break;
94                }
95            }
96
97            match tcx.anon_const_kind(def_id) {
98                // Stable: anon consts are not able to use any generic parameters...
99                ty::AnonConstKind::MCG => None,
100                // we provide generics to repeat expr counts as a backwards compatibility hack. #76200
101                ty::AnonConstKind::RepeatExprCount => Some(parent_did),
102
103                // Even GCE anon const should not be allowed to use generic parameters as it would be
104                // trivially forward declared uses once desugared. E.g. `const N: [u8; ANON::<N>]`.
105                //
106                // We could potentially mirror the hack done for defaults of generic parameters but
107                // this case just doesn't come up much compared to `const N: u32 = ...`. Long term the
108                // hack for defaulted parameters should be removed eventually anyway.
109                ty::AnonConstKind::GCE if in_param_ty => None,
110                // GCE anon consts as a default for a generic parameter should have their provided generics
111                // "truncated" up to whatever generic parameter this anon const is within the default of.
112                //
113                // FIXME(generic_const_exprs): This only handles `const N: usize = /*defid*/` but not type
114                // parameter defaults, e.g. `T = Foo</*defid*/>`.
115                ty::AnonConstKind::GCE
116                    if let Some(param_id) =
117                        tcx.hir_opt_const_param_default_param_def_id(hir_id) =>
118                {
119                    // If the def_id we are calling generics_of on is an anon ct default i.e:
120                    //
121                    // struct Foo<const N: usize = { .. }>;
122                    //        ^^^       ^          ^^^^^^ def id of this anon const
123                    //        ^         ^ param_id
124                    //        ^ parent_def_id
125                    //
126                    // then we only want to return generics for params to the left of `N`. If we don't do that we
127                    // end up with that const looking like: `ty::ConstKind::Alias(def_id, args: [N#0])`.
128                    //
129                    // This causes ICEs (#86580) when building the args for Foo in `fn foo() -> Foo { .. }` as
130                    // we instantiate the defaults with the partially built args when we build the args. Instantiating
131                    // the `N#0` on the alias const indexes into the empty args we're in the process of building.
132                    //
133                    // We fix this by having this function return the parent's generics ourselves and truncating the
134                    // generics to only include non-forward declared params (with the exception of the `Self` ty)
135                    //
136                    // For the above code example that means we want `args: []`
137                    // For the following struct def we want `args: [N#0]` when generics_of is called on
138                    // the def id of the `{ N + 1 }` anon const
139                    // struct Foo<const N: usize, const M: usize = { N + 1 }>;
140                    //
141                    // This has some implications for how we get the clauses available to the anon const
142                    // see `explicit_clauses_of` for more information on this
143                    let parent_def_id = tcx.local_parent(param_id);
144                    let generics = tcx.generics_of(parent_def_id);
145                    let param_def_idx = generics.param_def_id_to_index[&param_id.to_def_id()];
146                    // In the above example this would be .params[..N#0]
147                    let own_params = generics.params_to(param_def_idx as usize, tcx).to_owned();
148                    let param_def_id_to_index =
149                        own_params.iter().map(|param| (param.def_id, param.index)).collect();
150
151                    return ty::Generics {
152                        // we set the parent of these generics to be our parent's parent so that we
153                        // dont end up with args: [N, M, N] for the const default on a struct like this:
154                        // struct Foo<const N: usize, const M: usize = { ... }>;
155                        parent: generics.parent,
156                        parent_count: generics.parent_count,
157                        own_params,
158                        param_def_id_to_index,
159                        has_self: generics.has_self,
160                        has_late_bound_regions: generics.has_late_bound_regions,
161                    };
162                }
163                ty::AnonConstKind::GCE => Some(parent_did),
164
165                // Field defaults are allowed to use generic parameters, e.g. `field: u32 = /*defid: N + 1*/`
166                ty::AnonConstKind::NonTypeSystemAnon
167                    if matches!(tcx.parent_hir_node(hir_id), Node::TyPat(_) | Node::Field(_)) =>
168                {
169                    Some(parent_did)
170                }
171                // Default to no generic parameters for other kinds of anon consts
172                ty::AnonConstKind::NonTypeSystemAnon => None,
173                ty::AnonConstKind::NonTypeSystemInline => span_bug!(
174                    tcx.def_span(def_id),
175                    "a DefKind::AnonConst with a HIR parent of hir::Node::AnonConst should never be an AnonConstKind::NonTypeSystemInline"
176                ),
177            }
178        }
179        Node::ConstBlock(_)
180        | Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
181            Some(tcx.typeck_root_def_id_local(def_id))
182        }
183        Node::OpaqueTy(&hir::OpaqueTy {
184            origin:
185                hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, in_trait_or_impl }
186                | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
187            ..
188        }) => {
189            if in_trait_or_impl.is_some() {
190                assert_matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn);
191            } else {
192                assert_matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn);
193            }
194            Some(fn_def_id)
195        }
196        Node::OpaqueTy(&hir::OpaqueTy {
197            origin: hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty },
198            ..
199        }) => {
200            if in_assoc_ty {
201                assert_matches!(tcx.def_kind(parent), DefKind::AssocTy);
202            } else {
203                assert_matches!(tcx.def_kind(parent), DefKind::TyAlias);
204            }
205            debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent);
206            // Opaque types are always nested within another item, and
207            // inherit the generics of the item.
208            Some(parent)
209        }
210
211        // All of these nodes have no parent from which to inherit generics.
212        Node::Item(_) | Node::ForeignItem(_) => None,
213
214        // Params don't really have generics, but we use it when instantiating their value paths.
215        Node::GenericParam(_) => None,
216
217        Node::Synthetic => span_bug!(
218            tcx.def_span(def_id),
219            "synthetic HIR should have its `generics_of` explicitly fed"
220        ),
221
222        Node::ConstArg(..) | Node::Infer(hir::InferArg { kind: hir::InferArgKind::Const, .. }) => {
223            // These can show up in mGCA when representing "direct" const arguments. The
224            // DefCollector cannot know whether an anon const will be represented by an actual HIR
225            // Node::AnonConst, or whether it will be represented directly, so it must generate a
226            // DefId. If it ends up being direct, this DefId is then attached to the top-level
227            // ConstArg, which is what we are seeing here.
228            debug_assert!(tcx.features().min_generic_const_args());
229            // Forward to the real parent.
230            Some(tcx.local_parent(def_id))
231        }
232
233        _ => span_bug!(tcx.def_span(def_id), "generics_of: unexpected node kind {node:?}"),
234    };
235
236    // Add in the self type parameter.
237    let opt_self = if let Node::Item(item) = node
238        && let ItemKind::Trait { .. } | ItemKind::TraitAlias(..) = item.kind
239    {
240        // Something of a hack: We reuse the node ID of the trait for the self type parameter.
241        Some(ty::GenericParamDef {
242            index: 0,
243            name: kw::SelfUpper,
244            def_id: def_id.to_def_id(),
245            pure_wrt_drop: false,
246            kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
247        })
248    } else {
249        None
250    };
251
252    let param_default_policy = param_default_policy(node);
253    let hir_generics = node.generics().unwrap_or(hir::Generics::empty());
254    let has_self = opt_self.is_some();
255    let mut parent_has_self = false;
256    let mut own_start = has_self as u32;
257    let parent_count = parent_def_id.map_or(0, |def_id| {
258        let generics = tcx.generics_of(def_id);
259        assert!(!has_self);
260        parent_has_self = generics.has_self;
261        let count = generics.count();
262        own_start = count as u32;
263        count
264    });
265
266    let mut own_params: Vec<_> = Vec::with_capacity(hir_generics.params.len() + has_self as usize);
267
268    if let Some(opt_self) = opt_self {
269        own_params.push(opt_self);
270    }
271
272    let early_lifetimes = super::early_bound_lifetimes_from_generics(tcx, hir_generics);
273    own_params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
274        name: param.name.ident().name,
275        index: own_start + i as u32,
276        def_id: param.def_id.to_def_id(),
277        pure_wrt_drop: param.pure_wrt_drop,
278        kind: ty::GenericParamDefKind::Lifetime,
279    }));
280
281    // Now create the real type and const parameters.
282    let type_start = own_start - has_self as u32 + own_params.len() as u32;
283    let mut i: u32 = 0;
284    let mut next_index = || {
285        let prev = i;
286        i += 1;
287        prev + type_start
288    };
289
290    own_params.extend(hir_generics.params.iter().filter_map(|param| {
291        const MESSAGE: &str = "defaults for generic parameters are not allowed here";
292        let kind = match param.kind {
293            GenericParamKind::Lifetime { .. } => return None,
294            GenericParamKind::Type { default, synthetic } => {
295                if default.is_some() {
296                    match param_default_policy.expect("no policy for generic param default") {
297                        ParamDefaultPolicy::Allowed => {}
298                        ParamDefaultPolicy::FutureCompatForbidden => {
299                            tcx.emit_node_span_lint(
300                                INVALID_TYPE_PARAM_DEFAULT,
301                                param.hir_id,
302                                param.span,
303                                GenericParametersForbiddenHere { msg: MESSAGE },
304                            );
305                        }
306                        ParamDefaultPolicy::Forbidden => {
307                            tcx.dcx().span_err(param.span, MESSAGE);
308                        }
309                    }
310                }
311
312                ty::GenericParamDefKind::Type { has_default: default.is_some(), synthetic }
313            }
314            GenericParamKind::Const { ty: _, default } => {
315                if default.is_some() {
316                    match param_default_policy.expect("no policy for generic param default") {
317                        ParamDefaultPolicy::Allowed => {}
318                        ParamDefaultPolicy::FutureCompatForbidden
319                        | ParamDefaultPolicy::Forbidden => {
320                            tcx.dcx().span_err(param.span, MESSAGE);
321                        }
322                    }
323                }
324
325                ty::GenericParamDefKind::Const { has_default: default.is_some() }
326            }
327        };
328        Some(ty::GenericParamDef {
329            index: next_index(),
330            name: param.name.ident().name,
331            def_id: param.def_id.to_def_id(),
332            pure_wrt_drop: param.pure_wrt_drop,
333            kind,
334        })
335    }));
336
337    // provide junk type parameter defs - the only place that
338    // cares about anything but the length is instantiation,
339    // and we don't do that for closures.
340    if let Node::Expr(&hir::Expr {
341        kind: hir::ExprKind::Closure(hir::Closure { kind, .. }), ..
342    }) = node
343    {
344        // See `ClosureArgsParts`, `CoroutineArgsParts`, and `CoroutineClosureArgsParts`
345        // for info on the usage of each of these fields.
346        let len = match kind {
347            // The args are: closure_kind, closure_signature, upvars.
348            ClosureKind::Closure => 3,
349            // The args are: coroutine_kind, resume_ty, yield_ty, return_ty, upvars.
350            ClosureKind::Coroutine(_) => 5,
351            // The args are: closure_kind, closure_signature_parts, upvars, bound_captures_by_ref.
352            ClosureKind::CoroutineClosure(_) => 4,
353        };
354
355        own_params.extend((0..len).map(|_| ty::GenericParamDef {
356            index: next_index(),
357            name: sym::empty, // dummy; exact value doesn't matter
358            def_id: def_id.to_def_id(),
359            pure_wrt_drop: false,
360            kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
361        }));
362    }
363
364    // provide junk type parameter defs for const blocks.
365    if let Node::ConstBlock(_) = node {
366        own_params.push(ty::GenericParamDef {
367            index: next_index(),
368            name: rustc_span::sym::const_ty_placeholder,
369            def_id: def_id.to_def_id(),
370            pure_wrt_drop: false,
371            kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
372        });
373    }
374
375    if let Node::OpaqueTy(&hir::OpaqueTy { .. }) = node {
376        assert!(own_params.is_empty());
377
378        let lifetimes = tcx.opaque_captured_lifetimes(def_id);
379        debug!(?lifetimes);
380
381        own_params.extend(lifetimes.iter().map(|&(_, param)| ty::GenericParamDef {
382            name: tcx.item_name(param.to_def_id()),
383            index: next_index(),
384            def_id: param.to_def_id(),
385            pure_wrt_drop: false,
386            kind: ty::GenericParamDefKind::Lifetime,
387        }))
388    }
389
390    let param_def_id_to_index =
391        own_params.iter().map(|param| (param.def_id, param.index)).collect();
392
393    ty::Generics {
394        parent: parent_def_id.map(LocalDefId::to_def_id),
395        parent_count,
396        own_params,
397        param_def_id_to_index,
398        has_self: has_self || parent_has_self,
399        has_late_bound_regions: has_late_bound_regions(tcx, node),
400    }
401}
402
403#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ParamDefaultPolicy { }
#[automatically_derived]
impl ::core::clone::Clone for ParamDefaultPolicy {
    #[inline]
    fn clone(&self) -> ParamDefaultPolicy { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ParamDefaultPolicy { }Copy)]
404enum ParamDefaultPolicy {
405    Allowed,
406    /// Tracked in <https://github.com/rust-lang/rust/issues/36887>.
407    FutureCompatForbidden,
408    Forbidden,
409}
410
411fn param_default_policy(node: Node<'_>) -> Option<ParamDefaultPolicy> {
412    use rustc_hir::*;
413
414    Some(match node {
415        Node::Item(item) => match item.kind {
416            ItemKind::Trait { .. }
417            | ItemKind::TraitAlias(..)
418            | ItemKind::TyAlias(..)
419            | ItemKind::Enum(..)
420            | ItemKind::Struct(..)
421            | ItemKind::Union(..) => ParamDefaultPolicy::Allowed,
422            ItemKind::Fn { .. } | ItemKind::Impl(_) => ParamDefaultPolicy::FutureCompatForbidden,
423            // Re. GCI, we're not bound by backward compatibility.
424            ItemKind::Const(..) => ParamDefaultPolicy::Forbidden,
425            _ => return None,
426        },
427        Node::TraitItem(item) => match item.kind {
428            // Re. GATs and GACs (generic_const_items), we're not bound by backward compatibility.
429            TraitItemKind::Const(..) | TraitItemKind::Type(..) => ParamDefaultPolicy::Forbidden,
430            TraitItemKind::Fn(..) => ParamDefaultPolicy::FutureCompatForbidden,
431        },
432        Node::ImplItem(item) => match item.kind {
433            // Re. GATs and GACs (generic_const_items), we're not bound by backward compatibility.
434            ImplItemKind::Const(..) | ImplItemKind::Type(..) => ParamDefaultPolicy::Forbidden,
435            ImplItemKind::Fn(..) => ParamDefaultPolicy::FutureCompatForbidden,
436        },
437        // Generic params are (semantically) invalid on foreign items. Still, for maximum forward
438        // compatibility, let's hard-reject defaults on them.
439        Node::ForeignItem(_) => ParamDefaultPolicy::Forbidden,
440        Node::OpaqueTy(..) => ParamDefaultPolicy::Allowed,
441        _ => return None,
442    })
443}
444
445fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
446    struct LateBoundRegionsDetector<'tcx> {
447        tcx: TyCtxt<'tcx>,
448        outer_index: ty::DebruijnIndex,
449    }
450
451    impl<'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
452        type Result = ControlFlow<Span>;
453        fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx, AmbigArg>) -> ControlFlow<Span> {
454            match ty.kind {
455                hir::TyKind::FnPtr(..) => {
456                    self.outer_index.shift_in(1);
457                    let res = intravisit::walk_ty(self, ty);
458                    self.outer_index.shift_out(1);
459                    res
460                }
461                hir::TyKind::UnsafeBinder(_) => {
462                    self.outer_index.shift_in(1);
463                    let res = intravisit::walk_ty(self, ty);
464                    self.outer_index.shift_out(1);
465                    res
466                }
467                _ => intravisit::walk_ty(self, ty),
468            }
469        }
470
471        fn visit_poly_trait_ref(&mut self, tr: &'tcx hir::PolyTraitRef<'tcx>) -> ControlFlow<Span> {
472            self.outer_index.shift_in(1);
473            let res = intravisit::walk_poly_trait_ref(self, tr);
474            self.outer_index.shift_out(1);
475            res
476        }
477
478        fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) -> ControlFlow<Span> {
479            match self.tcx.named_bound_var(lt.hir_id) {
480                Some(rbv::ResolvedArg::StaticLifetime | rbv::ResolvedArg::EarlyBound(..)) => {
481                    ControlFlow::Continue(())
482                }
483                Some(rbv::ResolvedArg::LateBound(debruijn, _, _))
484                    if debruijn < self.outer_index =>
485                {
486                    ControlFlow::Continue(())
487                }
488                Some(
489                    rbv::ResolvedArg::LateBound(..)
490                    | rbv::ResolvedArg::Free(..)
491                    | rbv::ResolvedArg::Error(_),
492                )
493                | None => ControlFlow::Break(lt.ident.span),
494            }
495        }
496    }
497
498    fn has_late_bound_regions<'tcx>(
499        tcx: TyCtxt<'tcx>,
500        generics: &'tcx hir::Generics<'tcx>,
501        decl: &'tcx hir::FnDecl<'tcx>,
502    ) -> Option<Span> {
503        let mut visitor = LateBoundRegionsDetector { tcx, outer_index: ty::INNERMOST };
504        for param in generics.params {
505            if let GenericParamKind::Lifetime { .. } = param.kind {
506                if tcx.is_late_bound(param.hir_id) {
507                    return Some(param.span);
508                }
509            }
510        }
511        visitor.visit_fn_decl(decl).break_value()
512    }
513
514    let decl = node.fn_decl()?;
515    let generics = node.generics()?;
516    has_late_bound_regions(tcx, generics, decl)
517}
518
519struct AnonConstInParamTyDetector {
520    in_param_ty: bool,
521    ct: HirId,
522}
523
524impl<'v> Visitor<'v> for AnonConstInParamTyDetector {
525    type Result = ControlFlow<()>;
526
527    fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) -> Self::Result {
528        if let GenericParamKind::Const { ty, default: _ } = p.kind {
529            let prev = self.in_param_ty;
530            self.in_param_ty = true;
531            let res = self.visit_ty_unambig(ty);
532            self.in_param_ty = prev;
533            res
534        } else {
535            ControlFlow::Continue(())
536        }
537    }
538
539    fn visit_anon_const(&mut self, c: &'v hir::AnonConst) -> Self::Result {
540        if self.in_param_ty && self.ct == c.hir_id {
541            return ControlFlow::Break(());
542        }
543        intravisit::walk_anon_const(self, c)
544    }
545}