Skip to main content

rustc_middle/ty/
trait_def.rs

1use std::iter;
2
3use rustc_attr_ir::find_attr;
4use rustc_data_structures::fx::FxIndexMap;
5use rustc_errors::ErrorGuaranteed;
6use rustc_hir as hir;
7use rustc_hir::def::DefKind;
8use rustc_hir::def_id::{DefId, LOCAL_CRATE};
9use rustc_macros::{Decodable, Encodable, StableHash};
10use rustc_span::{Span, bug};
11use tracing::debug;
12
13use crate::query::LocalCrate;
14use crate::traits::specialization_graph;
15use crate::ty::fast_reject::{self, SimplifiedType, TreatParams};
16use crate::ty::{self, Ident, Interner, RestrictionKind, Ty, TyCtxt, VisitorResult, try_visit};
17
18/// A trait's definition with type information.
19#[derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for TraitDef {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    TraitDef {
                        def_id: ref __binding_0,
                        impl_restriction: ref __binding_1,
                        safety: ref __binding_2,
                        constness: ref __binding_3,
                        paren_sugar: ref __binding_4,
                        has_auto_impl: ref __binding_5,
                        is_marker: ref __binding_6,
                        is_coinductive: ref __binding_7,
                        is_fundamental: ref __binding_8,
                        skip_array_during_method_dispatch: ref __binding_9,
                        skip_boxed_slice_during_method_dispatch: ref __binding_10,
                        specialization_kind: ref __binding_11,
                        must_implement_one_of: ref __binding_12,
                        force_dyn_incompatible: ref __binding_13,
                        deny_explicit_impl: ref __binding_14 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                        { __binding_4.stable_hash(__hcx, __hasher); }
                        { __binding_5.stable_hash(__hcx, __hasher); }
                        { __binding_6.stable_hash(__hcx, __hasher); }
                        { __binding_7.stable_hash(__hcx, __hasher); }
                        { __binding_8.stable_hash(__hcx, __hasher); }
                        { __binding_9.stable_hash(__hcx, __hasher); }
                        { __binding_10.stable_hash(__hcx, __hasher); }
                        { __binding_11.stable_hash(__hcx, __hasher); }
                        { __binding_12.stable_hash(__hcx, __hasher); }
                        { __binding_13.stable_hash(__hcx, __hasher); }
                        { __binding_14.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for TraitDef {
            fn encode(&self, __encoder: &mut __E) {
                let TraitDef {
                        def_id: ref __binding_0,
                        impl_restriction: ref __binding_1,
                        safety: ref __binding_2,
                        constness: ref __binding_3,
                        paren_sugar: ref __binding_4,
                        has_auto_impl: ref __binding_5,
                        is_marker: ref __binding_6,
                        is_coinductive: ref __binding_7,
                        is_fundamental: ref __binding_8,
                        skip_array_during_method_dispatch: ref __binding_9,
                        skip_boxed_slice_during_method_dispatch: ref __binding_10,
                        specialization_kind: ref __binding_11,
                        must_implement_one_of: ref __binding_12,
                        force_dyn_incompatible: ref __binding_13,
                        deny_explicit_impl: ref __binding_14 } = *self;
                ::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);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_14,
                    __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),
                    impl_restriction: ::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    /// Restrictions on trait implementations.
24    pub impl_restriction: RestrictionKind,
25
26    pub safety: hir::Safety,
27
28    /// Whether this trait is `const`.
29    pub constness: hir::Constness,
30
31    /// If `true`, then this trait had the `#[rustc_paren_sugar]`
32    /// attribute, indicating that it should be used with `Foo()`
33    /// sugar. This is a temporary thing -- eventually any trait will
34    /// be usable with the sugar (or without it).
35    pub paren_sugar: bool,
36
37    pub has_auto_impl: bool,
38
39    /// If `true`, then this trait has the `#[marker]` attribute, indicating
40    /// that all its associated items have defaults that cannot be overridden,
41    /// and thus `impl`s of it are allowed to overlap.
42    pub is_marker: bool,
43
44    /// If `true`, then this trait has the `#[rustc_coinductive]` attribute or
45    /// is an auto trait. This indicates that trait solver cycles involving an
46    /// `X: ThisTrait` goal are accepted.
47    ///
48    /// In the future all traits should be coinductive, but we need a better
49    /// formal understanding of what exactly that means and should probably
50    /// also have already switched to the new trait solver.
51    pub is_coinductive: bool,
52
53    /// If `true`, then this trait has the `#[fundamental]` attribute. This
54    /// affects how conherence computes whether a trait may have trait implementations
55    /// added in the future.
56    pub is_fundamental: bool,
57
58    /// If `true`, then this trait has the `#[rustc_skip_during_method_dispatch(array)]`
59    /// attribute, indicating that editions before 2021 should not consider this trait
60    /// during method dispatch if the receiver is an array.
61    pub skip_array_during_method_dispatch: bool,
62
63    /// If `true`, then this trait has the `#[rustc_skip_during_method_dispatch(boxed_slice)]`
64    /// attribute, indicating that editions before 2024 should not consider this trait
65    /// during method dispatch if the receiver is a boxed slice.
66    pub skip_boxed_slice_during_method_dispatch: bool,
67
68    /// Used to determine whether the standard library is allowed to specialize
69    /// on this trait.
70    pub specialization_kind: TraitSpecializationKind,
71
72    /// List of functions from `#[rustc_must_implement_one_of]` attribute one of which
73    /// must be implemented.
74    pub must_implement_one_of: Option<Box<[Ident]>>,
75
76    /// Whether the trait should be considered dyn-incompatible, even if it otherwise
77    /// satisfies the requirements to be dyn-compatible.
78    pub force_dyn_incompatible: Option<Span>,
79
80    /// Whether a trait is fully built-in, and any implementation is disallowed.
81    /// This only applies to built-in traits, and is marked via
82    /// `#[rustc_deny_explicit_impl]`.
83    pub deny_explicit_impl: bool,
84}
85
86/// Whether this trait is treated specially by the standard library
87/// specialization lint.
88#[derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            TraitSpecializationKind {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    TraitSpecializationKind::None => {}
                    TraitSpecializationKind::Marker => {}
                    TraitSpecializationKind::AlwaysApplicable => {}
                }
            }
        }
    };StableHash, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for TraitSpecializationKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for TraitSpecializationKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TraitSpecializationKind { }
#[automatically_derived]
impl ::core::clone::Clone for TraitSpecializationKind {
    #[inline]
    fn clone(&self) -> Self { *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);
            }
        }
    };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)]
89pub enum TraitSpecializationKind {
90    /// The default. Specializing on this trait is not allowed.
91    None,
92    /// Specializing on this trait is allowed because it doesn't have any
93    /// methods. For example `Sized` or `FusedIterator`.
94    /// Applies to traits with the `rustc_allow_lifetime_dependent_specialization`
95    /// attribute.
96    Marker,
97    /// Specializing on this trait is allowed because all of the impls of this
98    /// trait are "always applicable". Always applicable means that if
99    /// `X<'x>: T<'y>` for any lifetimes, then `for<'a, 'b> X<'a>: T<'b>`.
100    /// Applies to traits with the `rustc_specialization_trait` attribute.
101    AlwaysApplicable,
102}
103
104#[derive(#[automatically_derived]
impl ::core::default::Default for TraitImpls {
    #[inline]
    fn default() -> Self {
        Self {
            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 ::rustc_data_structures::stable_hash::StableHash for TraitImpls {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    TraitImpls {
                        blanket_impls: ref __binding_0,
                        non_blanket_impls: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
105pub struct TraitImpls {
106    blanket_impls: Vec<DefId>,
107    /// Impls indexed by their simplified self type, for fast lookup.
108    non_blanket_impls: FxIndexMap<SimplifiedType, Vec<DefId>>,
109}
110
111impl TraitImpls {
112    pub fn is_empty(&self) -> bool {
113        self.blanket_impls.is_empty() && self.non_blanket_impls.is_empty()
114    }
115
116    pub fn blanket_impls(&self) -> &[DefId] {
117        self.blanket_impls.as_slice()
118    }
119
120    pub fn non_blanket_impls(&self) -> &FxIndexMap<SimplifiedType, Vec<DefId>> {
121        &self.non_blanket_impls
122    }
123}
124
125impl<'tcx> TraitDef {
126    pub fn ancestors(
127        &self,
128        tcx: TyCtxt<'tcx>,
129        of_impl: DefId,
130    ) -> Result<specialization_graph::Ancestors<'tcx>, ErrorGuaranteed> {
131        specialization_graph::ancestors(tcx, self.def_id, of_impl)
132    }
133}
134
135impl<'tcx> TyCtxt<'tcx> {
136    /// Iterate over every impl that could possibly match the self type `self_ty`.
137    ///
138    /// `trait_def_id` MUST BE the `DefId` of a trait.
139    pub fn for_each_relevant_impl<R: VisitorResult>(
140        self,
141        trait_def_id: DefId,
142        self_ty: Ty<'tcx>,
143        mut f: impl FnMut(DefId) -> R,
144    ) -> R {
145        let tcx = self;
146        let trait_impls = tcx.trait_impls_of(trait_def_id);
147        let mut consider_impls_for_simplified_type = |simp| {
148            if let Some(impls_for_type) = trait_impls.non_blanket_impls().get(&simp) {
149                for &impl_def_id in impls_for_type {
150                    match ::rustc_ast_ir::visit::VisitorResult::branch(f(impl_def_id)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
}try_visit!(f(impl_def_id))
151                }
152            }
153
154            R::output()
155        };
156
157        match self_ty.kind() {
158            ty::Bool
159            | ty::Char
160            | ty::Int(_)
161            | ty::Uint(_)
162            | ty::Float(_)
163            | ty::Adt(_, _)
164            | ty::Foreign(_)
165            | ty::Str
166            | ty::Array(_, _)
167            | ty::Slice(_)
168            | ty::RawPtr(_, _)
169            | ty::Ref(_, _, _)
170            | ty::FnDef(_, _)
171            | ty::FnPtr(..)
172            | ty::Dynamic(_, _)
173            | ty::Closure(..)
174            | ty::CoroutineClosure(..)
175            | ty::Coroutine(_, _)
176            | ty::Never
177            | ty::Tuple(_)
178            | ty::UnsafeBinder(_) => {
179                let simp = ty::fast_reject::simplify_type(
180                    tcx,
181                    self_ty,
182                    ty::fast_reject::TreatParams::AsRigid,
183                )
184                .unwrap();
185                match ::rustc_ast_ir::visit::VisitorResult::branch(consider_impls_for_simplified_type(simp))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(consider_impls_for_simplified_type(simp));
186            }
187
188            // HACK: For integer and float variables we have to manually look at all impls
189            // which have some integer or float as a self type.
190            ty::Infer(ty::IntVar(_)) => {
191                use ty::IntTy::*;
192                use ty::UintTy::*;
193                // This causes a compiler error if any new integer kinds are added.
194                let (I8 | I16 | I32 | I64 | I128 | Isize): ty::IntTy;
195                let (U8 | U16 | U32 | U64 | U128 | Usize): ty::UintTy;
196                let possible_integers = [
197                    // signed integers
198                    ty::SimplifiedType::Int(I8),
199                    ty::SimplifiedType::Int(I16),
200                    ty::SimplifiedType::Int(I32),
201                    ty::SimplifiedType::Int(I64),
202                    ty::SimplifiedType::Int(I128),
203                    ty::SimplifiedType::Int(Isize),
204                    // unsigned integers
205                    ty::SimplifiedType::Uint(U8),
206                    ty::SimplifiedType::Uint(U16),
207                    ty::SimplifiedType::Uint(U32),
208                    ty::SimplifiedType::Uint(U64),
209                    ty::SimplifiedType::Uint(U128),
210                    ty::SimplifiedType::Uint(Usize),
211                ];
212                for simp in possible_integers {
213                    match ::rustc_ast_ir::visit::VisitorResult::branch(consider_impls_for_simplified_type(simp))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(consider_impls_for_simplified_type(simp));
214                }
215            }
216
217            ty::Infer(ty::FloatVar(_)) => {
218                // This causes a compiler error if any new float kinds are added.
219                let (ty::FloatTy::F16 | ty::FloatTy::F32 | ty::FloatTy::F64 | ty::FloatTy::F128);
220                let possible_floats = [
221                    ty::SimplifiedType::Float(ty::FloatTy::F16),
222                    ty::SimplifiedType::Float(ty::FloatTy::F32),
223                    ty::SimplifiedType::Float(ty::FloatTy::F64),
224                    ty::SimplifiedType::Float(ty::FloatTy::F128),
225                ];
226
227                for simp in possible_floats {
228                    match ::rustc_ast_ir::visit::VisitorResult::branch(consider_impls_for_simplified_type(simp))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(consider_impls_for_simplified_type(simp));
229                }
230            }
231
232            // Pattern type might not have a simplified type.
233            ty::Pat(_, _) => {
234                if let Some(simp) = ty::fast_reject::simplify_type(
235                    tcx,
236                    self_ty,
237                    ty::fast_reject::TreatParams::AsRigid,
238                ) {
239                    match ::rustc_ast_ir::visit::VisitorResult::branch(consider_impls_for_simplified_type(simp))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(consider_impls_for_simplified_type(simp));
240                }
241            }
242
243            // This is only for diagnostics and normally ty vars should be handled by the callers.
244            ty::Infer(ty::TyVar(_)) => {
245                for &impl_def_id in trait_impls.non_blanket_impls().values().flatten() {
246                    match ::rustc_ast_ir::visit::VisitorResult::branch(f(impl_def_id)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(f(impl_def_id));
247                }
248            }
249
250            // The only traits applying to aliases and placeholders are blanket impls.
251            //
252            // Impls which apply to an alias after normalization are handled by
253            // `assemble_candidates_after_normalizing_self_ty`.
254            ty::Alias(ty::IsRigid::Yes, _) | ty::Placeholder(..) | ty::Error(_) => (),
255            // FIXME(-Znext-solver=no): Need to support aliases not marked as
256            // rigid for the old solver.
257            ty::Alias(ty::IsRigid::No, _) => (),
258
259            // FIXME: These should ideally not exist as a self type. It would be nice for
260            // the builtin auto trait impls of coroutines to instead directly recurse
261            // into the witness.
262            ty::CoroutineWitness(..) => (),
263
264            // These are used in diagnostics or in the old solver.
265            ty::Param(_) | ty::Bound(_, _) => (),
266
267            // These variants should not exist as a self type.
268            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
269                ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected self type: {0:?}", self_ty), Location::caller());bug!("unexpected self type: {self_ty:?}");
270            }
271        }
272
273        #[allow(rustc::usage_of_type_ir_traits)]
274        self.for_each_blanket_impl(trait_def_id, f)
275    }
276
277    /// `trait_def_id` MUST BE the `DefId` of a trait.
278    pub fn non_blanket_impls_for_ty(
279        self,
280        trait_def_id: DefId,
281        self_ty: Ty<'tcx>,
282    ) -> impl Iterator<Item = DefId> {
283        let impls = self.trait_impls_of(trait_def_id);
284        if let Some(simp) =
285            fast_reject::simplify_type(self, self_ty, TreatParams::InstantiateWithInfer)
286        {
287            if let Some(impls) = impls.non_blanket_impls.get(&simp) {
288                return impls.iter().copied();
289            }
290        }
291
292        [].iter().copied()
293    }
294
295    /// Returns an iterator containing all impls for `trait_def_id`.
296    ///
297    /// `trait_def_id` MUST BE the `DefId` of a trait.
298    pub fn all_impls(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> {
299        let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(trait_def_id);
300
301        blanket_impls.iter().chain(non_blanket_impls.iter().flat_map(|(_, v)| v)).cloned()
302    }
303}
304
305/// Query provider for `trait_impls_of`.
306pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> TraitImpls {
307    let mut impls = TraitImpls::default();
308
309    // Traits defined in the current crate can't have impls in upstream
310    // crates, so we don't bother querying the cstore.
311    if !trait_id.is_local() {
312        for &cnum in tcx.crates(()).iter() {
313            for &(impl_def_id, simplified_self_ty) in
314                tcx.implementations_of_trait((cnum, trait_id)).iter()
315            {
316                if let Some(simplified_self_ty) = simplified_self_ty {
317                    impls
318                        .non_blanket_impls
319                        .entry(simplified_self_ty)
320                        .or_default()
321                        .push(impl_def_id);
322                } else {
323                    impls.blanket_impls.push(impl_def_id);
324                }
325            }
326        }
327    }
328
329    for &impl_def_id in tcx.local_trait_impls(trait_id) {
330        let impl_def_id = impl_def_id.to_def_id();
331
332        let impl_self_ty = tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip();
333
334        if let Some(simplified_self_ty) =
335            fast_reject::simplify_type(tcx, impl_self_ty, TreatParams::InstantiateWithInfer)
336        {
337            impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id);
338        } else {
339            impls.blanket_impls.push(impl_def_id);
340        }
341    }
342
343    impls
344}
345
346/// Query provider for `incoherent_impls`.
347pub(super) fn incoherent_impls_provider(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] {
348    if let Some(def_id) = simp.def()
349        && !{
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcHasIncoherentInherentImpls)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcHasIncoherentInherentImpls)
350    {
351        return &[];
352    }
353
354    let mut impls = Vec::new();
355    for cnum in iter::once(LOCAL_CRATE).chain(tcx.crates(()).iter().copied()) {
356        for &impl_def_id in tcx.crate_incoherent_impls((cnum, simp)) {
357            impls.push(impl_def_id)
358        }
359    }
360    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/e3feeb59cd1bdd011a2bfcc0747b55125d9b8527/compiler/rustc_middle/src/ty/trait_def.rs:360",
                        "rustc_middle::ty::trait_def", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/e3feeb59cd1bdd011a2bfcc0747b55125d9b8527/compiler/rustc_middle/src/ty/trait_def.rs"),
                        ::tracing_core::__macro_support::Option::Some(360u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::trait_def"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("impls")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("impls");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impls)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?impls);
361
362    tcx.arena.alloc_slice(&impls)
363}
364
365pub(super) fn traits_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
366    let mut traits = Vec::new();
367    for id in tcx.hir_free_items() {
368        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) {
369            traits.push(id.owner_id.to_def_id())
370        }
371    }
372
373    tcx.arena.alloc_slice(&traits)
374}
375
376pub(super) fn trait_impls_in_crate_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
377    let mut trait_impls = Vec::new();
378    for id in tcx.hir_free_items() {
379        if tcx.def_kind(id.owner_id) == (DefKind::Impl { of_trait: true }) {
380            trait_impls.push(id.owner_id.to_def_id())
381        }
382    }
383
384    tcx.arena.alloc_slice(&trait_impls)
385}