1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Coherence phase
//
// The job of the coherence phase of typechecking is to ensure that each trait
// has at most one implementation for each type. Then we build a mapping from
// each trait in the system to its implementations.


use metadata::csearch::{each_impl, get_impl_trait, each_implementation_for_trait};
use metadata::csearch;
use middle::subst;
use middle::subst::{Substs};
use middle::ty::get;
use middle::ty::{ImplContainer, lookup_item_type};
use middle::ty::{t, ty_bool, ty_char, ty_bot, ty_box, ty_enum, ty_err};
use middle::ty::{ty_str, ty_vec, ty_float, ty_infer, ty_int, ty_nil};
use middle::ty::{ty_param, Polytype, ty_ptr};
use middle::ty::{ty_rptr, ty_struct, ty_trait, ty_tup};
use middle::ty::{ty_uint, ty_uniq, ty_bare_fn, ty_closure};
use middle::ty::type_is_ty_var;
use middle::subst::Subst;
use middle::ty;
use middle::typeck::CrateCtxt;
use middle::typeck::infer::combine::Combine;
use middle::typeck::infer::InferCtxt;
use middle::typeck::infer::{new_infer_ctxt, resolve_ivar, resolve_type};
use middle::typeck::infer;
use util::ppaux::Repr;
use middle::def::{DefStruct, DefTy};
use syntax::ast::{Crate, DefId};
use syntax::ast::{Item, ItemEnum, ItemImpl, ItemMod, ItemStruct};
use syntax::ast::{LOCAL_CRATE, TraitRef, TyPath};
use syntax::ast;
use syntax::ast_map::NodeItem;
use syntax::ast_map;
use syntax::ast_util::{local_def};
use syntax::codemap::{Span, DUMMY_SP};
use syntax::parse::token;
use syntax::visit;

use std::collections::HashSet;
use std::cell::RefCell;
use std::rc::Rc;

struct UniversalQuantificationResult {
    monotype: t
}

fn get_base_type(inference_context: &InferCtxt,
                 span: Span,
                 original_type: t)
                 -> Option<t> {
    let resolved_type;
    match resolve_type(inference_context,
                       Some(span),
                       original_type,
                       resolve_ivar) {
        Ok(resulting_type) if !type_is_ty_var(resulting_type) => {
            resolved_type = resulting_type;
        }
        _ => {
            inference_context.tcx.sess.span_fatal(span,
                                                  "the type of this value must be known in order \
                                                   to determine the base type");
        }
    }

    match get(resolved_type).sty {
        ty_enum(..) | ty_struct(..) => {
            debug!("(getting base type) found base type");
            Some(resolved_type)
        }
        // FIXME(14865) I would prefere to use `_` here, but that causes a
        // compiler error.
        ty_uniq(_) | ty_rptr(_, _) | ty_trait(..) if ty::type_is_trait(resolved_type) => {
            debug!("(getting base type) found base type (trait)");
            Some(resolved_type)
        }

        ty_nil | ty_bot | ty_bool | ty_char | ty_int(..) | ty_uint(..) | ty_float(..) |
        ty_str(..) | ty_vec(..) | ty_bare_fn(..) | ty_closure(..) | ty_tup(..) |
        ty_infer(..) | ty_param(..) | ty_err |
        ty_box(_) | ty_uniq(_) | ty_ptr(_) | ty_rptr(_, _) => {
            debug!("(getting base type) no base type; found {:?}",
                   get(original_type).sty);
            None
        }
        ty_trait(..) => fail!("should have been caught")
    }
}

fn type_is_defined_in_local_crate(tcx: &ty::ctxt, original_type: t) -> bool {
    /*!
     *
     * For coherence, when we have `impl Trait for Type`, we need to
     * guarantee that `Type` is "local" to the
     * crate.  For our purposes, this means that it must contain
     * some nominal type defined in this crate.
     */

    let mut found_nominal = false;
    ty::walk_ty(original_type, |t| {
        match get(t).sty {
            ty_enum(def_id, _) |
            ty_struct(def_id, _) => {
                if def_id.krate == ast::LOCAL_CRATE {
                    found_nominal = true;
                }
            }
            ty_trait(box ty::TyTrait { def_id, .. }) => {
                if def_id.krate == ast::LOCAL_CRATE {
                    found_nominal = true;
                }
            }
            ty_uniq(..) => {
                match tcx.lang_items.owned_box() {
                    Some(did) if did.krate == ast::LOCAL_CRATE => {
                        found_nominal = true;
                    }
                    _ => {}
                }
            }
            ty_box(..) => {
                match tcx.lang_items.gc() {
                    Some(did) if did.krate == ast::LOCAL_CRATE => {
                        found_nominal = true;
                    }
                    _ => {}
                }
            }

            _ => { }
        }
    });
    return found_nominal;
}

// Returns the def ID of the base type, if there is one.
fn get_base_type_def_id(inference_context: &InferCtxt,
                        span: Span,
                        original_type: t)
                        -> Option<DefId> {
    match get_base_type(inference_context, span, original_type) {
        None => None,
        Some(base_type) => {
            match get(base_type).sty {
                ty_enum(def_id, _) |
                ty_struct(def_id, _) => {
                    Some(def_id)
                }
                ty_rptr(_, ty::mt {ty, ..}) | ty_uniq(ty) => match ty::get(ty).sty {
                    ty_trait(box ty::TyTrait { def_id, .. }) => {
                        Some(def_id)
                    }
                    _ => {
                        fail!("get_base_type() returned a type that wasn't an \
                               enum, struct, or trait");
                    }
                },
                _ => {
                    fail!("get_base_type() returned a type that wasn't an \
                           enum, struct, or trait");
                }
            }
        }
    }
}

struct CoherenceChecker<'a> {
    crate_context: &'a CrateCtxt<'a>,
    inference_context: InferCtxt<'a>,
}

struct CoherenceCheckVisitor<'a> {
    cc: &'a CoherenceChecker<'a>
}

impl<'a> visit::Visitor<()> for CoherenceCheckVisitor<'a> {
    fn visit_item(&mut self, item: &Item, _: ()) {

        //debug!("(checking coherence) item '{}'", token::get_ident(item.ident));

        match item.node {
            ItemImpl(_, ref opt_trait, _, _) => {
                match opt_trait.clone() {
                    Some(opt_trait) => {
                        self.cc.check_implementation(item, [opt_trait]);
                    }
                    None => self.cc.check_implementation(item, [])
                }
            }
            _ => {
                // Nothing to do.
            }
        };

        visit::walk_item(self, item, ());
    }
}

struct PrivilegedScopeVisitor<'a> { cc: &'a CoherenceChecker<'a> }

impl<'a> visit::Visitor<()> for PrivilegedScopeVisitor<'a> {
    fn visit_item(&mut self, item: &Item, _: ()) {

        match item.node {
            ItemMod(ref module_) => {
                // Then visit the module items.
                visit::walk_mod(self, module_, ());
            }
            ItemImpl(_, None, ref ast_ty, _) => {
                if !self.cc.ast_type_is_defined_in_local_crate(&**ast_ty) {
                    // This is an error.
                    let session = &self.cc.crate_context.tcx.sess;
                    session.span_err(item.span,
                                     "cannot associate methods with a type outside the \
                                     crate the type is defined in; define and implement \
                                     a trait or new type instead");
                }
            }
            ItemImpl(_, Some(ref trait_ref), _, _) => {
                let tcx = self.cc.crate_context.tcx;
                // `for_ty` is `Type` in `impl Trait for Type`
                let for_ty = ty::node_id_to_type(tcx, item.id);
                if !type_is_defined_in_local_crate(tcx, for_ty) {
                    // This implementation is not in scope of its base
                    // type. This still might be OK if the trait is
                    // defined in the same crate.

                    let trait_def_id =
                        self.cc.trait_ref_to_trait_def_id(trait_ref);

                    if trait_def_id.krate != LOCAL_CRATE {
                        let session = &self.cc.crate_context.tcx.sess;
                        session.span_err(item.span,
                                "cannot provide an extension implementation \
                                where both trait and type are not defined in this crate");
                    }
                }

                visit::walk_item(self, item, ());
            }
            _ => {
                visit::walk_item(self, item, ());
            }
        }
    }
}

impl<'a> CoherenceChecker<'a> {
    fn check(&self, krate: &Crate) {
        // Check implementations and traits. This populates the tables
        // containing the inherent methods and extension methods. It also
        // builds up the trait inheritance table.
        let mut visitor = CoherenceCheckVisitor { cc: self };
        visit::walk_crate(&mut visitor, krate, ());

        // Check that there are no overlapping trait instances
        self.check_implementation_coherence();

        // Check whether traits with base types are in privileged scopes.
        self.check_privileged_scopes(krate);

        // Bring in external crates. It's fine for this to happen after the
        // coherence checks, because we ensure by construction that no errors
        // can happen at link time.
        self.add_external_crates();

        // Populate the table of destructors. It might seem a bit strange to
        // do this here, but it's actually the most convenient place, since
        // the coherence tables contain the trait -> type mappings.
        self.populate_destructor_table();
    }

    fn check_implementation(&self, item: &Item,
                            associated_traits: &[TraitRef]) {
        let tcx = self.crate_context.tcx;
        let impl_did = local_def(item.id);
        let self_type = ty::lookup_item_type(tcx, impl_did);

        // If there are no traits, then this implementation must have a
        // base type.

        if associated_traits.len() == 0 {
            debug!("(checking implementation) no associated traits for item '{}'",
                   token::get_ident(item.ident));

            match get_base_type_def_id(&self.inference_context,
                                       item.span,
                                       self_type.ty) {
                None => {
                    let session = &self.crate_context.tcx.sess;
                    session.span_err(item.span,
                                     "no base type found for inherent implementation; \
                                      implement a trait or new type instead");
                }
                Some(_) => {
                    // Nothing to do.
                }
            }
        }

        let impl_methods = self.create_impl_from_item(item);

        for associated_trait in associated_traits.iter() {
            let trait_ref = ty::node_id_to_trait_ref(
                self.crate_context.tcx, associated_trait.ref_id);
            debug!("(checking implementation) adding impl for trait '{}', item '{}'",
                   trait_ref.repr(self.crate_context.tcx),
                   token::get_ident(item.ident));

            self.add_trait_impl(trait_ref.def_id, impl_did);
        }

        // Add the implementation to the mapping from implementation to base
        // type def ID, if there is a base type for this implementation and
        // the implementation does not have any associated traits.
        match get_base_type_def_id(&self.inference_context,
                                   item.span,
                                   self_type.ty) {
            None => {
                // Nothing to do.
            }
            Some(base_type_def_id) => {
                // FIXME: Gather up default methods?
                if associated_traits.len() == 0 {
                    self.add_inherent_impl(base_type_def_id, impl_did);
                }
            }
        }

        tcx.impl_methods.borrow_mut().insert(impl_did, impl_methods);
    }

    // Creates default method IDs and performs type substitutions for an impl
    // and trait pair. Then, for each provided method in the trait, inserts a
    // `ProvidedMethodInfo` instance into the `provided_method_sources` map.
    fn instantiate_default_methods(&self,
                                   impl_id: DefId,
                                   trait_ref: &ty::TraitRef,
                                   all_methods: &mut Vec<DefId>) {
        let tcx = self.crate_context.tcx;
        debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})",
               impl_id, trait_ref.repr(tcx));

        let impl_poly_type = ty::lookup_item_type(tcx, impl_id);

        let prov = ty::provided_trait_methods(tcx, trait_ref.def_id);
        for trait_method in prov.iter() {
            // Synthesize an ID.
            let new_id = tcx.sess.next_node_id();
            let new_did = local_def(new_id);

            debug!("new_did={:?} trait_method={}", new_did, trait_method.repr(tcx));

            // Create substitutions for the various trait parameters.
            let new_method_ty =
                Rc::new(subst_receiver_types_in_method_ty(
                    tcx,
                    impl_id,
                    &impl_poly_type,
                    trait_ref,
                    new_did,
                    &**trait_method,
                    Some(trait_method.def_id)));

            debug!("new_method_ty={}", new_method_ty.repr(tcx));
            all_methods.push(new_did);

            // construct the polytype for the method based on the
            // method_ty.  it will have all the generics from the
            // impl, plus its own.
            let new_polytype = ty::Polytype {
                generics: new_method_ty.generics.clone(),
                ty: ty::mk_bare_fn(tcx, new_method_ty.fty.clone())
            };
            debug!("new_polytype={}", new_polytype.repr(tcx));

            tcx.tcache.borrow_mut().insert(new_did, new_polytype);
            tcx.methods.borrow_mut().insert(new_did, new_method_ty);

            // Pair the new synthesized ID up with the
            // ID of the method.
            self.crate_context.tcx.provided_method_sources.borrow_mut()
                .insert(new_did, trait_method.def_id);
        }
    }

    fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
        let tcx = self.crate_context.tcx;
        match tcx.inherent_impls.borrow().find(&base_def_id) {
            Some(implementation_list) => {
                implementation_list.borrow_mut().push(impl_def_id);
                return;
            }
            None => {}
        }

        tcx.inherent_impls.borrow_mut().insert(base_def_id,
                                               Rc::new(RefCell::new(vec!(impl_def_id))));
    }

    fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
        ty::record_trait_implementation(self.crate_context.tcx,
                                        base_def_id,
                                        impl_def_id);
    }

    fn check_implementation_coherence(&self) {
        for &trait_id in self.crate_context.tcx.trait_impls.borrow().keys() {
            self.check_implementation_coherence_of(trait_id);
        }
    }

    fn check_implementation_coherence_of(&self, trait_def_id: DefId) {
        // Unify pairs of polytypes.
        self.iter_impls_of_trait_local(trait_def_id, |impl_a| {
            let polytype_a =
                self.get_self_type_for_implementation(impl_a);

            // "We have an impl of trait <trait_def_id> for type <polytype_a>,
            // and that impl is <impl_a>"
            self.iter_impls_of_trait(trait_def_id, |impl_b| {

                // An impl is coherent with itself
                if impl_a != impl_b {
                    let polytype_b = self.get_self_type_for_implementation(
                            impl_b);

                    if self.polytypes_unify(polytype_a.clone(), polytype_b) {
                        let session = &self.crate_context.tcx.sess;
                        session.span_err(
                            self.span_of_impl(impl_a),
                            format!("conflicting implementations for trait `{}`",
                                    ty::item_path_str(
                                        self.crate_context.tcx,
                                        trait_def_id)).as_slice());
                        if impl_b.krate == LOCAL_CRATE {
                            session.span_note(self.span_of_impl(impl_b),
                                              "note conflicting implementation here");
                        } else {
                            let crate_store = &self.crate_context.tcx.sess.cstore;
                            let cdata = crate_store.get_crate_data(impl_b.krate);
                            session.note(
                                format!("conflicting implementation in crate \
                                         `{}`",
                                        cdata.name).as_slice());
                        }
                    }
                }
            })
        })
    }

    fn iter_impls_of_trait(&self, trait_def_id: DefId, f: |DefId|) {
        self.iter_impls_of_trait_local(trait_def_id, |x| f(x));

        if trait_def_id.krate == LOCAL_CRATE {
            return;
        }

        let crate_store = &self.crate_context.tcx.sess.cstore;
        csearch::each_implementation_for_trait(crate_store, trait_def_id, |impl_def_id| {
            // Is this actually necessary?
            let _ = lookup_item_type(self.crate_context.tcx, impl_def_id);
            f(impl_def_id);
        });
    }

    fn iter_impls_of_trait_local(&self, trait_def_id: DefId, f: |DefId|) {
        match self.crate_context.tcx.trait_impls.borrow().find(&trait_def_id) {
            Some(impls) => {
                for &impl_did in impls.borrow().iter() {
                    f(impl_did);
                }
            }
            None => { /* no impls? */ }
        }
    }

    fn polytypes_unify(&self,
                       polytype_a: Polytype,
                       polytype_b: Polytype)
                       -> bool {
        let universally_quantified_a =
            self.universally_quantify_polytype(polytype_a);
        let universally_quantified_b =
            self.universally_quantify_polytype(polytype_b);

        return self.can_unify_universally_quantified(
            &universally_quantified_a, &universally_quantified_b) ||
            self.can_unify_universally_quantified(
            &universally_quantified_b, &universally_quantified_a);
    }

    // Converts a polytype to a monotype by replacing all parameters with
    // type variables. Returns the monotype and the type variables created.
    fn universally_quantify_polytype(&self, polytype: Polytype)
                                     -> UniversalQuantificationResult
    {
        let substitutions =
            self.inference_context.fresh_substs_for_type(DUMMY_SP,
                                                         &polytype.generics);
        let monotype = polytype.ty.subst(self.crate_context.tcx, &substitutions);

        UniversalQuantificationResult {
            monotype: monotype
        }
    }

    fn can_unify_universally_quantified<'a>(&self,
                                            a: &'a UniversalQuantificationResult,
                                            b: &'a UniversalQuantificationResult)
                                            -> bool
    {
        infer::can_mk_subty(&self.inference_context,
                            a.monotype,
                            b.monotype).is_ok()
    }

    fn get_self_type_for_implementation(&self, impl_did: DefId)
                                        -> Polytype {
        self.crate_context.tcx.tcache.borrow().get_copy(&impl_did)
    }

    // Privileged scope checking
    fn check_privileged_scopes(&self, krate: &Crate) {
        let mut visitor = PrivilegedScopeVisitor{ cc: self };
        visit::walk_crate(&mut visitor, krate, ());
    }

    fn trait_ref_to_trait_def_id(&self, trait_ref: &TraitRef) -> DefId {
        let def_map = &self.crate_context.tcx.def_map;
        let trait_def = def_map.borrow().get_copy(&trait_ref.ref_id);
        let trait_id = trait_def.def_id();
        return trait_id;
    }

    /// For coherence, when we have `impl Type`, we need to guarantee that
    /// `Type` is "local" to the crate. For our purposes, this means that it
    /// must precisely name some nominal type defined in this crate.
    fn ast_type_is_defined_in_local_crate(&self, original_type: &ast::Ty) -> bool {
        match original_type.node {
            TyPath(_, _, path_id) => {
                match self.crate_context.tcx.def_map.borrow().get_copy(&path_id) {
                    DefTy(def_id) | DefStruct(def_id) => {
                        if def_id.krate != LOCAL_CRATE {
                            return false;
                        }

                        // Make sure that this type precisely names a nominal
                        // type.
                        match self.crate_context.tcx.map.find(def_id.node) {
                            None => {
                                self.crate_context.tcx.sess.span_bug(
                                    original_type.span,
                                    "resolve didn't resolve this type?!");
                            }
                            Some(NodeItem(item)) => {
                                match item.node {
                                    ItemStruct(..) | ItemEnum(..) => true,
                                    _ => false,
                                }
                            }
                            Some(_) => false,
                        }
                    }
                    _ => false
                }
            }
            _ => false
        }
    }

    // Converts an implementation in the AST to a vector of methods.
    fn create_impl_from_item(&self, item: &Item) -> Vec<DefId> {
        match item.node {
            ItemImpl(_, ref trait_refs, _, ref ast_methods) => {
                let mut methods: Vec<DefId> = ast_methods.iter().map(|ast_method| {
                    local_def(ast_method.id)
                }).collect();

                for trait_ref in trait_refs.iter() {
                    let ty_trait_ref = ty::node_id_to_trait_ref(
                        self.crate_context.tcx,
                        trait_ref.ref_id);

                    self.instantiate_default_methods(local_def(item.id),
                                                     &*ty_trait_ref,
                                                     &mut methods);
                }

                methods
            }
            _ => {
                self.crate_context.tcx.sess.span_bug(item.span,
                                                     "can't convert a non-impl to an impl");
            }
        }
    }

    fn span_of_impl(&self, impl_did: DefId) -> Span {
        assert_eq!(impl_did.krate, LOCAL_CRATE);
        self.crate_context.tcx.map.span(impl_did.node)
    }

    // External crate handling

    fn add_external_impl(&self,
                         impls_seen: &mut HashSet<DefId>,
                         impl_def_id: DefId) {
        let tcx = self.crate_context.tcx;
        let methods = csearch::get_impl_methods(&tcx.sess.cstore, impl_def_id);

        // Make sure we don't visit the same implementation multiple times.
        if !impls_seen.insert(impl_def_id) {
            // Skip this one.
            return
        }
        // Good. Continue.

        let _ = lookup_item_type(tcx, impl_def_id);
        let associated_traits = get_impl_trait(tcx, impl_def_id);

        // Do a sanity check.
        assert!(associated_traits.is_some());

        // Record all the trait methods.
        for trait_ref in associated_traits.iter() {
            self.add_trait_impl(trait_ref.def_id, impl_def_id);
        }

        // For any methods that use a default implementation, add them to
        // the map. This is a bit unfortunate.
        for &method_def_id in methods.iter() {
            for &source in ty::method(tcx, method_def_id).provided_source.iter() {
                tcx.provided_method_sources.borrow_mut().insert(method_def_id, source);
            }
        }

        tcx.impl_methods.borrow_mut().insert(impl_def_id, methods);
    }

    // Adds implementations and traits from external crates to the coherence
    // info.
    fn add_external_crates(&self) {
        let mut impls_seen = HashSet::new();

        let crate_store = &self.crate_context.tcx.sess.cstore;
        crate_store.iter_crate_data(|crate_number, _crate_metadata| {
            each_impl(crate_store, crate_number, |def_id| {
                assert_eq!(crate_number, def_id.krate);
                self.add_external_impl(&mut impls_seen, def_id)
            })
        })
    }

    //
    // Destructors
    //

    fn populate_destructor_table(&self) {
        let tcx = self.crate_context.tcx;
        let drop_trait = match tcx.lang_items.drop_trait() {
            Some(id) => id, None => { return }
        };

        let impl_methods = tcx.impl_methods.borrow();
        let trait_impls = match tcx.trait_impls.borrow().find_copy(&drop_trait) {
            None => return, // No types with (new-style) dtors present.
            Some(found_impls) => found_impls
        };

        for &impl_did in trait_impls.borrow().iter() {
            let methods = impl_methods.get(&impl_did);
            if methods.len() < 1 {
                // We'll error out later. For now, just don't ICE.
                continue;
            }
            let method_def_id = *methods.get(0);

            let self_type = self.get_self_type_for_implementation(impl_did);
            match ty::get(self_type.ty).sty {
                ty::ty_enum(type_def_id, _) |
                ty::ty_struct(type_def_id, _) => {
                    tcx.destructor_for_type.borrow_mut().insert(type_def_id,
                                                                method_def_id);
                    tcx.destructors.borrow_mut().insert(method_def_id);
                }
                _ => {
                    // Destructors only work on nominal types.
                    if impl_did.krate == ast::LOCAL_CRATE {
                        {
                            match tcx.map.find(impl_did.node) {
                                Some(ast_map::NodeItem(item)) => {
                                    tcx.sess.span_err((*item).span,
                                                      "the Drop trait may \
                                                       only be implemented \
                                                       on structures");
                                }
                                _ => {
                                    tcx.sess.bug("didn't find impl in ast \
                                                  map");
                                }
                            }
                        }
                    } else {
                        tcx.sess.bug("found external impl of Drop trait on \
                                      something other than a struct");
                    }
                }
            }
        }
    }
}

pub fn make_substs_for_receiver_types(tcx: &ty::ctxt,
                                      trait_ref: &ty::TraitRef,
                                      method: &ty::Method)
                                      -> subst::Substs
{
    /*!
     * Substitutes the values for the receiver's type parameters
     * that are found in method, leaving the method's type parameters
     * intact.
     */

    let meth_tps: Vec<ty::t> =
        method.generics.types.get_vec(subst::FnSpace)
              .iter()
              .map(|def| ty::mk_param_from_def(tcx, def))
              .collect();
    let meth_regions: Vec<ty::Region> =
        method.generics.regions.get_vec(subst::FnSpace)
              .iter()
              .map(|def| ty::ReEarlyBound(def.def_id.node, def.space,
                                          def.index, def.name))
              .collect();
    trait_ref.substs.clone().with_method(meth_tps, meth_regions)
}

fn subst_receiver_types_in_method_ty(tcx: &ty::ctxt,
                                     impl_id: ast::DefId,
                                     impl_poly_type: &ty::Polytype,
                                     trait_ref: &ty::TraitRef,
                                     new_def_id: ast::DefId,
                                     method: &ty::Method,
                                     provided_source: Option<ast::DefId>)
                                     -> ty::Method
{
    let combined_substs = make_substs_for_receiver_types(tcx, trait_ref, method);

    debug!("subst_receiver_types_in_method_ty: combined_substs={}",
           combined_substs.repr(tcx));

    let mut method_generics = method.generics.subst(tcx, &combined_substs);

    // replace the type parameters declared on the trait with those
    // from the impl
    for &space in [subst::TypeSpace, subst::SelfSpace].iter() {
        *method_generics.types.get_mut_vec(space) =
            impl_poly_type.generics.types.get_vec(space).clone();
        *method_generics.regions.get_mut_vec(space) =
            impl_poly_type.generics.regions.get_vec(space).clone();
    }

    debug!("subst_receiver_types_in_method_ty: method_generics={}",
           method_generics.repr(tcx));

    let method_fty = method.fty.subst(tcx, &combined_substs);

    debug!("subst_receiver_types_in_method_ty: method_ty={}",
           method.fty.repr(tcx));

    ty::Method::new(
        method.ident,
        method_generics,
        method_fty,
        method.explicit_self,
        method.vis,
        new_def_id,
        ImplContainer(impl_id),
        provided_source
    )
}

pub fn check_coherence(crate_context: &CrateCtxt, krate: &Crate) {
    CoherenceChecker {
        crate_context: crate_context,
        inference_context: new_infer_ctxt(crate_context.tcx),
    }.check(krate);
}