]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/trait_def.rs
Rollup merge of #106625 - Swatinem:ref/cov6, r=nagisa
[rust.git] / compiler / rustc_middle / src / ty / trait_def.rs
1 use crate::traits::specialization_graph;
2 use crate::ty::fast_reject::{self, SimplifiedType, TreatParams};
3 use crate::ty::visit::TypeVisitable;
4 use crate::ty::{Ident, Ty, TyCtxt};
5 use hir::def_id::LOCAL_CRATE;
6 use rustc_hir as hir;
7 use rustc_hir::def_id::DefId;
8 use std::iter;
9
10 use rustc_data_structures::fx::FxIndexMap;
11 use rustc_errors::ErrorGuaranteed;
12 use rustc_macros::HashStable;
13
14 /// A trait's definition with type information.
15 #[derive(HashStable, Encodable, Decodable)]
16 pub struct TraitDef {
17     pub def_id: DefId,
18
19     pub unsafety: hir::Unsafety,
20
21     /// If `true`, then this trait had the `#[rustc_paren_sugar]`
22     /// attribute, indicating that it should be used with `Foo()`
23     /// sugar. This is a temporary thing -- eventually any trait will
24     /// be usable with the sugar (or without it).
25     pub paren_sugar: bool,
26
27     pub has_auto_impl: bool,
28
29     /// If `true`, then this trait has the `#[marker]` attribute, indicating
30     /// that all its associated items have defaults that cannot be overridden,
31     /// and thus `impl`s of it are allowed to overlap.
32     pub is_marker: bool,
33
34     /// If `true`, then this trait has the `#[rustc_skip_array_during_method_dispatch]`
35     /// attribute, indicating that editions before 2021 should not consider this trait
36     /// during method dispatch if the receiver is an array.
37     pub skip_array_during_method_dispatch: bool,
38
39     /// Used to determine whether the standard library is allowed to specialize
40     /// on this trait.
41     pub specialization_kind: TraitSpecializationKind,
42
43     /// List of functions from `#[rustc_must_implement_one_of]` attribute one of which
44     /// must be implemented.
45     pub must_implement_one_of: Option<Box<[Ident]>>,
46 }
47
48 /// Whether this trait is treated specially by the standard library
49 /// specialization lint.
50 #[derive(HashStable, PartialEq, Clone, Copy, Encodable, Decodable)]
51 pub enum TraitSpecializationKind {
52     /// The default. Specializing on this trait is not allowed.
53     None,
54     /// Specializing on this trait is allowed because it doesn't have any
55     /// methods. For example `Sized` or `FusedIterator`.
56     /// Applies to traits with the `rustc_unsafe_specialization_marker`
57     /// attribute.
58     Marker,
59     /// Specializing on this trait is allowed because all of the impls of this
60     /// trait are "always applicable". Always applicable means that if
61     /// `X<'x>: T<'y>` for any lifetimes, then `for<'a, 'b> X<'a>: T<'b>`.
62     /// Applies to traits with the `rustc_specialization_trait` attribute.
63     AlwaysApplicable,
64 }
65
66 #[derive(Default, Debug, HashStable)]
67 pub struct TraitImpls {
68     blanket_impls: Vec<DefId>,
69     /// Impls indexed by their simplified self type, for fast lookup.
70     non_blanket_impls: FxIndexMap<SimplifiedType, Vec<DefId>>,
71 }
72
73 impl TraitImpls {
74     pub fn blanket_impls(&self) -> &[DefId] {
75         self.blanket_impls.as_slice()
76     }
77
78     pub fn non_blanket_impls(&self) -> &FxIndexMap<SimplifiedType, Vec<DefId>> {
79         &self.non_blanket_impls
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         must_implement_one_of: Option<Box<[Ident]>>,
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             must_implement_one_of,
103         }
104     }
105
106     pub fn ancestors(
107         &self,
108         tcx: TyCtxt<'tcx>,
109         of_impl: DefId,
110     ) -> Result<specialization_graph::Ancestors<'tcx>, ErrorGuaranteed> {
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     pub fn non_blanket_impls_for_ty(
145         self,
146         def_id: DefId,
147         self_ty: Ty<'tcx>,
148     ) -> impl Iterator<Item = DefId> + 'tcx {
149         let impls = self.trait_impls_of(def_id);
150         if let Some(simp) = fast_reject::simplify_type(self, self_ty, TreatParams::AsInfer) {
151             if let Some(impls) = impls.non_blanket_impls.get(&simp) {
152                 return impls.iter().copied();
153             }
154         }
155
156         [].iter().copied()
157     }
158
159     /// Applies function to every impl that could possibly match the self type `self_ty` and returns
160     /// the first non-none value.
161     pub fn find_map_relevant_impl<T, F: FnMut(DefId) -> Option<T>>(
162         self,
163         def_id: DefId,
164         self_ty: Ty<'tcx>,
165         mut f: F,
166     ) -> Option<T> {
167         // FIXME: This depends on the set of all impls for the trait. That is
168         // unfortunate wrt. incremental compilation.
169         //
170         // If we want to be faster, we could have separate queries for
171         // blanket and non-blanket impls, and compare them separately.
172         let impls = self.trait_impls_of(def_id);
173
174         for &impl_def_id in impls.blanket_impls.iter() {
175             if let result @ Some(_) = f(impl_def_id) {
176                 return result;
177             }
178         }
179
180         // Note that we're using `TreatParams::AsPlaceholder` to query `non_blanket_impls` while using
181         // `TreatParams::AsInfer` while actually adding them.
182         //
183         // This way, when searching for some impl for `T: Trait`, we do not look at any impls
184         // whose outer level is not a parameter or projection. Especially for things like
185         // `T: Clone` this is incredibly useful as we would otherwise look at all the impls
186         // of `Clone` for `Option<T>`, `Vec<T>`, `ConcreteType` and so on.
187         if let Some(simp) = fast_reject::simplify_type(self, self_ty, TreatParams::AsPlaceholder) {
188             if let Some(impls) = impls.non_blanket_impls.get(&simp) {
189                 for &impl_def_id in impls {
190                     if let result @ Some(_) = f(impl_def_id) {
191                         return result;
192                     }
193                 }
194             }
195         } else {
196             for &impl_def_id in impls.non_blanket_impls.values().flatten() {
197                 if let result @ Some(_) = f(impl_def_id) {
198                     return result;
199                 }
200             }
201         }
202
203         None
204     }
205
206     /// Returns an iterator containing all impls
207     pub fn all_impls(self, def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
208         let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(def_id);
209
210         blanket_impls.iter().chain(non_blanket_impls.iter().flat_map(|(_, v)| v)).cloned()
211     }
212 }
213
214 /// Query provider for `trait_impls_of`.
215 pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> TraitImpls {
216     let mut impls = TraitImpls::default();
217
218     // Traits defined in the current crate can't have impls in upstream
219     // crates, so we don't bother querying the cstore.
220     if !trait_id.is_local() {
221         for &cnum in tcx.crates(()).iter() {
222             for &(impl_def_id, simplified_self_ty) in
223                 tcx.implementations_of_trait((cnum, trait_id)).iter()
224             {
225                 if let Some(simplified_self_ty) = simplified_self_ty {
226                     impls
227                         .non_blanket_impls
228                         .entry(simplified_self_ty)
229                         .or_default()
230                         .push(impl_def_id);
231                 } else {
232                     impls.blanket_impls.push(impl_def_id);
233                 }
234             }
235         }
236     }
237
238     for &impl_def_id in tcx.hir().trait_impls(trait_id) {
239         let impl_def_id = impl_def_id.to_def_id();
240
241         let impl_self_ty = tcx.type_of(impl_def_id);
242         if impl_self_ty.references_error() {
243             continue;
244         }
245
246         if let Some(simplified_self_ty) =
247             fast_reject::simplify_type(tcx, impl_self_ty, TreatParams::AsInfer)
248         {
249             impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id);
250         } else {
251             impls.blanket_impls.push(impl_def_id);
252         }
253     }
254
255     impls
256 }
257
258 /// Query provider for `incoherent_impls`.
259 pub(super) fn incoherent_impls_provider(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] {
260     let mut impls = Vec::new();
261
262     for cnum in iter::once(LOCAL_CRATE).chain(tcx.crates(()).iter().copied()) {
263         for &impl_def_id in tcx.crate_incoherent_impls((cnum, simp)) {
264             impls.push(impl_def_id)
265         }
266     }
267
268     debug!(?impls);
269
270     tcx.arena.alloc_slice(&impls)
271 }