1 //! Check properties that are required by built-in traits and set
2 //! up data structures required by type-checking/codegen.
4 use rustc::infer::SuppressRegionErrors;
5 use rustc::infer::outlives::env::OutlivesEnvironment;
6 use rustc::middle::region;
7 use rustc::middle::lang_items::UnsizeTraitLangItem;
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;
16 use rustc::hir::def_id::DefId;
18 use rustc::hir::{self, ItemKind};
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);
29 struct Checker<'a, 'tcx: 'a> {
30 tcx: TyCtxt<'a, 'tcx, 'tcx>,
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)
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);
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 {
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,
59 struct_span_err!(tcx.sess,
62 "the Drop trait may only be implemented on \
64 .span_label(span, "implementing Drop requires a struct")
67 bug!("didn't find impl in ast map");
70 bug!("found external impl of Drop trait on \
71 something other than a struct");
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);
79 let impl_hir_id = if let Some(n) = tcx.hir().as_local_hir_id(impl_did) {
82 debug!("visit_implementation_of_copy(): impl not in this crate");
86 let self_type = tcx.type_of(impl_did);
87 debug!("visit_implementation_of_copy: self_type={:?} (bound)",
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());
94 debug!("visit_implementation_of_copy: self_type={:?} (free)",
97 match param_env.can_type_implement_copy(tcx, self_type) {
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 {
107 let mut err = struct_span_err!(tcx.sess,
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`");
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 {
124 struct_span_err!(tcx.sess,
127 "the trait `Copy` may not be implemented for this type")
128 .span_label(span, "type is not a structure or enumeration")
131 Err(CopyImplementationError::HasDestructor) => {
132 struct_span_err!(tcx.sess,
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")
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={:?}",
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
150 if impl_did.is_local() {
151 let span = tcx.def_span(impl_did);
152 tcx.at(span).coerce_unsized_info(impl_did);
156 fn visit_implementation_of_dispatch_from_dyn<'a, 'tcx>(
157 tcx: TyCtxt<'a, 'tcx, 'tcx>,
160 debug!("visit_implementation_of_dispatch_from_dyn: impl_did={:?}",
162 if impl_did.is_local() {
163 let dispatch_from_dyn_trait = tcx.lang_items().dispatch_from_dyn_trait().unwrap();
165 let impl_node_id = tcx.hir().as_local_node_id(impl_did).unwrap();
166 let span = tcx.hir().span(impl_node_id);
168 let source = tcx.type_of(impl_did);
169 assert!(!source.has_escaping_bound_vars());
171 let trait_ref = tcx.impl_trait_ref(impl_did).unwrap();
172 assert_eq!(trait_ref.def_id, dispatch_from_dyn_trait);
174 trait_ref.substs.type_at(1)
177 debug!("visit_implementation_of_dispatch_from_dyn: {:?} -> {:?}",
181 let param_env = tcx.param_env(impl_did);
183 let create_err = |msg: &str| {
184 struct_span_err!(tcx.sess, span, E0378, "{}", msg)
187 tcx.infer_ctxt().enter(|infcx| {
188 let cause = ObligationCause::misc(span, impl_node_id);
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() =>
201 let source_path = tcx.item_path_str(def_a.did);
202 let target_path = tcx.item_path_str(def_b.did);
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,
216 if def_a.repr.c() || def_a.repr.packed() {
218 "structs implementing `DispatchFromDyn` may not have \
219 `#[repr(packed)]` or `#[repr(C)]`"
223 let fields = &def_a.non_enum_variant().fields;
225 let coerced_fields = fields.iter().filter_map(|field| {
226 if tcx.type_of(field.did).is_phantom_data() {
227 // ignore PhantomData fields
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() {
236 "the trait `DispatchFromDyn` may only be implemented \
237 for structs containing the field being coerced, \
238 `PhantomData` fields, and nothing else"
241 "extra field `{}` of type `{}` is not allowed",
251 }).collect::<Vec<_>>();
253 if coerced_fields.is_empty() {
255 "the trait `DispatchFromDyn` may only be implemented \
256 for a coercion between structures with a single field \
257 being coerced, none found"
259 } else if coerced_fields.len() > 1 {
261 "implementing the `DispatchFromDyn` trait requires multiple coercions",
263 "the trait `DispatchFromDyn` may only be implemented \
264 for a coercion between structures with a single field \
268 "currently, {} fields need coercions: {}",
269 coerced_fields.len(),
270 coerced_fields.iter().map(|field| {
271 format!("`{}` (`{}` to `{}`)",
273 field.ty(tcx, substs_a),
274 field.ty(tcx, substs_b),
276 }).collect::<Vec<_>>()
281 let mut fulfill_cx = TraitEngine::new(infcx.tcx);
283 for field in coerced_fields {
285 let predicate = tcx.predicate_for_trait_def(
288 dispatch_from_dyn_trait,
290 field.ty(tcx, substs_a),
291 &[field.ty(tcx, substs_b).into()]
294 fulfill_cx.register_predicate_obligation(&infcx, predicate);
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);
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(
309 SuppressRegionErrors::default(),
315 "the trait `DispatchFromDyn` may only be implemented \
316 for a coercion between structures"
324 pub fn coerce_unsized_info<'a, 'gcx>(gcx: TyCtxt<'a, 'gcx, 'gcx>,
326 -> CoerceUnsizedInfo {
327 debug!("compute_coerce_unsized_info(impl_did={:?})", impl_did);
328 let coerce_unsized_trait = gcx.lang_items().coerce_unsized_trait().unwrap();
330 let unsize_trait = gcx.lang_items().require(UnsizeTraitLangItem).unwrap_or_else(|err| {
331 gcx.sess.fatal(&format!("`CoerceUnsized` implementation {}", err));
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)
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)",
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());
351 let err_info = CoerceUnsizedInfo { custom_kind: None };
353 debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (free)",
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,
366 ty::error::TypeError::Mutability)
369 (mt_a.ty, mt_b.ty, unsize_trait, None)
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))
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))
384 (&ty::RawPtr(mt_a), &ty::RawPtr(mt_b)) => {
385 check_mutbl(mt_a, mt_b, &|ty| gcx.mk_imm_ptr(ty))
388 (&ty::Adt(def_a, substs_a), &ty::Adt(def_b, substs_b)) if def_a.is_struct() &&
389 def_b.is_struct() => {
391 let source_path = gcx.item_path_str(def_a.did);
392 let target_path = gcx.item_path_str(def_b.did);
396 "the trait `CoerceUnsized` may only be implemented \
397 for a coercion between structures with the same \
398 definition; expected `{}`, found `{}`",
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`:
408 // struct Foo<T, U> {
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:
416 // impl<T, U: Unsize<V>, V> CoerceUnsized<Foo<T, V>> for Foo<T, U> {}
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.**
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:
434 // - `extra` has type `T` before and type `T` after
435 // - `ptr` has type `*mut U` before and type `*mut V` after
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()
446 .filter_map(|(i, f)| {
447 let (a, b) = (f.ty(gcx, substs_a), f.ty(gcx, substs_b));
449 if gcx.type_of(f.did).is_phantom_data() {
450 // Ignore PhantomData fields
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.)
463 if let Ok(ok) = infcx.at(&cause, param_env).eq(a, b) {
464 if ok.obligations.is_empty() {
469 // Collect up all fields that were significantly changed
470 // i.e., those that contain T in coerce_unsized T -> U
473 .collect::<Vec<_>>();
475 if diff_fields.is_empty() {
479 "the trait `CoerceUnsized` may only be implemented \
480 for a coercion between structures with one field \
481 being coerced, none found");
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 {
488 gcx.hir().span(impl_node_id)
491 let mut err = struct_span_err!(gcx.sess,
494 "implementing the trait \
495 `CoerceUnsized` requires multiple \
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: {}",
503 format!("`{}` (`{}` to `{}`)", fields[i].ident, a, b)
507 err.span_label(span, "requires multiple coercions");
512 let (i, a, b) = diff_fields[0];
513 let kind = ty::adjustment::CustomCoerceUnsized::Struct(i);
514 (a, b, coerce_unsized_trait, Some(kind))
521 "the trait `CoerceUnsized` may only be implemented \
522 for a coercion between structures");
527 let mut fulfill_cx = TraitEngine::new(infcx.tcx);
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,
537 fulfill_cx.register_predicate_obligation(&infcx, predicate);
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);
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(
551 SuppressRegionErrors::default(),