]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/coherence/mod.rs
8adf4bb94a898c66d88f63157e6a206f55122f0f
[rust.git] / src / librustc_typeck / coherence / mod.rs
1 // Coherence phase
2 //
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.
7
8 use crate::hir::HirId;
9 use crate::hir::def_id::{DefId, LOCAL_CRATE};
10 use rustc::traits;
11 use rustc::ty::{self, TyCtxt, TypeFoldable};
12 use rustc::ty::query::Providers;
13 use rustc::util::common::time;
14
15 mod builtin;
16 mod inherent_impls;
17 mod inherent_impls_overlap;
18 mod orphan;
19 mod unsafety;
20
21 fn check_impl(tcx: TyCtxt<'_>, hir_id: HirId) {
22     let impl_def_id = tcx.hir().local_def_id(hir_id);
23
24     // If there are no traits, then this implementation must have a
25     // base type.
26
27     if let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) {
28         debug!("(checking implementation) adding impl for trait '{:?}', item '{}'",
29                trait_ref,
30                tcx.def_path_str(impl_def_id));
31
32         // Skip impls where one of the self type is an error type.
33         // This occurs with e.g., resolve failures (#30589).
34         if trait_ref.references_error() {
35             return;
36         }
37
38         enforce_trait_manually_implementable(tcx, impl_def_id, trait_ref.def_id);
39         enforce_empty_impls_for_marker_traits(tcx, impl_def_id, trait_ref.def_id);
40     }
41 }
42
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();
46     let span = tcx.sess.source_map().def_span(tcx.span_of_impl(impl_def_id).unwrap());
47
48     // Disallow *all* explicit impls of `Sized` and `Unsize` for now.
49     if did == li.sized_trait() {
50         struct_span_err!(tcx.sess,
51                          span,
52                          E0322,
53                          "explicit impls for the `Sized` trait are not permitted")
54             .span_label(span, "impl of 'Sized' not allowed")
55             .emit();
56         return;
57     }
58
59     if did == li.unsize_trait() {
60         struct_span_err!(tcx.sess,
61                          span,
62                          E0328,
63                          "explicit impls for the `Unsize` trait are not permitted")
64             .span_label(span, "impl of `Unsize` not allowed")
65             .emit();
66         return;
67     }
68
69     if tcx.features().unboxed_closures {
70         // the feature gate allows all Fn traits
71         return;
72     }
73
74     let trait_name = if did == li.fn_trait() {
75         "Fn"
76     } else if did == li.fn_mut_trait() {
77         "FnMut"
78     } else if did == li.fn_once_trait() {
79         "FnOnce"
80     } else {
81         return; // everything OK
82     };
83     struct_span_err!(tcx.sess,
84                      span,
85                      E0183,
86                      "manual implementations of `{}` are experimental",
87                      trait_name)
88         .span_label(span, format!("manual implementations of `{}` are experimental", trait_name))
89         .help("add `#![feature(unboxed_closures)]` to the crate attributes to enable")
90         .emit();
91 }
92
93 /// We allow impls of marker traits to overlap, so they can't override impls
94 /// as that could make it ambiguous which associated item to use.
95 fn enforce_empty_impls_for_marker_traits(tcx: TyCtxt<'_>, impl_def_id: DefId, trait_def_id: DefId) {
96     if !tcx.trait_def(trait_def_id).is_marker {
97         return;
98     }
99
100     if tcx.associated_item_def_ids(trait_def_id).is_empty() {
101         return;
102     }
103
104     let span = tcx.sess.source_map().def_span(tcx.span_of_impl(impl_def_id).unwrap());
105     struct_span_err!(tcx.sess,
106                      span,
107                      E0715,
108                      "impls for marker traits cannot contain items")
109         .emit();
110 }
111
112 pub fn provide(providers: &mut Providers<'_>) {
113     use self::builtin::coerce_unsized_info;
114     use self::inherent_impls::{crate_inherent_impls, inherent_impls};
115     use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
116
117     *providers = Providers {
118         coherent_trait,
119         crate_inherent_impls,
120         inherent_impls,
121         crate_inherent_impls_overlap_check,
122         coerce_unsized_info,
123         ..*providers
124     };
125 }
126
127 fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) {
128     let impls = tcx.hir().trait_impls(def_id);
129     for &impl_id in impls {
130         check_impl(tcx, impl_id);
131     }
132     for &impl_id in impls {
133         check_impl_overlap(tcx, impl_id);
134     }
135     builtin::check_trait(tcx, def_id);
136 }
137
138 pub fn check_coherence(tcx: TyCtxt<'_>) {
139     for &trait_def_id in tcx.hir().krate().trait_impls.keys() {
140         tcx.ensure().coherent_trait(trait_def_id);
141     }
142
143     time(tcx.sess, "unsafety checking", || unsafety::check(tcx));
144     time(tcx.sess, "orphan checking", || orphan::check(tcx));
145
146     // these queries are executed for side-effects (error reporting):
147     tcx.ensure().crate_inherent_impls(LOCAL_CRATE);
148     tcx.ensure().crate_inherent_impls_overlap_check(LOCAL_CRATE);
149 }
150
151 /// Overlap: no two impls for the same trait are implemented for the
152 /// same type. Likewise, no two inherent impls for a given type
153 /// constructor provide a method with the same name.
154 fn check_impl_overlap<'tcx>(tcx: TyCtxt<'tcx>, hir_id: HirId) {
155     let impl_def_id = tcx.hir().local_def_id(hir_id);
156     let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
157     let trait_def_id = trait_ref.def_id;
158
159     if trait_ref.references_error() {
160         debug!("coherence: skipping impl {:?} with error {:?}",
161                impl_def_id, trait_ref);
162         return
163     }
164
165     // Trigger building the specialization graph for the trait of this impl.
166     // This will detect any overlap errors.
167     tcx.specialization_graph_of(trait_def_id);
168
169     // check for overlap with the automatic `impl Trait for Trait`
170     if let ty::Dynamic(ref data, ..) = trait_ref.self_ty().kind {
171         // This is something like impl Trait1 for Trait2. Illegal
172         // if Trait1 is a supertrait of Trait2 or Trait2 is not object safe.
173
174         let component_def_ids = data.iter().flat_map(|predicate| {
175             match predicate.skip_binder() {
176                 ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
177                 ty::ExistentialPredicate::AutoTrait(def_id) => Some(*def_id),
178                 // An associated type projection necessarily comes with
179                 // an additional `Trait` requirement.
180                 ty::ExistentialPredicate::Projection(..) => None,
181             }
182         });
183
184         for component_def_id in component_def_ids {
185             if !tcx.is_object_safe(component_def_id) {
186                 // Without the 'object_safe_for_dispatch' feature this is an error
187                 // which will be reported by wfcheck.  Ignore it here.
188                 // This is tested by `coherence-impl-trait-for-trait-object-safe.rs`.
189                 // With the feature enabled, the trait is not implemented automatically,
190                 // so this is valid.
191             } else {
192                 let mut supertrait_def_ids =
193                     traits::supertrait_def_ids(tcx, component_def_id);
194                 if supertrait_def_ids.any(|d| d == trait_def_id) {
195                     let sp = tcx.sess.source_map().def_span(tcx.span_of_impl(impl_def_id).unwrap());
196                     struct_span_err!(tcx.sess,
197                                      sp,
198                                      E0371,
199                                      "the object type `{}` automatically implements the trait `{}`",
200                                      trait_ref.self_ty(),
201                                      tcx.def_path_str(trait_def_id))
202                         .span_label(sp, format!("`{}` automatically implements trait `{}`",
203                                                 trait_ref.self_ty(),
204                                                 tcx.def_path_str(trait_def_id)))
205                         .emit();
206                 }
207             }
208         }
209     }
210 }