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