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 namespace::Namespace;
20 use rustc::ty::subst::{Subst, Substs};
21 use rustc::traits::{self, ObligationCause};
22 use rustc::ty::{self, Ty, ToPolyTraitRef, ToPredicate, TraitRef, TypeFoldable};
23 use rustc::infer::type_variable::TypeVariableOrigin;
24 use rustc::util::nodemap::FxHashSet;
25 use rustc::infer::{self, InferOk};
27 use syntax::util::lev_distance::{lev_distance, find_best_match_for_name};
36 use self::CandidateKind::*;
37 pub use self::PickKind::*;
39 /// Boolean flag used to indicate if this search is for a suggestion
40 /// or not. If true, we can allow ambiguity and so forth.
41 pub struct IsSuggestion(pub bool);
43 struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
44 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
47 method_name: Option<ast::Name>,
48 return_type: Option<Ty<'tcx>>,
49 steps: Rc<Vec<CandidateStep<'tcx>>>,
50 inherent_candidates: Vec<Candidate<'tcx>>,
51 extension_candidates: Vec<Candidate<'tcx>>,
52 impl_dups: FxHashSet<DefId>,
54 /// Collects near misses when the candidate functions are missing a `self` keyword and is only
55 /// used for error reporting
56 static_candidates: Vec<CandidateSource>,
58 /// When probing for names, include names that are close to the
59 /// requested name (by Levensthein distance)
60 allow_similar_names: bool,
62 /// Some(candidate) if there is a private candidate
63 private_candidate: Option<Def>,
65 /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
66 /// for error reporting
67 unsatisfied_predicates: Vec<TraitRef<'tcx>>,
70 impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
71 type Target = FnCtxt<'a, 'gcx, 'tcx>;
72 fn deref(&self) -> &Self::Target {
78 struct CandidateStep<'tcx> {
81 // true if the type results from a dereference of a raw pointer.
82 // when assembling candidates, we include these steps, but not when
83 // picking methods. This so that if we have `foo: *const Foo` and `Foo` has methods
84 // `fn by_raw_ptr(self: *const Self)` and `fn by_ref(&self)`, then
85 // `foo.by_raw_ptr()` will work and `foo.by_ref()` won't.
86 from_unsafe_deref: bool,
91 struct Candidate<'tcx> {
92 xform_self_ty: Ty<'tcx>,
93 xform_ret_ty: Option<Ty<'tcx>>,
94 item: ty::AssociatedItem,
95 kind: CandidateKind<'tcx>,
96 import_id: Option<ast::NodeId>,
100 enum CandidateKind<'tcx> {
101 InherentImplCandidate(&'tcx Substs<'tcx>,
102 // Normalize obligations
103 Vec<traits::PredicateObligation<'tcx>>),
105 TraitCandidate(ty::TraitRef<'tcx>),
106 WhereClauseCandidate(// Trait
107 ty::PolyTraitRef<'tcx>),
110 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
117 #[derive(Debug, PartialEq, Eq, Clone)]
118 pub struct Pick<'tcx> {
119 pub item: ty::AssociatedItem,
120 pub kind: PickKind<'tcx>,
121 pub import_id: Option<ast::NodeId>,
123 // Indicates that the source expression should be autoderef'd N times
125 // A = expr | *expr | **expr | ...
126 pub autoderefs: usize,
128 // Indicates that an autoref is applied after the optional autoderefs
130 // B = A | &A | &mut A
131 pub autoref: Option<hir::Mutability>,
133 // Indicates that the source expression should be "unsized" to a
134 // target type. This should probably eventually go away in favor
135 // of just coercing method receivers.
138 pub unsize: Option<Ty<'tcx>>,
141 #[derive(Clone, Debug, PartialEq, Eq)]
142 pub enum PickKind<'tcx> {
146 WhereClausePick(// Trait
147 ty::PolyTraitRef<'tcx>),
150 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
152 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
154 // An expression of the form `receiver.method_name(...)`.
155 // Autoderefs are performed on `receiver`, lookup is done based on the
156 // `self` argument of the method, and static methods aren't considered.
158 // An expression of the form `Type::item` or `<T>::item`.
159 // No autoderefs are performed, lookup is done based on the type each
160 // implementation is for, and static methods are included.
164 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
165 pub enum ProbeScope {
166 // Assemble candidates coming only from traits in scope.
169 // Assemble candidates coming from all traits.
173 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
174 /// This is used to offer suggestions to users. It returns methods
175 /// that could have been called which have the desired return
176 /// type. Some effort is made to rule out methods that, if called,
177 /// would result in an error (basically, the same criteria we
178 /// would use to decide if a method is a plausible fit for
179 /// ambiguity purposes).
180 pub fn probe_for_return_type(&self,
183 return_type: Ty<'tcx>,
185 scope_expr_id: ast::NodeId)
186 -> Vec<ty::AssociatedItem> {
187 debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
192 self.probe_op(span, mode, None, Some(return_type), IsSuggestion(true),
193 self_ty, scope_expr_id, ProbeScope::AllTraits,
194 |probe_cx| Ok(probe_cx.candidate_method_names()))
198 .flat_map(|&method_name| {
200 span, mode, Some(method_name), Some(return_type),
201 IsSuggestion(true), self_ty, scope_expr_id,
202 ProbeScope::AllTraits, |probe_cx| probe_cx.pick()
203 ).ok().map(|pick| pick.item)
208 pub fn probe_for_name(&self,
211 item_name: ast::Name,
212 is_suggestion: IsSuggestion,
214 scope_expr_id: ast::NodeId,
216 -> PickResult<'tcx> {
217 debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
229 |probe_cx| probe_cx.pick())
232 fn probe_op<OP,R>(&'a self,
235 method_name: Option<ast::Name>,
236 return_type: Option<Ty<'tcx>>,
237 is_suggestion: IsSuggestion,
239 scope_expr_id: ast::NodeId,
242 -> Result<R, MethodError<'tcx>>
243 where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
245 // FIXME(#18741) -- right now, creating the steps involves evaluating the
246 // `*` operator, which registers obligations that then escape into
247 // the global fulfillment context and thus has global
248 // side-effects. This is a bit of a pain to refactor. So just let
249 // it ride, although it's really not great, and in fact could I
250 // think cause spurious errors. Really though this part should
251 // take place in the `self.probe` below.
252 let steps = if mode == Mode::MethodCall {
253 match self.create_steps(span, scope_expr_id, self_ty, is_suggestion) {
254 Some(steps) => steps,
256 return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
267 from_unsafe_deref: false,
272 debug!("ProbeContext: steps for self_ty={:?} are {:?}",
276 // this creates one big transaction so that all type variables etc
277 // that we create during the probe process are removed later
280 ProbeContext::new(self, span, mode, method_name, return_type, Rc::new(steps));
282 probe_cx.assemble_inherent_candidates();
284 ProbeScope::TraitsInScope =>
285 probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?,
286 ProbeScope::AllTraits =>
287 probe_cx.assemble_extension_candidates_for_all_traits()?,
293 fn create_steps(&self,
295 scope_expr_id: ast::NodeId,
297 is_suggestion: IsSuggestion)
298 -> Option<Vec<CandidateStep<'tcx>>> {
299 // FIXME: we don't need to create the entire steps in one pass
301 let mut autoderef = self.autoderef(span, self_ty).include_raw_pointers();
302 let mut reached_raw_pointer = false;
303 let mut steps: Vec<_> = autoderef.by_ref()
305 let step = CandidateStep {
308 from_unsafe_deref: reached_raw_pointer,
311 if let ty::TyRawPtr(_) = ty.sty {
312 // all the subsequent steps will be from_unsafe_deref
313 reached_raw_pointer = true;
319 let final_ty = autoderef.maybe_ambiguous_final_ty();
321 ty::TyInfer(ty::TyVar(_)) => {
322 // Ended in an inference variable. If we are doing
323 // a real method lookup, this is a hard error because it's
324 // possible that there will be multiple applicable methods.
325 if !is_suggestion.0 {
326 if reached_raw_pointer
327 && !self.tcx.sess.features.borrow().arbitrary_self_types {
328 // this case used to be allowed by the compiler,
329 // so we do a future-compat lint here for the 2015 epoch
330 // (see https://github.com/rust-lang/rust/issues/46906)
331 if self.tcx.sess.rust_2018() {
332 span_err!(self.tcx.sess, span, E0908,
333 "the type of this value must be known \
334 to call a method on a raw pointer on it");
337 lint::builtin::TYVAR_BEHIND_RAW_POINTER,
340 &format!("type annotations needed"));
343 let t = self.structurally_resolved_type(span, final_ty);
344 assert_eq!(t, self.tcx.types.err);
348 // If we're just looking for suggestions,
349 // though, ambiguity is no big thing, we can
353 ty::TyArray(elem_ty, _) => {
354 let dereferences = steps.len() - 1;
356 steps.push(CandidateStep {
357 self_ty: self.tcx.mk_slice(elem_ty),
358 autoderefs: dereferences,
359 // this could be from an unsafe deref if we had
360 // a *mut/const [T; N]
361 from_unsafe_deref: reached_raw_pointer,
365 ty::TyError => return None,
369 debug!("create_steps: steps={:?}", steps);
375 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
376 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
379 method_name: Option<ast::Name>,
380 return_type: Option<Ty<'tcx>>,
381 steps: Rc<Vec<CandidateStep<'tcx>>>)
382 -> ProbeContext<'a, 'gcx, 'tcx> {
389 inherent_candidates: Vec::new(),
390 extension_candidates: Vec::new(),
391 impl_dups: FxHashSet(),
393 static_candidates: Vec::new(),
394 allow_similar_names: false,
395 private_candidate: None,
396 unsatisfied_predicates: Vec::new(),
400 fn reset(&mut self) {
401 self.inherent_candidates.clear();
402 self.extension_candidates.clear();
403 self.impl_dups.clear();
404 self.static_candidates.clear();
405 self.private_candidate = None;
408 ///////////////////////////////////////////////////////////////////////////
409 // CANDIDATE ASSEMBLY
411 fn push_candidate(&mut self,
412 candidate: Candidate<'tcx>,
415 let is_accessible = if let Some(name) = self.method_name {
416 let item = candidate.item;
417 let def_scope = self.tcx.adjust(name, item.container.id(), self.body_id).1;
418 item.vis.is_accessible_from(def_scope, self.tcx)
424 self.inherent_candidates.push(candidate);
426 self.extension_candidates.push(candidate);
428 } else if self.private_candidate.is_none() {
429 self.private_candidate = Some(candidate.item.def());
433 fn assemble_inherent_candidates(&mut self) {
434 let steps = self.steps.clone();
435 for step in steps.iter() {
436 self.assemble_probe(step.self_ty);
440 fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
441 debug!("assemble_probe: self_ty={:?}", self_ty);
442 let lang_items = self.tcx.lang_items();
445 ty::TyDynamic(ref data, ..) => {
446 if let Some(p) = data.principal() {
447 self.assemble_inherent_candidates_from_object(self_ty, p);
448 self.assemble_inherent_impl_candidates_for_type(p.def_id());
451 ty::TyAdt(def, _) => {
452 self.assemble_inherent_impl_candidates_for_type(def.did);
454 ty::TyForeign(did) => {
455 self.assemble_inherent_impl_candidates_for_type(did);
458 self.assemble_inherent_candidates_from_param(self_ty, p);
461 let lang_def_id = lang_items.char_impl();
462 self.assemble_inherent_impl_for_primitive(lang_def_id);
465 let lang_def_id = lang_items.str_impl();
466 self.assemble_inherent_impl_for_primitive(lang_def_id);
469 let lang_def_id = lang_items.slice_impl();
470 self.assemble_inherent_impl_for_primitive(lang_def_id);
472 let lang_def_id = lang_items.slice_u8_impl();
473 self.assemble_inherent_impl_for_primitive(lang_def_id);
475 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
476 let lang_def_id = lang_items.const_ptr_impl();
477 self.assemble_inherent_impl_for_primitive(lang_def_id);
479 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
480 let lang_def_id = lang_items.mut_ptr_impl();
481 self.assemble_inherent_impl_for_primitive(lang_def_id);
483 ty::TyInt(ast::IntTy::I8) => {
484 let lang_def_id = lang_items.i8_impl();
485 self.assemble_inherent_impl_for_primitive(lang_def_id);
487 ty::TyInt(ast::IntTy::I16) => {
488 let lang_def_id = lang_items.i16_impl();
489 self.assemble_inherent_impl_for_primitive(lang_def_id);
491 ty::TyInt(ast::IntTy::I32) => {
492 let lang_def_id = lang_items.i32_impl();
493 self.assemble_inherent_impl_for_primitive(lang_def_id);
495 ty::TyInt(ast::IntTy::I64) => {
496 let lang_def_id = lang_items.i64_impl();
497 self.assemble_inherent_impl_for_primitive(lang_def_id);
499 ty::TyInt(ast::IntTy::I128) => {
500 let lang_def_id = lang_items.i128_impl();
501 self.assemble_inherent_impl_for_primitive(lang_def_id);
503 ty::TyInt(ast::IntTy::Isize) => {
504 let lang_def_id = lang_items.isize_impl();
505 self.assemble_inherent_impl_for_primitive(lang_def_id);
507 ty::TyUint(ast::UintTy::U8) => {
508 let lang_def_id = lang_items.u8_impl();
509 self.assemble_inherent_impl_for_primitive(lang_def_id);
511 ty::TyUint(ast::UintTy::U16) => {
512 let lang_def_id = lang_items.u16_impl();
513 self.assemble_inherent_impl_for_primitive(lang_def_id);
515 ty::TyUint(ast::UintTy::U32) => {
516 let lang_def_id = lang_items.u32_impl();
517 self.assemble_inherent_impl_for_primitive(lang_def_id);
519 ty::TyUint(ast::UintTy::U64) => {
520 let lang_def_id = lang_items.u64_impl();
521 self.assemble_inherent_impl_for_primitive(lang_def_id);
523 ty::TyUint(ast::UintTy::U128) => {
524 let lang_def_id = lang_items.u128_impl();
525 self.assemble_inherent_impl_for_primitive(lang_def_id);
527 ty::TyUint(ast::UintTy::Usize) => {
528 let lang_def_id = lang_items.usize_impl();
529 self.assemble_inherent_impl_for_primitive(lang_def_id);
531 ty::TyFloat(ast::FloatTy::F32) => {
532 let lang_def_id = lang_items.f32_impl();
533 self.assemble_inherent_impl_for_primitive(lang_def_id);
535 ty::TyFloat(ast::FloatTy::F64) => {
536 let lang_def_id = lang_items.f64_impl();
537 self.assemble_inherent_impl_for_primitive(lang_def_id);
543 fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
544 if let Some(impl_def_id) = lang_def_id {
545 self.assemble_inherent_impl_probe(impl_def_id);
549 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
550 let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
551 for &impl_def_id in impl_def_ids.iter() {
552 self.assemble_inherent_impl_probe(impl_def_id);
556 fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
557 if !self.impl_dups.insert(impl_def_id) {
558 return; // already visited
561 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
563 for item in self.impl_or_trait_item(impl_def_id) {
564 if !self.has_applicable_self(&item) {
565 // No receiver declared. Not a candidate.
566 self.record_static_candidate(ImplSource(impl_def_id));
570 let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
571 let impl_ty = impl_ty.subst(self.tcx, impl_substs);
573 // Determine the receiver type that the method itself expects.
574 let xform_tys = self.xform_self_ty(&item, impl_ty, impl_substs);
576 // We can't use normalize_associated_types_in as it will pollute the
577 // fcx's fulfillment context after this probe is over.
578 let cause = traits::ObligationCause::misc(self.span, self.body_id);
579 let selcx = &mut traits::SelectionContext::new(self.fcx);
580 let traits::Normalized { value: (xform_self_ty, xform_ret_ty), obligations } =
581 traits::normalize(selcx, self.param_env, cause, &xform_tys);
582 debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}/{:?}",
583 xform_self_ty, xform_ret_ty);
585 self.push_candidate(Candidate {
586 xform_self_ty, xform_ret_ty, item,
587 kind: InherentImplCandidate(impl_substs, obligations),
593 fn assemble_inherent_candidates_from_object(&mut self,
595 principal: ty::PolyExistentialTraitRef<'tcx>) {
596 debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
599 // It is illegal to invoke a method on a trait instance that
600 // refers to the `Self` type. An error will be reported by
601 // `enforce_object_limitations()` if the method refers to the
602 // `Self` type anywhere other than the receiver. Here, we use
603 // a substitution that replaces `Self` with the object type
604 // itself. Hence, a `&self` method will wind up with an
605 // argument type like `&Trait`.
606 let trait_ref = principal.with_self_ty(self.tcx, self_ty);
607 self.elaborate_bounds(&[trait_ref], |this, new_trait_ref, item| {
608 let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
610 let (xform_self_ty, xform_ret_ty) =
611 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
612 this.push_candidate(Candidate {
613 xform_self_ty, xform_ret_ty, item,
614 kind: ObjectCandidate,
620 fn assemble_inherent_candidates_from_param(&mut self,
622 param_ty: ty::ParamTy) {
623 // FIXME -- Do we want to commit to this behavior for param bounds?
625 let bounds: Vec<_> = self.param_env
628 .filter_map(|predicate| {
630 ty::Predicate::Trait(ref trait_predicate) => {
631 match trait_predicate.0.trait_ref.self_ty().sty {
632 ty::TyParam(ref p) if *p == param_ty => {
633 Some(trait_predicate.to_poly_trait_ref())
638 ty::Predicate::Equate(..) |
639 ty::Predicate::Subtype(..) |
640 ty::Predicate::Projection(..) |
641 ty::Predicate::RegionOutlives(..) |
642 ty::Predicate::WellFormed(..) |
643 ty::Predicate::ObjectSafe(..) |
644 ty::Predicate::ClosureKind(..) |
645 ty::Predicate::TypeOutlives(..) |
646 ty::Predicate::ConstEvaluatable(..) => None,
651 self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
652 let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
654 let (xform_self_ty, xform_ret_ty) =
655 this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
657 // Because this trait derives from a where-clause, it
658 // should not contain any inference variables or other
659 // artifacts. This means it is safe to put into the
660 // `WhereClauseCandidate` and (eventually) into the
661 // `WhereClausePick`.
662 assert!(!trait_ref.substs.needs_infer());
664 this.push_candidate(Candidate {
665 xform_self_ty, xform_ret_ty, item,
666 kind: WhereClauseCandidate(poly_trait_ref),
672 // Do a search through a list of bounds, using a callback to actually
673 // create the candidates.
674 fn elaborate_bounds<F>(&mut self, bounds: &[ty::PolyTraitRef<'tcx>], mut mk_cand: F)
675 where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>,
676 ty::PolyTraitRef<'tcx>,
679 debug!("elaborate_bounds(bounds={:?})", bounds);
682 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
683 for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
684 if !self.has_applicable_self(&item) {
685 self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
687 mk_cand(self, bound_trait_ref, item);
693 fn assemble_extension_candidates_for_traits_in_scope(&mut self,
694 expr_id: ast::NodeId)
695 -> Result<(), MethodError<'tcx>> {
696 if expr_id == ast::DUMMY_NODE_ID {
699 let mut duplicates = FxHashSet();
700 let expr_hir_id = self.tcx.hir.node_to_hir_id(expr_id);
701 let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
702 if let Some(applicable_traits) = opt_applicable_traits {
703 for trait_candidate in applicable_traits.iter() {
704 let trait_did = trait_candidate.def_id;
705 if duplicates.insert(trait_did) {
706 let import_id = trait_candidate.import_id;
707 let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
715 fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
716 let mut duplicates = FxHashSet();
717 for trait_info in suggest::all_traits(self.tcx) {
718 if duplicates.insert(trait_info.def_id) {
719 self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
725 pub fn matches_return_type(&self,
726 method: &ty::AssociatedItem,
727 self_ty: Option<Ty<'tcx>>,
728 expected: Ty<'tcx>) -> bool {
730 Def::Method(def_id) => {
731 let fty = self.tcx.fn_sig(def_id);
733 let substs = self.fresh_substs_for_item(ty::UniverseIndex::ROOT,
736 let fty = fty.subst(self.tcx, substs);
737 let (fty, _) = self.replace_late_bound_regions_with_fresh_var(
738 self.span, infer::FnCall, &fty);
740 if let Some(self_ty) = self_ty {
741 if let Err(_) = self.at(&ObligationCause::dummy(), self.param_env)
742 .sup(fty.inputs()[0], self_ty)
747 self.can_sub(self.param_env, fty.output(), expected).is_ok()
754 fn assemble_extension_candidates_for_trait(&mut self,
755 import_id: Option<ast::NodeId>,
757 -> Result<(), MethodError<'tcx>> {
758 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
760 let trait_substs = self.fresh_item_substs(trait_def_id);
761 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
763 for item in self.impl_or_trait_item(trait_def_id) {
764 // Check whether `trait_def_id` defines a method with suitable name:
765 if !self.has_applicable_self(&item) {
766 debug!("method has inapplicable self");
767 self.record_static_candidate(TraitSource(trait_def_id));
771 let (xform_self_ty, xform_ret_ty) =
772 self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
773 self.push_candidate(Candidate {
774 xform_self_ty, xform_ret_ty, item, import_id,
775 kind: TraitCandidate(trait_ref),
781 fn candidate_method_names(&self) -> Vec<ast::Name> {
782 let mut set = FxHashSet();
783 let mut names: Vec<_> = self.inherent_candidates
785 .chain(&self.extension_candidates)
786 .filter(|candidate| {
787 if let Some(return_ty) = self.return_type {
788 self.matches_return_type(&candidate.item, None, return_ty)
793 .map(|candidate| candidate.item.name)
794 .filter(|&name| set.insert(name))
797 // sort them by the name so we have a stable result
798 names.sort_by_key(|n| n.as_str());
802 ///////////////////////////////////////////////////////////////////////////
805 fn pick(mut self) -> PickResult<'tcx> {
806 assert!(self.method_name.is_some());
808 if let Some(r) = self.pick_core() {
812 let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
813 let private_candidate = mem::replace(&mut self.private_candidate, None);
814 let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
816 // things failed, so lets look at all traits, for diagnostic purposes now:
819 let span = self.span;
822 self.assemble_extension_candidates_for_all_traits()?;
824 let out_of_scope_traits = match self.pick_core() {
825 Some(Ok(p)) => vec![p.item.container.id()],
826 //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
827 Some(Err(MethodError::Ambiguity(v))) => {
831 TraitSource(id) => id,
832 ImplSource(impl_id) => {
833 match tcx.trait_id_of_impl(impl_id) {
837 "found inherent method when looking at traits")
845 Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
846 assert!(others.is_empty());
852 if let Some(def) = private_candidate {
853 return Err(MethodError::PrivateMatch(def, out_of_scope_traits));
855 let lev_candidate = self.probe_for_lev_candidate()?;
857 Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
858 unsatisfied_predicates,
864 fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
865 let steps = self.steps.clone();
867 // find the first step that works
871 debug!("pick_core: step={:?}", step);
872 // skip types that are from a type error or that would require dereferencing
874 !step.self_ty.references_error() && !step.from_unsafe_deref
876 self.pick_by_value_method(step).or_else(|| {
877 self.pick_autorefd_method(step, hir::MutImmutable).or_else(|| {
878 self.pick_autorefd_method(step, hir::MutMutable)
883 fn pick_by_value_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
884 //! For each type `T` in the step list, this attempts to find a
885 //! method where the (transformed) self type is exactly `T`. We
886 //! do however do one transformation on the adjustment: if we
887 //! are passing a region pointer in, we will potentially
888 //! *reborrow* it to a shorter lifetime. This allows us to
889 //! transparently pass `&mut` pointers, in particular, without
890 //! consuming them for their entire lifetime.
896 self.pick_method(step.self_ty).map(|r| {
898 pick.autoderefs = step.autoderefs;
900 // Insert a `&*` or `&mut *` if this is a reference type:
901 if let ty::TyRef(_, mt) = step.self_ty.sty {
902 pick.autoderefs += 1;
903 pick.autoref = Some(mt.mutbl);
911 fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>, mutbl: hir::Mutability)
912 -> Option<PickResult<'tcx>> {
915 // In general, during probing we erase regions. See
916 // `impl_self_ty()` for an explanation.
917 let region = tcx.types.re_erased;
919 let autoref_ty = tcx.mk_ref(region,
921 ty: step.self_ty, mutbl
923 self.pick_method(autoref_ty).map(|r| {
925 pick.autoderefs = step.autoderefs;
926 pick.autoref = Some(mutbl);
927 pick.unsize = if step.unsize {
937 fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
938 debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
940 let mut possibly_unsatisfied_predicates = Vec::new();
942 debug!("searching inherent candidates");
943 if let Some(pick) = self.consider_candidates(self_ty,
944 &self.inherent_candidates,
945 &mut possibly_unsatisfied_predicates) {
949 debug!("searching extension candidates");
950 let res = self.consider_candidates(self_ty,
951 &self.extension_candidates,
952 &mut possibly_unsatisfied_predicates);
954 self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
959 fn consider_candidates(&self,
961 probes: &[Candidate<'tcx>],
962 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
963 -> Option<PickResult<'tcx>> {
964 let mut applicable_candidates: Vec<_> = probes.iter()
966 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
968 .filter(|&(_, status)| status != ProbeResult::NoMatch)
971 debug!("applicable_candidates: {:?}", applicable_candidates);
973 if applicable_candidates.len() > 1 {
974 if let Some(pick) = self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
975 return Some(Ok(pick));
979 if applicable_candidates.len() > 1 {
980 let sources = probes.iter()
981 .map(|p| self.candidate_source(p, self_ty))
983 return Some(Err(MethodError::Ambiguity(sources)));
986 applicable_candidates.pop().map(|(probe, status)| {
987 if status == ProbeResult::Match {
988 Ok(probe.to_unadjusted_pick())
990 Err(MethodError::BadReturnType)
995 fn select_trait_candidate(&self, trait_ref: ty::TraitRef<'tcx>)
996 -> traits::SelectionResult<'tcx, traits::Selection<'tcx>>
998 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1000 trait_ref.to_poly_trait_ref().to_poly_trait_predicate();
1001 let obligation = traits::Obligation::new(cause, self.param_env, predicate);
1002 traits::SelectionContext::new(self).select(&obligation)
1005 fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>)
1008 match candidate.kind {
1009 InherentImplCandidate(..) => ImplSource(candidate.item.container.id()),
1011 WhereClauseCandidate(_) => TraitSource(candidate.item.container.id()),
1012 TraitCandidate(trait_ref) => self.probe(|_| {
1013 let _ = self.at(&ObligationCause::dummy(), self.param_env)
1014 .sup(candidate.xform_self_ty, self_ty);
1015 match self.select_trait_candidate(trait_ref) {
1016 Ok(Some(traits::Vtable::VtableImpl(ref impl_data))) => {
1017 // If only a single impl matches, make the error message point
1019 ImplSource(impl_data.impl_def_id)
1022 TraitSource(candidate.item.container.id())
1029 fn consider_probe(&self,
1031 probe: &Candidate<'tcx>,
1032 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1034 debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1037 // First check that the self type can be related.
1038 let sub_obligations = match self.at(&ObligationCause::dummy(), self.param_env)
1039 .sup(probe.xform_self_ty, self_ty) {
1040 Ok(InferOk { obligations, value: () }) => obligations,
1042 debug!("--> cannot relate self-types");
1043 return ProbeResult::NoMatch;
1047 let mut result = ProbeResult::Match;
1048 let selcx = &mut traits::SelectionContext::new(self);
1049 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1051 // If so, impls may carry other conditions (e.g., where
1052 // clauses) that must be considered. Make sure that those
1053 // match as well (or at least may match, sometimes we
1054 // don't have enough information to fully evaluate).
1055 let candidate_obligations : Vec<_> = match probe.kind {
1056 InherentImplCandidate(ref substs, ref ref_obligations) => {
1057 // Check whether the impl imposes obligations we have to worry about.
1058 let impl_def_id = probe.item.container.id();
1059 let impl_bounds = self.tcx.predicates_of(impl_def_id);
1060 let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1061 let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1062 traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
1064 // Convert the bounds into obligations.
1065 let impl_obligations = traits::predicates_for_generics(
1066 cause.clone(), self.param_env, &impl_bounds);
1068 debug!("impl_obligations={:?}", impl_obligations);
1069 impl_obligations.into_iter()
1070 .chain(norm_obligations.into_iter())
1071 .chain(ref_obligations.iter().cloned())
1076 WhereClauseCandidate(..) => {
1077 // These have no additional conditions to check.
1081 TraitCandidate(trait_ref) => {
1082 let predicate = trait_ref.to_predicate();
1084 traits::Obligation::new(cause.clone(), self.param_env, predicate);
1085 if !selcx.evaluate_obligation(&obligation) {
1086 if self.probe(|_| self.select_trait_candidate(trait_ref).is_err()) {
1087 // This candidate's primary obligation doesn't even
1088 // select - don't bother registering anything in
1089 // `potentially_unsatisfied_predicates`.
1090 return ProbeResult::NoMatch;
1092 // Some nested subobligation of this predicate
1095 // FIXME: try to find the exact nested subobligation
1096 // and point at it rather than reporting the entire
1098 result = ProbeResult::NoMatch;
1099 let trait_ref = self.resolve_type_vars_if_possible(&trait_ref);
1100 possibly_unsatisfied_predicates.push(trait_ref);
1107 debug!("consider_probe - candidate_obligations={:?} sub_obligations={:?}",
1108 candidate_obligations, sub_obligations);
1110 // Evaluate those obligations to see if they might possibly hold.
1111 for o in candidate_obligations.into_iter().chain(sub_obligations) {
1112 let o = self.resolve_type_vars_if_possible(&o);
1113 if !selcx.evaluate_obligation(&o) {
1114 result = ProbeResult::NoMatch;
1115 if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1116 possibly_unsatisfied_predicates.push(pred.0.trait_ref);
1121 if let ProbeResult::Match = result {
1122 if let (Some(return_ty), Some(xform_ret_ty)) =
1123 (self.return_type, probe.xform_ret_ty)
1125 let xform_ret_ty = self.resolve_type_vars_if_possible(&xform_ret_ty);
1126 debug!("comparing return_ty {:?} with xform ret ty {:?}",
1128 probe.xform_ret_ty);
1129 if self.at(&ObligationCause::dummy(), self.param_env)
1130 .sup(return_ty, xform_ret_ty)
1133 return ProbeResult::BadReturnType;
1142 /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1143 /// same trait, but we don't know which impl to use. In this case, since in all cases the
1144 /// external interface of the method can be determined from the trait, it's ok not to decide.
1145 /// We can basically just collapse all of the probes for various impls into one where-clause
1146 /// probe. This will result in a pending obligation so when more type-info is available we can
1147 /// make the final decision.
1149 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1152 /// trait Foo { ... }
1153 /// impl Foo for Vec<int> { ... }
1154 /// impl Foo for Vec<usize> { ... }
1157 /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1158 /// use, so it's ok to just commit to "using the method from the trait Foo".
1159 fn collapse_candidates_to_trait_pick(&self, probes: &[(&Candidate<'tcx>, ProbeResult)])
1160 -> Option<Pick<'tcx>>
1162 // Do all probes correspond to the same trait?
1163 let container = probes[0].0.item.container;
1165 ty::TraitContainer(_) => {}
1166 ty::ImplContainer(_) => return None,
1168 if probes[1..].iter().any(|&(p, _)| p.item.container != container) {
1172 // FIXME: check the return type here somehow.
1173 // If so, just use this trait and call it a day.
1175 item: probes[0].0.item.clone(),
1177 import_id: probes[0].0.import_id,
1184 /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
1185 /// candidate method where the method name may have been misspelt. Similarly to other
1186 /// Levenshtein based suggestions, we provide at most one such suggestion.
1187 fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssociatedItem>, MethodError<'tcx>> {
1188 debug!("Probing for method names similar to {:?}",
1191 let steps = self.steps.clone();
1193 let mut pcx = ProbeContext::new(self.fcx, self.span, self.mode, self.method_name,
1194 self.return_type, steps);
1195 pcx.allow_similar_names = true;
1196 pcx.assemble_inherent_candidates();
1197 pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)?;
1199 let method_names = pcx.candidate_method_names();
1200 pcx.allow_similar_names = false;
1201 let applicable_close_candidates: Vec<ty::AssociatedItem> = method_names
1203 .filter_map(|&method_name| {
1205 pcx.method_name = Some(method_name);
1206 pcx.assemble_inherent_candidates();
1207 pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)
1208 .ok().map_or(None, |_| {
1210 .and_then(|pick| pick.ok())
1211 .and_then(|pick| Some(pick.item))
1216 if applicable_close_candidates.is_empty() {
1220 let names = applicable_close_candidates.iter().map(|cand| &cand.name);
1221 find_best_match_for_name(names,
1222 &self.method_name.unwrap().as_str(),
1225 Ok(applicable_close_candidates
1227 .find(|method| method.name == best_name))
1232 ///////////////////////////////////////////////////////////////////////////
1234 fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1235 // "Fast track" -- check for usage of sugar when in method call
1238 // In Path mode (i.e., resolving a value like `T::next`), consider any
1239 // associated value (i.e., methods, constants) but not types.
1241 Mode::MethodCall => item.method_has_self_argument,
1242 Mode::Path => match item.kind {
1243 ty::AssociatedKind::Type => false,
1244 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1247 // FIXME -- check for types that deref to `Self`,
1248 // like `Rc<Self>` and so on.
1250 // Note also that the current code will break if this type
1251 // includes any of the type parameters defined on the method
1252 // -- but this could be overcome.
1255 fn record_static_candidate(&mut self, source: CandidateSource) {
1256 self.static_candidates.push(source);
1259 fn xform_self_ty(&self,
1260 item: &ty::AssociatedItem,
1262 substs: &Substs<'tcx>)
1263 -> (Ty<'tcx>, Option<Ty<'tcx>>) {
1264 if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1265 let sig = self.xform_method_sig(item.def_id, substs);
1266 (sig.inputs()[0], Some(sig.output()))
1272 fn xform_method_sig(&self,
1274 substs: &Substs<'tcx>)
1277 let fn_sig = self.tcx.fn_sig(method);
1278 debug!("xform_self_ty(fn_sig={:?}, substs={:?})",
1282 assert!(!substs.has_escaping_regions());
1284 // It is possible for type parameters or early-bound lifetimes
1285 // to appear in the signature of `self`. The substitutions we
1286 // are given do not include type/lifetime parameters for the
1287 // method yet. So create fresh variables here for those too,
1288 // if there are any.
1289 let generics = self.tcx.generics_of(method);
1290 assert_eq!(substs.types().count(), generics.parent_types as usize);
1291 assert_eq!(substs.regions().count(), generics.parent_regions as usize);
1293 // Erase any late-bound regions from the method and substitute
1294 // in the values from the substitution.
1295 let xform_fn_sig = self.erase_late_bound_regions(&fn_sig);
1297 if generics.types.is_empty() && generics.regions.is_empty() {
1298 xform_fn_sig.subst(self.tcx, substs)
1300 let substs = Substs::for_item(self.tcx, method, |def, _| {
1301 let i = def.index as usize;
1302 if i < substs.len() {
1305 // In general, during probe we erase regions. See
1306 // `impl_self_ty()` for an explanation.
1307 self.tcx.types.re_erased
1309 }, |def, _cur_substs| {
1310 let i = def.index as usize;
1311 if i < substs.len() {
1314 self.type_var_for_def(ty::UniverseIndex::ROOT, self.span, def)
1317 xform_fn_sig.subst(self.tcx, substs)
1321 /// Get the type of an impl and generate substitutions with placeholders.
1322 fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
1323 (self.tcx.type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1326 fn fresh_item_substs(&self, def_id: DefId) -> &'tcx Substs<'tcx> {
1327 Substs::for_item(self.tcx,
1329 |_, _| self.tcx.types.re_erased,
1330 |_, _| self.next_ty_var(
1331 ty::UniverseIndex::ROOT,
1332 TypeVariableOrigin::SubstitutionPlaceholder(
1333 self.tcx.def_span(def_id))))
1336 /// Replace late-bound-regions bound by `value` with `'static` using
1337 /// `ty::erase_late_bound_regions`.
1339 /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1340 /// method matching. It is reasonable during the probe phase because we don't consider region
1341 /// relationships at all. Therefore, we can just replace all the region variables with 'static
1342 /// rather than creating fresh region variables. This is nice for two reasons:
1344 /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1345 /// particular method call, it winds up creating fewer types overall, which helps for memory
1346 /// usage. (Admittedly, this is a rather small effect, though measureable.)
1348 /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1349 /// late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1350 /// regions with actual region variables as is proper, we'd have to ensure that the same
1351 /// region got replaced with the same variable, which requires a bit more coordination
1352 /// and/or tracking the substitution and
1354 fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1355 where T: TypeFoldable<'tcx>
1357 self.tcx.erase_late_bound_regions(value)
1360 /// Find the method with the appropriate name (or return type, as the case may be). If
1361 /// `allow_similar_names` is set, find methods with close-matching names.
1362 fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1363 if let Some(name) = self.method_name {
1364 if self.allow_similar_names {
1365 let max_dist = max(name.as_str().len(), 3) / 3;
1366 self.tcx.associated_items(def_id)
1368 let dist = lev_distance(&*name.as_str(), &x.name.as_str());
1369 Namespace::from(x.kind) == Namespace::Value && dist > 0
1375 .associated_item(def_id, name, Namespace::Value)
1376 .map_or(Vec::new(), |x| vec![x])
1379 self.tcx.associated_items(def_id).collect()
1384 impl<'tcx> Candidate<'tcx> {
1385 fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1387 item: self.item.clone(),
1388 kind: match self.kind {
1389 InherentImplCandidate(..) => InherentImplPick,
1390 ObjectCandidate => ObjectPick,
1391 TraitCandidate(_) => TraitPick,
1392 WhereClauseCandidate(ref trait_ref) => {
1393 // Only trait derived from where-clauses should
1394 // appear here, so they should not contain any
1395 // inference variables or other artifacts. This
1396 // means they are safe to put into the
1397 // `WhereClausePick`.
1398 assert!(!trait_ref.substs().needs_infer());
1400 WhereClausePick(trait_ref.clone())
1403 import_id: self.import_id,