1 use super::MethodError;
2 use super::NoMatchData;
3 use super::{CandidateSource, ImplSource, TraitSource};
6 use crate::check::autoderef::{self, Autoderef};
7 use crate::check::FnCtxt;
8 use crate::hir::def_id::DefId;
9 use crate::hir::def::Def;
10 use crate::namespace::Namespace;
12 use rustc_data_structures::sync::Lrc;
15 use rustc::session::config::nightly_options;
16 use rustc::ty::subst::{Subst, InternalSubsts, SubstsRef};
17 use rustc::traits::{self, ObligationCause};
18 use rustc::traits::query::{CanonicalTyGoal};
19 use rustc::traits::query::method_autoderef::{CandidateStep, MethodAutoderefStepsResult};
20 use rustc::traits::query::method_autoderef::{MethodAutoderefBadTy};
21 use rustc::ty::{self, ParamEnvAnd, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TraitRef, TypeFoldable};
22 use rustc::ty::GenericParamDefKind;
23 use rustc::infer::type_variable::TypeVariableOrigin;
24 use rustc::util::nodemap::FxHashSet;
25 use rustc::infer::{self, InferOk};
26 use rustc::infer::canonical::{Canonical, QueryResponse};
27 use rustc::infer::canonical::{OriginalQueryValues};
28 use rustc::middle::stability;
30 use syntax::util::lev_distance::{lev_distance, find_best_match_for_name};
31 use syntax_pos::{DUMMY_SP, 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::Ident>,
50 return_type: Option<Ty<'tcx>>,
52 /// This is the OriginalQueryValues for the steps queries
53 /// that are answered in steps.
54 orig_steps_var_values: OriginalQueryValues<'tcx>,
55 steps: Lrc<Vec<CandidateStep<'gcx>>>,
57 inherent_candidates: Vec<Candidate<'tcx>>,
58 extension_candidates: Vec<Candidate<'tcx>>,
59 impl_dups: FxHashSet<DefId>,
61 /// Collects near misses when the candidate functions are missing a `self` keyword and is only
62 /// used for error reporting
63 static_candidates: Vec<CandidateSource>,
65 /// When probing for names, include names that are close to the
66 /// requested name (by Levensthein distance)
67 allow_similar_names: bool,
69 /// Some(candidate) if there is a private candidate
70 private_candidate: Option<Def>,
72 /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
73 /// for error reporting
74 unsatisfied_predicates: Vec<TraitRef<'tcx>>,
76 is_suggestion: IsSuggestion,
79 impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
80 type Target = FnCtxt<'a, 'gcx, 'tcx>;
81 fn deref(&self) -> &Self::Target {
87 struct Candidate<'tcx> {
88 // Candidates are (I'm not quite sure, but they are mostly) basically
89 // some metadata on top of a `ty::AssociatedItem` (without substs).
91 // However, method probing wants to be able to evaluate the predicates
92 // for a function with the substs applied - for example, if a function
93 // has `where Self: Sized`, we don't want to consider it unless `Self`
94 // is actually `Sized`, and similarly, return-type suggestions want
95 // to consider the "actual" return type.
97 // The way this is handled is through `xform_self_ty`. It contains
98 // the receiver type of this candidate, but `xform_self_ty`,
99 // `xform_ret_ty` and `kind` (which contains the predicates) have the
100 // generic parameters of this candidate substituted with the *same set*
101 // of inference variables, which acts as some weird sort of "query".
103 // When we check out a candidate, we require `xform_self_ty` to be
104 // a subtype of the passed-in self-type, and this equates the type
105 // variables in the rest of the fields.
107 // For example, if we have this candidate:
110 // fn foo(&self) where Self: Sized;
114 // Then `xform_self_ty` will be `&'erased ?X` and `kind` will contain
115 // the predicate `?X: Sized`, so if we are evaluating `Foo` for a
116 // the receiver `&T`, we'll do the subtyping which will make `?X`
117 // get the right value, then when we evaluate the predicate we'll check
119 xform_self_ty: Ty<'tcx>,
120 xform_ret_ty: Option<Ty<'tcx>>,
121 item: ty::AssociatedItem,
122 kind: CandidateKind<'tcx>,
123 import_id: Option<ast::NodeId>,
127 enum CandidateKind<'tcx> {
128 InherentImplCandidate(SubstsRef<'tcx>,
129 // Normalize obligations
130 Vec<traits::PredicateObligation<'tcx>>),
132 TraitCandidate(ty::TraitRef<'tcx>),
133 WhereClauseCandidate(// Trait
134 ty::PolyTraitRef<'tcx>),
137 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
144 #[derive(Debug, PartialEq, Clone)]
145 pub struct Pick<'tcx> {
146 pub item: ty::AssociatedItem,
147 pub kind: PickKind<'tcx>,
148 pub import_id: Option<ast::NodeId>,
150 // Indicates that the source expression should be autoderef'd N times
152 // A = expr | *expr | **expr | ...
153 pub autoderefs: usize,
155 // Indicates that an autoref is applied after the optional autoderefs
157 // B = A | &A | &mut A
158 pub autoref: Option<hir::Mutability>,
160 // Indicates that the source expression should be "unsized" to a
161 // target type. This should probably eventually go away in favor
162 // of just coercing method receivers.
165 pub unsize: Option<Ty<'tcx>>,
168 #[derive(Clone, Debug, PartialEq, Eq)]
169 pub enum PickKind<'tcx> {
173 WhereClausePick(// Trait
174 ty::PolyTraitRef<'tcx>),
177 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
179 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
181 // An expression of the form `receiver.method_name(...)`.
182 // Autoderefs are performed on `receiver`, lookup is done based on the
183 // `self` argument of the method, and static methods aren't considered.
185 // An expression of the form `Type::item` or `<T>::item`.
186 // No autoderefs are performed, lookup is done based on the type each
187 // implementation is for, and static methods are included.
191 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
192 pub enum ProbeScope {
193 // Assemble candidates coming only from traits in scope.
196 // Assemble candidates coming from all traits.
200 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
201 /// This is used to offer suggestions to users. It returns methods
202 /// that could have been called which have the desired return
203 /// type. Some effort is made to rule out methods that, if called,
204 /// would result in an error (basically, the same criteria we
205 /// would use to decide if a method is a plausible fit for
206 /// ambiguity purposes).
207 pub fn probe_for_return_type(&self,
210 return_type: Ty<'tcx>,
212 scope_expr_id: hir::HirId)
213 -> Vec<ty::AssociatedItem> {
214 debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
219 self.probe_op(span, mode, None, Some(return_type), IsSuggestion(true),
220 self_ty, scope_expr_id, ProbeScope::AllTraits,
221 |probe_cx| Ok(probe_cx.candidate_method_names()))
225 .flat_map(|&method_name| {
227 span, mode, Some(method_name), Some(return_type),
228 IsSuggestion(true), self_ty, scope_expr_id,
229 ProbeScope::AllTraits, |probe_cx| probe_cx.pick()
230 ).ok().map(|pick| pick.item)
235 pub fn probe_for_name(&self,
238 item_name: ast::Ident,
239 is_suggestion: IsSuggestion,
241 scope_expr_id: hir::HirId,
243 -> PickResult<'tcx> {
244 debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
256 |probe_cx| probe_cx.pick())
259 fn probe_op<OP,R>(&'a self,
262 method_name: Option<ast::Ident>,
263 return_type: Option<Ty<'tcx>>,
264 is_suggestion: IsSuggestion,
266 scope_expr_id: hir::HirId,
269 -> Result<R, MethodError<'tcx>>
270 where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
272 let mut orig_values = OriginalQueryValues::default();
273 let param_env_and_self_ty =
274 self.infcx.canonicalize_query(
276 param_env: self.param_env,
278 }, &mut orig_values);
280 let steps = if mode == Mode::MethodCall {
281 self.tcx.method_autoderef_steps(param_env_and_self_ty)
283 self.infcx.probe(|_| {
284 // Mode::Path - the deref steps is "trivial". This turns
285 // our CanonicalQuery into a "trivial" QueryResponse. This
286 // is a bit inefficient, but I don't think that writing
287 // special handling for this "trivial case" is a good idea.
289 let infcx = &self.infcx;
293 }, canonical_inference_vars) =
294 infcx.instantiate_canonical_with_fresh_inference_vars(
295 span, ¶m_env_and_self_ty);
296 debug!("probe_op: Mode::Path, param_env_and_self_ty={:?} self_ty={:?}",
297 param_env_and_self_ty, self_ty);
298 MethodAutoderefStepsResult {
299 steps: Lrc::new(vec![CandidateStep {
300 self_ty: self.make_query_response_ignoring_pending_obligations(
301 canonical_inference_vars, self_ty),
303 from_unsafe_deref: false,
307 reached_recursion_limit: false
312 // If our autoderef loop had reached the recursion limit,
313 // report an overflow error, but continue going on with
314 // the truncated autoderef list.
315 if steps.reached_recursion_limit {
317 let ty = &steps.steps.last().unwrap_or_else(|| {
318 span_bug!(span, "reached the recursion limit in 0 steps?")
320 let ty = self.probe_instantiate_query_response(span, &orig_values, ty)
321 .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
322 autoderef::report_autoderef_recursion_limit_error(self.tcx, span,
328 // If we encountered an `_` type or an error type during autoderef, this is
330 if let Some(bad_ty) = &steps.opt_bad_ty {
332 // Ambiguity was encountered during a suggestion. Just keep going.
333 debug!("ProbeContext: encountered ambiguity in suggestion");
334 } else if bad_ty.reached_raw_pointer && !self.tcx.features().arbitrary_self_types {
335 // this case used to be allowed by the compiler,
336 // so we do a future-compat lint here for the 2015 edition
337 // (see https://github.com/rust-lang/rust/issues/46906)
338 if self.tcx.sess.rust_2018() {
339 span_err!(self.tcx.sess, span, E0699,
340 "the type of this value must be known \
341 to call a method on a raw pointer on it");
344 lint::builtin::TYVAR_BEHIND_RAW_POINTER,
347 "type annotations needed");
350 // Encountered a real ambiguity, so abort the lookup. If `ty` is not
351 // an `Err`, report the right "type annotations needed" error pointing
354 let ty = self.probe_instantiate_query_response(span, &orig_values, ty)
355 .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
356 let ty = self.structurally_resolved_type(span, ty.value);
357 assert_eq!(ty, self.tcx.types.err);
358 return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
366 debug!("ProbeContext: steps for self_ty={:?} are {:?}",
371 // this creates one big transaction so that all type variables etc
372 // that we create during the probe process are removed later
374 let mut probe_cx = ProbeContext::new(
375 self, span, mode, method_name, return_type, orig_values,
376 steps.steps, is_suggestion,
379 probe_cx.assemble_inherent_candidates();
381 ProbeScope::TraitsInScope =>
382 probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?,
383 ProbeScope::AllTraits =>
384 probe_cx.assemble_extension_candidates_for_all_traits()?,
391 pub fn provide(providers: &mut ty::query::Providers<'_>) {
392 providers.method_autoderef_steps = method_autoderef_steps;
395 fn method_autoderef_steps<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
396 goal: CanonicalTyGoal<'tcx>)
397 -> MethodAutoderefStepsResult<'gcx>
399 debug!("method_autoderef_steps({:?})", goal);
401 tcx.infer_ctxt().enter_with_canonical(DUMMY_SP, &goal, |ref infcx, goal, inference_vars| {
402 let ParamEnvAnd { param_env, value: self_ty } = goal;
404 let mut autoderef = Autoderef::new(infcx, param_env, hir::DUMMY_HIR_ID, DUMMY_SP, self_ty)
405 .include_raw_pointers()
407 let mut reached_raw_pointer = false;
408 let mut steps: Vec<_> = autoderef.by_ref()
410 let step = CandidateStep {
411 self_ty: infcx.make_query_response_ignoring_pending_obligations(
412 inference_vars.clone(), ty),
414 from_unsafe_deref: reached_raw_pointer,
417 if let ty::RawPtr(_) = ty.sty {
418 // all the subsequent steps will be from_unsafe_deref
419 reached_raw_pointer = true;
425 let final_ty = autoderef.maybe_ambiguous_final_ty();
426 let opt_bad_ty = match final_ty.sty {
427 ty::Infer(ty::TyVar(_)) |
429 Some(MethodAutoderefBadTy {
431 ty: infcx.make_query_response_ignoring_pending_obligations(
432 inference_vars, final_ty)
435 ty::Array(elem_ty, _) => {
436 let dereferences = steps.len() - 1;
438 steps.push(CandidateStep {
439 self_ty: infcx.make_query_response_ignoring_pending_obligations(
440 inference_vars, infcx.tcx.mk_slice(elem_ty)),
441 autoderefs: dereferences,
442 // this could be from an unsafe deref if we had
443 // a *mut/const [T; N]
444 from_unsafe_deref: reached_raw_pointer,
453 debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
455 MethodAutoderefStepsResult {
456 steps: Lrc::new(steps),
457 opt_bad_ty: opt_bad_ty.map(Lrc::new),
458 reached_recursion_limit: autoderef.reached_recursion_limit()
464 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
465 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
468 method_name: Option<ast::Ident>,
469 return_type: Option<Ty<'tcx>>,
470 orig_steps_var_values: OriginalQueryValues<'tcx>,
471 steps: Lrc<Vec<CandidateStep<'gcx>>>,
472 is_suggestion: IsSuggestion)
473 -> ProbeContext<'a, 'gcx, 'tcx> {
480 inherent_candidates: Vec::new(),
481 extension_candidates: Vec::new(),
482 impl_dups: FxHashSet::default(),
483 orig_steps_var_values,
485 static_candidates: Vec::new(),
486 allow_similar_names: false,
487 private_candidate: None,
488 unsatisfied_predicates: Vec::new(),
493 fn reset(&mut self) {
494 self.inherent_candidates.clear();
495 self.extension_candidates.clear();
496 self.impl_dups.clear();
497 self.static_candidates.clear();
498 self.private_candidate = None;
501 ///////////////////////////////////////////////////////////////////////////
502 // CANDIDATE ASSEMBLY
504 fn push_candidate(&mut self,
505 candidate: Candidate<'tcx>,
508 let is_accessible = if let Some(name) = self.method_name {
509 let item = candidate.item;
510 let def_scope = self.tcx.adjust_ident(name, item.container.id(), self.body_id).1;
511 item.vis.is_accessible_from(def_scope, self.tcx)
517 self.inherent_candidates.push(candidate);
519 self.extension_candidates.push(candidate);
521 } else if self.private_candidate.is_none() {
522 self.private_candidate = Some(candidate.item.def());
526 fn assemble_inherent_candidates(&mut self) {
527 let steps = self.steps.clone();
528 for step in steps.iter() {
529 self.assemble_probe(&step.self_ty);
533 fn assemble_probe(&mut self, self_ty: &Canonical<'gcx, QueryResponse<'gcx, Ty<'gcx>>>) {
534 debug!("assemble_probe: self_ty={:?}", self_ty);
535 let lang_items = self.tcx.lang_items();
537 match self_ty.value.value.sty {
538 ty::Dynamic(ref data, ..) => {
539 if let Some(p) = data.principal() {
540 // Subtle: we can't use `instantiate_query_response` here: using it will
541 // commit to all of the type equalities assumed by inference going through
542 // autoderef (see the `method-probe-no-guessing` test).
544 // However, in this code, it is OK if we end up with an object type that is
545 // "more general" than the object type that we are evaluating. For *every*
546 // object type `MY_OBJECT`, a function call that goes through a trait-ref
547 // of the form `<MY_OBJECT as SuperTraitOf(MY_OBJECT)>::func` is a valid
548 // `ObjectCandidate`, and it should be discoverable "exactly" through one
549 // of the iterations in the autoderef loop, so there is no problem with it
550 // being discoverable in another one of these iterations.
552 // Using `instantiate_canonical_with_fresh_inference_vars` on our
553 // `Canonical<QueryResponse<Ty<'tcx>>>` and then *throwing away* the
554 // `CanonicalVarValues` will exactly give us such a generalization - it
555 // will still match the original object type, but it won't pollute our
556 // type variables in any form, so just do that!
557 let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) =
558 self.fcx.instantiate_canonical_with_fresh_inference_vars(
559 self.span, &self_ty);
561 self.assemble_inherent_candidates_from_object(generalized_self_ty);
562 self.assemble_inherent_impl_candidates_for_type(p.def_id());
566 self.assemble_inherent_impl_candidates_for_type(def.did);
568 ty::Foreign(did) => {
569 self.assemble_inherent_impl_candidates_for_type(did);
572 self.assemble_inherent_candidates_from_param(p);
575 let lang_def_id = lang_items.char_impl();
576 self.assemble_inherent_impl_for_primitive(lang_def_id);
579 let lang_def_id = lang_items.str_impl();
580 self.assemble_inherent_impl_for_primitive(lang_def_id);
582 let lang_def_id = lang_items.str_alloc_impl();
583 self.assemble_inherent_impl_for_primitive(lang_def_id);
586 let lang_def_id = lang_items.slice_impl();
587 self.assemble_inherent_impl_for_primitive(lang_def_id);
589 let lang_def_id = lang_items.slice_u8_impl();
590 self.assemble_inherent_impl_for_primitive(lang_def_id);
592 let lang_def_id = lang_items.slice_alloc_impl();
593 self.assemble_inherent_impl_for_primitive(lang_def_id);
595 let lang_def_id = lang_items.slice_u8_alloc_impl();
596 self.assemble_inherent_impl_for_primitive(lang_def_id);
598 ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
599 let lang_def_id = lang_items.const_ptr_impl();
600 self.assemble_inherent_impl_for_primitive(lang_def_id);
602 ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
603 let lang_def_id = lang_items.mut_ptr_impl();
604 self.assemble_inherent_impl_for_primitive(lang_def_id);
606 ty::Int(ast::IntTy::I8) => {
607 let lang_def_id = lang_items.i8_impl();
608 self.assemble_inherent_impl_for_primitive(lang_def_id);
610 ty::Int(ast::IntTy::I16) => {
611 let lang_def_id = lang_items.i16_impl();
612 self.assemble_inherent_impl_for_primitive(lang_def_id);
614 ty::Int(ast::IntTy::I32) => {
615 let lang_def_id = lang_items.i32_impl();
616 self.assemble_inherent_impl_for_primitive(lang_def_id);
618 ty::Int(ast::IntTy::I64) => {
619 let lang_def_id = lang_items.i64_impl();
620 self.assemble_inherent_impl_for_primitive(lang_def_id);
622 ty::Int(ast::IntTy::I128) => {
623 let lang_def_id = lang_items.i128_impl();
624 self.assemble_inherent_impl_for_primitive(lang_def_id);
626 ty::Int(ast::IntTy::Isize) => {
627 let lang_def_id = lang_items.isize_impl();
628 self.assemble_inherent_impl_for_primitive(lang_def_id);
630 ty::Uint(ast::UintTy::U8) => {
631 let lang_def_id = lang_items.u8_impl();
632 self.assemble_inherent_impl_for_primitive(lang_def_id);
634 ty::Uint(ast::UintTy::U16) => {
635 let lang_def_id = lang_items.u16_impl();
636 self.assemble_inherent_impl_for_primitive(lang_def_id);
638 ty::Uint(ast::UintTy::U32) => {
639 let lang_def_id = lang_items.u32_impl();
640 self.assemble_inherent_impl_for_primitive(lang_def_id);
642 ty::Uint(ast::UintTy::U64) => {
643 let lang_def_id = lang_items.u64_impl();
644 self.assemble_inherent_impl_for_primitive(lang_def_id);
646 ty::Uint(ast::UintTy::U128) => {
647 let lang_def_id = lang_items.u128_impl();
648 self.assemble_inherent_impl_for_primitive(lang_def_id);
650 ty::Uint(ast::UintTy::Usize) => {
651 let lang_def_id = lang_items.usize_impl();
652 self.assemble_inherent_impl_for_primitive(lang_def_id);
654 ty::Float(ast::FloatTy::F32) => {
655 let lang_def_id = lang_items.f32_impl();
656 self.assemble_inherent_impl_for_primitive(lang_def_id);
658 let lang_def_id = lang_items.f32_runtime_impl();
659 self.assemble_inherent_impl_for_primitive(lang_def_id);
661 ty::Float(ast::FloatTy::F64) => {
662 let lang_def_id = lang_items.f64_impl();
663 self.assemble_inherent_impl_for_primitive(lang_def_id);
665 let lang_def_id = lang_items.f64_runtime_impl();
666 self.assemble_inherent_impl_for_primitive(lang_def_id);
672 fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
673 if let Some(impl_def_id) = lang_def_id {
674 self.assemble_inherent_impl_probe(impl_def_id);
678 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
679 let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
680 for &impl_def_id in impl_def_ids.iter() {
681 self.assemble_inherent_impl_probe(impl_def_id);
685 fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
686 if !self.impl_dups.insert(impl_def_id) {
687 return; // already visited
690 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
692 for item in self.impl_or_trait_item(impl_def_id) {
693 if !self.has_applicable_self(&item) {
694 // No receiver declared. Not a candidate.
695 self.record_static_candidate(ImplSource(impl_def_id));
699 let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
700 let impl_ty = impl_ty.subst(self.tcx, impl_substs);
702 // Determine the receiver type that the method itself expects.
703 let xform_tys = self.xform_self_ty(&item, impl_ty, impl_substs);
705 // We can't use normalize_associated_types_in as it will pollute the
706 // fcx's fulfillment context after this probe is over.
707 let cause = traits::ObligationCause::misc(self.span, self.body_id);
708 let selcx = &mut traits::SelectionContext::new(self.fcx);
709 let traits::Normalized { value: (xform_self_ty, xform_ret_ty), obligations } =
710 traits::normalize(selcx, self.param_env, cause, &xform_tys);
711 debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}/{:?}",
712 xform_self_ty, xform_ret_ty);
714 self.push_candidate(Candidate {
715 xform_self_ty, xform_ret_ty, item,
716 kind: InherentImplCandidate(impl_substs, obligations),
722 fn assemble_inherent_candidates_from_object(&mut self,
724 debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
727 let principal = match self_ty.sty {
728 ty::Dynamic(ref data, ..) => Some(data),
730 }.and_then(|data| data.principal()).unwrap_or_else(|| {
731 span_bug!(self.span, "non-object {:?} in assemble_inherent_candidates_from_object",
735 // It is illegal to invoke a method on a trait instance that
736 // refers to the `Self` type. An error will be reported by
737 // `enforce_object_limitations()` if the method refers to the
738 // `Self` type anywhere other than the receiver. Here, we use
739 // a substitution that replaces `Self` with the object type
740 // itself. Hence, a `&self` method will wind up with an
741 // argument type like `&Trait`.
742 let trait_ref = principal.with_self_ty(self.tcx, self_ty);
743 self.elaborate_bounds(iter::once(trait_ref), |this, new_trait_ref, item| {
744 let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
746 let (xform_self_ty, xform_ret_ty) =
747 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
748 this.push_candidate(Candidate {
749 xform_self_ty, xform_ret_ty, item,
750 kind: ObjectCandidate,
756 fn assemble_inherent_candidates_from_param(&mut self,
757 param_ty: ty::ParamTy) {
758 // FIXME -- Do we want to commit to this behavior for param bounds?
760 let bounds = self.param_env
763 .filter_map(|predicate| {
765 ty::Predicate::Trait(ref trait_predicate) => {
766 match trait_predicate.skip_binder().trait_ref.self_ty().sty {
767 ty::Param(ref p) if *p == param_ty => {
768 Some(trait_predicate.to_poly_trait_ref())
773 ty::Predicate::Subtype(..) |
774 ty::Predicate::Projection(..) |
775 ty::Predicate::RegionOutlives(..) |
776 ty::Predicate::WellFormed(..) |
777 ty::Predicate::ObjectSafe(..) |
778 ty::Predicate::ClosureKind(..) |
779 ty::Predicate::TypeOutlives(..) |
780 ty::Predicate::ConstEvaluatable(..) => None,
784 self.elaborate_bounds(bounds, |this, poly_trait_ref, item| {
785 let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
787 let (xform_self_ty, xform_ret_ty) =
788 this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
790 // Because this trait derives from a where-clause, it
791 // should not contain any inference variables or other
792 // artifacts. This means it is safe to put into the
793 // `WhereClauseCandidate` and (eventually) into the
794 // `WhereClausePick`.
795 assert!(!trait_ref.substs.needs_infer());
797 this.push_candidate(Candidate {
798 xform_self_ty, xform_ret_ty, item,
799 kind: WhereClauseCandidate(poly_trait_ref),
805 // Do a search through a list of bounds, using a callback to actually
806 // create the candidates.
807 fn elaborate_bounds<F>(&mut self,
808 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
810 where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>,
811 ty::PolyTraitRef<'tcx>,
815 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
816 debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref);
817 for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
818 if !self.has_applicable_self(&item) {
819 self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
821 mk_cand(self, bound_trait_ref, item);
827 fn assemble_extension_candidates_for_traits_in_scope(&mut self,
828 expr_hir_id: hir::HirId)
829 -> Result<(), MethodError<'tcx>> {
830 if expr_hir_id == hir::DUMMY_HIR_ID {
833 let mut duplicates = FxHashSet::default();
834 let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
835 if let Some(applicable_traits) = opt_applicable_traits {
836 for trait_candidate in applicable_traits.iter() {
837 let trait_did = trait_candidate.def_id;
838 if duplicates.insert(trait_did) {
839 let import_id = trait_candidate.import_id;
840 let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
848 fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
849 let mut duplicates = FxHashSet::default();
850 for trait_info in suggest::all_traits(self.tcx) {
851 if duplicates.insert(trait_info.def_id) {
852 self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
858 pub fn matches_return_type(&self,
859 method: &ty::AssociatedItem,
860 self_ty: Option<Ty<'tcx>>,
861 expected: Ty<'tcx>) -> bool {
863 Def::Method(def_id) => {
864 let fty = self.tcx.fn_sig(def_id);
866 let substs = self.fresh_substs_for_item(self.span, method.def_id);
867 let fty = fty.subst(self.tcx, substs);
868 let (fty, _) = self.replace_bound_vars_with_fresh_vars(
874 if let Some(self_ty) = self_ty {
875 if self.at(&ObligationCause::dummy(), self.param_env)
876 .sup(fty.inputs()[0], self_ty)
882 self.can_sub(self.param_env, fty.output(), expected).is_ok()
889 fn assemble_extension_candidates_for_trait(&mut self,
890 import_id: Option<ast::NodeId>,
892 -> Result<(), MethodError<'tcx>> {
893 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
895 let trait_substs = self.fresh_item_substs(trait_def_id);
896 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
898 for item in self.impl_or_trait_item(trait_def_id) {
899 // Check whether `trait_def_id` defines a method with suitable name:
900 if !self.has_applicable_self(&item) {
901 debug!("method has inapplicable self");
902 self.record_static_candidate(TraitSource(trait_def_id));
906 let (xform_self_ty, xform_ret_ty) =
907 self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
908 self.push_candidate(Candidate {
909 xform_self_ty, xform_ret_ty, item, import_id,
910 kind: TraitCandidate(trait_ref),
916 fn candidate_method_names(&self) -> Vec<ast::Ident> {
917 let mut set = FxHashSet::default();
918 let mut names: Vec<_> = self.inherent_candidates
920 .chain(&self.extension_candidates)
921 .filter(|candidate| {
922 if let Some(return_ty) = self.return_type {
923 self.matches_return_type(&candidate.item, None, return_ty)
928 .map(|candidate| candidate.item.ident)
929 .filter(|&name| set.insert(name))
932 // sort them by the name so we have a stable result
933 names.sort_by_cached_key(|n| n.as_str());
937 ///////////////////////////////////////////////////////////////////////////
940 fn pick(mut self) -> PickResult<'tcx> {
941 assert!(self.method_name.is_some());
943 if let Some(r) = self.pick_core() {
947 let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
948 let private_candidate = self.private_candidate.take();
949 let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
951 // things failed, so lets look at all traits, for diagnostic purposes now:
954 let span = self.span;
957 self.assemble_extension_candidates_for_all_traits()?;
959 let out_of_scope_traits = match self.pick_core() {
960 Some(Ok(p)) => vec![p.item.container.id()],
961 //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
962 Some(Err(MethodError::Ambiguity(v))) => {
966 TraitSource(id) => id,
967 ImplSource(impl_id) => {
968 match tcx.trait_id_of_impl(impl_id) {
972 "found inherent method when looking at traits")
980 Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
981 assert!(others.is_empty());
987 if let Some(def) = private_candidate {
988 return Err(MethodError::PrivateMatch(def, out_of_scope_traits));
990 let lev_candidate = self.probe_for_lev_candidate()?;
992 Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
993 unsatisfied_predicates,
999 fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
1000 let steps = self.steps.clone();
1002 // find the first step that works
1006 debug!("pick_core: step={:?}", step);
1007 // skip types that are from a type error or that would require dereferencing
1009 !step.self_ty.references_error() && !step.from_unsafe_deref
1010 }).flat_map(|step| {
1011 let InferOk { value: self_ty, obligations: _ } =
1012 self.fcx.probe_instantiate_query_response(
1013 self.span, &self.orig_steps_var_values, &step.self_ty
1014 ).unwrap_or_else(|_| {
1015 span_bug!(self.span, "{:?} was applicable but now isn't?", step.self_ty)
1017 self.pick_by_value_method(step, self_ty).or_else(|| {
1018 self.pick_autorefd_method(step, self_ty, hir::MutImmutable).or_else(|| {
1019 self.pick_autorefd_method(step, self_ty, hir::MutMutable)
1024 fn pick_by_value_method(&mut self, step: &CandidateStep<'gcx>, self_ty: Ty<'tcx>)
1025 -> Option<PickResult<'tcx>>
1027 //! For each type `T` in the step list, this attempts to find a
1028 //! method where the (transformed) self type is exactly `T`. We
1029 //! do however do one transformation on the adjustment: if we
1030 //! are passing a region pointer in, we will potentially
1031 //! *reborrow* it to a shorter lifetime. This allows us to
1032 //! transparently pass `&mut` pointers, in particular, without
1033 //! consuming them for their entire lifetime.
1039 self.pick_method(self_ty).map(|r| {
1041 pick.autoderefs = step.autoderefs;
1043 // Insert a `&*` or `&mut *` if this is a reference type:
1044 if let ty::Ref(_, _, mutbl) = step.self_ty.value.value.sty {
1045 pick.autoderefs += 1;
1046 pick.autoref = Some(mutbl);
1054 fn pick_autorefd_method(&mut self,
1055 step: &CandidateStep<'gcx>,
1057 mutbl: hir::Mutability)
1058 -> Option<PickResult<'tcx>> {
1061 // In general, during probing we erase regions. See
1062 // `impl_self_ty()` for an explanation.
1063 let region = tcx.types.re_erased;
1065 let autoref_ty = tcx.mk_ref(region,
1069 self.pick_method(autoref_ty).map(|r| {
1071 pick.autoderefs = step.autoderefs;
1072 pick.autoref = Some(mutbl);
1073 pick.unsize = if step.unsize {
1083 fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
1084 debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1086 let mut possibly_unsatisfied_predicates = Vec::new();
1087 let mut unstable_candidates = Vec::new();
1089 for (kind, candidates) in &[
1090 ("inherent", &self.inherent_candidates),
1091 ("extension", &self.extension_candidates),
1093 debug!("searching {} candidates", kind);
1094 let res = self.consider_candidates(
1097 &mut possibly_unsatisfied_predicates,
1098 Some(&mut unstable_candidates),
1100 if let Some(pick) = res {
1101 if !self.is_suggestion.0 && !unstable_candidates.is_empty() {
1102 if let Ok(p) = &pick {
1103 // Emit a lint if there are unstable candidates alongside the stable ones.
1105 // We suppress warning if we're picking the method only because it is a
1107 self.emit_unstable_name_collision_hint(p, &unstable_candidates);
1114 debug!("searching unstable candidates");
1115 let res = self.consider_candidates(
1117 unstable_candidates.into_iter().map(|(c, _)| c),
1118 &mut possibly_unsatisfied_predicates,
1122 self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1127 fn consider_candidates<'b, ProbesIter>(
1131 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>,
1132 unstable_candidates: Option<&mut Vec<(&'b Candidate<'tcx>, Symbol)>>,
1133 ) -> Option<PickResult<'tcx>>
1135 ProbesIter: Iterator<Item = &'b Candidate<'tcx>> + Clone,
1137 let mut applicable_candidates: Vec<_> = probes.clone()
1139 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1141 .filter(|&(_, status)| status != ProbeResult::NoMatch)
1144 debug!("applicable_candidates: {:?}", applicable_candidates);
1146 if applicable_candidates.len() > 1 {
1147 if let Some(pick) = self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1148 return Some(Ok(pick));
1152 if let Some(uc) = unstable_candidates {
1153 applicable_candidates.retain(|&(p, _)| {
1154 if let stability::EvalResult::Deny { feature, .. } =
1155 self.tcx.eval_stability(p.item.def_id, None, self.span)
1157 uc.push((p, feature));
1164 if applicable_candidates.len() > 1 {
1165 let sources = probes
1166 .map(|p| self.candidate_source(p, self_ty))
1168 return Some(Err(MethodError::Ambiguity(sources)));
1171 applicable_candidates.pop().map(|(probe, status)| {
1172 if status == ProbeResult::Match {
1173 Ok(probe.to_unadjusted_pick())
1175 Err(MethodError::BadReturnType)
1180 fn emit_unstable_name_collision_hint(
1182 stable_pick: &Pick<'_>,
1183 unstable_candidates: &[(&Candidate<'tcx>, Symbol)],
1185 let mut diag = self.tcx.struct_span_lint_hir(
1186 lint::builtin::UNSTABLE_NAME_COLLISIONS,
1189 "a method with this name may be added to the standard library in the future",
1192 // FIXME: This should be a `span_suggestion` instead of `help`
1193 // However `self.span` only
1194 // highlights the method name, so we can't use it. Also consider reusing the code from
1195 // `report_method_error()`.
1197 "call with fully qualified syntax `{}(...)` to keep using the current method",
1198 self.tcx.item_path_str(stable_pick.item.def_id),
1201 if nightly_options::is_nightly_build() {
1202 for (candidate, feature) in unstable_candidates {
1204 "add #![feature({})] to the crate attributes to enable `{}`",
1206 self.tcx.item_path_str(candidate.item.def_id),
1214 fn select_trait_candidate(&self, trait_ref: ty::TraitRef<'tcx>)
1215 -> traits::SelectionResult<'tcx, traits::Selection<'tcx>>
1217 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1219 trait_ref.to_poly_trait_ref().to_poly_trait_predicate();
1220 let obligation = traits::Obligation::new(cause, self.param_env, predicate);
1221 traits::SelectionContext::new(self).select(&obligation)
1224 fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>)
1227 match candidate.kind {
1228 InherentImplCandidate(..) => ImplSource(candidate.item.container.id()),
1230 WhereClauseCandidate(_) => TraitSource(candidate.item.container.id()),
1231 TraitCandidate(trait_ref) => self.probe(|_| {
1232 let _ = self.at(&ObligationCause::dummy(), self.param_env)
1233 .sup(candidate.xform_self_ty, self_ty);
1234 match self.select_trait_candidate(trait_ref) {
1235 Ok(Some(traits::Vtable::VtableImpl(ref impl_data))) => {
1236 // If only a single impl matches, make the error message point
1238 ImplSource(impl_data.impl_def_id)
1241 TraitSource(candidate.item.container.id())
1248 fn consider_probe(&self,
1250 probe: &Candidate<'tcx>,
1251 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1253 debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1256 // First check that the self type can be related.
1257 let sub_obligations = match self.at(&ObligationCause::dummy(), self.param_env)
1258 .sup(probe.xform_self_ty, self_ty) {
1259 Ok(InferOk { obligations, value: () }) => obligations,
1261 debug!("--> cannot relate self-types");
1262 return ProbeResult::NoMatch;
1266 let mut result = ProbeResult::Match;
1267 let selcx = &mut traits::SelectionContext::new(self);
1268 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1270 // If so, impls may carry other conditions (e.g., where
1271 // clauses) that must be considered. Make sure that those
1272 // match as well (or at least may match, sometimes we
1273 // don't have enough information to fully evaluate).
1274 let candidate_obligations : Vec<_> = match probe.kind {
1275 InherentImplCandidate(ref substs, ref ref_obligations) => {
1276 // Check whether the impl imposes obligations we have to worry about.
1277 let impl_def_id = probe.item.container.id();
1278 let impl_bounds = self.tcx.predicates_of(impl_def_id);
1279 let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1280 let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1281 traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
1283 // Convert the bounds into obligations.
1284 let impl_obligations = traits::predicates_for_generics(
1285 cause, self.param_env, &impl_bounds);
1287 debug!("impl_obligations={:?}", impl_obligations);
1288 impl_obligations.into_iter()
1289 .chain(norm_obligations.into_iter())
1290 .chain(ref_obligations.iter().cloned())
1295 WhereClauseCandidate(..) => {
1296 // These have no additional conditions to check.
1300 TraitCandidate(trait_ref) => {
1301 let predicate = trait_ref.to_predicate();
1303 traits::Obligation::new(cause, self.param_env, predicate);
1304 if !self.predicate_may_hold(&obligation) {
1305 if self.probe(|_| self.select_trait_candidate(trait_ref).is_err()) {
1306 // This candidate's primary obligation doesn't even
1307 // select - don't bother registering anything in
1308 // `potentially_unsatisfied_predicates`.
1309 return ProbeResult::NoMatch;
1311 // Some nested subobligation of this predicate
1314 // FIXME: try to find the exact nested subobligation
1315 // and point at it rather than reporting the entire
1317 result = ProbeResult::NoMatch;
1318 let trait_ref = self.resolve_type_vars_if_possible(&trait_ref);
1319 possibly_unsatisfied_predicates.push(trait_ref);
1326 debug!("consider_probe - candidate_obligations={:?} sub_obligations={:?}",
1327 candidate_obligations, sub_obligations);
1329 // Evaluate those obligations to see if they might possibly hold.
1330 for o in candidate_obligations.into_iter().chain(sub_obligations) {
1331 let o = self.resolve_type_vars_if_possible(&o);
1332 if !self.predicate_may_hold(&o) {
1333 result = ProbeResult::NoMatch;
1334 if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1335 possibly_unsatisfied_predicates.push(pred.skip_binder().trait_ref);
1340 if let ProbeResult::Match = result {
1341 if let (Some(return_ty), Some(xform_ret_ty)) =
1342 (self.return_type, probe.xform_ret_ty)
1344 let xform_ret_ty = self.resolve_type_vars_if_possible(&xform_ret_ty);
1345 debug!("comparing return_ty {:?} with xform ret ty {:?}",
1347 probe.xform_ret_ty);
1348 if self.at(&ObligationCause::dummy(), self.param_env)
1349 .sup(return_ty, xform_ret_ty)
1352 return ProbeResult::BadReturnType;
1361 /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1362 /// same trait, but we don't know which impl to use. In this case, since in all cases the
1363 /// external interface of the method can be determined from the trait, it's ok not to decide.
1364 /// We can basically just collapse all of the probes for various impls into one where-clause
1365 /// probe. This will result in a pending obligation so when more type-info is available we can
1366 /// make the final decision.
1368 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1371 /// trait Foo { ... }
1372 /// impl Foo for Vec<int> { ... }
1373 /// impl Foo for Vec<usize> { ... }
1376 /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1377 /// use, so it's ok to just commit to "using the method from the trait Foo".
1378 fn collapse_candidates_to_trait_pick(&self, probes: &[(&Candidate<'tcx>, ProbeResult)])
1379 -> Option<Pick<'tcx>>
1381 // Do all probes correspond to the same trait?
1382 let container = probes[0].0.item.container;
1383 if let ty::ImplContainer(_) = container {
1386 if probes[1..].iter().any(|&(p, _)| p.item.container != container) {
1390 // FIXME: check the return type here somehow.
1391 // If so, just use this trait and call it a day.
1393 item: probes[0].0.item.clone(),
1395 import_id: probes[0].0.import_id,
1402 /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
1403 /// candidate method where the method name may have been misspelt. Similarly to other
1404 /// Levenshtein based suggestions, we provide at most one such suggestion.
1405 fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssociatedItem>, MethodError<'tcx>> {
1406 debug!("Probing for method names similar to {:?}",
1409 let steps = self.steps.clone();
1411 let mut pcx = ProbeContext::new(self.fcx, self.span, self.mode, self.method_name,
1413 self.orig_steps_var_values.clone(),
1414 steps, IsSuggestion(true));
1415 pcx.allow_similar_names = true;
1416 pcx.assemble_inherent_candidates();
1417 pcx.assemble_extension_candidates_for_traits_in_scope(hir::DUMMY_HIR_ID)?;
1419 let method_names = pcx.candidate_method_names();
1420 pcx.allow_similar_names = false;
1421 let applicable_close_candidates: Vec<ty::AssociatedItem> = method_names
1423 .filter_map(|&method_name| {
1425 pcx.method_name = Some(method_name);
1426 pcx.assemble_inherent_candidates();
1427 pcx.assemble_extension_candidates_for_traits_in_scope(hir::DUMMY_HIR_ID)
1428 .ok().map_or(None, |_| {
1430 .and_then(|pick| pick.ok())
1431 .and_then(|pick| Some(pick.item))
1436 if applicable_close_candidates.is_empty() {
1440 let names = applicable_close_candidates.iter().map(|cand| &cand.ident.name);
1441 find_best_match_for_name(names,
1442 &self.method_name.unwrap().as_str(),
1445 Ok(applicable_close_candidates
1447 .find(|method| method.ident.name == best_name))
1452 ///////////////////////////////////////////////////////////////////////////
1454 fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1455 // "Fast track" -- check for usage of sugar when in method call
1458 // In Path mode (i.e., resolving a value like `T::next`), consider any
1459 // associated value (i.e., methods, constants) but not types.
1461 Mode::MethodCall => item.method_has_self_argument,
1462 Mode::Path => match item.kind {
1463 ty::AssociatedKind::Existential |
1464 ty::AssociatedKind::Type => false,
1465 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1468 // FIXME -- check for types that deref to `Self`,
1469 // like `Rc<Self>` and so on.
1471 // Note also that the current code will break if this type
1472 // includes any of the type parameters defined on the method
1473 // -- but this could be overcome.
1476 fn record_static_candidate(&mut self, source: CandidateSource) {
1477 self.static_candidates.push(source);
1480 fn xform_self_ty(&self,
1481 item: &ty::AssociatedItem,
1483 substs: SubstsRef<'tcx>)
1484 -> (Ty<'tcx>, Option<Ty<'tcx>>) {
1485 if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1486 let sig = self.xform_method_sig(item.def_id, substs);
1487 (sig.inputs()[0], Some(sig.output()))
1493 fn xform_method_sig(&self,
1495 substs: SubstsRef<'tcx>)
1498 let fn_sig = self.tcx.fn_sig(method);
1499 debug!("xform_self_ty(fn_sig={:?}, substs={:?})",
1503 assert!(!substs.has_escaping_bound_vars());
1505 // It is possible for type parameters or early-bound lifetimes
1506 // to appear in the signature of `self`. The substitutions we
1507 // are given do not include type/lifetime parameters for the
1508 // method yet. So create fresh variables here for those too,
1509 // if there are any.
1510 let generics = self.tcx.generics_of(method);
1511 assert_eq!(substs.len(), generics.parent_count as usize);
1513 // Erase any late-bound regions from the method and substitute
1514 // in the values from the substitution.
1515 let xform_fn_sig = self.erase_late_bound_regions(&fn_sig);
1517 if generics.params.is_empty() {
1518 xform_fn_sig.subst(self.tcx, substs)
1520 let substs = InternalSubsts::for_item(self.tcx, method, |param, _| {
1521 let i = param.index as usize;
1522 if i < substs.len() {
1526 GenericParamDefKind::Lifetime => {
1527 // In general, during probe we erase regions. See
1528 // `impl_self_ty()` for an explanation.
1529 self.tcx.types.re_erased.into()
1531 GenericParamDefKind::Type { .. }
1532 | GenericParamDefKind::Const => {
1533 self.var_for_def(self.span, param)
1538 xform_fn_sig.subst(self.tcx, substs)
1542 /// Gets the type of an impl and generate substitutions with placeholders.
1543 fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, SubstsRef<'tcx>) {
1544 (self.tcx.type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1547 fn fresh_item_substs(&self, def_id: DefId) -> SubstsRef<'tcx> {
1548 InternalSubsts::for_item(self.tcx, def_id, |param, _| {
1550 GenericParamDefKind::Lifetime => self.tcx.types.re_erased.into(),
1551 GenericParamDefKind::Type { .. } => {
1552 self.next_ty_var(TypeVariableOrigin::SubstitutionPlaceholder(
1553 self.tcx.def_span(def_id))).into()
1555 GenericParamDefKind::Const { .. } => {
1556 unimplemented!() // FIXME(const_generics)
1562 /// Replaces late-bound-regions bound by `value` with `'static` using
1563 /// `ty::erase_late_bound_regions`.
1565 /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1566 /// method matching. It is reasonable during the probe phase because we don't consider region
1567 /// relationships at all. Therefore, we can just replace all the region variables with 'static
1568 /// rather than creating fresh region variables. This is nice for two reasons:
1570 /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1571 /// particular method call, it winds up creating fewer types overall, which helps for memory
1572 /// usage. (Admittedly, this is a rather small effect, though measurable.)
1574 /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1575 /// late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1576 /// regions with actual region variables as is proper, we'd have to ensure that the same
1577 /// region got replaced with the same variable, which requires a bit more coordination
1578 /// and/or tracking the substitution and
1580 fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1581 where T: TypeFoldable<'tcx>
1583 self.tcx.erase_late_bound_regions(value)
1586 /// Finds the method with the appropriate name (or return type, as the case may be). If
1587 /// `allow_similar_names` is set, find methods with close-matching names.
1588 fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1589 if let Some(name) = self.method_name {
1590 if self.allow_similar_names {
1591 let max_dist = max(name.as_str().len(), 3) / 3;
1592 self.tcx.associated_items(def_id)
1594 let dist = lev_distance(&*name.as_str(), &x.ident.as_str());
1595 Namespace::from(x.kind) == Namespace::Value && dist > 0
1601 .associated_item(def_id, name, Namespace::Value)
1602 .map_or(Vec::new(), |x| vec![x])
1605 self.tcx.associated_items(def_id).collect()
1610 impl<'tcx> Candidate<'tcx> {
1611 fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1613 item: self.item.clone(),
1614 kind: match self.kind {
1615 InherentImplCandidate(..) => InherentImplPick,
1616 ObjectCandidate => ObjectPick,
1617 TraitCandidate(_) => TraitPick,
1618 WhereClauseCandidate(ref trait_ref) => {
1619 // Only trait derived from where-clauses should
1620 // appear here, so they should not contain any
1621 // inference variables or other artifacts. This
1622 // means they are safe to put into the
1623 // `WhereClausePick`.
1625 !trait_ref.skip_binder().substs.needs_infer()
1626 && !trait_ref.skip_binder().substs.has_placeholders()
1629 WhereClausePick(trait_ref.clone())
1632 import_id: self.import_id,