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