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