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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(def_id) = self.parent {
                tcx.predicates_of(def_id).instantiate_into(tcx, instantiated,
                    args);
            }
            instantiated.predicates.extend(self.predicates.iter().map(|(p, _)|
                        EarlyBinder::bind(*p).instantiate(tcx, args)));
            instantiated.spans.extend(self.predicates.iter().map(|(_, sp)|
                        *sp));
        }
    }
}#[instrument(level = "debug", skip(self, tcx))]
396    fn instantiate_into(
397        self,
398        tcx: TyCtxt<'tcx>,
399        instantiated: &mut InstantiatedPredicates<'tcx>,
400        args: GenericArgsRef<'tcx>,
401    ) {
402        if let Some(def_id) = self.parent {
403            tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, args);
404        }
405        instantiated.predicates.extend(
406            self.predicates.iter().map(|(p, _)| EarlyBinder::bind(*p).instantiate(tcx, args)),
407        );
408        instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
409    }
410
411    pub fn instantiate_identity(self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
412        let mut instantiated = InstantiatedPredicates::empty();
413        self.instantiate_identity_into(tcx, &mut instantiated);
414        instantiated
415    }
416
417    fn instantiate_identity_into(
418        self,
419        tcx: TyCtxt<'tcx>,
420        instantiated: &mut InstantiatedPredicates<'tcx>,
421    ) {
422        if let Some(def_id) = self.parent {
423            tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
424        }
425        instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
426        instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
427    }
428}
429
430/// `[const]` bounds for a given item. This is represented using a struct much like
431/// `GenericPredicates`, where you can either choose to only instantiate the "own"
432/// bounds or all of the bounds including those from the parent. This distinction
433/// is necessary for code like `compare_method_predicate_entailment`.
434#[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, '__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for ConstConditions<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    ConstConditions {
                        parent: ref __binding_0, predicates: ref __binding_1 } => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable)]
435pub struct ConstConditions<'tcx> {
436    pub parent: Option<DefId>,
437    pub predicates: &'tcx [(ty::PolyTraitRef<'tcx>, Span)],
438}
439
440impl<'tcx> ConstConditions<'tcx> {
441    pub fn instantiate(
442        self,
443        tcx: TyCtxt<'tcx>,
444        args: GenericArgsRef<'tcx>,
445    ) -> Vec<(ty::PolyTraitRef<'tcx>, Span)> {
446        let mut instantiated = ::alloc::vec::Vec::new()vec![];
447        self.instantiate_into(tcx, &mut instantiated, args);
448        instantiated
449    }
450
451    pub fn instantiate_own(
452        self,
453        tcx: TyCtxt<'tcx>,
454        args: GenericArgsRef<'tcx>,
455    ) -> impl Iterator<Item = (ty::PolyTraitRef<'tcx>, Span)> + DoubleEndedIterator + ExactSizeIterator
456    {
457        EarlyBinder::bind(self.predicates).iter_instantiated_copied(tcx, args)
458    }
459
460    pub fn instantiate_own_identity(
461        self,
462    ) -> impl Iterator<Item = (ty::PolyTraitRef<'tcx>, Span)> + DoubleEndedIterator + ExactSizeIterator
463    {
464        EarlyBinder::bind(self.predicates).iter_identity_copied()
465    }
466
467    #[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(467u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::generics"),
                                    ::tracing_core::field::FieldSet::new(&["instantiated",
                                                    "args"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instantiated)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(def_id) = self.parent {
                tcx.const_conditions(def_id).instantiate_into(tcx,
                    instantiated, args);
            }
            instantiated.extend(self.predicates.iter().map(|&(p, s)|
                        (EarlyBinder::bind(p).instantiate(tcx, args), s)));
        }
    }
}#[instrument(level = "debug", skip(self, tcx))]
468    fn instantiate_into(
469        self,
470        tcx: TyCtxt<'tcx>,
471        instantiated: &mut Vec<(ty::PolyTraitRef<'tcx>, Span)>,
472        args: GenericArgsRef<'tcx>,
473    ) {
474        if let Some(def_id) = self.parent {
475            tcx.const_conditions(def_id).instantiate_into(tcx, instantiated, args);
476        }
477        instantiated.extend(
478            self.predicates.iter().map(|&(p, s)| (EarlyBinder::bind(p).instantiate(tcx, args), s)),
479        );
480    }
481
482    pub fn instantiate_identity(self, tcx: TyCtxt<'tcx>) -> Vec<(ty::PolyTraitRef<'tcx>, Span)> {
483        let mut instantiated = ::alloc::vec::Vec::new()vec![];
484        self.instantiate_identity_into(tcx, &mut instantiated);
485        instantiated
486    }
487
488    fn instantiate_identity_into(
489        self,
490        tcx: TyCtxt<'tcx>,
491        instantiated: &mut Vec<(ty::PolyTraitRef<'tcx>, Span)>,
492    ) {
493        if let Some(def_id) = self.parent {
494            tcx.const_conditions(def_id).instantiate_identity_into(tcx, instantiated);
495        }
496        instantiated.extend(self.predicates.iter().copied());
497    }
498}