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::ty::GenericParamDefKind;
24 use rustc::infer::type_variable::TypeVariableOrigin;
25 use rustc::util::nodemap::FxHashSet;
26 use rustc::infer::{self, InferOk};
27 use rustc::middle::stability;
29 use syntax::util::lev_distance::{lev_distance, find_best_match_for_name};
30 use syntax_pos::{Span, symbol::Symbol};
38 use self::CandidateKind::*;
39 pub use self::PickKind::*;
41 /// Boolean flag used to indicate if this search is for a suggestion
42 /// or not. If true, we can allow ambiguity and so forth.
43 #[derive(Clone, Copy)]
44 pub struct IsSuggestion(pub bool);
46 struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
47 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
50 method_name: Option<ast::Name>,
51 return_type: Option<Ty<'tcx>>,
52 steps: Rc<Vec<CandidateStep<'tcx>>>,
53 inherent_candidates: Vec<Candidate<'tcx>>,
54 extension_candidates: Vec<Candidate<'tcx>>,
55 impl_dups: FxHashSet<DefId>,
57 /// Collects near misses when the candidate functions are missing a `self` keyword and is only
58 /// used for error reporting
59 static_candidates: Vec<CandidateSource>,
61 /// When probing for names, include names that are close to the
62 /// requested name (by Levensthein distance)
63 allow_similar_names: bool,
65 /// Some(candidate) if there is a private candidate
66 private_candidate: Option<Def>,
68 /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
69 /// for error reporting
70 unsatisfied_predicates: Vec<TraitRef<'tcx>>,
72 is_suggestion: IsSuggestion,
75 impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
76 type Target = FnCtxt<'a, 'gcx, 'tcx>;
77 fn deref(&self) -> &Self::Target {
83 struct CandidateStep<'tcx> {
86 // true if the type results from a dereference of a raw pointer.
87 // when assembling candidates, we include these steps, but not when
88 // picking methods. This so that if we have `foo: *const Foo` and `Foo` has methods
89 // `fn by_raw_ptr(self: *const Self)` and `fn by_ref(&self)`, then
90 // `foo.by_raw_ptr()` will work and `foo.by_ref()` won't.
91 from_unsafe_deref: bool,
96 struct Candidate<'tcx> {
97 xform_self_ty: Ty<'tcx>,
98 xform_ret_ty: Option<Ty<'tcx>>,
99 item: ty::AssociatedItem,
100 kind: CandidateKind<'tcx>,
101 import_id: Option<ast::NodeId>,
105 enum CandidateKind<'tcx> {
106 InherentImplCandidate(&'tcx Substs<'tcx>,
107 // Normalize obligations
108 Vec<traits::PredicateObligation<'tcx>>),
110 TraitCandidate(ty::TraitRef<'tcx>),
111 WhereClauseCandidate(// Trait
112 ty::PolyTraitRef<'tcx>),
115 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
122 #[derive(Debug, PartialEq, Eq, Clone)]
123 pub struct Pick<'tcx> {
124 pub item: ty::AssociatedItem,
125 pub kind: PickKind<'tcx>,
126 pub import_id: Option<ast::NodeId>,
128 // Indicates that the source expression should be autoderef'd N times
130 // A = expr | *expr | **expr | ...
131 pub autoderefs: usize,
133 // Indicates that an autoref is applied after the optional autoderefs
135 // B = A | &A | &mut A
136 pub autoref: Option<hir::Mutability>,
138 // Indicates that the source expression should be "unsized" to a
139 // target type. This should probably eventually go away in favor
140 // of just coercing method receivers.
143 pub unsize: Option<Ty<'tcx>>,
146 #[derive(Clone, Debug, PartialEq, Eq)]
147 pub enum PickKind<'tcx> {
151 WhereClausePick(// Trait
152 ty::PolyTraitRef<'tcx>),
155 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
157 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
159 // An expression of the form `receiver.method_name(...)`.
160 // Autoderefs are performed on `receiver`, lookup is done based on the
161 // `self` argument of the method, and static methods aren't considered.
163 // An expression of the form `Type::item` or `<T>::item`.
164 // No autoderefs are performed, lookup is done based on the type each
165 // implementation is for, and static methods are included.
169 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
170 pub enum ProbeScope {
171 // Assemble candidates coming only from traits in scope.
174 // Assemble candidates coming from all traits.
178 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
179 /// This is used to offer suggestions to users. It returns methods
180 /// that could have been called which have the desired return
181 /// type. Some effort is made to rule out methods that, if called,
182 /// would result in an error (basically, the same criteria we
183 /// would use to decide if a method is a plausible fit for
184 /// ambiguity purposes).
185 pub fn probe_for_return_type(&self,
188 return_type: Ty<'tcx>,
190 scope_expr_id: ast::NodeId)
191 -> Vec<ty::AssociatedItem> {
192 debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
197 self.probe_op(span, mode, None, Some(return_type), IsSuggestion(true),
198 self_ty, scope_expr_id, ProbeScope::AllTraits,
199 |probe_cx| Ok(probe_cx.candidate_method_names()))
203 .flat_map(|&method_name| {
205 span, mode, Some(method_name), Some(return_type),
206 IsSuggestion(true), self_ty, scope_expr_id,
207 ProbeScope::AllTraits, |probe_cx| probe_cx.pick()
208 ).ok().map(|pick| pick.item)
213 pub fn probe_for_name(&self,
216 item_name: ast::Name,
217 is_suggestion: IsSuggestion,
219 scope_expr_id: ast::NodeId,
221 -> PickResult<'tcx> {
222 debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
234 |probe_cx| probe_cx.pick())
237 fn probe_op<OP,R>(&'a self,
240 method_name: Option<ast::Name>,
241 return_type: Option<Ty<'tcx>>,
242 is_suggestion: IsSuggestion,
244 scope_expr_id: ast::NodeId,
247 -> Result<R, MethodError<'tcx>>
248 where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
250 // FIXME(#18741) -- right now, creating the steps involves evaluating the
251 // `*` operator, which registers obligations that then escape into
252 // the global fulfillment context and thus has global
253 // side-effects. This is a bit of a pain to refactor. So just let
254 // it ride, although it's really not great, and in fact could I
255 // think cause spurious errors. Really though this part should
256 // take place in the `self.probe` below.
257 let steps = if mode == Mode::MethodCall {
258 match self.create_steps(span, scope_expr_id, self_ty, is_suggestion) {
259 Some(steps) => steps,
261 return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
272 from_unsafe_deref: false,
277 debug!("ProbeContext: steps for self_ty={:?} are {:?}",
281 // this creates one big transaction so that all type variables etc
282 // that we create during the probe process are removed later
284 let mut probe_cx = ProbeContext::new(
285 self, span, mode, method_name, return_type, Rc::new(steps), is_suggestion,
288 probe_cx.assemble_inherent_candidates();
290 ProbeScope::TraitsInScope =>
291 probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?,
292 ProbeScope::AllTraits =>
293 probe_cx.assemble_extension_candidates_for_all_traits()?,
299 fn create_steps(&self,
301 scope_expr_id: ast::NodeId,
303 is_suggestion: IsSuggestion)
304 -> Option<Vec<CandidateStep<'tcx>>> {
305 // FIXME: we don't need to create the entire steps in one pass
307 let mut autoderef = self.autoderef(span, self_ty).include_raw_pointers();
308 let mut reached_raw_pointer = false;
309 let mut steps: Vec<_> = autoderef.by_ref()
311 let step = CandidateStep {
314 from_unsafe_deref: reached_raw_pointer,
317 if let ty::TyRawPtr(_) = ty.sty {
318 // all the subsequent steps will be from_unsafe_deref
319 reached_raw_pointer = true;
325 let final_ty = autoderef.maybe_ambiguous_final_ty();
327 ty::TyInfer(ty::TyVar(_)) => {
328 // Ended in an inference variable. If we are doing
329 // a real method lookup, this is a hard error because it's
330 // possible that there will be multiple applicable methods.
331 if !is_suggestion.0 {
332 if reached_raw_pointer
333 && !self.tcx.features().arbitrary_self_types {
334 // this case used to be allowed by the compiler,
335 // so we do a future-compat lint here for the 2015 edition
336 // (see https://github.com/rust-lang/rust/issues/46906)
337 if self.tcx.sess.rust_2018() {
338 span_err!(self.tcx.sess, span, E0699,
339 "the type of this value must be known \
340 to call a method on a raw pointer on it");
343 lint::builtin::TYVAR_BEHIND_RAW_POINTER,
346 &format!("type annotations needed"));
349 let t = self.structurally_resolved_type(span, final_ty);
350 assert_eq!(t, self.tcx.types.err);
354 // If we're just looking for suggestions,
355 // though, ambiguity is no big thing, we can
359 ty::TyArray(elem_ty, _) => {
360 let dereferences = steps.len() - 1;
362 steps.push(CandidateStep {
363 self_ty: self.tcx.mk_slice(elem_ty),
364 autoderefs: dereferences,
365 // this could be from an unsafe deref if we had
366 // a *mut/const [T; N]
367 from_unsafe_deref: reached_raw_pointer,
371 ty::TyError => return None,
375 debug!("create_steps: steps={:?}", steps);
381 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
382 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
385 method_name: Option<ast::Name>,
386 return_type: Option<Ty<'tcx>>,
387 steps: Rc<Vec<CandidateStep<'tcx>>>,
388 is_suggestion: IsSuggestion)
389 -> ProbeContext<'a, 'gcx, 'tcx> {
396 inherent_candidates: Vec::new(),
397 extension_candidates: Vec::new(),
398 impl_dups: FxHashSet(),
400 static_candidates: Vec::new(),
401 allow_similar_names: false,
402 private_candidate: None,
403 unsatisfied_predicates: Vec::new(),
408 fn reset(&mut self) {
409 self.inherent_candidates.clear();
410 self.extension_candidates.clear();
411 self.impl_dups.clear();
412 self.static_candidates.clear();
413 self.private_candidate = None;
416 ///////////////////////////////////////////////////////////////////////////
417 // CANDIDATE ASSEMBLY
419 fn push_candidate(&mut self,
420 candidate: Candidate<'tcx>,
423 let is_accessible = if let Some(name) = self.method_name {
424 let item = candidate.item;
426 self.tcx.adjust_ident(name.to_ident(), item.container.id(), self.body_id).1;
427 item.vis.is_accessible_from(def_scope, self.tcx)
433 self.inherent_candidates.push(candidate);
435 self.extension_candidates.push(candidate);
437 } else if self.private_candidate.is_none() {
438 self.private_candidate = Some(candidate.item.def());
442 fn assemble_inherent_candidates(&mut self) {
443 let steps = self.steps.clone();
444 for step in steps.iter() {
445 self.assemble_probe(step.self_ty);
449 fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
450 debug!("assemble_probe: self_ty={:?}", self_ty);
451 let lang_items = self.tcx.lang_items();
454 ty::TyDynamic(ref data, ..) => {
455 if let Some(p) = data.principal() {
456 self.assemble_inherent_candidates_from_object(self_ty, p);
457 self.assemble_inherent_impl_candidates_for_type(p.def_id());
460 ty::TyAdt(def, _) => {
461 self.assemble_inherent_impl_candidates_for_type(def.did);
463 ty::TyForeign(did) => {
464 self.assemble_inherent_impl_candidates_for_type(did);
467 self.assemble_inherent_candidates_from_param(self_ty, p);
470 let lang_def_id = lang_items.char_impl();
471 self.assemble_inherent_impl_for_primitive(lang_def_id);
474 let lang_def_id = lang_items.str_impl();
475 self.assemble_inherent_impl_for_primitive(lang_def_id);
477 let lang_def_id = lang_items.str_alloc_impl();
478 self.assemble_inherent_impl_for_primitive(lang_def_id);
481 let lang_def_id = lang_items.slice_impl();
482 self.assemble_inherent_impl_for_primitive(lang_def_id);
484 let lang_def_id = lang_items.slice_u8_impl();
485 self.assemble_inherent_impl_for_primitive(lang_def_id);
487 let lang_def_id = lang_items.slice_alloc_impl();
488 self.assemble_inherent_impl_for_primitive(lang_def_id);
490 let lang_def_id = lang_items.slice_u8_alloc_impl();
491 self.assemble_inherent_impl_for_primitive(lang_def_id);
493 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
494 let lang_def_id = lang_items.const_ptr_impl();
495 self.assemble_inherent_impl_for_primitive(lang_def_id);
497 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
498 let lang_def_id = lang_items.mut_ptr_impl();
499 self.assemble_inherent_impl_for_primitive(lang_def_id);
501 ty::TyInt(ast::IntTy::I8) => {
502 let lang_def_id = lang_items.i8_impl();
503 self.assemble_inherent_impl_for_primitive(lang_def_id);
505 ty::TyInt(ast::IntTy::I16) => {
506 let lang_def_id = lang_items.i16_impl();
507 self.assemble_inherent_impl_for_primitive(lang_def_id);
509 ty::TyInt(ast::IntTy::I32) => {
510 let lang_def_id = lang_items.i32_impl();
511 self.assemble_inherent_impl_for_primitive(lang_def_id);
513 ty::TyInt(ast::IntTy::I64) => {
514 let lang_def_id = lang_items.i64_impl();
515 self.assemble_inherent_impl_for_primitive(lang_def_id);
517 ty::TyInt(ast::IntTy::I128) => {
518 let lang_def_id = lang_items.i128_impl();
519 self.assemble_inherent_impl_for_primitive(lang_def_id);
521 ty::TyInt(ast::IntTy::Isize) => {
522 let lang_def_id = lang_items.isize_impl();
523 self.assemble_inherent_impl_for_primitive(lang_def_id);
525 ty::TyUint(ast::UintTy::U8) => {
526 let lang_def_id = lang_items.u8_impl();
527 self.assemble_inherent_impl_for_primitive(lang_def_id);
529 ty::TyUint(ast::UintTy::U16) => {
530 let lang_def_id = lang_items.u16_impl();
531 self.assemble_inherent_impl_for_primitive(lang_def_id);
533 ty::TyUint(ast::UintTy::U32) => {
534 let lang_def_id = lang_items.u32_impl();
535 self.assemble_inherent_impl_for_primitive(lang_def_id);
537 ty::TyUint(ast::UintTy::U64) => {
538 let lang_def_id = lang_items.u64_impl();
539 self.assemble_inherent_impl_for_primitive(lang_def_id);
541 ty::TyUint(ast::UintTy::U128) => {
542 let lang_def_id = lang_items.u128_impl();
543 self.assemble_inherent_impl_for_primitive(lang_def_id);
545 ty::TyUint(ast::UintTy::Usize) => {
546 let lang_def_id = lang_items.usize_impl();
547 self.assemble_inherent_impl_for_primitive(lang_def_id);
549 ty::TyFloat(ast::FloatTy::F32) => {
550 let lang_def_id = lang_items.f32_impl();
551 self.assemble_inherent_impl_for_primitive(lang_def_id);
553 let lang_def_id = lang_items.f32_runtime_impl();
554 self.assemble_inherent_impl_for_primitive(lang_def_id);
556 ty::TyFloat(ast::FloatTy::F64) => {
557 let lang_def_id = lang_items.f64_impl();
558 self.assemble_inherent_impl_for_primitive(lang_def_id);
560 let lang_def_id = lang_items.f64_runtime_impl();
561 self.assemble_inherent_impl_for_primitive(lang_def_id);
567 fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
568 if let Some(impl_def_id) = lang_def_id {
569 self.assemble_inherent_impl_probe(impl_def_id);
573 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
574 let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
575 for &impl_def_id in impl_def_ids.iter() {
576 self.assemble_inherent_impl_probe(impl_def_id);
580 fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
581 if !self.impl_dups.insert(impl_def_id) {
582 return; // already visited
585 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
587 for item in self.impl_or_trait_item(impl_def_id) {
588 if !self.has_applicable_self(&item) {
589 // No receiver declared. Not a candidate.
590 self.record_static_candidate(ImplSource(impl_def_id));
594 let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
595 let impl_ty = impl_ty.subst(self.tcx, impl_substs);
597 // Determine the receiver type that the method itself expects.
598 let xform_tys = self.xform_self_ty(&item, impl_ty, impl_substs);
600 // We can't use normalize_associated_types_in as it will pollute the
601 // fcx's fulfillment context after this probe is over.
602 let cause = traits::ObligationCause::misc(self.span, self.body_id);
603 let selcx = &mut traits::SelectionContext::new(self.fcx);
604 let traits::Normalized { value: (xform_self_ty, xform_ret_ty), obligations } =
605 traits::normalize(selcx, self.param_env, cause, &xform_tys);
606 debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}/{:?}",
607 xform_self_ty, xform_ret_ty);
609 self.push_candidate(Candidate {
610 xform_self_ty, xform_ret_ty, item,
611 kind: InherentImplCandidate(impl_substs, obligations),
617 fn assemble_inherent_candidates_from_object(&mut self,
619 principal: ty::PolyExistentialTraitRef<'tcx>) {
620 debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
623 // It is illegal to invoke a method on a trait instance that
624 // refers to the `Self` type. An error will be reported by
625 // `enforce_object_limitations()` if the method refers to the
626 // `Self` type anywhere other than the receiver. Here, we use
627 // a substitution that replaces `Self` with the object type
628 // itself. Hence, a `&self` method will wind up with an
629 // argument type like `&Trait`.
630 let trait_ref = principal.with_self_ty(self.tcx, self_ty);
631 self.elaborate_bounds(&[trait_ref], |this, new_trait_ref, item| {
632 let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
634 let (xform_self_ty, xform_ret_ty) =
635 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
636 this.push_candidate(Candidate {
637 xform_self_ty, xform_ret_ty, item,
638 kind: ObjectCandidate,
644 fn assemble_inherent_candidates_from_param(&mut self,
646 param_ty: ty::ParamTy) {
647 // FIXME -- Do we want to commit to this behavior for param bounds?
649 let bounds: Vec<_> = self.param_env
652 .filter_map(|predicate| {
654 ty::Predicate::Trait(ref trait_predicate) => {
655 match trait_predicate.skip_binder().trait_ref.self_ty().sty {
656 ty::TyParam(ref p) if *p == param_ty => {
657 Some(trait_predicate.to_poly_trait_ref())
662 ty::Predicate::Subtype(..) |
663 ty::Predicate::Projection(..) |
664 ty::Predicate::RegionOutlives(..) |
665 ty::Predicate::WellFormed(..) |
666 ty::Predicate::ObjectSafe(..) |
667 ty::Predicate::ClosureKind(..) |
668 ty::Predicate::TypeOutlives(..) |
669 ty::Predicate::ConstEvaluatable(..) => None,
674 self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
675 let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
677 let (xform_self_ty, xform_ret_ty) =
678 this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
680 // Because this trait derives from a where-clause, it
681 // should not contain any inference variables or other
682 // artifacts. This means it is safe to put into the
683 // `WhereClauseCandidate` and (eventually) into the
684 // `WhereClausePick`.
685 assert!(!trait_ref.substs.needs_infer());
687 this.push_candidate(Candidate {
688 xform_self_ty, xform_ret_ty, item,
689 kind: WhereClauseCandidate(poly_trait_ref),
695 // Do a search through a list of bounds, using a callback to actually
696 // create the candidates.
697 fn elaborate_bounds<F>(&mut self, bounds: &[ty::PolyTraitRef<'tcx>], mut mk_cand: F)
698 where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>,
699 ty::PolyTraitRef<'tcx>,
702 debug!("elaborate_bounds(bounds={:?})", bounds);
705 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
706 for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
707 if !self.has_applicable_self(&item) {
708 self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
710 mk_cand(self, bound_trait_ref, item);
716 fn assemble_extension_candidates_for_traits_in_scope(&mut self,
717 expr_id: ast::NodeId)
718 -> Result<(), MethodError<'tcx>> {
719 if expr_id == ast::DUMMY_NODE_ID {
722 let mut duplicates = FxHashSet();
723 let expr_hir_id = self.tcx.hir.node_to_hir_id(expr_id);
724 let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
725 if let Some(applicable_traits) = opt_applicable_traits {
726 for trait_candidate in applicable_traits.iter() {
727 let trait_did = trait_candidate.def_id;
728 if duplicates.insert(trait_did) {
729 let import_id = trait_candidate.import_id;
730 let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
738 fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
739 let mut duplicates = FxHashSet();
740 for trait_info in suggest::all_traits(self.tcx) {
741 if duplicates.insert(trait_info.def_id) {
742 self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
748 pub fn matches_return_type(&self,
749 method: &ty::AssociatedItem,
750 self_ty: Option<Ty<'tcx>>,
751 expected: Ty<'tcx>) -> bool {
753 Def::Method(def_id) => {
754 let fty = self.tcx.fn_sig(def_id);
756 let substs = self.fresh_substs_for_item(self.span, method.def_id);
757 let fty = fty.subst(self.tcx, substs);
758 let (fty, _) = self.replace_late_bound_regions_with_fresh_var(
759 self.span, infer::FnCall, &fty);
761 if let Some(self_ty) = self_ty {
762 if let Err(_) = self.at(&ObligationCause::dummy(), self.param_env)
763 .sup(fty.inputs()[0], self_ty)
768 self.can_sub(self.param_env, fty.output(), expected).is_ok()
775 fn assemble_extension_candidates_for_trait(&mut self,
776 import_id: Option<ast::NodeId>,
778 -> Result<(), MethodError<'tcx>> {
779 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
781 let trait_substs = self.fresh_item_substs(trait_def_id);
782 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
784 for item in self.impl_or_trait_item(trait_def_id) {
785 // Check whether `trait_def_id` defines a method with suitable name:
786 if !self.has_applicable_self(&item) {
787 debug!("method has inapplicable self");
788 self.record_static_candidate(TraitSource(trait_def_id));
792 let (xform_self_ty, xform_ret_ty) =
793 self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
794 self.push_candidate(Candidate {
795 xform_self_ty, xform_ret_ty, item, import_id,
796 kind: TraitCandidate(trait_ref),
802 fn candidate_method_names(&self) -> Vec<ast::Name> {
803 let mut set = FxHashSet();
804 let mut names: Vec<_> = self.inherent_candidates
806 .chain(&self.extension_candidates)
807 .filter(|candidate| {
808 if let Some(return_ty) = self.return_type {
809 self.matches_return_type(&candidate.item, None, return_ty)
814 .map(|candidate| candidate.item.name)
815 .filter(|&name| set.insert(name))
818 // sort them by the name so we have a stable result
819 names.sort_by_cached_key(|n| n.as_str());
823 ///////////////////////////////////////////////////////////////////////////
826 fn pick(mut self) -> PickResult<'tcx> {
827 assert!(self.method_name.is_some());
829 if let Some(r) = self.pick_core() {
833 let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
834 let private_candidate = mem::replace(&mut self.private_candidate, None);
835 let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
837 // things failed, so lets look at all traits, for diagnostic purposes now:
840 let span = self.span;
843 self.assemble_extension_candidates_for_all_traits()?;
845 let out_of_scope_traits = match self.pick_core() {
846 Some(Ok(p)) => vec![p.item.container.id()],
847 //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
848 Some(Err(MethodError::Ambiguity(v))) => {
852 TraitSource(id) => id,
853 ImplSource(impl_id) => {
854 match tcx.trait_id_of_impl(impl_id) {
858 "found inherent method when looking at traits")
866 Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
867 assert!(others.is_empty());
873 if let Some(def) = private_candidate {
874 return Err(MethodError::PrivateMatch(def, out_of_scope_traits));
876 let lev_candidate = self.probe_for_lev_candidate()?;
878 Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
879 unsatisfied_predicates,
885 fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
886 let steps = self.steps.clone();
888 // find the first step that works
892 debug!("pick_core: step={:?}", step);
893 // skip types that are from a type error or that would require dereferencing
895 !step.self_ty.references_error() && !step.from_unsafe_deref
897 self.pick_by_value_method(step).or_else(|| {
898 self.pick_autorefd_method(step, hir::MutImmutable).or_else(|| {
899 self.pick_autorefd_method(step, hir::MutMutable)
904 fn pick_by_value_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
905 //! For each type `T` in the step list, this attempts to find a
906 //! method where the (transformed) self type is exactly `T`. We
907 //! do however do one transformation on the adjustment: if we
908 //! are passing a region pointer in, we will potentially
909 //! *reborrow* it to a shorter lifetime. This allows us to
910 //! transparently pass `&mut` pointers, in particular, without
911 //! consuming them for their entire lifetime.
917 self.pick_method(step.self_ty).map(|r| {
919 pick.autoderefs = step.autoderefs;
921 // Insert a `&*` or `&mut *` if this is a reference type:
922 if let ty::TyRef(_, _, mutbl) = step.self_ty.sty {
923 pick.autoderefs += 1;
924 pick.autoref = Some(mutbl);
932 fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>, mutbl: hir::Mutability)
933 -> Option<PickResult<'tcx>> {
936 // In general, during probing we erase regions. See
937 // `impl_self_ty()` for an explanation.
938 let region = tcx.types.re_erased;
940 let autoref_ty = tcx.mk_ref(region,
942 ty: step.self_ty, mutbl
944 self.pick_method(autoref_ty).map(|r| {
946 pick.autoderefs = step.autoderefs;
947 pick.autoref = Some(mutbl);
948 pick.unsize = if step.unsize {
958 fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
959 debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
961 let mut possibly_unsatisfied_predicates = Vec::new();
962 let mut unstable_candidates = Vec::new();
964 for (kind, candidates) in &[
965 ("inherent", &self.inherent_candidates),
966 ("extension", &self.extension_candidates),
968 debug!("searching {} candidates", kind);
969 let res = self.consider_candidates(
972 &mut possibly_unsatisfied_predicates,
973 Some(&mut unstable_candidates),
975 if let Some(pick) = res {
976 if !self.is_suggestion.0 && !unstable_candidates.is_empty() {
977 if let Ok(p) = &pick {
978 // Emit a lint if there are unstable candidates alongside the stable ones.
980 // We suppress warning if we're picking the method only because it is a
982 self.emit_unstable_name_collision_hint(p, &unstable_candidates);
989 debug!("searching unstable candidates");
990 let res = self.consider_candidates(
992 unstable_candidates.into_iter().map(|(c, _)| c),
993 &mut possibly_unsatisfied_predicates,
997 self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1002 fn consider_candidates<'b, ProbesIter>(
1006 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>,
1007 unstable_candidates: Option<&mut Vec<(&'b Candidate<'tcx>, Symbol)>>,
1008 ) -> Option<PickResult<'tcx>>
1010 ProbesIter: Iterator<Item = &'b Candidate<'tcx>> + Clone,
1012 let mut applicable_candidates: Vec<_> = probes.clone()
1014 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1016 .filter(|&(_, status)| status != ProbeResult::NoMatch)
1019 debug!("applicable_candidates: {:?}", applicable_candidates);
1021 if applicable_candidates.len() > 1 {
1022 if let Some(pick) = self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1023 return Some(Ok(pick));
1027 if let Some(uc) = unstable_candidates {
1028 applicable_candidates.retain(|&(p, _)| {
1029 if let stability::EvalResult::Deny { feature, .. } =
1030 self.tcx.eval_stability(p.item.def_id, None, self.span)
1032 uc.push((p, feature));
1039 if applicable_candidates.len() > 1 {
1040 let sources = probes
1041 .map(|p| self.candidate_source(p, self_ty))
1043 return Some(Err(MethodError::Ambiguity(sources)));
1046 applicable_candidates.pop().map(|(probe, status)| {
1047 if status == ProbeResult::Match {
1048 Ok(probe.to_unadjusted_pick())
1050 Err(MethodError::BadReturnType)
1055 fn emit_unstable_name_collision_hint(
1058 unstable_candidates: &[(&Candidate<'tcx>, Symbol)],
1060 let mut diag = self.tcx.struct_span_lint_node(
1061 lint::builtin::UNSTABLE_NAME_COLLISIONS,
1064 "a method with this name may be added to the standard library in the future",
1067 // FIXME: This should be a `span_suggestion` instead of `help`. However `self.span` only
1068 // highlights the method name, so we can't use it. Also consider reusing the code from
1069 // `report_method_error()`.
1071 "call with fully qualified syntax `{}(...)` to keep using the current method",
1072 self.tcx.item_path_str(stable_pick.item.def_id),
1075 if ::rustc::session::config::nightly_options::is_nightly_build() {
1076 for (candidate, feature) in unstable_candidates {
1078 "add #![feature({})] to the crate attributes to enable `{}`",
1080 self.tcx.item_path_str(candidate.item.def_id),
1088 fn select_trait_candidate(&self, trait_ref: ty::TraitRef<'tcx>)
1089 -> traits::SelectionResult<'tcx, traits::Selection<'tcx>>
1091 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1093 trait_ref.to_poly_trait_ref().to_poly_trait_predicate();
1094 let obligation = traits::Obligation::new(cause, self.param_env, predicate);
1095 traits::SelectionContext::new(self).select(&obligation)
1098 fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>)
1101 match candidate.kind {
1102 InherentImplCandidate(..) => ImplSource(candidate.item.container.id()),
1104 WhereClauseCandidate(_) => TraitSource(candidate.item.container.id()),
1105 TraitCandidate(trait_ref) => self.probe(|_| {
1106 let _ = self.at(&ObligationCause::dummy(), self.param_env)
1107 .sup(candidate.xform_self_ty, self_ty);
1108 match self.select_trait_candidate(trait_ref) {
1109 Ok(Some(traits::Vtable::VtableImpl(ref impl_data))) => {
1110 // If only a single impl matches, make the error message point
1112 ImplSource(impl_data.impl_def_id)
1115 TraitSource(candidate.item.container.id())
1122 fn consider_probe(&self,
1124 probe: &Candidate<'tcx>,
1125 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1127 debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1130 // First check that the self type can be related.
1131 let sub_obligations = match self.at(&ObligationCause::dummy(), self.param_env)
1132 .sup(probe.xform_self_ty, self_ty) {
1133 Ok(InferOk { obligations, value: () }) => obligations,
1135 debug!("--> cannot relate self-types");
1136 return ProbeResult::NoMatch;
1140 let mut result = ProbeResult::Match;
1141 let selcx = &mut traits::SelectionContext::new(self);
1142 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1144 // If so, impls may carry other conditions (e.g., where
1145 // clauses) that must be considered. Make sure that those
1146 // match as well (or at least may match, sometimes we
1147 // don't have enough information to fully evaluate).
1148 let candidate_obligations : Vec<_> = match probe.kind {
1149 InherentImplCandidate(ref substs, ref ref_obligations) => {
1150 // Check whether the impl imposes obligations we have to worry about.
1151 let impl_def_id = probe.item.container.id();
1152 let impl_bounds = self.tcx.predicates_of(impl_def_id);
1153 let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1154 let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1155 traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
1157 // Convert the bounds into obligations.
1158 let impl_obligations = traits::predicates_for_generics(
1159 cause.clone(), self.param_env, &impl_bounds);
1161 debug!("impl_obligations={:?}", impl_obligations);
1162 impl_obligations.into_iter()
1163 .chain(norm_obligations.into_iter())
1164 .chain(ref_obligations.iter().cloned())
1169 WhereClauseCandidate(..) => {
1170 // These have no additional conditions to check.
1174 TraitCandidate(trait_ref) => {
1175 let predicate = trait_ref.to_predicate();
1177 traits::Obligation::new(cause.clone(), self.param_env, predicate);
1178 if !self.predicate_may_hold(&obligation) {
1179 if self.probe(|_| self.select_trait_candidate(trait_ref).is_err()) {
1180 // This candidate's primary obligation doesn't even
1181 // select - don't bother registering anything in
1182 // `potentially_unsatisfied_predicates`.
1183 return ProbeResult::NoMatch;
1185 // Some nested subobligation of this predicate
1188 // FIXME: try to find the exact nested subobligation
1189 // and point at it rather than reporting the entire
1191 result = ProbeResult::NoMatch;
1192 let trait_ref = self.resolve_type_vars_if_possible(&trait_ref);
1193 possibly_unsatisfied_predicates.push(trait_ref);
1200 debug!("consider_probe - candidate_obligations={:?} sub_obligations={:?}",
1201 candidate_obligations, sub_obligations);
1203 // Evaluate those obligations to see if they might possibly hold.
1204 for o in candidate_obligations.into_iter().chain(sub_obligations) {
1205 let o = self.resolve_type_vars_if_possible(&o);
1206 if !self.predicate_may_hold(&o) {
1207 result = ProbeResult::NoMatch;
1208 if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1209 possibly_unsatisfied_predicates.push(pred.skip_binder().trait_ref);
1214 if let ProbeResult::Match = result {
1215 if let (Some(return_ty), Some(xform_ret_ty)) =
1216 (self.return_type, probe.xform_ret_ty)
1218 let xform_ret_ty = self.resolve_type_vars_if_possible(&xform_ret_ty);
1219 debug!("comparing return_ty {:?} with xform ret ty {:?}",
1221 probe.xform_ret_ty);
1222 if self.at(&ObligationCause::dummy(), self.param_env)
1223 .sup(return_ty, xform_ret_ty)
1226 return ProbeResult::BadReturnType;
1235 /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1236 /// same trait, but we don't know which impl to use. In this case, since in all cases the
1237 /// external interface of the method can be determined from the trait, it's ok not to decide.
1238 /// We can basically just collapse all of the probes for various impls into one where-clause
1239 /// probe. This will result in a pending obligation so when more type-info is available we can
1240 /// make the final decision.
1242 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1245 /// trait Foo { ... }
1246 /// impl Foo for Vec<int> { ... }
1247 /// impl Foo for Vec<usize> { ... }
1250 /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1251 /// use, so it's ok to just commit to "using the method from the trait Foo".
1252 fn collapse_candidates_to_trait_pick(&self, probes: &[(&Candidate<'tcx>, ProbeResult)])
1253 -> Option<Pick<'tcx>>
1255 // Do all probes correspond to the same trait?
1256 let container = probes[0].0.item.container;
1258 ty::TraitContainer(_) => {}
1259 ty::ImplContainer(_) => return None,
1261 if probes[1..].iter().any(|&(p, _)| p.item.container != container) {
1265 // FIXME: check the return type here somehow.
1266 // If so, just use this trait and call it a day.
1268 item: probes[0].0.item.clone(),
1270 import_id: probes[0].0.import_id,
1277 /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
1278 /// candidate method where the method name may have been misspelt. Similarly to other
1279 /// Levenshtein based suggestions, we provide at most one such suggestion.
1280 fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssociatedItem>, MethodError<'tcx>> {
1281 debug!("Probing for method names similar to {:?}",
1284 let steps = self.steps.clone();
1286 let mut pcx = ProbeContext::new(self.fcx, self.span, self.mode, self.method_name,
1287 self.return_type, steps, IsSuggestion(true));
1288 pcx.allow_similar_names = true;
1289 pcx.assemble_inherent_candidates();
1290 pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)?;
1292 let method_names = pcx.candidate_method_names();
1293 pcx.allow_similar_names = false;
1294 let applicable_close_candidates: Vec<ty::AssociatedItem> = method_names
1296 .filter_map(|&method_name| {
1298 pcx.method_name = Some(method_name);
1299 pcx.assemble_inherent_candidates();
1300 pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)
1301 .ok().map_or(None, |_| {
1303 .and_then(|pick| pick.ok())
1304 .and_then(|pick| Some(pick.item))
1309 if applicable_close_candidates.is_empty() {
1313 let names = applicable_close_candidates.iter().map(|cand| &cand.name);
1314 find_best_match_for_name(names,
1315 &self.method_name.unwrap().as_str(),
1318 Ok(applicable_close_candidates
1320 .find(|method| method.name == best_name))
1325 ///////////////////////////////////////////////////////////////////////////
1327 fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1328 // "Fast track" -- check for usage of sugar when in method call
1331 // In Path mode (i.e., resolving a value like `T::next`), consider any
1332 // associated value (i.e., methods, constants) but not types.
1334 Mode::MethodCall => item.method_has_self_argument,
1335 Mode::Path => match item.kind {
1336 ty::AssociatedKind::Type => false,
1337 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1340 // FIXME -- check for types that deref to `Self`,
1341 // like `Rc<Self>` and so on.
1343 // Note also that the current code will break if this type
1344 // includes any of the type parameters defined on the method
1345 // -- but this could be overcome.
1348 fn record_static_candidate(&mut self, source: CandidateSource) {
1349 self.static_candidates.push(source);
1352 fn xform_self_ty(&self,
1353 item: &ty::AssociatedItem,
1355 substs: &Substs<'tcx>)
1356 -> (Ty<'tcx>, Option<Ty<'tcx>>) {
1357 if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1358 let sig = self.xform_method_sig(item.def_id, substs);
1359 (sig.inputs()[0], Some(sig.output()))
1365 fn xform_method_sig(&self,
1367 substs: &Substs<'tcx>)
1370 let fn_sig = self.tcx.fn_sig(method);
1371 debug!("xform_self_ty(fn_sig={:?}, substs={:?})",
1375 assert!(!substs.has_escaping_regions());
1377 // It is possible for type parameters or early-bound lifetimes
1378 // to appear in the signature of `self`. The substitutions we
1379 // are given do not include type/lifetime parameters for the
1380 // method yet. So create fresh variables here for those too,
1381 // if there are any.
1382 let generics = self.tcx.generics_of(method);
1383 assert_eq!(substs.len(), generics.parent_count as usize);
1385 // Erase any late-bound regions from the method and substitute
1386 // in the values from the substitution.
1387 let xform_fn_sig = self.erase_late_bound_regions(&fn_sig);
1389 if generics.params.is_empty() {
1390 xform_fn_sig.subst(self.tcx, substs)
1392 let substs = Substs::for_item(self.tcx, method, |param, _| {
1393 let i = param.index as usize;
1394 if i < substs.len() {
1398 GenericParamDefKind::Lifetime => {
1399 // In general, during probe we erase regions. See
1400 // `impl_self_ty()` for an explanation.
1401 self.tcx.types.re_erased.into()
1403 GenericParamDefKind::Type {..} => self.var_for_def(self.span, param),
1407 xform_fn_sig.subst(self.tcx, substs)
1411 /// Get the type of an impl and generate substitutions with placeholders.
1412 fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
1413 (self.tcx.type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1416 fn fresh_item_substs(&self, def_id: DefId) -> &'tcx Substs<'tcx> {
1417 Substs::for_item(self.tcx, def_id, |param, _| {
1419 GenericParamDefKind::Lifetime => self.tcx.types.re_erased.into(),
1420 GenericParamDefKind::Type {..} => {
1421 self.next_ty_var(TypeVariableOrigin::SubstitutionPlaceholder(
1422 self.tcx.def_span(def_id))).into()
1428 /// Replace late-bound-regions bound by `value` with `'static` using
1429 /// `ty::erase_late_bound_regions`.
1431 /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1432 /// method matching. It is reasonable during the probe phase because we don't consider region
1433 /// relationships at all. Therefore, we can just replace all the region variables with 'static
1434 /// rather than creating fresh region variables. This is nice for two reasons:
1436 /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1437 /// particular method call, it winds up creating fewer types overall, which helps for memory
1438 /// usage. (Admittedly, this is a rather small effect, though measureable.)
1440 /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1441 /// late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1442 /// regions with actual region variables as is proper, we'd have to ensure that the same
1443 /// region got replaced with the same variable, which requires a bit more coordination
1444 /// and/or tracking the substitution and
1446 fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1447 where T: TypeFoldable<'tcx>
1449 self.tcx.erase_late_bound_regions(value)
1452 /// Find the method with the appropriate name (or return type, as the case may be). If
1453 /// `allow_similar_names` is set, find methods with close-matching names.
1454 fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1455 if let Some(name) = self.method_name {
1456 if self.allow_similar_names {
1457 let max_dist = max(name.as_str().len(), 3) / 3;
1458 self.tcx.associated_items(def_id)
1460 let dist = lev_distance(&*name.as_str(), &x.name.as_str());
1461 Namespace::from(x.kind) == Namespace::Value && dist > 0
1467 .associated_item(def_id, name, Namespace::Value)
1468 .map_or(Vec::new(), |x| vec![x])
1471 self.tcx.associated_items(def_id).collect()
1476 impl<'tcx> Candidate<'tcx> {
1477 fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1479 item: self.item.clone(),
1480 kind: match self.kind {
1481 InherentImplCandidate(..) => InherentImplPick,
1482 ObjectCandidate => ObjectPick,
1483 TraitCandidate(_) => TraitPick,
1484 WhereClauseCandidate(ref trait_ref) => {
1485 // Only trait derived from where-clauses should
1486 // appear here, so they should not contain any
1487 // inference variables or other artifacts. This
1488 // means they are safe to put into the
1489 // `WhereClausePick`.
1491 !trait_ref.skip_binder().substs.needs_infer()
1492 && !trait_ref.skip_binder().substs.has_skol()
1495 WhereClausePick(trait_ref.clone())
1498 import_id: self.import_id,