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