Skip to main content

rustc_middle/ty/
generics.rs

1use rustc_ast as ast;
2use rustc_data_structures::fx::FxHashMap;
3use rustc_hir::def_id::DefId;
4use rustc_macros::{StableHash, TyDecodable, TyEncodable};
5use rustc_span::{Span, Symbol, kw};
6use tracing::instrument;
7
8use super::{Clause, InstantiatedPredicates, ParamConst, ParamTy, Ty, TyCtxt, Unnormalized};
9use crate::ty;
10use crate::ty::region::RegionExt;
11use crate::ty::{EarlyBinder, GenericArgsRef};
12
13#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericParamDefKind {
    #[inline]
    fn clone(&self) -> GenericParamDefKind {
        match self {
            GenericParamDefKind::Lifetime => GenericParamDefKind::Lifetime,
            GenericParamDefKind::Type {
                has_default: __self_0, synthetic: __self_1 } =>
                GenericParamDefKind::Type {
                    has_default: ::core::clone::Clone::clone(__self_0),
                    synthetic: ::core::clone::Clone::clone(__self_1),
                },
            GenericParamDefKind::Const { has_default: __self_0 } =>
                GenericParamDefKind::Const {
                    has_default: ::core::clone::Clone::clone(__self_0),
                },
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericParamDefKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            GenericParamDefKind::Lifetime =>
                ::core::fmt::Formatter::write_str(f, "Lifetime"),
            GenericParamDefKind::Type {
                has_default: __self_0, synthetic: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Type",
                    "has_default", __self_0, "synthetic", &__self_1),
            GenericParamDefKind::Const { has_default: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Const",
                    "has_default", &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for GenericParamDefKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        GenericParamDefKind::Lifetime => { 0usize }
                        GenericParamDefKind::Type {
                            has_default: ref __binding_0, synthetic: ref __binding_1 }
                            => {
                            1usize
                        }
                        GenericParamDefKind::Const { has_default: ref __binding_0 }
                            => {
                            2usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    GenericParamDefKind::Lifetime => {}
                    GenericParamDefKind::Type {
                        has_default: ref __binding_0, synthetic: ref __binding_1 }
                        => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    GenericParamDefKind::Const { has_default: ref __binding_0 }
                        => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for GenericParamDefKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { GenericParamDefKind::Lifetime }
                    1usize => {
                        GenericParamDefKind::Type {
                            has_default: ::rustc_serialize::Decodable::decode(__decoder),
                            synthetic: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    2usize => {
                        GenericParamDefKind::Const {
                            has_default: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `GenericParamDefKind`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            GenericParamDefKind {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    GenericParamDefKind::Lifetime => {}
                    GenericParamDefKind::Type {
                        has_default: ref __binding_0, synthetic: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    GenericParamDefKind::Const { has_default: ref __binding_0 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
14pub enum GenericParamDefKind {
15    Lifetime,
16    Type { has_default: bool, synthetic: bool },
17    Const { has_default: bool },
18}
19
20impl GenericParamDefKind {
21    pub fn descr(&self) -> &'static str {
22        match self {
23            GenericParamDefKind::Lifetime => "lifetime",
24            GenericParamDefKind::Type { .. } => "type",
25            GenericParamDefKind::Const { .. } => "constant",
26        }
27    }
28    pub fn to_ord(&self) -> ast::ParamKindOrd {
29        match self {
30            GenericParamDefKind::Lifetime => ast::ParamKindOrd::Lifetime,
31            GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
32                ast::ParamKindOrd::TypeOrConst
33            }
34        }
35    }
36
37    pub fn is_ty_or_const(&self) -> bool {
38        match self {
39            GenericParamDefKind::Lifetime => false,
40            GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => true,
41        }
42    }
43
44    pub fn is_synthetic(&self) -> bool {
45        match self {
46            GenericParamDefKind::Type { synthetic, .. } => *synthetic,
47            _ => false,
48        }
49    }
50}
51
52#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericParamDef {
    #[inline]
    fn clone(&self) -> GenericParamDef {
        GenericParamDef {
            name: ::core::clone::Clone::clone(&self.name),
            def_id: ::core::clone::Clone::clone(&self.def_id),
            index: ::core::clone::Clone::clone(&self.index),
            pure_wrt_drop: ::core::clone::Clone::clone(&self.pure_wrt_drop),
            kind: ::core::clone::Clone::clone(&self.kind),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericParamDef {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "GenericParamDef", "name", &self.name, "def_id", &self.def_id,
            "index", &self.index, "pure_wrt_drop", &self.pure_wrt_drop,
            "kind", &&self.kind)
    }
}Debug, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for GenericParamDef {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    GenericParamDef {
                        name: ref __binding_0,
                        def_id: ref __binding_1,
                        index: ref __binding_2,
                        pure_wrt_drop: ref __binding_3,
                        kind: ref __binding_4 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_3,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_4,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for GenericParamDef {
            fn decode(__decoder: &mut __D) -> Self {
                GenericParamDef {
                    name: ::rustc_serialize::Decodable::decode(__decoder),
                    def_id: ::rustc_serialize::Decodable::decode(__decoder),
                    index: ::rustc_serialize::Decodable::decode(__decoder),
                    pure_wrt_drop: ::rustc_serialize::Decodable::decode(__decoder),
                    kind: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            GenericParamDef {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    GenericParamDef {
                        name: ref __binding_0,
                        def_id: ref __binding_1,
                        index: ref __binding_2,
                        pure_wrt_drop: ref __binding_3,
                        kind: ref __binding_4 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                        { __binding_4.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
53pub struct GenericParamDef {
54    pub name: Symbol,
55    pub def_id: DefId,
56    pub index: u32,
57
58    /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
59    /// on generic parameter `'a`/`T`, asserts data behind the parameter
60    /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
61    pub pure_wrt_drop: bool,
62
63    pub kind: GenericParamDefKind,
64}
65
66impl GenericParamDef {
67    pub fn to_early_bound_region_data(&self) -> ty::EarlyParamRegion {
68        if let GenericParamDefKind::Lifetime = self.kind {
69            ty::EarlyParamRegion { index: self.index, name: self.name }
70        } else {
71            crate::util::bug::bug_fmt(format_args!("cannot convert a non-lifetime parameter def to an early bound region"))bug!("cannot convert a non-lifetime parameter def to an early bound region")
72        }
73    }
74
75    pub fn is_anonymous_lifetime(&self) -> bool {
76        match self.kind {
77            GenericParamDefKind::Lifetime => self.name == kw::UnderscoreLifetime,
78            _ => false,
79        }
80    }
81
82    pub fn default_value<'tcx>(
83        &self,
84        tcx: TyCtxt<'tcx>,
85    ) -> Option<EarlyBinder<'tcx, ty::GenericArg<'tcx>>> {
86        match self.kind {
87            GenericParamDefKind::Type { has_default: true, .. } => {
88                Some(tcx.type_of(self.def_id).map_bound(|t| t.into()))
89            }
90            GenericParamDefKind::Const { has_default: true, .. } => {
91                Some(tcx.const_param_default(self.def_id).map_bound(|c| c.into()))
92            }
93            _ => None,
94        }
95    }
96
97    pub fn to_error<'tcx>(&self, tcx: TyCtxt<'tcx>) -> ty::GenericArg<'tcx> {
98        match &self.kind {
99            ty::GenericParamDefKind::Lifetime => ty::Region::new_error_misc(tcx).into(),
100            ty::GenericParamDefKind::Type { .. } => Ty::new_misc_error(tcx).into(),
101            ty::GenericParamDefKind::Const { .. } => ty::Const::new_misc_error(tcx).into(),
102        }
103    }
104}
105
106#[derive(#[automatically_derived]
impl ::core::default::Default for GenericParamCount {
    #[inline]
    fn default() -> GenericParamCount {
        GenericParamCount {
            lifetimes: ::core::default::Default::default(),
            types: ::core::default::Default::default(),
            consts: ::core::default::Default::default(),
        }
    }
}Default)]
107pub struct GenericParamCount {
108    pub lifetimes: usize,
109    pub types: usize,
110    pub consts: usize,
111}
112
113/// Information about the formal type/lifetime parameters associated
114/// with an item or method. Analogous to `hir::Generics`.
115///
116/// The ordering of parameters is the same as in [`ty::GenericArg`] (excluding child generics):
117/// `Self` (optionally), `Lifetime` params..., `Type` params...
118#[derive(#[automatically_derived]
impl ::core::clone::Clone for Generics {
    #[inline]
    fn clone(&self) -> Generics {
        Generics {
            parent: ::core::clone::Clone::clone(&self.parent),
            parent_count: ::core::clone::Clone::clone(&self.parent_count),
            own_params: ::core::clone::Clone::clone(&self.own_params),
            param_def_id_to_index: ::core::clone::Clone::clone(&self.param_def_id_to_index),
            has_self: ::core::clone::Clone::clone(&self.has_self),
            has_late_bound_regions: ::core::clone::Clone::clone(&self.has_late_bound_regions),
        }
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for Generics {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    Generics {
                        parent: ref __binding_0,
                        parent_count: ref __binding_1,
                        own_params: ref __binding_2,
                        param_def_id_to_index: ref __binding_3,
                        has_self: ref __binding_4,
                        has_late_bound_regions: ref __binding_5 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_3,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_4,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_5,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for Generics {
            fn decode(__decoder: &mut __D) -> Self {
                Generics {
                    parent: ::rustc_serialize::Decodable::decode(__decoder),
                    parent_count: ::rustc_serialize::Decodable::decode(__decoder),
                    own_params: ::rustc_serialize::Decodable::decode(__decoder),
                    param_def_id_to_index: ::rustc_serialize::Decodable::decode(__decoder),
                    has_self: ::rustc_serialize::Decodable::decode(__decoder),
                    has_late_bound_regions: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Generics {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Generics {
                        parent: ref __binding_0,
                        parent_count: ref __binding_1,
                        own_params: ref __binding_2,
                        param_def_id_to_index: ref __binding_3,
                        has_self: ref __binding_4,
                        has_late_bound_regions: ref __binding_5 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        {}
                        { __binding_4.stable_hash(__hcx, __hasher); }
                        { __binding_5.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
119pub struct Generics {
120    pub parent: Option<DefId>,
121    pub parent_count: usize,
122    pub own_params: Vec<GenericParamDef>,
123
124    /// Reverse map to the `index` field of each `GenericParamDef`.
125    #[stable_hash(ignore)]
126    pub param_def_id_to_index: FxHashMap<DefId, u32>,
127
128    pub has_self: bool,
129    pub has_late_bound_regions: Option<Span>,
130}
131
132impl std::fmt::Debug for Generics {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
134        // ironically, we get this warning because of what we're trying to fix.
135        #[expect(rustc::potential_query_instability)]
136        let mut stabilized_hashmap = self.param_def_id_to_index.iter().collect::<Vec<_>>();
137        stabilized_hashmap.sort_by_key(|(_, v)| **v);
138        f.debug_struct("Generics")
139            .field("parent", &self.parent)
140            .field("parent_count", &self.parent_count)
141            .field("own_params", &self.own_params)
142            .field("param_def_id_to_index", &stabilized_hashmap)
143            .field("has_self", &self.has_self)
144            .field("has_late_bound_regions", &self.has_late_bound_regions)
145            .finish()
146    }
147}
148
149impl<'tcx> rustc_type_ir::inherent::GenericsOf<TyCtxt<'tcx>> for &'tcx Generics {
150    fn count(&self) -> usize {
151        self.parent_count + self.own_params.len()
152    }
153}
154
155impl<'tcx> Generics {
156    /// Looks through the generics and all parents to find the index of the
157    /// given param def-id. This is in comparison to the `param_def_id_to_index`
158    /// struct member, which only stores information about this item's own
159    /// generics.
160    pub fn param_def_id_to_index(&self, tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<u32> {
161        if let Some(idx) = self.param_def_id_to_index.get(&def_id) {
162            Some(*idx)
163        } else if let Some(parent) = self.parent {
164            let parent = tcx.generics_of(parent);
165            parent.param_def_id_to_index(tcx, def_id)
166        } else {
167            None
168        }
169    }
170
171    #[inline]
172    pub fn count(&self) -> usize {
173        self.parent_count + self.own_params.len()
174    }
175
176    pub fn own_counts(&self) -> GenericParamCount {
177        // We could cache this as a property of `GenericParamCount`, but
178        // the aim is to refactor this away entirely eventually and the
179        // presence of this method will be a constant reminder.
180        let mut own_counts = GenericParamCount::default();
181
182        for param in &self.own_params {
183            match param.kind {
184                GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
185                GenericParamDefKind::Type { .. } => own_counts.types += 1,
186                GenericParamDefKind::Const { .. } => own_counts.consts += 1,
187            }
188        }
189
190        own_counts
191    }
192
193    pub fn own_defaults(&self) -> GenericParamCount {
194        let mut own_defaults = GenericParamCount::default();
195
196        for param in &self.own_params {
197            match param.kind {
198                GenericParamDefKind::Lifetime => (),
199                GenericParamDefKind::Type { has_default, .. } => {
200                    own_defaults.types += has_default as usize;
201                }
202                GenericParamDefKind::Const { has_default, .. } => {
203                    own_defaults.consts += has_default as usize;
204                }
205            }
206        }
207
208        own_defaults
209    }
210
211    pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
212        if self.own_requires_monomorphization() {
213            return true;
214        }
215
216        if let Some(parent_def_id) = self.parent {
217            let parent = tcx.generics_of(parent_def_id);
218            parent.requires_monomorphization(tcx)
219        } else {
220            false
221        }
222    }
223
224    pub fn own_requires_monomorphization(&self) -> bool {
225        for param in &self.own_params {
226            match param.kind {
227                GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
228                    return true;
229                }
230                GenericParamDefKind::Lifetime => {}
231            }
232        }
233        false
234    }
235
236    /// Returns the `GenericParamDef` with the given index.
237    pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
238        if let Some(index) = param_index.checked_sub(self.parent_count) {
239            &self.own_params[index]
240        } else {
241            tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
242                .param_at(param_index, tcx)
243        }
244    }
245
246    pub fn params_to(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx [GenericParamDef] {
247        if let Some(index) = param_index.checked_sub(self.parent_count) {
248            &self.own_params[..index]
249        } else {
250            tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
251                .params_to(param_index, tcx)
252        }
253    }
254
255    /// Returns the `GenericParamDef` associated with this `EarlyParamRegion`.
256    pub fn region_param(
257        &'tcx self,
258        param: ty::EarlyParamRegion,
259        tcx: TyCtxt<'tcx>,
260    ) -> &'tcx GenericParamDef {
261        let param = self.param_at(param.index as usize, tcx);
262        match param.kind {
263            GenericParamDefKind::Lifetime => param,
264            _ => {
265                crate::util::bug::bug_fmt(format_args!("expected lifetime parameter, but found another generic parameter: {0:#?}",
        param))bug!("expected lifetime parameter, but found another generic parameter: {param:#?}")
266            }
267        }
268    }
269
270    /// Returns the `GenericParamDef` associated with this `ParamTy`.
271    pub fn type_param(&'tcx self, param: ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
272        let param = self.param_at(param.index as usize, tcx);
273        match param.kind {
274            GenericParamDefKind::Type { .. } => param,
275            _ => crate::util::bug::bug_fmt(format_args!("expected type parameter, but found another generic parameter: {0:#?}",
        param))bug!("expected type parameter, but found another generic parameter: {param:#?}"),
276        }
277    }
278
279    /// Returns the `GenericParamDef` associated with this `ParamConst`.
280    pub fn const_param(&'tcx self, param: ParamConst, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
281        let param = self.param_at(param.index as usize, tcx);
282        match param.kind {
283            GenericParamDefKind::Const { .. } => param,
284            _ => crate::util::bug::bug_fmt(format_args!("expected const parameter, but found another generic parameter: {0:#?}",
        param))bug!("expected const parameter, but found another generic parameter: {param:#?}"),
285        }
286    }
287
288    /// Returns `true` if `params` has `impl Trait`.
289    pub fn has_impl_trait(&'tcx self) -> bool {
290        self.own_params.iter().any(|param| {
291            #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ty::GenericParamDefKind::Type { synthetic: true, .. } => true,
    _ => false,
}matches!(param.kind, ty::GenericParamDefKind::Type { synthetic: true, .. })
292        })
293    }
294
295    pub fn own_synthetic_params_count(&'tcx self) -> usize {
296        self.own_params.iter().filter(|p| p.kind.is_synthetic()).count()
297    }
298
299    /// Returns the args corresponding to the generic parameters
300    /// of this item, excluding `Self`.
301    ///
302    /// **This should only be used for diagnostics purposes.**
303    pub fn own_args_no_defaults<'a>(
304        &'tcx self,
305        tcx: TyCtxt<'tcx>,
306        args: &'a [ty::GenericArg<'tcx>],
307    ) -> &'a [ty::GenericArg<'tcx>] {
308        let mut own_params = self.parent_count..self.count();
309        if self.has_own_self() {
310            own_params.start = 1;
311        }
312
313        // Filter the default arguments.
314        //
315        // This currently uses structural equality instead
316        // of semantic equivalence. While not ideal, that's
317        // good enough for now as this should only be used
318        // for diagnostics anyways.
319        own_params.end -= self
320            .own_params
321            .iter()
322            .rev()
323            .take_while(|param| {
324                param.default_value(tcx).is_some_and(|default| {
325                    default.instantiate(tcx, args).skip_norm_wip() == args[param.index as usize]
326                })
327            })
328            .count();
329
330        &args[own_params]
331    }
332
333    /// Returns the args corresponding to the generic parameters of this item, excluding `Self`.
334    ///
335    /// **This should only be used for diagnostics purposes.**
336    pub fn own_args(
337        &'tcx self,
338        args: &'tcx [ty::GenericArg<'tcx>],
339    ) -> &'tcx [ty::GenericArg<'tcx>] {
340        let own = &args[self.parent_count..][..self.own_params.len()];
341        if self.has_own_self() { &own[1..] } else { own }
342    }
343
344    /// Returns true if a concrete type is specified after a default type.
345    /// For example, consider `struct T<W = usize, X = Vec<W>>(W, X)`
346    /// `T<usize, String>` will return true
347    /// `T<usize>` will return false
348    pub fn check_concrete_type_after_default(
349        &'tcx self,
350        tcx: TyCtxt<'tcx>,
351        args: &'tcx [ty::GenericArg<'tcx>],
352    ) -> bool {
353        let mut default_param_seen = false;
354        for param in self.own_params.iter() {
355            if let Some(inst) = param
356                .default_value(tcx)
357                .map(|default| default.instantiate(tcx, args).skip_norm_wip())
358            {
359                if inst == args[param.index as usize] {
360                    default_param_seen = true;
361                } else if default_param_seen {
362                    return true;
363                }
364            }
365        }
366        false
367    }
368
369    pub fn is_empty(&'tcx self) -> bool {
370        self.count() == 0
371    }
372
373    pub fn is_own_empty(&'tcx self) -> bool {
374        self.own_params.is_empty()
375    }
376
377    pub fn has_own_self(&'tcx self) -> bool {
378        self.has_self && self.parent.is_none()
379    }
380}
381
382/// Bounds on generics.
383#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for GenericPredicates<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for GenericPredicates<'tcx> {
    #[inline]
    fn clone(&self) -> GenericPredicates<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Option<DefId>>;
        let _:
                ::core::clone::AssertParamIsClone<&'tcx [(Clause<'tcx>,
                Span)]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::default::Default for GenericPredicates<'tcx> {
    #[inline]
    fn default() -> GenericPredicates<'tcx> {
        GenericPredicates {
            parent: ::core::default::Default::default(),
            predicates: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for GenericPredicates<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "GenericPredicates", "parent", &self.parent, "predicates",
            &&self.predicates)
    }
}Debug, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for GenericPredicates<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    GenericPredicates {
                        parent: ref __binding_0, predicates: __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for GenericPredicates<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                GenericPredicates {
                    parent: ::rustc_serialize::Decodable::decode(__decoder),
                    predicates: ::rustc_middle::ty::codec::RefDecodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            GenericPredicates<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    GenericPredicates {
                        parent: ref __binding_0, predicates: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
384pub struct GenericPredicates<'tcx> {
385    pub parent: Option<DefId>,
386    pub predicates: &'tcx [(Clause<'tcx>, Span)],
387}
388
389impl<'tcx> GenericPredicates<'tcx> {
390    pub fn instantiate(
391        self,
392        tcx: TyCtxt<'tcx>,
393        args: GenericArgsRef<'tcx>,
394    ) -> InstantiatedPredicates<'tcx> {
395        let mut instantiated = InstantiatedPredicates::empty();
396        self.instantiate_into(tcx, &mut instantiated, args);
397        instantiated
398    }
399
400    pub fn instantiate_own(
401        self,
402        tcx: TyCtxt<'tcx>,
403        args: GenericArgsRef<'tcx>,
404    ) -> impl Iterator<Item = (Unnormalized<'tcx, Clause<'tcx>>, Span)>
405    + DoubleEndedIterator
406    + ExactSizeIterator
407    + Clone {
408        EarlyBinder::bind_iter(self.predicates).iter_instantiated_copied(tcx, args).map(|u| {
409            let (clause, span) = u.unzip();
410            (clause, span.skip_normalization())
411        })
412    }
413
414    pub fn instantiate_own_identity(
415        self,
416    ) -> impl Iterator<Item = (Unnormalized<'tcx, Clause<'tcx>>, Span)>
417    + DoubleEndedIterator
418    + ExactSizeIterator
419    + Clone {
420        EarlyBinder::bind_iter(self.predicates).iter_identity_copied().map(|u| {
421            let (clause, span) = u.unzip();
422            (clause, span.skip_normalization())
423        })
424    }
425
426    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("instantiate_into",
                                    "rustc_middle::ty::generics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/generics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(426u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::generics"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instantiated")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instantiated");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        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(&instantiated)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(def_id) = self.parent {
                tcx.predicates_of(def_id).instantiate_into(tcx, instantiated,
                    args);
            }
            instantiated.predicates.extend(self.predicates.iter().map(|(p, _)|
                        EarlyBinder::bind(tcx, *p).instantiate(tcx, args)));
            instantiated.spans.extend(self.predicates.iter().map(|(_, sp)|
                        *sp));
        }
    }
}#[instrument(level = "debug", skip(self, tcx))]
427    fn instantiate_into(
428        self,
429        tcx: TyCtxt<'tcx>,
430        instantiated: &mut InstantiatedPredicates<'tcx>,
431        args: GenericArgsRef<'tcx>,
432    ) {
433        if let Some(def_id) = self.parent {
434            tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, args);
435        }
436        instantiated.predicates.extend(
437            self.predicates.iter().map(|(p, _)| EarlyBinder::bind(tcx, *p).instantiate(tcx, args)),
438        );
439        instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
440    }
441
442    pub fn instantiate_identity(self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
443        let mut instantiated = InstantiatedPredicates::empty();
444        self.instantiate_identity_into(tcx, &mut instantiated);
445        instantiated
446    }
447
448    fn instantiate_identity_into(
449        self,
450        tcx: TyCtxt<'tcx>,
451        instantiated: &mut InstantiatedPredicates<'tcx>,
452    ) {
453        if let Some(def_id) = self.parent {
454            tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
455        }
456        instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| Unnormalized::new(*p)));
457        instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
458    }
459}
460
461/// `[const]` bounds for a given item. This is represented using a struct much like
462/// `GenericPredicates`, where you can either choose to only instantiate the "own"
463/// bounds or all of the bounds including those from the parent. This distinction
464/// is necessary for code like `compare_method_predicate_entailment`.
465#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ConstConditions<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ConstConditions<'tcx> {
    #[inline]
    fn clone(&self) -> ConstConditions<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Option<DefId>>;
        let _:
                ::core::clone::AssertParamIsClone<&'tcx [(ty::PolyTraitRef<'tcx>,
                Span)]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::default::Default for ConstConditions<'tcx> {
    #[inline]
    fn default() -> ConstConditions<'tcx> {
        ConstConditions {
            parent: ::core::default::Default::default(),
            predicates: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ConstConditions<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ConstConditions", "parent", &self.parent, "predicates",
            &&self.predicates)
    }
}Debug, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for ConstConditions<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    ConstConditions {
                        parent: ref __binding_0, predicates: __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for ConstConditions<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                ConstConditions {
                    parent: ::rustc_serialize::Decodable::decode(__decoder),
                    predicates: ::rustc_middle::ty::codec::RefDecodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            ConstConditions<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ConstConditions {
                        parent: ref __binding_0, predicates: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
466pub struct ConstConditions<'tcx> {
467    pub parent: Option<DefId>,
468    pub predicates: &'tcx [(ty::PolyTraitRef<'tcx>, Span)],
469}
470
471impl<'tcx> ConstConditions<'tcx> {
472    pub fn instantiate(
473        self,
474        tcx: TyCtxt<'tcx>,
475        args: GenericArgsRef<'tcx>,
476    ) -> Vec<(Unnormalized<'tcx, ty::PolyTraitRef<'tcx>>, Span)> {
477        let mut instantiated = ::alloc::vec::Vec::new()vec![];
478        self.instantiate_into(tcx, &mut instantiated, args);
479        instantiated
480    }
481
482    pub fn instantiate_own(
483        self,
484        tcx: TyCtxt<'tcx>,
485        args: GenericArgsRef<'tcx>,
486    ) -> impl Iterator<Item = (Unnormalized<'tcx, ty::PolyTraitRef<'tcx>>, Span)>
487    + DoubleEndedIterator
488    + ExactSizeIterator
489    + Clone {
490        EarlyBinder::bind_iter(self.predicates).iter_instantiated_copied(tcx, args).map(|u| {
491            let (trait_ref, span) = u.unzip();
492            (trait_ref, span.skip_normalization())
493        })
494    }
495
496    pub fn instantiate_own_identity(
497        self,
498    ) -> impl Iterator<Item = (Unnormalized<'tcx, ty::PolyTraitRef<'tcx>>, Span)>
499    + DoubleEndedIterator
500    + ExactSizeIterator
501    + Clone {
502        EarlyBinder::bind_iter(self.predicates).iter_identity_copied().map(|u| {
503            let (trait_ref, span) = u.unzip();
504            (trait_ref, span.skip_normalization())
505        })
506    }
507
508    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("instantiate_into",
                                    "rustc_middle::ty::generics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/generics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(508u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::generics"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instantiated")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instantiated");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        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(&instantiated)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(def_id) = self.parent {
                tcx.const_conditions(def_id).instantiate_into(tcx,
                    instantiated, args);
            }
            instantiated.extend(self.predicates.iter().map(|&(p, s)|
                        (EarlyBinder::bind(tcx, p).instantiate(tcx, args), s)));
        }
    }
}#[instrument(level = "debug", skip(self, tcx))]
509    fn instantiate_into(
510        self,
511        tcx: TyCtxt<'tcx>,
512        instantiated: &mut Vec<(Unnormalized<'tcx, ty::PolyTraitRef<'tcx>>, Span)>,
513        args: GenericArgsRef<'tcx>,
514    ) {
515        if let Some(def_id) = self.parent {
516            tcx.const_conditions(def_id).instantiate_into(tcx, instantiated, args);
517        }
518        instantiated.extend(
519            self.predicates
520                .iter()
521                .map(|&(p, s)| (EarlyBinder::bind(tcx, p).instantiate(tcx, args), s)),
522        );
523    }
524
525    pub fn instantiate_identity(
526        self,
527        tcx: TyCtxt<'tcx>,
528    ) -> Vec<(Unnormalized<'tcx, ty::PolyTraitRef<'tcx>>, Span)> {
529        let mut instantiated = ::alloc::vec::Vec::new()vec![];
530        self.instantiate_identity_into(tcx, &mut instantiated);
531        instantiated
532    }
533
534    fn instantiate_identity_into(
535        self,
536        tcx: TyCtxt<'tcx>,
537        instantiated: &mut Vec<(Unnormalized<'tcx, ty::PolyTraitRef<'tcx>>, Span)>,
538    ) {
539        if let Some(def_id) = self.parent {
540            tcx.const_conditions(def_id).instantiate_identity_into(tcx, instantiated);
541        }
542        instantiated.extend(
543            self.predicates
544                .iter()
545                .copied()
546                .map(|(trait_ref, span)| (Unnormalized::new(trait_ref), span)),
547        );
548    }
549}