Skip to main content

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 !{
    {
            'done:
                {
                for i in self.tcx.get_all_attrs(ty_def_id) {
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AttributeKind::RustcHasIncoherentInherentImpls)
                            => {
                            break 'done Some(());
                        }
                        _ => {}
                    }
                }
                None
            }
        }.is_some()
}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 !{
    {
            'done:
                {
                for i in self.tcx.get_all_attrs(impl_item) {
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AttributeKind::RustcAllowIncoherentImpl(_))
                            => {
                            break 'done Some(());
                        }
                        _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(
93                    self.tcx.get_all_attrs(impl_item),
94                    AttributeKind::RustcAllowIncoherentImpl(_)
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                ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected self type: {0:?}",
        self_ty));bug!("unexpected self type: {:?}", self_ty);
109            }
110            Ok(())
111        } else {
112            let impl_span = self.tcx.def_span(impl_def_id);
113            let mut err = errors::InherentTyOutsideNew { span: impl_span, note: None };
114
115            if let hir::TyKind::Path(rustc_hir::QPath::Resolved(_, path)) =
116                self.tcx.hir_node_by_def_id(impl_def_id).expect_item().expect_impl().self_ty.kind
117                && let rustc_hir::def::Res::Def(DefKind::TyAlias, def_id) = path.res
118            {
119                let ty_name = self.tcx.def_path_str(def_id);
120                let alias_ty_name = self.tcx.type_of(def_id).skip_binder().to_string();
121                err.note = Some(errors::InherentTyOutsideNewAliasNote {
122                    span: self.tcx.def_span(def_id),
123                    ty_name,
124                    alias_ty_name,
125                });
126            }
127
128            Err(self.tcx.dcx().emit_err(err))
129        }
130    }
131
132    fn check_primitive_impl(
133        &mut self,
134        impl_def_id: LocalDefId,
135        ty: Ty<'tcx>,
136    ) -> Result<(), ErrorGuaranteed> {
137        let items = self.tcx.associated_item_def_ids(impl_def_id);
138        if !self.tcx.hir_rustc_coherence_is_core() {
139            if self.tcx.features().rustc_attrs() {
140                for &impl_item in items {
141                    if !{
    {
            'done:
                {
                for i in self.tcx.get_all_attrs(impl_item) {
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AttributeKind::RustcAllowIncoherentImpl(_))
                            => {
                            break 'done Some(());
                        }
                        _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(
142                        self.tcx.get_all_attrs(impl_item),
143                        AttributeKind::RustcAllowIncoherentImpl(_)
144                    ) {
145                        let span = self.tcx.def_span(impl_def_id);
146                        return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsidePrimitive {
147                            span,
148                            help_span: self.tcx.def_span(impl_item),
149                        }));
150                    }
151                }
152            } else {
153                let span = self.tcx.def_span(impl_def_id);
154                let mut note = None;
155                if let ty::Ref(_, subty, _) = ty.kind() {
156                    note = Some(errors::InherentPrimitiveTyNote { subty: *subty });
157                }
158                return Err(self.tcx.dcx().emit_err(errors::InherentPrimitiveTy { span, note }));
159            }
160        }
161
162        if let Some(simp) = simplify_type(self.tcx, ty, TreatParams::InstantiateWithInfer) {
163            self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id);
164        } else {
165            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected primitive type: {0:?}",
        ty));bug!("unexpected primitive type: {:?}", ty);
166        }
167        Ok(())
168    }
169
170    fn check_item(&mut self, id: hir::ItemId) -> Result<(), ErrorGuaranteed> {
171        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 }) {
172            return Ok(());
173        }
174
175        let id = id.owner_id.def_id;
176        let item_span = self.tcx.def_span(id);
177        let self_ty = self.tcx.type_of(id).instantiate_identity();
178        let mut self_ty = self.tcx.peel_off_free_alias_tys(self_ty);
179        // We allow impls on pattern types exactly when we allow impls on the base type.
180        // FIXME(pattern_types): Figure out the exact coherence rules we want here.
181        while let ty::Pat(base, _) = *self_ty.kind() {
182            self_ty = base;
183        }
184        match *self_ty.kind() {
185            ty::Adt(def, _) => self.check_def_id(id, self_ty, def.did()),
186            ty::Foreign(did) => self.check_def_id(id, self_ty, did),
187            ty::Dynamic(data, ..) if data.principal_def_id().is_some() => {
188                self.check_def_id(id, self_ty, data.principal_def_id().unwrap())
189            }
190            ty::Dynamic(..) => {
191                Err(self.tcx.dcx().emit_err(errors::InherentDyn { span: item_span }))
192            }
193            ty::Pat(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
194            ty::Bool
195            | ty::Char
196            | ty::Int(_)
197            | ty::Uint(_)
198            | ty::Float(_)
199            | ty::Str
200            | ty::Array(..)
201            | ty::Slice(_)
202            | ty::RawPtr(_, _)
203            | ty::Ref(..)
204            | ty::Never
205            | ty::FnPtr(..)
206            | ty::Tuple(..)
207            | ty::UnsafeBinder(_) => self.check_primitive_impl(id, self_ty),
208            ty::Alias(ty::Projection | ty::Inherent | ty::Opaque, _) | ty::Param(_) => {
209                Err(self.tcx.dcx().emit_err(errors::InherentNominal { span: item_span }))
210            }
211            ty::FnDef(..)
212            | ty::Closure(..)
213            | ty::CoroutineClosure(..)
214            | ty::Coroutine(..)
215            | ty::CoroutineWitness(..)
216            | ty::Alias(ty::Free, _)
217            | ty::Bound(..)
218            | ty::Placeholder(_)
219            | ty::Infer(_) => {
220                ::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);
221            }
222            // We could bail out here, but that will silence other useful errors.
223            ty::Error(_) => Ok(()),
224        }
225    }
226}