]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/trait_def.rs
Auto merge of #59798 - rchaser53:issue-59488, r=estebank
[rust.git] / src / librustc / ty / trait_def.rs
1 use crate::hir;
2 use crate::hir::def_id::DefId;
3 use crate::hir::map::DefPathHash;
4 use crate::ich::{self, StableHashingContext};
5 use crate::traits::specialization_graph;
6 use crate::ty::fast_reject;
7 use crate::ty::fold::TypeFoldable;
8 use crate::ty::{Ty, TyCtxt};
9
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
12                                            StableHasherResult};
13 use rustc_data_structures::sync::Lrc;
14 use rustc_macros::HashStable;
15
16 /// A trait's definition with type information.
17 #[derive(HashStable)]
18 pub struct TraitDef {
19     // We already have the def_path_hash below, no need to hash it twice
20     #[stable_hasher(ignore)]
21     pub def_id: DefId,
22
23     pub unsafety: hir::Unsafety,
24
25     /// If `true`, then this trait had the `#[rustc_paren_sugar]`
26     /// attribute, indicating that it should be used with `Foo()`
27     /// sugar. This is a temporary thing -- eventually any trait will
28     /// be usable with the sugar (or without it).
29     pub paren_sugar: bool,
30
31     pub has_auto_impl: bool,
32
33     /// If `true`, then this trait has the `#[marker]` attribute, indicating
34     /// that all its associated items have defaults that cannot be overridden,
35     /// and thus `impl`s of it are allowed to overlap.
36     pub is_marker: bool,
37
38     /// The ICH of this trait's DefPath, cached here so it doesn't have to be
39     /// recomputed all the time.
40     pub def_path_hash: DefPathHash,
41 }
42
43 #[derive(Default)]
44 pub struct TraitImpls {
45     blanket_impls: Vec<DefId>,
46     /// Impls indexed by their simplified self type, for fast lookup.
47     non_blanket_impls: FxHashMap<fast_reject::SimplifiedType, Vec<DefId>>,
48 }
49
50 impl<'a, 'gcx, 'tcx> TraitDef {
51     pub fn new(def_id: DefId,
52                unsafety: hir::Unsafety,
53                paren_sugar: bool,
54                has_auto_impl: bool,
55                is_marker: bool,
56                def_path_hash: DefPathHash)
57                -> TraitDef {
58         TraitDef {
59             def_id,
60             unsafety,
61             paren_sugar,
62             has_auto_impl,
63             is_marker,
64             def_path_hash,
65         }
66     }
67
68     pub fn ancestors(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
69                      of_impl: DefId)
70                      -> specialization_graph::Ancestors<'gcx> {
71         specialization_graph::ancestors(tcx, self.def_id, of_impl)
72     }
73 }
74
75 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
76     pub fn for_each_impl<F: FnMut(DefId)>(self, def_id: DefId, mut f: F) {
77         let impls = self.trait_impls_of(def_id);
78
79         for &impl_def_id in impls.blanket_impls.iter() {
80             f(impl_def_id);
81         }
82
83         for v in impls.non_blanket_impls.values() {
84             for &impl_def_id in v {
85                 f(impl_def_id);
86             }
87         }
88     }
89
90     /// Iterate over every impl that could possibly match the
91     /// self type `self_ty`.
92     pub fn for_each_relevant_impl<F: FnMut(DefId)>(self,
93                                                    def_id: DefId,
94                                                    self_ty: Ty<'tcx>,
95                                                    mut f: F)
96     {
97         let impls = self.trait_impls_of(def_id);
98
99         for &impl_def_id in impls.blanket_impls.iter() {
100             f(impl_def_id);
101         }
102
103         // simplify_type(.., false) basically replaces type parameters and
104         // projections with infer-variables. This is, of course, done on
105         // the impl trait-ref when it is instantiated, but not on the
106         // predicate trait-ref which is passed here.
107         //
108         // for example, if we match `S: Copy` against an impl like
109         // `impl<T:Copy> Copy for Option<T>`, we replace the type variable
110         // in `Option<T>` with an infer variable, to `Option<_>` (this
111         // doesn't actually change fast_reject output), but we don't
112         // replace `S` with anything - this impl of course can't be
113         // selected, and as there are hundreds of similar impls,
114         // considering them would significantly harm performance.
115
116         // This depends on the set of all impls for the trait. That is
117         // unfortunate. When we get red-green recompilation, we would like
118         // to have a way of knowing whether the set of relevant impls
119         // changed. The most naive
120         // way would be to compute the Vec of relevant impls and see whether
121         // it differs between compilations. That shouldn't be too slow by
122         // itself - we do quite a bit of work for each relevant impl anyway.
123         //
124         // If we want to be faster, we could have separate queries for
125         // blanket and non-blanket impls, and compare them separately.
126         //
127         // I think we'll cross that bridge when we get to it.
128         if let Some(simp) = fast_reject::simplify_type(self, self_ty, true) {
129             if let Some(impls) = impls.non_blanket_impls.get(&simp) {
130                 for &impl_def_id in impls {
131                     f(impl_def_id);
132                 }
133             }
134         } else {
135             for &impl_def_id in impls.non_blanket_impls.values().flatten() {
136                 f(impl_def_id);
137             }
138         }
139     }
140
141     /// Returns a vector containing all impls
142     pub fn all_impls(self, def_id: DefId) -> Vec<DefId> {
143         let impls = self.trait_impls_of(def_id);
144
145         impls.blanket_impls.iter().chain(
146             impls.non_blanket_impls.values().flatten()
147         ).cloned().collect()
148     }
149 }
150
151 // Query provider for `trait_impls_of`.
152 pub(super) fn trait_impls_of_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
153                                                 trait_id: DefId)
154                                                 -> Lrc<TraitImpls> {
155     let mut impls = TraitImpls::default();
156
157     {
158         let mut add_impl = |impl_def_id| {
159             let impl_self_ty = tcx.type_of(impl_def_id);
160             if impl_def_id.is_local() && impl_self_ty.references_error() {
161                 return;
162             }
163
164             if let Some(simplified_self_ty) =
165                 fast_reject::simplify_type(tcx, impl_self_ty, false)
166             {
167                 impls.non_blanket_impls
168                      .entry(simplified_self_ty)
169                      .or_default()
170                      .push(impl_def_id);
171             } else {
172                 impls.blanket_impls.push(impl_def_id);
173             }
174         };
175
176         // Traits defined in the current crate can't have impls in upstream
177         // crates, so we don't bother querying the cstore.
178         if !trait_id.is_local() {
179             for &cnum in tcx.crates().iter() {
180                 for &def_id in tcx.implementations_of_trait((cnum, trait_id)).iter() {
181                     add_impl(def_id);
182                 }
183             }
184         }
185
186         for &hir_id in tcx.hir().trait_impls(trait_id) {
187             add_impl(tcx.hir().local_def_id_from_hir_id(hir_id));
188         }
189     }
190
191     Lrc::new(impls)
192 }
193
194 impl<'a> HashStable<StableHashingContext<'a>> for TraitImpls {
195     fn hash_stable<W: StableHasherResult>(&self,
196                                           hcx: &mut StableHashingContext<'a>,
197                                           hasher: &mut StableHasher<W>) {
198         let TraitImpls {
199             ref blanket_impls,
200             ref non_blanket_impls,
201         } = *self;
202
203         ich::hash_stable_trait_impls(hcx, hasher, blanket_impls, non_blanket_impls);
204     }
205 }