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