rustc_hir_analysis/coherence/
inherent_impls.rs

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.
9
10use rustc_hir as hir;
11use rustc_hir::def::DefKind;
12use rustc_hir::def_id::{DefId, LocalDefId};
13use rustc_middle::bug;
14use rustc_middle::ty::fast_reject::{SimplifiedType, TreatParams, simplify_type};
15use rustc_middle::ty::{self, CrateInherentImpls, Ty, TyCtxt};
16use rustc_span::{ErrorGuaranteed, sym};
17
18use crate::errors;
19
20/// On-demand query: yields a map containing all types mapped to their inherent impls.
21pub(crate) fn crate_inherent_impls(
22    tcx: TyCtxt<'_>,
23    (): (),
24) -> (&'_ CrateInherentImpls, Result<(), ErrorGuaranteed>) {
25    let mut collect = InherentCollect { tcx, impls_map: Default::default() };
26
27    let mut res = Ok(());
28    for id in tcx.hir().items() {
29        res = res.and(collect.check_item(id));
30    }
31
32    (tcx.arena.alloc(collect.impls_map), res)
33}
34
35pub(crate) fn crate_inherent_impls_validity_check(
36    tcx: TyCtxt<'_>,
37    (): (),
38) -> Result<(), ErrorGuaranteed> {
39    tcx.crate_inherent_impls(()).1
40}
41
42pub(crate) fn crate_incoherent_impls(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] {
43    let (crate_map, _) = tcx.crate_inherent_impls(());
44    tcx.arena.alloc_from_iter(
45        crate_map.incoherent_impls.get(&simp).unwrap_or(&Vec::new()).iter().map(|d| d.to_def_id()),
46    )
47}
48
49/// On-demand query: yields a vector of the inherent impls for a specific type.
50pub(crate) fn inherent_impls(tcx: TyCtxt<'_>, ty_def_id: LocalDefId) -> &[DefId] {
51    let (crate_map, _) = tcx.crate_inherent_impls(());
52    match crate_map.inherent_impls.get(&ty_def_id) {
53        Some(v) => &v[..],
54        None => &[],
55    }
56}
57
58struct InherentCollect<'tcx> {
59    tcx: TyCtxt<'tcx>,
60    impls_map: CrateInherentImpls,
61}
62
63impl<'tcx> InherentCollect<'tcx> {
64    fn check_def_id(
65        &mut self,
66        impl_def_id: LocalDefId,
67        self_ty: Ty<'tcx>,
68        ty_def_id: DefId,
69    ) -> Result<(), ErrorGuaranteed> {
70        if let Some(ty_def_id) = ty_def_id.as_local() {
71            // Add the implementation to the mapping from implementation to base
72            // type def ID, if there is a base type for this implementation and
73            // the implementation does not have any associated traits.
74            let vec = self.impls_map.inherent_impls.entry(ty_def_id).or_default();
75            vec.push(impl_def_id.to_def_id());
76            return Ok(());
77        }
78
79        if self.tcx.features().rustc_attrs() {
80            let items = self.tcx.associated_item_def_ids(impl_def_id);
81
82            if !self.tcx.has_attr(ty_def_id, sym::rustc_has_incoherent_inherent_impls) {
83                let impl_span = self.tcx.def_span(impl_def_id);
84                return Err(self.tcx.dcx().emit_err(errors::InherentTyOutside { span: impl_span }));
85            }
86
87            for &impl_item in items {
88                if !self.tcx.has_attr(impl_item, sym::rustc_allow_incoherent_impl) {
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                bug!("unexpected self type: {:?}", self_ty);
102            }
103            Ok(())
104        } else {
105            let impl_span = self.tcx.def_span(impl_def_id);
106            Err(self.tcx.dcx().emit_err(errors::InherentTyOutsideNew { span: impl_span }))
107        }
108    }
109
110    fn check_primitive_impl(
111        &mut self,
112        impl_def_id: LocalDefId,
113        ty: Ty<'tcx>,
114    ) -> Result<(), ErrorGuaranteed> {
115        let items = self.tcx.associated_item_def_ids(impl_def_id);
116        if !self.tcx.hir().rustc_coherence_is_core() {
117            if self.tcx.features().rustc_attrs() {
118                for &impl_item in items {
119                    if !self.tcx.has_attr(impl_item, sym::rustc_allow_incoherent_impl) {
120                        let span = self.tcx.def_span(impl_def_id);
121                        return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsidePrimitive {
122                            span,
123                            help_span: self.tcx.def_span(impl_item),
124                        }));
125                    }
126                }
127            } else {
128                let span = self.tcx.def_span(impl_def_id);
129                let mut note = None;
130                if let ty::Ref(_, subty, _) = ty.kind() {
131                    note = Some(errors::InherentPrimitiveTyNote { subty: *subty });
132                }
133                return Err(self.tcx.dcx().emit_err(errors::InherentPrimitiveTy { span, note }));
134            }
135        }
136
137        if let Some(simp) = simplify_type(self.tcx, ty, TreatParams::InstantiateWithInfer) {
138            self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
139        } else {
140            bug!("unexpected primitive type: {:?}", ty);
141        }
142        Ok(())
143    }
144
145    fn check_item(&mut self, id: hir::ItemId) -> Result<(), ErrorGuaranteed> {
146        if !matches!(self.tcx.def_kind(id.owner_id), DefKind::Impl { of_trait: false }) {
147            return Ok(());
148        }
149
150        let id = id.owner_id.def_id;
151        let item_span = self.tcx.def_span(id);
152        let self_ty = self.tcx.type_of(id).instantiate_identity();
153        let mut self_ty = self.tcx.peel_off_weak_alias_tys(self_ty);
154        // We allow impls on pattern types exactly when we allow impls on the base type.
155        // FIXME(pattern_types): Figure out the exact coherence rules we want here.
156        while let ty::Pat(base, _) = *self_ty.kind() {
157            self_ty = base;
158        }
159        match *self_ty.kind() {
160            ty::Adt(def, _) => self.check_def_id(id, self_ty, def.did()),
161            ty::Foreign(did) => self.check_def_id(id, self_ty, did),
162            ty::Dynamic(data, ..) if data.principal_def_id().is_some() => {
163                self.check_def_id(id, self_ty, data.principal_def_id().unwrap())
164            }
165            ty::Dynamic(..) => {
166                Err(self.tcx.dcx().emit_err(errors::InherentDyn { span: item_span }))
167            }
168            ty::Pat(_, _) => unreachable!(),
169            ty::Bool
170            | ty::Char
171            | ty::Int(_)
172            | ty::Uint(_)
173            | ty::Float(_)
174            | ty::Str
175            | ty::Array(..)
176            | ty::Slice(_)
177            | ty::RawPtr(_, _)
178            | ty::Ref(..)
179            | ty::Never
180            | ty::FnPtr(..)
181            | ty::Tuple(..)
182            | ty::UnsafeBinder(_) => self.check_primitive_impl(id, self_ty),
183            ty::Alias(ty::Projection | ty::Inherent | ty::Opaque, _) | ty::Param(_) => {
184                Err(self.tcx.dcx().emit_err(errors::InherentNominal { span: item_span }))
185            }
186            ty::FnDef(..)
187            | ty::Closure(..)
188            | ty::CoroutineClosure(..)
189            | ty::Coroutine(..)
190            | ty::CoroutineWitness(..)
191            | ty::Alias(ty::Weak, _)
192            | ty::Bound(..)
193            | ty::Placeholder(_)
194            | ty::Infer(_) => {
195                bug!("unexpected impl self type of impl: {:?} {:?}", id, self_ty);
196            }
197            // We could bail out here, but that will silence other useful errors.
198            ty::Error(_) => Ok(()),
199        }
200    }
201}