1 //! The code in this module gathers up all of the inherent impls in
2 //! the current crate and organizes them in a map. It winds up
3 //! touching the whole crate and thus must be recomputed completely
4 //! for any change, but it is very cheap to compute. In practice, most
5 //! code in the compiler never *directly* requests this map. Instead,
6 //! it requests the inherent impls specific to some type (via
7 //! `tcx.inherent_impls(def_id)`). That value, however,
8 //! is computed by selecting an idea from this table.
10 use rustc_errors::struct_span_err;
12 use rustc_hir::def::DefKind;
13 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
14 use rustc_middle::ty::fast_reject::{simplify_type, SimplifiedType, TreatParams};
15 use rustc_middle::ty::{self, CrateInherentImpls, Ty, TyCtxt};
16 use rustc_span::symbol::sym;
19 /// On-demand query: yields a map containing all types mapped to their inherent impls.
20 pub fn crate_inherent_impls(tcx: TyCtxt<'_>, (): ()) -> CrateInherentImpls {
21 let mut collect = InherentCollect { tcx, impls_map: Default::default() };
22 for id in tcx.hir().items() {
23 collect.check_item(id);
28 pub fn crate_incoherent_impls(tcx: TyCtxt<'_>, (_, simp): (CrateNum, SimplifiedType)) -> &[DefId] {
29 let crate_map = tcx.crate_inherent_impls(());
30 tcx.arena.alloc_from_iter(
31 crate_map.incoherent_impls.get(&simp).unwrap_or(&Vec::new()).iter().map(|d| d.to_def_id()),
35 /// On-demand query: yields a vector of the inherent impls for a specific type.
36 pub fn inherent_impls(tcx: TyCtxt<'_>, ty_def_id: DefId) -> &[DefId] {
37 let ty_def_id = ty_def_id.expect_local();
39 let crate_map = tcx.crate_inherent_impls(());
40 match crate_map.inherent_impls.get(&ty_def_id) {
46 struct InherentCollect<'tcx> {
48 impls_map: CrateInherentImpls,
51 const INTO_CORE: &str = "consider moving this inherent impl into `core` if possible";
52 const INTO_DEFINING_CRATE: &str =
53 "consider moving this inherent impl into the crate defining the type if possible";
54 const ADD_ATTR_TO_TY: &str = "alternatively add `#[rustc_has_incoherent_inherent_impls]` to the type \
55 and `#[rustc_allow_incoherent_impl]` to the relevant impl items";
56 const ADD_ATTR: &str =
57 "alternatively add `#[rustc_allow_incoherent_impl]` to the relevant impl items";
59 impl<'tcx> InherentCollect<'tcx> {
60 fn check_def_id(&mut self, item: &hir::Item<'_>, self_ty: Ty<'tcx>, def_id: DefId) {
61 let impl_def_id = item.def_id;
62 if let Some(def_id) = def_id.as_local() {
63 // Add the implementation to the mapping from implementation to base
64 // type def ID, if there is a base type for this implementation and
65 // the implementation does not have any associated traits.
66 let vec = self.impls_map.inherent_impls.entry(def_id).or_default();
67 vec.push(impl_def_id.to_def_id());
71 if self.tcx.features().rustc_attrs {
72 let hir::ItemKind::Impl(&hir::Impl { items, .. }) = item.kind else {
73 bug!("expected `impl` item: {:?}", item);
76 if !self.tcx.has_attr(def_id, sym::rustc_has_incoherent_inherent_impls) {
81 "cannot define inherent `impl` for a type outside of the crate where the type is defined",
83 .help(INTO_DEFINING_CRATE)
84 .span_help(item.span, ADD_ATTR_TO_TY)
89 for impl_item in items {
92 .has_attr(impl_item.id.def_id.to_def_id(), sym::rustc_allow_incoherent_impl)
98 "cannot define inherent `impl` for a type outside of the crate where the type is defined",
100 .help(INTO_DEFINING_CRATE)
101 .span_help(impl_item.span, ADD_ATTR)
107 if let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::AsInfer) {
108 self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
110 bug!("unexpected self type: {:?}", self_ty);
117 "cannot define inherent `impl` for a type outside of the crate \
118 where the type is defined"
120 .span_label(item.span, "impl for type defined outside of crate.")
121 .note("define and implement a trait or new type instead")
126 fn check_primitive_impl(
128 impl_def_id: LocalDefId,
130 items: &[hir::ImplItemRef],
133 if !self.tcx.hir().rustc_coherence_is_core() {
134 if self.tcx.features().rustc_attrs {
138 .has_attr(item.id.def_id.to_def_id(), sym::rustc_allow_incoherent_impl)
144 "cannot define inherent `impl` for primitive types outside of `core`",
147 .span_help(item.span, ADD_ATTR)
153 let mut err = struct_span_err!(
157 "cannot define inherent `impl` for primitive types",
159 err.help("consider using an extension trait instead");
160 if let ty::Ref(_, subty, _) = ty.kind() {
162 "you could also try moving the reference to \
163 uses of `{}` (such as `self`) within the implementation",
172 if let Some(simp) = simplify_type(self.tcx, ty, TreatParams::AsInfer) {
173 self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
175 bug!("unexpected primitive type: {:?}", ty);
179 fn check_item(&mut self, id: hir::ItemId) {
180 if !matches!(self.tcx.def_kind(id.def_id), DefKind::Impl) {
184 let item = self.tcx.hir().item(id);
185 let hir::ItemKind::Impl(hir::Impl { of_trait: None, self_ty: ty, ref items, .. }) = item.kind else {
189 let self_ty = self.tcx.type_of(item.def_id);
190 match *self_ty.kind() {
192 self.check_def_id(item, self_ty, def.did());
194 ty::Foreign(did) => {
195 self.check_def_id(item, self_ty, did);
197 ty::Dynamic(data, ..) if data.principal_def_id().is_some() => {
198 self.check_def_id(item, self_ty, data.principal_def_id().unwrap());
205 "cannot define inherent `impl` for a dyn auto trait"
207 .span_label(ty.span, "impl requires at least one non-auto trait")
208 .note("define and implement a new trait or type instead")
222 | ty::Tuple(..) => self.check_primitive_impl(item.def_id, self_ty, items, ty.span),
223 ty::FnPtr(_) | ty::Projection(..) | ty::Opaque(..) | ty::Param(_) => {
224 let mut err = struct_span_err!(
228 "no nominal type found for inherent implementation"
231 err.span_label(ty.span, "impl requires a nominal type")
232 .note("either implement a trait on it or create a newtype to wrap it instead");
239 | ty::GeneratorWitness(..)
243 bug!("unexpected impl self type of impl: {:?} {:?}", item.def_id, self_ty);