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};
7 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
8 use rustc_hir::definitions::DefPathHash;
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;
16 /// A trait's definition with type information.
19 // We already have the def_path_hash below, no need to hash it twice
20 #[stable_hasher(ignore)]
23 pub unsafety: hir::Unsafety,
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,
31 pub has_auto_impl: bool,
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.
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,
43 /// Used to determine whether the standard library is allowed to specialize
45 pub specialization_kind: TraitSpecializationKind,
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,
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.
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`
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.
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>>,
78 pub fn blanket_impls(&self) -> &[DefId] {
79 self.blanket_impls.as_slice()
86 unsafety: hir::Unsafety,
90 skip_array_during_method_dispatch: bool,
91 specialization_kind: TraitSpecializationKind,
92 def_path_hash: DefPathHash,
100 skip_array_during_method_dispatch,
110 ) -> Result<specialization_graph::Ancestors<'tcx>, ErrorReported> {
111 specialization_graph::ancestors(tcx, self.def_id, of_impl)
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);
119 for &impl_def_id in impls.blanket_impls.iter() {
123 for v in impls.non_blanket_impls.values() {
124 for &impl_def_id in v {
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)>(
138 let _: Option<()> = self.find_map_relevant_impl(def_id, self_ty, |did| {
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>>(
152 let impls = self.trait_impls_of(def_id);
154 for &impl_def_id in impls.blanket_impls.iter() {
155 if let result @ Some(_) = f(impl_def_id) {
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.
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.
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.
181 // If we want to be faster, we could have separate queries for
182 // blanket and non-blanket impls, and compare them separately.
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) {
194 for &impl_def_id in impls.non_blanket_impls.values().flatten() {
195 if let result @ Some(_) = f(impl_def_id) {
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);
208 blanket_impls.iter().chain(non_blanket_impls.iter().map(|(_, v)| v).flatten()).cloned()
212 // Query provider for `all_local_trait_impls`.
213 pub(super) fn all_local_trait_impls<'tcx>(
216 ) -> &'tcx BTreeMap<DefId, Vec<LocalDefId>> {
217 &tcx.hir_crate(krate).trait_impls
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();
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()
231 if let Some(simplified_self_ty) = simplified_self_ty {
234 .entry(simplified_self_ty)
238 impls.blanket_impls.push(impl_def_id);
244 for &impl_def_id in tcx.hir().trait_impls(trait_id) {
245 let impl_def_id = impl_def_id.to_def_id();
247 let impl_self_ty = tcx.type_of(impl_def_id);
248 if impl_self_ty.references_error() {
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);
255 impls.blanket_impls.push(impl_def_id);
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;
266 ich::hash_stable_trait_impls(hcx, hasher, blanket_impls, non_blanket_impls);