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