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