]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/coherence/mod.rs
b92916d9c81c19acf91b8541604c8d6512e6b090
[rust.git] / src / librustc_typeck / coherence / mod.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Coherence phase
12 //
13 // The job of the coherence phase of typechecking is to ensure that
14 // each trait has at most one implementation for each type. This is
15 // done by the orphan and overlap modules. Then we build up various
16 // mappings. That mapping code resides here.
17
18 use hir::def_id::{DefId, LOCAL_CRATE};
19 use rustc::traits;
20 use rustc::ty::{self, TyCtxt, TypeFoldable};
21 use rustc::ty::query::Providers;
22
23 use syntax::ast;
24
25 mod builtin;
26 mod inherent_impls;
27 mod inherent_impls_overlap;
28 mod orphan;
29 mod unsafety;
30
31 fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, node_id: ast::NodeId) {
32     let impl_def_id = tcx.hir().local_def_id(node_id);
33
34     // If there are no traits, then this implementation must have a
35     // base type.
36
37     if let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) {
38         debug!("(checking implementation) adding impl for trait '{:?}', item '{}'",
39                trait_ref,
40                tcx.item_path_str(impl_def_id));
41
42         // Skip impls where one of the self type is an error type.
43         // This occurs with e.g. resolve failures (#30589).
44         if trait_ref.references_error() {
45             return;
46         }
47
48         enforce_trait_manually_implementable(tcx, impl_def_id, trait_ref.def_id);
49         enforce_empty_impls_for_marker_traits(tcx, impl_def_id, trait_ref.def_id);
50     }
51 }
52
53 fn enforce_trait_manually_implementable(tcx: TyCtxt, impl_def_id: DefId, trait_def_id: DefId) {
54     let did = Some(trait_def_id);
55     let li = tcx.lang_items();
56     let span = tcx.sess.source_map().def_span(tcx.span_of_impl(impl_def_id).unwrap());
57
58     // Disallow *all* explicit impls of `Sized` and `Unsize` for now.
59     if did == li.sized_trait() {
60         struct_span_err!(tcx.sess,
61                          span,
62                          E0322,
63                          "explicit impls for the `Sized` trait are not permitted")
64             .span_label(span, "impl of 'Sized' not allowed")
65             .emit();
66         return;
67     }
68
69     if did == li.unsize_trait() {
70         struct_span_err!(tcx.sess,
71                          span,
72                          E0328,
73                          "explicit impls for the `Unsize` trait are not permitted")
74             .span_label(span, "impl of `Unsize` not allowed")
75             .emit();
76         return;
77     }
78
79     if tcx.features().unboxed_closures {
80         // the feature gate allows all Fn traits
81         return;
82     }
83
84     let trait_name = if did == li.fn_trait() {
85         "Fn"
86     } else if did == li.fn_mut_trait() {
87         "FnMut"
88     } else if did == li.fn_once_trait() {
89         "FnOnce"
90     } else {
91         return; // everything OK
92     };
93     struct_span_err!(tcx.sess,
94                      span,
95                      E0183,
96                      "manual implementations of `{}` are experimental",
97                      trait_name)
98         .span_label(span, format!("manual implementations of `{}` are experimental", trait_name))
99         .help("add `#![feature(unboxed_closures)]` to the crate attributes to enable")
100         .emit();
101 }
102
103 /// We allow impls of marker traits to overlap, so they can't override impls
104 /// as that could make it ambiguous which associated item to use.
105 fn enforce_empty_impls_for_marker_traits(tcx: TyCtxt, impl_def_id: DefId, trait_def_id: DefId) {
106     if !tcx.trait_def(trait_def_id).is_marker {
107         return;
108     }
109
110     if tcx.associated_item_def_ids(trait_def_id).is_empty() {
111         return;
112     }
113
114     let span = tcx.sess.source_map().def_span(tcx.span_of_impl(impl_def_id).unwrap());
115     struct_span_err!(tcx.sess,
116                      span,
117                      E0715,
118                      "impls for marker traits cannot contain items")
119         .emit();
120 }
121
122 pub fn provide(providers: &mut Providers) {
123     use self::builtin::coerce_unsized_info;
124     use self::inherent_impls::{crate_inherent_impls, inherent_impls};
125     use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
126
127     *providers = Providers {
128         coherent_trait,
129         crate_inherent_impls,
130         inherent_impls,
131         crate_inherent_impls_overlap_check,
132         coerce_unsized_info,
133         ..*providers
134     };
135 }
136
137 fn coherent_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
138     let impls = tcx.hir().trait_impls(def_id);
139     for &impl_id in impls {
140         check_impl(tcx, impl_id);
141     }
142     for &impl_id in impls {
143         check_impl_overlap(tcx, impl_id);
144     }
145     builtin::check_trait(tcx, def_id);
146 }
147
148 pub fn check_coherence<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
149     for &trait_def_id in tcx.hir().krate().trait_impls.keys() {
150         ty::query::queries::coherent_trait::ensure(tcx, trait_def_id);
151     }
152
153     unsafety::check(tcx);
154     orphan::check(tcx);
155
156     // these queries are executed for side-effects (error reporting):
157     ty::query::queries::crate_inherent_impls::ensure(tcx, LOCAL_CRATE);
158     ty::query::queries::crate_inherent_impls_overlap_check::ensure(tcx, LOCAL_CRATE);
159 }
160
161 /// Overlap: No two impls for the same trait are implemented for the
162 /// same type. Likewise, no two inherent impls for a given type
163 /// constructor provide a method with the same name.
164 fn check_impl_overlap<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, node_id: ast::NodeId) {
165     let impl_def_id = tcx.hir().local_def_id(node_id);
166     let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
167     let trait_def_id = trait_ref.def_id;
168
169     if trait_ref.references_error() {
170         debug!("coherence: skipping impl {:?} with error {:?}",
171                impl_def_id, trait_ref);
172         return
173     }
174
175     // Trigger building the specialization graph for the trait of this impl.
176     // This will detect any overlap errors.
177     tcx.specialization_graph_of(trait_def_id);
178
179     // check for overlap with the automatic `impl Trait for Trait`
180     if let ty::Dynamic(ref data, ..) = trait_ref.self_ty().sty {
181         // This is something like impl Trait1 for Trait2. Illegal
182         // if Trait1 is a supertrait of Trait2 or Trait2 is not object safe.
183
184         if !tcx.is_object_safe(data.principal().def_id()) {
185             // This is an error, but it will be reported by wfcheck.  Ignore it here.
186             // This is tested by `coherence-impl-trait-for-trait-object-safe.rs`.
187         } else {
188             let mut supertrait_def_ids =
189                 traits::supertrait_def_ids(tcx, data.principal().def_id());
190             if supertrait_def_ids.any(|d| d == trait_def_id) {
191                 let sp = tcx.sess.source_map().def_span(tcx.span_of_impl(impl_def_id).unwrap());
192                 struct_span_err!(tcx.sess,
193                                  sp,
194                                  E0371,
195                                  "the object type `{}` automatically implements the trait `{}`",
196                                  trait_ref.self_ty(),
197                                  tcx.item_path_str(trait_def_id))
198                     .span_label(sp, format!("`{}` automatically implements trait `{}`",
199                                             trait_ref.self_ty(),
200                                             tcx.item_path_str(trait_def_id)))
201                     .emit();
202             }
203         }
204     }
205 }