]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/probe.rs
remove implementation detail from doc
[rust.git] / src / librustc_typeck / check / method / probe.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use super::MethodError;
12 use super::NoMatchData;
13 use super::{CandidateSource, ImplSource, TraitSource};
14 use super::suggest;
15
16 use check::FnCtxt;
17 use hir::def_id::DefId;
18 use hir::def::Def;
19 use namespace::Namespace;
20 use rustc::ty::subst::{Subst, Substs};
21 use rustc::traits::{self, ObligationCause};
22 use rustc::ty::{self, Ty, ToPolyTraitRef, ToPredicate, TraitRef, TypeFoldable};
23 use rustc::infer::type_variable::TypeVariableOrigin;
24 use rustc::util::nodemap::FxHashSet;
25 use rustc::infer::{self, InferOk};
26 use syntax::ast;
27 use syntax::util::lev_distance::{lev_distance, find_best_match_for_name};
28 use syntax_pos::Span;
29 use rustc::hir;
30 use rustc::lint;
31 use std::mem;
32 use std::ops::Deref;
33 use std::rc::Rc;
34 use std::cmp::max;
35
36 use self::CandidateKind::*;
37 pub use self::PickKind::*;
38
39 /// Boolean flag used to indicate if this search is for a suggestion
40 /// or not.  If true, we can allow ambiguity and so forth.
41 pub struct IsSuggestion(pub bool);
42
43 struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
44     fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
45     span: Span,
46     mode: Mode,
47     method_name: Option<ast::Name>,
48     return_type: Option<Ty<'tcx>>,
49     steps: Rc<Vec<CandidateStep<'tcx>>>,
50     inherent_candidates: Vec<Candidate<'tcx>>,
51     extension_candidates: Vec<Candidate<'tcx>>,
52     impl_dups: FxHashSet<DefId>,
53
54     /// Collects near misses when the candidate functions are missing a `self` keyword and is only
55     /// used for error reporting
56     static_candidates: Vec<CandidateSource>,
57
58     /// When probing for names, include names that are close to the
59     /// requested name (by Levensthein distance)
60     allow_similar_names: bool,
61
62     /// Some(candidate) if there is a private candidate
63     private_candidate: Option<Def>,
64
65     /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
66     /// for error reporting
67     unsatisfied_predicates: Vec<TraitRef<'tcx>>,
68 }
69
70 impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
71     type Target = FnCtxt<'a, 'gcx, 'tcx>;
72     fn deref(&self) -> &Self::Target {
73         &self.fcx
74     }
75 }
76
77 #[derive(Debug)]
78 struct CandidateStep<'tcx> {
79     self_ty: Ty<'tcx>,
80     autoderefs: usize,
81     // true if the type results from a dereference of a raw pointer.
82     // when assembling candidates, we include these steps, but not when
83     // picking methods. This so that if we have `foo: *const Foo` and `Foo` has methods
84     // `fn by_raw_ptr(self: *const Self)` and `fn by_ref(&self)`, then
85     // `foo.by_raw_ptr()` will work and `foo.by_ref()` won't.
86     from_unsafe_deref: bool,
87     unsize: bool,
88 }
89
90 #[derive(Debug)]
91 struct Candidate<'tcx> {
92     xform_self_ty: Ty<'tcx>,
93     xform_ret_ty: Option<Ty<'tcx>>,
94     item: ty::AssociatedItem,
95     kind: CandidateKind<'tcx>,
96     import_id: Option<ast::NodeId>,
97 }
98
99 #[derive(Debug)]
100 enum CandidateKind<'tcx> {
101     InherentImplCandidate(&'tcx Substs<'tcx>,
102                           // Normalize obligations
103                           Vec<traits::PredicateObligation<'tcx>>),
104     ObjectCandidate,
105     TraitCandidate(ty::TraitRef<'tcx>),
106     WhereClauseCandidate(// Trait
107                          ty::PolyTraitRef<'tcx>),
108 }
109
110 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
111 enum ProbeResult {
112     NoMatch,
113     BadReturnType,
114     Match,
115 }
116
117 #[derive(Debug, PartialEq, Eq, Clone)]
118 pub struct Pick<'tcx> {
119     pub item: ty::AssociatedItem,
120     pub kind: PickKind<'tcx>,
121     pub import_id: Option<ast::NodeId>,
122
123     // Indicates that the source expression should be autoderef'd N times
124     //
125     // A = expr | *expr | **expr | ...
126     pub autoderefs: usize,
127
128     // Indicates that an autoref is applied after the optional autoderefs
129     //
130     // B = A | &A | &mut A
131     pub autoref: Option<hir::Mutability>,
132
133     // Indicates that the source expression should be "unsized" to a
134     // target type. This should probably eventually go away in favor
135     // of just coercing method receivers.
136     //
137     // C = B | unsize(B)
138     pub unsize: Option<Ty<'tcx>>,
139 }
140
141 #[derive(Clone, Debug, PartialEq, Eq)]
142 pub enum PickKind<'tcx> {
143     InherentImplPick,
144     ObjectPick,
145     TraitPick,
146     WhereClausePick(// Trait
147                     ty::PolyTraitRef<'tcx>),
148 }
149
150 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
151
152 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
153 pub enum Mode {
154     // An expression of the form `receiver.method_name(...)`.
155     // Autoderefs are performed on `receiver`, lookup is done based on the
156     // `self` argument  of the method, and static methods aren't considered.
157     MethodCall,
158     // An expression of the form `Type::item` or `<T>::item`.
159     // No autoderefs are performed, lookup is done based on the type each
160     // implementation is for, and static methods are included.
161     Path,
162 }
163
164 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
165 pub enum ProbeScope {
166     // Assemble candidates coming only from traits in scope.
167     TraitsInScope,
168
169     // Assemble candidates coming from all traits.
170     AllTraits,
171 }
172
173 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
174     /// This is used to offer suggestions to users. It returns methods
175     /// that could have been called which have the desired return
176     /// type. Some effort is made to rule out methods that, if called,
177     /// would result in an error (basically, the same criteria we
178     /// would use to decide if a method is a plausible fit for
179     /// ambiguity purposes).
180     pub fn probe_for_return_type(&self,
181                                  span: Span,
182                                  mode: Mode,
183                                  return_type: Ty<'tcx>,
184                                  self_ty: Ty<'tcx>,
185                                  scope_expr_id: ast::NodeId)
186                                  -> Vec<ty::AssociatedItem> {
187         debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
188                self_ty,
189                return_type,
190                scope_expr_id);
191         let method_names =
192             self.probe_op(span, mode, None, Some(return_type), IsSuggestion(true),
193                           self_ty, scope_expr_id, ProbeScope::TraitsInScope,
194                           |probe_cx| Ok(probe_cx.candidate_method_names()))
195                 .unwrap_or(vec![]);
196          method_names
197              .iter()
198              .flat_map(|&method_name| {
199                  self.probe_op(
200                      span, mode, Some(method_name), Some(return_type),
201                      IsSuggestion(true), self_ty, scope_expr_id,
202                      ProbeScope::TraitsInScope, |probe_cx| probe_cx.pick()
203                  ).ok().map(|pick| pick.item)
204              })
205             .collect()
206     }
207
208     pub fn probe_for_name(&self,
209                           span: Span,
210                           mode: Mode,
211                           item_name: ast::Name,
212                           is_suggestion: IsSuggestion,
213                           self_ty: Ty<'tcx>,
214                           scope_expr_id: ast::NodeId,
215                           scope: ProbeScope)
216                           -> PickResult<'tcx> {
217         debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
218                self_ty,
219                item_name,
220                scope_expr_id);
221         self.probe_op(span,
222                       mode,
223                       Some(item_name),
224                       None,
225                       is_suggestion,
226                       self_ty,
227                       scope_expr_id,
228                       scope,
229                       |probe_cx| probe_cx.pick())
230     }
231
232     fn probe_op<OP,R>(&'a self,
233                       span: Span,
234                       mode: Mode,
235                       method_name: Option<ast::Name>,
236                       return_type: Option<Ty<'tcx>>,
237                       is_suggestion: IsSuggestion,
238                       self_ty: Ty<'tcx>,
239                       scope_expr_id: ast::NodeId,
240                       scope: ProbeScope,
241                       op: OP)
242                       -> Result<R, MethodError<'tcx>>
243         where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
244     {
245         // FIXME(#18741) -- right now, creating the steps involves evaluating the
246         // `*` operator, which registers obligations that then escape into
247         // the global fulfillment context and thus has global
248         // side-effects. This is a bit of a pain to refactor. So just let
249         // it ride, although it's really not great, and in fact could I
250         // think cause spurious errors. Really though this part should
251         // take place in the `self.probe` below.
252         let steps = if mode == Mode::MethodCall {
253             match self.create_steps(span, scope_expr_id, self_ty, is_suggestion) {
254                 Some(steps) => steps,
255                 None => {
256                     return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
257                                                                      Vec::new(),
258                                                                      Vec::new(),
259                                                                      None,
260                                                                      mode)))
261                 }
262             }
263         } else {
264             vec![CandidateStep {
265                      self_ty,
266                      autoderefs: 0,
267                      from_unsafe_deref: false,
268                      unsize: false,
269                  }]
270         };
271
272         debug!("ProbeContext: steps for self_ty={:?} are {:?}",
273                self_ty,
274                steps);
275
276         // this creates one big transaction so that all type variables etc
277         // that we create during the probe process are removed later
278         self.probe(|_| {
279             let mut probe_cx =
280                 ProbeContext::new(self, span, mode, method_name, return_type, Rc::new(steps));
281
282             probe_cx.assemble_inherent_candidates();
283             match scope {
284                 ProbeScope::TraitsInScope =>
285                     probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?,
286                 ProbeScope::AllTraits =>
287                     probe_cx.assemble_extension_candidates_for_all_traits()?,
288             };
289             op(probe_cx)
290         })
291     }
292
293     fn create_steps(&self,
294                     span: Span,
295                     scope_expr_id: ast::NodeId,
296                     self_ty: Ty<'tcx>,
297                     is_suggestion: IsSuggestion)
298                     -> Option<Vec<CandidateStep<'tcx>>> {
299         // FIXME: we don't need to create the entire steps in one pass
300
301         let mut autoderef = self.autoderef(span, self_ty).include_raw_pointers();
302         let mut reached_raw_pointer = false;
303         let mut steps: Vec<_> = autoderef.by_ref()
304             .map(|(ty, d)| {
305                 let step = CandidateStep {
306                     self_ty: ty,
307                     autoderefs: d,
308                     from_unsafe_deref: reached_raw_pointer,
309                     unsize: false,
310                 };
311                 if let ty::TyRawPtr(_) = ty.sty {
312                     // all the subsequent steps will be from_unsafe_deref
313                     reached_raw_pointer = true;
314                 }
315                 step
316             })
317             .collect();
318
319         let final_ty = autoderef.maybe_ambiguous_final_ty();
320         match final_ty.sty {
321             ty::TyInfer(ty::TyVar(_)) => {
322                 // Ended in an inference variable. If we are doing
323                 // a real method lookup, this is a hard error because it's
324                 // possible that there will be multiple applicable methods.
325                 if !is_suggestion.0 {
326                     if reached_raw_pointer
327                     && !self.tcx.sess.features.borrow().arbitrary_self_types {
328                         // this case used to be allowed by the compiler,
329                         // so we do a future-compat lint here
330                         // (see https://github.com/rust-lang/rust/issues/46906)
331                         self.tcx.lint_node(
332                             lint::builtin::TYVAR_BEHIND_RAW_POINTER,
333                             scope_expr_id,
334                             span,
335                             &format!("the type of this value must be known in this context"));
336                     } else {
337                         let t = self.structurally_resolved_type(span, final_ty);
338                         assert_eq!(t, self.tcx.types.err);
339                         return None
340                     }
341                 } else {
342                     // If we're just looking for suggestions,
343                     // though, ambiguity is no big thing, we can
344                     // just ignore it.
345                 }
346             }
347             ty::TyArray(elem_ty, _) => {
348                 let dereferences = steps.len() - 1;
349
350                 steps.push(CandidateStep {
351                     self_ty: self.tcx.mk_slice(elem_ty),
352                     autoderefs: dereferences,
353                     // this could be from an unsafe deref if we had
354                     // a *mut/const [T; N]
355                     from_unsafe_deref: reached_raw_pointer,
356                     unsize: true,
357                 });
358             }
359             ty::TyError => return None,
360             _ => (),
361         }
362
363         debug!("create_steps: steps={:?}", steps);
364
365         Some(steps)
366     }
367 }
368
369 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
370     fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
371            span: Span,
372            mode: Mode,
373            method_name: Option<ast::Name>,
374            return_type: Option<Ty<'tcx>>,
375            steps: Rc<Vec<CandidateStep<'tcx>>>)
376            -> ProbeContext<'a, 'gcx, 'tcx> {
377         ProbeContext {
378             fcx,
379             span,
380             mode,
381             method_name,
382             return_type,
383             inherent_candidates: Vec::new(),
384             extension_candidates: Vec::new(),
385             impl_dups: FxHashSet(),
386             steps: steps,
387             static_candidates: Vec::new(),
388             allow_similar_names: false,
389             private_candidate: None,
390             unsatisfied_predicates: Vec::new(),
391         }
392     }
393
394     fn reset(&mut self) {
395         self.inherent_candidates.clear();
396         self.extension_candidates.clear();
397         self.impl_dups.clear();
398         self.static_candidates.clear();
399         self.private_candidate = None;
400     }
401
402     ///////////////////////////////////////////////////////////////////////////
403     // CANDIDATE ASSEMBLY
404
405     fn push_candidate(&mut self,
406                       candidate: Candidate<'tcx>,
407                       is_inherent: bool)
408     {
409         let is_accessible = if let Some(name) = self.method_name {
410             let item = candidate.item;
411             let def_scope = self.tcx.adjust(name, item.container.id(), self.body_id).1;
412             item.vis.is_accessible_from(def_scope, self.tcx)
413         } else {
414             true
415         };
416         if is_accessible {
417             if is_inherent {
418                 self.inherent_candidates.push(candidate);
419             } else {
420                 self.extension_candidates.push(candidate);
421             }
422         } else if self.private_candidate.is_none() {
423             self.private_candidate = Some(candidate.item.def());
424         }
425     }
426
427     fn assemble_inherent_candidates(&mut self) {
428         let steps = self.steps.clone();
429         for step in steps.iter() {
430             self.assemble_probe(step.self_ty);
431         }
432     }
433
434     fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
435         debug!("assemble_probe: self_ty={:?}", self_ty);
436         let lang_items = self.tcx.lang_items();
437
438         match self_ty.sty {
439             ty::TyDynamic(ref data, ..) => {
440                 if let Some(p) = data.principal() {
441                     self.assemble_inherent_candidates_from_object(self_ty, p);
442                     self.assemble_inherent_impl_candidates_for_type(p.def_id());
443                 }
444             }
445             ty::TyAdt(def, _) => {
446                 self.assemble_inherent_impl_candidates_for_type(def.did);
447             }
448             ty::TyForeign(did) => {
449                 self.assemble_inherent_impl_candidates_for_type(did);
450             }
451             ty::TyParam(p) => {
452                 self.assemble_inherent_candidates_from_param(self_ty, p);
453             }
454             ty::TyChar => {
455                 let lang_def_id = lang_items.char_impl();
456                 self.assemble_inherent_impl_for_primitive(lang_def_id);
457             }
458             ty::TyStr => {
459                 let lang_def_id = lang_items.str_impl();
460                 self.assemble_inherent_impl_for_primitive(lang_def_id);
461             }
462             ty::TySlice(_) => {
463                 let lang_def_id = lang_items.slice_impl();
464                 self.assemble_inherent_impl_for_primitive(lang_def_id);
465
466                 let lang_def_id = lang_items.slice_u8_impl();
467                 self.assemble_inherent_impl_for_primitive(lang_def_id);
468             }
469             ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
470                 let lang_def_id = lang_items.const_ptr_impl();
471                 self.assemble_inherent_impl_for_primitive(lang_def_id);
472             }
473             ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
474                 let lang_def_id = lang_items.mut_ptr_impl();
475                 self.assemble_inherent_impl_for_primitive(lang_def_id);
476             }
477             ty::TyInt(ast::IntTy::I8) => {
478                 let lang_def_id = lang_items.i8_impl();
479                 self.assemble_inherent_impl_for_primitive(lang_def_id);
480             }
481             ty::TyInt(ast::IntTy::I16) => {
482                 let lang_def_id = lang_items.i16_impl();
483                 self.assemble_inherent_impl_for_primitive(lang_def_id);
484             }
485             ty::TyInt(ast::IntTy::I32) => {
486                 let lang_def_id = lang_items.i32_impl();
487                 self.assemble_inherent_impl_for_primitive(lang_def_id);
488             }
489             ty::TyInt(ast::IntTy::I64) => {
490                 let lang_def_id = lang_items.i64_impl();
491                 self.assemble_inherent_impl_for_primitive(lang_def_id);
492             }
493             ty::TyInt(ast::IntTy::I128) => {
494                 let lang_def_id = lang_items.i128_impl();
495                 self.assemble_inherent_impl_for_primitive(lang_def_id);
496             }
497             ty::TyInt(ast::IntTy::Isize) => {
498                 let lang_def_id = lang_items.isize_impl();
499                 self.assemble_inherent_impl_for_primitive(lang_def_id);
500             }
501             ty::TyUint(ast::UintTy::U8) => {
502                 let lang_def_id = lang_items.u8_impl();
503                 self.assemble_inherent_impl_for_primitive(lang_def_id);
504             }
505             ty::TyUint(ast::UintTy::U16) => {
506                 let lang_def_id = lang_items.u16_impl();
507                 self.assemble_inherent_impl_for_primitive(lang_def_id);
508             }
509             ty::TyUint(ast::UintTy::U32) => {
510                 let lang_def_id = lang_items.u32_impl();
511                 self.assemble_inherent_impl_for_primitive(lang_def_id);
512             }
513             ty::TyUint(ast::UintTy::U64) => {
514                 let lang_def_id = lang_items.u64_impl();
515                 self.assemble_inherent_impl_for_primitive(lang_def_id);
516             }
517             ty::TyUint(ast::UintTy::U128) => {
518                 let lang_def_id = lang_items.u128_impl();
519                 self.assemble_inherent_impl_for_primitive(lang_def_id);
520             }
521             ty::TyUint(ast::UintTy::Usize) => {
522                 let lang_def_id = lang_items.usize_impl();
523                 self.assemble_inherent_impl_for_primitive(lang_def_id);
524             }
525             ty::TyFloat(ast::FloatTy::F32) => {
526                 let lang_def_id = lang_items.f32_impl();
527                 self.assemble_inherent_impl_for_primitive(lang_def_id);
528             }
529             ty::TyFloat(ast::FloatTy::F64) => {
530                 let lang_def_id = lang_items.f64_impl();
531                 self.assemble_inherent_impl_for_primitive(lang_def_id);
532             }
533             _ => {}
534         }
535     }
536
537     fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
538         if let Some(impl_def_id) = lang_def_id {
539             self.assemble_inherent_impl_probe(impl_def_id);
540         }
541     }
542
543     fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
544         let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
545         for &impl_def_id in impl_def_ids.iter() {
546             self.assemble_inherent_impl_probe(impl_def_id);
547         }
548     }
549
550     fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
551         if !self.impl_dups.insert(impl_def_id) {
552             return; // already visited
553         }
554
555         debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
556
557         for item in self.impl_or_trait_item(impl_def_id) {
558             if !self.has_applicable_self(&item) {
559                 // No receiver declared. Not a candidate.
560                 self.record_static_candidate(ImplSource(impl_def_id));
561                 continue
562             }
563
564             let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
565             let impl_ty = impl_ty.subst(self.tcx, impl_substs);
566
567             // Determine the receiver type that the method itself expects.
568             let xform_tys = self.xform_self_ty(&item, impl_ty, impl_substs);
569
570             // We can't use normalize_associated_types_in as it will pollute the
571             // fcx's fulfillment context after this probe is over.
572             let cause = traits::ObligationCause::misc(self.span, self.body_id);
573             let selcx = &mut traits::SelectionContext::new(self.fcx);
574             let traits::Normalized { value: (xform_self_ty, xform_ret_ty), obligations } =
575                 traits::normalize(selcx, self.param_env, cause, &xform_tys);
576             debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}/{:?}",
577                    xform_self_ty, xform_ret_ty);
578
579             self.push_candidate(Candidate {
580                 xform_self_ty, xform_ret_ty, item,
581                 kind: InherentImplCandidate(impl_substs, obligations),
582                 import_id: None
583             }, true);
584         }
585     }
586
587     fn assemble_inherent_candidates_from_object(&mut self,
588                                                 self_ty: Ty<'tcx>,
589                                                 principal: ty::PolyExistentialTraitRef<'tcx>) {
590         debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
591                self_ty);
592
593         // It is illegal to invoke a method on a trait instance that
594         // refers to the `Self` type. An error will be reported by
595         // `enforce_object_limitations()` if the method refers to the
596         // `Self` type anywhere other than the receiver. Here, we use
597         // a substitution that replaces `Self` with the object type
598         // itself. Hence, a `&self` method will wind up with an
599         // argument type like `&Trait`.
600         let trait_ref = principal.with_self_ty(self.tcx, self_ty);
601         self.elaborate_bounds(&[trait_ref], |this, new_trait_ref, item| {
602             let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
603
604             let (xform_self_ty, xform_ret_ty) =
605                 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
606             this.push_candidate(Candidate {
607                 xform_self_ty, xform_ret_ty, item,
608                 kind: ObjectCandidate,
609                 import_id: None
610             }, true);
611         });
612     }
613
614     fn assemble_inherent_candidates_from_param(&mut self,
615                                                _rcvr_ty: Ty<'tcx>,
616                                                param_ty: ty::ParamTy) {
617         // FIXME -- Do we want to commit to this behavior for param bounds?
618
619         let bounds: Vec<_> = self.param_env
620             .caller_bounds
621             .iter()
622             .filter_map(|predicate| {
623                 match *predicate {
624                     ty::Predicate::Trait(ref trait_predicate) => {
625                         match trait_predicate.0.trait_ref.self_ty().sty {
626                             ty::TyParam(ref p) if *p == param_ty => {
627                                 Some(trait_predicate.to_poly_trait_ref())
628                             }
629                             _ => None,
630                         }
631                     }
632                     ty::Predicate::Equate(..) |
633                     ty::Predicate::Subtype(..) |
634                     ty::Predicate::Projection(..) |
635                     ty::Predicate::RegionOutlives(..) |
636                     ty::Predicate::WellFormed(..) |
637                     ty::Predicate::ObjectSafe(..) |
638                     ty::Predicate::ClosureKind(..) |
639                     ty::Predicate::TypeOutlives(..) |
640                     ty::Predicate::ConstEvaluatable(..) => None,
641                 }
642             })
643             .collect();
644
645         self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
646             let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
647
648             let (xform_self_ty, xform_ret_ty) =
649                 this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
650
651             // Because this trait derives from a where-clause, it
652             // should not contain any inference variables or other
653             // artifacts. This means it is safe to put into the
654             // `WhereClauseCandidate` and (eventually) into the
655             // `WhereClausePick`.
656             assert!(!trait_ref.substs.needs_infer());
657
658             this.push_candidate(Candidate {
659                 xform_self_ty, xform_ret_ty, item,
660                 kind: WhereClauseCandidate(poly_trait_ref),
661                 import_id: None
662             }, true);
663         });
664     }
665
666     // Do a search through a list of bounds, using a callback to actually
667     // create the candidates.
668     fn elaborate_bounds<F>(&mut self, bounds: &[ty::PolyTraitRef<'tcx>], mut mk_cand: F)
669         where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>,
670                                ty::PolyTraitRef<'tcx>,
671                                ty::AssociatedItem)
672     {
673         debug!("elaborate_bounds(bounds={:?})", bounds);
674
675         let tcx = self.tcx;
676         for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
677             for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
678                 if !self.has_applicable_self(&item) {
679                     self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
680                 } else {
681                     mk_cand(self, bound_trait_ref, item);
682                 }
683             }
684         }
685     }
686
687     fn assemble_extension_candidates_for_traits_in_scope(&mut self,
688                                                          expr_id: ast::NodeId)
689                                                          -> Result<(), MethodError<'tcx>> {
690         if expr_id == ast::DUMMY_NODE_ID {
691             return Ok(())
692         }
693         let mut duplicates = FxHashSet();
694         let expr_hir_id = self.tcx.hir.node_to_hir_id(expr_id);
695         let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
696         if let Some(applicable_traits) = opt_applicable_traits {
697             for trait_candidate in applicable_traits.iter() {
698                 let trait_did = trait_candidate.def_id;
699                 if duplicates.insert(trait_did) {
700                     let import_id = trait_candidate.import_id;
701                     let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
702                     result?;
703                 }
704             }
705         }
706         Ok(())
707     }
708
709     fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
710         let mut duplicates = FxHashSet();
711         for trait_info in suggest::all_traits(self.tcx) {
712             if duplicates.insert(trait_info.def_id) {
713                 self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
714             }
715         }
716         Ok(())
717     }
718
719     pub fn matches_return_type(&self,
720                                method: &ty::AssociatedItem,
721                                self_ty: Option<Ty<'tcx>>,
722                                expected: Ty<'tcx>) -> bool {
723         match method.def() {
724             Def::Method(def_id) => {
725                 let fty = self.tcx.fn_sig(def_id);
726                 self.probe(|_| {
727                     let substs = self.fresh_substs_for_item(self.span, method.def_id);
728                     let fty = fty.subst(self.tcx, substs);
729                     let (fty, _) = self.replace_late_bound_regions_with_fresh_var(
730                         self.span, infer::FnCall, &fty);
731
732                     if let Some(self_ty) = self_ty {
733                         if let Err(_) = self.at(&ObligationCause::dummy(), self.param_env)
734                             .sup(fty.inputs()[0], self_ty)
735                         {
736                             return false
737                         }
738                     }
739                     self.can_sub(self.param_env, fty.output(), expected).is_ok()
740                 })
741             }
742             _ => false,
743         }
744     }
745
746     fn assemble_extension_candidates_for_trait(&mut self,
747                                                import_id: Option<ast::NodeId>,
748                                                trait_def_id: DefId)
749                                                -> Result<(), MethodError<'tcx>> {
750         debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
751                trait_def_id);
752         let trait_substs = self.fresh_item_substs(trait_def_id);
753         let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
754
755         for item in self.impl_or_trait_item(trait_def_id) {
756             // Check whether `trait_def_id` defines a method with suitable name:
757             if !self.has_applicable_self(&item) {
758                 debug!("method has inapplicable self");
759                 self.record_static_candidate(TraitSource(trait_def_id));
760                 continue;
761             }
762
763             let (xform_self_ty, xform_ret_ty) =
764                 self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
765             self.push_candidate(Candidate {
766                 xform_self_ty, xform_ret_ty, item, import_id,
767                 kind: TraitCandidate(trait_ref),
768             }, false);
769         }
770         Ok(())
771     }
772
773     fn candidate_method_names(&self) -> Vec<ast::Name> {
774         let mut set = FxHashSet();
775         let mut names: Vec<_> = self.inherent_candidates
776             .iter()
777             .chain(&self.extension_candidates)
778             .filter(|candidate| {
779                 if let Some(return_ty) = self.return_type {
780                     self.matches_return_type(&candidate.item, None, return_ty)
781                 } else {
782                     true
783                 }
784             })
785             .map(|candidate| candidate.item.name)
786             .filter(|&name| set.insert(name))
787             .collect();
788
789         // sort them by the name so we have a stable result
790         names.sort_by_key(|n| n.as_str());
791         names
792     }
793
794     ///////////////////////////////////////////////////////////////////////////
795     // THE ACTUAL SEARCH
796
797     fn pick(mut self) -> PickResult<'tcx> {
798         assert!(self.method_name.is_some());
799
800         if let Some(r) = self.pick_core() {
801             return r;
802         }
803
804         let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
805         let private_candidate = mem::replace(&mut self.private_candidate, None);
806         let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
807
808         // things failed, so lets look at all traits, for diagnostic purposes now:
809         self.reset();
810
811         let span = self.span;
812         let tcx = self.tcx;
813
814         self.assemble_extension_candidates_for_all_traits()?;
815
816         let out_of_scope_traits = match self.pick_core() {
817             Some(Ok(p)) => vec![p.item.container.id()],
818             //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
819             Some(Err(MethodError::Ambiguity(v))) => {
820                 v.into_iter()
821                     .map(|source| {
822                         match source {
823                             TraitSource(id) => id,
824                             ImplSource(impl_id) => {
825                                 match tcx.trait_id_of_impl(impl_id) {
826                                     Some(id) => id,
827                                     None => {
828                                         span_bug!(span,
829                                                   "found inherent method when looking at traits")
830                                     }
831                                 }
832                             }
833                         }
834                     })
835                     .collect()
836             }
837             Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
838                 assert!(others.is_empty());
839                 vec![]
840             }
841             _ => vec![],
842         };
843
844         if let Some(def) = private_candidate {
845             return Err(MethodError::PrivateMatch(def, out_of_scope_traits));
846         }
847         let lev_candidate = self.probe_for_lev_candidate()?;
848
849         Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
850                                                   unsatisfied_predicates,
851                                                   out_of_scope_traits,
852                                                   lev_candidate,
853                                                   self.mode)))
854     }
855
856     fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
857         let steps = self.steps.clone();
858
859         // find the first step that works
860         steps
861             .iter()
862             .filter(|step| {
863                 debug!("pick_core: step={:?}", step);
864                 // skip types that are from a type error or that would require dereferencing
865                 // a raw pointer
866                 !step.self_ty.references_error() && !step.from_unsafe_deref
867             }).flat_map(|step| {
868                 self.pick_by_value_method(step).or_else(|| {
869                 self.pick_autorefd_method(step, hir::MutImmutable).or_else(|| {
870                 self.pick_autorefd_method(step, hir::MutMutable)
871             })})})
872             .next()
873     }
874
875     fn pick_by_value_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
876         //! For each type `T` in the step list, this attempts to find a
877         //! method where the (transformed) self type is exactly `T`. We
878         //! do however do one transformation on the adjustment: if we
879         //! are passing a region pointer in, we will potentially
880         //! *reborrow* it to a shorter lifetime. This allows us to
881         //! transparently pass `&mut` pointers, in particular, without
882         //! consuming them for their entire lifetime.
883
884         if step.unsize {
885             return None;
886         }
887
888         self.pick_method(step.self_ty).map(|r| {
889             r.map(|mut pick| {
890                 pick.autoderefs = step.autoderefs;
891
892                 // Insert a `&*` or `&mut *` if this is a reference type:
893                 if let ty::TyRef(_, mt) = step.self_ty.sty {
894                     pick.autoderefs += 1;
895                     pick.autoref = Some(mt.mutbl);
896                 }
897
898                 pick
899             })
900         })
901     }
902
903     fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>, mutbl: hir::Mutability)
904                             -> Option<PickResult<'tcx>> {
905         let tcx = self.tcx;
906
907         // In general, during probing we erase regions. See
908         // `impl_self_ty()` for an explanation.
909         let region = tcx.types.re_erased;
910
911         let autoref_ty = tcx.mk_ref(region,
912                                     ty::TypeAndMut {
913                                         ty: step.self_ty, mutbl
914                                     });
915         self.pick_method(autoref_ty).map(|r| {
916             r.map(|mut pick| {
917                 pick.autoderefs = step.autoderefs;
918                 pick.autoref = Some(mutbl);
919                 pick.unsize = if step.unsize {
920                     Some(step.self_ty)
921                 } else {
922                     None
923                 };
924                 pick
925             })
926         })
927     }
928
929     fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
930         debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
931
932         let mut possibly_unsatisfied_predicates = Vec::new();
933
934         debug!("searching inherent candidates");
935         if let Some(pick) = self.consider_candidates(self_ty,
936                                                      &self.inherent_candidates,
937                                                      &mut possibly_unsatisfied_predicates) {
938             return Some(pick);
939         }
940
941         debug!("searching extension candidates");
942         let res = self.consider_candidates(self_ty,
943                                            &self.extension_candidates,
944                                            &mut possibly_unsatisfied_predicates);
945         if let None = res {
946             self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
947         }
948         res
949     }
950
951     fn consider_candidates(&self,
952                            self_ty: Ty<'tcx>,
953                            probes: &[Candidate<'tcx>],
954                            possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
955                            -> Option<PickResult<'tcx>> {
956         let mut applicable_candidates: Vec<_> = probes.iter()
957             .map(|probe| {
958                 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
959             })
960             .filter(|&(_, status)| status != ProbeResult::NoMatch)
961             .collect();
962
963         debug!("applicable_candidates: {:?}", applicable_candidates);
964
965         if applicable_candidates.len() > 1 {
966             if let Some(pick) = self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
967                 return Some(Ok(pick));
968             }
969         }
970
971         if applicable_candidates.len() > 1 {
972             let sources = probes.iter()
973                 .map(|p| self.candidate_source(p, self_ty))
974                 .collect();
975             return Some(Err(MethodError::Ambiguity(sources)));
976         }
977
978         applicable_candidates.pop().map(|(probe, status)| {
979             if status == ProbeResult::Match {
980                 Ok(probe.to_unadjusted_pick())
981             } else {
982                 Err(MethodError::BadReturnType)
983             }
984         })
985     }
986
987     fn select_trait_candidate(&self, trait_ref: ty::TraitRef<'tcx>)
988                               -> traits::SelectionResult<'tcx, traits::Selection<'tcx>>
989     {
990         let cause = traits::ObligationCause::misc(self.span, self.body_id);
991         let predicate =
992             trait_ref.to_poly_trait_ref().to_poly_trait_predicate();
993         let obligation = traits::Obligation::new(cause, self.param_env, predicate);
994         traits::SelectionContext::new(self).select(&obligation)
995     }
996
997     fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>)
998                         -> CandidateSource
999     {
1000         match candidate.kind {
1001             InherentImplCandidate(..) => ImplSource(candidate.item.container.id()),
1002             ObjectCandidate |
1003             WhereClauseCandidate(_) => TraitSource(candidate.item.container.id()),
1004             TraitCandidate(trait_ref) => self.probe(|_| {
1005                 let _ = self.at(&ObligationCause::dummy(), self.param_env)
1006                     .sup(candidate.xform_self_ty, self_ty);
1007                 match self.select_trait_candidate(trait_ref) {
1008                     Ok(Some(traits::Vtable::VtableImpl(ref impl_data))) => {
1009                         // If only a single impl matches, make the error message point
1010                         // to that impl.
1011                         ImplSource(impl_data.impl_def_id)
1012                     }
1013                     _ => {
1014                         TraitSource(candidate.item.container.id())
1015                     }
1016                 }
1017             })
1018         }
1019     }
1020
1021     fn consider_probe(&self,
1022                       self_ty: Ty<'tcx>,
1023                       probe: &Candidate<'tcx>,
1024                       possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1025                       -> ProbeResult {
1026         debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1027
1028         self.probe(|_| {
1029             // First check that the self type can be related.
1030             let sub_obligations = match self.at(&ObligationCause::dummy(), self.param_env)
1031                                             .sup(probe.xform_self_ty, self_ty) {
1032                 Ok(InferOk { obligations, value: () }) => obligations,
1033                 Err(_) => {
1034                     debug!("--> cannot relate self-types");
1035                     return ProbeResult::NoMatch;
1036                 }
1037             };
1038
1039             let mut result = ProbeResult::Match;
1040             let selcx = &mut traits::SelectionContext::new(self);
1041             let cause = traits::ObligationCause::misc(self.span, self.body_id);
1042
1043             // If so, impls may carry other conditions (e.g., where
1044             // clauses) that must be considered. Make sure that those
1045             // match as well (or at least may match, sometimes we
1046             // don't have enough information to fully evaluate).
1047             let candidate_obligations : Vec<_> = match probe.kind {
1048                 InherentImplCandidate(ref substs, ref ref_obligations) => {
1049                     // Check whether the impl imposes obligations we have to worry about.
1050                     let impl_def_id = probe.item.container.id();
1051                     let impl_bounds = self.tcx.predicates_of(impl_def_id);
1052                     let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1053                     let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1054                         traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
1055
1056                     // Convert the bounds into obligations.
1057                     let impl_obligations = traits::predicates_for_generics(
1058                         cause.clone(), self.param_env, &impl_bounds);
1059
1060                     debug!("impl_obligations={:?}", impl_obligations);
1061                     impl_obligations.into_iter()
1062                         .chain(norm_obligations.into_iter())
1063                         .chain(ref_obligations.iter().cloned())
1064                         .collect()
1065                 }
1066
1067                 ObjectCandidate |
1068                 WhereClauseCandidate(..) => {
1069                     // These have no additional conditions to check.
1070                     vec![]
1071                 }
1072
1073                 TraitCandidate(trait_ref) => {
1074                     let predicate = trait_ref.to_predicate();
1075                     let obligation =
1076                         traits::Obligation::new(cause.clone(), self.param_env, predicate);
1077                     if !selcx.evaluate_obligation(&obligation) {
1078                         if self.probe(|_| self.select_trait_candidate(trait_ref).is_err()) {
1079                             // This candidate's primary obligation doesn't even
1080                             // select - don't bother registering anything in
1081                             // `potentially_unsatisfied_predicates`.
1082                             return ProbeResult::NoMatch;
1083                         } else {
1084                             // Some nested subobligation of this predicate
1085                             // failed.
1086                             //
1087                             // FIXME: try to find the exact nested subobligation
1088                             // and point at it rather than reporting the entire
1089                             // trait-ref?
1090                             result = ProbeResult::NoMatch;
1091                             let trait_ref = self.resolve_type_vars_if_possible(&trait_ref);
1092                             possibly_unsatisfied_predicates.push(trait_ref);
1093                         }
1094                     }
1095                     vec![]
1096                 }
1097             };
1098
1099             debug!("consider_probe - candidate_obligations={:?} sub_obligations={:?}",
1100                    candidate_obligations, sub_obligations);
1101
1102             // Evaluate those obligations to see if they might possibly hold.
1103             for o in candidate_obligations.into_iter().chain(sub_obligations) {
1104                 let o = self.resolve_type_vars_if_possible(&o);
1105                 if !selcx.evaluate_obligation(&o) {
1106                     result = ProbeResult::NoMatch;
1107                     if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1108                         possibly_unsatisfied_predicates.push(pred.0.trait_ref);
1109                     }
1110                 }
1111             }
1112
1113             if let ProbeResult::Match = result {
1114                 if let (Some(return_ty), Some(xform_ret_ty)) =
1115                     (self.return_type, probe.xform_ret_ty)
1116                 {
1117                     let xform_ret_ty = self.resolve_type_vars_if_possible(&xform_ret_ty);
1118                     debug!("comparing return_ty {:?} with xform ret ty {:?}",
1119                            return_ty,
1120                            probe.xform_ret_ty);
1121                     if self.at(&ObligationCause::dummy(), self.param_env)
1122                         .sup(return_ty, xform_ret_ty)
1123                         .is_err()
1124                     {
1125                         return ProbeResult::BadReturnType;
1126                     }
1127                 }
1128             }
1129
1130             result
1131         })
1132     }
1133
1134     /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1135     /// same trait, but we don't know which impl to use. In this case, since in all cases the
1136     /// external interface of the method can be determined from the trait, it's ok not to decide.
1137     /// We can basically just collapse all of the probes for various impls into one where-clause
1138     /// probe. This will result in a pending obligation so when more type-info is available we can
1139     /// make the final decision.
1140     ///
1141     /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1142     ///
1143     /// ```
1144     /// trait Foo { ... }
1145     /// impl Foo for Vec<int> { ... }
1146     /// impl Foo for Vec<usize> { ... }
1147     /// ```
1148     ///
1149     /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1150     /// use, so it's ok to just commit to "using the method from the trait Foo".
1151     fn collapse_candidates_to_trait_pick(&self, probes: &[(&Candidate<'tcx>, ProbeResult)])
1152                                          -> Option<Pick<'tcx>>
1153     {
1154         // Do all probes correspond to the same trait?
1155         let container = probes[0].0.item.container;
1156         match container {
1157             ty::TraitContainer(_) => {}
1158             ty::ImplContainer(_) => return None,
1159         }
1160         if probes[1..].iter().any(|&(p, _)| p.item.container != container) {
1161             return None;
1162         }
1163
1164         // FIXME: check the return type here somehow.
1165         // If so, just use this trait and call it a day.
1166         Some(Pick {
1167             item: probes[0].0.item.clone(),
1168             kind: TraitPick,
1169             import_id: probes[0].0.import_id,
1170             autoderefs: 0,
1171             autoref: None,
1172             unsize: None,
1173         })
1174     }
1175
1176     /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
1177     /// candidate method where the method name may have been misspelt. Similarly to other
1178     /// Levenshtein based suggestions, we provide at most one such suggestion.
1179     fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssociatedItem>, MethodError<'tcx>> {
1180         debug!("Probing for method names similar to {:?}",
1181                self.method_name);
1182
1183         let steps = self.steps.clone();
1184         self.probe(|_| {
1185             let mut pcx = ProbeContext::new(self.fcx, self.span, self.mode, self.method_name,
1186                                             self.return_type, steps);
1187             pcx.allow_similar_names = true;
1188             pcx.assemble_inherent_candidates();
1189             pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)?;
1190
1191             let method_names = pcx.candidate_method_names();
1192             pcx.allow_similar_names = false;
1193             let applicable_close_candidates: Vec<ty::AssociatedItem> = method_names
1194                 .iter()
1195                 .filter_map(|&method_name| {
1196                     pcx.reset();
1197                     pcx.method_name = Some(method_name);
1198                     pcx.assemble_inherent_candidates();
1199                     pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)
1200                         .ok().map_or(None, |_| {
1201                             pcx.pick_core()
1202                                 .and_then(|pick| pick.ok())
1203                                 .and_then(|pick| Some(pick.item))
1204                         })
1205                 })
1206                .collect();
1207
1208             if applicable_close_candidates.is_empty() {
1209                 Ok(None)
1210             } else {
1211                 let best_name = {
1212                     let names = applicable_close_candidates.iter().map(|cand| &cand.name);
1213                     find_best_match_for_name(names,
1214                                              &self.method_name.unwrap().as_str(),
1215                                              None)
1216                 }.unwrap();
1217                 Ok(applicable_close_candidates
1218                    .into_iter()
1219                    .find(|method| method.name == best_name))
1220             }
1221         })
1222     }
1223
1224     ///////////////////////////////////////////////////////////////////////////
1225     // MISCELLANY
1226     fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1227         // "Fast track" -- check for usage of sugar when in method call
1228         // mode.
1229         //
1230         // In Path mode (i.e., resolving a value like `T::next`), consider any
1231         // associated value (i.e., methods, constants) but not types.
1232         match self.mode {
1233             Mode::MethodCall => item.method_has_self_argument,
1234             Mode::Path => match item.kind {
1235                 ty::AssociatedKind::Type => false,
1236                 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1237             },
1238         }
1239         // FIXME -- check for types that deref to `Self`,
1240         // like `Rc<Self>` and so on.
1241         //
1242         // Note also that the current code will break if this type
1243         // includes any of the type parameters defined on the method
1244         // -- but this could be overcome.
1245     }
1246
1247     fn record_static_candidate(&mut self, source: CandidateSource) {
1248         self.static_candidates.push(source);
1249     }
1250
1251     fn xform_self_ty(&self,
1252                      item: &ty::AssociatedItem,
1253                      impl_ty: Ty<'tcx>,
1254                      substs: &Substs<'tcx>)
1255                      -> (Ty<'tcx>, Option<Ty<'tcx>>) {
1256         if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1257             let sig = self.xform_method_sig(item.def_id, substs);
1258             (sig.inputs()[0], Some(sig.output()))
1259         } else {
1260             (impl_ty, None)
1261         }
1262     }
1263
1264     fn xform_method_sig(&self,
1265                         method: DefId,
1266                         substs: &Substs<'tcx>)
1267                         -> ty::FnSig<'tcx>
1268     {
1269         let fn_sig = self.tcx.fn_sig(method);
1270         debug!("xform_self_ty(fn_sig={:?}, substs={:?})",
1271                fn_sig,
1272                substs);
1273
1274         assert!(!substs.has_escaping_regions());
1275
1276         // It is possible for type parameters or early-bound lifetimes
1277         // to appear in the signature of `self`. The substitutions we
1278         // are given do not include type/lifetime parameters for the
1279         // method yet. So create fresh variables here for those too,
1280         // if there are any.
1281         let generics = self.tcx.generics_of(method);
1282         assert_eq!(substs.types().count(), generics.parent_types as usize);
1283         assert_eq!(substs.regions().count(), generics.parent_regions as usize);
1284
1285         // Erase any late-bound regions from the method and substitute
1286         // in the values from the substitution.
1287         let xform_fn_sig = self.erase_late_bound_regions(&fn_sig);
1288
1289         if generics.types.is_empty() && generics.regions.is_empty() {
1290             xform_fn_sig.subst(self.tcx, substs)
1291         } else {
1292             let substs = Substs::for_item(self.tcx, method, |def, _| {
1293                 let i = def.index as usize;
1294                 if i < substs.len() {
1295                     substs.region_at(i)
1296                 } else {
1297                     // In general, during probe we erase regions. See
1298                     // `impl_self_ty()` for an explanation.
1299                     self.tcx.types.re_erased
1300                 }
1301             }, |def, cur_substs| {
1302                 let i = def.index as usize;
1303                 if i < substs.len() {
1304                     substs.type_at(i)
1305                 } else {
1306                     self.type_var_for_def(self.span, def, cur_substs)
1307                 }
1308             });
1309             xform_fn_sig.subst(self.tcx, substs)
1310         }
1311     }
1312
1313     /// Get the type of an impl and generate substitutions with placeholders.
1314     fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
1315         (self.tcx.type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1316     }
1317
1318     fn fresh_item_substs(&self, def_id: DefId) -> &'tcx Substs<'tcx> {
1319         Substs::for_item(self.tcx,
1320                          def_id,
1321                          |_, _| self.tcx.types.re_erased,
1322                          |_, _| self.next_ty_var(
1323                              TypeVariableOrigin::SubstitutionPlaceholder(
1324                                  self.tcx.def_span(def_id))))
1325     }
1326
1327     /// Replace late-bound-regions bound by `value` with `'static` using
1328     /// `ty::erase_late_bound_regions`.
1329     ///
1330     /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1331     /// method matching. It is reasonable during the probe phase because we don't consider region
1332     /// relationships at all. Therefore, we can just replace all the region variables with 'static
1333     /// rather than creating fresh region variables. This is nice for two reasons:
1334     ///
1335     /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1336     ///    particular method call, it winds up creating fewer types overall, which helps for memory
1337     ///    usage. (Admittedly, this is a rather small effect, though measureable.)
1338     ///
1339     /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1340     ///    late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1341     ///    regions with actual region variables as is proper, we'd have to ensure that the same
1342     ///    region got replaced with the same variable, which requires a bit more coordination
1343     ///    and/or tracking the substitution and
1344     ///    so forth.
1345     fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1346         where T: TypeFoldable<'tcx>
1347     {
1348         self.tcx.erase_late_bound_regions(value)
1349     }
1350
1351     /// Find the method with the appropriate name (or return type, as the case may be). If
1352     /// `allow_similar_names` is set, find methods with close-matching names.
1353     fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1354         if let Some(name) = self.method_name {
1355             if self.allow_similar_names {
1356                 let max_dist = max(name.as_str().len(), 3) / 3;
1357                 self.tcx.associated_items(def_id)
1358                     .filter(|x| {
1359                         let dist = lev_distance(&*name.as_str(), &x.name.as_str());
1360                         Namespace::from(x.kind) == Namespace::Value && dist > 0
1361                         && dist <= max_dist
1362                     })
1363                     .collect()
1364             } else {
1365                 self.fcx
1366                     .associated_item(def_id, name, Namespace::Value)
1367                     .map_or(Vec::new(), |x| vec![x])
1368             }
1369         } else {
1370             self.tcx.associated_items(def_id).collect()
1371         }
1372     }
1373 }
1374
1375 impl<'tcx> Candidate<'tcx> {
1376     fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1377         Pick {
1378             item: self.item.clone(),
1379             kind: match self.kind {
1380                 InherentImplCandidate(..) => InherentImplPick,
1381                 ObjectCandidate => ObjectPick,
1382                 TraitCandidate(_) => TraitPick,
1383                 WhereClauseCandidate(ref trait_ref) => {
1384                     // Only trait derived from where-clauses should
1385                     // appear here, so they should not contain any
1386                     // inference variables or other artifacts. This
1387                     // means they are safe to put into the
1388                     // `WhereClausePick`.
1389                     assert!(!trait_ref.substs().needs_infer());
1390
1391                     WhereClausePick(trait_ref.clone())
1392                 }
1393             },
1394             import_id: self.import_id,
1395             autoderefs: 0,
1396             autoref: None,
1397             unsize: None,
1398         }
1399     }
1400 }