]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/probe.rs
rustdoc: Hide `self: Box<Self>` in list of deref methods
[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, 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.type_of(def_id).fn_sig();
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_types(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, 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) => (data.trait_ref.def_id, data.trait_ref.substs),
865                 ty::TyAnon(def_id, substs) => (def_id, substs),
866                 _ => continue,
867             };
868
869             debug!("assemble_projection_candidates: def_id={:?} substs={:?}",
870                    def_id,
871                    substs);
872
873             let trait_predicates = self.tcx.predicates_of(def_id);
874             let bounds = trait_predicates.instantiate(self.tcx, substs);
875             let predicates = bounds.predicates;
876             debug!("assemble_projection_candidates: predicates={:?}",
877                    predicates);
878             for poly_bound in traits::elaborate_predicates(self.tcx, predicates)
879                 .filter_map(|p| p.to_opt_poly_trait_ref())
880                 .filter(|b| b.def_id() == trait_def_id) {
881                 let bound = self.erase_late_bound_regions(&poly_bound);
882
883                 debug!("assemble_projection_candidates: def_id={:?} substs={:?} bound={:?}",
884                        def_id,
885                        substs,
886                        bound);
887
888                 if self.can_equate(&step.self_ty, &bound.self_ty()).is_ok() {
889                     let xform_self_ty = self.xform_self_ty(&item, bound.self_ty(), bound.substs);
890
891                     debug!("assemble_projection_candidates: bound={:?} xform_self_ty={:?}",
892                            bound,
893                            xform_self_ty);
894
895                     self.push_extension_candidate(xform_self_ty, item, TraitCandidate, import_id);
896                 }
897             }
898         }
899     }
900
901     fn assemble_where_clause_candidates(&mut self,
902                                         import_id: Option<ast::NodeId>,
903                                         trait_def_id: DefId,
904                                         item: ty::AssociatedItem) {
905         debug!("assemble_where_clause_candidates(trait_def_id={:?})",
906                trait_def_id);
907
908         let caller_predicates = self.param_env.caller_bounds.to_vec();
909         for poly_bound in traits::elaborate_predicates(self.tcx, caller_predicates)
910             .filter_map(|p| p.to_opt_poly_trait_ref())
911             .filter(|b| b.def_id() == trait_def_id) {
912             let bound = self.erase_late_bound_regions(&poly_bound);
913             let xform_self_ty = self.xform_self_ty(&item, bound.self_ty(), bound.substs);
914
915             debug!("assemble_where_clause_candidates: bound={:?} xform_self_ty={:?}",
916                    bound,
917                    xform_self_ty);
918
919             self.push_extension_candidate(xform_self_ty, item,
920                                           WhereClauseCandidate(poly_bound), import_id);
921         }
922     }
923
924     fn candidate_method_names(&self) -> Vec<ast::Name> {
925         let mut set = FxHashSet();
926         let mut names: Vec<_> =
927             self.inherent_candidates
928                 .iter()
929                 .chain(&self.extension_candidates)
930                 .map(|candidate| candidate.item.name)
931                 .filter(|&name| set.insert(name))
932                 .collect();
933
934         // sort them by the name so we have a stable result
935         names.sort_by_key(|n| n.as_str());
936         names
937     }
938
939     ///////////////////////////////////////////////////////////////////////////
940     // THE ACTUAL SEARCH
941
942     fn pick(mut self) -> PickResult<'tcx> {
943         assert!(match self.looking_for {
944             LookingFor::MethodName(_) => true,
945             LookingFor::ReturnType(_) => false,
946         });
947
948         if let Some(r) = self.pick_core() {
949             return r;
950         }
951
952         let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
953         let private_candidate = mem::replace(&mut self.private_candidate, None);
954         let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
955
956         // things failed, so lets look at all traits, for diagnostic purposes now:
957         self.reset();
958
959         let span = self.span;
960         let tcx = self.tcx;
961
962         self.assemble_extension_candidates_for_all_traits()?;
963
964         let out_of_scope_traits = match self.pick_core() {
965             Some(Ok(p)) => vec![p.item.container.id()],
966             //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
967             Some(Err(MethodError::Ambiguity(v))) => {
968                 v.into_iter()
969                     .map(|source| {
970                         match source {
971                             TraitSource(id) => id,
972                             ImplSource(impl_id) => {
973                                 match tcx.trait_id_of_impl(impl_id) {
974                                     Some(id) => id,
975                                     None => {
976                                         span_bug!(span,
977                                                   "found inherent method when looking at traits")
978                                     }
979                                 }
980                             }
981                         }
982                     })
983                     .collect()
984             }
985             Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
986                 assert!(others.is_empty());
987                 vec![]
988             }
989             Some(Err(MethodError::ClosureAmbiguity(..))) => {
990                 // this error only occurs when assembling candidates
991                 span_bug!(span, "encountered ClosureAmbiguity from pick_core");
992             }
993             _ => vec![],
994         };
995
996         if let Some(def) = private_candidate {
997             return Err(MethodError::PrivateMatch(def));
998         }
999
1000         Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
1001                                                   unsatisfied_predicates,
1002                                                   out_of_scope_traits,
1003                                                   self.mode)))
1004     }
1005
1006     fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
1007         let steps = self.steps.clone();
1008
1009         // find the first step that works
1010         steps.iter().filter_map(|step| self.pick_step(step)).next()
1011     }
1012
1013     fn pick_step(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
1014         debug!("pick_step: step={:?}", step);
1015
1016         if step.self_ty.references_error() {
1017             return None;
1018         }
1019
1020         if let Some(result) = self.pick_by_value_method(step) {
1021             return Some(result);
1022         }
1023
1024         self.pick_autorefd_method(step)
1025     }
1026
1027     fn pick_by_value_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
1028         //! For each type `T` in the step list, this attempts to find a
1029         //! method where the (transformed) self type is exactly `T`. We
1030         //! do however do one transformation on the adjustment: if we
1031         //! are passing a region pointer in, we will potentially
1032         //! *reborrow* it to a shorter lifetime. This allows us to
1033         //! transparently pass `&mut` pointers, in particular, without
1034         //! consuming them for their entire lifetime.
1035
1036         if step.unsize {
1037             return None;
1038         }
1039
1040         self.pick_method(step.self_ty).map(|r| {
1041             r.map(|mut pick| {
1042                 pick.autoderefs = step.autoderefs;
1043
1044                 // Insert a `&*` or `&mut *` if this is a reference type:
1045                 if let ty::TyRef(_, mt) = step.self_ty.sty {
1046                     pick.autoderefs += 1;
1047                     pick.autoref = Some(mt.mutbl);
1048                 }
1049
1050                 pick
1051             })
1052         })
1053     }
1054
1055     fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
1056         let tcx = self.tcx;
1057
1058         // In general, during probing we erase regions. See
1059         // `impl_self_ty()` for an explanation.
1060         let region = tcx.types.re_erased;
1061
1062         // Search through mutabilities in order to find one where pick works:
1063         [hir::MutImmutable, hir::MutMutable]
1064             .iter()
1065             .filter_map(|&m| {
1066                 let autoref_ty = tcx.mk_ref(region,
1067                                             ty::TypeAndMut {
1068                                                 ty: step.self_ty,
1069                                                 mutbl: m,
1070                                             });
1071                 self.pick_method(autoref_ty).map(|r| {
1072                     r.map(|mut pick| {
1073                         pick.autoderefs = step.autoderefs;
1074                         pick.autoref = Some(m);
1075                         pick.unsize = if step.unsize {
1076                             Some(step.self_ty)
1077                         } else {
1078                             None
1079                         };
1080                         pick
1081                     })
1082                 })
1083             })
1084             .nth(0)
1085     }
1086
1087     fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
1088         debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1089
1090         let mut possibly_unsatisfied_predicates = Vec::new();
1091
1092         debug!("searching inherent candidates");
1093         if let Some(pick) = self.consider_candidates(self_ty,
1094                                                      &self.inherent_candidates,
1095                                                      &mut possibly_unsatisfied_predicates) {
1096             return Some(pick);
1097         }
1098
1099         debug!("searching extension candidates");
1100         let res = self.consider_candidates(self_ty,
1101                                            &self.extension_candidates,
1102                                            &mut possibly_unsatisfied_predicates);
1103         if let None = res {
1104             self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1105         }
1106         res
1107     }
1108
1109     fn consider_candidates(&self,
1110                            self_ty: Ty<'tcx>,
1111                            probes: &[Candidate<'tcx>],
1112                            possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1113                            -> Option<PickResult<'tcx>> {
1114         let mut applicable_candidates: Vec<_> = probes.iter()
1115             .filter(|&probe| self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1116             .collect();
1117
1118         debug!("applicable_candidates: {:?}", applicable_candidates);
1119
1120         if applicable_candidates.len() > 1 {
1121             match self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1122                 Some(pick) => {
1123                     return Some(Ok(pick));
1124                 }
1125                 None => {}
1126             }
1127         }
1128
1129         if applicable_candidates.len() > 1 {
1130             let sources = probes.iter().map(|p| p.to_source()).collect();
1131             return Some(Err(MethodError::Ambiguity(sources)));
1132         }
1133
1134         applicable_candidates.pop().map(|probe| Ok(probe.to_unadjusted_pick()))
1135     }
1136
1137     fn consider_probe(&self,
1138                       self_ty: Ty<'tcx>,
1139                       probe: &Candidate<'tcx>,
1140                       possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1141                       -> bool {
1142         debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1143
1144         self.probe(|_| {
1145             // First check that the self type can be related.
1146             let sub_obligations = match self.sub_types(false,
1147                                                        &ObligationCause::dummy(),
1148                                                        self_ty,
1149                                                        probe.xform_self_ty) {
1150                 Ok(InferOk { obligations, value: () }) => obligations,
1151                 Err(_) => {
1152                     debug!("--> cannot relate self-types");
1153                     return false;
1154                 }
1155             };
1156
1157             // If so, impls may carry other conditions (e.g., where
1158             // clauses) that must be considered. Make sure that those
1159             // match as well (or at least may match, sometimes we
1160             // don't have enough information to fully evaluate).
1161             let (impl_def_id, substs, ref_obligations) = match probe.kind {
1162                 InherentImplCandidate(ref substs, ref ref_obligations) => {
1163                     (probe.item.container.id(), substs, ref_obligations)
1164                 }
1165
1166                 ExtensionImplCandidate(impl_def_id, ref substs, ref ref_obligations) => {
1167                     (impl_def_id, substs, ref_obligations)
1168                 }
1169
1170                 ObjectCandidate |
1171                 TraitCandidate |
1172                 WhereClauseCandidate(..) => {
1173                     // These have no additional conditions to check.
1174                     return true;
1175                 }
1176             };
1177
1178             let selcx = &mut traits::SelectionContext::new(self);
1179             let cause = traits::ObligationCause::misc(self.span, self.body_id);
1180
1181             // Check whether the impl imposes obligations we have to worry about.
1182             let impl_bounds = self.tcx.predicates_of(impl_def_id);
1183             let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1184             let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1185                 traits::normalize(selcx, cause.clone(), &impl_bounds);
1186
1187             // Convert the bounds into obligations.
1188             let obligations = traits::predicates_for_generics(cause.clone(), &impl_bounds);
1189             debug!("impl_obligations={:?}", obligations);
1190
1191             // Evaluate those obligations to see if they might possibly hold.
1192             let mut all_true = true;
1193             for o in obligations.iter()
1194                 .chain(sub_obligations.iter())
1195                 .chain(norm_obligations.iter())
1196                 .chain(ref_obligations.iter()) {
1197                 if !selcx.evaluate_obligation(o) {
1198                     all_true = false;
1199                     if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1200                         possibly_unsatisfied_predicates.push(pred.0.trait_ref);
1201                     }
1202                 }
1203             }
1204             all_true
1205         })
1206     }
1207
1208     /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1209     /// same trait, but we don't know which impl to use. In this case, since in all cases the
1210     /// external interface of the method can be determined from the trait, it's ok not to decide.
1211     /// We can basically just collapse all of the probes for various impls into one where-clause
1212     /// probe. This will result in a pending obligation so when more type-info is available we can
1213     /// make the final decision.
1214     ///
1215     /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1216     ///
1217     /// ```
1218     /// trait Foo { ... }
1219     /// impl Foo for Vec<int> { ... }
1220     /// impl Foo for Vec<usize> { ... }
1221     /// ```
1222     ///
1223     /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1224     /// use, so it's ok to just commit to "using the method from the trait Foo".
1225     fn collapse_candidates_to_trait_pick(&self, probes: &[&Candidate<'tcx>]) -> Option<Pick<'tcx>> {
1226         // Do all probes correspond to the same trait?
1227         let container = probes[0].item.container;
1228         match container {
1229             ty::TraitContainer(_) => {}
1230             ty::ImplContainer(_) => return None,
1231         }
1232         if probes[1..].iter().any(|p| p.item.container != container) {
1233             return None;
1234         }
1235
1236         // If so, just use this trait and call it a day.
1237         Some(Pick {
1238             item: probes[0].item.clone(),
1239             kind: TraitPick,
1240             import_id: probes[0].import_id,
1241             autoderefs: 0,
1242             autoref: None,
1243             unsize: None,
1244         })
1245     }
1246
1247     ///////////////////////////////////////////////////////////////////////////
1248     // MISCELLANY
1249     fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1250         // "Fast track" -- check for usage of sugar when in method call
1251         // mode.
1252         //
1253         // In Path mode (i.e., resolving a value like `T::next`), consider any
1254         // associated value (i.e., methods, constants) but not types.
1255         match self.mode {
1256             Mode::MethodCall => item.method_has_self_argument,
1257             Mode::Path => match item.kind {
1258                 ty::AssociatedKind::Type => false,
1259                 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1260             },
1261         }
1262         // FIXME -- check for types that deref to `Self`,
1263         // like `Rc<Self>` and so on.
1264         //
1265         // Note also that the current code will break if this type
1266         // includes any of the type parameters defined on the method
1267         // -- but this could be overcome.
1268     }
1269
1270     fn record_static_candidate(&mut self, source: CandidateSource) {
1271         self.static_candidates.push(source);
1272     }
1273
1274     fn xform_self_ty(&self,
1275                      item: &ty::AssociatedItem,
1276                      impl_ty: Ty<'tcx>,
1277                      substs: &Substs<'tcx>)
1278                      -> Ty<'tcx> {
1279         if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1280             self.xform_method_self_ty(item.def_id, impl_ty, substs)
1281         } else {
1282             impl_ty
1283         }
1284     }
1285
1286     fn xform_method_self_ty(&self,
1287                             method: DefId,
1288                             impl_ty: Ty<'tcx>,
1289                             substs: &Substs<'tcx>)
1290                             -> Ty<'tcx> {
1291         let self_ty = self.tcx.type_of(method).fn_sig().input(0);
1292         debug!("xform_self_ty(impl_ty={:?}, self_ty={:?}, substs={:?})",
1293                impl_ty,
1294                self_ty,
1295                substs);
1296
1297         assert!(!substs.has_escaping_regions());
1298
1299         // It is possible for type parameters or early-bound lifetimes
1300         // to appear in the signature of `self`. The substitutions we
1301         // are given do not include type/lifetime parameters for the
1302         // method yet. So create fresh variables here for those too,
1303         // if there are any.
1304         let generics = self.tcx.generics_of(method);
1305         assert_eq!(substs.types().count(), generics.parent_types as usize);
1306         assert_eq!(substs.regions().count(), generics.parent_regions as usize);
1307
1308         // Erase any late-bound regions from the method and substitute
1309         // in the values from the substitution.
1310         let xform_self_ty = self.erase_late_bound_regions(&self_ty);
1311
1312         if generics.types.is_empty() && generics.regions.is_empty() {
1313             xform_self_ty.subst(self.tcx, substs)
1314         } else {
1315             let substs = Substs::for_item(self.tcx, method, |def, _| {
1316                 let i = def.index as usize;
1317                 if i < substs.len() {
1318                     substs.region_at(i)
1319                 } else {
1320                     // In general, during probe we erase regions. See
1321                     // `impl_self_ty()` for an explanation.
1322                     self.tcx.types.re_erased
1323                 }
1324             }, |def, cur_substs| {
1325                 let i = def.index as usize;
1326                 if i < substs.len() {
1327                     substs.type_at(i)
1328                 } else {
1329                     self.type_var_for_def(self.span, def, cur_substs)
1330                 }
1331             });
1332             xform_self_ty.subst(self.tcx, substs)
1333         }
1334     }
1335
1336     /// Get the type of an impl and generate substitutions with placeholders.
1337     fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
1338         let impl_ty = self.tcx.type_of(impl_def_id);
1339
1340         let substs = Substs::for_item(self.tcx,
1341                                       impl_def_id,
1342                                       |_, _| self.tcx.types.re_erased,
1343                                       |_, _| self.next_ty_var(
1344                                         TypeVariableOrigin::SubstitutionPlaceholder(
1345                                             self.tcx.def_span(impl_def_id))));
1346
1347         (impl_ty, substs)
1348     }
1349
1350     /// Replace late-bound-regions bound by `value` with `'static` using
1351     /// `ty::erase_late_bound_regions`.
1352     ///
1353     /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1354     /// method matching. It is reasonable during the probe phase because we don't consider region
1355     /// relationships at all. Therefore, we can just replace all the region variables with 'static
1356     /// rather than creating fresh region variables. This is nice for two reasons:
1357     ///
1358     /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1359     ///    particular method call, it winds up creating fewer types overall, which helps for memory
1360     ///    usage. (Admittedly, this is a rather small effect, though measureable.)
1361     ///
1362     /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1363     ///    late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1364     ///    regions with actual region variables as is proper, we'd have to ensure that the same
1365     ///    region got replaced with the same variable, which requires a bit more coordination
1366     ///    and/or tracking the substitution and
1367     ///    so forth.
1368     fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1369         where T: TypeFoldable<'tcx>
1370     {
1371         self.tcx.erase_late_bound_regions(value)
1372     }
1373
1374     /// Find the method with the appropriate name (or return type, as the case may be).
1375     fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1376         match self.looking_for {
1377             LookingFor::MethodName(name) => {
1378                 self.fcx.associated_item(def_id, name).map_or(Vec::new(), |x| vec![x])
1379             }
1380             LookingFor::ReturnType(return_ty) => {
1381                 self.tcx
1382                     .associated_items(def_id)
1383                     .map(|did| self.tcx.associated_item(did.def_id))
1384                     .filter(|m| self.matches_return_type(m, return_ty))
1385                     .collect()
1386             }
1387         }
1388     }
1389 }
1390
1391 impl<'tcx> Candidate<'tcx> {
1392     fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1393         Pick {
1394             item: self.item.clone(),
1395             kind: match self.kind {
1396                 InherentImplCandidate(..) => InherentImplPick,
1397                 ExtensionImplCandidate(def_id, ..) => ExtensionImplPick(def_id),
1398                 ObjectCandidate => ObjectPick,
1399                 TraitCandidate => TraitPick,
1400                 WhereClauseCandidate(ref trait_ref) => {
1401                     // Only trait derived from where-clauses should
1402                     // appear here, so they should not contain any
1403                     // inference variables or other artifacts. This
1404                     // means they are safe to put into the
1405                     // `WhereClausePick`.
1406                     assert!(!trait_ref.substs().needs_infer());
1407
1408                     WhereClausePick(trait_ref.clone())
1409                 }
1410             },
1411             import_id: self.import_id,
1412             autoderefs: 0,
1413             autoref: None,
1414             unsize: None,
1415         }
1416     }
1417
1418     fn to_source(&self) -> CandidateSource {
1419         match self.kind {
1420             InherentImplCandidate(..) => ImplSource(self.item.container.id()),
1421             ExtensionImplCandidate(def_id, ..) => ImplSource(def_id),
1422             ObjectCandidate |
1423             TraitCandidate |
1424             WhereClauseCandidate(_) => TraitSource(self.item.container.id()),
1425         }
1426     }
1427 }