1use std::iter;
2use std::ops::ControlFlow;
3
4use rustc_data_structures::fx::FxIndexMap;
5use rustc_errors::ErrorGuaranteed;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE};
8use rustc_hir::{self as hir, find_attr};
9use rustc_macros::{Decodable, Encodable, StableHash};
10use rustc_span::Span;
11use tracing::debug;
12
13use crate::query::LocalCrate;
14use crate::traits::specialization_graph;
15use crate::ty::fast_reject::{self, SimplifiedType, TreatParams};
16use crate::ty::{self, Ident, Interner, RestrictionKind, Ty, TyCtxt, VisitorResult};
17
18#[derive(const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for TraitDef {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
TraitDef {
def_id: ref __binding_0,
impl_restriction: ref __binding_1,
safety: ref __binding_2,
constness: ref __binding_3,
paren_sugar: ref __binding_4,
has_auto_impl: ref __binding_5,
is_marker: ref __binding_6,
is_coinductive: ref __binding_7,
is_fundamental: ref __binding_8,
skip_array_during_method_dispatch: ref __binding_9,
skip_boxed_slice_during_method_dispatch: ref __binding_10,
specialization_kind: ref __binding_11,
must_implement_one_of: ref __binding_12,
force_dyn_incompatible: ref __binding_13,
deny_explicit_impl: ref __binding_14 } => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
{ __binding_2.stable_hash(__hcx, __hasher); }
{ __binding_3.stable_hash(__hcx, __hasher); }
{ __binding_4.stable_hash(__hcx, __hasher); }
{ __binding_5.stable_hash(__hcx, __hasher); }
{ __binding_6.stable_hash(__hcx, __hasher); }
{ __binding_7.stable_hash(__hcx, __hasher); }
{ __binding_8.stable_hash(__hcx, __hasher); }
{ __binding_9.stable_hash(__hcx, __hasher); }
{ __binding_10.stable_hash(__hcx, __hasher); }
{ __binding_11.stable_hash(__hcx, __hasher); }
{ __binding_12.stable_hash(__hcx, __hasher); }
{ __binding_13.stable_hash(__hcx, __hasher); }
{ __binding_14.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for TraitDef {
fn encode(&self, __encoder: &mut __E) {
match *self {
TraitDef {
def_id: ref __binding_0,
impl_restriction: ref __binding_1,
safety: ref __binding_2,
constness: ref __binding_3,
paren_sugar: ref __binding_4,
has_auto_impl: ref __binding_5,
is_marker: ref __binding_6,
is_coinductive: ref __binding_7,
is_fundamental: ref __binding_8,
skip_array_during_method_dispatch: ref __binding_9,
skip_boxed_slice_during_method_dispatch: ref __binding_10,
specialization_kind: ref __binding_11,
must_implement_one_of: ref __binding_12,
force_dyn_incompatible: ref __binding_13,
deny_explicit_impl: ref __binding_14 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for TraitDef {
fn decode(__decoder: &mut __D) -> Self {
TraitDef {
def_id: ::rustc_serialize::Decodable::decode(__decoder),
impl_restriction: ::rustc_serialize::Decodable::decode(__decoder),
safety: ::rustc_serialize::Decodable::decode(__decoder),
constness: ::rustc_serialize::Decodable::decode(__decoder),
paren_sugar: ::rustc_serialize::Decodable::decode(__decoder),
has_auto_impl: ::rustc_serialize::Decodable::decode(__decoder),
is_marker: ::rustc_serialize::Decodable::decode(__decoder),
is_coinductive: ::rustc_serialize::Decodable::decode(__decoder),
is_fundamental: ::rustc_serialize::Decodable::decode(__decoder),
skip_array_during_method_dispatch: ::rustc_serialize::Decodable::decode(__decoder),
skip_boxed_slice_during_method_dispatch: ::rustc_serialize::Decodable::decode(__decoder),
specialization_kind: ::rustc_serialize::Decodable::decode(__decoder),
must_implement_one_of: ::rustc_serialize::Decodable::decode(__decoder),
force_dyn_incompatible: ::rustc_serialize::Decodable::decode(__decoder),
deny_explicit_impl: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
20pub struct TraitDef {
21 pub def_id: DefId,
22
23 pub impl_restriction: RestrictionKind,
25
26 pub safety: hir::Safety,
27
28 pub constness: hir::Constness,
30
31 pub paren_sugar: bool,
36
37 pub has_auto_impl: bool,
38
39 pub is_marker: bool,
43
44 pub is_coinductive: bool,
52
53 pub is_fundamental: bool,
57
58 pub skip_array_during_method_dispatch: bool,
62
63 pub skip_boxed_slice_during_method_dispatch: bool,
67
68 pub specialization_kind: TraitSpecializationKind,
71
72 pub must_implement_one_of: Option<Box<[Ident]>>,
75
76 pub force_dyn_incompatible: Option<Span>,
79
80 pub deny_explicit_impl: bool,
84}
85
86#[derive(const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
TraitSpecializationKind {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
TraitSpecializationKind::None => {}
TraitSpecializationKind::Marker => {}
TraitSpecializationKind::AlwaysApplicable => {}
}
}
}
};StableHash, #[automatically_derived]
impl ::core::cmp::PartialEq for TraitSpecializationKind {
#[inline]
fn eq(&self, other: &TraitSpecializationKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for TraitSpecializationKind {
#[inline]
fn clone(&self) -> TraitSpecializationKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TraitSpecializationKind { }Copy, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for TraitSpecializationKind {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
TraitSpecializationKind::None => { 0usize }
TraitSpecializationKind::Marker => { 1usize }
TraitSpecializationKind::AlwaysApplicable => { 2usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
TraitSpecializationKind::None => {}
TraitSpecializationKind::Marker => {}
TraitSpecializationKind::AlwaysApplicable => {}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for TraitSpecializationKind {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { TraitSpecializationKind::None }
1usize => { TraitSpecializationKind::Marker }
2usize => { TraitSpecializationKind::AlwaysApplicable }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `TraitSpecializationKind`, expected 0..3, actual {0}",
n));
}
}
}
}
};Decodable)]
89pub enum TraitSpecializationKind {
90 None,
92 Marker,
97 AlwaysApplicable,
102}
103
104#[derive(#[automatically_derived]
impl ::core::default::Default for TraitImpls {
#[inline]
fn default() -> TraitImpls {
TraitImpls {
blanket_impls: ::core::default::Default::default(),
non_blanket_impls: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]
impl ::core::fmt::Debug for TraitImpls {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "TraitImpls",
"blanket_impls", &self.blanket_impls, "non_blanket_impls",
&&self.non_blanket_impls)
}
}Debug, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for TraitImpls {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
TraitImpls {
blanket_impls: ref __binding_0,
non_blanket_impls: ref __binding_1 } => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
105pub struct TraitImpls {
106 blanket_impls: Vec<DefId>,
107 non_blanket_impls: FxIndexMap<SimplifiedType, Vec<DefId>>,
109}
110
111impl TraitImpls {
112 pub fn is_empty(&self) -> bool {
113 self.blanket_impls.is_empty() && self.non_blanket_impls.is_empty()
114 }
115
116 pub fn blanket_impls(&self) -> &[DefId] {
117 self.blanket_impls.as_slice()
118 }
119
120 pub fn non_blanket_impls(&self) -> &FxIndexMap<SimplifiedType, Vec<DefId>> {
121 &self.non_blanket_impls
122 }
123}
124
125impl<'tcx> TraitDef {
126 pub fn ancestors(
127 &self,
128 tcx: TyCtxt<'tcx>,
129 of_impl: DefId,
130 ) -> Result<specialization_graph::Ancestors<'tcx>, ErrorGuaranteed> {
131 specialization_graph::ancestors(tcx, self.def_id, of_impl)
132 }
133}
134
135impl<'tcx> TyCtxt<'tcx> {
136 pub fn for_each_relevant_impl<R: VisitorResult>(
140 self,
141 trait_def_id: DefId,
142 self_ty: Ty<'tcx>,
143 mut f: impl FnMut(DefId) -> R,
144 ) -> R {
145 macro_rules! ret {
146 ($e: expr) => {
147 match $e.branch() {
148 ControlFlow::Break(b) => return R::from_residual(b),
149 ControlFlow::Continue(()) => {}
150 }
151 };
152 }
153
154 let tcx = self;
155 let trait_impls = tcx.trait_impls_of(trait_def_id);
156 let mut consider_impls_for_simplified_type = |simp| {
157 if let Some(impls_for_type) = trait_impls.non_blanket_impls().get(&simp) {
158 for &impl_def_id in impls_for_type {
159 match f(impl_def_id).branch() {
ControlFlow::Break(b) => return R::from_residual(b),
ControlFlow::Continue(()) => {}
}ret!(f(impl_def_id))
160 }
161 }
162
163 R::output()
164 };
165
166 match self_ty.kind() {
167 ty::Bool
168 | ty::Char
169 | ty::Int(_)
170 | ty::Uint(_)
171 | ty::Float(_)
172 | ty::Adt(_, _)
173 | ty::Foreign(_)
174 | ty::Str
175 | ty::Array(_, _)
176 | ty::Slice(_)
177 | ty::RawPtr(_, _)
178 | ty::Ref(_, _, _)
179 | ty::FnDef(_, _)
180 | ty::FnPtr(..)
181 | ty::Dynamic(_, _)
182 | ty::Closure(..)
183 | ty::CoroutineClosure(..)
184 | ty::Coroutine(_, _)
185 | ty::Never
186 | ty::Tuple(_)
187 | ty::UnsafeBinder(_) => {
188 let simp = ty::fast_reject::simplify_type(
189 tcx,
190 self_ty,
191 ty::fast_reject::TreatParams::AsRigid,
192 )
193 .unwrap();
194 match consider_impls_for_simplified_type(simp).branch() {
ControlFlow::Break(b) => return R::from_residual(b),
ControlFlow::Continue(()) => {}
};ret!(consider_impls_for_simplified_type(simp));
195 }
196
197 ty::Infer(ty::IntVar(_)) => {
200 use ty::IntTy::*;
201 use ty::UintTy::*;
202 let (I8 | I16 | I32 | I64 | I128 | Isize): ty::IntTy;
204 let (U8 | U16 | U32 | U64 | U128 | Usize): ty::UintTy;
205 let possible_integers = [
206 ty::SimplifiedType::Int(I8),
208 ty::SimplifiedType::Int(I16),
209 ty::SimplifiedType::Int(I32),
210 ty::SimplifiedType::Int(I64),
211 ty::SimplifiedType::Int(I128),
212 ty::SimplifiedType::Int(Isize),
213 ty::SimplifiedType::Uint(U8),
215 ty::SimplifiedType::Uint(U16),
216 ty::SimplifiedType::Uint(U32),
217 ty::SimplifiedType::Uint(U64),
218 ty::SimplifiedType::Uint(U128),
219 ty::SimplifiedType::Uint(Usize),
220 ];
221 for simp in possible_integers {
222 match consider_impls_for_simplified_type(simp).branch() {
ControlFlow::Break(b) => return R::from_residual(b),
ControlFlow::Continue(()) => {}
};ret!(consider_impls_for_simplified_type(simp));
223 }
224 }
225
226 ty::Infer(ty::FloatVar(_)) => {
227 let (ty::FloatTy::F16 | ty::FloatTy::F32 | ty::FloatTy::F64 | ty::FloatTy::F128);
229 let possible_floats = [
230 ty::SimplifiedType::Float(ty::FloatTy::F16),
231 ty::SimplifiedType::Float(ty::FloatTy::F32),
232 ty::SimplifiedType::Float(ty::FloatTy::F64),
233 ty::SimplifiedType::Float(ty::FloatTy::F128),
234 ];
235
236 for simp in possible_floats {
237 match consider_impls_for_simplified_type(simp).branch() {
ControlFlow::Break(b) => return R::from_residual(b),
ControlFlow::Continue(()) => {}
};ret!(consider_impls_for_simplified_type(simp));
238 }
239 }
240
241 ty::Pat(_, _) => {
243 if let Some(simp) = ty::fast_reject::simplify_type(
244 tcx,
245 self_ty,
246 ty::fast_reject::TreatParams::AsRigid,
247 ) {
248 match consider_impls_for_simplified_type(simp).branch() {
ControlFlow::Break(b) => return R::from_residual(b),
ControlFlow::Continue(()) => {}
};ret!(consider_impls_for_simplified_type(simp));
249 }
250 }
251
252 ty::Infer(ty::TyVar(_)) => {
254 for &impl_def_id in trait_impls.non_blanket_impls().values().flatten() {
255 match f(impl_def_id).branch() {
ControlFlow::Break(b) => return R::from_residual(b),
ControlFlow::Continue(()) => {}
};ret!(f(impl_def_id));
256 }
257 }
258
259 ty::Alias(ty::IsRigid::Yes, _) | ty::Placeholder(..) | ty::Error(_) => (),
264 ty::Alias(ty::IsRigid::No, _) => (),
267
268 ty::CoroutineWitness(..) => (),
272
273 ty::Param(_) | ty::Bound(_, _) => (),
275
276 ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
278 crate::util::bug::bug_fmt(format_args!("unexpected self type: {0:?}",
self_ty));bug!("unexpected self type: {self_ty:?}");
279 }
280 }
281
282 #[allow(rustc::usage_of_type_ir_traits)]
283 self.for_each_blanket_impl(trait_def_id, f)
284 }
285
286 pub fn non_blanket_impls_for_ty(
288 self,
289 trait_def_id: DefId,
290 self_ty: Ty<'tcx>,
291 ) -> impl Iterator<Item = DefId> {
292 let impls = self.trait_impls_of(trait_def_id);
293 if let Some(simp) =
294 fast_reject::simplify_type(self, self_ty, TreatParams::InstantiateWithInfer)
295 {
296 if let Some(impls) = impls.non_blanket_impls.get(&simp) {
297 return impls.iter().copied();
298 }
299 }
300
301 [].iter().copied()
302 }
303
304 pub fn all_impls(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> {
308 let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(trait_def_id);
309
310 blanket_impls.iter().chain(non_blanket_impls.iter().flat_map(|(_, v)| v)).cloned()
311 }
312}
313
314pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> TraitImpls {
316 let mut impls = TraitImpls::default();
317
318 if !trait_id.is_local() {
321 for &cnum in tcx.crates(()).iter() {
322 for &(impl_def_id, simplified_self_ty) in
323 tcx.implementations_of_trait((cnum, trait_id)).iter()
324 {
325 if let Some(simplified_self_ty) = simplified_self_ty {
326 impls
327 .non_blanket_impls
328 .entry(simplified_self_ty)
329 .or_default()
330 .push(impl_def_id);
331 } else {
332 impls.blanket_impls.push(impl_def_id);
333 }
334 }
335 }
336 }
337
338 for &impl_def_id in tcx.local_trait_impls(trait_id) {
339 let impl_def_id = impl_def_id.to_def_id();
340
341 let impl_self_ty = tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip();
342
343 if let Some(simplified_self_ty) =
344 fast_reject::simplify_type(tcx, impl_self_ty, TreatParams::InstantiateWithInfer)
345 {
346 impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id);
347 } else {
348 impls.blanket_impls.push(impl_def_id);
349 }
350 }
351
352 impls
353}
354
355pub(super) fn incoherent_impls_provider(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] {
357 if let Some(def_id) = simp.def()
358 && !{
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx)
{
#[allow(unused_imports)]
use ::rustc_hir::attrs::AttributeKind::*;
let i: &::rustc_hir::Attribute = i;
match i {
::rustc_hir::Attribute::Parsed(RustcHasIncoherentInherentImpls)
=> {
break 'done Some(());
}
::rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, RustcHasIncoherentInherentImpls)
359 {
360 return &[];
361 }
362
363 let mut impls = Vec::new();
364 for cnum in iter::once(LOCAL_CRATE).chain(tcx.crates(()).iter().copied()) {
365 for &impl_def_id in tcx.crate_incoherent_impls((cnum, simp)) {
366 impls.push(impl_def_id)
367 }
368 }
369 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/trait_def.rs:369",
"rustc_middle::ty::trait_def", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/trait_def.rs"),
::tracing_core::__macro_support::Option::Some(369u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::trait_def"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impls")
}> =
::tracing::__macro_support::FieldName::new("impls");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impls)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?impls);
370
371 tcx.arena.alloc_slice(&impls)
372}
373
374pub(super) fn traits_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
375 let mut traits = Vec::new();
376 for id in tcx.hir_free_items() {
377 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(id.owner_id) {
DefKind::Trait | DefKind::TraitAlias => true,
_ => false,
}matches!(tcx.def_kind(id.owner_id), DefKind::Trait | DefKind::TraitAlias) {
378 traits.push(id.owner_id.to_def_id())
379 }
380 }
381
382 tcx.arena.alloc_slice(&traits)
383}
384
385pub(super) fn trait_impls_in_crate_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
386 let mut trait_impls = Vec::new();
387 for id in tcx.hir_free_items() {
388 if tcx.def_kind(id.owner_id) == (DefKind::Impl { of_trait: true }) {
389 trait_impls.push(id.owner_id.to_def_id())
390 }
391 }
392
393 tcx.arena.alloc_slice(&trait_impls)
394}