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