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