]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/coherence/mod.rs
Rollup merge of #85766 - workingjubilee:file-options, r=yaahc
[rust.git] / compiler / rustc_typeck / src / 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_errors::struct_span_err;
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_middle::ty::query::Providers;
11 use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
12 use rustc_span::Span;
13 use rustc_trait_selection::traits;
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: LocalDefId) -> Span {
23     tcx.sess.source_map().guess_head_span(tcx.span_of_impl(impl_def_id.to_def_id()).unwrap())
24 }
25
26 fn check_impl(tcx: TyCtxt<'_>, impl_def_id: LocalDefId, 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.to_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(
44     tcx: TyCtxt<'_>,
45     impl_def_id: LocalDefId,
46     trait_def_id: DefId,
47 ) {
48     let did = Some(trait_def_id);
49     let li = tcx.lang_items();
50
51     // Disallow *all* explicit impls of `Pointee`, `DiscriminantKind`, `Sized` and `Unsize` for now.
52     if did == li.pointee_trait() {
53         let span = impl_header_span(tcx, impl_def_id);
54         struct_span_err!(
55             tcx.sess,
56             span,
57             E0322,
58             "explicit impls for the `Pointee` trait are not permitted"
59         )
60         .span_label(span, "impl of 'Pointee' not allowed")
61         .emit();
62         return;
63     }
64
65     if did == li.discriminant_kind_trait() {
66         let span = impl_header_span(tcx, impl_def_id);
67         struct_span_err!(
68             tcx.sess,
69             span,
70             E0322,
71             "explicit impls for the `DiscriminantKind` trait are not permitted"
72         )
73         .span_label(span, "impl of 'DiscriminantKind' not allowed")
74         .emit();
75         return;
76     }
77
78     if did == li.sized_trait() {
79         let span = impl_header_span(tcx, impl_def_id);
80         struct_span_err!(
81             tcx.sess,
82             span,
83             E0322,
84             "explicit impls for the `Sized` trait are not permitted"
85         )
86         .span_label(span, "impl of 'Sized' not allowed")
87         .emit();
88         return;
89     }
90
91     if did == li.unsize_trait() {
92         let span = impl_header_span(tcx, impl_def_id);
93         struct_span_err!(
94             tcx.sess,
95             span,
96             E0328,
97             "explicit impls for the `Unsize` trait are not permitted"
98         )
99         .span_label(span, "impl of `Unsize` not allowed")
100         .emit();
101         return;
102     }
103
104     if tcx.features().unboxed_closures {
105         // the feature gate allows all Fn traits
106         return;
107     }
108
109     if let ty::trait_def::TraitSpecializationKind::AlwaysApplicable =
110         tcx.trait_def(trait_def_id).specialization_kind
111     {
112         if !tcx.features().specialization && !tcx.features().min_specialization {
113             let span = impl_header_span(tcx, impl_def_id);
114             tcx.sess
115                 .struct_span_err(
116                     span,
117                     "implementing `rustc_specialization_trait` traits is unstable",
118                 )
119                 .help("add `#![feature(min_specialization)]` to the crate attributes to enable")
120                 .emit();
121             return;
122         }
123     }
124
125     let trait_name = if did == li.fn_trait() {
126         "Fn"
127     } else if did == li.fn_mut_trait() {
128         "FnMut"
129     } else if did == li.fn_once_trait() {
130         "FnOnce"
131     } else {
132         return; // everything OK
133     };
134
135     let span = impl_header_span(tcx, impl_def_id);
136     struct_span_err!(
137         tcx.sess,
138         span,
139         E0183,
140         "manual implementations of `{}` are experimental",
141         trait_name
142     )
143     .span_label(span, format!("manual implementations of `{}` are experimental", trait_name))
144     .help("add `#![feature(unboxed_closures)]` to the crate attributes to enable")
145     .emit();
146 }
147
148 /// We allow impls of marker traits to overlap, so they can't override impls
149 /// as that could make it ambiguous which associated item to use.
150 fn enforce_empty_impls_for_marker_traits(
151     tcx: TyCtxt<'_>,
152     impl_def_id: LocalDefId,
153     trait_def_id: DefId,
154 ) {
155     if !tcx.trait_def(trait_def_id).is_marker {
156         return;
157     }
158
159     if tcx.associated_item_def_ids(trait_def_id).is_empty() {
160         return;
161     }
162
163     let span = impl_header_span(tcx, impl_def_id);
164     struct_span_err!(tcx.sess, span, E0715, "impls for marker traits cannot contain items").emit();
165 }
166
167 pub fn provide(providers: &mut Providers) {
168     use self::builtin::coerce_unsized_info;
169     use self::inherent_impls::{crate_inherent_impls, inherent_impls};
170     use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
171     use self::orphan::orphan_check_crate;
172
173     *providers = Providers {
174         coherent_trait,
175         crate_inherent_impls,
176         inherent_impls,
177         crate_inherent_impls_overlap_check,
178         coerce_unsized_info,
179         orphan_check_crate,
180         ..*providers
181     };
182 }
183
184 fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) {
185     // Trigger building the specialization graph for the trait. This will detect and report any
186     // overlap errors.
187     tcx.ensure().specialization_graph_of(def_id);
188
189     let impls = tcx.hir().trait_impls(def_id);
190     for &impl_def_id in impls {
191         let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
192
193         check_impl(tcx, impl_def_id, trait_ref);
194         check_object_overlap(tcx, impl_def_id, trait_ref);
195     }
196     builtin::check_trait(tcx, def_id);
197 }
198
199 pub fn check_coherence(tcx: TyCtxt<'_>) {
200     tcx.sess.time("unsafety_checking", || unsafety::check(tcx));
201     tcx.ensure().orphan_check_crate(());
202
203     for &trait_def_id in tcx.all_local_trait_impls(()).keys() {
204         tcx.ensure().coherent_trait(trait_def_id);
205     }
206
207     // these queries are executed for side-effects (error reporting):
208     tcx.ensure().crate_inherent_impls(());
209     tcx.ensure().crate_inherent_impls_overlap_check(());
210 }
211
212 /// Checks whether an impl overlaps with the automatic `impl Trait for dyn Trait`.
213 fn check_object_overlap<'tcx>(
214     tcx: TyCtxt<'tcx>,
215     impl_def_id: LocalDefId,
216     trait_ref: ty::TraitRef<'tcx>,
217 ) {
218     let trait_def_id = trait_ref.def_id;
219
220     if trait_ref.references_error() {
221         debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
222         return;
223     }
224
225     // check for overlap with the automatic `impl Trait for dyn Trait`
226     if let ty::Dynamic(data, ..) = trait_ref.self_ty().kind() {
227         // This is something like impl Trait1 for Trait2. Illegal
228         // if Trait1 is a supertrait of Trait2 or Trait2 is not object safe.
229
230         let component_def_ids = data.iter().flat_map(|predicate| {
231             match predicate.skip_binder() {
232                 ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
233                 ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
234                 // An associated type projection necessarily comes with
235                 // an additional `Trait` requirement.
236                 ty::ExistentialPredicate::Projection(..) => None,
237             }
238         });
239
240         for component_def_id in component_def_ids {
241             if !tcx.is_object_safe(component_def_id) {
242                 // Without the 'object_safe_for_dispatch' feature this is an error
243                 // which will be reported by wfcheck.  Ignore it here.
244                 // This is tested by `coherence-impl-trait-for-trait-object-safe.rs`.
245                 // With the feature enabled, the trait is not implemented automatically,
246                 // so this is valid.
247             } else {
248                 let mut supertrait_def_ids = traits::supertrait_def_ids(tcx, component_def_id);
249                 if supertrait_def_ids.any(|d| d == trait_def_id) {
250                     let span = impl_header_span(tcx, impl_def_id);
251                     struct_span_err!(
252                         tcx.sess,
253                         span,
254                         E0371,
255                         "the object type `{}` automatically implements the trait `{}`",
256                         trait_ref.self_ty(),
257                         tcx.def_path_str(trait_def_id)
258                     )
259                     .span_label(
260                         span,
261                         format!(
262                             "`{}` automatically implements trait `{}`",
263                             trait_ref.self_ty(),
264                             tcx.def_path_str(trait_def_id)
265                         ),
266                     )
267                     .emit();
268                 }
269             }
270         }
271     }
272 }