]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/coherence/mod.rs
Auto merge of #69260 - GuillaumeGomez:create-E0747-error-code, r=varkor,estebank
[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::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;
13 use rustc_span::Span;
14
15 mod builtin;
16 mod inherent_impls;
17 mod inherent_impls_overlap;
18 mod orphan;
19 mod unsafety;
20
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())
24 }
25
26 fn check_impl(tcx: TyCtxt<'_>, impl_def_id: DefId, trait_ref: ty::TraitRef<'_>) {
27     debug!(
28         "(checking implementation) adding impl for trait '{:?}', item '{}'",
29         trait_ref,
30         tcx.def_path_str(impl_def_id)
31     );
32
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() {
36         return;
37     }
38
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);
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
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);
50         struct_span_err!(
51             tcx.sess,
52             span,
53             E0322,
54             "explicit impls for the `Sized` trait are not permitted"
55         )
56         .span_label(span, "impl of 'Sized' not allowed")
57         .emit();
58         return;
59     }
60
61     if did == li.unsize_trait() {
62         let span = impl_header_span(tcx, impl_def_id);
63         struct_span_err!(
64             tcx.sess,
65             span,
66             E0328,
67             "explicit impls for the `Unsize` trait are not permitted"
68         )
69         .span_label(span, "impl of `Unsize` not allowed")
70         .emit();
71         return;
72     }
73
74     if tcx.features().unboxed_closures {
75         // the feature gate allows all Fn traits
76         return;
77     }
78
79     let trait_name = if did == li.fn_trait() {
80         "Fn"
81     } else if did == li.fn_mut_trait() {
82         "FnMut"
83     } else if did == li.fn_once_trait() {
84         "FnOnce"
85     } else {
86         return; // everything OK
87     };
88
89     let span = impl_header_span(tcx, impl_def_id);
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 = impl_header_span(tcx, impl_def_id);
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     // Trigger building the specialization graph for the trait. This will detect and report any
134     // overlap errors.
135     tcx.specialization_graph_of(def_id);
136
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();
141
142         check_impl(tcx, impl_def_id, trait_ref);
143         check_object_overlap(tcx, impl_def_id, trait_ref);
144     }
145     builtin::check_trait(tcx, def_id);
146 }
147
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);
151     }
152
153     tcx.sess.time("unsafety_checking", || unsafety::check(tcx));
154     tcx.sess.time("orphan_checking", || orphan::check(tcx));
155
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);
159 }
160
161 /// Checks whether an impl overlaps with the automatic `impl Trait for dyn Trait`.
162 fn check_object_overlap<'tcx>(
163     tcx: TyCtxt<'tcx>,
164     impl_def_id: DefId,
165     trait_ref: ty::TraitRef<'tcx>,
166 ) {
167     let trait_def_id = trait_ref.def_id;
168
169     if trait_ref.references_error() {
170         debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
171         return;
172     }
173
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.
178
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,
186             }
187         });
188
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,
195                 // so this is valid.
196             } else {
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);
200                     struct_span_err!(
201                         tcx.sess,
202                         span,
203                         E0371,
204                         "the object type `{}` automatically implements the trait `{}`",
205                         trait_ref.self_ty(),
206                         tcx.def_path_str(trait_def_id)
207                     )
208                     .span_label(
209                         span,
210                         format!(
211                             "`{}` automatically implements trait `{}`",
212                             trait_ref.self_ty(),
213                             tcx.def_path_str(trait_def_id)
214                         ),
215                     )
216                     .emit();
217                 }
218             }
219         }
220     }
221 }