]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/typeck/coherence.rs
auto merge of #16393 : SimonSapin/rust/patch-9, r=steveklabnik
[rust.git] / src / librustc / middle / typeck / coherence.rs
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.
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 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.
16
17
18 use metadata::csearch::{each_impl, get_impl_trait, each_implementation_for_trait};
19 use metadata::csearch;
20 use middle::subst;
21 use middle::subst::{Substs};
22 use middle::ty::get;
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, ty_open};
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;
33 use middle::ty;
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};
44 use syntax::ast;
45 use syntax::ast_map::NodeItem;
46 use syntax::ast_map;
47 use syntax::ast_util::{local_def};
48 use syntax::codemap::{Span, DUMMY_SP};
49 use syntax::parse::token;
50 use syntax::visit;
51
52 use std::collections::HashSet;
53 use std::cell::RefCell;
54 use std::rc::Rc;
55
56 struct UniversalQuantificationResult {
57     monotype: t
58 }
59
60 fn get_base_type(inference_context: &InferCtxt,
61                  span: Span,
62                  original_type: t)
63                  -> Option<t> {
64     let resolved_type = match resolve_type(inference_context,
65                                            Some(span),
66                                            original_type,
67                                            resolve_ivar) {
68         Ok(resulting_type) if !type_is_ty_var(resulting_type) => resulting_type,
69         _ => {
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");
73         }
74     };
75
76     match get(resolved_type).sty {
77         ty_enum(..) | ty_struct(..) | ty_unboxed_closure(..) => {
78             debug!("(getting base type) found base type");
79             Some(resolved_type)
80         }
81
82         _ if ty::type_is_trait(resolved_type) => {
83             debug!("(getting base type) found base type (trait)");
84             Some(resolved_type)
85         }
86
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 | ty_open(..) |
90         ty_box(_) | ty_uniq(_) | ty_ptr(_) | ty_rptr(_, _) => {
91             debug!("(getting base type) no base type; found {:?}",
92                    get(original_type).sty);
93             None
94         }
95         ty_trait(..) => fail!("should have been caught")
96     }
97 }
98
99 fn type_is_defined_in_local_crate(tcx: &ty::ctxt, original_type: t) -> bool {
100     /*!
101      *
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.
106      */
107
108     let mut found_nominal = false;
109     ty::walk_ty(original_type, |t| {
110         match get(t).sty {
111             ty_enum(def_id, _) |
112             ty_struct(def_id, _) |
113             ty_unboxed_closure(def_id, _) => {
114                 if def_id.krate == ast::LOCAL_CRATE {
115                     found_nominal = true;
116                 }
117             }
118             ty_trait(box ty::TyTrait { def_id, .. }) => {
119                 if def_id.krate == ast::LOCAL_CRATE {
120                     found_nominal = true;
121                 }
122             }
123             ty_uniq(..) => {
124                 match tcx.lang_items.owned_box() {
125                     Some(did) if did.krate == ast::LOCAL_CRATE => {
126                         found_nominal = true;
127                     }
128                     _ => {}
129                 }
130             }
131             ty_box(..) => {
132                 match tcx.lang_items.gc() {
133                     Some(did) if did.krate == ast::LOCAL_CRATE => {
134                         found_nominal = true;
135                     }
136                     _ => {}
137                 }
138             }
139
140             _ => { }
141         }
142     });
143     return found_nominal;
144 }
145
146 // Returns the def ID of the base type, if there is one.
147 fn get_base_type_def_id(inference_context: &InferCtxt,
148                         span: Span,
149                         original_type: t)
150                         -> Option<DefId> {
151     match get_base_type(inference_context, span, original_type) {
152         None => None,
153         Some(base_type) => {
154             match get(base_type).sty {
155                 ty_enum(def_id, _) |
156                 ty_struct(def_id, _) |
157                 ty_unboxed_closure(def_id, _) => {
158                     Some(def_id)
159                 }
160                 ty_rptr(_, ty::mt {ty, ..}) | ty_uniq(ty) => match ty::get(ty).sty {
161                     ty_trait(box ty::TyTrait { def_id, .. }) => {
162                         Some(def_id)
163                     }
164                     _ => {
165                         fail!("get_base_type() returned a type that wasn't an \
166                                enum, struct, or trait");
167                     }
168                 },
169                 ty_trait(box ty::TyTrait { def_id, .. }) => {
170                     Some(def_id)
171                 }
172                 _ => {
173                     fail!("get_base_type() returned a type that wasn't an \
174                            enum, struct, or trait");
175                 }
176             }
177         }
178     }
179 }
180
181 struct CoherenceChecker<'a> {
182     crate_context: &'a CrateCtxt<'a>,
183     inference_context: InferCtxt<'a>,
184 }
185
186 struct CoherenceCheckVisitor<'a> {
187     cc: &'a CoherenceChecker<'a>
188 }
189
190 impl<'a> visit::Visitor<()> for CoherenceCheckVisitor<'a> {
191     fn visit_item(&mut self, item: &Item, _: ()) {
192
193         //debug!("(checking coherence) item '{}'", token::get_ident(item.ident));
194
195         match item.node {
196             ItemImpl(_, ref opt_trait, _, _) => {
197                 match opt_trait.clone() {
198                     Some(opt_trait) => {
199                         self.cc.check_implementation(item, [opt_trait]);
200                     }
201                     None => self.cc.check_implementation(item, [])
202                 }
203             }
204             _ => {
205                 // Nothing to do.
206             }
207         };
208
209         visit::walk_item(self, item, ());
210     }
211 }
212
213 struct PrivilegedScopeVisitor<'a> { cc: &'a CoherenceChecker<'a> }
214
215 impl<'a> visit::Visitor<()> for PrivilegedScopeVisitor<'a> {
216     fn visit_item(&mut self, item: &Item, _: ()) {
217
218         match item.node {
219             ItemMod(ref module_) => {
220                 // Then visit the module items.
221                 visit::walk_mod(self, module_, ());
222             }
223             ItemImpl(_, None, ref ast_ty, _) => {
224                 if !self.cc.ast_type_is_defined_in_local_crate(&**ast_ty) {
225                     // This is an error.
226                     let session = &self.cc.crate_context.tcx.sess;
227                     span_err!(session, item.span, E0116,
228                               "cannot associate methods with a type outside the \
229                                crate the type is defined in; define and implement \
230                                a trait or new type instead");
231                 }
232             }
233             ItemImpl(_, Some(ref trait_ref), _, _) => {
234                 let tcx = self.cc.crate_context.tcx;
235                 // `for_ty` is `Type` in `impl Trait for Type`
236                 let for_ty = ty::node_id_to_type(tcx, item.id);
237                 if !type_is_defined_in_local_crate(tcx, for_ty) {
238                     // This implementation is not in scope of its base
239                     // type. This still might be OK if the trait is
240                     // defined in the same crate.
241
242                     let trait_def_id =
243                         self.cc.trait_ref_to_trait_def_id(trait_ref);
244
245                     if trait_def_id.krate != LOCAL_CRATE {
246                         let session = &self.cc.crate_context.tcx.sess;
247                         span_err!(session, item.span, E0117,
248                                   "cannot provide an extension implementation \
249                                    where both trait and type are not defined in this crate");
250                     }
251                 }
252
253                 visit::walk_item(self, item, ());
254             }
255             _ => {
256                 visit::walk_item(self, item, ());
257             }
258         }
259     }
260 }
261
262 impl<'a> CoherenceChecker<'a> {
263     fn check(&self, krate: &Crate) {
264         // Check implementations and traits. This populates the tables
265         // containing the inherent methods and extension methods. It also
266         // builds up the trait inheritance table.
267         let mut visitor = CoherenceCheckVisitor { cc: self };
268         visit::walk_crate(&mut visitor, krate, ());
269
270         // Check that there are no overlapping trait instances
271         self.check_implementation_coherence();
272
273         // Check whether traits with base types are in privileged scopes.
274         self.check_privileged_scopes(krate);
275
276         // Bring in external crates. It's fine for this to happen after the
277         // coherence checks, because we ensure by construction that no errors
278         // can happen at link time.
279         self.add_external_crates();
280
281         // Populate the table of destructors. It might seem a bit strange to
282         // do this here, but it's actually the most convenient place, since
283         // the coherence tables contain the trait -> type mappings.
284         self.populate_destructor_table();
285     }
286
287     fn check_implementation(&self, item: &Item,
288                             associated_traits: &[TraitRef]) {
289         let tcx = self.crate_context.tcx;
290         let impl_did = local_def(item.id);
291         let self_type = ty::lookup_item_type(tcx, impl_did);
292
293         // If there are no traits, then this implementation must have a
294         // base type.
295
296         if associated_traits.len() == 0 {
297             debug!("(checking implementation) no associated traits for item '{}'",
298                    token::get_ident(item.ident));
299
300             match get_base_type_def_id(&self.inference_context,
301                                        item.span,
302                                        self_type.ty) {
303                 None => {
304                     let session = &self.crate_context.tcx.sess;
305                     span_err!(session, item.span, E0118,
306                               "no base type found for inherent implementation; \
307                                implement a trait or new type instead");
308                 }
309                 Some(_) => {
310                     // Nothing to do.
311                 }
312             }
313         }
314
315         let impl_items = self.create_impl_from_item(item);
316
317         for associated_trait in associated_traits.iter() {
318             let trait_ref = ty::node_id_to_trait_ref(
319                 self.crate_context.tcx, associated_trait.ref_id);
320             debug!("(checking implementation) adding impl for trait '{}', item '{}'",
321                    trait_ref.repr(self.crate_context.tcx),
322                    token::get_ident(item.ident));
323
324             self.add_trait_impl(trait_ref.def_id, impl_did);
325         }
326
327         // Add the implementation to the mapping from implementation to base
328         // type def ID, if there is a base type for this implementation and
329         // the implementation does not have any associated traits.
330         match get_base_type_def_id(&self.inference_context,
331                                    item.span,
332                                    self_type.ty) {
333             None => {
334                 // Nothing to do.
335             }
336             Some(base_type_def_id) => {
337                 // FIXME: Gather up default methods?
338                 if associated_traits.len() == 0 {
339                     self.add_inherent_impl(base_type_def_id, impl_did);
340                 }
341             }
342         }
343
344         tcx.impl_items.borrow_mut().insert(impl_did, impl_items);
345     }
346
347     // Creates default method IDs and performs type substitutions for an impl
348     // and trait pair. Then, for each provided method in the trait, inserts a
349     // `ProvidedMethodInfo` instance into the `provided_method_sources` map.
350     fn instantiate_default_methods(
351             &self,
352             impl_id: DefId,
353             trait_ref: &ty::TraitRef,
354             all_impl_items: &mut Vec<ImplOrTraitItemId>) {
355         let tcx = self.crate_context.tcx;
356         debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})",
357                impl_id, trait_ref.repr(tcx));
358
359         let impl_poly_type = ty::lookup_item_type(tcx, impl_id);
360
361         let prov = ty::provided_trait_methods(tcx, trait_ref.def_id);
362         for trait_method in prov.iter() {
363             // Synthesize an ID.
364             let new_id = tcx.sess.next_node_id();
365             let new_did = local_def(new_id);
366
367             debug!("new_did={:?} trait_method={}", new_did, trait_method.repr(tcx));
368
369             // Create substitutions for the various trait parameters.
370             let new_method_ty =
371                 Rc::new(subst_receiver_types_in_method_ty(
372                     tcx,
373                     impl_id,
374                     &impl_poly_type,
375                     trait_ref,
376                     new_did,
377                     &**trait_method,
378                     Some(trait_method.def_id)));
379
380             debug!("new_method_ty={}", new_method_ty.repr(tcx));
381             all_impl_items.push(MethodTraitItemId(new_did));
382
383             // construct the polytype for the method based on the
384             // method_ty.  it will have all the generics from the
385             // impl, plus its own.
386             let new_polytype = ty::Polytype {
387                 generics: new_method_ty.generics.clone(),
388                 ty: ty::mk_bare_fn(tcx, new_method_ty.fty.clone())
389             };
390             debug!("new_polytype={}", new_polytype.repr(tcx));
391
392             tcx.tcache.borrow_mut().insert(new_did, new_polytype);
393             tcx.impl_or_trait_items
394                .borrow_mut()
395                .insert(new_did, ty::MethodTraitItem(new_method_ty));
396
397             // Pair the new synthesized ID up with the
398             // ID of the method.
399             self.crate_context.tcx.provided_method_sources.borrow_mut()
400                 .insert(new_did, trait_method.def_id);
401         }
402     }
403
404     fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
405         let tcx = self.crate_context.tcx;
406         match tcx.inherent_impls.borrow().find(&base_def_id) {
407             Some(implementation_list) => {
408                 implementation_list.borrow_mut().push(impl_def_id);
409                 return;
410             }
411             None => {}
412         }
413
414         tcx.inherent_impls.borrow_mut().insert(base_def_id,
415                                                Rc::new(RefCell::new(vec!(impl_def_id))));
416     }
417
418     fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
419         ty::record_trait_implementation(self.crate_context.tcx,
420                                         base_def_id,
421                                         impl_def_id);
422     }
423
424     fn check_implementation_coherence(&self) {
425         for trait_id in self.crate_context.tcx.trait_impls.borrow().keys() {
426             self.check_implementation_coherence_of(*trait_id);
427         }
428     }
429
430     fn check_implementation_coherence_of(&self, trait_def_id: DefId) {
431         // Unify pairs of polytypes.
432         self.iter_impls_of_trait_local(trait_def_id, |impl_a| {
433             let polytype_a =
434                 self.get_self_type_for_implementation(impl_a);
435
436             // "We have an impl of trait <trait_def_id> for type <polytype_a>,
437             // and that impl is <impl_a>"
438             self.iter_impls_of_trait(trait_def_id, |impl_b| {
439
440                 // An impl is coherent with itself
441                 if impl_a != impl_b {
442                     let polytype_b = self.get_self_type_for_implementation(
443                             impl_b);
444
445                     if self.polytypes_unify(polytype_a.clone(), polytype_b) {
446                         let session = &self.crate_context.tcx.sess;
447                         span_err!(session, self.span_of_impl(impl_a), E0119,
448                                   "conflicting implementations for trait `{}`",
449                                   ty::item_path_str(self.crate_context.tcx, trait_def_id));
450                         if impl_b.krate == LOCAL_CRATE {
451                             span_note!(session, self.span_of_impl(impl_b),
452                                        "note conflicting implementation here");
453                         } else {
454                             let crate_store = &self.crate_context.tcx.sess.cstore;
455                             let cdata = crate_store.get_crate_data(impl_b.krate);
456                             span_note!(session, self.span_of_impl(impl_a),
457                                        "conflicting implementation in crate `{}`",
458                                        cdata.name);
459                         }
460                     }
461                 }
462             })
463         })
464     }
465
466     fn iter_impls_of_trait(&self, trait_def_id: DefId, f: |DefId|) {
467         self.iter_impls_of_trait_local(trait_def_id, |x| f(x));
468
469         if trait_def_id.krate == LOCAL_CRATE {
470             return;
471         }
472
473         let crate_store = &self.crate_context.tcx.sess.cstore;
474         csearch::each_implementation_for_trait(crate_store, trait_def_id, |impl_def_id| {
475             // Is this actually necessary?
476             let _ = lookup_item_type(self.crate_context.tcx, impl_def_id);
477             f(impl_def_id);
478         });
479     }
480
481     fn iter_impls_of_trait_local(&self, trait_def_id: DefId, f: |DefId|) {
482         match self.crate_context.tcx.trait_impls.borrow().find(&trait_def_id) {
483             Some(impls) => {
484                 for &impl_did in impls.borrow().iter() {
485                     f(impl_did);
486                 }
487             }
488             None => { /* no impls? */ }
489         }
490     }
491
492     fn polytypes_unify(&self,
493                        polytype_a: Polytype,
494                        polytype_b: Polytype)
495                        -> bool {
496         let universally_quantified_a =
497             self.universally_quantify_polytype(polytype_a);
498         let universally_quantified_b =
499             self.universally_quantify_polytype(polytype_b);
500
501         return self.can_unify_universally_quantified(
502             &universally_quantified_a, &universally_quantified_b) ||
503             self.can_unify_universally_quantified(
504             &universally_quantified_b, &universally_quantified_a);
505     }
506
507     // Converts a polytype to a monotype by replacing all parameters with
508     // type variables. Returns the monotype and the type variables created.
509     fn universally_quantify_polytype(&self, polytype: Polytype)
510                                      -> UniversalQuantificationResult
511     {
512         let substitutions =
513             self.inference_context.fresh_substs_for_type(DUMMY_SP,
514                                                          &polytype.generics);
515         let monotype = polytype.ty.subst(self.crate_context.tcx, &substitutions);
516
517         UniversalQuantificationResult {
518             monotype: monotype
519         }
520     }
521
522     fn can_unify_universally_quantified<'a>(&self,
523                                             a: &'a UniversalQuantificationResult,
524                                             b: &'a UniversalQuantificationResult)
525                                             -> bool
526     {
527         infer::can_mk_subty(&self.inference_context,
528                             a.monotype,
529                             b.monotype).is_ok()
530     }
531
532     fn get_self_type_for_implementation(&self, impl_did: DefId)
533                                         -> Polytype {
534         self.crate_context.tcx.tcache.borrow().get_copy(&impl_did)
535     }
536
537     // Privileged scope checking
538     fn check_privileged_scopes(&self, krate: &Crate) {
539         let mut visitor = PrivilegedScopeVisitor{ cc: self };
540         visit::walk_crate(&mut visitor, krate, ());
541     }
542
543     fn trait_ref_to_trait_def_id(&self, trait_ref: &TraitRef) -> DefId {
544         let def_map = &self.crate_context.tcx.def_map;
545         let trait_def = def_map.borrow().get_copy(&trait_ref.ref_id);
546         let trait_id = trait_def.def_id();
547         return trait_id;
548     }
549
550     /// For coherence, when we have `impl Type`, we need to guarantee that
551     /// `Type` is "local" to the crate. For our purposes, this means that it
552     /// must precisely name some nominal type defined in this crate.
553     fn ast_type_is_defined_in_local_crate(&self, original_type: &ast::Ty) -> bool {
554         match original_type.node {
555             TyPath(_, _, path_id) => {
556                 match self.crate_context.tcx.def_map.borrow().get_copy(&path_id) {
557                     DefTy(def_id) | DefStruct(def_id) => {
558                         if def_id.krate != LOCAL_CRATE {
559                             return false;
560                         }
561
562                         // Make sure that this type precisely names a nominal
563                         // type.
564                         match self.crate_context.tcx.map.find(def_id.node) {
565                             None => {
566                                 self.crate_context.tcx.sess.span_bug(
567                                     original_type.span,
568                                     "resolve didn't resolve this type?!");
569                             }
570                             Some(NodeItem(item)) => {
571                                 match item.node {
572                                     ItemStruct(..) | ItemEnum(..) => true,
573                                     _ => false,
574                                 }
575                             }
576                             Some(_) => false,
577                         }
578                     }
579                     _ => false
580                 }
581             }
582             _ => false
583         }
584     }
585
586     // Converts an implementation in the AST to a vector of items.
587     fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> {
588         match item.node {
589             ItemImpl(_, ref trait_refs, _, ref ast_items) => {
590                 let mut items: Vec<ImplOrTraitItemId> =
591                         ast_items.iter()
592                                  .map(|ast_item| {
593                             match *ast_item {
594                                 ast::MethodImplItem(ast_method) => {
595                                     MethodTraitItemId(
596                                         local_def(ast_method.id))
597                                 }
598                             }
599                         }).collect();
600
601                 for trait_ref in trait_refs.iter() {
602                     let ty_trait_ref = ty::node_id_to_trait_ref(
603                         self.crate_context.tcx,
604                         trait_ref.ref_id);
605
606                     self.instantiate_default_methods(local_def(item.id),
607                                                      &*ty_trait_ref,
608                                                      &mut items);
609                 }
610
611                 items
612             }
613             _ => {
614                 self.crate_context.tcx.sess.span_bug(item.span,
615                                                      "can't convert a non-impl to an impl");
616             }
617         }
618     }
619
620     fn span_of_impl(&self, impl_did: DefId) -> Span {
621         assert_eq!(impl_did.krate, LOCAL_CRATE);
622         self.crate_context.tcx.map.span(impl_did.node)
623     }
624
625     // External crate handling
626
627     fn add_external_impl(&self,
628                          impls_seen: &mut HashSet<DefId>,
629                          impl_def_id: DefId) {
630         let tcx = self.crate_context.tcx;
631         let impl_items = csearch::get_impl_items(&tcx.sess.cstore,
632                                                  impl_def_id);
633
634         // Make sure we don't visit the same implementation multiple times.
635         if !impls_seen.insert(impl_def_id) {
636             // Skip this one.
637             return
638         }
639         // Good. Continue.
640
641         let _ = lookup_item_type(tcx, impl_def_id);
642         let associated_traits = get_impl_trait(tcx, impl_def_id);
643
644         // Do a sanity check.
645         assert!(associated_traits.is_some());
646
647         // Record all the trait items.
648         for trait_ref in associated_traits.iter() {
649             self.add_trait_impl(trait_ref.def_id, impl_def_id);
650         }
651
652         // For any methods that use a default implementation, add them to
653         // the map. This is a bit unfortunate.
654         for item_def_id in impl_items.iter() {
655             let impl_item = ty::impl_or_trait_item(tcx, item_def_id.def_id());
656             match impl_item {
657                 ty::MethodTraitItem(ref method) => {
658                     for &source in method.provided_source.iter() {
659                         tcx.provided_method_sources
660                            .borrow_mut()
661                            .insert(item_def_id.def_id(), source);
662                     }
663                 }
664             }
665         }
666
667         tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
668     }
669
670     // Adds implementations and traits from external crates to the coherence
671     // info.
672     fn add_external_crates(&self) {
673         let mut impls_seen = HashSet::new();
674
675         let crate_store = &self.crate_context.tcx.sess.cstore;
676         crate_store.iter_crate_data(|crate_number, _crate_metadata| {
677             each_impl(crate_store, crate_number, |def_id| {
678                 assert_eq!(crate_number, def_id.krate);
679                 self.add_external_impl(&mut impls_seen, def_id)
680             })
681         })
682     }
683
684     //
685     // Destructors
686     //
687
688     fn populate_destructor_table(&self) {
689         let tcx = self.crate_context.tcx;
690         let drop_trait = match tcx.lang_items.drop_trait() {
691             Some(id) => id, None => { return }
692         };
693
694         let impl_items = tcx.impl_items.borrow();
695         let trait_impls = match tcx.trait_impls.borrow().find_copy(&drop_trait) {
696             None => return, // No types with (new-style) dtors present.
697             Some(found_impls) => found_impls
698         };
699
700         for &impl_did in trait_impls.borrow().iter() {
701             let items = impl_items.get(&impl_did);
702             if items.len() < 1 {
703                 // We'll error out later. For now, just don't ICE.
704                 continue;
705             }
706             let method_def_id = *items.get(0);
707
708             let self_type = self.get_self_type_for_implementation(impl_did);
709             match ty::get(self_type.ty).sty {
710                 ty::ty_enum(type_def_id, _) |
711                 ty::ty_struct(type_def_id, _) |
712                 ty::ty_unboxed_closure(type_def_id, _) => {
713                     tcx.destructor_for_type
714                        .borrow_mut()
715                        .insert(type_def_id, method_def_id.def_id());
716                     tcx.destructors
717                        .borrow_mut()
718                        .insert(method_def_id.def_id());
719                 }
720                 _ => {
721                     // Destructors only work on nominal types.
722                     if impl_did.krate == ast::LOCAL_CRATE {
723                         {
724                             match tcx.map.find(impl_did.node) {
725                                 Some(ast_map::NodeItem(item)) => {
726                                     span_err!(tcx.sess, item.span, E0120,
727                                         "the Drop trait may only be implemented on structures");
728                                 }
729                                 _ => {
730                                     tcx.sess.bug("didn't find impl in ast \
731                                                   map");
732                                 }
733                             }
734                         }
735                     } else {
736                         tcx.sess.bug("found external impl of Drop trait on \
737                                       something other than a struct");
738                     }
739                 }
740             }
741         }
742     }
743 }
744
745 pub fn make_substs_for_receiver_types(tcx: &ty::ctxt,
746                                       trait_ref: &ty::TraitRef,
747                                       method: &ty::Method)
748                                       -> subst::Substs
749 {
750     /*!
751      * Substitutes the values for the receiver's type parameters
752      * that are found in method, leaving the method's type parameters
753      * intact.
754      */
755
756     let meth_tps: Vec<ty::t> =
757         method.generics.types.get_slice(subst::FnSpace)
758               .iter()
759               .map(|def| ty::mk_param_from_def(tcx, def))
760               .collect();
761     let meth_regions: Vec<ty::Region> =
762         method.generics.regions.get_slice(subst::FnSpace)
763               .iter()
764               .map(|def| ty::ReEarlyBound(def.def_id.node, def.space,
765                                           def.index, def.name))
766               .collect();
767     trait_ref.substs.clone().with_method(meth_tps, meth_regions)
768 }
769
770 fn subst_receiver_types_in_method_ty(tcx: &ty::ctxt,
771                                      impl_id: ast::DefId,
772                                      impl_poly_type: &ty::Polytype,
773                                      trait_ref: &ty::TraitRef,
774                                      new_def_id: ast::DefId,
775                                      method: &ty::Method,
776                                      provided_source: Option<ast::DefId>)
777                                      -> ty::Method
778 {
779     let combined_substs = make_substs_for_receiver_types(tcx, trait_ref, method);
780
781     debug!("subst_receiver_types_in_method_ty: combined_substs={}",
782            combined_substs.repr(tcx));
783
784     let mut method_generics = method.generics.subst(tcx, &combined_substs);
785
786     // replace the type parameters declared on the trait with those
787     // from the impl
788     for &space in [subst::TypeSpace, subst::SelfSpace].iter() {
789         method_generics.types.replace(
790             space,
791             Vec::from_slice(impl_poly_type.generics.types.get_slice(space)));
792         method_generics.regions.replace(
793             space,
794             Vec::from_slice(impl_poly_type.generics.regions.get_slice(space)));
795     }
796
797     debug!("subst_receiver_types_in_method_ty: method_generics={}",
798            method_generics.repr(tcx));
799
800     let method_fty = method.fty.subst(tcx, &combined_substs);
801
802     debug!("subst_receiver_types_in_method_ty: method_ty={}",
803            method.fty.repr(tcx));
804
805     ty::Method::new(
806         method.ident,
807         method_generics,
808         method_fty,
809         method.explicit_self,
810         method.vis,
811         new_def_id,
812         ImplContainer(impl_id),
813         provided_source
814     )
815 }
816
817 pub fn check_coherence(crate_context: &CrateCtxt, krate: &Crate) {
818     CoherenceChecker {
819         crate_context: crate_context,
820         inference_context: new_infer_ctxt(crate_context.tcx),
821     }.check(krate);
822 }