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