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