]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/typeck/check/method.rs
Doc says to avoid mixing allocator instead of forbiding it
[rust.git] / src / librustc / middle / typeck / check / method.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
12
13 # Method lookup
14
15 Method lookup can be rather complex due to the interaction of a number
16 of factors, such as self types, autoderef, trait lookup, etc.  The
17 algorithm is divided into two parts: candidate collection and
18 candidate selection.
19
20 ## Candidate collection
21
22 A `Candidate` is a method item that might plausibly be the method
23 being invoked.  Candidates are grouped into two kinds, inherent and
24 extension.  Inherent candidates are those that are derived from the
25 type of the receiver itself.  So, if you have a receiver of some
26 nominal type `Foo` (e.g., a struct), any methods defined within an
27 impl like `impl Foo` are inherent methods.  Nothing needs to be
28 imported to use an inherent method, they are associated with the type
29 itself (note that inherent impls can only be defined in the same
30 module as the type itself).
31
32 Inherent candidates are not always derived from impls.  If you have a
33 trait instance, such as a value of type `Box<ToString>`, then the trait
34 methods (`to_string()`, in this case) are inherently associated with it.
35 Another case is type parameters, in which case the methods of their
36 bounds are inherent.
37
38 Extension candidates are derived from imported traits.  If I have the
39 trait `ToString` imported, and I call `to_string()` on a value of type `T`,
40 then we will go off to find out whether there is an impl of `ToString`
41 for `T`.  These kinds of method calls are called "extension methods".
42 They can be defined in any module, not only the one that defined `T`.
43 Furthermore, you must import the trait to call such a method.
44
45 For better or worse, we currently give weight to inherent methods over
46 extension methods during candidate selection (below).
47
48 ## Candidate selection
49
50 Once we know the set of candidates, we can go off and try to select
51 which one is actually being called.  We do this by taking the type of
52 the receiver, let's call it R, and checking whether it matches against
53 the expected receiver type for each of the collected candidates.  We
54 first check for inherent candidates and see whether we get exactly one
55 match (zero means keep searching, more than one is an error).  If so,
56 we return that as the candidate.  Otherwise we search the extension
57 candidates in the same way.
58
59 If find no matching candidate at all, we proceed to auto-deref the
60 receiver type and search again.  We keep doing that until we cannot
61 auto-deref any longer.  At each step, we also check for candidates
62 based on "autoptr", which if the current type is `T`, checks for `&mut
63 T`, `&const T`, and `&T` receivers.  Finally, at the very end, we will
64 also try autoslice, which converts `~[]` to `&[]` (there is no point
65 at trying autoslice earlier, because no autoderefable type is also
66 sliceable).
67
68 ## Why two phases?
69
70 You might wonder why we first collect the candidates and then select.
71 Both the inherent candidate collection and the candidate selection
72 proceed by progressively deref'ing the receiver type, after all.  The
73 answer is that two phases are needed to elegantly deal with explicit
74 self.  After all, if there is an impl for the type `Foo`, it can
75 define a method with the type `Box<self>`, which means that it expects a
76 receiver of type `Box<Foo>`.  If we have a receiver of type `Box<Foo>`, but we
77 waited to search for that impl until we have deref'd the `Box` away and
78 obtained the type `Foo`, we would never match this method.
79
80 */
81
82
83 use middle::subst;
84 use middle::subst::Subst;
85 use middle::ty::*;
86 use middle::ty;
87 use middle::typeck::astconv::AstConv;
88 use middle::typeck::check::{FnCtxt, PreferMutLvalue, impl_self_ty};
89 use middle::typeck::check;
90 use middle::typeck::infer;
91 use middle::typeck::MethodCallee;
92 use middle::typeck::{MethodOrigin, MethodParam};
93 use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure, MethodObject};
94 use middle::typeck::{param_index};
95 use middle::typeck::check::regionmanip::replace_late_bound_regions_in_fn_sig;
96 use middle::typeck::TypeAndSubsts;
97 use util::common::indenter;
98 use util::ppaux;
99 use util::ppaux::Repr;
100
101 use std::collections::HashSet;
102 use std::rc::Rc;
103 use syntax::ast::{DefId, MutImmutable, MutMutable};
104 use syntax::ast;
105 use syntax::codemap::Span;
106 use syntax::parse::token;
107
108 #[deriving(PartialEq)]
109 pub enum CheckTraitsFlag {
110     CheckTraitsOnly,
111     CheckTraitsAndInherentMethods,
112 }
113
114 #[deriving(PartialEq)]
115 pub enum AutoderefReceiverFlag {
116     AutoderefReceiver,
117     DontAutoderefReceiver,
118 }
119
120 #[deriving(PartialEq)]
121 pub enum StaticMethodsFlag {
122     ReportStaticMethods,
123     IgnoreStaticMethods,
124 }
125
126 pub fn lookup<'a, 'tcx>(
127         fcx: &'a FnCtxt<'a, 'tcx>,
128
129         // In a call `a.b::<X, Y, ...>(...)`:
130         expr: &ast::Expr,                   // The expression `a.b(...)`.
131         self_expr: &'a ast::Expr,           // The expression `a`.
132         m_name: ast::Name,                  // The name `b`.
133         self_ty: ty::t,                     // The type of `a`.
134         supplied_tps: &'a [ty::t],          // The list of types X, Y, ... .
135         deref_args: check::DerefArgs,       // Whether we autopointer first.
136         check_traits: CheckTraitsFlag,      // Whether we check traits only.
137         autoderef_receiver: AutoderefReceiverFlag,
138         report_statics: StaticMethodsFlag)
139      -> Option<MethodCallee> {
140     let mut lcx = LookupContext {
141         fcx: fcx,
142         span: expr.span,
143         self_expr: Some(self_expr),
144         m_name: m_name,
145         supplied_tps: supplied_tps,
146         impl_dups: HashSet::new(),
147         inherent_candidates: Vec::new(),
148         extension_candidates: Vec::new(),
149         deref_args: deref_args,
150         check_traits: check_traits,
151         autoderef_receiver: autoderef_receiver,
152         report_statics: report_statics,
153     };
154
155     debug!("method lookup(self_ty={}, expr={}, self_expr={})",
156            self_ty.repr(fcx.tcx()), expr.repr(fcx.tcx()),
157            self_expr.repr(fcx.tcx()));
158
159     debug!("searching inherent candidates");
160     lcx.push_inherent_candidates(self_ty);
161     let mme = lcx.search(self_ty);
162     if mme.is_some() {
163         return mme;
164     }
165
166     debug!("searching extension candidates");
167     lcx.reset_candidates();
168     lcx.push_bound_candidates(self_ty, None);
169     lcx.push_extension_candidates(expr.id);
170     lcx.search(self_ty)
171 }
172
173 pub fn lookup_in_trait<'a, 'tcx>(
174         fcx: &'a FnCtxt<'a, 'tcx>,
175
176         // In a call `a.b::<X, Y, ...>(...)`:
177         span: Span,                         // The expression `a.b(...)`'s span.
178         self_expr: Option<&'a ast::Expr>,   // The expression `a`, if available.
179         m_name: ast::Name,                  // The name `b`.
180         trait_did: DefId,                   // The trait to limit the lookup to.
181         self_ty: ty::t,                     // The type of `a`.
182         supplied_tps: &'a [ty::t],          // The list of types X, Y, ... .
183         autoderef_receiver: AutoderefReceiverFlag,
184         report_statics: StaticMethodsFlag)
185      -> Option<MethodCallee> {
186     let mut lcx = LookupContext {
187         fcx: fcx,
188         span: span,
189         self_expr: self_expr,
190         m_name: m_name,
191         supplied_tps: supplied_tps,
192         impl_dups: HashSet::new(),
193         inherent_candidates: Vec::new(),
194         extension_candidates: Vec::new(),
195         deref_args: check::DoDerefArgs,
196         check_traits: CheckTraitsOnly,
197         autoderef_receiver: autoderef_receiver,
198         report_statics: report_statics,
199     };
200
201     debug!("method lookup_in_trait(self_ty={}, self_expr={})",
202            self_ty.repr(fcx.tcx()), self_expr.map(|e| e.repr(fcx.tcx())));
203
204     lcx.push_bound_candidates(self_ty, Some(trait_did));
205     lcx.push_extension_candidate(trait_did);
206     lcx.search(self_ty)
207 }
208
209 // Determine the index of a method in the list of all methods belonging
210 // to a trait and its supertraits.
211 fn get_method_index(tcx: &ty::ctxt,
212                     trait_ref: &TraitRef,
213                     subtrait: Rc<TraitRef>,
214                     n_method: uint) -> uint {
215     // We need to figure the "real index" of the method in a
216     // listing of all the methods of an object. We do this by
217     // iterating down the supertraits of the object's trait until
218     // we find the trait the method came from, counting up the
219     // methods from them.
220     let mut method_count = 0;
221     ty::each_bound_trait_and_supertraits(tcx, &[subtrait], |bound_ref| {
222         if bound_ref.def_id == trait_ref.def_id {
223             false
224         } else {
225             let trait_items = ty::trait_items(tcx, bound_ref.def_id);
226             for trait_item in trait_items.iter() {
227                 match *trait_item {
228                     ty::MethodTraitItem(_) => method_count += 1,
229                 }
230             }
231             true
232         }
233     });
234     method_count + n_method
235 }
236
237 fn construct_transformed_self_ty_for_object(
238     tcx: &ty::ctxt,
239     span: Span,
240     trait_def_id: ast::DefId,
241     rcvr_substs: &subst::Substs,
242     rcvr_bounds: ty::ExistentialBounds,
243     method_ty: &ty::Method)
244     -> ty::t
245 {
246     /*!
247      * This is a bit tricky. We have a match against a trait method
248      * being invoked on an object, and we want to generate the
249      * self-type. As an example, consider a trait
250      *
251      *     trait Foo {
252      *         fn r_method<'a>(&'a self);
253      *         fn u_method(Box<self>);
254      *     }
255      *
256      * Now, assuming that `r_method` is being called, we want the
257      * result to be `&'a Foo`. Assuming that `u_method` is being
258      * called, we want the result to be `Box<Foo>`. Of course,
259      * this transformation has already been done as part of
260      * `method_ty.fty.sig.inputs[0]`, but there the type
261      * is expressed in terms of `Self` (i.e., `&'a Self`, `Box<Self>`).
262      * Because objects are not standalone types, we can't just substitute
263      * `s/Self/Foo/`, so we must instead perform this kind of hokey
264      * match below.
265      */
266
267     let mut obj_substs = rcvr_substs.clone();
268
269     // The subst we get in has Err as the "Self" type. For an object
270     // type, we don't put any type into the Self paramspace, so let's
271     // make a copy of rcvr_substs that has the Self paramspace empty.
272     obj_substs.types.pop(subst::SelfSpace).unwrap();
273
274     match method_ty.explicit_self {
275         StaticExplicitSelfCategory => {
276             tcx.sess.span_bug(span, "static method for object type receiver");
277         }
278         ByValueExplicitSelfCategory => {
279             let tr = ty::mk_trait(tcx, trait_def_id, obj_substs, rcvr_bounds);
280             ty::mk_uniq(tcx, tr)
281         }
282         ByReferenceExplicitSelfCategory(..) | ByBoxExplicitSelfCategory => {
283             let transformed_self_ty = *method_ty.fty.sig.inputs.get(0);
284             match ty::get(transformed_self_ty).sty {
285                 ty::ty_rptr(r, mt) => { // must be SelfRegion
286                     let r = r.subst(tcx, rcvr_substs); // handle Early-Bound lifetime
287                     let tr = ty::mk_trait(tcx, trait_def_id, obj_substs,
288                                           rcvr_bounds);
289                     ty::mk_rptr(tcx, r, ty::mt{ ty: tr, mutbl: mt.mutbl })
290                 }
291                 ty::ty_uniq(_) => { // must be SelfUniq
292                     let tr = ty::mk_trait(tcx, trait_def_id, obj_substs,
293                                           rcvr_bounds);
294                     ty::mk_uniq(tcx, tr)
295                 }
296                 _ => {
297                     tcx.sess.span_bug(span,
298                         format!("'impossible' transformed_self_ty: {}",
299                                 transformed_self_ty.repr(tcx)).as_slice());
300                 }
301             }
302         }
303     }
304 }
305
306 struct LookupContext<'a, 'tcx: 'a> {
307     fcx: &'a FnCtxt<'a, 'tcx>,
308     span: Span,
309
310     // The receiver to the method call. Only `None` in the case of
311     // an overloaded autoderef, where the receiver may be an intermediate
312     // state like "the expression `x` when it has been autoderef'd
313     // twice already".
314     self_expr: Option<&'a ast::Expr>,
315
316     m_name: ast::Name,
317     supplied_tps: &'a [ty::t],
318     impl_dups: HashSet<DefId>,
319     inherent_candidates: Vec<Candidate>,
320     extension_candidates: Vec<Candidate>,
321     deref_args: check::DerefArgs,
322     check_traits: CheckTraitsFlag,
323     autoderef_receiver: AutoderefReceiverFlag,
324     report_statics: StaticMethodsFlag,
325 }
326
327 /**
328  * A potential method that might be called, assuming the receiver
329  * is of a suitable type.
330  */
331 #[deriving(Clone)]
332 struct Candidate {
333     rcvr_match_condition: RcvrMatchCondition,
334     rcvr_substs: subst::Substs,
335     method_ty: Rc<ty::Method>,
336     origin: MethodOrigin,
337 }
338
339 /// This type represents the conditions under which the receiver is
340 /// considered to "match" a given method candidate. Typically the test
341 /// is whether the receiver is of a particular type. However, this
342 /// type is the type of the receiver *after accounting for the
343 /// method's self type* (e.g., if the method is an `Box<self>` method, we
344 /// have *already verified* that the receiver is of some type `Box<T>` and
345 /// now we must check that the type `T` is correct).  Unfortunately,
346 /// because traits are not types, this is a pain to do.
347 #[deriving(Clone)]
348 pub enum RcvrMatchCondition {
349     RcvrMatchesIfObject(ast::DefId),
350     RcvrMatchesIfSubtype(ty::t),
351     RcvrMatchesIfEqtype(ty::t)
352 }
353
354 impl<'a, 'tcx> LookupContext<'a, 'tcx> {
355     fn search(&self, self_ty: ty::t) -> Option<MethodCallee> {
356         let span = self.self_expr.map_or(self.span, |e| e.span);
357         let self_expr_id = self.self_expr.map(|e| e.id);
358
359         let (_, _, result) =
360             check::autoderef(
361                 self.fcx, span, self_ty, self_expr_id, PreferMutLvalue,
362                 |self_ty, autoderefs| self.search_step(self_ty, autoderefs));
363
364         match result {
365             Some(Some(result)) => Some(result),
366             _ => None
367         }
368     }
369
370     fn search_step(&self,
371                    self_ty: ty::t,
372                    autoderefs: uint)
373                    -> Option<Option<MethodCallee>> {
374         debug!("search_step: self_ty={} autoderefs={}",
375                self.ty_to_string(self_ty), autoderefs);
376
377         match self.deref_args {
378             check::DontDerefArgs => {
379                 match self.search_for_autoderefd_method(self_ty, autoderefs) {
380                     Some(result) => return Some(Some(result)),
381                     None => {}
382                 }
383
384                 match self.search_for_autoptrd_method(self_ty, autoderefs) {
385                     Some(result) => return Some(Some(result)),
386                     None => {}
387                 }
388             }
389             check::DoDerefArgs => {
390                 match self.search_for_autoptrd_method(self_ty, autoderefs) {
391                     Some(result) => return Some(Some(result)),
392                     None => {}
393                 }
394
395                 match self.search_for_autoderefd_method(self_ty, autoderefs) {
396                     Some(result) => return Some(Some(result)),
397                     None => {}
398                 }
399             }
400         }
401
402         // If we are searching for an overloaded deref, no
403         // need to try coercing a `~[T]` to an `&[T]` and
404         // searching for an overloaded deref on *that*.
405         if !self.is_overloaded_deref() {
406             match self.search_for_autofatptrd_method(self_ty, autoderefs) {
407                 Some(result) => return Some(Some(result)),
408                 None => {}
409             }
410         }
411
412         // Don't autoderef if we aren't supposed to.
413         if self.autoderef_receiver == DontAutoderefReceiver {
414             Some(None)
415         } else {
416             None
417         }
418     }
419
420     fn is_overloaded_deref(&self) -> bool {
421         self.self_expr.is_none()
422     }
423
424     // ______________________________________________________________________
425     // Candidate collection (see comment at start of file)
426
427     fn reset_candidates(&mut self) {
428         self.inherent_candidates = Vec::new();
429         self.extension_candidates = Vec::new();
430     }
431
432     fn push_inherent_candidates(&mut self, self_ty: ty::t) {
433         /*!
434          * Collect all inherent candidates into
435          * `self.inherent_candidates`.  See comment at the start of
436          * the file.  To find the inherent candidates, we repeatedly
437          * deref the self-ty to find the "base-type".  So, for
438          * example, if the receiver is Box<Box<C>> where `C` is a struct type,
439          * we'll want to find the inherent impls for `C`.
440          */
441
442         let span = self.self_expr.map_or(self.span, |e| e.span);
443         check::autoderef(self.fcx, span, self_ty, None, PreferMutLvalue, |self_ty, _| {
444             match get(self_ty).sty {
445                 ty_trait(box TyTrait { def_id, ref substs, bounds, .. }) => {
446                     self.push_inherent_candidates_from_object(
447                         def_id, substs, bounds);
448                     self.push_inherent_impl_candidates_for_type(def_id);
449                 }
450                 ty_enum(did, _) |
451                 ty_struct(did, _) |
452                 ty_unboxed_closure(did, _) => {
453                     if self.check_traits == CheckTraitsAndInherentMethods {
454                         self.push_inherent_impl_candidates_for_type(did);
455                     }
456                 }
457                 _ => { /* No inherent methods in these types */ }
458             }
459
460             // Don't autoderef if we aren't supposed to.
461             if self.autoderef_receiver == DontAutoderefReceiver {
462                 Some(())
463             } else {
464                 None
465             }
466         });
467     }
468
469     fn push_bound_candidates(&mut self, self_ty: ty::t, restrict_to: Option<DefId>) {
470         let span = self.self_expr.map_or(self.span, |e| e.span);
471         check::autoderef(self.fcx, span, self_ty, None, PreferMutLvalue, |self_ty, _| {
472             match get(self_ty).sty {
473                 ty_param(p) => {
474                     self.push_inherent_candidates_from_param(self_ty, restrict_to, p);
475                 }
476                 ty_unboxed_closure(closure_did, _) => {
477                     self.push_unboxed_closure_call_candidates_if_applicable(
478                         closure_did);
479                 }
480                 _ => { /* No bound methods in these types */ }
481             }
482
483             // Don't autoderef if we aren't supposed to.
484             if self.autoderef_receiver == DontAutoderefReceiver {
485                 Some(())
486             } else {
487                 None
488             }
489         });
490     }
491
492     fn push_extension_candidate(&mut self, trait_did: DefId) {
493         ty::populate_implementations_for_trait_if_necessary(self.tcx(), trait_did);
494
495         // Look for explicit implementations.
496         let impl_items = self.tcx().impl_items.borrow();
497         for impl_infos in self.tcx().trait_impls.borrow().find(&trait_did).iter() {
498             for impl_did in impl_infos.borrow().iter() {
499                 let items = impl_items.get(impl_did);
500                 self.push_candidates_from_impl(*impl_did,
501                                                items.as_slice(),
502                                                true);
503             }
504         }
505     }
506
507     fn push_extension_candidates(&mut self, expr_id: ast::NodeId) {
508         // If the method being called is associated with a trait, then
509         // find all the impls of that trait.  Each of those are
510         // candidates.
511         let opt_applicable_traits = self.fcx.ccx.trait_map.find(&expr_id);
512         for applicable_traits in opt_applicable_traits.move_iter() {
513             for trait_did in applicable_traits.iter() {
514                 debug!("push_extension_candidates() found trait: {}",
515                        if trait_did.krate == ast::LOCAL_CRATE {
516                            self.fcx.ccx.tcx.map.node_to_string(trait_did.node)
517                        } else {
518                            "(external)".to_string()
519                        });
520                 self.push_extension_candidate(*trait_did);
521             }
522         }
523     }
524
525     fn push_unboxed_closure_call_candidate_if_applicable(
526             &mut self,
527             trait_did: DefId,
528             closure_did: DefId,
529             closure_function_type: &ClosureTy) {
530         let trait_item = ty::trait_items(self.tcx(), trait_did).get(0)
531                                                                .clone();
532         let method = match trait_item {
533             ty::MethodTraitItem(method) => method,
534         };
535
536         // Make sure it has the right name!
537         if method.ident.name != self.m_name {
538             return
539         }
540
541         let vcx = self.fcx.vtable_context();
542
543         // Get the tupled type of the arguments.
544         let arguments_type = *closure_function_type.sig.inputs.get(0);
545         let return_type = closure_function_type.sig.output;
546
547         let closure_region =
548             vcx.infcx.next_region_var(infer::MiscVariable(self.span));
549         let unboxed_closure_type = ty::mk_unboxed_closure(self.tcx(),
550                                                           closure_did,
551                                                           closure_region);
552         self.extension_candidates.push(Candidate {
553             rcvr_match_condition:
554                 RcvrMatchesIfSubtype(unboxed_closure_type),
555             rcvr_substs: subst::Substs::new_trait(
556                 vec![arguments_type, return_type],
557                 vec![],
558                 *vcx.infcx.next_ty_vars(1).get(0)),
559             method_ty: method,
560             origin: MethodStaticUnboxedClosure(closure_did),
561         });
562     }
563
564     fn push_unboxed_closure_call_candidates_if_applicable(
565             &mut self,
566             closure_did: DefId) {
567         match self.tcx().unboxed_closures.borrow().find(&closure_did) {
568             None => {}  // Fall through to try inherited.
569             Some(closure) => {
570                 let tcx = self.tcx();
571                 self.push_unboxed_closure_call_candidate_if_applicable(
572                     closure.kind.trait_did(tcx),
573                     closure_did,
574                     &closure.closure_type);
575                 return
576             }
577         }
578
579         match self.fcx.inh.unboxed_closures.borrow().find(&closure_did) {
580             Some(closure) => {
581                 let tcx = self.tcx();
582                 self.push_unboxed_closure_call_candidate_if_applicable(
583                     closure.kind.trait_did(tcx),
584                     closure_did,
585                     &closure.closure_type);
586                 return
587             }
588             None => {}
589         }
590
591         self.tcx().sess.bug("didn't find unboxed closure type in tcx map or \
592                              inherited map, so there")
593     }
594
595     fn push_inherent_candidates_from_object(&mut self,
596                                             did: DefId,
597                                             substs: &subst::Substs,
598                                             bounds: ty::ExistentialBounds) {
599         debug!("push_inherent_candidates_from_object(did={}, substs={})",
600                self.did_to_string(did),
601                substs.repr(self.tcx()));
602         let tcx = self.tcx();
603         let span = self.span;
604
605         // It is illegal to invoke a method on a trait instance that
606         // refers to the `self` type. An error will be reported by
607         // `enforce_object_limitations()` if the method refers
608         // to the `Self` type. Substituting ty_err here allows
609         // compiler to soldier on.
610         //
611         // `confirm_candidate()` also relies upon this substitution
612         // for Self. (fix)
613         let rcvr_substs = substs.with_self_ty(ty::mk_err());
614         let trait_ref = Rc::new(TraitRef {
615             def_id: did,
616             substs: rcvr_substs.clone()
617         });
618
619         self.push_inherent_candidates_from_bounds_inner(
620             &[trait_ref.clone()],
621             |_this, new_trait_ref, m, method_num, _bound_num| {
622                 let vtable_index =
623                     get_method_index(tcx, &*new_trait_ref,
624                                      trait_ref.clone(), method_num);
625                 let mut m = (*m).clone();
626                 // We need to fix up the transformed self type.
627                 *m.fty.sig.inputs.get_mut(0) =
628                     construct_transformed_self_ty_for_object(
629                         tcx, span, did, &rcvr_substs, bounds, &m);
630
631                 Some(Candidate {
632                     rcvr_match_condition: RcvrMatchesIfObject(did),
633                     rcvr_substs: new_trait_ref.substs.clone(),
634                     method_ty: Rc::new(m),
635                     origin: MethodObject(MethodObject {
636                         trait_id: new_trait_ref.def_id,
637                         object_trait_id: did,
638                         method_num: method_num,
639                         real_index: vtable_index
640                     })
641                 })
642             });
643     }
644
645     fn push_inherent_candidates_from_param(&mut self,
646                                            rcvr_ty: ty::t,
647                                            restrict_to: Option<DefId>,
648                                            param_ty: ParamTy) {
649         debug!("push_inherent_candidates_from_param(param_ty={:?})",
650                param_ty);
651         self.push_inherent_candidates_from_bounds(
652             rcvr_ty,
653             param_ty.space,
654             param_ty.idx,
655             restrict_to,
656             param_index { space: param_ty.space, index: param_ty.idx });
657     }
658
659
660     fn push_inherent_candidates_from_bounds(&mut self,
661                                             self_ty: ty::t,
662                                             space: subst::ParamSpace,
663                                             index: uint,
664                                             restrict_to: Option<DefId>,
665                                             param: param_index) {
666         let bounds =
667             self.fcx.inh.param_env.bounds.get(space, index).trait_bounds
668             .as_slice();
669         self.push_inherent_candidates_from_bounds_inner(bounds,
670             |this, trait_ref, m, method_num, bound_num| {
671                 match restrict_to {
672                     Some(trait_did) => {
673                         if trait_did != trait_ref.def_id {
674                             return None;
675                         }
676                     }
677                     _ => {}
678                 }
679
680                 let condition = match m.explicit_self {
681                     ByReferenceExplicitSelfCategory(_, mt) if mt == MutMutable =>
682                         RcvrMatchesIfEqtype(self_ty),
683                     _ =>
684                         RcvrMatchesIfSubtype(self_ty)
685                 };
686
687                 debug!("found match: trait_ref={} substs={} m={}",
688                        trait_ref.repr(this.tcx()),
689                        trait_ref.substs.repr(this.tcx()),
690                        m.repr(this.tcx()));
691                 assert_eq!(m.generics.types.get_slice(subst::TypeSpace).len(),
692                            trait_ref.substs.types.get_slice(subst::TypeSpace).len());
693                 assert_eq!(m.generics.regions.get_slice(subst::TypeSpace).len(),
694                            trait_ref.substs.regions().get_slice(subst::TypeSpace).len());
695                 assert_eq!(m.generics.types.get_slice(subst::SelfSpace).len(),
696                            trait_ref.substs.types.get_slice(subst::SelfSpace).len());
697                 assert_eq!(m.generics.regions.get_slice(subst::SelfSpace).len(),
698                            trait_ref.substs.regions().get_slice(subst::SelfSpace).len());
699                 Some(Candidate {
700                     rcvr_match_condition: condition,
701                     rcvr_substs: trait_ref.substs.clone(),
702                     method_ty: m,
703                     origin: MethodParam(MethodParam {
704                         trait_id: trait_ref.def_id,
705                         method_num: method_num,
706                         param_num: param,
707                         bound_num: bound_num,
708                     })
709                 })
710         })
711     }
712
713     // Do a search through a list of bounds, using a callback to actually
714     // create the candidates.
715     fn push_inherent_candidates_from_bounds_inner(
716         &mut self,
717         bounds: &[Rc<TraitRef>],
718         mk_cand: |this: &mut LookupContext,
719                   tr: Rc<TraitRef>,
720                   m: Rc<ty::Method>,
721                   method_num: uint,
722                   bound_num: uint|
723                   -> Option<Candidate>) {
724         let tcx = self.tcx();
725         let mut next_bound_idx = 0; // count only trait bounds
726
727         ty::each_bound_trait_and_supertraits(tcx, bounds, |bound_trait_ref| {
728             let this_bound_idx = next_bound_idx;
729             next_bound_idx += 1;
730
731             let trait_items = ty::trait_items(tcx, bound_trait_ref.def_id);
732             match trait_items.iter().position(|ti| {
733                 match *ti {
734                     ty::MethodTraitItem(ref m) => {
735                         m.explicit_self != ty::StaticExplicitSelfCategory &&
736                         m.ident.name == self.m_name
737                     }
738                 }
739             }) {
740                 Some(pos) => {
741                     let method = match *trait_items.get(pos) {
742                         ty::MethodTraitItem(ref method) => (*method).clone(),
743                     };
744
745                     match mk_cand(self,
746                                   bound_trait_ref,
747                                   method,
748                                   pos,
749                                   this_bound_idx) {
750                         Some(cand) => {
751                             debug!("pushing inherent candidate for param: {}",
752                                    cand.repr(self.tcx()));
753                             self.inherent_candidates.push(cand);
754                         }
755                         None => {}
756                     }
757                 }
758                 None => {
759                     debug!("trait doesn't contain method: {:?}",
760                         bound_trait_ref.def_id);
761                     // check next trait or bound
762                 }
763             }
764             true
765         });
766     }
767
768
769     fn push_inherent_impl_candidates_for_type(&mut self, did: DefId) {
770         // Read the inherent implementation candidates for this type from the
771         // metadata if necessary.
772         ty::populate_implementations_for_type_if_necessary(self.tcx(), did);
773
774         let impl_items = self.tcx().impl_items.borrow();
775         for impl_infos in self.tcx().inherent_impls.borrow().find(&did).iter() {
776             for impl_did in impl_infos.borrow().iter() {
777                 let items = impl_items.get(impl_did);
778                 self.push_candidates_from_impl(*impl_did,
779                                                items.as_slice(),
780                                                false);
781             }
782         }
783     }
784
785     fn push_candidates_from_impl(&mut self,
786                                  impl_did: DefId,
787                                  impl_items: &[ImplOrTraitItemId],
788                                  is_extension: bool) {
789         let did = if self.report_statics == ReportStaticMethods {
790             // we only want to report each base trait once
791             match ty::impl_trait_ref(self.tcx(), impl_did) {
792                 Some(trait_ref) => trait_ref.def_id,
793                 None => impl_did
794             }
795         } else {
796             impl_did
797         };
798
799         if !self.impl_dups.insert(did) {
800             return; // already visited
801         }
802
803         debug!("push_candidates_from_impl: {} {}",
804                token::get_name(self.m_name),
805                impl_items.iter()
806                          .map(|&did| {
807                              ty::impl_or_trait_item(self.tcx(),
808                                                     did.def_id()).ident()
809                          })
810                          .collect::<Vec<ast::Ident>>()
811                          .repr(self.tcx()));
812
813         let method = match impl_items.iter()
814                                      .map(|&did| {
815                                          ty::impl_or_trait_item(self.tcx(),
816                                                                 did.def_id())
817                                      })
818                                      .find(|m| {
819                                          m.ident().name == self.m_name
820                                      }) {
821             Some(ty::MethodTraitItem(method)) => method,
822             None => { return; } // No method with the right name.
823         };
824
825         // determine the `self` of the impl with fresh
826         // variables for each parameter:
827         let span = self.self_expr.map_or(self.span, |e| e.span);
828         let vcx = self.fcx.vtable_context();
829         let TypeAndSubsts {
830             substs: impl_substs,
831             ty: impl_ty
832         } = impl_self_ty(&vcx, span, impl_did);
833
834         let condition = match method.explicit_self {
835             ByReferenceExplicitSelfCategory(_, mt) if mt == MutMutable =>
836                 RcvrMatchesIfEqtype(impl_ty),
837             _ =>
838                 RcvrMatchesIfSubtype(impl_ty)
839         };
840
841         let candidates = if is_extension {
842             &mut self.extension_candidates
843         } else {
844             &mut self.inherent_candidates
845         };
846
847         candidates.push(Candidate {
848             rcvr_match_condition: condition,
849             rcvr_substs: impl_substs,
850             origin: MethodStatic(method.def_id),
851             method_ty: method,
852         });
853     }
854
855     // ______________________________________________________________________
856     // Candidate selection (see comment at start of file)
857
858     fn search_for_autoderefd_method(&self,
859                                     self_ty: ty::t,
860                                     autoderefs: uint)
861                                     -> Option<MethodCallee> {
862         // Hacky. For overloaded derefs, there may be an adjustment
863         // added to the expression from the outside context, so we do not store
864         // an explicit adjustment, but rather we hardwire the single deref
865         // that occurs in trans and mem_categorization.
866         if self.self_expr.is_none() {
867             return None;
868         }
869
870         let (self_ty, auto_deref_ref) = self.consider_reborrow(self_ty, autoderefs);
871         let adjustment = Some((self.self_expr.unwrap().id, ty::AutoDerefRef(auto_deref_ref)));
872
873         match self.search_for_method(self_ty) {
874             None => None,
875             Some(method) => {
876                 debug!("(searching for autoderef'd method) writing \
877                        adjustment {:?} for {}", adjustment, self.ty_to_string(self_ty));
878                 match adjustment {
879                     Some((self_expr_id, adj)) => {
880                         self.fcx.write_adjustment(self_expr_id, adj);
881                     }
882                     None => {}
883                 }
884                 Some(method)
885             }
886         }
887     }
888
889     fn consider_reborrow(&self,
890                          self_ty: ty::t,
891                          autoderefs: uint)
892                          -> (ty::t, ty::AutoDerefRef) {
893         /*!
894          * In the event that we are invoking a method with a receiver
895          * of a borrowed type like `&T`, `&mut T`, or `&mut [T]`,
896          * we will "reborrow" the receiver implicitly.  For example, if
897          * you have a call `r.inc()` and where `r` has type `&mut T`,
898          * then we treat that like `(&mut *r).inc()`.  This avoids
899          * consuming the original pointer.
900          *
901          * You might think that this would be a natural byproduct of
902          * the auto-deref/auto-ref process.  This is true for `Box<T>`
903          * but not for an `&mut T` receiver.  With `Box<T>`, we would
904          * begin by testing for methods with a self type `Box<T>`,
905          * then autoderef to `T`, then autoref to `&mut T`.  But with
906          * an `&mut T` receiver the process begins with `&mut T`, only
907          * without any autoadjustments.
908          */
909
910         let tcx = self.tcx();
911         return match ty::get(self_ty).sty {
912             ty::ty_rptr(_, self_mt) if default_method_hack(self_mt) => {
913                 (self_ty,
914                  ty::AutoDerefRef {
915                      autoderefs: autoderefs,
916                      autoref: None})
917             }
918             ty::ty_rptr(_, self_mt) => {
919                 let region =
920                     self.infcx().next_region_var(infer::Autoref(self.span));
921                 (ty::mk_rptr(tcx, region, self_mt),
922                  ty::AutoDerefRef {
923                      autoderefs: autoderefs + 1,
924                      autoref: Some(ty::AutoPtr(region, self_mt.mutbl, None))})
925             }
926             _ => {
927                 (self_ty,
928                  ty::AutoDerefRef {
929                      autoderefs: autoderefs,
930                      autoref: None})
931             }
932         };
933
934         fn default_method_hack(self_mt: ty::mt) -> bool {
935             // FIXME(#6129). Default methods can't deal with autoref.
936             //
937             // I am a horrible monster and I pray for death. Currently
938             // the default method code fails when you try to reborrow
939             // because it is not handling types correctly. In lieu of
940             // fixing that, I am introducing this horrible hack. - ndm
941             self_mt.mutbl == MutImmutable && ty::type_is_self(self_mt.ty)
942         }
943     }
944
945     // Takes an [T] - an unwrapped DST pointer (either ~ or &)
946     // [T] to &[T] or &&[T] (note that we started with a &[T] or ~[T] which has
947     // been implicitly derefed).
948     fn auto_slice_vec(&self, ty: ty::t, autoderefs: uint) -> Option<MethodCallee> {
949         let tcx = self.tcx();
950         debug!("auto_slice_vec {}", ppaux::ty_to_string(tcx, ty));
951
952         // First try to borrow to a slice
953         let entry = self.search_for_some_kind_of_autorefd_method(
954             |r, m| AutoPtr(r, m, None), autoderefs, [MutImmutable, MutMutable],
955             |m,r| ty::mk_slice(tcx, r,
956                                ty::mt {ty:ty, mutbl:m}));
957
958         if entry.is_some() {
959             return entry;
960         }
961
962         // Then try to borrow to a slice *and* borrow a pointer.
963         self.search_for_some_kind_of_autorefd_method(
964             |r, m| AutoPtr(r, ast::MutImmutable, Some( box AutoPtr(r, m, None))),
965             autoderefs, [MutImmutable, MutMutable],
966             |m, r| {
967                 let slice_ty = ty::mk_slice(tcx, r,
968                                             ty::mt {ty:ty, mutbl:m});
969                 // NB: we do not try to autoref to a mutable
970                 // pointer. That would be creating a pointer
971                 // to a temporary pointer (the borrowed
972                 // slice), so any update the callee makes to
973                 // it can't be observed.
974                 ty::mk_rptr(tcx, r, ty::mt {ty:slice_ty, mutbl:MutImmutable})
975             })
976     }
977
978     // [T, ..len] -> [T] or &[T] or &&[T]
979     fn auto_unsize_vec(&self, ty: ty::t, autoderefs: uint, len: uint) -> Option<MethodCallee> {
980         let tcx = self.tcx();
981         debug!("auto_unsize_vec {}", ppaux::ty_to_string(tcx, ty));
982
983         // First try to borrow to an unsized vec.
984         let entry = self.search_for_some_kind_of_autorefd_method(
985             |_r, _m| AutoUnsize(ty::UnsizeLength(len)),
986             autoderefs, [MutImmutable, MutMutable],
987             |_m, _r| ty::mk_vec(tcx, ty, None));
988
989         if entry.is_some() {
990             return entry;
991         }
992
993         // Then try to borrow to a slice.
994         let entry = self.search_for_some_kind_of_autorefd_method(
995             |r, m| AutoPtr(r, m, Some(box AutoUnsize(ty::UnsizeLength(len)))),
996             autoderefs, [MutImmutable, MutMutable],
997             |m, r|  ty::mk_slice(tcx, r, ty::mt {ty:ty, mutbl:m}));
998
999         if entry.is_some() {
1000             return entry;
1001         }
1002
1003         // Then try to borrow to a slice *and* borrow a pointer.
1004         self.search_for_some_kind_of_autorefd_method(
1005             |r, m| AutoPtr(r, m,
1006                            Some(box AutoPtr(r, m,
1007                                             Some(box AutoUnsize(ty::UnsizeLength(len)))))),
1008             autoderefs, [MutImmutable, MutMutable],
1009             |m, r| {
1010                 let slice_ty = ty::mk_slice(tcx, r, ty::mt {ty:ty, mutbl:m});
1011                 ty::mk_rptr(tcx, r, ty::mt {ty:slice_ty, mutbl:MutImmutable})
1012             })
1013     }
1014
1015     fn auto_slice_str(&self, autoderefs: uint) -> Option<MethodCallee> {
1016         let tcx = self.tcx();
1017         debug!("auto_slice_str");
1018
1019         let entry = self.search_for_some_kind_of_autorefd_method(
1020             |r, m| AutoPtr(r, m, None), autoderefs, [MutImmutable],
1021             |_m, r| ty::mk_str_slice(tcx, r, MutImmutable));
1022
1023         if entry.is_some() {
1024             return entry;
1025         }
1026
1027         self.search_for_some_kind_of_autorefd_method(
1028             |r, m| AutoPtr(r, ast::MutImmutable, Some( box AutoPtr(r, m, None))),
1029             autoderefs, [MutImmutable],
1030             |m, r| {
1031                 let slice_ty = ty::mk_str_slice(tcx, r, m);
1032                 ty::mk_rptr(tcx, r, ty::mt {ty:slice_ty, mutbl:m})
1033             })
1034     }
1035
1036     // Coerce Box/&Trait instances to &Trait.
1037     fn auto_slice_trait(&self, ty: ty::t, autoderefs: uint) -> Option<MethodCallee> {
1038         debug!("auto_slice_trait");
1039         match ty::get(ty).sty {
1040             ty_trait(box ty::TyTrait {
1041                     def_id: trt_did,
1042                     substs: ref trt_substs,
1043                     bounds: b,
1044                     .. }) => {
1045                 let tcx = self.tcx();
1046                 self.search_for_some_kind_of_autorefd_method(
1047                     |r, m| AutoPtr(r, m, None),
1048                     autoderefs, [MutImmutable, MutMutable],
1049                     |m, r| {
1050                         let tr = ty::mk_trait(tcx, trt_did, trt_substs.clone(), b);
1051                         ty::mk_rptr(tcx, r, ty::mt{ ty: tr, mutbl: m })
1052                     })
1053             }
1054             _ => fail!("Expected ty_trait in auto_slice_trait")
1055         }
1056     }
1057
1058     fn search_for_autofatptrd_method(&self,
1059                                      self_ty: ty::t,
1060                                      autoderefs: uint)
1061                                      -> Option<MethodCallee> {
1062         /*!
1063          * Searches for a candidate by converting things like
1064          * `~[]` to `&[]`.
1065          */
1066
1067         let tcx = self.tcx();
1068         debug!("search_for_autofatptrd_method {}", ppaux::ty_to_string(tcx, self_ty));
1069
1070         let sty = ty::get(self_ty).sty.clone();
1071         match sty {
1072             ty_vec(ty, Some(len)) => self.auto_unsize_vec(ty, autoderefs, len),
1073             ty_vec(ty, None) => self.auto_slice_vec(ty, autoderefs),
1074             ty_str => self.auto_slice_str(autoderefs),
1075             ty_trait(..) => self.auto_slice_trait(self_ty, autoderefs),
1076
1077             ty_closure(..) => {
1078                 // This case should probably be handled similarly to
1079                 // Trait instances.
1080                 None
1081             }
1082
1083             _ => None
1084         }
1085     }
1086
1087     fn search_for_autoptrd_method(&self, self_ty: ty::t, autoderefs: uint)
1088                                   -> Option<MethodCallee> {
1089         /*!
1090          *
1091          * Converts any type `T` to `&M T` where `M` is an
1092          * appropriate mutability.
1093          */
1094
1095         let tcx = self.tcx();
1096         match ty::get(self_ty).sty {
1097             ty_bare_fn(..) | ty_box(..) | ty_uniq(..) | ty_rptr(..) |
1098             ty_infer(IntVar(_)) |
1099             ty_infer(FloatVar(_)) |
1100             ty_param(..) | ty_nil | ty_bot | ty_bool |
1101             ty_char | ty_int(..) | ty_uint(..) |
1102             ty_float(..) | ty_enum(..) | ty_ptr(..) | ty_struct(..) |
1103             ty_unboxed_closure(..) | ty_tup(..) | ty_open(..) |
1104             ty_str | ty_vec(..) | ty_trait(..) | ty_closure(..) => {
1105                 self.search_for_some_kind_of_autorefd_method(
1106                     |r, m| AutoPtr(r, m, None), autoderefs, [MutImmutable, MutMutable],
1107                     |m,r| ty::mk_rptr(tcx, r, ty::mt {ty:self_ty, mutbl:m}))
1108             }
1109
1110             ty_err => None,
1111
1112             ty_infer(TyVar(_)) => {
1113                 self.bug(format!("unexpected type: {}",
1114                                  self.ty_to_string(self_ty)).as_slice());
1115             }
1116         }
1117     }
1118
1119     fn search_for_some_kind_of_autorefd_method(
1120             &self,
1121             kind: |Region, ast::Mutability| -> ty::AutoRef,
1122             autoderefs: uint,
1123             mutbls: &[ast::Mutability],
1124             mk_autoref_ty: |ast::Mutability, ty::Region| -> ty::t)
1125             -> Option<MethodCallee> {
1126         // Hacky. For overloaded derefs, there may be an adjustment
1127         // added to the expression from the outside context, so we do not store
1128         // an explicit adjustment, but rather we hardwire the single deref
1129         // that occurs in trans and mem_categorization.
1130         let self_expr_id = match self.self_expr {
1131             Some(expr) => Some(expr.id),
1132             None => {
1133                 assert_eq!(autoderefs, 0);
1134                 assert!(kind(ty::ReEmpty, ast::MutImmutable) ==
1135                         ty::AutoPtr(ty::ReEmpty, ast::MutImmutable, None));
1136                 None
1137             }
1138         };
1139
1140         // This is hokey. We should have mutability inference as a
1141         // variable.  But for now, try &const, then &, then &mut:
1142         let region =
1143             self.infcx().next_region_var(infer::Autoref(self.span));
1144         for mutbl in mutbls.iter() {
1145             let autoref_ty = mk_autoref_ty(*mutbl, region);
1146             match self.search_for_method(autoref_ty) {
1147                 None => {}
1148                 Some(method) => {
1149                     match self_expr_id {
1150                         Some(self_expr_id) => {
1151                             self.fcx.write_adjustment(
1152                                 self_expr_id,
1153                                 ty::AutoDerefRef(ty::AutoDerefRef {
1154                                     autoderefs: autoderefs,
1155                                     autoref: Some(kind(region, *mutbl))
1156                                 }));
1157                         }
1158                         None => {}
1159                     }
1160                     return Some(method);
1161                 }
1162             }
1163         }
1164         None
1165     }
1166
1167     fn search_for_method(&self, rcvr_ty: ty::t) -> Option<MethodCallee> {
1168         debug!("search_for_method(rcvr_ty={})", self.ty_to_string(rcvr_ty));
1169         let _indenter = indenter();
1170
1171         // I am not sure that inherent methods should have higher
1172         // priority, but it is necessary ATM to handle some of the
1173         // existing code.
1174
1175         debug!("searching inherent candidates");
1176         match self.consider_candidates(rcvr_ty, self.inherent_candidates.as_slice()) {
1177             None => {}
1178             Some(mme) => {
1179                 return Some(mme);
1180             }
1181         }
1182
1183         debug!("searching extension candidates");
1184         self.consider_candidates(rcvr_ty, self.extension_candidates.as_slice())
1185     }
1186
1187     fn consider_candidates(&self, rcvr_ty: ty::t,
1188                            candidates: &[Candidate])
1189                            -> Option<MethodCallee> {
1190         let relevant_candidates = self.filter_candidates(rcvr_ty, candidates);
1191
1192         if relevant_candidates.len() == 0 {
1193             return None;
1194         }
1195
1196         if self.report_statics == ReportStaticMethods {
1197             // lookup should only be called with ReportStaticMethods if a regular lookup failed
1198             assert!(relevant_candidates.iter()
1199                                        .all(|c| {
1200                 c.method_ty.explicit_self == ty::StaticExplicitSelfCategory
1201             }));
1202
1203             self.tcx().sess.fileline_note(self.span,
1204                                 "found defined static methods, maybe a `self` is missing?");
1205
1206             for (idx, candidate) in relevant_candidates.iter().enumerate() {
1207                 self.report_candidate(idx, &candidate.origin);
1208             }
1209
1210             // return something so we don't get errors for every mutability
1211             return Some(MethodCallee {
1212                 origin: relevant_candidates.get(0).origin,
1213                 ty: ty::mk_err(),
1214                 substs: subst::Substs::empty()
1215             });
1216         }
1217
1218         if relevant_candidates.len() > 1 {
1219             span_err!(self.tcx().sess, self.span, E0034,
1220                 "multiple applicable methods in scope");
1221             for (idx, candidate) in relevant_candidates.iter().enumerate() {
1222                 self.report_candidate(idx, &candidate.origin);
1223             }
1224         }
1225
1226         Some(self.confirm_candidate(rcvr_ty, relevant_candidates.get(0)))
1227     }
1228
1229     fn filter_candidates(&self, rcvr_ty: ty::t, candidates: &[Candidate]) -> Vec<Candidate> {
1230         let mut relevant_candidates: Vec<Candidate> = Vec::new();
1231
1232         for candidate_a in candidates.iter().filter(|&c| self.is_relevant(rcvr_ty, c)) {
1233             // Skip this one if we already have one like it
1234             if !relevant_candidates.iter().any(|candidate_b| {
1235                 debug!("attempting to merge {} and {}",
1236                        candidate_a.repr(self.tcx()),
1237                        candidate_b.repr(self.tcx()));
1238                 match (&candidate_a.origin, &candidate_b.origin) {
1239                     (&MethodParam(ref p1), &MethodParam(ref p2)) => {
1240                         let same_trait = p1.trait_id == p2.trait_id;
1241                         let same_method = p1.method_num == p2.method_num;
1242                         let same_param = p1.param_num == p2.param_num;
1243                         // The bound number may be different because
1244                         // multiple bounds may lead to the same trait
1245                         // impl
1246                         same_trait && same_method && same_param
1247                     }
1248                     _ => false
1249                 }
1250             }) {
1251                 relevant_candidates.push(candidate_a.clone());
1252             }
1253         }
1254
1255         relevant_candidates
1256     }
1257
1258     fn confirm_candidate(&self, rcvr_ty: ty::t, candidate: &Candidate)
1259                          -> MethodCallee
1260     {
1261         // This method performs two sets of substitutions, one after the other:
1262         // 1. Substitute values for any type/lifetime parameters from the impl and
1263         //    method declaration into the method type. This is the function type
1264         //    before it is called; it may still include late bound region variables.
1265         // 2. Instantiate any late bound lifetime parameters in the method itself
1266         //    with fresh region variables.
1267
1268         let tcx = self.tcx();
1269
1270         debug!("confirm_candidate(rcvr_ty={}, candidate={})",
1271                self.ty_to_string(rcvr_ty),
1272                candidate.repr(self.tcx()));
1273
1274         self.enforce_object_limitations(candidate);
1275         self.enforce_drop_trait_limitations(candidate);
1276
1277         // static methods should never have gotten this far:
1278         assert!(candidate.method_ty.explicit_self !=
1279                 ty::StaticExplicitSelfCategory);
1280
1281         // Determine the values for the generic parameters of the method.
1282         // If they were not explicitly supplied, just construct fresh
1283         // variables.
1284         let num_supplied_tps = self.supplied_tps.len();
1285         let num_method_tps = candidate.method_ty.generics.types.len(subst::FnSpace);
1286         let m_types = {
1287             if num_supplied_tps == 0u {
1288                 self.fcx.infcx().next_ty_vars(num_method_tps)
1289             } else if num_method_tps == 0u {
1290                 span_err!(tcx.sess, self.span, E0035,
1291                     "does not take type parameters");
1292                 self.fcx.infcx().next_ty_vars(num_method_tps)
1293             } else if num_supplied_tps != num_method_tps {
1294                 span_err!(tcx.sess, self.span, E0036,
1295                     "incorrect number of type parameters given for this method");
1296                 self.fcx.infcx().next_ty_vars(num_method_tps)
1297             } else {
1298                 Vec::from_slice(self.supplied_tps)
1299             }
1300         };
1301
1302         // Create subst for early-bound lifetime parameters, combining
1303         // parameters from the type and those from the method.
1304         //
1305         // FIXME -- permit users to manually specify lifetimes
1306         let m_regions =
1307             self.fcx.infcx().region_vars_for_defs(
1308                 self.span,
1309                 candidate.method_ty.generics.regions.get_slice(subst::FnSpace));
1310
1311         let all_substs = candidate.rcvr_substs.clone().with_method(m_types, m_regions);
1312
1313         let ref bare_fn_ty = candidate.method_ty.fty;
1314
1315         // Compute the method type with type parameters substituted
1316         debug!("fty={} all_substs={}",
1317                bare_fn_ty.repr(tcx),
1318                all_substs.repr(tcx));
1319
1320         let fn_sig = &bare_fn_ty.sig;
1321         let inputs = match candidate.origin {
1322             MethodObject(..) => {
1323                 // For annoying reasons, we've already handled the
1324                 // substitution of self for object calls.
1325                 let args = fn_sig.inputs.slice_from(1).iter().map(|t| {
1326                     t.subst(tcx, &all_substs)
1327                 });
1328                 Some(*fn_sig.inputs.get(0)).move_iter().chain(args).collect()
1329             }
1330             _ => fn_sig.inputs.subst(tcx, &all_substs)
1331         };
1332         let fn_sig = ty::FnSig {
1333             binder_id: fn_sig.binder_id,
1334             inputs: inputs,
1335             output: fn_sig.output.subst(tcx, &all_substs),
1336             variadic: fn_sig.variadic
1337         };
1338
1339         debug!("after subst, fty={}", fn_sig.repr(tcx));
1340
1341         // Replace any bound regions that appear in the function
1342         // signature with region variables
1343         let (_, fn_sig) = replace_late_bound_regions_in_fn_sig(
1344             tcx, &fn_sig,
1345             |br| self.fcx.infcx().next_region_var(
1346                 infer::LateBoundRegion(self.span, br)));
1347         let transformed_self_ty = *fn_sig.inputs.get(0);
1348         let fty = ty::mk_bare_fn(tcx, ty::BareFnTy {
1349             sig: fn_sig,
1350             fn_style: bare_fn_ty.fn_style,
1351             abi: bare_fn_ty.abi.clone(),
1352         });
1353         debug!("after replacing bound regions, fty={}", self.ty_to_string(fty));
1354
1355         // Before, we only checked whether self_ty could be a subtype
1356         // of rcvr_ty; now we actually make it so (this may cause
1357         // variables to unify etc).  Since we checked beforehand, and
1358         // nothing has changed in the meantime, this unification
1359         // should never fail.
1360         let span = self.self_expr.map_or(self.span, |e| e.span);
1361         match self.fcx.mk_subty(false, infer::Misc(span),
1362                                 rcvr_ty, transformed_self_ty) {
1363             Ok(_) => {}
1364             Err(_) => {
1365                 self.bug(format!(
1366                         "{} was a subtype of {} but now is not?",
1367                         self.ty_to_string(rcvr_ty),
1368                         self.ty_to_string(transformed_self_ty)).as_slice());
1369             }
1370         }
1371
1372         self.fcx.add_region_obligations_for_parameters(
1373             self.span,
1374             &all_substs,
1375             &candidate.method_ty.generics);
1376
1377         MethodCallee {
1378             origin: candidate.origin,
1379             ty: fty,
1380             substs: all_substs
1381         }
1382     }
1383
1384     fn enforce_object_limitations(&self, candidate: &Candidate) {
1385         /*!
1386          * There are some limitations to calling functions through an
1387          * object, because (a) the self type is not known
1388          * (that's the whole point of a trait instance, after all, to
1389          * obscure the self type) and (b) the call must go through a
1390          * vtable and hence cannot be monomorphized.
1391          */
1392
1393         match candidate.origin {
1394             MethodStatic(..) |
1395             MethodParam(..) |
1396             MethodStaticUnboxedClosure(..) => {
1397                 return; // not a call to a trait instance
1398             }
1399             MethodObject(..) => {}
1400         }
1401
1402         match candidate.method_ty.explicit_self {
1403             ty::StaticExplicitSelfCategory => { // reason (a) above
1404                 self.tcx().sess.span_err(
1405                     self.span,
1406                     "cannot call a method without a receiver \
1407                      through an object");
1408             }
1409
1410             ty::ByValueExplicitSelfCategory |
1411             ty::ByReferenceExplicitSelfCategory(..) |
1412             ty::ByBoxExplicitSelfCategory => {}
1413         }
1414
1415         // reason (a) above
1416         let check_for_self_ty = |ty| {
1417             if ty::type_has_self(ty) {
1418                 span_err!(self.tcx().sess, self.span, E0038,
1419                     "cannot call a method whose type contains a \
1420                      self-type through an object");
1421                 true
1422             } else {
1423                 false
1424             }
1425         };
1426         let ref sig = candidate.method_ty.fty.sig;
1427         let mut found_self_ty = false;
1428         for &input_ty in sig.inputs.iter() {
1429             if check_for_self_ty(input_ty) {
1430                 found_self_ty = true;
1431                 break;
1432             }
1433         }
1434         if !found_self_ty {
1435             check_for_self_ty(sig.output);
1436         }
1437
1438         if candidate.method_ty.generics.has_type_params(subst::FnSpace) {
1439             // reason (b) above
1440             span_err!(self.tcx().sess, self.span, E0039,
1441                 "cannot call a generic method through an object");
1442         }
1443     }
1444
1445     fn enforce_drop_trait_limitations(&self, candidate: &Candidate) {
1446         // No code can call the finalize method explicitly.
1447         let bad;
1448         match candidate.origin {
1449             MethodStatic(method_id) => {
1450                 bad = self.tcx().destructors.borrow().contains(&method_id);
1451             }
1452             MethodStaticUnboxedClosure(_) => bad = false,
1453             // FIXME: does this properly enforce this on everything now
1454             // that self has been merged in? -sully
1455             MethodParam(MethodParam { trait_id: trait_id, .. }) |
1456             MethodObject(MethodObject { trait_id: trait_id, .. }) => {
1457                 bad = self.tcx().destructor_for_type.borrow()
1458                           .contains_key(&trait_id);
1459             }
1460         }
1461
1462         if bad {
1463             span_err!(self.tcx().sess, self.span, E0040,
1464                 "explicit call to destructor");
1465         }
1466     }
1467
1468     // `rcvr_ty` is the type of the expression. It may be a subtype of a
1469     // candidate method's `self_ty`.
1470     fn is_relevant(&self, rcvr_ty: ty::t, candidate: &Candidate) -> bool {
1471         debug!("is_relevant(rcvr_ty={}, candidate={})",
1472                self.ty_to_string(rcvr_ty), candidate.repr(self.tcx()));
1473
1474         return match candidate.method_ty.explicit_self {
1475             StaticExplicitSelfCategory => {
1476                 debug!("(is relevant?) explicit self is static");
1477                 self.report_statics == ReportStaticMethods
1478             }
1479
1480             ByValueExplicitSelfCategory => {
1481                 debug!("(is relevant?) explicit self is by-value");
1482                 match ty::get(rcvr_ty).sty {
1483                     ty::ty_uniq(typ) => {
1484                         match ty::get(typ).sty {
1485                             ty::ty_trait(box ty::TyTrait {
1486                                 def_id: self_did,
1487                                 ..
1488                             }) => {
1489                                 rcvr_matches_object(self_did, candidate) ||
1490                                     rcvr_matches_ty(self.fcx,
1491                                                     rcvr_ty,
1492                                                     candidate)
1493                             }
1494                             _ => {
1495                                 rcvr_matches_ty(self.fcx, rcvr_ty, candidate)
1496                             }
1497                         }
1498                     }
1499                     _ => rcvr_matches_ty(self.fcx, rcvr_ty, candidate)
1500                 }
1501             }
1502
1503             ByReferenceExplicitSelfCategory(_, m) => {
1504                 debug!("(is relevant?) explicit self is a region");
1505                 match ty::get(rcvr_ty).sty {
1506                     ty::ty_rptr(_, mt) => {
1507                         match ty::get(mt.ty).sty {
1508                             ty::ty_trait(box ty::TyTrait { def_id: self_did, .. }) => {
1509                                 mutability_matches(mt.mutbl, m) &&
1510                                 rcvr_matches_object(self_did, candidate)
1511                             }
1512                             _ => mutability_matches(mt.mutbl, m) &&
1513                                  rcvr_matches_ty(self.fcx, mt.ty, candidate)
1514                         }
1515                     }
1516
1517                     _ => false
1518                 }
1519             }
1520
1521             ByBoxExplicitSelfCategory => {
1522                 debug!("(is relevant?) explicit self is a unique pointer");
1523                 match ty::get(rcvr_ty).sty {
1524                     ty::ty_uniq(typ) => {
1525                         match ty::get(typ).sty {
1526                             ty::ty_trait(box ty::TyTrait { def_id: self_did, .. }) => {
1527                                 rcvr_matches_object(self_did, candidate)
1528                             }
1529                             _ => rcvr_matches_ty(self.fcx, typ, candidate),
1530                         }
1531                     }
1532
1533                     _ => false
1534                 }
1535             }
1536         };
1537
1538         fn rcvr_matches_object(self_did: ast::DefId,
1539                                candidate: &Candidate) -> bool {
1540             match candidate.rcvr_match_condition {
1541                 RcvrMatchesIfObject(desired_did) => {
1542                     self_did == desired_did
1543                 }
1544                 RcvrMatchesIfSubtype(_) | RcvrMatchesIfEqtype(_) => {
1545                     false
1546                 }
1547             }
1548         }
1549
1550         fn rcvr_matches_ty(fcx: &FnCtxt,
1551                            rcvr_ty: ty::t,
1552                            candidate: &Candidate) -> bool {
1553             match candidate.rcvr_match_condition {
1554                 RcvrMatchesIfObject(_) => {
1555                     false
1556                 }
1557                 RcvrMatchesIfSubtype(of_type) => {
1558                     fcx.can_mk_subty(rcvr_ty, of_type).is_ok()
1559                 }
1560                 RcvrMatchesIfEqtype(of_type) => {
1561                     fcx.can_mk_eqty(rcvr_ty, of_type).is_ok()
1562                 }
1563             }
1564         }
1565
1566         fn mutability_matches(self_mutbl: ast::Mutability,
1567                               candidate_mutbl: ast::Mutability)
1568                               -> bool {
1569             //! True if `self_mutbl <: candidate_mutbl`
1570             self_mutbl == candidate_mutbl
1571         }
1572     }
1573
1574     fn report_candidate(&self, idx: uint, origin: &MethodOrigin) {
1575         match *origin {
1576             MethodStatic(impl_did) => {
1577                 let did = if self.report_statics == ReportStaticMethods {
1578                     // If we're reporting statics, we want to report the trait
1579                     // definition if possible, rather than an impl
1580                     match ty::trait_item_of_item(self.tcx(), impl_did) {
1581                         None => {
1582                             debug!("(report candidate) No trait method \
1583                                     found");
1584                             impl_did
1585                         }
1586                         Some(MethodTraitItemId(trait_did)) => {
1587                             debug!("(report candidate) Found trait ref");
1588                             trait_did
1589                         }
1590                     }
1591                 } else {
1592                     // If it is an instantiated default method, use the original
1593                     // default method for error reporting.
1594                     match provided_source(self.tcx(), impl_did) {
1595                         None => impl_did,
1596                         Some(did) => did
1597                     }
1598                 };
1599                 self.report_static_candidate(idx, did)
1600             }
1601             MethodStaticUnboxedClosure(did) => {
1602                 self.report_static_candidate(idx, did)
1603             }
1604             MethodParam(ref mp) => {
1605                 self.report_param_candidate(idx, (*mp).trait_id)
1606             }
1607             MethodObject(ref mo) => {
1608                 self.report_trait_candidate(idx, mo.trait_id)
1609             }
1610         }
1611     }
1612
1613     fn report_static_candidate(&self, idx: uint, did: DefId) {
1614         let span = if did.krate == ast::LOCAL_CRATE {
1615             self.tcx().map.span(did.node)
1616         } else {
1617             self.span
1618         };
1619         span_note!(self.tcx().sess, span,
1620             "candidate #{} is `{}`",
1621             idx + 1u, ty::item_path_str(self.tcx(), did));
1622     }
1623
1624     fn report_param_candidate(&self, idx: uint, did: DefId) {
1625         span_note!(self.tcx().sess, self.span,
1626             "candidate #{} derives from the bound `{}`",
1627             idx + 1u, ty::item_path_str(self.tcx(), did));
1628     }
1629
1630     fn report_trait_candidate(&self, idx: uint, did: DefId) {
1631         span_note!(self.tcx().sess, self.span,
1632             "candidate #{} derives from the type of the receiver, \
1633             which is the trait `{}`",
1634             idx + 1u, ty::item_path_str(self.tcx(), did));
1635     }
1636
1637     fn infcx(&'a self) -> &'a infer::InferCtxt<'a, 'tcx> {
1638         &self.fcx.inh.infcx
1639     }
1640
1641     fn tcx(&self) -> &'a ty::ctxt<'tcx> {
1642         self.fcx.tcx()
1643     }
1644
1645     fn ty_to_string(&self, t: ty::t) -> String {
1646         self.fcx.infcx().ty_to_string(t)
1647     }
1648
1649     fn did_to_string(&self, did: DefId) -> String {
1650         ty::item_path_str(self.tcx(), did)
1651     }
1652
1653     fn bug(&self, s: &str) -> ! {
1654         self.tcx().sess.span_bug(self.span, s)
1655     }
1656 }
1657
1658 impl Repr for Candidate {
1659     fn repr(&self, tcx: &ty::ctxt) -> String {
1660         format!("Candidate(rcvr_ty={}, rcvr_substs={}, method_ty={}, \
1661                  origin={:?})",
1662                 self.rcvr_match_condition.repr(tcx),
1663                 self.rcvr_substs.repr(tcx),
1664                 self.method_ty.repr(tcx),
1665                 self.origin)
1666     }
1667 }
1668
1669 impl Repr for RcvrMatchCondition {
1670     fn repr(&self, tcx: &ty::ctxt) -> String {
1671         match *self {
1672             RcvrMatchesIfObject(d) => {
1673                 format!("RcvrMatchesIfObject({})", d.repr(tcx))
1674             }
1675             RcvrMatchesIfSubtype(t) => {
1676                 format!("RcvrMatchesIfSubtype({})", t.repr(tcx))
1677             }
1678             RcvrMatchesIfEqtype(t) => {
1679                 format!("RcvrMatchesIfEqtype({})", t.repr(tcx))
1680             }
1681         }
1682     }
1683 }