]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/coherence/mod.rs
Rollup merge of #97166 - nnethercote:move-conditions-out, r=estebank
[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
126 /// We allow impls of marker traits to overlap, so they can't override impls
127 /// as that could make it ambiguous which associated item to use.
128 fn enforce_empty_impls_for_marker_traits(
129     tcx: TyCtxt<'_>,
130     impl_def_id: LocalDefId,
131     trait_def_id: DefId,
132 ) {
133     if !tcx.trait_def(trait_def_id).is_marker {
134         return;
135     }
136
137     if tcx.associated_item_def_ids(trait_def_id).is_empty() {
138         return;
139     }
140
141     let span = impl_header_span(tcx, impl_def_id);
142     struct_span_err!(tcx.sess, span, E0715, "impls for marker traits cannot contain items").emit();
143 }
144
145 pub fn provide(providers: &mut Providers) {
146     use self::builtin::coerce_unsized_info;
147     use self::inherent_impls::{crate_incoherent_impls, crate_inherent_impls, inherent_impls};
148     use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
149     use self::orphan::orphan_check_crate;
150
151     *providers = Providers {
152         coherent_trait,
153         crate_inherent_impls,
154         crate_incoherent_impls,
155         inherent_impls,
156         crate_inherent_impls_overlap_check,
157         coerce_unsized_info,
158         orphan_check_crate,
159         ..*providers
160     };
161 }
162
163 fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) {
164     // Trigger building the specialization graph for the trait. This will detect and report any
165     // overlap errors.
166     tcx.ensure().specialization_graph_of(def_id);
167
168     let impls = tcx.hir().trait_impls(def_id);
169     for &impl_def_id in impls {
170         let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
171
172         check_impl(tcx, impl_def_id, trait_ref);
173         check_object_overlap(tcx, impl_def_id, trait_ref);
174     }
175     builtin::check_trait(tcx, def_id);
176 }
177
178 pub fn check_coherence(tcx: TyCtxt<'_>) {
179     tcx.sess.time("unsafety_checking", || unsafety::check(tcx));
180     tcx.ensure().orphan_check_crate(());
181
182     for &trait_def_id in tcx.all_local_trait_impls(()).keys() {
183         tcx.ensure().coherent_trait(trait_def_id);
184     }
185
186     // these queries are executed for side-effects (error reporting):
187     tcx.ensure().crate_inherent_impls(());
188     tcx.ensure().crate_inherent_impls_overlap_check(());
189 }
190
191 /// Checks whether an impl overlaps with the automatic `impl Trait for dyn Trait`.
192 fn check_object_overlap<'tcx>(
193     tcx: TyCtxt<'tcx>,
194     impl_def_id: LocalDefId,
195     trait_ref: ty::TraitRef<'tcx>,
196 ) {
197     let trait_def_id = trait_ref.def_id;
198
199     if trait_ref.references_error() {
200         debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
201         return;
202     }
203
204     // check for overlap with the automatic `impl Trait for dyn Trait`
205     if let ty::Dynamic(data, ..) = trait_ref.self_ty().kind() {
206         // This is something like impl Trait1 for Trait2. Illegal
207         // if Trait1 is a supertrait of Trait2 or Trait2 is not object safe.
208
209         let component_def_ids = data.iter().flat_map(|predicate| {
210             match predicate.skip_binder() {
211                 ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
212                 ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
213                 // An associated type projection necessarily comes with
214                 // an additional `Trait` requirement.
215                 ty::ExistentialPredicate::Projection(..) => None,
216             }
217         });
218
219         for component_def_id in component_def_ids {
220             if !tcx.is_object_safe(component_def_id) {
221                 // Without the 'object_safe_for_dispatch' feature this is an error
222                 // which will be reported by wfcheck.  Ignore it here.
223                 // This is tested by `coherence-impl-trait-for-trait-object-safe.rs`.
224                 // With the feature enabled, the trait is not implemented automatically,
225                 // so this is valid.
226             } else {
227                 let mut supertrait_def_ids = traits::supertrait_def_ids(tcx, component_def_id);
228                 if supertrait_def_ids.any(|d| d == trait_def_id) {
229                     let span = impl_header_span(tcx, impl_def_id);
230                     struct_span_err!(
231                         tcx.sess,
232                         span,
233                         E0371,
234                         "the object type `{}` automatically implements the trait `{}`",
235                         trait_ref.self_ty(),
236                         tcx.def_path_str(trait_def_id)
237                     )
238                     .span_label(
239                         span,
240                         format!(
241                             "`{}` automatically implements trait `{}`",
242                             trait_ref.self_ty(),
243                             tcx.def_path_str(trait_def_id)
244                         ),
245                     )
246                     .emit();
247                 }
248             }
249         }
250     }
251 }