]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/coherence/builtin.rs
3ec08f221f576e98b13f30d84bf0bcf00cf810d6
[rust.git] / src / librustc_typeck / coherence / builtin.rs
1 //! Check properties that are required by built-in traits and set
2 //! up data structures required by type-checking/codegen.
3
4 use rustc::infer::SuppressRegionErrors;
5 use rustc::infer::outlives::env::OutlivesEnvironment;
6 use rustc::middle::region;
7 use rustc::middle::lang_items::UnsizeTraitLangItem;
8
9 use rustc::traits::{self, TraitEngine, ObligationCause};
10 use rustc::ty::{self, Ty, TyCtxt};
11 use rustc::ty::TypeFoldable;
12 use rustc::ty::adjustment::CoerceUnsizedInfo;
13 use rustc::ty::util::CopyImplementationError;
14 use rustc::infer;
15
16 use rustc::hir::def_id::DefId;
17 use hir::Node;
18 use rustc::hir::{self, ItemKind};
19
20 pub fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_def_id: DefId) {
21     Checker { tcx, trait_def_id }
22         .check(tcx.lang_items().drop_trait(), visit_implementation_of_drop)
23         .check(tcx.lang_items().copy_trait(), visit_implementation_of_copy)
24         .check(tcx.lang_items().coerce_unsized_trait(), visit_implementation_of_coerce_unsized)
25         .check(tcx.lang_items().dispatch_from_dyn_trait(),
26             visit_implementation_of_dispatch_from_dyn);
27 }
28
29 struct Checker<'a, 'tcx: 'a> {
30     tcx: TyCtxt<'a, 'tcx, 'tcx>,
31     trait_def_id: DefId
32 }
33
34 impl<'a, 'tcx> Checker<'a, 'tcx> {
35     fn check<F>(&self, trait_def_id: Option<DefId>, mut f: F) -> &Self
36         where F: FnMut(TyCtxt<'a, 'tcx, 'tcx>, DefId)
37     {
38         if Some(self.trait_def_id) == trait_def_id {
39             for &impl_id in self.tcx.hir().trait_impls(self.trait_def_id) {
40                 let impl_def_id = self.tcx.hir().local_def_id(impl_id);
41                 f(self.tcx, impl_def_id);
42             }
43         }
44         self
45     }
46 }
47
48 fn visit_implementation_of_drop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_did: DefId) {
49     if let ty::Adt(..) = tcx.type_of(impl_did).sty {
50         /* do nothing */
51     } else {
52         // Destructors only work on nominal types.
53         if let Some(impl_node_id) = tcx.hir().as_local_node_id(impl_did) {
54             if let Some(Node::Item(item)) = tcx.hir().find(impl_node_id) {
55                 let span = match item.node {
56                     ItemKind::Impl(.., ref ty, _) => ty.span,
57                     _ => item.span,
58                 };
59                 struct_span_err!(tcx.sess,
60                                  span,
61                                  E0120,
62                                  "the Drop trait may only be implemented on \
63                                   structures")
64                     .span_label(span, "implementing Drop requires a struct")
65                     .emit();
66             } else {
67                 bug!("didn't find impl in ast map");
68             }
69         } else {
70             bug!("found external impl of Drop trait on \
71                   something other than a struct");
72         }
73     }
74 }
75
76 fn visit_implementation_of_copy<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_did: DefId) {
77     debug!("visit_implementation_of_copy: impl_did={:?}", impl_did);
78
79     let impl_hir_id = if let Some(n) = tcx.hir().as_local_hir_id(impl_did) {
80         n
81     } else {
82         debug!("visit_implementation_of_copy(): impl not in this crate");
83         return;
84     };
85
86     let self_type = tcx.type_of(impl_did);
87     debug!("visit_implementation_of_copy: self_type={:?} (bound)",
88            self_type);
89
90     let span = tcx.hir().span_by_hir_id(impl_hir_id);
91     let param_env = tcx.param_env(impl_did);
92     assert!(!self_type.has_escaping_bound_vars());
93
94     debug!("visit_implementation_of_copy: self_type={:?} (free)",
95            self_type);
96
97     match param_env.can_type_implement_copy(tcx, self_type) {
98         Ok(()) => {}
99         Err(CopyImplementationError::InfrigingFields(fields)) => {
100             let item = tcx.hir().expect_item_by_hir_id(impl_hir_id);
101             let span = if let ItemKind::Impl(.., Some(ref tr), _, _) = item.node {
102                 tr.path.span
103             } else {
104                 span
105             };
106
107             let mut err = struct_span_err!(tcx.sess,
108                                            span,
109                                            E0204,
110                                            "the trait `Copy` may not be implemented for this type");
111             for span in fields.iter().map(|f| tcx.def_span(f.did)) {
112                 err.span_label(span, "this field does not implement `Copy`");
113             }
114             err.emit()
115         }
116         Err(CopyImplementationError::NotAnAdt) => {
117             let item = tcx.hir().expect_item_by_hir_id(impl_hir_id);
118             let span = if let ItemKind::Impl(.., ref ty, _) = item.node {
119                 ty.span
120             } else {
121                 span
122             };
123
124             struct_span_err!(tcx.sess,
125                              span,
126                              E0206,
127                              "the trait `Copy` may not be implemented for this type")
128                 .span_label(span, "type is not a structure or enumeration")
129                 .emit();
130         }
131         Err(CopyImplementationError::HasDestructor) => {
132             struct_span_err!(tcx.sess,
133                              span,
134                              E0184,
135                              "the trait `Copy` may not be implemented for this type; the \
136                               type has a destructor")
137                 .span_label(span, "Copy not allowed on types with destructors")
138                 .emit();
139         }
140     }
141 }
142
143 fn visit_implementation_of_coerce_unsized<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_did: DefId) {
144     debug!("visit_implementation_of_coerce_unsized: impl_did={:?}",
145            impl_did);
146
147     // Just compute this for the side-effects, in particular reporting
148     // errors; other parts of the code may demand it for the info of
149     // course.
150     if impl_did.is_local() {
151         let span = tcx.def_span(impl_did);
152         tcx.at(span).coerce_unsized_info(impl_did);
153     }
154 }
155
156 fn visit_implementation_of_dispatch_from_dyn<'a, 'tcx>(
157     tcx: TyCtxt<'a, 'tcx, 'tcx>,
158     impl_did: DefId,
159 ) {
160     debug!("visit_implementation_of_dispatch_from_dyn: impl_did={:?}",
161            impl_did);
162     if impl_did.is_local() {
163         let dispatch_from_dyn_trait = tcx.lang_items().dispatch_from_dyn_trait().unwrap();
164
165         let impl_node_id = tcx.hir().as_local_node_id(impl_did).unwrap();
166         let span = tcx.hir().span(impl_node_id);
167
168         let source = tcx.type_of(impl_did);
169         assert!(!source.has_escaping_bound_vars());
170         let target = {
171             let trait_ref = tcx.impl_trait_ref(impl_did).unwrap();
172             assert_eq!(trait_ref.def_id, dispatch_from_dyn_trait);
173
174             trait_ref.substs.type_at(1)
175         };
176
177         debug!("visit_implementation_of_dispatch_from_dyn: {:?} -> {:?}",
178             source,
179             target);
180
181         let param_env = tcx.param_env(impl_did);
182
183         let create_err = |msg: &str| {
184             struct_span_err!(tcx.sess, span, E0378, "{}", msg)
185         };
186
187         tcx.infer_ctxt().enter(|infcx| {
188             let cause = ObligationCause::misc(span, impl_node_id);
189
190             use ty::TyKind::*;
191             match (&source.sty, &target.sty) {
192                 (&Ref(r_a, _, mutbl_a), Ref(r_b, _, mutbl_b))
193                     if infcx.at(&cause, param_env).eq(r_a, r_b).is_ok()
194                     && mutbl_a == *mutbl_b => (),
195                 (&RawPtr(tm_a), &RawPtr(tm_b))
196                     if tm_a.mutbl == tm_b.mutbl => (),
197                 (&Adt(def_a, substs_a), &Adt(def_b, substs_b))
198                     if def_a.is_struct() && def_b.is_struct() =>
199                 {
200                     if def_a != def_b {
201                         let source_path = tcx.item_path_str(def_a.did);
202                         let target_path = tcx.item_path_str(def_b.did);
203
204                         create_err(
205                             &format!(
206                                 "the trait `DispatchFromDyn` may only be implemented \
207                                 for a coercion between structures with the same \
208                                 definition; expected `{}`, found `{}`",
209                                 source_path, target_path,
210                             )
211                         ).emit();
212
213                         return
214                     }
215
216                     if def_a.repr.c() || def_a.repr.packed() {
217                         create_err(
218                             "structs implementing `DispatchFromDyn` may not have \
219                              `#[repr(packed)]` or `#[repr(C)]`"
220                         ).emit();
221                     }
222
223                     let fields = &def_a.non_enum_variant().fields;
224
225                     let coerced_fields = fields.iter().filter_map(|field| {
226                         if tcx.type_of(field.did).is_phantom_data() {
227                             // ignore PhantomData fields
228                             return None
229                         }
230
231                         let ty_a = field.ty(tcx, substs_a);
232                         let ty_b = field.ty(tcx, substs_b);
233                         if let Ok(ok) = infcx.at(&cause, param_env).eq(ty_a, ty_b) {
234                             if ok.obligations.is_empty() {
235                                 create_err(
236                                     "the trait `DispatchFromDyn` may only be implemented \
237                                      for structs containing the field being coerced, \
238                                      `PhantomData` fields, and nothing else"
239                                 ).note(
240                                     &format!(
241                                         "extra field `{}` of type `{}` is not allowed",
242                                         field.ident, ty_a,
243                                     )
244                                 ).emit();
245
246                                 return None;
247                             }
248                         }
249
250                         Some(field)
251                     }).collect::<Vec<_>>();
252
253                     if coerced_fields.is_empty() {
254                         create_err(
255                             "the trait `DispatchFromDyn` may only be implemented \
256                             for a coercion between structures with a single field \
257                             being coerced, none found"
258                         ).emit();
259                     } else if coerced_fields.len() > 1 {
260                         create_err(
261                             "implementing the `DispatchFromDyn` trait requires multiple coercions",
262                         ).note(
263                             "the trait `DispatchFromDyn` may only be implemented \
264                                 for a coercion between structures with a single field \
265                                 being coerced"
266                         ).note(
267                             &format!(
268                                 "currently, {} fields need coercions: {}",
269                                 coerced_fields.len(),
270                                 coerced_fields.iter().map(|field| {
271                                     format!("`{}` (`{}` to `{}`)",
272                                         field.ident,
273                                         field.ty(tcx, substs_a),
274                                         field.ty(tcx, substs_b),
275                                     )
276                                 }).collect::<Vec<_>>()
277                                 .join(", ")
278                             )
279                         ).emit();
280                     } else {
281                         let mut fulfill_cx = TraitEngine::new(infcx.tcx);
282
283                         for field in coerced_fields {
284
285                             let predicate = tcx.predicate_for_trait_def(
286                                 param_env,
287                                 cause.clone(),
288                                 dispatch_from_dyn_trait,
289                                 0,
290                                 field.ty(tcx, substs_a),
291                                 &[field.ty(tcx, substs_b).into()]
292                             );
293
294                             fulfill_cx.register_predicate_obligation(&infcx, predicate);
295                         }
296
297                         // Check that all transitive obligations are satisfied.
298                         if let Err(errors) = fulfill_cx.select_all_or_error(&infcx) {
299                             infcx.report_fulfillment_errors(&errors, None, false);
300                         }
301
302                         // Finally, resolve all regions.
303                         let region_scope_tree = region::ScopeTree::default();
304                         let outlives_env = OutlivesEnvironment::new(param_env);
305                         infcx.resolve_regions_and_report_errors(
306                             impl_did,
307                             &region_scope_tree,
308                             &outlives_env,
309                             SuppressRegionErrors::default(),
310                         );
311                     }
312                 }
313                 _ => {
314                     create_err(
315                         "the trait `DispatchFromDyn` may only be implemented \
316                         for a coercion between structures"
317                     ).emit();
318                 }
319             }
320         })
321     }
322 }
323
324 pub fn coerce_unsized_info<'a, 'gcx>(gcx: TyCtxt<'a, 'gcx, 'gcx>,
325                                      impl_did: DefId)
326                                      -> CoerceUnsizedInfo {
327     debug!("compute_coerce_unsized_info(impl_did={:?})", impl_did);
328     let coerce_unsized_trait = gcx.lang_items().coerce_unsized_trait().unwrap();
329
330     let unsize_trait = gcx.lang_items().require(UnsizeTraitLangItem).unwrap_or_else(|err| {
331         gcx.sess.fatal(&format!("`CoerceUnsized` implementation {}", err));
332     });
333
334     // this provider should only get invoked for local def-ids
335     let impl_node_id = gcx.hir().as_local_node_id(impl_did).unwrap_or_else(|| {
336         bug!("coerce_unsized_info: invoked for non-local def-id {:?}", impl_did)
337     });
338
339     let source = gcx.type_of(impl_did);
340     let trait_ref = gcx.impl_trait_ref(impl_did).unwrap();
341     assert_eq!(trait_ref.def_id, coerce_unsized_trait);
342     let target = trait_ref.substs.type_at(1);
343     debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (bound)",
344            source,
345            target);
346
347     let span = gcx.hir().span(impl_node_id);
348     let param_env = gcx.param_env(impl_did);
349     assert!(!source.has_escaping_bound_vars());
350
351     let err_info = CoerceUnsizedInfo { custom_kind: None };
352
353     debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (free)",
354            source,
355            target);
356
357     gcx.infer_ctxt().enter(|infcx| {
358         let cause = ObligationCause::misc(span, impl_node_id);
359         let check_mutbl = |mt_a: ty::TypeAndMut<'gcx>,
360                            mt_b: ty::TypeAndMut<'gcx>,
361                            mk_ptr: &dyn Fn(Ty<'gcx>) -> Ty<'gcx>| {
362             if (mt_a.mutbl, mt_b.mutbl) == (hir::MutImmutable, hir::MutMutable) {
363                 infcx.report_mismatched_types(&cause,
364                                               mk_ptr(mt_b.ty),
365                                               target,
366                                               ty::error::TypeError::Mutability)
367                     .emit();
368             }
369             (mt_a.ty, mt_b.ty, unsize_trait, None)
370         };
371         let (source, target, trait_def_id, kind) = match (&source.sty, &target.sty) {
372             (&ty::Ref(r_a, ty_a, mutbl_a), &ty::Ref(r_b, ty_b, mutbl_b)) => {
373                 infcx.sub_regions(infer::RelateObjectBound(span), r_b, r_a);
374                 let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
375                 let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
376                 check_mutbl(mt_a, mt_b, &|ty| gcx.mk_imm_ref(r_b, ty))
377             }
378
379             (&ty::Ref(_, ty_a, mutbl_a), &ty::RawPtr(mt_b)) => {
380                 let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
381                 check_mutbl(mt_a, mt_b, &|ty| gcx.mk_imm_ptr(ty))
382             }
383
384             (&ty::RawPtr(mt_a), &ty::RawPtr(mt_b)) => {
385                 check_mutbl(mt_a, mt_b, &|ty| gcx.mk_imm_ptr(ty))
386             }
387
388             (&ty::Adt(def_a, substs_a), &ty::Adt(def_b, substs_b)) if def_a.is_struct() &&
389                                                                       def_b.is_struct() => {
390                 if def_a != def_b {
391                     let source_path = gcx.item_path_str(def_a.did);
392                     let target_path = gcx.item_path_str(def_b.did);
393                     span_err!(gcx.sess,
394                               span,
395                               E0377,
396                               "the trait `CoerceUnsized` may only be implemented \
397                                for a coercion between structures with the same \
398                                definition; expected `{}`, found `{}`",
399                               source_path,
400                               target_path);
401                     return err_info;
402                 }
403
404                 // Here we are considering a case of converting
405                 // `S<P0...Pn>` to S<Q0...Qn>`. As an example, let's imagine a struct `Foo<T, U>`,
406                 // which acts like a pointer to `U`, but carries along some extra data of type `T`:
407                 //
408                 //     struct Foo<T, U> {
409                 //         extra: T,
410                 //         ptr: *mut U,
411                 //     }
412                 //
413                 // We might have an impl that allows (e.g.) `Foo<T, [i32; 3]>` to be unsized
414                 // to `Foo<T, [i32]>`. That impl would look like:
415                 //
416                 //   impl<T, U: Unsize<V>, V> CoerceUnsized<Foo<T, V>> for Foo<T, U> {}
417                 //
418                 // Here `U = [i32; 3]` and `V = [i32]`. At runtime,
419                 // when this coercion occurs, we would be changing the
420                 // field `ptr` from a thin pointer of type `*mut [i32;
421                 // 3]` to a fat pointer of type `*mut [i32]` (with
422                 // extra data `3`).  **The purpose of this check is to
423                 // make sure that we know how to do this conversion.**
424                 //
425                 // To check if this impl is legal, we would walk down
426                 // the fields of `Foo` and consider their types with
427                 // both substitutes. We are looking to find that
428                 // exactly one (non-phantom) field has changed its
429                 // type, which we will expect to be the pointer that
430                 // is becoming fat (we could probably generalize this
431                 // to multiple thin pointers of the same type becoming
432                 // fat, but we don't). In this case:
433                 //
434                 // - `extra` has type `T` before and type `T` after
435                 // - `ptr` has type `*mut U` before and type `*mut V` after
436                 //
437                 // Since just one field changed, we would then check
438                 // that `*mut U: CoerceUnsized<*mut V>` is implemented
439                 // (in other words, that we know how to do this
440                 // conversion). This will work out because `U:
441                 // Unsize<V>`, and we have a builtin rule that `*mut
442                 // U` can be coerced to `*mut V` if `U: Unsize<V>`.
443                 let fields = &def_a.non_enum_variant().fields;
444                 let diff_fields = fields.iter()
445                     .enumerate()
446                     .filter_map(|(i, f)| {
447                         let (a, b) = (f.ty(gcx, substs_a), f.ty(gcx, substs_b));
448
449                         if gcx.type_of(f.did).is_phantom_data() {
450                             // Ignore PhantomData fields
451                             return None;
452                         }
453
454                         // Ignore fields that aren't changed; it may
455                         // be that we could get away with subtyping or
456                         // something more accepting, but we use
457                         // equality because we want to be able to
458                         // perform this check without computing
459                         // variance where possible. (This is because
460                         // we may have to evaluate constraint
461                         // expressions in the course of execution.)
462                         // See e.g., #41936.
463                         if let Ok(ok) = infcx.at(&cause, param_env).eq(a, b) {
464                             if ok.obligations.is_empty() {
465                                 return None;
466                             }
467                         }
468
469                         // Collect up all fields that were significantly changed
470                         // i.e., those that contain T in coerce_unsized T -> U
471                         Some((i, a, b))
472                     })
473                     .collect::<Vec<_>>();
474
475                 if diff_fields.is_empty() {
476                     span_err!(gcx.sess,
477                               span,
478                               E0374,
479                               "the trait `CoerceUnsized` may only be implemented \
480                                for a coercion between structures with one field \
481                                being coerced, none found");
482                     return err_info;
483                 } else if diff_fields.len() > 1 {
484                     let item = gcx.hir().expect_item(impl_node_id);
485                     let span = if let ItemKind::Impl(.., Some(ref t), _, _) = item.node {
486                         t.path.span
487                     } else {
488                         gcx.hir().span(impl_node_id)
489                     };
490
491                     let mut err = struct_span_err!(gcx.sess,
492                                                    span,
493                                                    E0375,
494                                                    "implementing the trait \
495                                                     `CoerceUnsized` requires multiple \
496                                                     coercions");
497                     err.note("`CoerceUnsized` may only be implemented for \
498                               a coercion between structures with one field being coerced");
499                     err.note(&format!("currently, {} fields need coercions: {}",
500                                       diff_fields.len(),
501                                       diff_fields.iter()
502                                           .map(|&(i, a, b)| {
503                                               format!("`{}` (`{}` to `{}`)", fields[i].ident, a, b)
504                                           })
505                                           .collect::<Vec<_>>()
506                                           .join(", ")));
507                     err.span_label(span, "requires multiple coercions");
508                     err.emit();
509                     return err_info;
510                 }
511
512                 let (i, a, b) = diff_fields[0];
513                 let kind = ty::adjustment::CustomCoerceUnsized::Struct(i);
514                 (a, b, coerce_unsized_trait, Some(kind))
515             }
516
517             _ => {
518                 span_err!(gcx.sess,
519                           span,
520                           E0376,
521                           "the trait `CoerceUnsized` may only be implemented \
522                            for a coercion between structures");
523                 return err_info;
524             }
525         };
526
527         let mut fulfill_cx = TraitEngine::new(infcx.tcx);
528
529         // Register an obligation for `A: Trait<B>`.
530         let cause = traits::ObligationCause::misc(span, impl_node_id);
531         let predicate = gcx.predicate_for_trait_def(param_env,
532                                                     cause,
533                                                     trait_def_id,
534                                                     0,
535                                                     source,
536                                                     &[target.into()]);
537         fulfill_cx.register_predicate_obligation(&infcx, predicate);
538
539         // Check that all transitive obligations are satisfied.
540         if let Err(errors) = fulfill_cx.select_all_or_error(&infcx) {
541             infcx.report_fulfillment_errors(&errors, None, false);
542         }
543
544         // Finally, resolve all regions.
545         let region_scope_tree = region::ScopeTree::default();
546         let outlives_env = OutlivesEnvironment::new(param_env);
547         infcx.resolve_regions_and_report_errors(
548             impl_did,
549             &region_scope_tree,
550             &outlives_env,
551             SuppressRegionErrors::default(),
552         );
553
554         CoerceUnsizedInfo {
555             custom_kind: kind
556         }
557     })
558 }