1 // Copyright 2014 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
14 // each trait has at most one implementation for each type. This is
15 // done by the orphan and overlap modules. Then we build up various
16 // mappings. That mapping code resides here.
19 use metadata::csearch::{each_impl, get_impl_trait};
20 use metadata::csearch;
21 use middle::subst::{self, Subst};
22 use middle::ty::RegionEscape;
23 use middle::ty::{ImplContainer, ImplOrTraitItemId, MethodTraitItemId};
24 use middle::ty::{ParameterEnvironment, TypeTraitItemId, lookup_item_type};
25 use middle::ty::{Ty, ty_bool, ty_char, ty_closure, ty_enum, ty_err};
26 use middle::ty::{ty_param, TypeScheme, ty_ptr};
27 use middle::ty::{ty_rptr, ty_struct, ty_trait, ty_tup};
28 use middle::ty::{ty_str, ty_vec, ty_float, ty_infer, ty_int, ty_open};
29 use middle::ty::{ty_uint, ty_unboxed_closure, ty_uniq, ty_bare_fn};
30 use middle::ty::{ty_projection};
33 use middle::infer::combine::Combine;
34 use middle::infer::InferCtxt;
35 use middle::infer::{new_infer_ctxt};
36 use std::collections::{HashSet};
37 use std::cell::RefCell;
39 use syntax::ast::{Crate, DefId};
40 use syntax::ast::{Item, ItemImpl};
41 use syntax::ast::{LOCAL_CRATE, TraitRef};
43 use syntax::ast_map::NodeItem;
45 use syntax::ast_util::{local_def};
46 use syntax::codemap::{Span};
47 use syntax::parse::token;
49 use util::nodemap::{DefIdMap, FnvHashMap};
50 use util::ppaux::Repr;
56 // Returns the def ID of the base type, if there is one.
57 fn get_base_type_def_id<'a, 'tcx>(inference_context: &InferCtxt<'a, 'tcx>,
63 ty_struct(def_id, _) => {
68 Some(t.principal_def_id())
71 ty_bool | ty_char | ty_int(..) | ty_uint(..) | ty_float(..) |
72 ty_str(..) | ty_vec(..) | ty_bare_fn(..) | ty_closure(..) | ty_tup(..) |
73 ty_param(..) | ty_err | ty_open(..) | ty_uniq(_) |
74 ty_ptr(_) | ty_rptr(_, _) | ty_projection(..) => {
78 ty_infer(..) | ty_unboxed_closure(..) => {
79 // `ty` comes from a user declaration so we should only expect types
80 // that the user can type
81 inference_context.tcx.sess.span_bug(
83 format!("coherence encountered unexpected type searching for base type: {}",
84 ty.repr(inference_context.tcx))[]);
89 struct CoherenceChecker<'a, 'tcx: 'a> {
90 crate_context: &'a CrateCtxt<'a, 'tcx>,
91 inference_context: InferCtxt<'a, 'tcx>,
92 inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
95 struct CoherenceCheckVisitor<'a, 'tcx: 'a> {
96 cc: &'a CoherenceChecker<'a, 'tcx>
99 impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> {
100 fn visit_item(&mut self, item: &Item) {
102 //debug!("(checking coherence) item '{}'", token::get_ident(item.ident));
105 ItemImpl(_, _, ref opt_trait, _, _) => {
106 match opt_trait.clone() {
108 self.cc.check_implementation(item, &[opt_trait]);
110 None => self.cc.check_implementation(item, &[])
118 visit::walk_item(self, item);
122 impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> {
123 fn check(&self, krate: &Crate) {
124 // Check implementations and traits. This populates the tables
125 // containing the inherent methods and extension methods. It also
126 // builds up the trait inheritance table.
127 let mut visitor = CoherenceCheckVisitor { cc: self };
128 visit::walk_crate(&mut visitor, krate);
130 // Copy over the inherent impls we gathered up during the walk into
132 let mut tcx_inherent_impls =
133 self.crate_context.tcx.inherent_impls.borrow_mut();
134 for (k, v) in self.inherent_impls.borrow().iter() {
135 tcx_inherent_impls.insert((*k).clone(),
136 Rc::new((*v.borrow()).clone()));
139 // Bring in external crates. It's fine for this to happen after the
140 // coherence checks, because we ensure by construction that no errors
141 // can happen at link time.
142 self.add_external_crates();
144 // Populate the table of destructors. It might seem a bit strange to
145 // do this here, but it's actually the most convenient place, since
146 // the coherence tables contain the trait -> type mappings.
147 self.populate_destructor_table();
149 // Check to make sure implementations of `Copy` are legal.
150 self.check_implementations_of_copy();
153 fn check_implementation(&self,
155 associated_traits: &[TraitRef]) {
156 let tcx = self.crate_context.tcx;
157 let impl_did = local_def(item.id);
158 let self_type = ty::lookup_item_type(tcx, impl_did);
160 // If there are no traits, then this implementation must have a
163 let impl_items = self.create_impl_from_item(item);
165 for associated_trait in associated_traits.iter() {
166 let trait_ref = ty::node_id_to_trait_ref(self.crate_context.tcx,
167 associated_trait.ref_id);
168 debug!("(checking implementation) adding impl for trait '{}', item '{}'",
169 trait_ref.repr(self.crate_context.tcx),
170 token::get_ident(item.ident));
172 enforce_trait_manually_implementable(self.crate_context.tcx,
175 self.add_trait_impl(trait_ref.def_id, impl_did);
178 // Add the implementation to the mapping from implementation to base
179 // type def ID, if there is a base type for this implementation and
180 // the implementation does not have any associated traits.
181 match get_base_type_def_id(&self.inference_context,
187 Some(base_type_def_id) => {
188 // FIXME: Gather up default methods?
189 if associated_traits.len() == 0 {
190 self.add_inherent_impl(base_type_def_id, impl_did);
195 tcx.impl_items.borrow_mut().insert(impl_did, impl_items);
198 // Creates default method IDs and performs type substitutions for an impl
199 // and trait pair. Then, for each provided method in the trait, inserts a
200 // `ProvidedMethodInfo` instance into the `provided_method_sources` map.
201 fn instantiate_default_methods(
204 trait_ref: &ty::TraitRef<'tcx>,
205 all_impl_items: &mut Vec<ImplOrTraitItemId>) {
206 let tcx = self.crate_context.tcx;
207 debug!("instantiate_default_methods(impl_id={}, trait_ref={})",
208 impl_id, trait_ref.repr(tcx));
210 let impl_type_scheme = ty::lookup_item_type(tcx, impl_id);
212 let prov = ty::provided_trait_methods(tcx, trait_ref.def_id);
213 for trait_method in prov.iter() {
215 let new_id = tcx.sess.next_node_id();
216 let new_did = local_def(new_id);
218 debug!("new_did={} trait_method={}", new_did, trait_method.repr(tcx));
220 // Create substitutions for the various trait parameters.
222 Rc::new(subst_receiver_types_in_method_ty(
229 Some(trait_method.def_id)));
231 debug!("new_method_ty={}", new_method_ty.repr(tcx));
232 all_impl_items.push(MethodTraitItemId(new_did));
234 // construct the polytype for the method based on the
235 // method_ty. it will have all the generics from the
236 // impl, plus its own.
237 let new_polytype = ty::TypeScheme {
238 generics: new_method_ty.generics.clone(),
239 ty: ty::mk_bare_fn(tcx, Some(new_did),
240 tcx.mk_bare_fn(new_method_ty.fty.clone()))
242 debug!("new_polytype={}", new_polytype.repr(tcx));
244 tcx.tcache.borrow_mut().insert(new_did, new_polytype);
245 tcx.impl_or_trait_items
247 .insert(new_did, ty::MethodTraitItem(new_method_ty));
249 // Pair the new synthesized ID up with the
251 self.crate_context.tcx.provided_method_sources.borrow_mut()
252 .insert(new_did, trait_method.def_id);
256 fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
257 match self.inherent_impls.borrow().get(&base_def_id) {
258 Some(implementation_list) => {
259 implementation_list.borrow_mut().push(impl_def_id);
265 self.inherent_impls.borrow_mut().insert(
267 Rc::new(RefCell::new(vec!(impl_def_id))));
270 fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
271 debug!("add_trait_impl: base_def_id={} impl_def_id={}",
272 base_def_id, impl_def_id);
273 ty::record_trait_implementation(self.crate_context.tcx,
278 fn get_self_type_for_implementation(&self, impl_did: DefId)
279 -> TypeScheme<'tcx> {
280 self.crate_context.tcx.tcache.borrow()[impl_did].clone()
283 // Converts an implementation in the AST to a vector of items.
284 fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> {
286 ItemImpl(_, _, ref trait_refs, _, ref ast_items) => {
287 let mut items: Vec<ImplOrTraitItemId> =
291 ast::MethodImplItem(ref ast_method) => {
293 local_def(ast_method.id))
295 ast::TypeImplItem(ref typedef) => {
296 TypeTraitItemId(local_def(typedef.id))
301 for trait_ref in trait_refs.iter() {
302 let ty_trait_ref = ty::node_id_to_trait_ref(
303 self.crate_context.tcx,
306 self.instantiate_default_methods(local_def(item.id),
314 self.crate_context.tcx.sess.span_bug(item.span,
315 "can't convert a non-impl to an impl");
320 // External crate handling
322 fn add_external_impl(&self,
323 impls_seen: &mut HashSet<DefId>,
324 impl_def_id: DefId) {
325 let tcx = self.crate_context.tcx;
326 let impl_items = csearch::get_impl_items(&tcx.sess.cstore,
329 // Make sure we don't visit the same implementation multiple times.
330 if !impls_seen.insert(impl_def_id) {
336 let _ = lookup_item_type(tcx, impl_def_id);
337 let associated_traits = get_impl_trait(tcx, impl_def_id);
339 // Do a sanity check.
340 assert!(associated_traits.is_some());
342 // Record all the trait items.
343 for trait_ref in associated_traits.iter() {
344 self.add_trait_impl(trait_ref.def_id, impl_def_id);
347 // For any methods that use a default implementation, add them to
348 // the map. This is a bit unfortunate.
349 for item_def_id in impl_items.iter() {
350 let impl_item = ty::impl_or_trait_item(tcx, item_def_id.def_id());
352 ty::MethodTraitItem(ref method) => {
353 for &source in method.provided_source.iter() {
354 tcx.provided_method_sources
356 .insert(item_def_id.def_id(), source);
359 ty::TypeTraitItem(_) => {}
363 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
366 // Adds implementations and traits from external crates to the coherence
368 fn add_external_crates(&self) {
369 let mut impls_seen = HashSet::new();
371 let crate_store = &self.crate_context.tcx.sess.cstore;
372 crate_store.iter_crate_data(|crate_number, _crate_metadata| {
373 each_impl(crate_store, crate_number, |def_id| {
374 assert_eq!(crate_number, def_id.krate);
375 self.add_external_impl(&mut impls_seen, def_id)
384 fn populate_destructor_table(&self) {
385 let tcx = self.crate_context.tcx;
386 let drop_trait = match tcx.lang_items.drop_trait() {
387 Some(id) => id, None => { return }
390 let impl_items = tcx.impl_items.borrow();
391 let trait_impls = match tcx.trait_impls.borrow().get(&drop_trait).cloned() {
392 None => return, // No types with (new-style) dtors present.
393 Some(found_impls) => found_impls
396 for &impl_did in trait_impls.borrow().iter() {
397 let items = &(*impl_items)[impl_did];
399 // We'll error out later. For now, just don't ICE.
402 let method_def_id = items[0];
404 let self_type = self.get_self_type_for_implementation(impl_did);
405 match self_type.ty.sty {
406 ty::ty_enum(type_def_id, _) |
407 ty::ty_struct(type_def_id, _) |
408 ty::ty_unboxed_closure(type_def_id, _, _) => {
409 tcx.destructor_for_type
411 .insert(type_def_id, method_def_id.def_id());
414 .insert(method_def_id.def_id());
417 // Destructors only work on nominal types.
418 if impl_did.krate == ast::LOCAL_CRATE {
420 match tcx.map.find(impl_did.node) {
421 Some(ast_map::NodeItem(item)) => {
422 span_err!(tcx.sess, item.span, E0120,
423 "the Drop trait may only be implemented on structures");
426 tcx.sess.bug("didn't find impl in ast \
432 tcx.sess.bug("found external impl of Drop trait on \
433 something other than a struct");
440 /// Ensures that implementations of the built-in trait `Copy` are legal.
441 fn check_implementations_of_copy(&self) {
442 let tcx = self.crate_context.tcx;
443 let copy_trait = match tcx.lang_items.copy_trait() {
448 let trait_impls = match tcx.trait_impls
453 debug!("check_implementations_of_copy(): no types with \
454 implementations of `Copy` found");
457 Some(found_impls) => found_impls
460 // Clone first to avoid a double borrow error.
461 let trait_impls = trait_impls.borrow().clone();
463 for &impl_did in trait_impls.iter() {
464 debug!("check_implementations_of_copy: impl_did={}",
467 if impl_did.krate != ast::LOCAL_CRATE {
468 debug!("check_implementations_of_copy(): impl not in this \
473 let self_type = self.get_self_type_for_implementation(impl_did);
474 debug!("check_implementations_of_copy: self_type={} (bound)",
475 self_type.repr(tcx));
477 let span = tcx.map.span(impl_did.node);
478 let param_env = ParameterEnvironment::for_item(tcx, impl_did.node);
479 let self_type = self_type.ty.subst(tcx, ¶m_env.free_substs);
480 assert!(!self_type.has_escaping_regions());
482 debug!("check_implementations_of_copy: self_type={} (free)",
483 self_type.repr(tcx));
485 match ty::can_type_implement_copy(¶m_env, span, self_type) {
487 Err(ty::FieldDoesNotImplementCopy(name)) => {
490 format!("the trait `Copy` may not be \
491 implemented for this type; field \
492 `{}` does not implement `Copy`",
493 token::get_name(name))[])
495 Err(ty::VariantDoesNotImplementCopy(name)) => {
498 format!("the trait `Copy` may not be \
499 implemented for this type; variant \
500 `{}` does not implement `Copy`",
501 token::get_name(name))[])
503 Err(ty::TypeIsStructural) => {
506 "the trait `Copy` may not be implemented \
507 for this type; type is not a structure or \
515 fn enforce_trait_manually_implementable(tcx: &ty::ctxt, sp: Span, trait_def_id: ast::DefId) {
516 if tcx.sess.features.borrow().unboxed_closures {
517 // the feature gate allows all of them
520 let did = Some(trait_def_id);
521 let li = &tcx.lang_items;
523 let trait_name = if did == li.fn_trait() {
525 } else if did == li.fn_mut_trait() {
527 } else if did == li.fn_once_trait() {
530 return // everything OK
532 span_err!(tcx.sess, sp, E0183, "manual implementations of `{}` are experimental", trait_name);
533 span_help!(tcx.sess, sp,
534 "add `#![feature(unboxed_closures)]` to the crate attributes to enable");
537 fn subst_receiver_types_in_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>,
539 impl_type_scheme: &ty::TypeScheme<'tcx>,
540 trait_ref: &ty::TraitRef<'tcx>,
541 new_def_id: ast::DefId,
542 method: &ty::Method<'tcx>,
543 provided_source: Option<ast::DefId>)
546 let combined_substs = ty::make_substs_for_receiver_types(tcx, trait_ref, method);
548 debug!("subst_receiver_types_in_method_ty: combined_substs={}",
549 combined_substs.repr(tcx));
551 let mut method_generics = method.generics.subst(tcx, &combined_substs);
553 // replace the type parameters declared on the trait with those
555 for &space in [subst::TypeSpace, subst::SelfSpace].iter() {
556 method_generics.types.replace(
558 impl_type_scheme.generics.types.get_slice(space).to_vec());
559 method_generics.regions.replace(
561 impl_type_scheme.generics.regions.get_slice(space).to_vec());
564 debug!("subst_receiver_types_in_method_ty: method_generics={}",
565 method_generics.repr(tcx));
567 let method_fty = method.fty.subst(tcx, &combined_substs);
569 debug!("subst_receiver_types_in_method_ty: method_ty={}",
570 method.fty.repr(tcx));
576 method.explicit_self,
579 ImplContainer(impl_id),
584 pub fn check_coherence(crate_context: &CrateCtxt) {
586 crate_context: crate_context,
587 inference_context: new_infer_ctxt(crate_context.tcx),
588 inherent_impls: RefCell::new(FnvHashMap::new()),
589 }.check(crate_context.tcx.map.krate());
590 unsafety::check(crate_context.tcx);
591 orphan::check(crate_context.tcx);
592 overlap::check(crate_context.tcx);