]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/trait_def.rs
Rollup merge of #89224 - TaKO8Ki:change-the-order-of-suggestions, r=joshtriplett
[rust.git] / compiler / rustc_middle / src / ty / trait_def.rs
1 use crate::traits::specialization_graph;
2 use crate::ty::fast_reject;
3 use crate::ty::fold::TypeFoldable;
4 use crate::ty::{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
49 /// Whether this trait is treated specially by the standard library
50 /// specialization lint.
51 #[derive(HashStable, PartialEq, Clone, Copy, TyEncodable, TyDecodable)]
52 pub enum TraitSpecializationKind {
53     /// The default. Specializing on this trait is not allowed.
54     None,
55     /// Specializing on this trait is allowed because it doesn't have any
56     /// methods. For example `Sized` or `FusedIterator`.
57     /// Applies to traits with the `rustc_unsafe_specialization_marker`
58     /// attribute.
59     Marker,
60     /// Specializing on this trait is allowed because all of the impls of this
61     /// trait are "always applicable". Always applicable means that if
62     /// `X<'x>: T<'y>` for any lifetimes, then `for<'a, 'b> X<'a>: T<'b>`.
63     /// Applies to traits with the `rustc_specialization_trait` attribute.
64     AlwaysApplicable,
65 }
66
67 #[derive(Default, Debug, HashStable)]
68 pub struct TraitImpls {
69     blanket_impls: Vec<DefId>,
70     /// Impls indexed by their simplified self type, for fast lookup.
71     non_blanket_impls: FxIndexMap<fast_reject::SimplifiedType, Vec<DefId>>,
72 }
73
74 impl TraitImpls {
75     pub fn blanket_impls(&self) -> &[DefId] {
76         self.blanket_impls.as_slice()
77     }
78 }
79
80 impl<'tcx> TraitDef {
81     pub fn new(
82         def_id: DefId,
83         unsafety: hir::Unsafety,
84         paren_sugar: bool,
85         has_auto_impl: bool,
86         is_marker: bool,
87         skip_array_during_method_dispatch: bool,
88         specialization_kind: TraitSpecializationKind,
89         def_path_hash: DefPathHash,
90     ) -> TraitDef {
91         TraitDef {
92             def_id,
93             unsafety,
94             paren_sugar,
95             has_auto_impl,
96             is_marker,
97             skip_array_during_method_dispatch,
98             specialization_kind,
99             def_path_hash,
100         }
101     }
102
103     pub fn ancestors(
104         &self,
105         tcx: TyCtxt<'tcx>,
106         of_impl: DefId,
107     ) -> Result<specialization_graph::Ancestors<'tcx>, ErrorReported> {
108         specialization_graph::ancestors(tcx, self.def_id, of_impl)
109     }
110 }
111
112 impl<'tcx> TyCtxt<'tcx> {
113     pub fn for_each_impl<F: FnMut(DefId)>(self, def_id: DefId, mut f: F) {
114         let impls = self.trait_impls_of(def_id);
115
116         for &impl_def_id in impls.blanket_impls.iter() {
117             f(impl_def_id);
118         }
119
120         for v in impls.non_blanket_impls.values() {
121             for &impl_def_id in v {
122                 f(impl_def_id);
123             }
124         }
125     }
126
127     /// Iterate over every impl that could possibly match the
128     /// self type `self_ty`.
129     pub fn for_each_relevant_impl<F: FnMut(DefId)>(
130         self,
131         def_id: DefId,
132         self_ty: Ty<'tcx>,
133         mut f: F,
134     ) {
135         let _: Option<()> = self.find_map_relevant_impl(def_id, self_ty, |did| {
136             f(did);
137             None
138         });
139     }
140
141     /// Applies function to every impl that could possibly match the self type `self_ty` and returns
142     /// the first non-none value.
143     pub fn find_map_relevant_impl<T, F: FnMut(DefId) -> Option<T>>(
144         self,
145         def_id: DefId,
146         self_ty: Ty<'tcx>,
147         mut f: F,
148     ) -> Option<T> {
149         let impls = self.trait_impls_of(def_id);
150
151         for &impl_def_id in impls.blanket_impls.iter() {
152             if let result @ Some(_) = f(impl_def_id) {
153                 return result;
154             }
155         }
156
157         // simplify_type(.., false) basically replaces type parameters and
158         // projections with infer-variables. This is, of course, done on
159         // the impl trait-ref when it is instantiated, but not on the
160         // predicate trait-ref which is passed here.
161         //
162         // for example, if we match `S: Copy` against an impl like
163         // `impl<T:Copy> Copy for Option<T>`, we replace the type variable
164         // in `Option<T>` with an infer variable, to `Option<_>` (this
165         // doesn't actually change fast_reject output), but we don't
166         // replace `S` with anything - this impl of course can't be
167         // selected, and as there are hundreds of similar impls,
168         // considering them would significantly harm performance.
169
170         // This depends on the set of all impls for the trait. That is
171         // unfortunate. When we get red-green recompilation, we would like
172         // to have a way of knowing whether the set of relevant impls
173         // changed. The most naive
174         // way would be to compute the Vec of relevant impls and see whether
175         // it differs between compilations. That shouldn't be too slow by
176         // itself - we do quite a bit of work for each relevant impl anyway.
177         //
178         // If we want to be faster, we could have separate queries for
179         // blanket and non-blanket impls, and compare them separately.
180         //
181         // I think we'll cross that bridge when we get to it.
182         if let Some(simp) = fast_reject::simplify_type(self, self_ty, true) {
183             if let Some(impls) = impls.non_blanket_impls.get(&simp) {
184                 for &impl_def_id in impls {
185                     if let result @ Some(_) = f(impl_def_id) {
186                         return result;
187                     }
188                 }
189             }
190         } else {
191             for &impl_def_id in impls.non_blanket_impls.values().flatten() {
192                 if let result @ Some(_) = f(impl_def_id) {
193                     return result;
194                 }
195             }
196         }
197
198         None
199     }
200
201     /// Returns an iterator containing all impls
202     pub fn all_impls(self, def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
203         let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(def_id);
204
205         blanket_impls.iter().chain(non_blanket_impls.iter().map(|(_, v)| v).flatten()).cloned()
206     }
207 }
208
209 // Query provider for `trait_impls_of`.
210 pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> TraitImpls {
211     let mut impls = TraitImpls::default();
212
213     // Traits defined in the current crate can't have impls in upstream
214     // crates, so we don't bother querying the cstore.
215     if !trait_id.is_local() {
216         for &cnum in tcx.crates(()).iter() {
217             for &(impl_def_id, simplified_self_ty) in
218                 tcx.implementations_of_trait((cnum, trait_id)).iter()
219             {
220                 if let Some(simplified_self_ty) = simplified_self_ty {
221                     impls
222                         .non_blanket_impls
223                         .entry(simplified_self_ty)
224                         .or_default()
225                         .push(impl_def_id);
226                 } else {
227                     impls.blanket_impls.push(impl_def_id);
228                 }
229             }
230         }
231     }
232
233     for &impl_def_id in tcx.hir().trait_impls(trait_id) {
234         let impl_def_id = impl_def_id.to_def_id();
235
236         let impl_self_ty = tcx.type_of(impl_def_id);
237         if impl_self_ty.references_error() {
238             continue;
239         }
240
241         if let Some(simplified_self_ty) = fast_reject::simplify_type(tcx, impl_self_ty, false) {
242             impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id);
243         } else {
244             impls.blanket_impls.push(impl_def_id);
245         }
246     }
247
248     impls
249 }