3 // The job of the coherence phase of typechecking is to ensure that
4 // each trait has at most one implementation for each type. This is
5 // done by the orphan and overlap modules. Then we build up various
6 // mappings. That mapping code resides here.
8 use rustc_errors::struct_span_err;
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_middle::ty::query::Providers;
11 use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
13 use rustc_trait_selection::traits;
17 mod inherent_impls_overlap;
21 /// Obtains the span of just the impl header of `impl_def_id`.
22 fn impl_header_span(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) -> Span {
23 tcx.sess.source_map().guess_head_span(tcx.span_of_impl(impl_def_id.to_def_id()).unwrap())
26 fn check_impl(tcx: TyCtxt<'_>, impl_def_id: LocalDefId, trait_ref: ty::TraitRef<'_>) {
28 "(checking implementation) adding impl for trait '{:?}', item '{}'",
30 tcx.def_path_str(impl_def_id.to_def_id())
33 // Skip impls where one of the self type is an error type.
34 // This occurs with e.g., resolve failures (#30589).
35 if trait_ref.references_error() {
39 enforce_trait_manually_implementable(tcx, impl_def_id, trait_ref.def_id);
40 enforce_empty_impls_for_marker_traits(tcx, impl_def_id, trait_ref.def_id);
43 fn enforce_trait_manually_implementable(
45 impl_def_id: LocalDefId,
48 let did = Some(trait_def_id);
49 let li = tcx.lang_items();
51 // Disallow *all* explicit impls of `Pointee`, `DiscriminantKind`, `Sized` and `Unsize` for now.
52 if did == li.pointee_trait() {
53 let span = impl_header_span(tcx, impl_def_id);
58 "explicit impls for the `Pointee` trait are not permitted"
60 .span_label(span, "impl of 'Pointee' not allowed")
65 if did == li.discriminant_kind_trait() {
66 let span = impl_header_span(tcx, impl_def_id);
71 "explicit impls for the `DiscriminantKind` trait are not permitted"
73 .span_label(span, "impl of 'DiscriminantKind' not allowed")
78 if did == li.sized_trait() {
79 let span = impl_header_span(tcx, impl_def_id);
84 "explicit impls for the `Sized` trait are not permitted"
86 .span_label(span, "impl of 'Sized' not allowed")
91 if did == li.unsize_trait() {
92 let span = impl_header_span(tcx, impl_def_id);
97 "explicit impls for the `Unsize` trait are not permitted"
99 .span_label(span, "impl of `Unsize` not allowed")
104 if tcx.features().unboxed_closures {
105 // the feature gate allows all Fn traits
109 if let ty::trait_def::TraitSpecializationKind::AlwaysApplicable =
110 tcx.trait_def(trait_def_id).specialization_kind
112 if !tcx.features().specialization && !tcx.features().min_specialization {
113 let span = impl_header_span(tcx, impl_def_id);
117 "implementing `rustc_specialization_trait` traits is unstable",
119 .help("add `#![feature(min_specialization)]` to the crate attributes to enable")
126 /// We allow impls of marker traits to overlap, so they can't override impls
127 /// as that could make it ambiguous which associated item to use.
128 fn enforce_empty_impls_for_marker_traits(
130 impl_def_id: LocalDefId,
133 if !tcx.trait_def(trait_def_id).is_marker {
137 if tcx.associated_item_def_ids(trait_def_id).is_empty() {
141 let span = impl_header_span(tcx, impl_def_id);
142 struct_span_err!(tcx.sess, span, E0715, "impls for marker traits cannot contain items").emit();
145 pub fn provide(providers: &mut Providers) {
146 use self::builtin::coerce_unsized_info;
147 use self::inherent_impls::{crate_incoherent_impls, crate_inherent_impls, inherent_impls};
148 use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
149 use self::orphan::orphan_check_crate;
151 *providers = Providers {
153 crate_inherent_impls,
154 crate_incoherent_impls,
156 crate_inherent_impls_overlap_check,
163 fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) {
164 // Trigger building the specialization graph for the trait. This will detect and report any
166 tcx.ensure().specialization_graph_of(def_id);
168 let impls = tcx.hir().trait_impls(def_id);
169 for &impl_def_id in impls {
170 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
172 check_impl(tcx, impl_def_id, trait_ref);
173 check_object_overlap(tcx, impl_def_id, trait_ref);
175 builtin::check_trait(tcx, def_id);
178 pub fn check_coherence(tcx: TyCtxt<'_>) {
179 tcx.sess.time("unsafety_checking", || unsafety::check(tcx));
180 tcx.ensure().orphan_check_crate(());
182 for &trait_def_id in tcx.all_local_trait_impls(()).keys() {
183 tcx.ensure().coherent_trait(trait_def_id);
186 // these queries are executed for side-effects (error reporting):
187 tcx.ensure().crate_inherent_impls(());
188 tcx.ensure().crate_inherent_impls_overlap_check(());
191 /// Checks whether an impl overlaps with the automatic `impl Trait for dyn Trait`.
192 fn check_object_overlap<'tcx>(
194 impl_def_id: LocalDefId,
195 trait_ref: ty::TraitRef<'tcx>,
197 let trait_def_id = trait_ref.def_id;
199 if trait_ref.references_error() {
200 debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
204 // check for overlap with the automatic `impl Trait for dyn Trait`
205 if let ty::Dynamic(data, ..) = trait_ref.self_ty().kind() {
206 // This is something like impl Trait1 for Trait2. Illegal
207 // if Trait1 is a supertrait of Trait2 or Trait2 is not object safe.
209 let component_def_ids = data.iter().flat_map(|predicate| {
210 match predicate.skip_binder() {
211 ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
212 ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
213 // An associated type projection necessarily comes with
214 // an additional `Trait` requirement.
215 ty::ExistentialPredicate::Projection(..) => None,
219 for component_def_id in component_def_ids {
220 if !tcx.is_object_safe(component_def_id) {
221 // Without the 'object_safe_for_dispatch' feature this is an error
222 // which will be reported by wfcheck. Ignore it here.
223 // This is tested by `coherence-impl-trait-for-trait-object-safe.rs`.
224 // With the feature enabled, the trait is not implemented automatically,
227 let mut supertrait_def_ids = traits::supertrait_def_ids(tcx, component_def_id);
228 if supertrait_def_ids.any(|d| d == trait_def_id) {
229 let span = impl_header_span(tcx, impl_def_id);
234 "the object type `{}` automatically implements the trait `{}`",
236 tcx.def_path_str(trait_def_id)
241 "`{}` automatically implements trait `{}`",
243 tcx.def_path_str(trait_def_id)