]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/probe.rs
5b0418921563a2dea56b4fa4bbf47897b57f3fc8
[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 assemble_inherent_candidates(&mut self) {
373         let steps = self.steps.clone();
374         for step in steps.iter() {
375             self.assemble_probe(step.self_ty);
376         }
377     }
378
379     fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
380         debug!("assemble_probe: self_ty={:?}", self_ty);
381
382         match self_ty.sty {
383             ty::TyDynamic(ref data, ..) => {
384                 if let Some(p) = data.principal() {
385                     self.assemble_inherent_candidates_from_object(self_ty, p);
386                     self.assemble_inherent_impl_candidates_for_type(p.def_id());
387                 }
388             }
389             ty::TyAdt(def, _) => {
390                 self.assemble_inherent_impl_candidates_for_type(def.did);
391             }
392             ty::TyParam(p) => {
393                 self.assemble_inherent_candidates_from_param(self_ty, p);
394             }
395             ty::TyChar => {
396                 let lang_def_id = self.tcx.lang_items.char_impl();
397                 self.assemble_inherent_impl_for_primitive(lang_def_id);
398             }
399             ty::TyStr => {
400                 let lang_def_id = self.tcx.lang_items.str_impl();
401                 self.assemble_inherent_impl_for_primitive(lang_def_id);
402             }
403             ty::TySlice(_) => {
404                 let lang_def_id = self.tcx.lang_items.slice_impl();
405                 self.assemble_inherent_impl_for_primitive(lang_def_id);
406             }
407             ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
408                 let lang_def_id = self.tcx.lang_items.const_ptr_impl();
409                 self.assemble_inherent_impl_for_primitive(lang_def_id);
410             }
411             ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
412                 let lang_def_id = self.tcx.lang_items.mut_ptr_impl();
413                 self.assemble_inherent_impl_for_primitive(lang_def_id);
414             }
415             ty::TyInt(ast::IntTy::I8) => {
416                 let lang_def_id = self.tcx.lang_items.i8_impl();
417                 self.assemble_inherent_impl_for_primitive(lang_def_id);
418             }
419             ty::TyInt(ast::IntTy::I16) => {
420                 let lang_def_id = self.tcx.lang_items.i16_impl();
421                 self.assemble_inherent_impl_for_primitive(lang_def_id);
422             }
423             ty::TyInt(ast::IntTy::I32) => {
424                 let lang_def_id = self.tcx.lang_items.i32_impl();
425                 self.assemble_inherent_impl_for_primitive(lang_def_id);
426             }
427             ty::TyInt(ast::IntTy::I64) => {
428                 let lang_def_id = self.tcx.lang_items.i64_impl();
429                 self.assemble_inherent_impl_for_primitive(lang_def_id);
430             }
431             ty::TyInt(ast::IntTy::I128) => {
432                 let lang_def_id = self.tcx.lang_items.i128_impl();
433                 self.assemble_inherent_impl_for_primitive(lang_def_id);
434             }
435             ty::TyInt(ast::IntTy::Is) => {
436                 let lang_def_id = self.tcx.lang_items.isize_impl();
437                 self.assemble_inherent_impl_for_primitive(lang_def_id);
438             }
439             ty::TyUint(ast::UintTy::U8) => {
440                 let lang_def_id = self.tcx.lang_items.u8_impl();
441                 self.assemble_inherent_impl_for_primitive(lang_def_id);
442             }
443             ty::TyUint(ast::UintTy::U16) => {
444                 let lang_def_id = self.tcx.lang_items.u16_impl();
445                 self.assemble_inherent_impl_for_primitive(lang_def_id);
446             }
447             ty::TyUint(ast::UintTy::U32) => {
448                 let lang_def_id = self.tcx.lang_items.u32_impl();
449                 self.assemble_inherent_impl_for_primitive(lang_def_id);
450             }
451             ty::TyUint(ast::UintTy::U64) => {
452                 let lang_def_id = self.tcx.lang_items.u64_impl();
453                 self.assemble_inherent_impl_for_primitive(lang_def_id);
454             }
455             ty::TyUint(ast::UintTy::U128) => {
456                 let lang_def_id = self.tcx.lang_items.u128_impl();
457                 self.assemble_inherent_impl_for_primitive(lang_def_id);
458             }
459             ty::TyUint(ast::UintTy::Us) => {
460                 let lang_def_id = self.tcx.lang_items.usize_impl();
461                 self.assemble_inherent_impl_for_primitive(lang_def_id);
462             }
463             ty::TyFloat(ast::FloatTy::F32) => {
464                 let lang_def_id = self.tcx.lang_items.f32_impl();
465                 self.assemble_inherent_impl_for_primitive(lang_def_id);
466             }
467             ty::TyFloat(ast::FloatTy::F64) => {
468                 let lang_def_id = self.tcx.lang_items.f64_impl();
469                 self.assemble_inherent_impl_for_primitive(lang_def_id);
470             }
471             _ => {}
472         }
473     }
474
475     fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
476         if let Some(impl_def_id) = lang_def_id {
477             self.assemble_inherent_impl_probe(impl_def_id);
478         }
479     }
480
481     fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
482         let impl_def_ids = ty::queries::inherent_impls::get(self.tcx, self.span, def_id);
483         for &impl_def_id in impl_def_ids.iter() {
484             self.assemble_inherent_impl_probe(impl_def_id);
485         }
486     }
487
488     fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
489         if !self.impl_dups.insert(impl_def_id) {
490             return; // already visited
491         }
492
493         debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
494
495         for item in self.impl_or_trait_item(impl_def_id) {
496             if !self.has_applicable_self(&item) {
497                 // No receiver declared. Not a candidate.
498                 self.record_static_candidate(ImplSource(impl_def_id));
499                 continue
500             }
501
502             if !self.tcx.vis_is_accessible_from(item.vis, self.body_id) {
503                 self.private_candidate = Some(item.def());
504                 continue
505             }
506
507             let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
508             let impl_ty = impl_ty.subst(self.tcx, impl_substs);
509
510             // Determine the receiver type that the method itself expects.
511             let xform_self_ty = self.xform_self_ty(&item, impl_ty, impl_substs);
512
513             // We can't use normalize_associated_types_in as it will pollute the
514             // fcx's fulfillment context after this probe is over.
515             let cause = traits::ObligationCause::misc(self.span, self.body_id);
516             let mut selcx = &mut traits::SelectionContext::new(self.fcx);
517             let traits::Normalized { value: xform_self_ty, obligations } =
518                 traits::normalize(selcx, cause, &xform_self_ty);
519             debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}",
520                    xform_self_ty);
521
522             self.inherent_candidates.push(Candidate {
523                 xform_self_ty: xform_self_ty,
524                 item: item,
525                 kind: InherentImplCandidate(impl_substs, obligations),
526                 import_id: None,
527             });
528         }
529     }
530
531     fn assemble_inherent_candidates_from_object(&mut self,
532                                                 self_ty: Ty<'tcx>,
533                                                 principal: ty::PolyExistentialTraitRef<'tcx>) {
534         debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
535                self_ty);
536
537         // It is illegal to invoke a method on a trait instance that
538         // refers to the `Self` type. An error will be reported by
539         // `enforce_object_limitations()` if the method refers to the
540         // `Self` type anywhere other than the receiver. Here, we use
541         // a substitution that replaces `Self` with the object type
542         // itself. Hence, a `&self` method will wind up with an
543         // argument type like `&Trait`.
544         let trait_ref = principal.with_self_ty(self.tcx, self_ty);
545         self.elaborate_bounds(&[trait_ref], |this, new_trait_ref, item| {
546             let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
547
548             let xform_self_ty =
549                 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
550
551             this.inherent_candidates.push(Candidate {
552                 xform_self_ty: xform_self_ty,
553                 item: item,
554                 kind: ObjectCandidate,
555                 import_id: None,
556             });
557         });
558     }
559
560     fn assemble_inherent_candidates_from_param(&mut self,
561                                                _rcvr_ty: Ty<'tcx>,
562                                                param_ty: ty::ParamTy) {
563         // FIXME -- Do we want to commit to this behavior for param bounds?
564
565         let bounds: Vec<_> = self.parameter_environment
566             .caller_bounds
567             .iter()
568             .filter_map(|predicate| {
569                 match *predicate {
570                     ty::Predicate::Trait(ref trait_predicate) => {
571                         match trait_predicate.0.trait_ref.self_ty().sty {
572                             ty::TyParam(ref p) if *p == param_ty => {
573                                 Some(trait_predicate.to_poly_trait_ref())
574                             }
575                             _ => None,
576                         }
577                     }
578                     ty::Predicate::Equate(..) |
579                     ty::Predicate::Projection(..) |
580                     ty::Predicate::RegionOutlives(..) |
581                     ty::Predicate::WellFormed(..) |
582                     ty::Predicate::ObjectSafe(..) |
583                     ty::Predicate::ClosureKind(..) |
584                     ty::Predicate::TypeOutlives(..) => None,
585                 }
586             })
587             .collect();
588
589         self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
590             let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
591
592             let xform_self_ty = this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
593
594             // Because this trait derives from a where-clause, it
595             // should not contain any inference variables or other
596             // artifacts. This means it is safe to put into the
597             // `WhereClauseCandidate` and (eventually) into the
598             // `WhereClausePick`.
599             assert!(!trait_ref.substs.needs_infer());
600
601             this.inherent_candidates.push(Candidate {
602                 xform_self_ty: xform_self_ty,
603                 item: item,
604                 kind: WhereClauseCandidate(poly_trait_ref),
605                 import_id: None,
606             });
607         });
608     }
609
610     // Do a search through a list of bounds, using a callback to actually
611     // create the candidates.
612     fn elaborate_bounds<F>(&mut self, bounds: &[ty::PolyTraitRef<'tcx>], mut mk_cand: F)
613         where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>,
614                                ty::PolyTraitRef<'tcx>,
615                                ty::AssociatedItem)
616     {
617         debug!("elaborate_bounds(bounds={:?})", bounds);
618
619         let tcx = self.tcx;
620         for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
621             for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
622                 if !self.has_applicable_self(&item) {
623                     self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
624                 } else {
625                     mk_cand(self, bound_trait_ref, item);
626                 }
627             }
628         }
629     }
630
631     fn assemble_extension_candidates_for_traits_in_scope(&mut self,
632                                                          expr_id: ast::NodeId)
633                                                          -> Result<(), MethodError<'tcx>> {
634         let mut duplicates = FxHashSet();
635         let opt_applicable_traits = self.tcx.trait_map.get(&expr_id);
636         if let Some(applicable_traits) = opt_applicable_traits {
637             for trait_candidate in applicable_traits {
638                 let trait_did = trait_candidate.def_id;
639                 if duplicates.insert(trait_did) {
640                     let import_id = trait_candidate.import_id;
641                     let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
642                     result?;
643                 }
644             }
645         }
646         Ok(())
647     }
648
649     fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
650         let mut duplicates = FxHashSet();
651         for trait_info in suggest::all_traits(self.tcx) {
652             if duplicates.insert(trait_info.def_id) {
653                 self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
654             }
655         }
656         Ok(())
657     }
658
659     pub fn matches_return_type(&self, method: &ty::AssociatedItem,
660                                expected: ty::Ty<'tcx>) -> bool {
661         match method.def() {
662             Def::Method(def_id) => {
663                 let fty = self.tcx.item_type(def_id).fn_sig();
664                 self.probe(|_| {
665                     let substs = self.fresh_substs_for_item(self.span, method.def_id);
666                     let output = fty.output().subst(self.tcx, substs);
667                     let (output, _) = self.replace_late_bound_regions_with_fresh_var(
668                         self.span, infer::FnCall, &output);
669                     self.can_sub_types(output, expected).is_ok()
670                 })
671             }
672             _ => false,
673         }
674     }
675
676     fn assemble_extension_candidates_for_trait(&mut self,
677                                                import_id: Option<ast::NodeId>,
678                                                trait_def_id: DefId)
679                                                -> Result<(), MethodError<'tcx>> {
680         debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
681                trait_def_id);
682
683         for item in self.impl_or_trait_item(trait_def_id) {
684             // Check whether `trait_def_id` defines a method with suitable name:
685             if !self.has_applicable_self(&item) {
686                 debug!("method has inapplicable self");
687                 self.record_static_candidate(TraitSource(trait_def_id));
688                 continue;
689             }
690
691             self.assemble_extension_candidates_for_trait_impls(import_id, trait_def_id,
692                                                                item.clone());
693
694             self.assemble_closure_candidates(import_id, trait_def_id, item.clone())?;
695
696             self.assemble_projection_candidates(import_id, trait_def_id, item.clone());
697
698             self.assemble_where_clause_candidates(import_id, trait_def_id, item.clone());
699         }
700
701         Ok(())
702     }
703
704     fn assemble_extension_candidates_for_trait_impls(&mut self,
705                                                      import_id: Option<ast::NodeId>,
706                                                      trait_def_id: DefId,
707                                                      item: ty::AssociatedItem) {
708         let trait_def = self.tcx.lookup_trait_def(trait_def_id);
709
710         // FIXME(arielb1): can we use for_each_relevant_impl here?
711         trait_def.for_each_impl(self.tcx, |impl_def_id| {
712             debug!("assemble_extension_candidates_for_trait_impl: trait_def_id={:?} \
713                                                                   impl_def_id={:?}",
714                    trait_def_id,
715                    impl_def_id);
716
717             if !self.impl_can_possibly_match(impl_def_id) {
718                 return;
719             }
720
721             let (_, impl_substs) = self.impl_ty_and_substs(impl_def_id);
722
723             debug!("impl_substs={:?}", impl_substs);
724
725             let impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id)
726                 .unwrap() // we know this is a trait impl
727                 .subst(self.tcx, impl_substs);
728
729             debug!("impl_trait_ref={:?}", impl_trait_ref);
730
731             // Determine the receiver type that the method itself expects.
732             let xform_self_ty =
733                 self.xform_self_ty(&item, impl_trait_ref.self_ty(), impl_trait_ref.substs);
734
735             // Normalize the receiver. We can't use normalize_associated_types_in
736             // as it will pollute the fcx's fulfillment context after this probe
737             // is over.
738             let cause = traits::ObligationCause::misc(self.span, self.body_id);
739             let mut selcx = &mut traits::SelectionContext::new(self.fcx);
740             let traits::Normalized { value: xform_self_ty, obligations } =
741                 traits::normalize(selcx, cause, &xform_self_ty);
742
743             debug!("xform_self_ty={:?}", xform_self_ty);
744
745             self.extension_candidates.push(Candidate {
746                 xform_self_ty: xform_self_ty,
747                 item: item.clone(),
748                 kind: ExtensionImplCandidate(impl_def_id, impl_substs, obligations),
749                 import_id: import_id,
750             });
751         });
752     }
753
754     fn impl_can_possibly_match(&self, impl_def_id: DefId) -> bool {
755         let simplified_steps = match self.opt_simplified_steps {
756             Some(ref simplified_steps) => simplified_steps,
757             None => {
758                 return true;
759             }
760         };
761
762         let impl_type = self.tcx.item_type(impl_def_id);
763         let impl_simplified_type =
764             match ty::fast_reject::simplify_type(self.tcx, impl_type, false) {
765                 Some(simplified_type) => simplified_type,
766                 None => {
767                     return true;
768                 }
769             };
770
771         simplified_steps.contains(&impl_simplified_type)
772     }
773
774     fn assemble_closure_candidates(&mut self,
775                                    import_id: Option<ast::NodeId>,
776                                    trait_def_id: DefId,
777                                    item: ty::AssociatedItem)
778                                    -> Result<(), MethodError<'tcx>> {
779         // Check if this is one of the Fn,FnMut,FnOnce traits.
780         let tcx = self.tcx;
781         let kind = if Some(trait_def_id) == tcx.lang_items.fn_trait() {
782             ty::ClosureKind::Fn
783         } else if Some(trait_def_id) == tcx.lang_items.fn_mut_trait() {
784             ty::ClosureKind::FnMut
785         } else if Some(trait_def_id) == tcx.lang_items.fn_once_trait() {
786             ty::ClosureKind::FnOnce
787         } else {
788             return Ok(());
789         };
790
791         // Check if there is an unboxed-closure self-type in the list of receivers.
792         // If so, add "synthetic impls".
793         let steps = self.steps.clone();
794         for step in steps.iter() {
795             let closure_id = match step.self_ty.sty {
796                 ty::TyClosure(def_id, _) => {
797                     if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
798                         id
799                     } else {
800                         continue;
801                     }
802                 }
803                 _ => continue,
804             };
805
806             let closure_kinds = &self.tables.borrow().closure_kinds;
807             let closure_kind = match closure_kinds.get(&closure_id) {
808                 Some(&k) => k,
809                 None => {
810                     return Err(MethodError::ClosureAmbiguity(trait_def_id));
811                 }
812             };
813
814             // this closure doesn't implement the right kind of `Fn` trait
815             if !closure_kind.extends(kind) {
816                 continue;
817             }
818
819             // create some substitutions for the argument/return type;
820             // for the purposes of our method lookup, we only take
821             // receiver type into account, so we can just substitute
822             // fresh types here to use during substitution and subtyping.
823             let substs = Substs::for_item(self.tcx,
824                                           trait_def_id,
825                                           |def, _| self.region_var_for_def(self.span, def),
826                                           |def, substs| {
827                 if def.index == 0 {
828                     step.self_ty
829                 } else {
830                     self.type_var_for_def(self.span, def, substs)
831                 }
832             });
833
834             let xform_self_ty = self.xform_self_ty(&item, step.self_ty, substs);
835             self.inherent_candidates.push(Candidate {
836                 xform_self_ty: xform_self_ty,
837                 item: item.clone(),
838                 kind: TraitCandidate,
839                 import_id: import_id,
840             });
841         }
842
843         Ok(())
844     }
845
846     fn assemble_projection_candidates(&mut self,
847                                       import_id: Option<ast::NodeId>,
848                                       trait_def_id: DefId,
849                                       item: ty::AssociatedItem) {
850         debug!("assemble_projection_candidates(\
851                trait_def_id={:?}, \
852                item={:?})",
853                trait_def_id,
854                item);
855
856         for step in self.steps.iter() {
857             debug!("assemble_projection_candidates: step={:?}", step);
858
859             let (def_id, substs) = match step.self_ty.sty {
860                 ty::TyProjection(ref data) => (data.trait_ref.def_id, data.trait_ref.substs),
861                 ty::TyAnon(def_id, substs) => (def_id, substs),
862                 _ => continue,
863             };
864
865             debug!("assemble_projection_candidates: def_id={:?} substs={:?}",
866                    def_id,
867                    substs);
868
869             let trait_predicates = self.tcx.item_predicates(def_id);
870             let bounds = trait_predicates.instantiate(self.tcx, substs);
871             let predicates = bounds.predicates;
872             debug!("assemble_projection_candidates: predicates={:?}",
873                    predicates);
874             for poly_bound in traits::elaborate_predicates(self.tcx, predicates)
875                 .filter_map(|p| p.to_opt_poly_trait_ref())
876                 .filter(|b| b.def_id() == trait_def_id) {
877                 let bound = self.erase_late_bound_regions(&poly_bound);
878
879                 debug!("assemble_projection_candidates: def_id={:?} substs={:?} bound={:?}",
880                        def_id,
881                        substs,
882                        bound);
883
884                 if self.can_equate(&step.self_ty, &bound.self_ty()).is_ok() {
885                     let xform_self_ty = self.xform_self_ty(&item, bound.self_ty(), bound.substs);
886
887                     debug!("assemble_projection_candidates: bound={:?} xform_self_ty={:?}",
888                            bound,
889                            xform_self_ty);
890
891                     self.extension_candidates.push(Candidate {
892                         xform_self_ty: xform_self_ty,
893                         item: item.clone(),
894                         kind: TraitCandidate,
895                         import_id: import_id,
896                     });
897                 }
898             }
899         }
900     }
901
902     fn assemble_where_clause_candidates(&mut self,
903                                         import_id: Option<ast::NodeId>,
904                                         trait_def_id: DefId,
905                                         item: ty::AssociatedItem) {
906         debug!("assemble_where_clause_candidates(trait_def_id={:?})",
907                trait_def_id);
908
909         let caller_predicates = self.parameter_environment.caller_bounds.clone();
910         for poly_bound in traits::elaborate_predicates(self.tcx, caller_predicates)
911             .filter_map(|p| p.to_opt_poly_trait_ref())
912             .filter(|b| b.def_id() == trait_def_id) {
913             let bound = self.erase_late_bound_regions(&poly_bound);
914             let xform_self_ty = self.xform_self_ty(&item, bound.self_ty(), bound.substs);
915
916             debug!("assemble_where_clause_candidates: bound={:?} xform_self_ty={:?}",
917                    bound,
918                    xform_self_ty);
919
920             self.extension_candidates.push(Candidate {
921                 xform_self_ty: xform_self_ty,
922                 item: item.clone(),
923                 kind: WhereClauseCandidate(poly_bound),
924                 import_id: import_id,
925             });
926         }
927     }
928
929     fn candidate_method_names(&self) -> Vec<ast::Name> {
930         let mut set = FxHashSet();
931         let mut names: Vec<_> =
932             self.inherent_candidates
933                 .iter()
934                 .chain(&self.extension_candidates)
935                 .map(|candidate| candidate.item.name)
936                 .filter(|&name| set.insert(name))
937                 .collect();
938
939         // sort them by the name so we have a stable result
940         names.sort_by_key(|n| n.as_str());
941         names
942     }
943
944     ///////////////////////////////////////////////////////////////////////////
945     // THE ACTUAL SEARCH
946
947     fn pick(mut self) -> PickResult<'tcx> {
948         assert!(match self.looking_for {
949             LookingFor::MethodName(_) => true,
950             LookingFor::ReturnType(_) => false,
951         });
952
953         if let Some(r) = self.pick_core() {
954             return r;
955         }
956
957         let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
958         let private_candidate = mem::replace(&mut self.private_candidate, None);
959         let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
960
961         // things failed, so lets look at all traits, for diagnostic purposes now:
962         self.reset();
963
964         let span = self.span;
965         let tcx = self.tcx;
966
967         self.assemble_extension_candidates_for_all_traits()?;
968
969         let out_of_scope_traits = match self.pick_core() {
970             Some(Ok(p)) => vec![p.item.container.id()],
971             //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
972             Some(Err(MethodError::Ambiguity(v))) => {
973                 v.into_iter()
974                     .map(|source| {
975                         match source {
976                             TraitSource(id) => id,
977                             ImplSource(impl_id) => {
978                                 match tcx.trait_id_of_impl(impl_id) {
979                                     Some(id) => id,
980                                     None => {
981                                         span_bug!(span,
982                                                   "found inherent method when looking at traits")
983                                     }
984                                 }
985                             }
986                         }
987                     })
988                     .collect()
989             }
990             Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
991                 assert!(others.is_empty());
992                 vec![]
993             }
994             Some(Err(MethodError::ClosureAmbiguity(..))) => {
995                 // this error only occurs when assembling candidates
996                 span_bug!(span, "encountered ClosureAmbiguity from pick_core");
997             }
998             _ => vec![],
999         };
1000
1001         if let Some(def) = private_candidate {
1002             return Err(MethodError::PrivateMatch(def));
1003         }
1004
1005         Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
1006                                                   unsatisfied_predicates,
1007                                                   out_of_scope_traits,
1008                                                   self.mode)))
1009     }
1010
1011     fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
1012         let steps = self.steps.clone();
1013
1014         // find the first step that works
1015         steps.iter().filter_map(|step| self.pick_step(step)).next()
1016     }
1017
1018     fn pick_step(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
1019         debug!("pick_step: step={:?}", step);
1020
1021         if step.self_ty.references_error() {
1022             return None;
1023         }
1024
1025         if let Some(result) = self.pick_by_value_method(step) {
1026             return Some(result);
1027         }
1028
1029         self.pick_autorefd_method(step)
1030     }
1031
1032     fn pick_by_value_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
1033         //! For each type `T` in the step list, this attempts to find a
1034         //! method where the (transformed) self type is exactly `T`. We
1035         //! do however do one transformation on the adjustment: if we
1036         //! are passing a region pointer in, we will potentially
1037         //! *reborrow* it to a shorter lifetime. This allows us to
1038         //! transparently pass `&mut` pointers, in particular, without
1039         //! consuming them for their entire lifetime.
1040
1041         if step.unsize {
1042             return None;
1043         }
1044
1045         self.pick_method(step.self_ty).map(|r| {
1046             r.map(|mut pick| {
1047                 pick.autoderefs = step.autoderefs;
1048
1049                 // Insert a `&*` or `&mut *` if this is a reference type:
1050                 if let ty::TyRef(_, mt) = step.self_ty.sty {
1051                     pick.autoderefs += 1;
1052                     pick.autoref = Some(mt.mutbl);
1053                 }
1054
1055                 pick
1056             })
1057         })
1058     }
1059
1060     fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
1061         let tcx = self.tcx;
1062
1063         // In general, during probing we erase regions. See
1064         // `impl_self_ty()` for an explanation.
1065         let region = tcx.mk_region(ty::ReErased);
1066
1067         // Search through mutabilities in order to find one where pick works:
1068         [hir::MutImmutable, hir::MutMutable]
1069             .iter()
1070             .filter_map(|&m| {
1071                 let autoref_ty = tcx.mk_ref(region,
1072                                             ty::TypeAndMut {
1073                                                 ty: step.self_ty,
1074                                                 mutbl: m,
1075                                             });
1076                 self.pick_method(autoref_ty).map(|r| {
1077                     r.map(|mut pick| {
1078                         pick.autoderefs = step.autoderefs;
1079                         pick.autoref = Some(m);
1080                         pick.unsize = if step.unsize {
1081                             Some(step.self_ty)
1082                         } else {
1083                             None
1084                         };
1085                         pick
1086                     })
1087                 })
1088             })
1089             .nth(0)
1090     }
1091
1092     fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
1093         debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1094
1095         let mut possibly_unsatisfied_predicates = Vec::new();
1096
1097         debug!("searching inherent candidates");
1098         if let Some(pick) = self.consider_candidates(self_ty,
1099                                                      &self.inherent_candidates,
1100                                                      &mut possibly_unsatisfied_predicates) {
1101             return Some(pick);
1102         }
1103
1104         debug!("searching extension candidates");
1105         let res = self.consider_candidates(self_ty,
1106                                            &self.extension_candidates,
1107                                            &mut possibly_unsatisfied_predicates);
1108         if let None = res {
1109             self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1110         }
1111         res
1112     }
1113
1114     fn consider_candidates(&self,
1115                            self_ty: Ty<'tcx>,
1116                            probes: &[Candidate<'tcx>],
1117                            possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1118                            -> Option<PickResult<'tcx>> {
1119         let mut applicable_candidates: Vec<_> = probes.iter()
1120             .filter(|&probe| self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1121             .collect();
1122
1123         debug!("applicable_candidates: {:?}", applicable_candidates);
1124
1125         if applicable_candidates.len() > 1 {
1126             match self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1127                 Some(pick) => {
1128                     return Some(Ok(pick));
1129                 }
1130                 None => {}
1131             }
1132         }
1133
1134         if applicable_candidates.len() > 1 {
1135             let sources = probes.iter().map(|p| p.to_source()).collect();
1136             return Some(Err(MethodError::Ambiguity(sources)));
1137         }
1138
1139         applicable_candidates.pop().map(|probe| Ok(probe.to_unadjusted_pick()))
1140     }
1141
1142     fn consider_probe(&self,
1143                       self_ty: Ty<'tcx>,
1144                       probe: &Candidate<'tcx>,
1145                       possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1146                       -> bool {
1147         debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1148
1149         self.probe(|_| {
1150             // First check that the self type can be related.
1151             match self.sub_types(false,
1152                                  &ObligationCause::dummy(),
1153                                  self_ty,
1154                                  probe.xform_self_ty) {
1155                 Ok(InferOk { obligations, value: () }) => {
1156                     // FIXME(#32730) propagate obligations
1157                     assert!(obligations.is_empty())
1158                 }
1159                 Err(_) => {
1160                     debug!("--> cannot relate self-types");
1161                     return false;
1162                 }
1163             }
1164
1165             // If so, impls may carry other conditions (e.g., where
1166             // clauses) that must be considered. Make sure that those
1167             // match as well (or at least may match, sometimes we
1168             // don't have enough information to fully evaluate).
1169             let (impl_def_id, substs, ref_obligations) = match probe.kind {
1170                 InherentImplCandidate(ref substs, ref ref_obligations) => {
1171                     (probe.item.container.id(), substs, ref_obligations)
1172                 }
1173
1174                 ExtensionImplCandidate(impl_def_id, ref substs, ref ref_obligations) => {
1175                     (impl_def_id, substs, ref_obligations)
1176                 }
1177
1178                 ObjectCandidate |
1179                 TraitCandidate |
1180                 WhereClauseCandidate(..) => {
1181                     // These have no additional conditions to check.
1182                     return true;
1183                 }
1184             };
1185
1186             let selcx = &mut traits::SelectionContext::new(self);
1187             let cause = traits::ObligationCause::misc(self.span, self.body_id);
1188
1189             // Check whether the impl imposes obligations we have to worry about.
1190             let impl_bounds = self.tcx.item_predicates(impl_def_id);
1191             let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1192             let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1193                 traits::normalize(selcx, cause.clone(), &impl_bounds);
1194
1195             // Convert the bounds into obligations.
1196             let obligations = traits::predicates_for_generics(cause.clone(), &impl_bounds);
1197             debug!("impl_obligations={:?}", obligations);
1198
1199             // Evaluate those obligations to see if they might possibly hold.
1200             let mut all_true = true;
1201             for o in obligations.iter()
1202                 .chain(norm_obligations.iter())
1203                 .chain(ref_obligations.iter()) {
1204                 if !selcx.evaluate_obligation(o) {
1205                     all_true = false;
1206                     if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1207                         possibly_unsatisfied_predicates.push(pred.0.trait_ref);
1208                     }
1209                 }
1210             }
1211             all_true
1212         })
1213     }
1214
1215     /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1216     /// same trait, but we don't know which impl to use. In this case, since in all cases the
1217     /// external interface of the method can be determined from the trait, it's ok not to decide.
1218     /// We can basically just collapse all of the probes for various impls into one where-clause
1219     /// probe. This will result in a pending obligation so when more type-info is available we can
1220     /// make the final decision.
1221     ///
1222     /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1223     ///
1224     /// ```
1225     /// trait Foo { ... }
1226     /// impl Foo for Vec<int> { ... }
1227     /// impl Foo for Vec<usize> { ... }
1228     /// ```
1229     ///
1230     /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1231     /// use, so it's ok to just commit to "using the method from the trait Foo".
1232     fn collapse_candidates_to_trait_pick(&self, probes: &[&Candidate<'tcx>]) -> Option<Pick<'tcx>> {
1233         // Do all probes correspond to the same trait?
1234         let container = probes[0].item.container;
1235         match container {
1236             ty::TraitContainer(_) => {}
1237             ty::ImplContainer(_) => return None,
1238         }
1239         if probes[1..].iter().any(|p| p.item.container != container) {
1240             return None;
1241         }
1242
1243         // If so, just use this trait and call it a day.
1244         Some(Pick {
1245             item: probes[0].item.clone(),
1246             kind: TraitPick,
1247             import_id: probes[0].import_id,
1248             autoderefs: 0,
1249             autoref: None,
1250             unsize: None,
1251         })
1252     }
1253
1254     ///////////////////////////////////////////////////////////////////////////
1255     // MISCELLANY
1256     fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1257         // "Fast track" -- check for usage of sugar when in method call
1258         // mode.
1259         //
1260         // In Path mode (i.e., resolving a value like `T::next`), consider any
1261         // associated value (i.e., methods, constants) but not types.
1262         match self.mode {
1263             Mode::MethodCall => item.method_has_self_argument,
1264             Mode::Path => match item.kind {
1265                 ty::AssociatedKind::Type => false,
1266                 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1267             },
1268         }
1269         // FIXME -- check for types that deref to `Self`,
1270         // like `Rc<Self>` and so on.
1271         //
1272         // Note also that the current code will break if this type
1273         // includes any of the type parameters defined on the method
1274         // -- but this could be overcome.
1275     }
1276
1277     fn record_static_candidate(&mut self, source: CandidateSource) {
1278         self.static_candidates.push(source);
1279     }
1280
1281     fn xform_self_ty(&self,
1282                      item: &ty::AssociatedItem,
1283                      impl_ty: Ty<'tcx>,
1284                      substs: &Substs<'tcx>)
1285                      -> Ty<'tcx> {
1286         if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1287             self.xform_method_self_ty(item.def_id, impl_ty, substs)
1288         } else {
1289             impl_ty
1290         }
1291     }
1292
1293     fn xform_method_self_ty(&self,
1294                             method: DefId,
1295                             impl_ty: Ty<'tcx>,
1296                             substs: &Substs<'tcx>)
1297                             -> Ty<'tcx> {
1298         let self_ty = self.tcx.item_type(method).fn_sig().input(0);
1299         debug!("xform_self_ty(impl_ty={:?}, self_ty={:?}, substs={:?})",
1300                impl_ty,
1301                self_ty,
1302                substs);
1303
1304         assert!(!substs.has_escaping_regions());
1305
1306         // It is possible for type parameters or early-bound lifetimes
1307         // to appear in the signature of `self`. The substitutions we
1308         // are given do not include type/lifetime parameters for the
1309         // method yet. So create fresh variables here for those too,
1310         // if there are any.
1311         let generics = self.tcx.item_generics(method);
1312         assert_eq!(substs.types().count(), generics.parent_types as usize);
1313         assert_eq!(substs.regions().count(), generics.parent_regions as usize);
1314
1315         // Erase any late-bound regions from the method and substitute
1316         // in the values from the substitution.
1317         let xform_self_ty = self.erase_late_bound_regions(&self_ty);
1318
1319         if generics.types.is_empty() && generics.regions.is_empty() {
1320             xform_self_ty.subst(self.tcx, substs)
1321         } else {
1322             let substs = Substs::for_item(self.tcx, method, |def, _| {
1323                 let i = def.index as usize;
1324                 if i < substs.len() {
1325                     substs.region_at(i)
1326                 } else {
1327                     // In general, during probe we erase regions. See
1328                     // `impl_self_ty()` for an explanation.
1329                     self.tcx.mk_region(ty::ReErased)
1330                 }
1331             }, |def, cur_substs| {
1332                 let i = def.index as usize;
1333                 if i < substs.len() {
1334                     substs.type_at(i)
1335                 } else {
1336                     self.type_var_for_def(self.span, def, cur_substs)
1337                 }
1338             });
1339             xform_self_ty.subst(self.tcx, substs)
1340         }
1341     }
1342
1343     /// Get the type of an impl and generate substitutions with placeholders.
1344     fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
1345         let impl_ty = self.tcx.item_type(impl_def_id);
1346
1347         let substs = Substs::for_item(self.tcx,
1348                                       impl_def_id,
1349                                       |_, _| self.tcx.mk_region(ty::ReErased),
1350                                       |_, _| self.next_ty_var(
1351                                         TypeVariableOrigin::SubstitutionPlaceholder(
1352                                             self.tcx.def_span(impl_def_id))));
1353
1354         (impl_ty, substs)
1355     }
1356
1357     /// Replace late-bound-regions bound by `value` with `'static` using
1358     /// `ty::erase_late_bound_regions`.
1359     ///
1360     /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1361     /// method matching. It is reasonable during the probe phase because we don't consider region
1362     /// relationships at all. Therefore, we can just replace all the region variables with 'static
1363     /// rather than creating fresh region variables. This is nice for two reasons:
1364     ///
1365     /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1366     ///    particular method call, it winds up creating fewer types overall, which helps for memory
1367     ///    usage. (Admittedly, this is a rather small effect, though measureable.)
1368     ///
1369     /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1370     ///    late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1371     ///    regions with actual region variables as is proper, we'd have to ensure that the same
1372     ///    region got replaced with the same variable, which requires a bit more coordination
1373     ///    and/or tracking the substitution and
1374     ///    so forth.
1375     fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1376         where T: TypeFoldable<'tcx>
1377     {
1378         self.tcx.erase_late_bound_regions(value)
1379     }
1380
1381     /// Find the method with the appropriate name (or return type, as the case may be).
1382     fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1383         match self.looking_for {
1384             LookingFor::MethodName(name) => {
1385                 self.fcx.associated_item(def_id, name).map_or(Vec::new(), |x| vec![x])
1386             }
1387             LookingFor::ReturnType(return_ty) => {
1388                 self.tcx
1389                     .associated_items(def_id)
1390                     .map(|did| self.tcx.associated_item(did.def_id))
1391                     .filter(|m| self.matches_return_type(m, return_ty))
1392                     .collect()
1393             }
1394         }
1395     }
1396 }
1397
1398 impl<'tcx> Candidate<'tcx> {
1399     fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1400         Pick {
1401             item: self.item.clone(),
1402             kind: match self.kind {
1403                 InherentImplCandidate(..) => InherentImplPick,
1404                 ExtensionImplCandidate(def_id, ..) => ExtensionImplPick(def_id),
1405                 ObjectCandidate => ObjectPick,
1406                 TraitCandidate => TraitPick,
1407                 WhereClauseCandidate(ref trait_ref) => {
1408                     // Only trait derived from where-clauses should
1409                     // appear here, so they should not contain any
1410                     // inference variables or other artifacts. This
1411                     // means they are safe to put into the
1412                     // `WhereClausePick`.
1413                     assert!(!trait_ref.substs().needs_infer());
1414
1415                     WhereClausePick(trait_ref.clone())
1416                 }
1417             },
1418             import_id: self.import_id,
1419             autoderefs: 0,
1420             autoref: None,
1421             unsize: None,
1422         }
1423     }
1424
1425     fn to_source(&self) -> CandidateSource {
1426         match self.kind {
1427             InherentImplCandidate(..) => ImplSource(self.item.container.id()),
1428             ExtensionImplCandidate(def_id, ..) => ImplSource(def_id),
1429             ObjectCandidate |
1430             TraitCandidate |
1431             WhereClauseCandidate(_) => TraitSource(self.item.container.id()),
1432         }
1433     }
1434 }