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::def::DefKind;
6use rustc_hir::def_id::{DefId, LOCAL_CRATE};
7use rustc_hir::{self as hir, find_attr};
8use rustc_macros::{Decodable, Encodable, HashStable};
9use rustc_span::Span;
10use tracing::debug;
11
12use crate::query::LocalCrate;
13use crate::traits::specialization_graph;
14use crate::ty::fast_reject::{self, SimplifiedType, TreatParams};
15use crate::ty::{Ident, Ty, TyCtxt};
16
17/// A trait's definition with type information.
18#[derive(const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for TraitDef {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::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)]
19pub struct TraitDef {
20    pub def_id: DefId,
21
22    pub safety: hir::Safety,
23
24    /// Whether this trait is `const`.
25    pub constness: hir::Constness,
26
27    /// If `true`, then this trait had the `#[rustc_paren_sugar]`
28    /// attribute, indicating that it should be used with `Foo()`
29    /// sugar. This is a temporary thing -- eventually any trait will
30    /// be usable with the sugar (or without it).
31    pub paren_sugar: bool,
32
33    pub has_auto_impl: bool,
34
35    /// If `true`, then this trait has the `#[marker]` attribute, indicating
36    /// that all its associated items have defaults that cannot be overridden,
37    /// and thus `impl`s of it are allowed to overlap.
38    pub is_marker: bool,
39
40    /// If `true`, then this trait has the `#[rustc_coinductive]` attribute or
41    /// is an auto trait. This indicates that trait solver cycles involving an
42    /// `X: ThisTrait` goal are accepted.
43    ///
44    /// In the future all traits should be coinductive, but we need a better
45    /// formal understanding of what exactly that means and should probably
46    /// also have already switched to the new trait solver.
47    pub is_coinductive: bool,
48
49    /// If `true`, then this trait has the `#[fundamental]` attribute. This
50    /// affects how conherence computes whether a trait may have trait implementations
51    /// added in the future.
52    pub is_fundamental: bool,
53
54    /// If `true`, then this trait has the `#[rustc_skip_during_method_dispatch(array)]`
55    /// attribute, indicating that editions before 2021 should not consider this trait
56    /// during method dispatch if the receiver is an array.
57    pub skip_array_during_method_dispatch: bool,
58
59    /// If `true`, then this trait has the `#[rustc_skip_during_method_dispatch(boxed_slice)]`
60    /// attribute, indicating that editions before 2024 should not consider this trait
61    /// during method dispatch if the receiver is a boxed slice.
62    pub skip_boxed_slice_during_method_dispatch: bool,
63
64    /// Used to determine whether the standard library is allowed to specialize
65    /// on this trait.
66    pub specialization_kind: TraitSpecializationKind,
67
68    /// List of functions from `#[rustc_must_implement_one_of]` attribute one of which
69    /// must be implemented.
70    pub must_implement_one_of: Option<Box<[Ident]>>,
71
72    /// Whether the trait should be considered dyn-incompatible, even if it otherwise
73    /// satisfies the requirements to be dyn-compatible.
74    pub force_dyn_incompatible: Option<Span>,
75
76    /// Whether a trait is fully built-in, and any implementation is disallowed.
77    /// This only applies to built-in traits, and is marked via
78    /// `#[rustc_deny_explicit_impl]`.
79    pub deny_explicit_impl: bool,
80}
81
82/// Whether this trait is treated specially by the standard library
83/// specialization lint.
84#[derive(const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for TraitSpecializationKind {
            #[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 {
                    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)]
85pub enum TraitSpecializationKind {
86    /// The default. Specializing on this trait is not allowed.
87    None,
88    /// Specializing on this trait is allowed because it doesn't have any
89    /// methods. For example `Sized` or `FusedIterator`.
90    /// Applies to traits with the `rustc_unsafe_specialization_marker`
91    /// attribute.
92    Marker,
93    /// Specializing on this trait is allowed because all of the impls of this
94    /// trait are "always applicable". Always applicable means that if
95    /// `X<'x>: T<'y>` for any lifetimes, then `for<'a, 'b> X<'a>: T<'b>`.
96    /// Applies to traits with the `rustc_specialization_trait` attribute.
97    AlwaysApplicable,
98}
99
100#[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_middle::ich::StableHashingContext<'__ctx>>
            for TraitImpls {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::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)]
101pub struct TraitImpls {
102    blanket_impls: Vec<DefId>,
103    /// Impls indexed by their simplified self type, for fast lookup.
104    non_blanket_impls: FxIndexMap<SimplifiedType, Vec<DefId>>,
105}
106
107impl TraitImpls {
108    pub fn is_empty(&self) -> bool {
109        self.blanket_impls.is_empty() && self.non_blanket_impls.is_empty()
110    }
111
112    pub fn blanket_impls(&self) -> &[DefId] {
113        self.blanket_impls.as_slice()
114    }
115
116    pub fn non_blanket_impls(&self) -> &FxIndexMap<SimplifiedType, Vec<DefId>> {
117        &self.non_blanket_impls
118    }
119}
120
121impl<'tcx> TraitDef {
122    pub fn ancestors(
123        &self,
124        tcx: TyCtxt<'tcx>,
125        of_impl: DefId,
126    ) -> Result<specialization_graph::Ancestors<'tcx>, ErrorGuaranteed> {
127        specialization_graph::ancestors(tcx, self.def_id, of_impl)
128    }
129}
130
131impl<'tcx> TyCtxt<'tcx> {
132    /// Iterate over every impl that could possibly match the self type `self_ty`.
133    ///
134    /// `trait_def_id` MUST BE the `DefId` of a trait.
135    pub fn for_each_relevant_impl(
136        self,
137        trait_def_id: DefId,
138        self_ty: Ty<'tcx>,
139        mut f: impl FnMut(DefId),
140    ) {
141        // FIXME: This depends on the set of all impls for the trait. That is
142        // unfortunate wrt. incremental compilation.
143        //
144        // If we want to be faster, we could have separate queries for
145        // blanket and non-blanket impls, and compare them separately.
146        let impls = self.trait_impls_of(trait_def_id);
147
148        for &impl_def_id in impls.blanket_impls.iter() {
149            f(impl_def_id);
150        }
151
152        // This way, when searching for some impl for `T: Trait`, we do not look at any impls
153        // whose outer level is not a parameter or projection. Especially for things like
154        // `T: Clone` this is incredibly useful as we would otherwise look at all the impls
155        // of `Clone` for `Option<T>`, `Vec<T>`, `ConcreteType` and so on.
156        // Note that we're using `TreatParams::AsRigid` to query `non_blanket_impls` while using
157        // `TreatParams::InstantiateWithInfer` while actually adding them.
158        if let Some(simp) = fast_reject::simplify_type(self, self_ty, TreatParams::AsRigid) {
159            if let Some(impls) = impls.non_blanket_impls.get(&simp) {
160                for &impl_def_id in impls {
161                    f(impl_def_id);
162                }
163            }
164        } else {
165            for &impl_def_id in impls.non_blanket_impls.values().flatten() {
166                f(impl_def_id);
167            }
168        }
169    }
170
171    /// `trait_def_id` MUST BE the `DefId` of a trait.
172    pub fn non_blanket_impls_for_ty(
173        self,
174        trait_def_id: DefId,
175        self_ty: Ty<'tcx>,
176    ) -> impl Iterator<Item = DefId> {
177        let impls = self.trait_impls_of(trait_def_id);
178        if let Some(simp) =
179            fast_reject::simplify_type(self, self_ty, TreatParams::InstantiateWithInfer)
180        {
181            if let Some(impls) = impls.non_blanket_impls.get(&simp) {
182                return impls.iter().copied();
183            }
184        }
185
186        [].iter().copied()
187    }
188
189    /// Returns an iterator containing all impls for `trait_def_id`.
190    ///
191    /// `trait_def_id` MUST BE the `DefId` of a trait.
192    pub fn all_impls(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> {
193        let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(trait_def_id);
194
195        blanket_impls.iter().chain(non_blanket_impls.iter().flat_map(|(_, v)| v)).cloned()
196    }
197}
198
199/// Query provider for `trait_impls_of`.
200pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> TraitImpls {
201    let mut impls = TraitImpls::default();
202
203    // Traits defined in the current crate can't have impls in upstream
204    // crates, so we don't bother querying the cstore.
205    if !trait_id.is_local() {
206        for &cnum in tcx.crates(()).iter() {
207            for &(impl_def_id, simplified_self_ty) in
208                tcx.implementations_of_trait((cnum, trait_id)).iter()
209            {
210                if let Some(simplified_self_ty) = simplified_self_ty {
211                    impls
212                        .non_blanket_impls
213                        .entry(simplified_self_ty)
214                        .or_default()
215                        .push(impl_def_id);
216                } else {
217                    impls.blanket_impls.push(impl_def_id);
218                }
219            }
220        }
221    }
222
223    for &impl_def_id in tcx.local_trait_impls(trait_id) {
224        let impl_def_id = impl_def_id.to_def_id();
225
226        let impl_self_ty = tcx.type_of(impl_def_id).instantiate_identity();
227
228        if let Some(simplified_self_ty) =
229            fast_reject::simplify_type(tcx, impl_self_ty, TreatParams::InstantiateWithInfer)
230        {
231            impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id);
232        } else {
233            impls.blanket_impls.push(impl_def_id);
234        }
235    }
236
237    impls
238}
239
240/// Query provider for `incoherent_impls`.
241pub(super) fn incoherent_impls_provider(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] {
242    if let Some(def_id) = simp.def()
243        && !{

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in tcx.get_all_attrs(def_id) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcHasIncoherentInherentImpls)
                                => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcHasIncoherentInherentImpls)
244    {
245        return &[];
246    }
247
248    let mut impls = Vec::new();
249    for cnum in iter::once(LOCAL_CRATE).chain(tcx.crates(()).iter().copied()) {
250        for &impl_def_id in tcx.crate_incoherent_impls((cnum, simp)) {
251            impls.push(impl_def_id)
252        }
253    }
254    {
    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:254",
                        "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(254u32),
                        ::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);
255
256    tcx.arena.alloc_slice(&impls)
257}
258
259pub(super) fn traits_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
260    let mut traits = Vec::new();
261    for id in tcx.hir_free_items() {
262        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) {
263            traits.push(id.owner_id.to_def_id())
264        }
265    }
266
267    tcx.arena.alloc_slice(&traits)
268}
269
270pub(super) fn trait_impls_in_crate_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
271    let mut trait_impls = Vec::new();
272    for id in tcx.hir_free_items() {
273        if tcx.def_kind(id.owner_id) == (DefKind::Impl { of_trait: true }) {
274            trait_impls.push(id.owner_id.to_def_id())
275        }
276    }
277
278    tcx.arena.alloc_slice(&trait_impls)
279}