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 tracing::debug;
10
11use crate::query::LocalCrate;
12use crate::traits::specialization_graph;
13use crate::ty::fast_reject::{self, SimplifiedType, TreatParams};
14use crate::ty::{Ident, Ty, TyCtxt};
15
16/// A trait's definition with type information.
17#[derive(HashStable, Encodable, Decodable)]
18pub struct TraitDef {
19    pub def_id: DefId,
20
21    pub safety: hir::Safety,
22
23    /// Whether this trait has been annotated with `#[const_trait]`.
24    pub constness: hir::Constness,
25
26    /// If `true`, then this trait had the `#[rustc_paren_sugar]`
27    /// attribute, indicating that it should be used with `Foo()`
28    /// sugar. This is a temporary thing -- eventually any trait will
29    /// be usable with the sugar (or without it).
30    pub paren_sugar: bool,
31
32    pub has_auto_impl: bool,
33
34    /// If `true`, then this trait has the `#[marker]` attribute, indicating
35    /// that all its associated items have defaults that cannot be overridden,
36    /// and thus `impl`s of it are allowed to overlap.
37    pub is_marker: bool,
38
39    /// If `true`, then this trait has the `#[rustc_coinductive]` attribute or
40    /// is an auto trait. This indicates that trait solver cycles involving an
41    /// `X: ThisTrait` goal are accepted.
42    ///
43    /// In the future all traits should be coinductive, but we need a better
44    /// formal understanding of what exactly that means and should probably
45    /// also have already switched to the new trait solver.
46    pub is_coinductive: bool,
47
48    /// If `true`, then this trait has the `#[fundamental]` attribute. This
49    /// affects how conherence computes whether a trait may have trait implementations
50    /// added in the future.
51    pub is_fundamental: bool,
52
53    /// If `true`, then this trait has the `#[rustc_skip_during_method_dispatch(array)]`
54    /// attribute, indicating that editions before 2021 should not consider this trait
55    /// during method dispatch if the receiver is an array.
56    pub skip_array_during_method_dispatch: bool,
57
58    /// If `true`, then this trait has the `#[rustc_skip_during_method_dispatch(boxed_slice)]`
59    /// attribute, indicating that editions before 2024 should not consider this trait
60    /// during method dispatch if the receiver is a boxed slice.
61    pub skip_boxed_slice_during_method_dispatch: bool,
62
63    /// Used to determine whether the standard library is allowed to specialize
64    /// on this trait.
65    pub specialization_kind: TraitSpecializationKind,
66
67    /// List of functions from `#[rustc_must_implement_one_of]` attribute one of which
68    /// must be implemented.
69    pub must_implement_one_of: Option<Box<[Ident]>>,
70
71    /// Whether to add a builtin `dyn Trait: Trait` implementation.
72    /// This is enabled for all traits except ones marked with
73    /// `#[rustc_do_not_implement_via_object]`.
74    pub implement_via_object: bool,
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(HashStable, PartialEq, Clone, Copy, Encodable, 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(Default, Debug, 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    let mut impls = Vec::new();
243    for cnum in iter::once(LOCAL_CRATE).chain(tcx.crates(()).iter().copied()) {
244        for &impl_def_id in tcx.crate_incoherent_impls((cnum, simp)) {
245            impls.push(impl_def_id)
246        }
247    }
248    debug!(?impls);
249
250    tcx.arena.alloc_slice(&impls)
251}
252
253pub(super) fn traits_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
254    let mut traits = Vec::new();
255    for id in tcx.hir_free_items() {
256        if matches!(tcx.def_kind(id.owner_id), DefKind::Trait | DefKind::TraitAlias) {
257            traits.push(id.owner_id.to_def_id())
258        }
259    }
260
261    tcx.arena.alloc_slice(&traits)
262}
263
264pub(super) fn trait_impls_in_crate_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
265    let mut trait_impls = Vec::new();
266    for id in tcx.hir_free_items() {
267        if matches!(tcx.def_kind(id.owner_id), DefKind::Impl { .. })
268            && tcx.impl_trait_ref(id.owner_id).is_some()
269        {
270            trait_impls.push(id.owner_id.to_def_id())
271        }
272    }
273
274    tcx.arena.alloc_slice(&trait_impls)
275}
OSZAR »