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