rustc_middle/ty/
trait_def.rs

1use std::iter;
2
3use rustc_data_structures::fx::FxIndexMap;
4use rustc_errors::ErrorGuaranteed;
5use rustc_hir as hir;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE};
8use rustc_macros::{Decodable, Encodable, HashStable};
9use rustc_span::symbol::sym;
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(HashStable, Encodable, 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 to add a builtin `dyn Trait: Trait` implementation.
73    /// This is enabled for all traits except ones marked with
74    /// `#[rustc_do_not_implement_via_object]`.
75    pub implement_via_object: bool,
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(HashStable, PartialEq, Clone, Copy, Encodable, 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(Default, Debug, 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        && !tcx.has_attr(def_id, sym::rustc_has_incoherent_inherent_impls)
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    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 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 matches!(tcx.def_kind(id.owner_id), DefKind::Impl { .. })
275            && tcx.impl_trait_ref(id.owner_id).is_some()
276        {
277            trait_impls.push(id.owner_id.to_def_id())
278        }
279    }
280
281    tcx.arena.alloc_slice(&trait_impls)
282}