]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/coherence/mod.rs
doc: remove incomplete sentence
[rust.git] / src / librustc_typeck / coherence / mod.rs
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.
4 //
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.
10
11 // Coherence phase
12 //
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.
17
18
19 use metadata::csearch::{each_impl, get_impl_trait};
20 use metadata::csearch;
21 use middle::subst::{mod, 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};
31 use middle::ty;
32 use CrateCtxt;
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;
38 use std::rc::Rc;
39 use syntax::ast::{Crate, DefId};
40 use syntax::ast::{Item, ItemImpl};
41 use syntax::ast::{LOCAL_CRATE, TraitRef};
42 use syntax::ast;
43 use syntax::ast_map::NodeItem;
44 use syntax::ast_map;
45 use syntax::ast_util::{local_def};
46 use syntax::codemap::{Span};
47 use syntax::parse::token;
48 use syntax::visit;
49 use util::nodemap::{DefIdMap, FnvHashMap};
50 use util::ppaux::Repr;
51
52 mod orphan;
53 mod overlap;
54 mod unsafety;
55
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>,
58                                   span: Span,
59                                   ty: Ty<'tcx>)
60                                   -> Option<DefId> {
61     match ty.sty {
62         ty_enum(def_id, _) |
63         ty_struct(def_id, _) => {
64             Some(def_id)
65         }
66
67         ty_trait(ref t) => {
68             Some(t.principal_def_id())
69         }
70
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(..) => {
75             None
76         }
77
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(
82                 span,
83                 format!("coherence encountered unexpected type searching for base type: {}",
84                         ty.repr(inference_context.tcx))[]);
85         }
86     }
87 }
88
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>>>>>,
93 }
94
95 struct CoherenceCheckVisitor<'a, 'tcx: 'a> {
96     cc: &'a CoherenceChecker<'a, 'tcx>
97 }
98
99 impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> {
100     fn visit_item(&mut self, item: &Item) {
101
102         //debug!("(checking coherence) item '{}'", token::get_ident(item.ident));
103
104         match item.node {
105             ItemImpl(_, _, ref opt_trait, _, _) => {
106                 match opt_trait.clone() {
107                     Some(opt_trait) => {
108                         self.cc.check_implementation(item, &[opt_trait]);
109                     }
110                     None => self.cc.check_implementation(item, &[])
111                 }
112             }
113             _ => {
114                 // Nothing to do.
115             }
116         };
117
118         visit::walk_item(self, item);
119     }
120 }
121
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);
129
130         // Copy over the inherent impls we gathered up during the walk into
131         // the tcx.
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()));
137         }
138
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();
143
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();
148
149         // Check to make sure implementations of `Copy` are legal.
150         self.check_implementations_of_copy();
151     }
152
153     fn check_implementation(&self,
154                             item: &Item,
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);
159
160         // If there are no traits, then this implementation must have a
161         // base type.
162
163         let impl_items = self.create_impl_from_item(item);
164
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));
171
172             enforce_trait_manually_implementable(self.crate_context.tcx,
173                                                  item.span,
174                                                  trait_ref.def_id);
175             self.add_trait_impl(trait_ref.def_id, impl_did);
176         }
177
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,
182                                    item.span,
183                                    self_type.ty) {
184             None => {
185                 // Nothing to do.
186             }
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);
191                 }
192             }
193         }
194
195         tcx.impl_items.borrow_mut().insert(impl_did, impl_items);
196     }
197
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(
202             &self,
203             impl_id: DefId,
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));
209
210         let impl_type_scheme = ty::lookup_item_type(tcx, impl_id);
211
212         let prov = ty::provided_trait_methods(tcx, trait_ref.def_id);
213         for trait_method in prov.iter() {
214             // Synthesize an ID.
215             let new_id = tcx.sess.next_node_id();
216             let new_did = local_def(new_id);
217
218             debug!("new_did={} trait_method={}", new_did, trait_method.repr(tcx));
219
220             // Create substitutions for the various trait parameters.
221             let new_method_ty =
222                 Rc::new(subst_receiver_types_in_method_ty(
223                     tcx,
224                     impl_id,
225                     &impl_type_scheme,
226                     trait_ref,
227                     new_did,
228                     &**trait_method,
229                     Some(trait_method.def_id)));
230
231             debug!("new_method_ty={}", new_method_ty.repr(tcx));
232             all_impl_items.push(MethodTraitItemId(new_did));
233
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()))
241             };
242             debug!("new_polytype={}", new_polytype.repr(tcx));
243
244             tcx.tcache.borrow_mut().insert(new_did, new_polytype);
245             tcx.impl_or_trait_items
246                .borrow_mut()
247                .insert(new_did, ty::MethodTraitItem(new_method_ty));
248
249             // Pair the new synthesized ID up with the
250             // ID of the method.
251             self.crate_context.tcx.provided_method_sources.borrow_mut()
252                 .insert(new_did, trait_method.def_id);
253         }
254     }
255
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);
260                 return;
261             }
262             None => {}
263         }
264
265         self.inherent_impls.borrow_mut().insert(
266             base_def_id,
267             Rc::new(RefCell::new(vec!(impl_def_id))));
268     }
269
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,
274                                         base_def_id,
275                                         impl_def_id);
276     }
277
278     fn get_self_type_for_implementation(&self, impl_did: DefId)
279                                         -> TypeScheme<'tcx> {
280         self.crate_context.tcx.tcache.borrow()[impl_did].clone()
281     }
282
283     // Converts an implementation in the AST to a vector of items.
284     fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> {
285         match item.node {
286             ItemImpl(_, _, ref trait_refs, _, ref ast_items) => {
287                 let mut items: Vec<ImplOrTraitItemId> =
288                         ast_items.iter()
289                                  .map(|ast_item| {
290                             match *ast_item {
291                                 ast::MethodImplItem(ref ast_method) => {
292                                     MethodTraitItemId(
293                                         local_def(ast_method.id))
294                                 }
295                                 ast::TypeImplItem(ref typedef) => {
296                                     TypeTraitItemId(local_def(typedef.id))
297                                 }
298                             }
299                         }).collect();
300
301                 for trait_ref in trait_refs.iter() {
302                     let ty_trait_ref = ty::node_id_to_trait_ref(
303                         self.crate_context.tcx,
304                         trait_ref.ref_id);
305
306                     self.instantiate_default_methods(local_def(item.id),
307                                                      &*ty_trait_ref,
308                                                      &mut items);
309                 }
310
311                 items
312             }
313             _ => {
314                 self.crate_context.tcx.sess.span_bug(item.span,
315                                                      "can't convert a non-impl to an impl");
316             }
317         }
318     }
319
320     // External crate handling
321
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,
327                                                  impl_def_id);
328
329         // Make sure we don't visit the same implementation multiple times.
330         if !impls_seen.insert(impl_def_id) {
331             // Skip this one.
332             return
333         }
334         // Good. Continue.
335
336         let _ = lookup_item_type(tcx, impl_def_id);
337         let associated_traits = get_impl_trait(tcx, impl_def_id);
338
339         // Do a sanity check.
340         assert!(associated_traits.is_some());
341
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);
345         }
346
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());
351             match impl_item {
352                 ty::MethodTraitItem(ref method) => {
353                     for &source in method.provided_source.iter() {
354                         tcx.provided_method_sources
355                            .borrow_mut()
356                            .insert(item_def_id.def_id(), source);
357                     }
358                 }
359                 ty::TypeTraitItem(_) => {}
360             }
361         }
362
363         tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
364     }
365
366     // Adds implementations and traits from external crates to the coherence
367     // info.
368     fn add_external_crates(&self) {
369         let mut impls_seen = HashSet::new();
370
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)
376             })
377         })
378     }
379
380     //
381     // Destructors
382     //
383
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 }
388         };
389
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
394         };
395
396         for &impl_did in trait_impls.borrow().iter() {
397             let items = &(*impl_items)[impl_did];
398             if items.len() < 1 {
399                 // We'll error out later. For now, just don't ICE.
400                 continue;
401             }
402             let method_def_id = items[0];
403
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
410                        .borrow_mut()
411                        .insert(type_def_id, method_def_id.def_id());
412                     tcx.destructors
413                        .borrow_mut()
414                        .insert(method_def_id.def_id());
415                 }
416                 _ => {
417                     // Destructors only work on nominal types.
418                     if impl_did.krate == ast::LOCAL_CRATE {
419                         {
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");
424                                 }
425                                 _ => {
426                                     tcx.sess.bug("didn't find impl in ast \
427                                                   map");
428                                 }
429                             }
430                         }
431                     } else {
432                         tcx.sess.bug("found external impl of Drop trait on \
433                                       something other than a struct");
434                     }
435                 }
436             }
437         }
438     }
439
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() {
444             Some(id) => id,
445             None => return,
446         };
447
448         let trait_impls = match tcx.trait_impls
449                                    .borrow()
450                                    .get(&copy_trait)
451                                    .cloned() {
452             None => {
453                 debug!("check_implementations_of_copy(): no types with \
454                         implementations of `Copy` found");
455                 return
456             }
457             Some(found_impls) => found_impls
458         };
459
460         // Clone first to avoid a double borrow error.
461         let trait_impls = trait_impls.borrow().clone();
462
463         for &impl_did in trait_impls.iter() {
464             debug!("check_implementations_of_copy: impl_did={}",
465                    impl_did.repr(tcx));
466
467             if impl_did.krate != ast::LOCAL_CRATE {
468                 debug!("check_implementations_of_copy(): impl not in this \
469                         crate");
470                 continue
471             }
472
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));
476
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, &param_env.free_substs);
480             assert!(!self_type.has_escaping_regions());
481
482             debug!("check_implementations_of_copy: self_type={} (free)",
483                    self_type.repr(tcx));
484
485             match ty::can_type_implement_copy(&param_env, span, self_type) {
486                 Ok(()) => {}
487                 Err(ty::FieldDoesNotImplementCopy(name)) => {
488                     tcx.sess
489                        .span_err(span,
490                                  format!("the trait `Copy` may not be \
491                                           implemented for this type; field \
492                                           `{}` does not implement `Copy`",
493                                          token::get_name(name))[])
494                 }
495                 Err(ty::VariantDoesNotImplementCopy(name)) => {
496                     tcx.sess
497                        .span_err(span,
498                                  format!("the trait `Copy` may not be \
499                                           implemented for this type; variant \
500                                           `{}` does not implement `Copy`",
501                                          token::get_name(name))[])
502                 }
503                 Err(ty::TypeIsStructural) => {
504                     tcx.sess
505                        .span_err(span,
506                                  "the trait `Copy` may not be implemented \
507                                   for this type; type is not a structure or \
508                                   enumeration")
509                 }
510             }
511         }
512     }
513 }
514
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
518         return
519     }
520     let did = Some(trait_def_id);
521     let li = &tcx.lang_items;
522
523     let trait_name = if did == li.fn_trait() {
524         "Fn"
525     } else if did == li.fn_mut_trait() {
526         "FnMut"
527     } else if did == li.fn_once_trait() {
528         "FnOnce"
529     } else {
530         return // everything OK
531     };
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");
535 }
536
537 fn subst_receiver_types_in_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>,
538                                            impl_id: ast::DefId,
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>)
544                                            -> ty::Method<'tcx>
545 {
546     let combined_substs = ty::make_substs_for_receiver_types(tcx, trait_ref, method);
547
548     debug!("subst_receiver_types_in_method_ty: combined_substs={}",
549            combined_substs.repr(tcx));
550
551     let mut method_generics = method.generics.subst(tcx, &combined_substs);
552
553     // replace the type parameters declared on the trait with those
554     // from the impl
555     for &space in [subst::TypeSpace, subst::SelfSpace].iter() {
556         method_generics.types.replace(
557             space,
558             impl_type_scheme.generics.types.get_slice(space).to_vec());
559         method_generics.regions.replace(
560             space,
561             impl_type_scheme.generics.regions.get_slice(space).to_vec());
562     }
563
564     debug!("subst_receiver_types_in_method_ty: method_generics={}",
565            method_generics.repr(tcx));
566
567     let method_fty = method.fty.subst(tcx, &combined_substs);
568
569     debug!("subst_receiver_types_in_method_ty: method_ty={}",
570            method.fty.repr(tcx));
571
572     ty::Method::new(
573         method.name,
574         method_generics,
575         method_fty,
576         method.explicit_self,
577         method.vis,
578         new_def_id,
579         ImplContainer(impl_id),
580         provided_source
581     )
582 }
583
584 pub fn check_coherence(crate_context: &CrateCtxt) {
585     CoherenceChecker {
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);
593 }