]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/probe.rs
hir: remove NodeId from Expr
[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: hir::HirId)
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: hir::HirId,
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: hir::HirId,
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_hir(
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_hir_id: hir::HirId)
829                                                          -> Result<(), MethodError<'tcx>> {
830         if expr_hir_id == hir::DUMMY_HIR_ID {
831             return Ok(())
832         }
833         let mut duplicates = FxHashSet::default();
834         let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
835         if let Some(applicable_traits) = opt_applicable_traits {
836             for trait_candidate in applicable_traits.iter() {
837                 let trait_did = trait_candidate.def_id;
838                 if duplicates.insert(trait_did) {
839                     let import_id = trait_candidate.import_id;
840                     let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
841                     result?;
842                 }
843             }
844         }
845         Ok(())
846     }
847
848     fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
849         let mut duplicates = FxHashSet::default();
850         for trait_info in suggest::all_traits(self.tcx) {
851             if duplicates.insert(trait_info.def_id) {
852                 self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
853             }
854         }
855         Ok(())
856     }
857
858     pub fn matches_return_type(&self,
859                                method: &ty::AssociatedItem,
860                                self_ty: Option<Ty<'tcx>>,
861                                expected: Ty<'tcx>) -> bool {
862         match method.def() {
863             Def::Method(def_id) => {
864                 let fty = self.tcx.fn_sig(def_id);
865                 self.probe(|_| {
866                     let substs = self.fresh_substs_for_item(self.span, method.def_id);
867                     let fty = fty.subst(self.tcx, substs);
868                     let (fty, _) = self.replace_bound_vars_with_fresh_vars(
869                         self.span,
870                         infer::FnCall,
871                         &fty
872                     );
873
874                     if let Some(self_ty) = self_ty {
875                         if self.at(&ObligationCause::dummy(), self.param_env)
876                                .sup(fty.inputs()[0], self_ty)
877                                .is_err()
878                         {
879                             return false
880                         }
881                     }
882                     self.can_sub(self.param_env, fty.output(), expected).is_ok()
883                 })
884             }
885             _ => false,
886         }
887     }
888
889     fn assemble_extension_candidates_for_trait(&mut self,
890                                                import_id: Option<ast::NodeId>,
891                                                trait_def_id: DefId)
892                                                -> Result<(), MethodError<'tcx>> {
893         debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
894                trait_def_id);
895         let trait_substs = self.fresh_item_substs(trait_def_id);
896         let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
897
898         for item in self.impl_or_trait_item(trait_def_id) {
899             // Check whether `trait_def_id` defines a method with suitable name:
900             if !self.has_applicable_self(&item) {
901                 debug!("method has inapplicable self");
902                 self.record_static_candidate(TraitSource(trait_def_id));
903                 continue;
904             }
905
906             let (xform_self_ty, xform_ret_ty) =
907                 self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
908             self.push_candidate(Candidate {
909                 xform_self_ty, xform_ret_ty, item, import_id,
910                 kind: TraitCandidate(trait_ref),
911             }, false);
912         }
913         Ok(())
914     }
915
916     fn candidate_method_names(&self) -> Vec<ast::Ident> {
917         let mut set = FxHashSet::default();
918         let mut names: Vec<_> = self.inherent_candidates
919             .iter()
920             .chain(&self.extension_candidates)
921             .filter(|candidate| {
922                 if let Some(return_ty) = self.return_type {
923                     self.matches_return_type(&candidate.item, None, return_ty)
924                 } else {
925                     true
926                 }
927             })
928             .map(|candidate| candidate.item.ident)
929             .filter(|&name| set.insert(name))
930             .collect();
931
932         // sort them by the name so we have a stable result
933         names.sort_by_cached_key(|n| n.as_str());
934         names
935     }
936
937     ///////////////////////////////////////////////////////////////////////////
938     // THE ACTUAL SEARCH
939
940     fn pick(mut self) -> PickResult<'tcx> {
941         assert!(self.method_name.is_some());
942
943         if let Some(r) = self.pick_core() {
944             return r;
945         }
946
947         let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
948         let private_candidate = self.private_candidate.take();
949         let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
950
951         // things failed, so lets look at all traits, for diagnostic purposes now:
952         self.reset();
953
954         let span = self.span;
955         let tcx = self.tcx;
956
957         self.assemble_extension_candidates_for_all_traits()?;
958
959         let out_of_scope_traits = match self.pick_core() {
960             Some(Ok(p)) => vec![p.item.container.id()],
961             //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
962             Some(Err(MethodError::Ambiguity(v))) => {
963                 v.into_iter()
964                     .map(|source| {
965                         match source {
966                             TraitSource(id) => id,
967                             ImplSource(impl_id) => {
968                                 match tcx.trait_id_of_impl(impl_id) {
969                                     Some(id) => id,
970                                     None => {
971                                         span_bug!(span,
972                                                   "found inherent method when looking at traits")
973                                     }
974                                 }
975                             }
976                         }
977                     })
978                     .collect()
979             }
980             Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
981                 assert!(others.is_empty());
982                 vec![]
983             }
984             _ => vec![],
985         };
986
987         if let Some(def) = private_candidate {
988             return Err(MethodError::PrivateMatch(def, out_of_scope_traits));
989         }
990         let lev_candidate = self.probe_for_lev_candidate()?;
991
992         Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
993                                                   unsatisfied_predicates,
994                                                   out_of_scope_traits,
995                                                   lev_candidate,
996                                                   self.mode)))
997     }
998
999     fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
1000         let steps = self.steps.clone();
1001
1002         // find the first step that works
1003         steps
1004             .iter()
1005             .filter(|step| {
1006                 debug!("pick_core: step={:?}", step);
1007                 // skip types that are from a type error or that would require dereferencing
1008                 // a raw pointer
1009                 !step.self_ty.references_error() && !step.from_unsafe_deref
1010             }).flat_map(|step| {
1011                 let InferOk { value: self_ty, obligations: _ } =
1012                     self.fcx.probe_instantiate_query_response(
1013                         self.span, &self.orig_steps_var_values, &step.self_ty
1014                     ).unwrap_or_else(|_| {
1015                         span_bug!(self.span, "{:?} was applicable but now isn't?", step.self_ty)
1016                     });
1017                 self.pick_by_value_method(step, self_ty).or_else(|| {
1018                 self.pick_autorefd_method(step, self_ty, hir::MutImmutable).or_else(|| {
1019                 self.pick_autorefd_method(step, self_ty, hir::MutMutable)
1020             })})})
1021             .next()
1022     }
1023
1024     fn pick_by_value_method(&mut self, step: &CandidateStep<'gcx>, self_ty: Ty<'tcx>)
1025                             -> Option<PickResult<'tcx>>
1026     {
1027         //! For each type `T` in the step list, this attempts to find a
1028         //! method where the (transformed) self type is exactly `T`. We
1029         //! do however do one transformation on the adjustment: if we
1030         //! are passing a region pointer in, we will potentially
1031         //! *reborrow* it to a shorter lifetime. This allows us to
1032         //! transparently pass `&mut` pointers, in particular, without
1033         //! consuming them for their entire lifetime.
1034
1035         if step.unsize {
1036             return None;
1037         }
1038
1039         self.pick_method(self_ty).map(|r| {
1040             r.map(|mut pick| {
1041                 pick.autoderefs = step.autoderefs;
1042
1043                 // Insert a `&*` or `&mut *` if this is a reference type:
1044                 if let ty::Ref(_, _, mutbl) = step.self_ty.value.value.sty {
1045                     pick.autoderefs += 1;
1046                     pick.autoref = Some(mutbl);
1047                 }
1048
1049                 pick
1050             })
1051         })
1052     }
1053
1054     fn pick_autorefd_method(&mut self,
1055                             step: &CandidateStep<'gcx>,
1056                             self_ty: Ty<'tcx>,
1057                             mutbl: hir::Mutability)
1058                             -> Option<PickResult<'tcx>> {
1059         let tcx = self.tcx;
1060
1061         // In general, during probing we erase regions. See
1062         // `impl_self_ty()` for an explanation.
1063         let region = tcx.types.re_erased;
1064
1065         let autoref_ty = tcx.mk_ref(region,
1066                                     ty::TypeAndMut {
1067                                         ty: self_ty, mutbl
1068                                     });
1069         self.pick_method(autoref_ty).map(|r| {
1070             r.map(|mut pick| {
1071                 pick.autoderefs = step.autoderefs;
1072                 pick.autoref = Some(mutbl);
1073                 pick.unsize = if step.unsize {
1074                     Some(self_ty)
1075                 } else {
1076                     None
1077                 };
1078                 pick
1079             })
1080         })
1081     }
1082
1083     fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
1084         debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1085
1086         let mut possibly_unsatisfied_predicates = Vec::new();
1087         let mut unstable_candidates = Vec::new();
1088
1089         for (kind, candidates) in &[
1090             ("inherent", &self.inherent_candidates),
1091             ("extension", &self.extension_candidates),
1092         ] {
1093             debug!("searching {} candidates", kind);
1094             let res = self.consider_candidates(
1095                 self_ty,
1096                 candidates.iter(),
1097                 &mut possibly_unsatisfied_predicates,
1098                 Some(&mut unstable_candidates),
1099             );
1100             if let Some(pick) = res {
1101                 if !self.is_suggestion.0 && !unstable_candidates.is_empty() {
1102                     if let Ok(p) = &pick {
1103                         // Emit a lint if there are unstable candidates alongside the stable ones.
1104                         //
1105                         // We suppress warning if we're picking the method only because it is a
1106                         // suggestion.
1107                         self.emit_unstable_name_collision_hint(p, &unstable_candidates);
1108                     }
1109                 }
1110                 return Some(pick);
1111             }
1112         }
1113
1114         debug!("searching unstable candidates");
1115         let res = self.consider_candidates(
1116             self_ty,
1117             unstable_candidates.into_iter().map(|(c, _)| c),
1118             &mut possibly_unsatisfied_predicates,
1119             None,
1120         );
1121         if res.is_none() {
1122             self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1123         }
1124         res
1125     }
1126
1127     fn consider_candidates<'b, ProbesIter>(
1128         &self,
1129         self_ty: Ty<'tcx>,
1130         probes: ProbesIter,
1131         possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>,
1132         unstable_candidates: Option<&mut Vec<(&'b Candidate<'tcx>, Symbol)>>,
1133     ) -> Option<PickResult<'tcx>>
1134     where
1135         ProbesIter: Iterator<Item = &'b Candidate<'tcx>> + Clone,
1136     {
1137         let mut applicable_candidates: Vec<_> = probes.clone()
1138             .map(|probe| {
1139                 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1140             })
1141             .filter(|&(_, status)| status != ProbeResult::NoMatch)
1142             .collect();
1143
1144         debug!("applicable_candidates: {:?}", applicable_candidates);
1145
1146         if applicable_candidates.len() > 1 {
1147             if let Some(pick) = self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1148                 return Some(Ok(pick));
1149             }
1150         }
1151
1152         if let Some(uc) = unstable_candidates {
1153             applicable_candidates.retain(|&(p, _)| {
1154                 if let stability::EvalResult::Deny { feature, .. } =
1155                     self.tcx.eval_stability(p.item.def_id, None, self.span)
1156                 {
1157                     uc.push((p, feature));
1158                     return false;
1159                 }
1160                 true
1161             });
1162         }
1163
1164         if applicable_candidates.len() > 1 {
1165             let sources = probes
1166                 .map(|p| self.candidate_source(p, self_ty))
1167                 .collect();
1168             return Some(Err(MethodError::Ambiguity(sources)));
1169         }
1170
1171         applicable_candidates.pop().map(|(probe, status)| {
1172             if status == ProbeResult::Match {
1173                 Ok(probe.to_unadjusted_pick())
1174             } else {
1175                 Err(MethodError::BadReturnType)
1176             }
1177         })
1178     }
1179
1180     fn emit_unstable_name_collision_hint(
1181         &self,
1182         stable_pick: &Pick,
1183         unstable_candidates: &[(&Candidate<'tcx>, Symbol)],
1184     ) {
1185         let mut diag = self.tcx.struct_span_lint_hir(
1186             lint::builtin::UNSTABLE_NAME_COLLISIONS,
1187             self.fcx.body_id,
1188             self.span,
1189             "a method with this name may be added to the standard library in the future",
1190         );
1191
1192         // FIXME: This should be a `span_suggestion` instead of `help`
1193         // However `self.span` only
1194         // highlights the method name, so we can't use it. Also consider reusing the code from
1195         // `report_method_error()`.
1196         diag.help(&format!(
1197             "call with fully qualified syntax `{}(...)` to keep using the current method",
1198             self.tcx.item_path_str(stable_pick.item.def_id),
1199         ));
1200
1201         if nightly_options::is_nightly_build() {
1202             for (candidate, feature) in unstable_candidates {
1203                 diag.help(&format!(
1204                     "add #![feature({})] to the crate attributes to enable `{}`",
1205                     feature,
1206                     self.tcx.item_path_str(candidate.item.def_id),
1207                 ));
1208             }
1209         }
1210
1211         diag.emit();
1212     }
1213
1214     fn select_trait_candidate(&self, trait_ref: ty::TraitRef<'tcx>)
1215                               -> traits::SelectionResult<'tcx, traits::Selection<'tcx>>
1216     {
1217         let cause = traits::ObligationCause::misc(self.span, self.body_id);
1218         let predicate =
1219             trait_ref.to_poly_trait_ref().to_poly_trait_predicate();
1220         let obligation = traits::Obligation::new(cause, self.param_env, predicate);
1221         traits::SelectionContext::new(self).select(&obligation)
1222     }
1223
1224     fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>)
1225                         -> CandidateSource
1226     {
1227         match candidate.kind {
1228             InherentImplCandidate(..) => ImplSource(candidate.item.container.id()),
1229             ObjectCandidate |
1230             WhereClauseCandidate(_) => TraitSource(candidate.item.container.id()),
1231             TraitCandidate(trait_ref) => self.probe(|_| {
1232                 let _ = self.at(&ObligationCause::dummy(), self.param_env)
1233                     .sup(candidate.xform_self_ty, self_ty);
1234                 match self.select_trait_candidate(trait_ref) {
1235                     Ok(Some(traits::Vtable::VtableImpl(ref impl_data))) => {
1236                         // If only a single impl matches, make the error message point
1237                         // to that impl.
1238                         ImplSource(impl_data.impl_def_id)
1239                     }
1240                     _ => {
1241                         TraitSource(candidate.item.container.id())
1242                     }
1243                 }
1244             })
1245         }
1246     }
1247
1248     fn consider_probe(&self,
1249                       self_ty: Ty<'tcx>,
1250                       probe: &Candidate<'tcx>,
1251                       possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1252                       -> ProbeResult {
1253         debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1254
1255         self.probe(|_| {
1256             // First check that the self type can be related.
1257             let sub_obligations = match self.at(&ObligationCause::dummy(), self.param_env)
1258                                             .sup(probe.xform_self_ty, self_ty) {
1259                 Ok(InferOk { obligations, value: () }) => obligations,
1260                 Err(_) => {
1261                     debug!("--> cannot relate self-types");
1262                     return ProbeResult::NoMatch;
1263                 }
1264             };
1265
1266             let mut result = ProbeResult::Match;
1267             let selcx = &mut traits::SelectionContext::new(self);
1268             let cause = traits::ObligationCause::misc(self.span, self.body_id);
1269
1270             // If so, impls may carry other conditions (e.g., where
1271             // clauses) that must be considered. Make sure that those
1272             // match as well (or at least may match, sometimes we
1273             // don't have enough information to fully evaluate).
1274             let candidate_obligations : Vec<_> = match probe.kind {
1275                 InherentImplCandidate(ref substs, ref ref_obligations) => {
1276                     // Check whether the impl imposes obligations we have to worry about.
1277                     let impl_def_id = probe.item.container.id();
1278                     let impl_bounds = self.tcx.predicates_of(impl_def_id);
1279                     let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1280                     let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1281                         traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
1282
1283                     // Convert the bounds into obligations.
1284                     let impl_obligations = traits::predicates_for_generics(
1285                         cause, self.param_env, &impl_bounds);
1286
1287                     debug!("impl_obligations={:?}", impl_obligations);
1288                     impl_obligations.into_iter()
1289                         .chain(norm_obligations.into_iter())
1290                         .chain(ref_obligations.iter().cloned())
1291                         .collect()
1292                 }
1293
1294                 ObjectCandidate |
1295                 WhereClauseCandidate(..) => {
1296                     // These have no additional conditions to check.
1297                     vec![]
1298                 }
1299
1300                 TraitCandidate(trait_ref) => {
1301                     let predicate = trait_ref.to_predicate();
1302                     let obligation =
1303                         traits::Obligation::new(cause, self.param_env, predicate);
1304                     if !self.predicate_may_hold(&obligation) {
1305                         if self.probe(|_| self.select_trait_candidate(trait_ref).is_err()) {
1306                             // This candidate's primary obligation doesn't even
1307                             // select - don't bother registering anything in
1308                             // `potentially_unsatisfied_predicates`.
1309                             return ProbeResult::NoMatch;
1310                         } else {
1311                             // Some nested subobligation of this predicate
1312                             // failed.
1313                             //
1314                             // FIXME: try to find the exact nested subobligation
1315                             // and point at it rather than reporting the entire
1316                             // trait-ref?
1317                             result = ProbeResult::NoMatch;
1318                             let trait_ref = self.resolve_type_vars_if_possible(&trait_ref);
1319                             possibly_unsatisfied_predicates.push(trait_ref);
1320                         }
1321                     }
1322                     vec![]
1323                 }
1324             };
1325
1326             debug!("consider_probe - candidate_obligations={:?} sub_obligations={:?}",
1327                    candidate_obligations, sub_obligations);
1328
1329             // Evaluate those obligations to see if they might possibly hold.
1330             for o in candidate_obligations.into_iter().chain(sub_obligations) {
1331                 let o = self.resolve_type_vars_if_possible(&o);
1332                 if !self.predicate_may_hold(&o) {
1333                     result = ProbeResult::NoMatch;
1334                     if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1335                         possibly_unsatisfied_predicates.push(pred.skip_binder().trait_ref);
1336                     }
1337                 }
1338             }
1339
1340             if let ProbeResult::Match = result {
1341                 if let (Some(return_ty), Some(xform_ret_ty)) =
1342                     (self.return_type, probe.xform_ret_ty)
1343                 {
1344                     let xform_ret_ty = self.resolve_type_vars_if_possible(&xform_ret_ty);
1345                     debug!("comparing return_ty {:?} with xform ret ty {:?}",
1346                            return_ty,
1347                            probe.xform_ret_ty);
1348                     if self.at(&ObligationCause::dummy(), self.param_env)
1349                         .sup(return_ty, xform_ret_ty)
1350                         .is_err()
1351                     {
1352                         return ProbeResult::BadReturnType;
1353                     }
1354                 }
1355             }
1356
1357             result
1358         })
1359     }
1360
1361     /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1362     /// same trait, but we don't know which impl to use. In this case, since in all cases the
1363     /// external interface of the method can be determined from the trait, it's ok not to decide.
1364     /// We can basically just collapse all of the probes for various impls into one where-clause
1365     /// probe. This will result in a pending obligation so when more type-info is available we can
1366     /// make the final decision.
1367     ///
1368     /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1369     ///
1370     /// ```
1371     /// trait Foo { ... }
1372     /// impl Foo for Vec<int> { ... }
1373     /// impl Foo for Vec<usize> { ... }
1374     /// ```
1375     ///
1376     /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1377     /// use, so it's ok to just commit to "using the method from the trait Foo".
1378     fn collapse_candidates_to_trait_pick(&self, probes: &[(&Candidate<'tcx>, ProbeResult)])
1379                                          -> Option<Pick<'tcx>>
1380     {
1381         // Do all probes correspond to the same trait?
1382         let container = probes[0].0.item.container;
1383         if let ty::ImplContainer(_) = container {
1384             return None
1385         }
1386         if probes[1..].iter().any(|&(p, _)| p.item.container != container) {
1387             return None;
1388         }
1389
1390         // FIXME: check the return type here somehow.
1391         // If so, just use this trait and call it a day.
1392         Some(Pick {
1393             item: probes[0].0.item.clone(),
1394             kind: TraitPick,
1395             import_id: probes[0].0.import_id,
1396             autoderefs: 0,
1397             autoref: None,
1398             unsize: None,
1399         })
1400     }
1401
1402     /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
1403     /// candidate method where the method name may have been misspelt. Similarly to other
1404     /// Levenshtein based suggestions, we provide at most one such suggestion.
1405     fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssociatedItem>, MethodError<'tcx>> {
1406         debug!("Probing for method names similar to {:?}",
1407                self.method_name);
1408
1409         let steps = self.steps.clone();
1410         self.probe(|_| {
1411             let mut pcx = ProbeContext::new(self.fcx, self.span, self.mode, self.method_name,
1412                                             self.return_type,
1413                                             self.orig_steps_var_values.clone(),
1414                                             steps, IsSuggestion(true));
1415             pcx.allow_similar_names = true;
1416             pcx.assemble_inherent_candidates();
1417             pcx.assemble_extension_candidates_for_traits_in_scope(hir::DUMMY_HIR_ID)?;
1418
1419             let method_names = pcx.candidate_method_names();
1420             pcx.allow_similar_names = false;
1421             let applicable_close_candidates: Vec<ty::AssociatedItem> = method_names
1422                 .iter()
1423                 .filter_map(|&method_name| {
1424                     pcx.reset();
1425                     pcx.method_name = Some(method_name);
1426                     pcx.assemble_inherent_candidates();
1427                     pcx.assemble_extension_candidates_for_traits_in_scope(hir::DUMMY_HIR_ID)
1428                         .ok().map_or(None, |_| {
1429                             pcx.pick_core()
1430                                 .and_then(|pick| pick.ok())
1431                                 .and_then(|pick| Some(pick.item))
1432                         })
1433                 })
1434                .collect();
1435
1436             if applicable_close_candidates.is_empty() {
1437                 Ok(None)
1438             } else {
1439                 let best_name = {
1440                     let names = applicable_close_candidates.iter().map(|cand| &cand.ident.name);
1441                     find_best_match_for_name(names,
1442                                              &self.method_name.unwrap().as_str(),
1443                                              None)
1444                 }.unwrap();
1445                 Ok(applicable_close_candidates
1446                    .into_iter()
1447                    .find(|method| method.ident.name == best_name))
1448             }
1449         })
1450     }
1451
1452     ///////////////////////////////////////////////////////////////////////////
1453     // MISCELLANY
1454     fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1455         // "Fast track" -- check for usage of sugar when in method call
1456         // mode.
1457         //
1458         // In Path mode (i.e., resolving a value like `T::next`), consider any
1459         // associated value (i.e., methods, constants) but not types.
1460         match self.mode {
1461             Mode::MethodCall => item.method_has_self_argument,
1462             Mode::Path => match item.kind {
1463                 ty::AssociatedKind::Existential |
1464                 ty::AssociatedKind::Type => false,
1465                 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1466             },
1467         }
1468         // FIXME -- check for types that deref to `Self`,
1469         // like `Rc<Self>` and so on.
1470         //
1471         // Note also that the current code will break if this type
1472         // includes any of the type parameters defined on the method
1473         // -- but this could be overcome.
1474     }
1475
1476     fn record_static_candidate(&mut self, source: CandidateSource) {
1477         self.static_candidates.push(source);
1478     }
1479
1480     fn xform_self_ty(&self,
1481                      item: &ty::AssociatedItem,
1482                      impl_ty: Ty<'tcx>,
1483                      substs: &Substs<'tcx>)
1484                      -> (Ty<'tcx>, Option<Ty<'tcx>>) {
1485         if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1486             let sig = self.xform_method_sig(item.def_id, substs);
1487             (sig.inputs()[0], Some(sig.output()))
1488         } else {
1489             (impl_ty, None)
1490         }
1491     }
1492
1493     fn xform_method_sig(&self,
1494                         method: DefId,
1495                         substs: &Substs<'tcx>)
1496                         -> ty::FnSig<'tcx>
1497     {
1498         let fn_sig = self.tcx.fn_sig(method);
1499         debug!("xform_self_ty(fn_sig={:?}, substs={:?})",
1500                fn_sig,
1501                substs);
1502
1503         assert!(!substs.has_escaping_bound_vars());
1504
1505         // It is possible for type parameters or early-bound lifetimes
1506         // to appear in the signature of `self`. The substitutions we
1507         // are given do not include type/lifetime parameters for the
1508         // method yet. So create fresh variables here for those too,
1509         // if there are any.
1510         let generics = self.tcx.generics_of(method);
1511         assert_eq!(substs.len(), generics.parent_count as usize);
1512
1513         // Erase any late-bound regions from the method and substitute
1514         // in the values from the substitution.
1515         let xform_fn_sig = self.erase_late_bound_regions(&fn_sig);
1516
1517         if generics.params.is_empty() {
1518             xform_fn_sig.subst(self.tcx, substs)
1519         } else {
1520             let substs = Substs::for_item(self.tcx, method, |param, _| {
1521                 let i = param.index as usize;
1522                 if i < substs.len() {
1523                     substs[i]
1524                 } else {
1525                     match param.kind {
1526                         GenericParamDefKind::Lifetime => {
1527                             // In general, during probe we erase regions. See
1528                             // `impl_self_ty()` for an explanation.
1529                             self.tcx.types.re_erased.into()
1530                         }
1531                         GenericParamDefKind::Type {..} => self.var_for_def(self.span, param),
1532                     }
1533                 }
1534             });
1535             xform_fn_sig.subst(self.tcx, substs)
1536         }
1537     }
1538
1539     /// Gets the type of an impl and generate substitutions with placeholders.
1540     fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
1541         (self.tcx.type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1542     }
1543
1544     fn fresh_item_substs(&self, def_id: DefId) -> &'tcx Substs<'tcx> {
1545         Substs::for_item(self.tcx, def_id, |param, _| {
1546             match param.kind {
1547                 GenericParamDefKind::Lifetime => self.tcx.types.re_erased.into(),
1548                 GenericParamDefKind::Type {..} => {
1549                     self.next_ty_var(TypeVariableOrigin::SubstitutionPlaceholder(
1550                         self.tcx.def_span(def_id))).into()
1551                 }
1552             }
1553         })
1554     }
1555
1556     /// Replaces late-bound-regions bound by `value` with `'static` using
1557     /// `ty::erase_late_bound_regions`.
1558     ///
1559     /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1560     /// method matching. It is reasonable during the probe phase because we don't consider region
1561     /// relationships at all. Therefore, we can just replace all the region variables with 'static
1562     /// rather than creating fresh region variables. This is nice for two reasons:
1563     ///
1564     /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1565     ///    particular method call, it winds up creating fewer types overall, which helps for memory
1566     ///    usage. (Admittedly, this is a rather small effect, though measurable.)
1567     ///
1568     /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1569     ///    late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1570     ///    regions with actual region variables as is proper, we'd have to ensure that the same
1571     ///    region got replaced with the same variable, which requires a bit more coordination
1572     ///    and/or tracking the substitution and
1573     ///    so forth.
1574     fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1575         where T: TypeFoldable<'tcx>
1576     {
1577         self.tcx.erase_late_bound_regions(value)
1578     }
1579
1580     /// Finds the method with the appropriate name (or return type, as the case may be). If
1581     /// `allow_similar_names` is set, find methods with close-matching names.
1582     fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1583         if let Some(name) = self.method_name {
1584             if self.allow_similar_names {
1585                 let max_dist = max(name.as_str().len(), 3) / 3;
1586                 self.tcx.associated_items(def_id)
1587                     .filter(|x| {
1588                         let dist = lev_distance(&*name.as_str(), &x.ident.as_str());
1589                         Namespace::from(x.kind) == Namespace::Value && dist > 0
1590                             && dist <= max_dist
1591                     })
1592                     .collect()
1593             } else {
1594                 self.fcx
1595                     .associated_item(def_id, name, Namespace::Value)
1596                     .map_or(Vec::new(), |x| vec![x])
1597             }
1598         } else {
1599             self.tcx.associated_items(def_id).collect()
1600         }
1601     }
1602 }
1603
1604 impl<'tcx> Candidate<'tcx> {
1605     fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1606         Pick {
1607             item: self.item.clone(),
1608             kind: match self.kind {
1609                 InherentImplCandidate(..) => InherentImplPick,
1610                 ObjectCandidate => ObjectPick,
1611                 TraitCandidate(_) => TraitPick,
1612                 WhereClauseCandidate(ref trait_ref) => {
1613                     // Only trait derived from where-clauses should
1614                     // appear here, so they should not contain any
1615                     // inference variables or other artifacts. This
1616                     // means they are safe to put into the
1617                     // `WhereClausePick`.
1618                     assert!(
1619                         !trait_ref.skip_binder().substs.needs_infer()
1620                             && !trait_ref.skip_binder().substs.has_placeholders()
1621                     );
1622
1623                     WhereClausePick(trait_ref.clone())
1624                 }
1625             },
1626             import_id: self.import_id,
1627             autoderefs: 0,
1628             autoref: None,
1629             unsize: None,
1630         }
1631     }
1632 }