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, sym};
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            let items = self.tcx.associated_item_def_ids(impl_def_id);
83
84            if !self.tcx.has_attr(ty_def_id, sym::rustc_has_incoherent_inherent_impls) {
85                let impl_span = self.tcx.def_span(impl_def_id);
86                return Err(self.tcx.dcx().emit_err(errors::InherentTyOutside { span: impl_span }));
87            }
88
89            for &impl_item in items {
90                if !find_attr!(
91                    self.tcx.get_all_attrs(impl_item),
92                    AttributeKind::AllowIncoherentImpl(_)
93                ) {
94                    let impl_span = self.tcx.def_span(impl_def_id);
95                    return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsideRelevant {
96                        span: impl_span,
97                        help_span: self.tcx.def_span(impl_item),
98                    }));
99                }
100            }
101
102            if let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::InstantiateWithInfer)
103            {
104                self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
105            } else {
106                bug!("unexpected self type: {:?}", self_ty);
107            }
108            Ok(())
109        } else {
110            let impl_span = self.tcx.def_span(impl_def_id);
111            Err(self.tcx.dcx().emit_err(errors::InherentTyOutsideNew { span: impl_span }))
112        }
113    }
114
115    fn check_primitive_impl(
116        &mut self,
117        impl_def_id: LocalDefId,
118        ty: Ty<'tcx>,
119    ) -> Result<(), ErrorGuaranteed> {
120        let items = self.tcx.associated_item_def_ids(impl_def_id);
121        if !self.tcx.hir_rustc_coherence_is_core() {
122            if self.tcx.features().rustc_attrs() {
123                for &impl_item in items {
124                    if !find_attr!(
125                        self.tcx.get_all_attrs(impl_item),
126                        AttributeKind::AllowIncoherentImpl(_)
127                    ) {
128                        let span = self.tcx.def_span(impl_def_id);
129                        return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsidePrimitive {
130                            span,
131                            help_span: self.tcx.def_span(impl_item),
132                        }));
133                    }
134                }
135            } else {
136                let span = self.tcx.def_span(impl_def_id);
137                let mut note = None;
138                if let ty::Ref(_, subty, _) = ty.kind() {
139                    note = Some(errors::InherentPrimitiveTyNote { subty: *subty });
140                }
141                return Err(self.tcx.dcx().emit_err(errors::InherentPrimitiveTy { span, note }));
142            }
143        }
144
145        if let Some(simp) = simplify_type(self.tcx, ty, TreatParams::InstantiateWithInfer) {
146            self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
147        } else {
148            bug!("unexpected primitive type: {:?}", ty);
149        }
150        Ok(())
151    }
152
153    fn check_item(&mut self, id: hir::ItemId) -> Result<(), ErrorGuaranteed> {
154        if !matches!(self.tcx.def_kind(id.owner_id), DefKind::Impl { of_trait: false }) {
155            return Ok(());
156        }
157
158        let id = id.owner_id.def_id;
159        let item_span = self.tcx.def_span(id);
160        let self_ty = self.tcx.type_of(id).instantiate_identity();
161        let mut self_ty = self.tcx.peel_off_free_alias_tys(self_ty);
162        // We allow impls on pattern types exactly when we allow impls on the base type.
163        // FIXME(pattern_types): Figure out the exact coherence rules we want here.
164        while let ty::Pat(base, _) = *self_ty.kind() {
165            self_ty = base;
166        }
167        match *self_ty.kind() {
168            ty::Adt(def, _) => self.check_def_id(id, self_ty, def.did()),
169            ty::Foreign(did) => self.check_def_id(id, self_ty, did),
170            ty::Dynamic(data, ..) if data.principal_def_id().is_some() => {
171                self.check_def_id(id, self_ty, data.principal_def_id().unwrap())
172            }
173            ty::Dynamic(..) => {
174                Err(self.tcx.dcx().emit_err(errors::InherentDyn { span: item_span }))
175            }
176            ty::Pat(_, _) => unreachable!(),
177            ty::Bool
178            | ty::Char
179            | ty::Int(_)
180            | ty::Uint(_)
181            | ty::Float(_)
182            | ty::Str
183            | ty::Array(..)
184            | ty::Slice(_)
185            | ty::RawPtr(_, _)
186            | ty::Ref(..)
187            | ty::Never
188            | ty::FnPtr(..)
189            | ty::Tuple(..)
190            | ty::UnsafeBinder(_) => self.check_primitive_impl(id, self_ty),
191            ty::Alias(ty::Projection | ty::Inherent | ty::Opaque, _) | ty::Param(_) => {
192                Err(self.tcx.dcx().emit_err(errors::InherentNominal { span: item_span }))
193            }
194            ty::FnDef(..)
195            | ty::Closure(..)
196            | ty::CoroutineClosure(..)
197            | ty::Coroutine(..)
198            | ty::CoroutineWitness(..)
199            | ty::Alias(ty::Free, _)
200            | ty::Bound(..)
201            | ty::Placeholder(_)
202            | ty::Infer(_) => {
203                bug!("unexpected impl self type of impl: {:?} {:?}", id, self_ty);
204            }
205            // We could bail out here, but that will silence other useful errors.
206            ty::Error(_) => Ok(()),
207        }
208    }
209}