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