rustc_hir_analysis/coherence/
inherent_impls.rs1use rustc_hir as hir;
11use rustc_hir::def::DefKind;
12use rustc_hir::def_id::{DefId, LocalDefId};
13use rustc_hir::find_attr;
14use rustc_middle::bug;
15use rustc_middle::ty::fast_reject::{SimplifiedType, TreatParams, simplify_type};
16use rustc_middle::ty::{self, CrateInherentImpls, Ty, TyCtxt};
17use rustc_span::ErrorGuaranteed;
18
19use crate::errors;
20
21pub(crate) fn crate_inherent_impls(
23 tcx: TyCtxt<'_>,
24 (): (),
25) -> (&'_ CrateInherentImpls, Result<(), ErrorGuaranteed>) {
26 let mut collect = InherentCollect { tcx, impls_map: Default::default() };
27
28 let mut res = Ok(());
29 for id in tcx.hir_free_items() {
30 res = res.and(collect.check_item(id));
31 }
32
33 (tcx.arena.alloc(collect.impls_map), res)
34}
35
36pub(crate) fn crate_inherent_impls_validity_check(
37 tcx: TyCtxt<'_>,
38 (): (),
39) -> Result<(), ErrorGuaranteed> {
40 tcx.crate_inherent_impls(()).1
41}
42
43pub(crate) fn crate_incoherent_impls(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] {
44 let (crate_map, _) = tcx.crate_inherent_impls(());
45 tcx.arena.alloc_from_iter(
46 crate_map.incoherent_impls.get(&simp).unwrap_or(&Vec::new()).iter().map(|d| d.to_def_id()),
47 )
48}
49
50pub(crate) fn inherent_impls(tcx: TyCtxt<'_>, ty_def_id: LocalDefId) -> &[DefId] {
52 let (crate_map, _) = tcx.crate_inherent_impls(());
53 match crate_map.inherent_impls.get(&ty_def_id) {
54 Some(v) => &v[..],
55 None => &[],
56 }
57}
58
59struct InherentCollect<'tcx> {
60 tcx: TyCtxt<'tcx>,
61 impls_map: CrateInherentImpls,
62}
63
64impl<'tcx> InherentCollect<'tcx> {
65 fn check_def_id(
66 &mut self,
67 impl_def_id: LocalDefId,
68 self_ty: Ty<'tcx>,
69 ty_def_id: DefId,
70 ) -> Result<(), ErrorGuaranteed> {
71 if let Some(ty_def_id) = ty_def_id.as_local() {
72 let vec = self.impls_map.inherent_impls.entry(ty_def_id).or_default();
76 vec.push(impl_def_id.to_def_id());
77 return Ok(());
78 }
79
80 if self.tcx.features().rustc_attrs() {
81 if !{
#[allow(deprecated)]
{
{
'done:
{
for i in self.tcx.get_all_attrs(ty_def_id) {
#[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!(self.tcx, ty_def_id, RustcHasIncoherentInherentImpls) {
82 let impl_span = self.tcx.def_span(impl_def_id);
83 return Err(self.tcx.dcx().emit_err(errors::InherentTyOutside { span: impl_span }));
84 }
85
86 let items = self.tcx.associated_item_def_ids(impl_def_id);
87 for &impl_item in items {
88 if !{
#[allow(deprecated)]
{
{
'done:
{
for i in self.tcx.get_all_attrs(impl_item) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcAllowIncoherentImpl(_)) =>
{
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}.is_some()find_attr!(self.tcx, impl_item, RustcAllowIncoherentImpl(_)) {
89 let impl_span = self.tcx.def_span(impl_def_id);
90 return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsideRelevant {
91 span: impl_span,
92 help_span: self.tcx.def_span(impl_item),
93 }));
94 }
95 }
96
97 if let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::InstantiateWithInfer)
98 {
99 self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
100 } else {
101 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected self type: {0:?}",
self_ty));bug!("unexpected self type: {:?}", self_ty);
102 }
103 Ok(())
104 } else {
105 let impl_span = self.tcx.def_span(impl_def_id);
106 let mut err = errors::InherentTyOutsideNew { span: impl_span, note: None };
107
108 if let hir::TyKind::Path(rustc_hir::QPath::Resolved(_, path)) =
109 self.tcx.hir_node_by_def_id(impl_def_id).expect_item().expect_impl().self_ty.kind
110 && let rustc_hir::def::Res::Def(DefKind::TyAlias, def_id) = path.res
111 {
112 let ty_name = self.tcx.def_path_str(def_id);
113 let alias_ty_name = self.tcx.type_of(def_id).skip_binder().to_string();
114 err.note = Some(errors::InherentTyOutsideNewAliasNote {
115 span: self.tcx.def_span(def_id),
116 ty_name,
117 alias_ty_name,
118 });
119 }
120
121 Err(self.tcx.dcx().emit_err(err))
122 }
123 }
124
125 fn check_primitive_impl(
126 &mut self,
127 impl_def_id: LocalDefId,
128 ty: Ty<'tcx>,
129 ) -> Result<(), ErrorGuaranteed> {
130 let items = self.tcx.associated_item_def_ids(impl_def_id);
131 if !self.tcx.hir_rustc_coherence_is_core() {
132 if self.tcx.features().rustc_attrs() {
133 for &impl_item in items {
134 if !{
#[allow(deprecated)]
{
{
'done:
{
for i in self.tcx.get_all_attrs(impl_item) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcAllowIncoherentImpl(_)) =>
{
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}.is_some()find_attr!(self.tcx, impl_item, RustcAllowIncoherentImpl(_)) {
135 let span = self.tcx.def_span(impl_def_id);
136 return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsidePrimitive {
137 span,
138 help_span: self.tcx.def_span(impl_item),
139 }));
140 }
141 }
142 } else {
143 let span = self.tcx.def_span(impl_def_id);
144 let mut note = None;
145 if let ty::Ref(_, subty, _) = ty.kind() {
146 note = Some(errors::InherentPrimitiveTyNote { subty: *subty });
147 }
148 return Err(self.tcx.dcx().emit_err(errors::InherentPrimitiveTy { span, note }));
149 }
150 }
151
152 if let Some(simp) = simplify_type(self.tcx, ty, TreatParams::InstantiateWithInfer) {
153 self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
154 } else {
155 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected primitive type: {0:?}",
ty));bug!("unexpected primitive type: {:?}", ty);
156 }
157 Ok(())
158 }
159
160 fn check_item(&mut self, id: hir::ItemId) -> Result<(), ErrorGuaranteed> {
161 if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(id.owner_id)
{
DefKind::Impl { of_trait: false } => true,
_ => false,
}matches!(self.tcx.def_kind(id.owner_id), DefKind::Impl { of_trait: false }) {
162 return Ok(());
163 }
164
165 let id = id.owner_id.def_id;
166 let item_span = self.tcx.def_span(id);
167 let self_ty = self.tcx.type_of(id).instantiate_identity();
168 let mut self_ty = self.tcx.peel_off_free_alias_tys(self_ty);
169 while let ty::Pat(base, _) = *self_ty.kind() {
172 self_ty = base;
173 }
174 match *self_ty.kind() {
175 ty::Adt(def, _) => self.check_def_id(id, self_ty, def.did()),
176 ty::Foreign(did) => self.check_def_id(id, self_ty, did),
177 ty::Dynamic(data, ..) if data.principal_def_id().is_some() => {
178 self.check_def_id(id, self_ty, data.principal_def_id().unwrap())
179 }
180 ty::Dynamic(..) => {
181 Err(self.tcx.dcx().emit_err(errors::InherentDyn { span: item_span }))
182 }
183 ty::Pat(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
184 ty::Bool
185 | ty::Char
186 | ty::Int(_)
187 | ty::Uint(_)
188 | ty::Float(_)
189 | ty::Str
190 | ty::Array(..)
191 | ty::Slice(_)
192 | ty::RawPtr(_, _)
193 | ty::Ref(..)
194 | ty::Never
195 | ty::FnPtr(..)
196 | ty::Tuple(..)
197 | ty::UnsafeBinder(_) => self.check_primitive_impl(id, self_ty),
198 ty::Alias(ty::Projection | ty::Inherent | ty::Opaque, _) | ty::Param(_) => {
199 Err(self.tcx.dcx().emit_err(errors::InherentNominal { span: item_span }))
200 }
201 ty::FnDef(..)
202 | ty::Closure(..)
203 | ty::CoroutineClosure(..)
204 | ty::Coroutine(..)
205 | ty::CoroutineWitness(..)
206 | ty::Alias(ty::Free, _)
207 | ty::Bound(..)
208 | ty::Placeholder(_)
209 | ty::Infer(_) => {
210 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected impl self type of impl: {0:?} {1:?}",
id, self_ty));bug!("unexpected impl self type of impl: {:?} {:?}", id, self_ty);
211 }
212 ty::Error(_) => Ok(()),
214 }
215 }
216}