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