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};
26 use rustc::middle::stability;
28 use syntax::util::lev_distance::{lev_distance, find_best_match_for_name};
29 use syntax_pos::{Span, symbol::Symbol};
37 use self::CandidateKind::*;
38 pub use self::PickKind::*;
40 /// Boolean flag used to indicate if this search is for a suggestion
41 /// or not. If true, we can allow ambiguity and so forth.
42 #[derive(Clone, Copy)]
43 pub struct IsSuggestion(pub bool);
45 struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
46 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
49 method_name: Option<ast::Name>,
50 return_type: Option<Ty<'tcx>>,
51 steps: Rc<Vec<CandidateStep<'tcx>>>,
52 inherent_candidates: Vec<Candidate<'tcx>>,
53 extension_candidates: Vec<Candidate<'tcx>>,
54 impl_dups: FxHashSet<DefId>,
56 /// Collects near misses when the candidate functions are missing a `self` keyword and is only
57 /// used for error reporting
58 static_candidates: Vec<CandidateSource>,
60 /// When probing for names, include names that are close to the
61 /// requested name (by Levensthein distance)
62 allow_similar_names: bool,
64 /// Some(candidate) if there is a private candidate
65 private_candidate: Option<Def>,
67 /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
68 /// for error reporting
69 unsatisfied_predicates: Vec<TraitRef<'tcx>>,
71 is_suggestion: IsSuggestion,
74 impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
75 type Target = FnCtxt<'a, 'gcx, 'tcx>;
76 fn deref(&self) -> &Self::Target {
82 struct CandidateStep<'tcx> {
85 // true if the type results from a dereference of a raw pointer.
86 // when assembling candidates, we include these steps, but not when
87 // picking methods. This so that if we have `foo: *const Foo` and `Foo` has methods
88 // `fn by_raw_ptr(self: *const Self)` and `fn by_ref(&self)`, then
89 // `foo.by_raw_ptr()` will work and `foo.by_ref()` won't.
90 from_unsafe_deref: bool,
95 struct Candidate<'tcx> {
96 xform_self_ty: Ty<'tcx>,
97 xform_ret_ty: Option<Ty<'tcx>>,
98 item: ty::AssociatedItem,
99 kind: CandidateKind<'tcx>,
100 import_id: Option<ast::NodeId>,
104 enum CandidateKind<'tcx> {
105 InherentImplCandidate(&'tcx Substs<'tcx>,
106 // Normalize obligations
107 Vec<traits::PredicateObligation<'tcx>>),
109 TraitCandidate(ty::TraitRef<'tcx>),
110 WhereClauseCandidate(// Trait
111 ty::PolyTraitRef<'tcx>),
114 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
121 #[derive(Debug, PartialEq, Eq, Clone)]
122 pub struct Pick<'tcx> {
123 pub item: ty::AssociatedItem,
124 pub kind: PickKind<'tcx>,
125 pub import_id: Option<ast::NodeId>,
127 // Indicates that the source expression should be autoderef'd N times
129 // A = expr | *expr | **expr | ...
130 pub autoderefs: usize,
132 // Indicates that an autoref is applied after the optional autoderefs
134 // B = A | &A | &mut A
135 pub autoref: Option<hir::Mutability>,
137 // Indicates that the source expression should be "unsized" to a
138 // target type. This should probably eventually go away in favor
139 // of just coercing method receivers.
142 pub unsize: Option<Ty<'tcx>>,
145 #[derive(Clone, Debug, PartialEq, Eq)]
146 pub enum PickKind<'tcx> {
150 WhereClausePick(// Trait
151 ty::PolyTraitRef<'tcx>),
154 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
156 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
158 // An expression of the form `receiver.method_name(...)`.
159 // Autoderefs are performed on `receiver`, lookup is done based on the
160 // `self` argument of the method, and static methods aren't considered.
162 // An expression of the form `Type::item` or `<T>::item`.
163 // No autoderefs are performed, lookup is done based on the type each
164 // implementation is for, and static methods are included.
168 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
169 pub enum ProbeScope {
170 // Assemble candidates coming only from traits in scope.
173 // Assemble candidates coming from all traits.
177 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
178 /// This is used to offer suggestions to users. It returns methods
179 /// that could have been called which have the desired return
180 /// type. Some effort is made to rule out methods that, if called,
181 /// would result in an error (basically, the same criteria we
182 /// would use to decide if a method is a plausible fit for
183 /// ambiguity purposes).
184 pub fn probe_for_return_type(&self,
187 return_type: Ty<'tcx>,
189 scope_expr_id: ast::NodeId)
190 -> Vec<ty::AssociatedItem> {
191 debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
196 self.probe_op(span, mode, None, Some(return_type), IsSuggestion(true),
197 self_ty, scope_expr_id, ProbeScope::AllTraits,
198 |probe_cx| Ok(probe_cx.candidate_method_names()))
202 .flat_map(|&method_name| {
204 span, mode, Some(method_name), Some(return_type),
205 IsSuggestion(true), self_ty, scope_expr_id,
206 ProbeScope::AllTraits, |probe_cx| probe_cx.pick()
207 ).ok().map(|pick| pick.item)
212 pub fn probe_for_name(&self,
215 item_name: ast::Name,
216 is_suggestion: IsSuggestion,
218 scope_expr_id: ast::NodeId,
220 -> PickResult<'tcx> {
221 debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
233 |probe_cx| probe_cx.pick())
236 fn probe_op<OP,R>(&'a self,
239 method_name: Option<ast::Name>,
240 return_type: Option<Ty<'tcx>>,
241 is_suggestion: IsSuggestion,
243 scope_expr_id: ast::NodeId,
246 -> Result<R, MethodError<'tcx>>
247 where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
249 // FIXME(#18741) -- right now, creating the steps involves evaluating the
250 // `*` operator, which registers obligations that then escape into
251 // the global fulfillment context and thus has global
252 // side-effects. This is a bit of a pain to refactor. So just let
253 // it ride, although it's really not great, and in fact could I
254 // think cause spurious errors. Really though this part should
255 // take place in the `self.probe` below.
256 let steps = if mode == Mode::MethodCall {
257 match self.create_steps(span, scope_expr_id, self_ty, is_suggestion) {
258 Some(steps) => steps,
260 return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
271 from_unsafe_deref: false,
276 debug!("ProbeContext: steps for self_ty={:?} are {:?}",
280 // this creates one big transaction so that all type variables etc
281 // that we create during the probe process are removed later
283 let mut probe_cx = ProbeContext::new(
284 self, span, mode, method_name, return_type, Rc::new(steps), is_suggestion,
287 probe_cx.assemble_inherent_candidates();
289 ProbeScope::TraitsInScope =>
290 probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?,
291 ProbeScope::AllTraits =>
292 probe_cx.assemble_extension_candidates_for_all_traits()?,
298 fn create_steps(&self,
300 scope_expr_id: ast::NodeId,
302 is_suggestion: IsSuggestion)
303 -> Option<Vec<CandidateStep<'tcx>>> {
304 // FIXME: we don't need to create the entire steps in one pass
306 let mut autoderef = self.autoderef(span, self_ty).include_raw_pointers();
307 let mut reached_raw_pointer = false;
308 let mut steps: Vec<_> = autoderef.by_ref()
310 let step = CandidateStep {
313 from_unsafe_deref: reached_raw_pointer,
316 if let ty::TyRawPtr(_) = ty.sty {
317 // all the subsequent steps will be from_unsafe_deref
318 reached_raw_pointer = true;
324 let final_ty = autoderef.maybe_ambiguous_final_ty();
326 ty::TyInfer(ty::TyVar(_)) => {
327 // Ended in an inference variable. If we are doing
328 // a real method lookup, this is a hard error because it's
329 // possible that there will be multiple applicable methods.
330 if !is_suggestion.0 {
331 if reached_raw_pointer
332 && !self.tcx.features().arbitrary_self_types {
333 // this case used to be allowed by the compiler,
334 // so we do a future-compat lint here for the 2015 edition
335 // (see https://github.com/rust-lang/rust/issues/46906)
336 if self.tcx.sess.rust_2018() {
337 span_err!(self.tcx.sess, span, E0908,
338 "the type of this value must be known \
339 to call a method on a raw pointer on it");
342 lint::builtin::TYVAR_BEHIND_RAW_POINTER,
345 &format!("type annotations needed"));
348 let t = self.structurally_resolved_type(span, final_ty);
349 assert_eq!(t, self.tcx.types.err);
353 // If we're just looking for suggestions,
354 // though, ambiguity is no big thing, we can
358 ty::TyArray(elem_ty, _) => {
359 let dereferences = steps.len() - 1;
361 steps.push(CandidateStep {
362 self_ty: self.tcx.mk_slice(elem_ty),
363 autoderefs: dereferences,
364 // this could be from an unsafe deref if we had
365 // a *mut/const [T; N]
366 from_unsafe_deref: reached_raw_pointer,
370 ty::TyError => return None,
374 debug!("create_steps: steps={:?}", steps);
380 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
381 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
384 method_name: Option<ast::Name>,
385 return_type: Option<Ty<'tcx>>,
386 steps: Rc<Vec<CandidateStep<'tcx>>>,
387 is_suggestion: IsSuggestion)
388 -> ProbeContext<'a, 'gcx, 'tcx> {
395 inherent_candidates: Vec::new(),
396 extension_candidates: Vec::new(),
397 impl_dups: FxHashSet(),
399 static_candidates: Vec::new(),
400 allow_similar_names: false,
401 private_candidate: None,
402 unsatisfied_predicates: Vec::new(),
407 fn reset(&mut self) {
408 self.inherent_candidates.clear();
409 self.extension_candidates.clear();
410 self.impl_dups.clear();
411 self.static_candidates.clear();
412 self.private_candidate = None;
415 ///////////////////////////////////////////////////////////////////////////
416 // CANDIDATE ASSEMBLY
418 fn push_candidate(&mut self,
419 candidate: Candidate<'tcx>,
422 let is_accessible = if let Some(name) = self.method_name {
423 let item = candidate.item;
424 let def_scope = self.tcx.adjust(name, item.container.id(), self.body_id).1;
425 item.vis.is_accessible_from(def_scope, self.tcx)
431 self.inherent_candidates.push(candidate);
433 self.extension_candidates.push(candidate);
435 } else if self.private_candidate.is_none() {
436 self.private_candidate = Some(candidate.item.def());
440 fn assemble_inherent_candidates(&mut self) {
441 let steps = self.steps.clone();
442 for step in steps.iter() {
443 self.assemble_probe(step.self_ty);
447 fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
448 debug!("assemble_probe: self_ty={:?}", self_ty);
449 let lang_items = self.tcx.lang_items();
452 ty::TyDynamic(ref data, ..) => {
453 if let Some(p) = data.principal() {
454 self.assemble_inherent_candidates_from_object(self_ty, p);
455 self.assemble_inherent_impl_candidates_for_type(p.def_id());
458 ty::TyAdt(def, _) => {
459 self.assemble_inherent_impl_candidates_for_type(def.did);
461 ty::TyForeign(did) => {
462 self.assemble_inherent_impl_candidates_for_type(did);
465 self.assemble_inherent_candidates_from_param(self_ty, p);
468 let lang_def_id = lang_items.char_impl();
469 self.assemble_inherent_impl_for_primitive(lang_def_id);
472 let lang_def_id = lang_items.str_impl();
473 self.assemble_inherent_impl_for_primitive(lang_def_id);
475 let lang_def_id = lang_items.str_alloc_impl();
476 self.assemble_inherent_impl_for_primitive(lang_def_id);
479 let lang_def_id = lang_items.slice_impl();
480 self.assemble_inherent_impl_for_primitive(lang_def_id);
482 let lang_def_id = lang_items.slice_u8_impl();
483 self.assemble_inherent_impl_for_primitive(lang_def_id);
485 let lang_def_id = lang_items.slice_alloc_impl();
486 self.assemble_inherent_impl_for_primitive(lang_def_id);
488 let lang_def_id = lang_items.slice_u8_alloc_impl();
489 self.assemble_inherent_impl_for_primitive(lang_def_id);
491 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
492 let lang_def_id = lang_items.const_ptr_impl();
493 self.assemble_inherent_impl_for_primitive(lang_def_id);
495 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
496 let lang_def_id = lang_items.mut_ptr_impl();
497 self.assemble_inherent_impl_for_primitive(lang_def_id);
499 ty::TyInt(ast::IntTy::I8) => {
500 let lang_def_id = lang_items.i8_impl();
501 self.assemble_inherent_impl_for_primitive(lang_def_id);
503 ty::TyInt(ast::IntTy::I16) => {
504 let lang_def_id = lang_items.i16_impl();
505 self.assemble_inherent_impl_for_primitive(lang_def_id);
507 ty::TyInt(ast::IntTy::I32) => {
508 let lang_def_id = lang_items.i32_impl();
509 self.assemble_inherent_impl_for_primitive(lang_def_id);
511 ty::TyInt(ast::IntTy::I64) => {
512 let lang_def_id = lang_items.i64_impl();
513 self.assemble_inherent_impl_for_primitive(lang_def_id);
515 ty::TyInt(ast::IntTy::I128) => {
516 let lang_def_id = lang_items.i128_impl();
517 self.assemble_inherent_impl_for_primitive(lang_def_id);
519 ty::TyInt(ast::IntTy::Isize) => {
520 let lang_def_id = lang_items.isize_impl();
521 self.assemble_inherent_impl_for_primitive(lang_def_id);
523 ty::TyUint(ast::UintTy::U8) => {
524 let lang_def_id = lang_items.u8_impl();
525 self.assemble_inherent_impl_for_primitive(lang_def_id);
527 ty::TyUint(ast::UintTy::U16) => {
528 let lang_def_id = lang_items.u16_impl();
529 self.assemble_inherent_impl_for_primitive(lang_def_id);
531 ty::TyUint(ast::UintTy::U32) => {
532 let lang_def_id = lang_items.u32_impl();
533 self.assemble_inherent_impl_for_primitive(lang_def_id);
535 ty::TyUint(ast::UintTy::U64) => {
536 let lang_def_id = lang_items.u64_impl();
537 self.assemble_inherent_impl_for_primitive(lang_def_id);
539 ty::TyUint(ast::UintTy::U128) => {
540 let lang_def_id = lang_items.u128_impl();
541 self.assemble_inherent_impl_for_primitive(lang_def_id);
543 ty::TyUint(ast::UintTy::Usize) => {
544 let lang_def_id = lang_items.usize_impl();
545 self.assemble_inherent_impl_for_primitive(lang_def_id);
547 ty::TyFloat(ast::FloatTy::F32) => {
548 let lang_def_id = lang_items.f32_impl();
549 self.assemble_inherent_impl_for_primitive(lang_def_id);
551 let lang_def_id = lang_items.f32_runtime_impl();
552 self.assemble_inherent_impl_for_primitive(lang_def_id);
554 ty::TyFloat(ast::FloatTy::F64) => {
555 let lang_def_id = lang_items.f64_impl();
556 self.assemble_inherent_impl_for_primitive(lang_def_id);
558 let lang_def_id = lang_items.f64_runtime_impl();
559 self.assemble_inherent_impl_for_primitive(lang_def_id);
565 fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
566 if let Some(impl_def_id) = lang_def_id {
567 self.assemble_inherent_impl_probe(impl_def_id);
571 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
572 let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
573 for &impl_def_id in impl_def_ids.iter() {
574 self.assemble_inherent_impl_probe(impl_def_id);
578 fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
579 if !self.impl_dups.insert(impl_def_id) {
580 return; // already visited
583 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
585 for item in self.impl_or_trait_item(impl_def_id) {
586 if !self.has_applicable_self(&item) {
587 // No receiver declared. Not a candidate.
588 self.record_static_candidate(ImplSource(impl_def_id));
592 let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
593 let impl_ty = impl_ty.subst(self.tcx, impl_substs);
595 // Determine the receiver type that the method itself expects.
596 let xform_tys = self.xform_self_ty(&item, impl_ty, impl_substs);
598 // We can't use normalize_associated_types_in as it will pollute the
599 // fcx's fulfillment context after this probe is over.
600 let cause = traits::ObligationCause::misc(self.span, self.body_id);
601 let selcx = &mut traits::SelectionContext::new(self.fcx);
602 let traits::Normalized { value: (xform_self_ty, xform_ret_ty), obligations } =
603 traits::normalize(selcx, self.param_env, cause, &xform_tys);
604 debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}/{:?}",
605 xform_self_ty, xform_ret_ty);
607 self.push_candidate(Candidate {
608 xform_self_ty, xform_ret_ty, item,
609 kind: InherentImplCandidate(impl_substs, obligations),
615 fn assemble_inherent_candidates_from_object(&mut self,
617 principal: ty::PolyExistentialTraitRef<'tcx>) {
618 debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
621 // It is illegal to invoke a method on a trait instance that
622 // refers to the `Self` type. An error will be reported by
623 // `enforce_object_limitations()` if the method refers to the
624 // `Self` type anywhere other than the receiver. Here, we use
625 // a substitution that replaces `Self` with the object type
626 // itself. Hence, a `&self` method will wind up with an
627 // argument type like `&Trait`.
628 let trait_ref = principal.with_self_ty(self.tcx, self_ty);
629 self.elaborate_bounds(&[trait_ref], |this, new_trait_ref, item| {
630 let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
632 let (xform_self_ty, xform_ret_ty) =
633 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
634 this.push_candidate(Candidate {
635 xform_self_ty, xform_ret_ty, item,
636 kind: ObjectCandidate,
642 fn assemble_inherent_candidates_from_param(&mut self,
644 param_ty: ty::ParamTy) {
645 // FIXME -- Do we want to commit to this behavior for param bounds?
647 let bounds: Vec<_> = self.param_env
650 .filter_map(|predicate| {
652 ty::Predicate::Trait(ref trait_predicate) => {
653 match trait_predicate.skip_binder().trait_ref.self_ty().sty {
654 ty::TyParam(ref p) if *p == param_ty => {
655 Some(trait_predicate.to_poly_trait_ref())
660 ty::Predicate::Subtype(..) |
661 ty::Predicate::Projection(..) |
662 ty::Predicate::RegionOutlives(..) |
663 ty::Predicate::WellFormed(..) |
664 ty::Predicate::ObjectSafe(..) |
665 ty::Predicate::ClosureKind(..) |
666 ty::Predicate::TypeOutlives(..) |
667 ty::Predicate::ConstEvaluatable(..) => None,
672 self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
673 let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
675 let (xform_self_ty, xform_ret_ty) =
676 this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
678 // Because this trait derives from a where-clause, it
679 // should not contain any inference variables or other
680 // artifacts. This means it is safe to put into the
681 // `WhereClauseCandidate` and (eventually) into the
682 // `WhereClausePick`.
683 assert!(!trait_ref.substs.needs_infer());
685 this.push_candidate(Candidate {
686 xform_self_ty, xform_ret_ty, item,
687 kind: WhereClauseCandidate(poly_trait_ref),
693 // Do a search through a list of bounds, using a callback to actually
694 // create the candidates.
695 fn elaborate_bounds<F>(&mut self, bounds: &[ty::PolyTraitRef<'tcx>], mut mk_cand: F)
696 where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>,
697 ty::PolyTraitRef<'tcx>,
700 debug!("elaborate_bounds(bounds={:?})", bounds);
703 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
704 for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
705 if !self.has_applicable_self(&item) {
706 self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
708 mk_cand(self, bound_trait_ref, item);
714 fn assemble_extension_candidates_for_traits_in_scope(&mut self,
715 expr_id: ast::NodeId)
716 -> Result<(), MethodError<'tcx>> {
717 if expr_id == ast::DUMMY_NODE_ID {
720 let mut duplicates = FxHashSet();
721 let expr_hir_id = self.tcx.hir.node_to_hir_id(expr_id);
722 let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
723 if let Some(applicable_traits) = opt_applicable_traits {
724 for trait_candidate in applicable_traits.iter() {
725 let trait_did = trait_candidate.def_id;
726 if duplicates.insert(trait_did) {
727 let import_id = trait_candidate.import_id;
728 let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
736 fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
737 let mut duplicates = FxHashSet();
738 for trait_info in suggest::all_traits(self.tcx) {
739 if duplicates.insert(trait_info.def_id) {
740 self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
746 pub fn matches_return_type(&self,
747 method: &ty::AssociatedItem,
748 self_ty: Option<Ty<'tcx>>,
749 expected: Ty<'tcx>) -> bool {
751 Def::Method(def_id) => {
752 let fty = self.tcx.fn_sig(def_id);
754 let substs = self.fresh_substs_for_item(self.span, method.def_id);
755 let fty = fty.subst(self.tcx, substs);
756 let (fty, _) = self.replace_late_bound_regions_with_fresh_var(
757 self.span, infer::FnCall, &fty);
759 if let Some(self_ty) = self_ty {
760 if let Err(_) = self.at(&ObligationCause::dummy(), self.param_env)
761 .sup(fty.inputs()[0], self_ty)
766 self.can_sub(self.param_env, fty.output(), expected).is_ok()
773 fn assemble_extension_candidates_for_trait(&mut self,
774 import_id: Option<ast::NodeId>,
776 -> Result<(), MethodError<'tcx>> {
777 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
779 let trait_substs = self.fresh_item_substs(trait_def_id);
780 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
782 for item in self.impl_or_trait_item(trait_def_id) {
783 // Check whether `trait_def_id` defines a method with suitable name:
784 if !self.has_applicable_self(&item) {
785 debug!("method has inapplicable self");
786 self.record_static_candidate(TraitSource(trait_def_id));
790 let (xform_self_ty, xform_ret_ty) =
791 self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
792 self.push_candidate(Candidate {
793 xform_self_ty, xform_ret_ty, item, import_id,
794 kind: TraitCandidate(trait_ref),
800 fn candidate_method_names(&self) -> Vec<ast::Name> {
801 let mut set = FxHashSet();
802 let mut names: Vec<_> = self.inherent_candidates
804 .chain(&self.extension_candidates)
805 .filter(|candidate| {
806 if let Some(return_ty) = self.return_type {
807 self.matches_return_type(&candidate.item, None, return_ty)
812 .map(|candidate| candidate.item.name)
813 .filter(|&name| set.insert(name))
816 // sort them by the name so we have a stable result
817 names.sort_by_cached_key(|n| n.as_str());
821 ///////////////////////////////////////////////////////////////////////////
824 fn pick(mut self) -> PickResult<'tcx> {
825 assert!(self.method_name.is_some());
827 if let Some(r) = self.pick_core() {
831 let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
832 let private_candidate = mem::replace(&mut self.private_candidate, None);
833 let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
835 // things failed, so lets look at all traits, for diagnostic purposes now:
838 let span = self.span;
841 self.assemble_extension_candidates_for_all_traits()?;
843 let out_of_scope_traits = match self.pick_core() {
844 Some(Ok(p)) => vec![p.item.container.id()],
845 //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
846 Some(Err(MethodError::Ambiguity(v))) => {
850 TraitSource(id) => id,
851 ImplSource(impl_id) => {
852 match tcx.trait_id_of_impl(impl_id) {
856 "found inherent method when looking at traits")
864 Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
865 assert!(others.is_empty());
871 if let Some(def) = private_candidate {
872 return Err(MethodError::PrivateMatch(def, out_of_scope_traits));
874 let lev_candidate = self.probe_for_lev_candidate()?;
876 Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
877 unsatisfied_predicates,
883 fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
884 let steps = self.steps.clone();
886 // find the first step that works
890 debug!("pick_core: step={:?}", step);
891 // skip types that are from a type error or that would require dereferencing
893 !step.self_ty.references_error() && !step.from_unsafe_deref
895 self.pick_by_value_method(step).or_else(|| {
896 self.pick_autorefd_method(step, hir::MutImmutable).or_else(|| {
897 self.pick_autorefd_method(step, hir::MutMutable)
902 fn pick_by_value_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
903 //! For each type `T` in the step list, this attempts to find a
904 //! method where the (transformed) self type is exactly `T`. We
905 //! do however do one transformation on the adjustment: if we
906 //! are passing a region pointer in, we will potentially
907 //! *reborrow* it to a shorter lifetime. This allows us to
908 //! transparently pass `&mut` pointers, in particular, without
909 //! consuming them for their entire lifetime.
915 self.pick_method(step.self_ty).map(|r| {
917 pick.autoderefs = step.autoderefs;
919 // Insert a `&*` or `&mut *` if this is a reference type:
920 if let ty::TyRef(_, mt) = step.self_ty.sty {
921 pick.autoderefs += 1;
922 pick.autoref = Some(mt.mutbl);
930 fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>, mutbl: hir::Mutability)
931 -> Option<PickResult<'tcx>> {
934 // In general, during probing we erase regions. See
935 // `impl_self_ty()` for an explanation.
936 let region = tcx.types.re_erased;
938 let autoref_ty = tcx.mk_ref(region,
940 ty: step.self_ty, mutbl
942 self.pick_method(autoref_ty).map(|r| {
944 pick.autoderefs = step.autoderefs;
945 pick.autoref = Some(mutbl);
946 pick.unsize = if step.unsize {
956 fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
957 debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
959 let mut possibly_unsatisfied_predicates = Vec::new();
960 let mut unstable_candidates = Vec::new();
962 for (kind, candidates) in &[
963 ("inherent", &self.inherent_candidates),
964 ("extension", &self.extension_candidates),
966 debug!("searching {} candidates", kind);
967 let res = self.consider_candidates(
970 &mut possibly_unsatisfied_predicates,
971 Some(&mut unstable_candidates),
973 if let Some(pick) = res {
974 if !self.is_suggestion.0 && !unstable_candidates.is_empty() {
975 if let Ok(p) = &pick {
976 // Emit a lint if there are unstable candidates alongside the stable ones.
978 // We suppress warning if we're picking the method only because it is a
980 self.emit_unstable_name_collision_hint(p, &unstable_candidates);
987 debug!("searching unstable candidates");
988 let res = self.consider_candidates(
990 unstable_candidates.into_iter().map(|(c, _)| c),
991 &mut possibly_unsatisfied_predicates,
995 self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1000 fn consider_candidates<'b, ProbesIter>(
1004 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>,
1005 unstable_candidates: Option<&mut Vec<(&'b Candidate<'tcx>, Symbol)>>,
1006 ) -> Option<PickResult<'tcx>>
1008 ProbesIter: Iterator<Item = &'b Candidate<'tcx>> + Clone,
1010 let mut applicable_candidates: Vec<_> = probes.clone()
1012 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1014 .filter(|&(_, status)| status != ProbeResult::NoMatch)
1017 debug!("applicable_candidates: {:?}", applicable_candidates);
1019 if applicable_candidates.len() > 1 {
1020 if let Some(pick) = self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1021 return Some(Ok(pick));
1025 if let Some(uc) = unstable_candidates {
1026 applicable_candidates.retain(|&(p, _)| {
1027 if let stability::EvalResult::Deny { feature, .. } =
1028 self.tcx.eval_stability(p.item.def_id, None, self.span)
1030 uc.push((p, feature));
1037 if applicable_candidates.len() > 1 {
1038 let sources = probes
1039 .map(|p| self.candidate_source(p, self_ty))
1041 return Some(Err(MethodError::Ambiguity(sources)));
1044 applicable_candidates.pop().map(|(probe, status)| {
1045 if status == ProbeResult::Match {
1046 Ok(probe.to_unadjusted_pick())
1048 Err(MethodError::BadReturnType)
1053 fn emit_unstable_name_collision_hint(
1056 unstable_candidates: &[(&Candidate<'tcx>, Symbol)],
1058 let mut diag = self.tcx.struct_span_lint_node(
1059 lint::builtin::UNSTABLE_NAME_COLLISION,
1062 "a method with this name may be added to the standard library in the future",
1065 // FIXME: This should be a `span_suggestion` instead of `help`. However `self.span` only
1066 // highlights the method name, so we can't use it. Also consider reusing the code from
1067 // `report_method_error()`.
1069 "call with fully qualified syntax `{}(...)` to keep using the current method",
1070 self.tcx.item_path_str(stable_pick.item.def_id),
1073 if ::rustc::session::config::nightly_options::is_nightly_build() {
1074 for (candidate, feature) in unstable_candidates {
1076 "add #![feature({})] to the crate attributes to enable `{}`",
1078 self.tcx.item_path_str(candidate.item.def_id),
1086 fn select_trait_candidate(&self, trait_ref: ty::TraitRef<'tcx>)
1087 -> traits::SelectionResult<'tcx, traits::Selection<'tcx>>
1089 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1091 trait_ref.to_poly_trait_ref().to_poly_trait_predicate();
1092 let obligation = traits::Obligation::new(cause, self.param_env, predicate);
1093 traits::SelectionContext::new(self).select(&obligation)
1096 fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>)
1099 match candidate.kind {
1100 InherentImplCandidate(..) => ImplSource(candidate.item.container.id()),
1102 WhereClauseCandidate(_) => TraitSource(candidate.item.container.id()),
1103 TraitCandidate(trait_ref) => self.probe(|_| {
1104 let _ = self.at(&ObligationCause::dummy(), self.param_env)
1105 .sup(candidate.xform_self_ty, self_ty);
1106 match self.select_trait_candidate(trait_ref) {
1107 Ok(Some(traits::Vtable::VtableImpl(ref impl_data))) => {
1108 // If only a single impl matches, make the error message point
1110 ImplSource(impl_data.impl_def_id)
1113 TraitSource(candidate.item.container.id())
1120 fn consider_probe(&self,
1122 probe: &Candidate<'tcx>,
1123 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1125 debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1128 // First check that the self type can be related.
1129 let sub_obligations = match self.at(&ObligationCause::dummy(), self.param_env)
1130 .sup(probe.xform_self_ty, self_ty) {
1131 Ok(InferOk { obligations, value: () }) => obligations,
1133 debug!("--> cannot relate self-types");
1134 return ProbeResult::NoMatch;
1138 let mut result = ProbeResult::Match;
1139 let selcx = &mut traits::SelectionContext::new(self);
1140 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1142 // If so, impls may carry other conditions (e.g., where
1143 // clauses) that must be considered. Make sure that those
1144 // match as well (or at least may match, sometimes we
1145 // don't have enough information to fully evaluate).
1146 let candidate_obligations : Vec<_> = match probe.kind {
1147 InherentImplCandidate(ref substs, ref ref_obligations) => {
1148 // Check whether the impl imposes obligations we have to worry about.
1149 let impl_def_id = probe.item.container.id();
1150 let impl_bounds = self.tcx.predicates_of(impl_def_id);
1151 let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1152 let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1153 traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
1155 // Convert the bounds into obligations.
1156 let impl_obligations = traits::predicates_for_generics(
1157 cause.clone(), self.param_env, &impl_bounds);
1159 debug!("impl_obligations={:?}", impl_obligations);
1160 impl_obligations.into_iter()
1161 .chain(norm_obligations.into_iter())
1162 .chain(ref_obligations.iter().cloned())
1167 WhereClauseCandidate(..) => {
1168 // These have no additional conditions to check.
1172 TraitCandidate(trait_ref) => {
1173 let predicate = trait_ref.to_predicate();
1175 traits::Obligation::new(cause.clone(), self.param_env, predicate);
1176 if !self.predicate_may_hold(&obligation) {
1177 if self.probe(|_| self.select_trait_candidate(trait_ref).is_err()) {
1178 // This candidate's primary obligation doesn't even
1179 // select - don't bother registering anything in
1180 // `potentially_unsatisfied_predicates`.
1181 return ProbeResult::NoMatch;
1183 // Some nested subobligation of this predicate
1186 // FIXME: try to find the exact nested subobligation
1187 // and point at it rather than reporting the entire
1189 result = ProbeResult::NoMatch;
1190 let trait_ref = self.resolve_type_vars_if_possible(&trait_ref);
1191 possibly_unsatisfied_predicates.push(trait_ref);
1198 debug!("consider_probe - candidate_obligations={:?} sub_obligations={:?}",
1199 candidate_obligations, sub_obligations);
1201 // Evaluate those obligations to see if they might possibly hold.
1202 for o in candidate_obligations.into_iter().chain(sub_obligations) {
1203 let o = self.resolve_type_vars_if_possible(&o);
1204 if !self.predicate_may_hold(&o) {
1205 result = ProbeResult::NoMatch;
1206 if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1207 possibly_unsatisfied_predicates.push(pred.skip_binder().trait_ref);
1212 if let ProbeResult::Match = result {
1213 if let (Some(return_ty), Some(xform_ret_ty)) =
1214 (self.return_type, probe.xform_ret_ty)
1216 let xform_ret_ty = self.resolve_type_vars_if_possible(&xform_ret_ty);
1217 debug!("comparing return_ty {:?} with xform ret ty {:?}",
1219 probe.xform_ret_ty);
1220 if self.at(&ObligationCause::dummy(), self.param_env)
1221 .sup(return_ty, xform_ret_ty)
1224 return ProbeResult::BadReturnType;
1233 /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1234 /// same trait, but we don't know which impl to use. In this case, since in all cases the
1235 /// external interface of the method can be determined from the trait, it's ok not to decide.
1236 /// We can basically just collapse all of the probes for various impls into one where-clause
1237 /// probe. This will result in a pending obligation so when more type-info is available we can
1238 /// make the final decision.
1240 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1243 /// trait Foo { ... }
1244 /// impl Foo for Vec<int> { ... }
1245 /// impl Foo for Vec<usize> { ... }
1248 /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1249 /// use, so it's ok to just commit to "using the method from the trait Foo".
1250 fn collapse_candidates_to_trait_pick(&self, probes: &[(&Candidate<'tcx>, ProbeResult)])
1251 -> Option<Pick<'tcx>>
1253 // Do all probes correspond to the same trait?
1254 let container = probes[0].0.item.container;
1256 ty::TraitContainer(_) => {}
1257 ty::ImplContainer(_) => return None,
1259 if probes[1..].iter().any(|&(p, _)| p.item.container != container) {
1263 // FIXME: check the return type here somehow.
1264 // If so, just use this trait and call it a day.
1266 item: probes[0].0.item.clone(),
1268 import_id: probes[0].0.import_id,
1275 /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
1276 /// candidate method where the method name may have been misspelt. Similarly to other
1277 /// Levenshtein based suggestions, we provide at most one such suggestion.
1278 fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssociatedItem>, MethodError<'tcx>> {
1279 debug!("Probing for method names similar to {:?}",
1282 let steps = self.steps.clone();
1284 let mut pcx = ProbeContext::new(self.fcx, self.span, self.mode, self.method_name,
1285 self.return_type, steps, IsSuggestion(true));
1286 pcx.allow_similar_names = true;
1287 pcx.assemble_inherent_candidates();
1288 pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)?;
1290 let method_names = pcx.candidate_method_names();
1291 pcx.allow_similar_names = false;
1292 let applicable_close_candidates: Vec<ty::AssociatedItem> = method_names
1294 .filter_map(|&method_name| {
1296 pcx.method_name = Some(method_name);
1297 pcx.assemble_inherent_candidates();
1298 pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)
1299 .ok().map_or(None, |_| {
1301 .and_then(|pick| pick.ok())
1302 .and_then(|pick| Some(pick.item))
1307 if applicable_close_candidates.is_empty() {
1311 let names = applicable_close_candidates.iter().map(|cand| &cand.name);
1312 find_best_match_for_name(names,
1313 &self.method_name.unwrap().as_str(),
1316 Ok(applicable_close_candidates
1318 .find(|method| method.name == best_name))
1323 ///////////////////////////////////////////////////////////////////////////
1325 fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1326 // "Fast track" -- check for usage of sugar when in method call
1329 // In Path mode (i.e., resolving a value like `T::next`), consider any
1330 // associated value (i.e., methods, constants) but not types.
1332 Mode::MethodCall => item.method_has_self_argument,
1333 Mode::Path => match item.kind {
1334 ty::AssociatedKind::Type => false,
1335 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1338 // FIXME -- check for types that deref to `Self`,
1339 // like `Rc<Self>` and so on.
1341 // Note also that the current code will break if this type
1342 // includes any of the type parameters defined on the method
1343 // -- but this could be overcome.
1346 fn record_static_candidate(&mut self, source: CandidateSource) {
1347 self.static_candidates.push(source);
1350 fn xform_self_ty(&self,
1351 item: &ty::AssociatedItem,
1353 substs: &Substs<'tcx>)
1354 -> (Ty<'tcx>, Option<Ty<'tcx>>) {
1355 if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1356 let sig = self.xform_method_sig(item.def_id, substs);
1357 (sig.inputs()[0], Some(sig.output()))
1363 fn xform_method_sig(&self,
1365 substs: &Substs<'tcx>)
1368 let fn_sig = self.tcx.fn_sig(method);
1369 debug!("xform_self_ty(fn_sig={:?}, substs={:?})",
1373 assert!(!substs.has_escaping_regions());
1375 // It is possible for type parameters or early-bound lifetimes
1376 // to appear in the signature of `self`. The substitutions we
1377 // are given do not include type/lifetime parameters for the
1378 // method yet. So create fresh variables here for those too,
1379 // if there are any.
1380 let generics = self.tcx.generics_of(method);
1381 assert_eq!(substs.types().count(), generics.parent_types as usize);
1382 assert_eq!(substs.regions().count(), generics.parent_regions as usize);
1384 // Erase any late-bound regions from the method and substitute
1385 // in the values from the substitution.
1386 let xform_fn_sig = self.erase_late_bound_regions(&fn_sig);
1388 if generics.types.is_empty() && generics.regions.is_empty() {
1389 xform_fn_sig.subst(self.tcx, substs)
1391 let substs = Substs::for_item(self.tcx, method, |def, _| {
1392 let i = def.index as usize;
1393 if i < substs.len() {
1396 // In general, during probe we erase regions. See
1397 // `impl_self_ty()` for an explanation.
1398 self.tcx.types.re_erased
1400 }, |def, _cur_substs| {
1401 let i = def.index as usize;
1402 if i < substs.len() {
1405 self.type_var_for_def(self.span, def)
1408 xform_fn_sig.subst(self.tcx, substs)
1412 /// Get the type of an impl and generate substitutions with placeholders.
1413 fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
1414 (self.tcx.type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1417 fn fresh_item_substs(&self, def_id: DefId) -> &'tcx Substs<'tcx> {
1418 Substs::for_item(self.tcx,
1420 |_, _| self.tcx.types.re_erased,
1421 |_, _| self.next_ty_var(
1422 TypeVariableOrigin::SubstitutionPlaceholder(
1423 self.tcx.def_span(def_id))))
1426 /// Replace late-bound-regions bound by `value` with `'static` using
1427 /// `ty::erase_late_bound_regions`.
1429 /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1430 /// method matching. It is reasonable during the probe phase because we don't consider region
1431 /// relationships at all. Therefore, we can just replace all the region variables with 'static
1432 /// rather than creating fresh region variables. This is nice for two reasons:
1434 /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1435 /// particular method call, it winds up creating fewer types overall, which helps for memory
1436 /// usage. (Admittedly, this is a rather small effect, though measureable.)
1438 /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1439 /// late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1440 /// regions with actual region variables as is proper, we'd have to ensure that the same
1441 /// region got replaced with the same variable, which requires a bit more coordination
1442 /// and/or tracking the substitution and
1444 fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1445 where T: TypeFoldable<'tcx>
1447 self.tcx.erase_late_bound_regions(value)
1450 /// Find the method with the appropriate name (or return type, as the case may be). If
1451 /// `allow_similar_names` is set, find methods with close-matching names.
1452 fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1453 if let Some(name) = self.method_name {
1454 if self.allow_similar_names {
1455 let max_dist = max(name.as_str().len(), 3) / 3;
1456 self.tcx.associated_items(def_id)
1458 let dist = lev_distance(&*name.as_str(), &x.name.as_str());
1459 Namespace::from(x.kind) == Namespace::Value && dist > 0
1465 .associated_item(def_id, name, Namespace::Value)
1466 .map_or(Vec::new(), |x| vec![x])
1469 self.tcx.associated_items(def_id).collect()
1474 impl<'tcx> Candidate<'tcx> {
1475 fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1477 item: self.item.clone(),
1478 kind: match self.kind {
1479 InherentImplCandidate(..) => InherentImplPick,
1480 ObjectCandidate => ObjectPick,
1481 TraitCandidate(_) => TraitPick,
1482 WhereClauseCandidate(ref trait_ref) => {
1483 // Only trait derived from where-clauses should
1484 // appear here, so they should not contain any
1485 // inference variables or other artifacts. This
1486 // means they are safe to put into the
1487 // `WhereClausePick`.
1488 assert!(!trait_ref.skip_binder().substs.needs_infer());
1490 WhereClausePick(trait_ref.clone())
1493 import_id: self.import_id,