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.
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.
11 use super::MethodError;
12 use super::NoMatchData;
13 use super::{CandidateSource, ImplSource, TraitSource};
17 use hir::def_id::DefId;
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};
32 use self::CandidateKind::*;
33 pub use self::PickKind::*;
35 pub enum LookingFor<'tcx> {
36 /// looking for methods with the given name; this is the normal case
37 MethodName(ast::Name),
39 /// looking for methods that return a given type; this is used to
40 /// assemble suggestions
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);
48 struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
49 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
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>,
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>,
63 /// Some(candidate) if there is a private candidate
64 private_candidate: Option<Def>,
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>>,
71 impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
72 type Target = FnCtxt<'a, 'gcx, 'tcx>;
73 fn deref(&self) -> &Self::Target {
79 struct CandidateStep<'tcx> {
86 struct Candidate<'tcx> {
87 xform_self_ty: Ty<'tcx>,
88 item: ty::AssociatedItem,
89 kind: CandidateKind<'tcx>,
90 import_id: Option<ast::NodeId>,
94 enum CandidateKind<'tcx> {
95 InherentImplCandidate(&'tcx Substs<'tcx>,
96 // Normalize obligations
97 Vec<traits::PredicateObligation<'tcx>>),
98 ExtensionImplCandidate(// Impl
101 // Normalize obligations
102 Vec<traits::PredicateObligation<'tcx>>),
105 WhereClauseCandidate(// Trait
106 ty::PolyTraitRef<'tcx>),
110 pub struct Pick<'tcx> {
111 pub item: ty::AssociatedItem,
112 pub kind: PickKind<'tcx>,
113 pub import_id: Option<ast::NodeId>,
115 // Indicates that the source expression should be autoderef'd N times
117 // A = expr | *expr | **expr | ...
118 pub autoderefs: usize,
120 // Indicates that an autoref is applied after the optional autoderefs
122 // B = A | &A | &mut A
123 pub autoref: Option<hir::Mutability>,
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.
130 pub unsize: Option<Ty<'tcx>>,
133 #[derive(Clone,Debug)]
134 pub enum PickKind<'tcx> {
136 ExtensionImplPick(// Impl
140 WhereClausePick(// Trait
141 ty::PolyTraitRef<'tcx>),
144 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
146 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
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.
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.
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,
168 return_type: Ty<'tcx>,
170 scope_expr_id: ast::NodeId)
171 -> Vec<ty::AssociatedItem> {
172 debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
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()))
183 .flat_map(|&method_name| {
184 match self.probe_for_name(span, mode, method_name, IsSuggestion(true), self_ty,
186 Ok(pick) => Some(pick.item),
193 pub fn probe_for_name(&self,
196 item_name: ast::Name,
197 is_suggestion: IsSuggestion,
199 scope_expr_id: ast::NodeId)
200 -> PickResult<'tcx> {
201 debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
207 LookingFor::MethodName(item_name),
211 |probe_cx| probe_cx.pick())
214 fn probe_op<OP,R>(&'a self,
217 looking_for: LookingFor<'tcx>,
218 is_suggestion: IsSuggestion,
220 scope_expr_id: ast::NodeId,
222 -> Result<R, MethodError<'tcx>>
223 where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
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,
236 return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
250 // Create a list of simplified self types, if we can.
251 let mut simplified_steps = Vec::new();
253 match ty::fast_reject::simplify_type(self.tcx, step.self_ty, true) {
257 Some(simplified_type) => {
258 simplified_steps.push(simplified_type);
262 let opt_simplified_steps = if simplified_steps.len() < steps.len() {
263 None // failed to convert at least one of the steps
265 Some(simplified_steps)
268 debug!("ProbeContext: steps for self_ty={:?} are {:?}",
272 // this creates one big transaction so that all type variables etc
273 // that we create during the probe process are removed later
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)?;
284 fn create_steps(&self,
287 is_suggestion: IsSuggestion)
288 -> Option<Vec<CandidateStep<'tcx>>> {
289 // FIXME: we don't need to create the entire steps in one pass
291 let mut autoderef = self.autoderef(span, self_ty);
292 let mut steps: Vec<_> = autoderef.by_ref()
302 let final_ty = autoderef.maybe_ambiguous_final_ty();
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);
313 // If we're just looking for suggestions,
314 // though, ambiguity is no big thing, we can
318 ty::TyArray(elem_ty, _) => {
319 let dereferences = steps.len() - 1;
321 steps.push(CandidateStep {
322 self_ty: self.tcx.mk_slice(elem_ty),
323 autoderefs: dereferences,
327 ty::TyError => return None,
331 debug!("create_steps: steps={:?}", steps);
337 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
338 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
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> {
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(),
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;
369 ///////////////////////////////////////////////////////////////////////////
370 // CANDIDATE ASSEMBLY
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);
379 fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
380 debug!("assemble_probe: self_ty={:?}", self_ty);
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());
389 ty::TyAdt(def, _) => {
390 self.assemble_inherent_impl_candidates_for_type(def.did);
393 self.assemble_inherent_candidates_from_param(self_ty, p);
396 let lang_def_id = self.tcx.lang_items.char_impl();
397 self.assemble_inherent_impl_for_primitive(lang_def_id);
400 let lang_def_id = self.tcx.lang_items.str_impl();
401 self.assemble_inherent_impl_for_primitive(lang_def_id);
404 let lang_def_id = self.tcx.lang_items.slice_impl();
405 self.assemble_inherent_impl_for_primitive(lang_def_id);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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
493 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
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));
502 if !self.tcx.vis_is_accessible_from(item.vis, self.body_id) {
503 self.private_candidate = Some(item.def());
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);
510 // Determine the receiver type that the method itself expects.
511 let xform_self_ty = self.xform_self_ty(&item, impl_ty, impl_substs);
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 = {:?}",
522 self.inherent_candidates.push(Candidate {
523 xform_self_ty: xform_self_ty,
525 kind: InherentImplCandidate(impl_substs, obligations),
531 fn assemble_inherent_candidates_from_object(&mut self,
533 principal: ty::PolyExistentialTraitRef<'tcx>) {
534 debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
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);
549 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
551 this.inherent_candidates.push(Candidate {
552 xform_self_ty: xform_self_ty,
554 kind: ObjectCandidate,
560 fn assemble_inherent_candidates_from_param(&mut self,
562 param_ty: ty::ParamTy) {
563 // FIXME -- Do we want to commit to this behavior for param bounds?
565 let bounds: Vec<_> = self.parameter_environment
568 .filter_map(|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())
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,
590 self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
591 let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
593 let xform_self_ty = this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
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());
602 this.inherent_candidates.push(Candidate {
603 xform_self_ty: xform_self_ty,
605 kind: WhereClauseCandidate(poly_trait_ref),
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>,
618 debug!("elaborate_bounds(bounds={:?})", bounds);
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()));
626 mk_cand(self, bound_trait_ref, item);
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);
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)?;
660 pub fn matches_return_type(&self, method: &ty::AssociatedItem,
661 expected: ty::Ty<'tcx>) -> bool {
663 Def::Method(def_id) => {
664 let fty = self.tcx.item_type(def_id).fn_sig();
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()
677 fn assemble_extension_candidates_for_trait(&mut self,
678 import_id: Option<ast::NodeId>,
680 -> Result<(), MethodError<'tcx>> {
681 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
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));
692 self.assemble_extension_candidates_for_trait_impls(import_id, trait_def_id,
695 self.assemble_closure_candidates(import_id, trait_def_id, item.clone())?;
697 self.assemble_projection_candidates(import_id, trait_def_id, item.clone());
699 self.assemble_where_clause_candidates(import_id, trait_def_id, item.clone());
705 fn assemble_extension_candidates_for_trait_impls(&mut self,
706 import_id: Option<ast::NodeId>,
708 item: ty::AssociatedItem) {
709 let trait_def = self.tcx.lookup_trait_def(trait_def_id);
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={:?} \
718 if !self.impl_can_possibly_match(impl_def_id) {
722 let (_, impl_substs) = self.impl_ty_and_substs(impl_def_id);
724 debug!("impl_substs={:?}", impl_substs);
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);
730 debug!("impl_trait_ref={:?}", impl_trait_ref);
732 // Determine the receiver type that the method itself expects.
734 self.xform_self_ty(&item, impl_trait_ref.self_ty(), impl_trait_ref.substs);
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
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);
744 debug!("xform_self_ty={:?}", xform_self_ty);
746 self.extension_candidates.push(Candidate {
747 xform_self_ty: xform_self_ty,
749 kind: ExtensionImplCandidate(impl_def_id, impl_substs, obligations),
750 import_id: import_id,
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,
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,
772 simplified_steps.contains(&impl_simplified_type)
775 fn assemble_closure_candidates(&mut self,
776 import_id: Option<ast::NodeId>,
778 item: ty::AssociatedItem)
779 -> Result<(), MethodError<'tcx>> {
780 // Check if this is one of the Fn,FnMut,FnOnce traits.
782 let kind = if Some(trait_def_id) == tcx.lang_items.fn_trait() {
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
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) {
807 let closure_kinds = &self.tables.borrow().closure_kinds;
808 let closure_kind = match closure_kinds.get(&closure_id) {
811 return Err(MethodError::ClosureAmbiguity(trait_def_id));
815 // this closure doesn't implement the right kind of `Fn` trait
816 if !closure_kind.extends(kind) {
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,
826 |def, _| self.region_var_for_def(self.span, def),
831 self.type_var_for_def(self.span, def, substs)
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,
839 kind: TraitCandidate,
840 import_id: import_id,
847 fn assemble_projection_candidates(&mut self,
848 import_id: Option<ast::NodeId>,
850 item: ty::AssociatedItem) {
851 debug!("assemble_projection_candidates(\
857 for step in self.steps.iter() {
858 debug!("assemble_projection_candidates: step={:?}", step);
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),
866 debug!("assemble_projection_candidates: def_id={:?} substs={:?}",
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={:?}",
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);
880 debug!("assemble_projection_candidates: def_id={:?} substs={:?} bound={:?}",
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);
888 debug!("assemble_projection_candidates: bound={:?} xform_self_ty={:?}",
892 self.extension_candidates.push(Candidate {
893 xform_self_ty: xform_self_ty,
895 kind: TraitCandidate,
896 import_id: import_id,
903 fn assemble_where_clause_candidates(&mut self,
904 import_id: Option<ast::NodeId>,
906 item: ty::AssociatedItem) {
907 debug!("assemble_where_clause_candidates(trait_def_id={:?})",
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);
917 debug!("assemble_where_clause_candidates: bound={:?} xform_self_ty={:?}",
921 self.extension_candidates.push(Candidate {
922 xform_self_ty: xform_self_ty,
924 kind: WhereClauseCandidate(poly_bound),
925 import_id: import_id,
930 fn candidate_method_names(&self) -> Vec<ast::Name> {
931 let mut set = FxHashSet();
932 let mut names: Vec<_> =
933 self.inherent_candidates
935 .chain(&self.extension_candidates)
936 .map(|candidate| candidate.item.name)
937 .filter(|&name| set.insert(name))
940 // sort them by the name so we have a stable result
941 names.sort_by_key(|n| n.as_str());
945 ///////////////////////////////////////////////////////////////////////////
948 fn pick(mut self) -> PickResult<'tcx> {
949 assert!(match self.looking_for {
950 LookingFor::MethodName(_) => true,
951 LookingFor::ReturnType(_) => false,
954 if let Some(r) = self.pick_core() {
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![]);
962 // things failed, so lets look at all traits, for diagnostic purposes now:
965 let span = self.span;
968 self.assemble_extension_candidates_for_all_traits()?;
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))) => {
977 TraitSource(id) => id,
978 ImplSource(impl_id) => {
979 match tcx.trait_id_of_impl(impl_id) {
983 "found inherent method when looking at traits")
991 Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
992 assert!(others.is_empty());
995 Some(Err(MethodError::ClosureAmbiguity(..))) => {
996 // this error only occurs when assembling candidates
997 span_bug!(span, "encountered ClosureAmbiguity from pick_core");
1002 if let Some(def) = private_candidate {
1003 return Err(MethodError::PrivateMatch(def));
1006 Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
1007 unsatisfied_predicates,
1008 out_of_scope_traits,
1012 fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
1013 let steps = self.steps.clone();
1015 // find the first step that works
1016 steps.iter().filter_map(|step| self.pick_step(step)).next()
1019 fn pick_step(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
1020 debug!("pick_step: step={:?}", step);
1022 if step.self_ty.references_error() {
1026 if let Some(result) = self.pick_by_value_method(step) {
1027 return Some(result);
1030 self.pick_autorefd_method(step)
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.
1046 self.pick_method(step.self_ty).map(|r| {
1048 pick.autoderefs = step.autoderefs;
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);
1061 fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
1064 // In general, during probing we erase regions. See
1065 // `impl_self_ty()` for an explanation.
1066 let region = tcx.mk_region(ty::ReErased);
1068 // Search through mutabilities in order to find one where pick works:
1069 [hir::MutImmutable, hir::MutMutable]
1072 let autoref_ty = tcx.mk_ref(region,
1077 self.pick_method(autoref_ty).map(|r| {
1079 pick.autoderefs = step.autoderefs;
1080 pick.autoref = Some(m);
1081 pick.unsize = if step.unsize {
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));
1096 let mut possibly_unsatisfied_predicates = Vec::new();
1098 debug!("searching inherent candidates");
1099 if let Some(pick) = self.consider_candidates(self_ty,
1100 &self.inherent_candidates,
1101 &mut possibly_unsatisfied_predicates) {
1105 debug!("searching extension candidates");
1106 let res = self.consider_candidates(self_ty,
1107 &self.extension_candidates,
1108 &mut possibly_unsatisfied_predicates);
1110 self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1115 fn consider_candidates(&self,
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))
1124 debug!("applicable_candidates: {:?}", applicable_candidates);
1126 if applicable_candidates.len() > 1 {
1127 match self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1129 return Some(Ok(pick));
1135 if applicable_candidates.len() > 1 {
1136 let sources = probes.iter().map(|p| p.to_source()).collect();
1137 return Some(Err(MethodError::Ambiguity(sources)));
1140 applicable_candidates.pop().map(|probe| Ok(probe.to_unadjusted_pick()))
1143 fn consider_probe(&self,
1145 probe: &Candidate<'tcx>,
1146 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1148 debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1151 // First check that the self type can be related.
1152 let sub_obligations = match self.sub_types(false,
1153 &ObligationCause::dummy(),
1155 probe.xform_self_ty) {
1156 Ok(InferOk { obligations, value: () }) => obligations,
1158 debug!("--> cannot relate self-types");
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)
1172 ExtensionImplCandidate(impl_def_id, ref substs, ref ref_obligations) => {
1173 (impl_def_id, substs, ref_obligations)
1178 WhereClauseCandidate(..) => {
1179 // These have no additional conditions to check.
1184 let selcx = &mut traits::SelectionContext::new(self);
1185 let cause = traits::ObligationCause::misc(self.span, self.body_id);
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);
1193 // Convert the bounds into obligations.
1194 let obligations = traits::predicates_for_generics(cause.clone(), &impl_bounds);
1195 debug!("impl_obligations={:?}", obligations);
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) {
1205 if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1206 possibly_unsatisfied_predicates.push(pred.0.trait_ref);
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.
1221 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1224 /// trait Foo { ... }
1225 /// impl Foo for Vec<int> { ... }
1226 /// impl Foo for Vec<usize> { ... }
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;
1235 ty::TraitContainer(_) => {}
1236 ty::ImplContainer(_) => return None,
1238 if probes[1..].iter().any(|p| p.item.container != container) {
1242 // If so, just use this trait and call it a day.
1244 item: probes[0].item.clone(),
1246 import_id: probes[0].import_id,
1253 ///////////////////////////////////////////////////////////////////////////
1255 fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1256 // "Fast track" -- check for usage of sugar when in method call
1259 // In Path mode (i.e., resolving a value like `T::next`), consider any
1260 // associated value (i.e., methods, constants) but not types.
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
1268 // FIXME -- check for types that deref to `Self`,
1269 // like `Rc<Self>` and so on.
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.
1276 fn record_static_candidate(&mut self, source: CandidateSource) {
1277 self.static_candidates.push(source);
1280 fn xform_self_ty(&self,
1281 item: &ty::AssociatedItem,
1283 substs: &Substs<'tcx>)
1285 if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1286 self.xform_method_self_ty(item.def_id, impl_ty, substs)
1292 fn xform_method_self_ty(&self,
1295 substs: &Substs<'tcx>)
1297 let self_ty = self.tcx.item_type(method).fn_sig().input(0);
1298 debug!("xform_self_ty(impl_ty={:?}, self_ty={:?}, substs={:?})",
1303 assert!(!substs.has_escaping_regions());
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);
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);
1318 if generics.types.is_empty() && generics.regions.is_empty() {
1319 xform_self_ty.subst(self.tcx, substs)
1321 let substs = Substs::for_item(self.tcx, method, |def, _| {
1322 let i = def.index as usize;
1323 if i < substs.len() {
1326 // In general, during probe we erase regions. See
1327 // `impl_self_ty()` for an explanation.
1328 self.tcx.mk_region(ty::ReErased)
1330 }, |def, cur_substs| {
1331 let i = def.index as usize;
1332 if i < substs.len() {
1335 self.type_var_for_def(self.span, def, cur_substs)
1338 xform_self_ty.subst(self.tcx, substs)
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);
1346 let substs = Substs::for_item(self.tcx,
1348 |_, _| self.tcx.mk_region(ty::ReErased),
1349 |_, _| self.next_ty_var(
1350 TypeVariableOrigin::SubstitutionPlaceholder(
1351 self.tcx.def_span(impl_def_id))));
1356 /// Replace late-bound-regions bound by `value` with `'static` using
1357 /// `ty::erase_late_bound_regions`.
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:
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.)
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
1374 fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1375 where T: TypeFoldable<'tcx>
1377 self.tcx.erase_late_bound_regions(value)
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])
1386 LookingFor::ReturnType(return_ty) => {
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))
1397 impl<'tcx> Candidate<'tcx> {
1398 fn to_unadjusted_pick(&self) -> Pick<'tcx> {
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());
1414 WhereClausePick(trait_ref.clone())
1417 import_id: self.import_id,
1424 fn to_source(&self) -> CandidateSource {
1426 InherentImplCandidate(..) => ImplSource(self.item.container.id()),
1427 ExtensionImplCandidate(def_id, ..) => ImplSource(def_id),
1430 WhereClauseCandidate(_) => TraitSource(self.item.container.id()),