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