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