Skip to main content

rustc_middle/ty/
trait_def.rs

1use std::iter;
2
3use rustc_data_structures::fx::FxIndexMap;
4use rustc_errors::ErrorGuaranteed;
5use rustc_hir::attrs::AttributeKind;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE};
8use rustc_hir::{self as hir, find_attr};
9use rustc_macros::{Decodable, Encodable, HashStable};
10use rustc_span::Span;
11use tracing::debug;
12
13use crate::query::LocalCrate;
14use crate::traits::specialization_graph;
15use crate::ty::fast_reject::{self, SimplifiedType, TreatParams};
16use crate::ty::{Ident, Ty, TyCtxt};
17
18/// A trait's definition with type information.
19#[derive(const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
            for TraitDef {
            #[inline]
            fn hash_stable(&self,
                __hcx:
                    &mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    TraitDef {
                        def_id: ref __binding_0,
                        safety: ref __binding_1,
                        constness: ref __binding_2,
                        paren_sugar: ref __binding_3,
                        has_auto_impl: ref __binding_4,
                        is_marker: ref __binding_5,
                        is_coinductive: ref __binding_6,
                        is_fundamental: ref __binding_7,
                        skip_array_during_method_dispatch: ref __binding_8,
                        skip_boxed_slice_during_method_dispatch: ref __binding_9,
                        specialization_kind: ref __binding_10,
                        must_implement_one_of: ref __binding_11,
                        force_dyn_incompatible: ref __binding_12,
                        deny_explicit_impl: ref __binding_13 } => {
                        { __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); }
                        { __binding_5.hash_stable(__hcx, __hasher); }
                        { __binding_6.hash_stable(__hcx, __hasher); }
                        { __binding_7.hash_stable(__hcx, __hasher); }
                        { __binding_8.hash_stable(__hcx, __hasher); }
                        { __binding_9.hash_stable(__hcx, __hasher); }
                        { __binding_10.hash_stable(__hcx, __hasher); }
                        { __binding_11.hash_stable(__hcx, __hasher); }
                        { __binding_12.hash_stable(__hcx, __hasher); }
                        { __binding_13.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for TraitDef {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    TraitDef {
                        def_id: ref __binding_0,
                        safety: ref __binding_1,
                        constness: ref __binding_2,
                        paren_sugar: ref __binding_3,
                        has_auto_impl: ref __binding_4,
                        is_marker: ref __binding_5,
                        is_coinductive: ref __binding_6,
                        is_fundamental: ref __binding_7,
                        skip_array_during_method_dispatch: ref __binding_8,
                        skip_boxed_slice_during_method_dispatch: ref __binding_9,
                        specialization_kind: ref __binding_10,
                        must_implement_one_of: ref __binding_11,
                        force_dyn_incompatible: ref __binding_12,
                        deny_explicit_impl: ref __binding_13 } => {
                        ::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);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_6,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_7,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_8,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_9,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_10,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_11,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_12,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_13,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for TraitDef {
            fn decode(__decoder: &mut __D) -> Self {
                TraitDef {
                    def_id: ::rustc_serialize::Decodable::decode(__decoder),
                    safety: ::rustc_serialize::Decodable::decode(__decoder),
                    constness: ::rustc_serialize::Decodable::decode(__decoder),
                    paren_sugar: ::rustc_serialize::Decodable::decode(__decoder),
                    has_auto_impl: ::rustc_serialize::Decodable::decode(__decoder),
                    is_marker: ::rustc_serialize::Decodable::decode(__decoder),
                    is_coinductive: ::rustc_serialize::Decodable::decode(__decoder),
                    is_fundamental: ::rustc_serialize::Decodable::decode(__decoder),
                    skip_array_during_method_dispatch: ::rustc_serialize::Decodable::decode(__decoder),
                    skip_boxed_slice_during_method_dispatch: ::rustc_serialize::Decodable::decode(__decoder),
                    specialization_kind: ::rustc_serialize::Decodable::decode(__decoder),
                    must_implement_one_of: ::rustc_serialize::Decodable::decode(__decoder),
                    force_dyn_incompatible: ::rustc_serialize::Decodable::decode(__decoder),
                    deny_explicit_impl: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
20pub struct TraitDef {
21    pub def_id: DefId,
22
23    pub safety: hir::Safety,
24
25    /// Whether this trait is `const`.
26    pub constness: hir::Constness,
27
28    /// If `true`, then this trait had the `#[rustc_paren_sugar]`
29    /// attribute, indicating that it should be used with `Foo()`
30    /// sugar. This is a temporary thing -- eventually any trait will
31    /// be usable with the sugar (or without it).
32    pub paren_sugar: bool,
33
34    pub has_auto_impl: bool,
35
36    /// If `true`, then this trait has the `#[marker]` attribute, indicating
37    /// that all its associated items have defaults that cannot be overridden,
38    /// and thus `impl`s of it are allowed to overlap.
39    pub is_marker: bool,
40
41    /// If `true`, then this trait has the `#[rustc_coinductive]` attribute or
42    /// is an auto trait. This indicates that trait solver cycles involving an
43    /// `X: ThisTrait` goal are accepted.
44    ///
45    /// In the future all traits should be coinductive, but we need a better
46    /// formal understanding of what exactly that means and should probably
47    /// also have already switched to the new trait solver.
48    pub is_coinductive: bool,
49
50    /// If `true`, then this trait has the `#[fundamental]` attribute. This
51    /// affects how conherence computes whether a trait may have trait implementations
52    /// added in the future.
53    pub is_fundamental: bool,
54
55    /// If `true`, then this trait has the `#[rustc_skip_during_method_dispatch(array)]`
56    /// attribute, indicating that editions before 2021 should not consider this trait
57    /// during method dispatch if the receiver is an array.
58    pub skip_array_during_method_dispatch: bool,
59
60    /// If `true`, then this trait has the `#[rustc_skip_during_method_dispatch(boxed_slice)]`
61    /// attribute, indicating that editions before 2024 should not consider this trait
62    /// during method dispatch if the receiver is a boxed slice.
63    pub skip_boxed_slice_during_method_dispatch: bool,
64
65    /// Used to determine whether the standard library is allowed to specialize
66    /// on this trait.
67    pub specialization_kind: TraitSpecializationKind,
68
69    /// List of functions from `#[rustc_must_implement_one_of]` attribute one of which
70    /// must be implemented.
71    pub must_implement_one_of: Option<Box<[Ident]>>,
72
73    /// Whether the trait should be considered dyn-incompatible, even if it otherwise
74    /// satisfies the requirements to be dyn-compatible.
75    pub force_dyn_incompatible: Option<Span>,
76
77    /// Whether a trait is fully built-in, and any implementation is disallowed.
78    /// This only applies to built-in traits, and is marked via
79    /// `#[rustc_deny_explicit_impl]`.
80    pub deny_explicit_impl: bool,
81}
82
83/// Whether this trait is treated specially by the standard library
84/// specialization lint.
85#[derive(const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
            for TraitSpecializationKind {
            #[inline]
            fn hash_stable(&self,
                __hcx:
                    &mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                ::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
                match *self {
                    TraitSpecializationKind::None => {}
                    TraitSpecializationKind::Marker => {}
                    TraitSpecializationKind::AlwaysApplicable => {}
                }
            }
        }
    };HashStable, #[automatically_derived]
impl ::core::cmp::PartialEq for TraitSpecializationKind {
    #[inline]
    fn eq(&self, other: &TraitSpecializationKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for TraitSpecializationKind {
    #[inline]
    fn clone(&self) -> TraitSpecializationKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TraitSpecializationKind { }Copy, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for TraitSpecializationKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        TraitSpecializationKind::None => { 0usize }
                        TraitSpecializationKind::Marker => { 1usize }
                        TraitSpecializationKind::AlwaysApplicable => { 2usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    TraitSpecializationKind::None => {}
                    TraitSpecializationKind::Marker => {}
                    TraitSpecializationKind::AlwaysApplicable => {}
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for TraitSpecializationKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { TraitSpecializationKind::None }
                    1usize => { TraitSpecializationKind::Marker }
                    2usize => { TraitSpecializationKind::AlwaysApplicable }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `TraitSpecializationKind`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
86pub enum TraitSpecializationKind {
87    /// The default. Specializing on this trait is not allowed.
88    None,
89    /// Specializing on this trait is allowed because it doesn't have any
90    /// methods. For example `Sized` or `FusedIterator`.
91    /// Applies to traits with the `rustc_unsafe_specialization_marker`
92    /// attribute.
93    Marker,
94    /// Specializing on this trait is allowed because all of the impls of this
95    /// trait are "always applicable". Always applicable means that if
96    /// `X<'x>: T<'y>` for any lifetimes, then `for<'a, 'b> X<'a>: T<'b>`.
97    /// Applies to traits with the `rustc_specialization_trait` attribute.
98    AlwaysApplicable,
99}
100
101#[derive(#[automatically_derived]
impl ::core::default::Default for TraitImpls {
    #[inline]
    fn default() -> TraitImpls {
        TraitImpls {
            blanket_impls: ::core::default::Default::default(),
            non_blanket_impls: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl ::core::fmt::Debug for TraitImpls {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "TraitImpls",
            "blanket_impls", &self.blanket_impls, "non_blanket_impls",
            &&self.non_blanket_impls)
    }
}Debug, const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
            for TraitImpls {
            #[inline]
            fn hash_stable(&self,
                __hcx:
                    &mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    TraitImpls {
                        blanket_impls: ref __binding_0,
                        non_blanket_impls: ref __binding_1 } => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable)]
102pub struct TraitImpls {
103    blanket_impls: Vec<DefId>,
104    /// Impls indexed by their simplified self type, for fast lookup.
105    non_blanket_impls: FxIndexMap<SimplifiedType, Vec<DefId>>,
106}
107
108impl TraitImpls {
109    pub fn is_empty(&self) -> bool {
110        self.blanket_impls.is_empty() && self.non_blanket_impls.is_empty()
111    }
112
113    pub fn blanket_impls(&self) -> &[DefId] {
114        self.blanket_impls.as_slice()
115    }
116
117    pub fn non_blanket_impls(&self) -> &FxIndexMap<SimplifiedType, Vec<DefId>> {
118        &self.non_blanket_impls
119    }
120}
121
122impl<'tcx> TraitDef {
123    pub fn ancestors(
124        &self,
125        tcx: TyCtxt<'tcx>,
126        of_impl: DefId,
127    ) -> Result<specialization_graph::Ancestors<'tcx>, ErrorGuaranteed> {
128        specialization_graph::ancestors(tcx, self.def_id, of_impl)
129    }
130}
131
132impl<'tcx> TyCtxt<'tcx> {
133    /// Iterate over every impl that could possibly match the self type `self_ty`.
134    ///
135    /// `trait_def_id` MUST BE the `DefId` of a trait.
136    pub fn for_each_relevant_impl(
137        self,
138        trait_def_id: DefId,
139        self_ty: Ty<'tcx>,
140        mut f: impl FnMut(DefId),
141    ) {
142        // FIXME: This depends on the set of all impls for the trait. That is
143        // unfortunate wrt. incremental compilation.
144        //
145        // If we want to be faster, we could have separate queries for
146        // blanket and non-blanket impls, and compare them separately.
147        let impls = self.trait_impls_of(trait_def_id);
148
149        for &impl_def_id in impls.blanket_impls.iter() {
150            f(impl_def_id);
151        }
152
153        // This way, when searching for some impl for `T: Trait`, we do not look at any impls
154        // whose outer level is not a parameter or projection. Especially for things like
155        // `T: Clone` this is incredibly useful as we would otherwise look at all the impls
156        // of `Clone` for `Option<T>`, `Vec<T>`, `ConcreteType` and so on.
157        // Note that we're using `TreatParams::AsRigid` to query `non_blanket_impls` while using
158        // `TreatParams::InstantiateWithInfer` while actually adding them.
159        if let Some(simp) = fast_reject::simplify_type(self, self_ty, TreatParams::AsRigid) {
160            if let Some(impls) = impls.non_blanket_impls.get(&simp) {
161                for &impl_def_id in impls {
162                    f(impl_def_id);
163                }
164            }
165        } else {
166            for &impl_def_id in impls.non_blanket_impls.values().flatten() {
167                f(impl_def_id);
168            }
169        }
170    }
171
172    /// `trait_def_id` MUST BE the `DefId` of a trait.
173    pub fn non_blanket_impls_for_ty(
174        self,
175        trait_def_id: DefId,
176        self_ty: Ty<'tcx>,
177    ) -> impl Iterator<Item = DefId> {
178        let impls = self.trait_impls_of(trait_def_id);
179        if let Some(simp) =
180            fast_reject::simplify_type(self, self_ty, TreatParams::InstantiateWithInfer)
181        {
182            if let Some(impls) = impls.non_blanket_impls.get(&simp) {
183                return impls.iter().copied();
184            }
185        }
186
187        [].iter().copied()
188    }
189
190    /// Returns an iterator containing all impls for `trait_def_id`.
191    ///
192    /// `trait_def_id` MUST BE the `DefId` of a trait.
193    pub fn all_impls(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> {
194        let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(trait_def_id);
195
196        blanket_impls.iter().chain(non_blanket_impls.iter().flat_map(|(_, v)| v)).cloned()
197    }
198}
199
200/// Query provider for `trait_impls_of`.
201pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> TraitImpls {
202    let mut impls = TraitImpls::default();
203
204    // Traits defined in the current crate can't have impls in upstream
205    // crates, so we don't bother querying the cstore.
206    if !trait_id.is_local() {
207        for &cnum in tcx.crates(()).iter() {
208            for &(impl_def_id, simplified_self_ty) in
209                tcx.implementations_of_trait((cnum, trait_id)).iter()
210            {
211                if let Some(simplified_self_ty) = simplified_self_ty {
212                    impls
213                        .non_blanket_impls
214                        .entry(simplified_self_ty)
215                        .or_default()
216                        .push(impl_def_id);
217                } else {
218                    impls.blanket_impls.push(impl_def_id);
219                }
220            }
221        }
222    }
223
224    for &impl_def_id in tcx.local_trait_impls(trait_id) {
225        let impl_def_id = impl_def_id.to_def_id();
226
227        let impl_self_ty = tcx.type_of(impl_def_id).instantiate_identity();
228
229        if let Some(simplified_self_ty) =
230            fast_reject::simplify_type(tcx, impl_self_ty, TreatParams::InstantiateWithInfer)
231        {
232            impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id);
233        } else {
234            impls.blanket_impls.push(impl_def_id);
235        }
236    }
237
238    impls
239}
240
241/// Query provider for `incoherent_impls`.
242pub(super) fn incoherent_impls_provider(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] {
243    if let Some(def_id) = simp.def()
244        && !{
    {
            'done:
                {
                for i in tcx.get_all_attrs(def_id) {
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AttributeKind::RustcHasIncoherentInherentImpls)
                            => {
                            break 'done Some(());
                        }
                        _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcHasIncoherentInherentImpls)
245    {
246        return &[];
247    }
248
249    let mut impls = Vec::new();
250    for cnum in iter::once(LOCAL_CRATE).chain(tcx.crates(()).iter().copied()) {
251        for &impl_def_id in tcx.crate_incoherent_impls((cnum, simp)) {
252            impls.push(impl_def_id)
253        }
254    }
255    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/trait_def.rs:255",
                        "rustc_middle::ty::trait_def", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/trait_def.rs"),
                        ::tracing_core::__macro_support::Option::Some(255u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::trait_def"),
                        ::tracing_core::field::FieldSet::new(&["impls"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&impls) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?impls);
256
257    tcx.arena.alloc_slice(&impls)
258}
259
260pub(super) fn traits_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
261    let mut traits = Vec::new();
262    for id in tcx.hir_free_items() {
263        if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(id.owner_id) {
    DefKind::Trait | DefKind::TraitAlias => true,
    _ => false,
}matches!(tcx.def_kind(id.owner_id), DefKind::Trait | DefKind::TraitAlias) {
264            traits.push(id.owner_id.to_def_id())
265        }
266    }
267
268    tcx.arena.alloc_slice(&traits)
269}
270
271pub(super) fn trait_impls_in_crate_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
272    let mut trait_impls = Vec::new();
273    for id in tcx.hir_free_items() {
274        if tcx.def_kind(id.owner_id) == (DefKind::Impl { of_trait: true }) {
275            trait_impls.push(id.owner_id.to_def_id())
276        }
277    }
278
279    tcx.arena.alloc_slice(&trait_impls)
280}