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