1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 // The job of the coherence phase of typechecking is to ensure that each trait
14 // has at most one implementation for each type. Then we build a mapping from
15 // each trait in the system to its implementations.
18 use metadata::csearch::{each_impl, get_impl_trait, each_implementation_for_trait};
19 use metadata::csearch;
21 use middle::subst::{Substs};
23 use middle::ty::{ImplContainer, ImplOrTraitItemId, MethodTraitItemId};
24 use middle::ty::{lookup_item_type};
25 use middle::ty::{t, ty_bool, ty_char, ty_bot, ty_box, ty_enum, ty_err};
26 use middle::ty::{ty_str, ty_vec, ty_float, ty_infer, ty_int, ty_nil};
27 use middle::ty::{ty_param, Polytype, ty_ptr};
28 use middle::ty::{ty_rptr, ty_struct, ty_trait, ty_tup};
29 use middle::ty::{ty_uint, ty_unboxed_closure, ty_uniq, ty_bare_fn};
30 use middle::ty::{ty_closure};
31 use middle::ty::type_is_ty_var;
32 use middle::subst::Subst;
34 use middle::typeck::CrateCtxt;
35 use middle::typeck::infer::combine::Combine;
36 use middle::typeck::infer::InferCtxt;
37 use middle::typeck::infer::{new_infer_ctxt, resolve_ivar, resolve_type};
38 use middle::typeck::infer;
39 use util::ppaux::Repr;
40 use middle::def::{DefStruct, DefTy};
41 use syntax::ast::{Crate, DefId};
42 use syntax::ast::{Item, ItemEnum, ItemImpl, ItemMod, ItemStruct};
43 use syntax::ast::{LOCAL_CRATE, TraitRef, TyPath};
45 use syntax::ast_map::NodeItem;
47 use syntax::ast_util::{local_def};
48 use syntax::codemap::{Span, DUMMY_SP};
49 use syntax::parse::token;
52 use std::collections::HashSet;
53 use std::cell::RefCell;
56 struct UniversalQuantificationResult {
60 fn get_base_type(inference_context: &InferCtxt,
64 let resolved_type = match resolve_type(inference_context,
68 Ok(resulting_type) if !type_is_ty_var(resulting_type) => resulting_type,
70 inference_context.tcx.sess.span_fatal(span,
71 "the type of this value must be known in order \
72 to determine the base type");
76 match get(resolved_type).sty {
77 ty_enum(..) | ty_struct(..) | ty_unboxed_closure(..) => {
78 debug!("(getting base type) found base type");
82 _ if ty::type_is_trait(resolved_type) => {
83 debug!("(getting base type) found base type (trait)");
87 ty_nil | ty_bot | ty_bool | ty_char | ty_int(..) | ty_uint(..) | ty_float(..) |
88 ty_str(..) | ty_vec(..) | ty_bare_fn(..) | ty_closure(..) | ty_tup(..) |
89 ty_infer(..) | ty_param(..) | ty_err |
90 ty_box(_) | ty_uniq(_) | ty_ptr(_) | ty_rptr(_, _) => {
91 debug!("(getting base type) no base type; found {:?}",
92 get(original_type).sty);
95 ty_trait(..) => fail!("should have been caught")
99 fn type_is_defined_in_local_crate(tcx: &ty::ctxt, original_type: t) -> bool {
102 * For coherence, when we have `impl Trait for Type`, we need to
103 * guarantee that `Type` is "local" to the
104 * crate. For our purposes, this means that it must contain
105 * some nominal type defined in this crate.
108 let mut found_nominal = false;
109 ty::walk_ty(original_type, |t| {
112 ty_struct(def_id, _) |
113 ty_unboxed_closure(def_id, _) => {
114 if def_id.krate == ast::LOCAL_CRATE {
115 found_nominal = true;
118 ty_trait(box ty::TyTrait { def_id, .. }) => {
119 if def_id.krate == ast::LOCAL_CRATE {
120 found_nominal = true;
124 match tcx.lang_items.owned_box() {
125 Some(did) if did.krate == ast::LOCAL_CRATE => {
126 found_nominal = true;
132 match tcx.lang_items.gc() {
133 Some(did) if did.krate == ast::LOCAL_CRATE => {
134 found_nominal = true;
143 return found_nominal;
146 // Returns the def ID of the base type, if there is one.
147 fn get_base_type_def_id(inference_context: &InferCtxt,
151 match get_base_type(inference_context, span, original_type) {
154 match get(base_type).sty {
156 ty_struct(def_id, _) |
157 ty_unboxed_closure(def_id, _) => {
160 ty_rptr(_, ty::mt {ty, ..}) | ty_uniq(ty) => match ty::get(ty).sty {
161 ty_trait(box ty::TyTrait { def_id, .. }) => {
165 fail!("get_base_type() returned a type that wasn't an \
166 enum, struct, or trait");
170 fail!("get_base_type() returned a type that wasn't an \
171 enum, struct, or trait");
178 struct CoherenceChecker<'a> {
179 crate_context: &'a CrateCtxt<'a>,
180 inference_context: InferCtxt<'a>,
183 struct CoherenceCheckVisitor<'a> {
184 cc: &'a CoherenceChecker<'a>
187 impl<'a> visit::Visitor<()> for CoherenceCheckVisitor<'a> {
188 fn visit_item(&mut self, item: &Item, _: ()) {
190 //debug!("(checking coherence) item '{}'", token::get_ident(item.ident));
193 ItemImpl(_, ref opt_trait, _, _) => {
194 match opt_trait.clone() {
196 self.cc.check_implementation(item, [opt_trait]);
198 None => self.cc.check_implementation(item, [])
206 visit::walk_item(self, item, ());
210 struct PrivilegedScopeVisitor<'a> { cc: &'a CoherenceChecker<'a> }
212 impl<'a> visit::Visitor<()> for PrivilegedScopeVisitor<'a> {
213 fn visit_item(&mut self, item: &Item, _: ()) {
216 ItemMod(ref module_) => {
217 // Then visit the module items.
218 visit::walk_mod(self, module_, ());
220 ItemImpl(_, None, ref ast_ty, _) => {
221 if !self.cc.ast_type_is_defined_in_local_crate(&**ast_ty) {
223 let session = &self.cc.crate_context.tcx.sess;
224 span_err!(session, item.span, E0116,
225 "cannot associate methods with a type outside the \
226 crate the type is defined in; define and implement \
227 a trait or new type instead");
230 ItemImpl(_, Some(ref trait_ref), _, _) => {
231 let tcx = self.cc.crate_context.tcx;
232 // `for_ty` is `Type` in `impl Trait for Type`
233 let for_ty = ty::node_id_to_type(tcx, item.id);
234 if !type_is_defined_in_local_crate(tcx, for_ty) {
235 // This implementation is not in scope of its base
236 // type. This still might be OK if the trait is
237 // defined in the same crate.
240 self.cc.trait_ref_to_trait_def_id(trait_ref);
242 if trait_def_id.krate != LOCAL_CRATE {
243 let session = &self.cc.crate_context.tcx.sess;
244 span_err!(session, item.span, E0117,
245 "cannot provide an extension implementation \
246 where both trait and type are not defined in this crate");
250 visit::walk_item(self, item, ());
253 visit::walk_item(self, item, ());
259 impl<'a> CoherenceChecker<'a> {
260 fn check(&self, krate: &Crate) {
261 // Check implementations and traits. This populates the tables
262 // containing the inherent methods and extension methods. It also
263 // builds up the trait inheritance table.
264 let mut visitor = CoherenceCheckVisitor { cc: self };
265 visit::walk_crate(&mut visitor, krate, ());
267 // Check that there are no overlapping trait instances
268 self.check_implementation_coherence();
270 // Check whether traits with base types are in privileged scopes.
271 self.check_privileged_scopes(krate);
273 // Bring in external crates. It's fine for this to happen after the
274 // coherence checks, because we ensure by construction that no errors
275 // can happen at link time.
276 self.add_external_crates();
278 // Populate the table of destructors. It might seem a bit strange to
279 // do this here, but it's actually the most convenient place, since
280 // the coherence tables contain the trait -> type mappings.
281 self.populate_destructor_table();
284 fn check_implementation(&self, item: &Item,
285 associated_traits: &[TraitRef]) {
286 let tcx = self.crate_context.tcx;
287 let impl_did = local_def(item.id);
288 let self_type = ty::lookup_item_type(tcx, impl_did);
290 // If there are no traits, then this implementation must have a
293 if associated_traits.len() == 0 {
294 debug!("(checking implementation) no associated traits for item '{}'",
295 token::get_ident(item.ident));
297 match get_base_type_def_id(&self.inference_context,
301 let session = &self.crate_context.tcx.sess;
302 span_err!(session, item.span, E0118,
303 "no base type found for inherent implementation; \
304 implement a trait or new type instead");
312 let impl_items = self.create_impl_from_item(item);
314 for associated_trait in associated_traits.iter() {
315 let trait_ref = ty::node_id_to_trait_ref(
316 self.crate_context.tcx, associated_trait.ref_id);
317 debug!("(checking implementation) adding impl for trait '{}', item '{}'",
318 trait_ref.repr(self.crate_context.tcx),
319 token::get_ident(item.ident));
321 self.add_trait_impl(trait_ref.def_id, impl_did);
324 // Add the implementation to the mapping from implementation to base
325 // type def ID, if there is a base type for this implementation and
326 // the implementation does not have any associated traits.
327 match get_base_type_def_id(&self.inference_context,
333 Some(base_type_def_id) => {
334 // FIXME: Gather up default methods?
335 if associated_traits.len() == 0 {
336 self.add_inherent_impl(base_type_def_id, impl_did);
341 tcx.impl_items.borrow_mut().insert(impl_did, impl_items);
344 // Creates default method IDs and performs type substitutions for an impl
345 // and trait pair. Then, for each provided method in the trait, inserts a
346 // `ProvidedMethodInfo` instance into the `provided_method_sources` map.
347 fn instantiate_default_methods(
350 trait_ref: &ty::TraitRef,
351 all_impl_items: &mut Vec<ImplOrTraitItemId>) {
352 let tcx = self.crate_context.tcx;
353 debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})",
354 impl_id, trait_ref.repr(tcx));
356 let impl_poly_type = ty::lookup_item_type(tcx, impl_id);
358 let prov = ty::provided_trait_methods(tcx, trait_ref.def_id);
359 for trait_method in prov.iter() {
361 let new_id = tcx.sess.next_node_id();
362 let new_did = local_def(new_id);
364 debug!("new_did={:?} trait_method={}", new_did, trait_method.repr(tcx));
366 // Create substitutions for the various trait parameters.
368 Rc::new(subst_receiver_types_in_method_ty(
375 Some(trait_method.def_id)));
377 debug!("new_method_ty={}", new_method_ty.repr(tcx));
378 all_impl_items.push(MethodTraitItemId(new_did));
380 // construct the polytype for the method based on the
381 // method_ty. it will have all the generics from the
382 // impl, plus its own.
383 let new_polytype = ty::Polytype {
384 generics: new_method_ty.generics.clone(),
385 ty: ty::mk_bare_fn(tcx, new_method_ty.fty.clone())
387 debug!("new_polytype={}", new_polytype.repr(tcx));
389 tcx.tcache.borrow_mut().insert(new_did, new_polytype);
390 tcx.impl_or_trait_items
392 .insert(new_did, ty::MethodTraitItem(new_method_ty));
394 // Pair the new synthesized ID up with the
396 self.crate_context.tcx.provided_method_sources.borrow_mut()
397 .insert(new_did, trait_method.def_id);
401 fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
402 let tcx = self.crate_context.tcx;
403 match tcx.inherent_impls.borrow().find(&base_def_id) {
404 Some(implementation_list) => {
405 implementation_list.borrow_mut().push(impl_def_id);
411 tcx.inherent_impls.borrow_mut().insert(base_def_id,
412 Rc::new(RefCell::new(vec!(impl_def_id))));
415 fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
416 ty::record_trait_implementation(self.crate_context.tcx,
421 fn check_implementation_coherence(&self) {
422 for trait_id in self.crate_context.tcx.trait_impls.borrow().keys() {
423 self.check_implementation_coherence_of(*trait_id);
427 fn check_implementation_coherence_of(&self, trait_def_id: DefId) {
428 // Unify pairs of polytypes.
429 self.iter_impls_of_trait_local(trait_def_id, |impl_a| {
431 self.get_self_type_for_implementation(impl_a);
433 // "We have an impl of trait <trait_def_id> for type <polytype_a>,
434 // and that impl is <impl_a>"
435 self.iter_impls_of_trait(trait_def_id, |impl_b| {
437 // An impl is coherent with itself
438 if impl_a != impl_b {
439 let polytype_b = self.get_self_type_for_implementation(
442 if self.polytypes_unify(polytype_a.clone(), polytype_b) {
443 let session = &self.crate_context.tcx.sess;
444 span_err!(session, self.span_of_impl(impl_a), E0119,
445 "conflicting implementations for trait `{}`",
446 ty::item_path_str(self.crate_context.tcx, trait_def_id));
447 if impl_b.krate == LOCAL_CRATE {
448 span_note!(session, self.span_of_impl(impl_b),
449 "note conflicting implementation here");
451 let crate_store = &self.crate_context.tcx.sess.cstore;
452 let cdata = crate_store.get_crate_data(impl_b.krate);
453 span_note!(session, self.span_of_impl(impl_a),
454 "conflicting implementation in crate `{}`",
463 fn iter_impls_of_trait(&self, trait_def_id: DefId, f: |DefId|) {
464 self.iter_impls_of_trait_local(trait_def_id, |x| f(x));
466 if trait_def_id.krate == LOCAL_CRATE {
470 let crate_store = &self.crate_context.tcx.sess.cstore;
471 csearch::each_implementation_for_trait(crate_store, trait_def_id, |impl_def_id| {
472 // Is this actually necessary?
473 let _ = lookup_item_type(self.crate_context.tcx, impl_def_id);
478 fn iter_impls_of_trait_local(&self, trait_def_id: DefId, f: |DefId|) {
479 match self.crate_context.tcx.trait_impls.borrow().find(&trait_def_id) {
481 for &impl_did in impls.borrow().iter() {
485 None => { /* no impls? */ }
489 fn polytypes_unify(&self,
490 polytype_a: Polytype,
491 polytype_b: Polytype)
493 let universally_quantified_a =
494 self.universally_quantify_polytype(polytype_a);
495 let universally_quantified_b =
496 self.universally_quantify_polytype(polytype_b);
498 return self.can_unify_universally_quantified(
499 &universally_quantified_a, &universally_quantified_b) ||
500 self.can_unify_universally_quantified(
501 &universally_quantified_b, &universally_quantified_a);
504 // Converts a polytype to a monotype by replacing all parameters with
505 // type variables. Returns the monotype and the type variables created.
506 fn universally_quantify_polytype(&self, polytype: Polytype)
507 -> UniversalQuantificationResult
510 self.inference_context.fresh_substs_for_type(DUMMY_SP,
512 let monotype = polytype.ty.subst(self.crate_context.tcx, &substitutions);
514 UniversalQuantificationResult {
519 fn can_unify_universally_quantified<'a>(&self,
520 a: &'a UniversalQuantificationResult,
521 b: &'a UniversalQuantificationResult)
524 infer::can_mk_subty(&self.inference_context,
529 fn get_self_type_for_implementation(&self, impl_did: DefId)
531 self.crate_context.tcx.tcache.borrow().get_copy(&impl_did)
534 // Privileged scope checking
535 fn check_privileged_scopes(&self, krate: &Crate) {
536 let mut visitor = PrivilegedScopeVisitor{ cc: self };
537 visit::walk_crate(&mut visitor, krate, ());
540 fn trait_ref_to_trait_def_id(&self, trait_ref: &TraitRef) -> DefId {
541 let def_map = &self.crate_context.tcx.def_map;
542 let trait_def = def_map.borrow().get_copy(&trait_ref.ref_id);
543 let trait_id = trait_def.def_id();
547 /// For coherence, when we have `impl Type`, we need to guarantee that
548 /// `Type` is "local" to the crate. For our purposes, this means that it
549 /// must precisely name some nominal type defined in this crate.
550 fn ast_type_is_defined_in_local_crate(&self, original_type: &ast::Ty) -> bool {
551 match original_type.node {
552 TyPath(_, _, path_id) => {
553 match self.crate_context.tcx.def_map.borrow().get_copy(&path_id) {
554 DefTy(def_id) | DefStruct(def_id) => {
555 if def_id.krate != LOCAL_CRATE {
559 // Make sure that this type precisely names a nominal
561 match self.crate_context.tcx.map.find(def_id.node) {
563 self.crate_context.tcx.sess.span_bug(
565 "resolve didn't resolve this type?!");
567 Some(NodeItem(item)) => {
569 ItemStruct(..) | ItemEnum(..) => true,
583 // Converts an implementation in the AST to a vector of items.
584 fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> {
586 ItemImpl(_, ref trait_refs, _, ref ast_items) => {
587 let mut items: Vec<ImplOrTraitItemId> =
591 ast::MethodImplItem(ast_method) => {
593 local_def(ast_method.id))
598 for trait_ref in trait_refs.iter() {
599 let ty_trait_ref = ty::node_id_to_trait_ref(
600 self.crate_context.tcx,
603 self.instantiate_default_methods(local_def(item.id),
611 self.crate_context.tcx.sess.span_bug(item.span,
612 "can't convert a non-impl to an impl");
617 fn span_of_impl(&self, impl_did: DefId) -> Span {
618 assert_eq!(impl_did.krate, LOCAL_CRATE);
619 self.crate_context.tcx.map.span(impl_did.node)
622 // External crate handling
624 fn add_external_impl(&self,
625 impls_seen: &mut HashSet<DefId>,
626 impl_def_id: DefId) {
627 let tcx = self.crate_context.tcx;
628 let impl_items = csearch::get_impl_items(&tcx.sess.cstore,
631 // Make sure we don't visit the same implementation multiple times.
632 if !impls_seen.insert(impl_def_id) {
638 let _ = lookup_item_type(tcx, impl_def_id);
639 let associated_traits = get_impl_trait(tcx, impl_def_id);
641 // Do a sanity check.
642 assert!(associated_traits.is_some());
644 // Record all the trait items.
645 for trait_ref in associated_traits.iter() {
646 self.add_trait_impl(trait_ref.def_id, impl_def_id);
649 // For any methods that use a default implementation, add them to
650 // the map. This is a bit unfortunate.
651 for item_def_id in impl_items.iter() {
652 let impl_item = ty::impl_or_trait_item(tcx, item_def_id.def_id());
654 ty::MethodTraitItem(ref method) => {
655 for &source in method.provided_source.iter() {
656 tcx.provided_method_sources
658 .insert(item_def_id.def_id(), source);
664 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
667 // Adds implementations and traits from external crates to the coherence
669 fn add_external_crates(&self) {
670 let mut impls_seen = HashSet::new();
672 let crate_store = &self.crate_context.tcx.sess.cstore;
673 crate_store.iter_crate_data(|crate_number, _crate_metadata| {
674 each_impl(crate_store, crate_number, |def_id| {
675 assert_eq!(crate_number, def_id.krate);
676 self.add_external_impl(&mut impls_seen, def_id)
685 fn populate_destructor_table(&self) {
686 let tcx = self.crate_context.tcx;
687 let drop_trait = match tcx.lang_items.drop_trait() {
688 Some(id) => id, None => { return }
691 let impl_items = tcx.impl_items.borrow();
692 let trait_impls = match tcx.trait_impls.borrow().find_copy(&drop_trait) {
693 None => return, // No types with (new-style) dtors present.
694 Some(found_impls) => found_impls
697 for &impl_did in trait_impls.borrow().iter() {
698 let items = impl_items.get(&impl_did);
700 // We'll error out later. For now, just don't ICE.
703 let method_def_id = *items.get(0);
705 let self_type = self.get_self_type_for_implementation(impl_did);
706 match ty::get(self_type.ty).sty {
707 ty::ty_enum(type_def_id, _) |
708 ty::ty_struct(type_def_id, _) |
709 ty::ty_unboxed_closure(type_def_id, _) => {
710 tcx.destructor_for_type
712 .insert(type_def_id, method_def_id.def_id());
715 .insert(method_def_id.def_id());
718 // Destructors only work on nominal types.
719 if impl_did.krate == ast::LOCAL_CRATE {
721 match tcx.map.find(impl_did.node) {
722 Some(ast_map::NodeItem(item)) => {
723 span_err!(tcx.sess, item.span, E0120,
724 "the Drop trait may only be implemented on structures");
727 tcx.sess.bug("didn't find impl in ast \
733 tcx.sess.bug("found external impl of Drop trait on \
734 something other than a struct");
742 pub fn make_substs_for_receiver_types(tcx: &ty::ctxt,
743 trait_ref: &ty::TraitRef,
748 * Substitutes the values for the receiver's type parameters
749 * that are found in method, leaving the method's type parameters
753 let meth_tps: Vec<ty::t> =
754 method.generics.types.get_slice(subst::FnSpace)
756 .map(|def| ty::mk_param_from_def(tcx, def))
758 let meth_regions: Vec<ty::Region> =
759 method.generics.regions.get_slice(subst::FnSpace)
761 .map(|def| ty::ReEarlyBound(def.def_id.node, def.space,
762 def.index, def.name))
764 trait_ref.substs.clone().with_method(meth_tps, meth_regions)
767 fn subst_receiver_types_in_method_ty(tcx: &ty::ctxt,
769 impl_poly_type: &ty::Polytype,
770 trait_ref: &ty::TraitRef,
771 new_def_id: ast::DefId,
773 provided_source: Option<ast::DefId>)
776 let combined_substs = make_substs_for_receiver_types(tcx, trait_ref, method);
778 debug!("subst_receiver_types_in_method_ty: combined_substs={}",
779 combined_substs.repr(tcx));
781 let mut method_generics = method.generics.subst(tcx, &combined_substs);
783 // replace the type parameters declared on the trait with those
785 for &space in [subst::TypeSpace, subst::SelfSpace].iter() {
786 method_generics.types.replace(
788 Vec::from_slice(impl_poly_type.generics.types.get_slice(space)));
789 method_generics.regions.replace(
791 Vec::from_slice(impl_poly_type.generics.regions.get_slice(space)));
794 debug!("subst_receiver_types_in_method_ty: method_generics={}",
795 method_generics.repr(tcx));
797 let method_fty = method.fty.subst(tcx, &combined_substs);
799 debug!("subst_receiver_types_in_method_ty: method_ty={}",
800 method.fty.repr(tcx));
806 method.explicit_self,
809 ImplContainer(impl_id),
814 pub fn check_coherence(crate_context: &CrateCtxt, krate: &Crate) {
816 crate_context: crate_context,
817 inference_context: new_infer_ctxt(crate_context.tcx),