rustc_hir_analysis/coherence/
mod.rs1use rustc_errors::codes::*;
9use rustc_errors::struct_span_code_err;
10use rustc_hir::LangItem;
11use rustc_hir::def_id::{DefId, LocalDefId};
12use rustc_middle::query::Providers;
13use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt, elaborate};
14use rustc_session::parse::feature_err;
15use rustc_span::{ErrorGuaranteed, sym};
16use tracing::debug;
17
18use crate::check::always_applicable;
19use crate::errors;
20
21mod builtin;
22mod inherent_impls;
23mod inherent_impls_overlap;
24mod orphan;
25mod unsafety;
26
27fn check_impl<'tcx>(
28 tcx: TyCtxt<'tcx>,
29 impl_def_id: LocalDefId,
30 trait_ref: ty::TraitRef<'tcx>,
31 trait_def: &'tcx ty::TraitDef,
32 polarity: ty::ImplPolarity,
33) -> Result<(), ErrorGuaranteed> {
34 debug!(
35 "(checking implementation) adding impl for trait '{:?}', item '{}'",
36 trait_ref,
37 tcx.def_path_str(impl_def_id)
38 );
39
40 if trait_ref.references_error() {
43 return Ok(());
44 }
45
46 enforce_trait_manually_implementable(tcx, impl_def_id, trait_ref.def_id, trait_def)
47 .and(enforce_empty_impls_for_marker_traits(tcx, impl_def_id, trait_ref.def_id, trait_def))
48 .and(always_applicable::check_negative_auto_trait_impl(
49 tcx,
50 impl_def_id,
51 trait_ref,
52 polarity,
53 ))
54}
55
56fn enforce_trait_manually_implementable(
57 tcx: TyCtxt<'_>,
58 impl_def_id: LocalDefId,
59 trait_def_id: DefId,
60 trait_def: &ty::TraitDef,
61) -> Result<(), ErrorGuaranteed> {
62 let impl_header_span = tcx.def_span(impl_def_id);
63
64 if tcx.is_lang_item(trait_def_id, LangItem::Freeze) && !tcx.features().freeze_impls() {
65 feature_err(
66 &tcx.sess,
67 sym::freeze_impls,
68 impl_header_span,
69 "explicit impls for the `Freeze` trait are not permitted",
70 )
71 .with_span_label(impl_header_span, format!("impl of `Freeze` not allowed"))
72 .emit();
73 }
74
75 if trait_def.deny_explicit_impl {
77 let trait_name = tcx.item_name(trait_def_id);
78 let mut err = struct_span_code_err!(
79 tcx.dcx(),
80 impl_header_span,
81 E0322,
82 "explicit impls for the `{trait_name}` trait are not permitted"
83 );
84 err.span_label(impl_header_span, format!("impl of `{trait_name}` not allowed"));
85
86 if tcx.is_lang_item(trait_def_id, LangItem::Unsize) {
89 err.code(E0328);
90 }
91
92 return Err(err.emit());
93 }
94
95 if let ty::trait_def::TraitSpecializationKind::AlwaysApplicable = trait_def.specialization_kind
96 {
97 if !tcx.features().specialization()
98 && !tcx.features().min_specialization()
99 && !impl_header_span.allows_unstable(sym::specialization)
100 && !impl_header_span.allows_unstable(sym::min_specialization)
101 {
102 return Err(tcx.dcx().emit_err(errors::SpecializationTrait { span: impl_header_span }));
103 }
104 }
105 Ok(())
106}
107
108fn enforce_empty_impls_for_marker_traits(
111 tcx: TyCtxt<'_>,
112 impl_def_id: LocalDefId,
113 trait_def_id: DefId,
114 trait_def: &ty::TraitDef,
115) -> Result<(), ErrorGuaranteed> {
116 if !trait_def.is_marker {
117 return Ok(());
118 }
119
120 if tcx.associated_item_def_ids(trait_def_id).is_empty() {
121 return Ok(());
122 }
123
124 Err(struct_span_code_err!(
125 tcx.dcx(),
126 tcx.def_span(impl_def_id),
127 E0715,
128 "impls for marker traits cannot contain items"
129 )
130 .emit())
131}
132
133pub(crate) fn provide(providers: &mut Providers) {
134 use self::builtin::coerce_unsized_info;
135 use self::inherent_impls::{
136 crate_incoherent_impls, crate_inherent_impls, crate_inherent_impls_validity_check,
137 inherent_impls,
138 };
139 use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
140 use self::orphan::orphan_check_impl;
141
142 *providers = Providers {
143 coherent_trait,
144 crate_inherent_impls,
145 crate_incoherent_impls,
146 inherent_impls,
147 crate_inherent_impls_validity_check,
148 crate_inherent_impls_overlap_check,
149 coerce_unsized_info,
150 orphan_check_impl,
151 ..*providers
152 };
153}
154
155fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) -> Result<(), ErrorGuaranteed> {
156 let impls = tcx.local_trait_impls(def_id);
157 if impls.is_empty() {
160 return Ok(());
161 }
162 let mut res = tcx.ensure_ok().specialization_graph_of(def_id);
165
166 for &impl_def_id in impls {
167 let impl_header = tcx.impl_trait_header(impl_def_id).unwrap();
168 let trait_ref = impl_header.trait_ref.instantiate_identity();
169 let trait_def = tcx.trait_def(trait_ref.def_id);
170
171 res = res
172 .and(check_impl(tcx, impl_def_id, trait_ref, trait_def, impl_header.polarity))
173 .and(check_object_overlap(tcx, impl_def_id, trait_ref))
174 .and(unsafety::check_item(tcx, impl_def_id, impl_header, trait_def))
175 .and(tcx.ensure_ok().orphan_check_impl(impl_def_id))
176 .and(builtin::check_trait(tcx, def_id, impl_def_id, impl_header));
177 }
178
179 res
180}
181
182fn check_object_overlap<'tcx>(
184 tcx: TyCtxt<'tcx>,
185 impl_def_id: LocalDefId,
186 trait_ref: ty::TraitRef<'tcx>,
187) -> Result<(), ErrorGuaranteed> {
188 let trait_def_id = trait_ref.def_id;
189
190 if trait_ref.references_error() {
191 debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
192 return Ok(());
193 }
194
195 if let ty::Dynamic(data, ..) = trait_ref.self_ty().kind() {
197 let component_def_ids = data.iter().flat_map(|predicate| {
201 match predicate.skip_binder() {
202 ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
203 ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
204 ty::ExistentialPredicate::Projection(..) => None,
207 }
208 });
209
210 for component_def_id in component_def_ids {
211 if !tcx.is_dyn_compatible(component_def_id) {
212 } else {
214 let mut supertrait_def_ids = elaborate::supertrait_def_ids(tcx, component_def_id);
215 if supertrait_def_ids
216 .any(|d| d == trait_def_id && tcx.trait_def(d).implement_via_object)
217 {
218 let span = tcx.def_span(impl_def_id);
219 return Err(struct_span_code_err!(
220 tcx.dcx(),
221 span,
222 E0371,
223 "the object type `{}` automatically implements the trait `{}`",
224 trait_ref.self_ty(),
225 tcx.def_path_str(trait_def_id)
226 )
227 .with_span_label(
228 span,
229 format!(
230 "`{}` automatically implements trait `{}`",
231 trait_ref.self_ty(),
232 tcx.def_path_str(trait_def_id)
233 ),
234 )
235 .emit());
236 }
237 }
238 }
239 }
240 Ok(())
241}