]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/trait_def.rs
Rollup merge of #94045 - ehuss:update-books, r=ehuss
[rust.git] / compiler / rustc_middle / src / ty / trait_def.rs
1 use crate::traits::specialization_graph;
2 use crate::ty::fast_reject::{self, SimplifiedType, SimplifyParams};
3 use crate::ty::fold::TypeFoldable;
4 use crate::ty::{Ident, Ty, TyCtxt};
5 use rustc_hir as hir;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::definitions::DefPathHash;
8
9 use rustc_data_structures::fx::FxIndexMap;
10 use rustc_errors::ErrorReported;
11 use rustc_macros::HashStable;
12
13 /// A trait's definition with type information.
14 #[derive(HashStable)]
15 pub struct TraitDef {
16     // We already have the def_path_hash below, no need to hash it twice
17     #[stable_hasher(ignore)]
18     pub def_id: DefId,
19
20     pub unsafety: hir::Unsafety,
21
22     /// If `true`, then this trait had the `#[rustc_paren_sugar]`
23     /// attribute, indicating that it should be used with `Foo()`
24     /// sugar. This is a temporary thing -- eventually any trait will
25     /// be usable with the sugar (or without it).
26     pub paren_sugar: bool,
27
28     pub has_auto_impl: bool,
29
30     /// If `true`, then this trait has the `#[marker]` attribute, indicating
31     /// that all its associated items have defaults that cannot be overridden,
32     /// and thus `impl`s of it are allowed to overlap.
33     pub is_marker: bool,
34
35     /// If `true`, then this trait has the `#[rustc_skip_array_during_method_dispatch]`
36     /// attribute, indicating that editions before 2021 should not consider this trait
37     /// during method dispatch if the receiver is an array.
38     pub skip_array_during_method_dispatch: bool,
39
40     /// Used to determine whether the standard library is allowed to specialize
41     /// on this trait.
42     pub specialization_kind: TraitSpecializationKind,
43
44     /// The ICH of this trait's DefPath, cached here so it doesn't have to be
45     /// recomputed all the time.
46     pub def_path_hash: DefPathHash,
47
48     /// List of functions from `#[rustc_must_implement_one_of]` attribute one of which
49     /// must be implemented.
50     pub must_implement_one_of: Option<Box<[Ident]>>,
51 }
52
53 /// Whether this trait is treated specially by the standard library
54 /// specialization lint.
55 #[derive(HashStable, PartialEq, Clone, Copy, TyEncodable, TyDecodable)]
56 pub enum TraitSpecializationKind {
57     /// The default. Specializing on this trait is not allowed.
58     None,
59     /// Specializing on this trait is allowed because it doesn't have any
60     /// methods. For example `Sized` or `FusedIterator`.
61     /// Applies to traits with the `rustc_unsafe_specialization_marker`
62     /// attribute.
63     Marker,
64     /// Specializing on this trait is allowed because all of the impls of this
65     /// trait are "always applicable". Always applicable means that if
66     /// `X<'x>: T<'y>` for any lifetimes, then `for<'a, 'b> X<'a>: T<'b>`.
67     /// Applies to traits with the `rustc_specialization_trait` attribute.
68     AlwaysApplicable,
69 }
70
71 #[derive(Default, Debug, HashStable)]
72 pub struct TraitImpls {
73     blanket_impls: Vec<DefId>,
74     /// Impls indexed by their simplified self type, for fast lookup.
75     non_blanket_impls: FxIndexMap<SimplifiedType, Vec<DefId>>,
76 }
77
78 impl TraitImpls {
79     pub fn blanket_impls(&self) -> &[DefId] {
80         self.blanket_impls.as_slice()
81     }
82 }
83
84 impl<'tcx> TraitDef {
85     pub fn new(
86         def_id: DefId,
87         unsafety: hir::Unsafety,
88         paren_sugar: bool,
89         has_auto_impl: bool,
90         is_marker: bool,
91         skip_array_during_method_dispatch: bool,
92         specialization_kind: TraitSpecializationKind,
93         def_path_hash: DefPathHash,
94         must_implement_one_of: Option<Box<[Ident]>>,
95     ) -> TraitDef {
96         TraitDef {
97             def_id,
98             unsafety,
99             paren_sugar,
100             has_auto_impl,
101             is_marker,
102             skip_array_during_method_dispatch,
103             specialization_kind,
104             def_path_hash,
105             must_implement_one_of,
106         }
107     }
108
109     pub fn ancestors(
110         &self,
111         tcx: TyCtxt<'tcx>,
112         of_impl: DefId,
113     ) -> Result<specialization_graph::Ancestors<'tcx>, ErrorReported> {
114         specialization_graph::ancestors(tcx, self.def_id, of_impl)
115     }
116 }
117
118 impl<'tcx> TyCtxt<'tcx> {
119     pub fn for_each_impl<F: FnMut(DefId)>(self, def_id: DefId, mut f: F) {
120         let impls = self.trait_impls_of(def_id);
121
122         for &impl_def_id in impls.blanket_impls.iter() {
123             f(impl_def_id);
124         }
125
126         for v in impls.non_blanket_impls.values() {
127             for &impl_def_id in v {
128                 f(impl_def_id);
129             }
130         }
131     }
132
133     /// Iterate over every impl that could possibly match the
134     /// self type `self_ty`.
135     pub fn for_each_relevant_impl<F: FnMut(DefId)>(
136         self,
137         def_id: DefId,
138         self_ty: Ty<'tcx>,
139         mut f: F,
140     ) {
141         let _: Option<()> = self.find_map_relevant_impl(def_id, self_ty, |did| {
142             f(did);
143             None
144         });
145     }
146
147     pub fn non_blanket_impls_for_ty(
148         self,
149         def_id: DefId,
150         self_ty: Ty<'tcx>,
151     ) -> impl Iterator<Item = DefId> + 'tcx {
152         let impls = self.trait_impls_of(def_id);
153         if let Some(simp) = fast_reject::simplify_type(self, self_ty, SimplifyParams::No) {
154             if let Some(impls) = impls.non_blanket_impls.get(&simp) {
155                 return impls.iter().copied();
156             }
157         }
158
159         [].iter().copied()
160     }
161
162     /// Applies function to every impl that could possibly match the self type `self_ty` and returns
163     /// the first non-none value.
164     pub fn find_map_relevant_impl<T, F: FnMut(DefId) -> Option<T>>(
165         self,
166         def_id: DefId,
167         self_ty: Ty<'tcx>,
168         mut f: F,
169     ) -> Option<T> {
170         // FIXME: This depends on the set of all impls for the trait. That is
171         // unfortunate wrt. incremental compilation.
172         //
173         // If we want to be faster, we could have separate queries for
174         // blanket and non-blanket impls, and compare them separately.
175         let impls = self.trait_impls_of(def_id);
176
177         for &impl_def_id in impls.blanket_impls.iter() {
178             if let result @ Some(_) = f(impl_def_id) {
179                 return result;
180             }
181         }
182
183         // Note that we're using `SimplifyParams::Yes` to query `non_blanket_impls` while using
184         // `SimplifyParams::No` while actually adding them.
185         //
186         // This way, when searching for some impl for `T: Trait`, we do not look at any impls
187         // whose outer level is not a parameter or projection. Especially for things like
188         // `T: Clone` this is incredibly useful as we would otherwise look at all the impls
189         // of `Clone` for `Option<T>`, `Vec<T>`, `ConcreteType` and so on.
190         if let Some(simp) = fast_reject::simplify_type(self, self_ty, SimplifyParams::Yes) {
191             if let Some(impls) = impls.non_blanket_impls.get(&simp) {
192                 for &impl_def_id in impls {
193                     if let result @ Some(_) = f(impl_def_id) {
194                         return result;
195                     }
196                 }
197             }
198         } else {
199             for &impl_def_id in impls.non_blanket_impls.values().flatten() {
200                 if let result @ Some(_) = f(impl_def_id) {
201                     return result;
202                 }
203             }
204         }
205
206         None
207     }
208
209     /// Returns an iterator containing all impls
210     pub fn all_impls(self, def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
211         let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(def_id);
212
213         blanket_impls.iter().chain(non_blanket_impls.iter().map(|(_, v)| v).flatten()).cloned()
214     }
215 }
216
217 // Query provider for `trait_impls_of`.
218 pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> TraitImpls {
219     let mut impls = TraitImpls::default();
220
221     // Traits defined in the current crate can't have impls in upstream
222     // crates, so we don't bother querying the cstore.
223     if !trait_id.is_local() {
224         for &cnum in tcx.crates(()).iter() {
225             for &(impl_def_id, simplified_self_ty) in
226                 tcx.implementations_of_trait((cnum, trait_id)).iter()
227             {
228                 if let Some(simplified_self_ty) = simplified_self_ty {
229                     impls
230                         .non_blanket_impls
231                         .entry(simplified_self_ty)
232                         .or_default()
233                         .push(impl_def_id);
234                 } else {
235                     impls.blanket_impls.push(impl_def_id);
236                 }
237             }
238         }
239     }
240
241     for &impl_def_id in tcx.hir().trait_impls(trait_id) {
242         let impl_def_id = impl_def_id.to_def_id();
243
244         let impl_self_ty = tcx.type_of(impl_def_id);
245         if impl_self_ty.references_error() {
246             continue;
247         }
248
249         if let Some(simplified_self_ty) =
250             fast_reject::simplify_type(tcx, impl_self_ty, SimplifyParams::No)
251         {
252             impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id);
253         } else {
254             impls.blanket_impls.push(impl_def_id);
255         }
256     }
257
258     impls
259 }