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::ty::query::Providers;
9 use rustc::ty::{self, TyCtxt, TypeFoldable};
10 use rustc_errors::struct_span_err;
11 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
12 use rustc_infer::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: DefId) -> Span {
23 tcx.sess.source_map().def_span(tcx.span_of_impl(impl_def_id).unwrap())
26 fn check_impl(tcx: TyCtxt<'_>, impl_def_id: DefId, trait_ref: ty::TraitRef<'_>) {
28 "(checking implementation) adding impl for trait '{:?}', item '{}'",
30 tcx.def_path_str(impl_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(tcx: TyCtxt<'_>, impl_def_id: DefId, trait_def_id: DefId) {
44 let did = Some(trait_def_id);
45 let li = tcx.lang_items();
47 // Disallow *all* explicit impls of `Sized` and `Unsize` for now.
48 if did == li.sized_trait() {
49 let span = impl_header_span(tcx, impl_def_id);
54 "explicit impls for the `Sized` trait are not permitted"
56 .span_label(span, "impl of 'Sized' not allowed")
61 if did == li.unsize_trait() {
62 let span = impl_header_span(tcx, impl_def_id);
67 "explicit impls for the `Unsize` trait are not permitted"
69 .span_label(span, "impl of `Unsize` not allowed")
74 if tcx.features().unboxed_closures {
75 // the feature gate allows all Fn traits
79 let trait_name = if did == li.fn_trait() {
81 } else if did == li.fn_mut_trait() {
83 } else if did == li.fn_once_trait() {
86 return; // everything OK
89 let span = impl_header_span(tcx, impl_def_id);
94 "manual implementations of `{}` are experimental",
97 .span_label(span, format!("manual implementations of `{}` are experimental", trait_name))
98 .help("add `#![feature(unboxed_closures)]` to the crate attributes to enable")
102 /// We allow impls of marker traits to overlap, so they can't override impls
103 /// as that could make it ambiguous which associated item to use.
104 fn enforce_empty_impls_for_marker_traits(tcx: TyCtxt<'_>, impl_def_id: DefId, trait_def_id: DefId) {
105 if !tcx.trait_def(trait_def_id).is_marker {
109 if tcx.associated_item_def_ids(trait_def_id).is_empty() {
113 let span = impl_header_span(tcx, impl_def_id);
114 struct_span_err!(tcx.sess, span, E0715, "impls for marker traits cannot contain items").emit();
117 pub fn provide(providers: &mut Providers<'_>) {
118 use self::builtin::coerce_unsized_info;
119 use self::inherent_impls::{crate_inherent_impls, inherent_impls};
120 use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
122 *providers = Providers {
124 crate_inherent_impls,
126 crate_inherent_impls_overlap_check,
132 fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) {
133 // Trigger building the specialization graph for the trait. This will detect and report any
135 tcx.specialization_graph_of(def_id);
137 let impls = tcx.hir().trait_impls(def_id);
138 for &hir_id in impls {
139 let impl_def_id = tcx.hir().local_def_id(hir_id);
140 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
142 check_impl(tcx, impl_def_id, trait_ref);
143 check_object_overlap(tcx, impl_def_id, trait_ref);
145 builtin::check_trait(tcx, def_id);
148 pub fn check_coherence(tcx: TyCtxt<'_>) {
149 for &trait_def_id in tcx.hir().krate().trait_impls.keys() {
150 tcx.ensure().coherent_trait(trait_def_id);
153 tcx.sess.time("unsafety_checking", || unsafety::check(tcx));
154 tcx.sess.time("orphan_checking", || orphan::check(tcx));
156 // these queries are executed for side-effects (error reporting):
157 tcx.ensure().crate_inherent_impls(LOCAL_CRATE);
158 tcx.ensure().crate_inherent_impls_overlap_check(LOCAL_CRATE);
161 /// Checks whether an impl overlaps with the automatic `impl Trait for dyn Trait`.
162 fn check_object_overlap<'tcx>(
165 trait_ref: ty::TraitRef<'tcx>,
167 let trait_def_id = trait_ref.def_id;
169 if trait_ref.references_error() {
170 debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
174 // check for overlap with the automatic `impl Trait for dyn Trait`
175 if let ty::Dynamic(ref data, ..) = trait_ref.self_ty().kind {
176 // This is something like impl Trait1 for Trait2. Illegal
177 // if Trait1 is a supertrait of Trait2 or Trait2 is not object safe.
179 let component_def_ids = data.iter().flat_map(|predicate| {
180 match predicate.skip_binder() {
181 ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
182 ty::ExistentialPredicate::AutoTrait(def_id) => Some(*def_id),
183 // An associated type projection necessarily comes with
184 // an additional `Trait` requirement.
185 ty::ExistentialPredicate::Projection(..) => None,
189 for component_def_id in component_def_ids {
190 if !tcx.is_object_safe(component_def_id) {
191 // Without the 'object_safe_for_dispatch' feature this is an error
192 // which will be reported by wfcheck. Ignore it here.
193 // This is tested by `coherence-impl-trait-for-trait-object-safe.rs`.
194 // With the feature enabled, the trait is not implemented automatically,
197 let mut supertrait_def_ids = traits::supertrait_def_ids(tcx, component_def_id);
198 if supertrait_def_ids.any(|d| d == trait_def_id) {
199 let span = impl_header_span(tcx, impl_def_id);
204 "the object type `{}` automatically implements the trait `{}`",
206 tcx.def_path_str(trait_def_id)
211 "`{}` automatically implements trait `{}`",
213 tcx.def_path_str(trait_def_id)