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