1 use super::MethodError;
2 use super::NoMatchData;
3 use super::{CandidateSource, ImplSource, TraitSource};
6 use check::autoderef::{self, Autoderef};
8 use hir::def_id::DefId;
10 use namespace::Namespace;
12 use rustc_data_structures::sync::Lrc;
15 use rustc::session::config::nightly_options;
16 use rustc::ty::subst::{Subst, Substs};
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 xform_self_ty: Ty<'tcx>,
89 xform_ret_ty: Option<Ty<'tcx>>,
90 item: ty::AssociatedItem,
91 kind: CandidateKind<'tcx>,
92 import_id: Option<ast::NodeId>,
96 enum CandidateKind<'tcx> {
97 InherentImplCandidate(&'tcx Substs<'tcx>,
98 // Normalize obligations
99 Vec<traits::PredicateObligation<'tcx>>),
101 TraitCandidate(ty::TraitRef<'tcx>),
102 WhereClauseCandidate(// Trait
103 ty::PolyTraitRef<'tcx>),
106 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
113 #[derive(Debug, PartialEq, Clone)]
114 pub struct Pick<'tcx> {
115 pub item: ty::AssociatedItem,
116 pub kind: PickKind<'tcx>,
117 pub import_id: Option<ast::NodeId>,
119 // Indicates that the source expression should be autoderef'd N times
121 // A = expr | *expr | **expr | ...
122 pub autoderefs: usize,
124 // Indicates that an autoref is applied after the optional autoderefs
126 // B = A | &A | &mut A
127 pub autoref: Option<hir::Mutability>,
129 // Indicates that the source expression should be "unsized" to a
130 // target type. This should probably eventually go away in favor
131 // of just coercing method receivers.
134 pub unsize: Option<Ty<'tcx>>,
137 #[derive(Clone, Debug, PartialEq, Eq)]
138 pub enum PickKind<'tcx> {
142 WhereClausePick(// Trait
143 ty::PolyTraitRef<'tcx>),
146 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
148 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
150 // An expression of the form `receiver.method_name(...)`.
151 // Autoderefs are performed on `receiver`, lookup is done based on the
152 // `self` argument of the method, and static methods aren't considered.
154 // An expression of the form `Type::item` or `<T>::item`.
155 // No autoderefs are performed, lookup is done based on the type each
156 // implementation is for, and static methods are included.
160 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
161 pub enum ProbeScope {
162 // Assemble candidates coming only from traits in scope.
165 // Assemble candidates coming from all traits.
169 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
170 /// This is used to offer suggestions to users. It returns methods
171 /// that could have been called which have the desired return
172 /// type. Some effort is made to rule out methods that, if called,
173 /// would result in an error (basically, the same criteria we
174 /// would use to decide if a method is a plausible fit for
175 /// ambiguity purposes).
176 pub fn probe_for_return_type(&self,
179 return_type: Ty<'tcx>,
181 scope_expr_id: ast::NodeId)
182 -> Vec<ty::AssociatedItem> {
183 debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
188 self.probe_op(span, mode, None, Some(return_type), IsSuggestion(true),
189 self_ty, scope_expr_id, ProbeScope::AllTraits,
190 |probe_cx| Ok(probe_cx.candidate_method_names()))
194 .flat_map(|&method_name| {
196 span, mode, Some(method_name), Some(return_type),
197 IsSuggestion(true), self_ty, scope_expr_id,
198 ProbeScope::AllTraits, |probe_cx| probe_cx.pick()
199 ).ok().map(|pick| pick.item)
204 pub fn probe_for_name(&self,
207 item_name: ast::Ident,
208 is_suggestion: IsSuggestion,
210 scope_expr_id: ast::NodeId,
212 -> PickResult<'tcx> {
213 debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
225 |probe_cx| probe_cx.pick())
228 fn probe_op<OP,R>(&'a self,
231 method_name: Option<ast::Ident>,
232 return_type: Option<Ty<'tcx>>,
233 is_suggestion: IsSuggestion,
235 scope_expr_id: ast::NodeId,
238 -> Result<R, MethodError<'tcx>>
239 where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
241 let mut orig_values = OriginalQueryValues::default();
242 let param_env_and_self_ty =
243 self.infcx.canonicalize_query(
245 param_env: self.param_env,
247 }, &mut orig_values);
249 let steps = if mode == Mode::MethodCall {
250 self.tcx.method_autoderef_steps(param_env_and_self_ty)
252 self.infcx.probe(|_| {
253 // Mode::Path - the deref steps is "trivial". This turns
254 // our CanonicalQuery into a "trivial" QueryResponse. This
255 // is a bit inefficient, but I don't think that writing
256 // special handling for this "trivial case" is a good idea.
258 let infcx = &self.infcx;
262 }, canonical_inference_vars) =
263 infcx.instantiate_canonical_with_fresh_inference_vars(
264 span, ¶m_env_and_self_ty);
265 debug!("probe_op: Mode::Path, param_env_and_self_ty={:?} self_ty={:?}",
266 param_env_and_self_ty, self_ty);
267 MethodAutoderefStepsResult {
268 steps: Lrc::new(vec![CandidateStep {
269 self_ty: self.make_query_response_ignoring_pending_obligations(
270 canonical_inference_vars, self_ty),
272 from_unsafe_deref: false,
276 reached_recursion_limit: false
281 // If our autoderef loop had reached the recursion limit,
282 // report an overflow error, but continue going on with
283 // the truncated autoderef list.
284 if steps.reached_recursion_limit {
286 let ty = &steps.steps.last().unwrap_or_else(|| {
287 span_bug!(span, "reached the recursion limit in 0 steps?")
289 let ty = self.probe_instantiate_query_response(span, &orig_values, ty)
290 .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
291 autoderef::report_autoderef_recursion_limit_error(self.tcx, span,
297 // If we encountered an `_` type or an error type during autoderef, this is
299 if let Some(bad_ty) = &steps.opt_bad_ty {
301 // Ambiguity was encountered during a suggestion. Just keep going.
302 debug!("ProbeContext: encountered ambiguity in suggestion");
303 } else if bad_ty.reached_raw_pointer && !self.tcx.features().arbitrary_self_types {
304 // this case used to be allowed by the compiler,
305 // so we do a future-compat lint here for the 2015 edition
306 // (see https://github.com/rust-lang/rust/issues/46906)
307 if self.tcx.sess.rust_2018() {
308 span_err!(self.tcx.sess, span, E0699,
309 "the type of this value must be known \
310 to call a method on a raw pointer on it");
313 lint::builtin::TYVAR_BEHIND_RAW_POINTER,
316 "type annotations needed");
319 // Encountered a real ambiguity, so abort the lookup. If `ty` is not
320 // an `Err`, report the right "type annotations needed" error pointing
323 let ty = self.probe_instantiate_query_response(span, &orig_values, ty)
324 .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
325 let ty = self.structurally_resolved_type(span, ty.value);
326 assert_eq!(ty, self.tcx.types.err);
327 return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
335 debug!("ProbeContext: steps for self_ty={:?} are {:?}",
340 // this creates one big transaction so that all type variables etc
341 // that we create during the probe process are removed later
343 let mut probe_cx = ProbeContext::new(
344 self, span, mode, method_name, return_type, orig_values,
345 steps.steps, is_suggestion,
348 probe_cx.assemble_inherent_candidates();
350 ProbeScope::TraitsInScope =>
351 probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?,
352 ProbeScope::AllTraits =>
353 probe_cx.assemble_extension_candidates_for_all_traits()?,
360 pub fn provide(providers: &mut ty::query::Providers) {
361 providers.method_autoderef_steps = method_autoderef_steps;
364 fn method_autoderef_steps<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
365 goal: CanonicalTyGoal<'tcx>)
366 -> MethodAutoderefStepsResult<'gcx>
368 debug!("method_autoderef_steps({:?})", goal);
370 tcx.infer_ctxt().enter_with_canonical(DUMMY_SP, &goal, |ref infcx, goal, inference_vars| {
371 let ParamEnvAnd { param_env, value: self_ty } = goal;
373 let mut autoderef = Autoderef::new(infcx, param_env, ast::DUMMY_NODE_ID, DUMMY_SP, self_ty)
374 .include_raw_pointers()
376 let mut reached_raw_pointer = false;
377 let mut steps: Vec<_> = autoderef.by_ref()
379 let step = CandidateStep {
380 self_ty: infcx.make_query_response_ignoring_pending_obligations(
381 inference_vars.clone(), ty),
383 from_unsafe_deref: reached_raw_pointer,
386 if let ty::RawPtr(_) = ty.sty {
387 // all the subsequent steps will be from_unsafe_deref
388 reached_raw_pointer = true;
394 let final_ty = autoderef.maybe_ambiguous_final_ty();
395 let opt_bad_ty = match final_ty.sty {
396 ty::Infer(ty::TyVar(_)) |
398 Some(MethodAutoderefBadTy {
400 ty: infcx.make_query_response_ignoring_pending_obligations(
401 inference_vars, final_ty)
404 ty::Array(elem_ty, _) => {
405 let dereferences = steps.len() - 1;
407 steps.push(CandidateStep {
408 self_ty: infcx.make_query_response_ignoring_pending_obligations(
409 inference_vars, infcx.tcx.mk_slice(elem_ty)),
410 autoderefs: dereferences,
411 // this could be from an unsafe deref if we had
412 // a *mut/const [T; N]
413 from_unsafe_deref: reached_raw_pointer,
422 debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
424 MethodAutoderefStepsResult {
425 steps: Lrc::new(steps),
426 opt_bad_ty: opt_bad_ty.map(Lrc::new),
427 reached_recursion_limit: autoderef.reached_recursion_limit()
433 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
434 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
437 method_name: Option<ast::Ident>,
438 return_type: Option<Ty<'tcx>>,
439 orig_steps_var_values: OriginalQueryValues<'tcx>,
440 steps: Lrc<Vec<CandidateStep<'gcx>>>,
441 is_suggestion: IsSuggestion)
442 -> ProbeContext<'a, 'gcx, 'tcx> {
449 inherent_candidates: Vec::new(),
450 extension_candidates: Vec::new(),
451 impl_dups: FxHashSet::default(),
452 orig_steps_var_values,
454 static_candidates: Vec::new(),
455 allow_similar_names: false,
456 private_candidate: None,
457 unsatisfied_predicates: Vec::new(),
462 fn reset(&mut self) {
463 self.inherent_candidates.clear();
464 self.extension_candidates.clear();
465 self.impl_dups.clear();
466 self.static_candidates.clear();
467 self.private_candidate = None;
470 ///////////////////////////////////////////////////////////////////////////
471 // CANDIDATE ASSEMBLY
473 fn push_candidate(&mut self,
474 candidate: Candidate<'tcx>,
477 let is_accessible = if let Some(name) = self.method_name {
478 let item = candidate.item;
479 let def_scope = self.tcx.adjust_ident(name, item.container.id(), self.body_id).1;
480 item.vis.is_accessible_from(def_scope, self.tcx)
486 self.inherent_candidates.push(candidate);
488 self.extension_candidates.push(candidate);
490 } else if self.private_candidate.is_none() {
491 self.private_candidate = Some(candidate.item.def());
495 fn assemble_inherent_candidates(&mut self) {
496 let steps = self.steps.clone();
497 for step in steps.iter() {
498 self.assemble_probe(&step.self_ty);
502 fn assemble_probe(&mut self, self_ty: &Canonical<'gcx, QueryResponse<'gcx, Ty<'gcx>>>) {
503 debug!("assemble_probe: self_ty={:?}", self_ty);
504 let lang_items = self.tcx.lang_items();
506 match self_ty.value.value.sty {
507 ty::Dynamic(ref data, ..) => {
508 if let Some(p) = data.principal() {
509 let InferOk { value: instantiated_self_ty, obligations: _ } =
510 self.fcx.probe_instantiate_query_response(
511 self.span, &self.orig_steps_var_values, self_ty)
512 .unwrap_or_else(|_| {
513 span_bug!(self.span, "{:?} was applicable but now isn't?", self_ty)
515 self.assemble_inherent_candidates_from_object(instantiated_self_ty);
516 self.assemble_inherent_impl_candidates_for_type(p.def_id());
520 self.assemble_inherent_impl_candidates_for_type(def.did);
522 ty::Foreign(did) => {
523 self.assemble_inherent_impl_candidates_for_type(did);
526 self.assemble_inherent_candidates_from_param(p);
529 let lang_def_id = lang_items.char_impl();
530 self.assemble_inherent_impl_for_primitive(lang_def_id);
533 let lang_def_id = lang_items.str_impl();
534 self.assemble_inherent_impl_for_primitive(lang_def_id);
536 let lang_def_id = lang_items.str_alloc_impl();
537 self.assemble_inherent_impl_for_primitive(lang_def_id);
540 let lang_def_id = lang_items.slice_impl();
541 self.assemble_inherent_impl_for_primitive(lang_def_id);
543 let lang_def_id = lang_items.slice_u8_impl();
544 self.assemble_inherent_impl_for_primitive(lang_def_id);
546 let lang_def_id = lang_items.slice_alloc_impl();
547 self.assemble_inherent_impl_for_primitive(lang_def_id);
549 let lang_def_id = lang_items.slice_u8_alloc_impl();
550 self.assemble_inherent_impl_for_primitive(lang_def_id);
552 ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
553 let lang_def_id = lang_items.const_ptr_impl();
554 self.assemble_inherent_impl_for_primitive(lang_def_id);
556 ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
557 let lang_def_id = lang_items.mut_ptr_impl();
558 self.assemble_inherent_impl_for_primitive(lang_def_id);
560 ty::Int(ast::IntTy::I8) => {
561 let lang_def_id = lang_items.i8_impl();
562 self.assemble_inherent_impl_for_primitive(lang_def_id);
564 ty::Int(ast::IntTy::I16) => {
565 let lang_def_id = lang_items.i16_impl();
566 self.assemble_inherent_impl_for_primitive(lang_def_id);
568 ty::Int(ast::IntTy::I32) => {
569 let lang_def_id = lang_items.i32_impl();
570 self.assemble_inherent_impl_for_primitive(lang_def_id);
572 ty::Int(ast::IntTy::I64) => {
573 let lang_def_id = lang_items.i64_impl();
574 self.assemble_inherent_impl_for_primitive(lang_def_id);
576 ty::Int(ast::IntTy::I128) => {
577 let lang_def_id = lang_items.i128_impl();
578 self.assemble_inherent_impl_for_primitive(lang_def_id);
580 ty::Int(ast::IntTy::Isize) => {
581 let lang_def_id = lang_items.isize_impl();
582 self.assemble_inherent_impl_for_primitive(lang_def_id);
584 ty::Uint(ast::UintTy::U8) => {
585 let lang_def_id = lang_items.u8_impl();
586 self.assemble_inherent_impl_for_primitive(lang_def_id);
588 ty::Uint(ast::UintTy::U16) => {
589 let lang_def_id = lang_items.u16_impl();
590 self.assemble_inherent_impl_for_primitive(lang_def_id);
592 ty::Uint(ast::UintTy::U32) => {
593 let lang_def_id = lang_items.u32_impl();
594 self.assemble_inherent_impl_for_primitive(lang_def_id);
596 ty::Uint(ast::UintTy::U64) => {
597 let lang_def_id = lang_items.u64_impl();
598 self.assemble_inherent_impl_for_primitive(lang_def_id);
600 ty::Uint(ast::UintTy::U128) => {
601 let lang_def_id = lang_items.u128_impl();
602 self.assemble_inherent_impl_for_primitive(lang_def_id);
604 ty::Uint(ast::UintTy::Usize) => {
605 let lang_def_id = lang_items.usize_impl();
606 self.assemble_inherent_impl_for_primitive(lang_def_id);
608 ty::Float(ast::FloatTy::F32) => {
609 let lang_def_id = lang_items.f32_impl();
610 self.assemble_inherent_impl_for_primitive(lang_def_id);
612 let lang_def_id = lang_items.f32_runtime_impl();
613 self.assemble_inherent_impl_for_primitive(lang_def_id);
615 ty::Float(ast::FloatTy::F64) => {
616 let lang_def_id = lang_items.f64_impl();
617 self.assemble_inherent_impl_for_primitive(lang_def_id);
619 let lang_def_id = lang_items.f64_runtime_impl();
620 self.assemble_inherent_impl_for_primitive(lang_def_id);
626 fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
627 if let Some(impl_def_id) = lang_def_id {
628 self.assemble_inherent_impl_probe(impl_def_id);
632 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
633 let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
634 for &impl_def_id in impl_def_ids.iter() {
635 self.assemble_inherent_impl_probe(impl_def_id);
639 fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
640 if !self.impl_dups.insert(impl_def_id) {
641 return; // already visited
644 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
646 for item in self.impl_or_trait_item(impl_def_id) {
647 if !self.has_applicable_self(&item) {
648 // No receiver declared. Not a candidate.
649 self.record_static_candidate(ImplSource(impl_def_id));
653 let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
654 let impl_ty = impl_ty.subst(self.tcx, impl_substs);
656 // Determine the receiver type that the method itself expects.
657 let xform_tys = self.xform_self_ty(&item, impl_ty, impl_substs);
659 // We can't use normalize_associated_types_in as it will pollute the
660 // fcx's fulfillment context after this probe is over.
661 let cause = traits::ObligationCause::misc(self.span, self.body_id);
662 let selcx = &mut traits::SelectionContext::new(self.fcx);
663 let traits::Normalized { value: (xform_self_ty, xform_ret_ty), obligations } =
664 traits::normalize(selcx, self.param_env, cause, &xform_tys);
665 debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}/{:?}",
666 xform_self_ty, xform_ret_ty);
668 self.push_candidate(Candidate {
669 xform_self_ty, xform_ret_ty, item,
670 kind: InherentImplCandidate(impl_substs, obligations),
676 fn assemble_inherent_candidates_from_object(&mut self,
678 debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
681 let principal = match self_ty.sty {
682 ty::Dynamic(ref data, ..) => Some(data),
684 }.and_then(|data| data.principal()).unwrap_or_else(|| {
685 span_bug!(self.span, "non-object {:?} in assemble_inherent_candidates_from_object",
689 // It is illegal to invoke a method on a trait instance that
690 // refers to the `Self` type. An error will be reported by
691 // `enforce_object_limitations()` if the method refers to the
692 // `Self` type anywhere other than the receiver. Here, we use
693 // a substitution that replaces `Self` with the object type
694 // itself. Hence, a `&self` method will wind up with an
695 // argument type like `&Trait`.
696 let trait_ref = principal.with_self_ty(self.tcx, self_ty);
697 self.elaborate_bounds(iter::once(trait_ref), |this, new_trait_ref, item| {
698 let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
700 let (xform_self_ty, xform_ret_ty) =
701 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
702 this.push_candidate(Candidate {
703 xform_self_ty, xform_ret_ty, item,
704 kind: ObjectCandidate,
710 fn assemble_inherent_candidates_from_param(&mut self,
711 param_ty: ty::ParamTy) {
712 // FIXME -- Do we want to commit to this behavior for param bounds?
714 let bounds = self.param_env
717 .filter_map(|predicate| {
719 ty::Predicate::Trait(ref trait_predicate) => {
720 match trait_predicate.skip_binder().trait_ref.self_ty().sty {
721 ty::Param(ref p) if *p == param_ty => {
722 Some(trait_predicate.to_poly_trait_ref())
727 ty::Predicate::Subtype(..) |
728 ty::Predicate::Projection(..) |
729 ty::Predicate::RegionOutlives(..) |
730 ty::Predicate::WellFormed(..) |
731 ty::Predicate::ObjectSafe(..) |
732 ty::Predicate::ClosureKind(..) |
733 ty::Predicate::TypeOutlives(..) |
734 ty::Predicate::ConstEvaluatable(..) => None,
738 self.elaborate_bounds(bounds, |this, poly_trait_ref, item| {
739 let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
741 let (xform_self_ty, xform_ret_ty) =
742 this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
744 // Because this trait derives from a where-clause, it
745 // should not contain any inference variables or other
746 // artifacts. This means it is safe to put into the
747 // `WhereClauseCandidate` and (eventually) into the
748 // `WhereClausePick`.
749 assert!(!trait_ref.substs.needs_infer());
751 this.push_candidate(Candidate {
752 xform_self_ty, xform_ret_ty, item,
753 kind: WhereClauseCandidate(poly_trait_ref),
759 // Do a search through a list of bounds, using a callback to actually
760 // create the candidates.
761 fn elaborate_bounds<F>(&mut self,
762 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
764 where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>,
765 ty::PolyTraitRef<'tcx>,
769 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
770 debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref);
771 for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
772 if !self.has_applicable_self(&item) {
773 self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
775 mk_cand(self, bound_trait_ref, item);
781 fn assemble_extension_candidates_for_traits_in_scope(&mut self,
782 expr_id: ast::NodeId)
783 -> Result<(), MethodError<'tcx>> {
784 if expr_id == ast::DUMMY_NODE_ID {
787 let mut duplicates = FxHashSet::default();
788 let expr_hir_id = self.tcx.hir().node_to_hir_id(expr_id);
789 let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
790 if let Some(applicable_traits) = opt_applicable_traits {
791 for trait_candidate in applicable_traits.iter() {
792 let trait_did = trait_candidate.def_id;
793 if duplicates.insert(trait_did) {
794 let import_id = trait_candidate.import_id;
795 let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
803 fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
804 let mut duplicates = FxHashSet::default();
805 for trait_info in suggest::all_traits(self.tcx) {
806 if duplicates.insert(trait_info.def_id) {
807 self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
813 pub fn matches_return_type(&self,
814 method: &ty::AssociatedItem,
815 self_ty: Option<Ty<'tcx>>,
816 expected: Ty<'tcx>) -> bool {
818 Def::Method(def_id) => {
819 let fty = self.tcx.fn_sig(def_id);
821 let substs = self.fresh_substs_for_item(self.span, method.def_id);
822 let fty = fty.subst(self.tcx, substs);
823 let (fty, _) = self.replace_bound_vars_with_fresh_vars(
829 if let Some(self_ty) = self_ty {
830 if self.at(&ObligationCause::dummy(), self.param_env)
831 .sup(fty.inputs()[0], self_ty)
837 self.can_sub(self.param_env, fty.output(), expected).is_ok()
844 fn assemble_extension_candidates_for_trait(&mut self,
845 import_id: Option<ast::NodeId>,
847 -> Result<(), MethodError<'tcx>> {
848 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
850 let trait_substs = self.fresh_item_substs(trait_def_id);
851 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
853 for item in self.impl_or_trait_item(trait_def_id) {
854 // Check whether `trait_def_id` defines a method with suitable name:
855 if !self.has_applicable_self(&item) {
856 debug!("method has inapplicable self");
857 self.record_static_candidate(TraitSource(trait_def_id));
861 let (xform_self_ty, xform_ret_ty) =
862 self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
863 self.push_candidate(Candidate {
864 xform_self_ty, xform_ret_ty, item, import_id,
865 kind: TraitCandidate(trait_ref),
871 fn candidate_method_names(&self) -> Vec<ast::Ident> {
872 let mut set = FxHashSet::default();
873 let mut names: Vec<_> = self.inherent_candidates
875 .chain(&self.extension_candidates)
876 .filter(|candidate| {
877 if let Some(return_ty) = self.return_type {
878 self.matches_return_type(&candidate.item, None, return_ty)
883 .map(|candidate| candidate.item.ident)
884 .filter(|&name| set.insert(name))
887 // sort them by the name so we have a stable result
888 names.sort_by_cached_key(|n| n.as_str());
892 ///////////////////////////////////////////////////////////////////////////
895 fn pick(mut self) -> PickResult<'tcx> {
896 assert!(self.method_name.is_some());
898 if let Some(r) = self.pick_core() {
902 let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
903 let private_candidate = self.private_candidate.take();
904 let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
906 // things failed, so lets look at all traits, for diagnostic purposes now:
909 let span = self.span;
912 self.assemble_extension_candidates_for_all_traits()?;
914 let out_of_scope_traits = match self.pick_core() {
915 Some(Ok(p)) => vec![p.item.container.id()],
916 //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
917 Some(Err(MethodError::Ambiguity(v))) => {
921 TraitSource(id) => id,
922 ImplSource(impl_id) => {
923 match tcx.trait_id_of_impl(impl_id) {
927 "found inherent method when looking at traits")
935 Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
936 assert!(others.is_empty());
942 if let Some(def) = private_candidate {
943 return Err(MethodError::PrivateMatch(def, out_of_scope_traits));
945 let lev_candidate = self.probe_for_lev_candidate()?;
947 Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
948 unsatisfied_predicates,
954 fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
955 let steps = self.steps.clone();
957 // find the first step that works
961 debug!("pick_core: step={:?}", step);
962 // skip types that are from a type error or that would require dereferencing
964 !step.self_ty.references_error() && !step.from_unsafe_deref
966 let InferOk { value: self_ty, obligations: _ } =
967 self.fcx.probe_instantiate_query_response(
968 self.span, &self.orig_steps_var_values, &step.self_ty
969 ).unwrap_or_else(|_| {
970 span_bug!(self.span, "{:?} was applicable but now isn't?", step.self_ty)
972 self.pick_by_value_method(step, self_ty).or_else(|| {
973 self.pick_autorefd_method(step, self_ty, hir::MutImmutable).or_else(|| {
974 self.pick_autorefd_method(step, self_ty, hir::MutMutable)
979 fn pick_by_value_method(&mut self, step: &CandidateStep<'gcx>, self_ty: Ty<'tcx>)
980 -> Option<PickResult<'tcx>>
982 //! For each type `T` in the step list, this attempts to find a
983 //! method where the (transformed) self type is exactly `T`. We
984 //! do however do one transformation on the adjustment: if we
985 //! are passing a region pointer in, we will potentially
986 //! *reborrow* it to a shorter lifetime. This allows us to
987 //! transparently pass `&mut` pointers, in particular, without
988 //! consuming them for their entire lifetime.
994 self.pick_method(self_ty).map(|r| {
996 pick.autoderefs = step.autoderefs;
998 // Insert a `&*` or `&mut *` if this is a reference type:
999 if let ty::Ref(_, _, mutbl) = step.self_ty.value.value.sty {
1000 pick.autoderefs += 1;
1001 pick.autoref = Some(mutbl);
1009 fn pick_autorefd_method(&mut self,
1010 step: &CandidateStep<'gcx>,
1012 mutbl: hir::Mutability)
1013 -> Option<PickResult<'tcx>> {
1016 // In general, during probing we erase regions. See
1017 // `impl_self_ty()` for an explanation.
1018 let region = tcx.types.re_erased;
1020 let autoref_ty = tcx.mk_ref(region,
1024 self.pick_method(autoref_ty).map(|r| {
1026 pick.autoderefs = step.autoderefs;
1027 pick.autoref = Some(mutbl);
1028 pick.unsize = if step.unsize {
1038 fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
1039 debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1041 let mut possibly_unsatisfied_predicates = Vec::new();
1042 let mut unstable_candidates = Vec::new();
1044 for (kind, candidates) in &[
1045 ("inherent", &self.inherent_candidates),
1046 ("extension", &self.extension_candidates),
1048 debug!("searching {} candidates", kind);
1049 let res = self.consider_candidates(
1052 &mut possibly_unsatisfied_predicates,
1053 Some(&mut unstable_candidates),
1055 if let Some(pick) = res {
1056 if !self.is_suggestion.0 && !unstable_candidates.is_empty() {
1057 if let Ok(p) = &pick {
1058 // Emit a lint if there are unstable candidates alongside the stable ones.
1060 // We suppress warning if we're picking the method only because it is a
1062 self.emit_unstable_name_collision_hint(p, &unstable_candidates);
1069 debug!("searching unstable candidates");
1070 let res = self.consider_candidates(
1072 unstable_candidates.into_iter().map(|(c, _)| c),
1073 &mut possibly_unsatisfied_predicates,
1077 self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1082 fn consider_candidates<'b, ProbesIter>(
1086 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>,
1087 unstable_candidates: Option<&mut Vec<(&'b Candidate<'tcx>, Symbol)>>,
1088 ) -> Option<PickResult<'tcx>>
1090 ProbesIter: Iterator<Item = &'b Candidate<'tcx>> + Clone,
1092 let mut applicable_candidates: Vec<_> = probes.clone()
1094 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1096 .filter(|&(_, status)| status != ProbeResult::NoMatch)
1099 debug!("applicable_candidates: {:?}", applicable_candidates);
1101 if applicable_candidates.len() > 1 {
1102 if let Some(pick) = self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1103 return Some(Ok(pick));
1107 if let Some(uc) = unstable_candidates {
1108 applicable_candidates.retain(|&(p, _)| {
1109 if let stability::EvalResult::Deny { feature, .. } =
1110 self.tcx.eval_stability(p.item.def_id, None, self.span)
1112 uc.push((p, feature));
1119 if applicable_candidates.len() > 1 {
1120 let sources = probes
1121 .map(|p| self.candidate_source(p, self_ty))
1123 return Some(Err(MethodError::Ambiguity(sources)));
1126 applicable_candidates.pop().map(|(probe, status)| {
1127 if status == ProbeResult::Match {
1128 Ok(probe.to_unadjusted_pick())
1130 Err(MethodError::BadReturnType)
1135 fn emit_unstable_name_collision_hint(
1138 unstable_candidates: &[(&Candidate<'tcx>, Symbol)],
1140 let mut diag = self.tcx.struct_span_lint_node(
1141 lint::builtin::UNSTABLE_NAME_COLLISIONS,
1144 "a method with this name may be added to the standard library in the future",
1147 // FIXME: This should be a `span_suggestion` instead of `help`
1148 // However `self.span` only
1149 // highlights the method name, so we can't use it. Also consider reusing the code from
1150 // `report_method_error()`.
1152 "call with fully qualified syntax `{}(...)` to keep using the current method",
1153 self.tcx.item_path_str(stable_pick.item.def_id),
1156 if nightly_options::is_nightly_build() {
1157 for (candidate, feature) in unstable_candidates {
1159 "add #![feature({})] to the crate attributes to enable `{}`",
1161 self.tcx.item_path_str(candidate.item.def_id),
1169 fn select_trait_candidate(&self, trait_ref: ty::TraitRef<'tcx>)
1170 -> traits::SelectionResult<'tcx, traits::Selection<'tcx>>
1172 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1174 trait_ref.to_poly_trait_ref().to_poly_trait_predicate();
1175 let obligation = traits::Obligation::new(cause, self.param_env, predicate);
1176 traits::SelectionContext::new(self).select(&obligation)
1179 fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>)
1182 match candidate.kind {
1183 InherentImplCandidate(..) => ImplSource(candidate.item.container.id()),
1185 WhereClauseCandidate(_) => TraitSource(candidate.item.container.id()),
1186 TraitCandidate(trait_ref) => self.probe(|_| {
1187 let _ = self.at(&ObligationCause::dummy(), self.param_env)
1188 .sup(candidate.xform_self_ty, self_ty);
1189 match self.select_trait_candidate(trait_ref) {
1190 Ok(Some(traits::Vtable::VtableImpl(ref impl_data))) => {
1191 // If only a single impl matches, make the error message point
1193 ImplSource(impl_data.impl_def_id)
1196 TraitSource(candidate.item.container.id())
1203 fn consider_probe(&self,
1205 probe: &Candidate<'tcx>,
1206 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1208 debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1211 // First check that the self type can be related.
1212 let sub_obligations = match self.at(&ObligationCause::dummy(), self.param_env)
1213 .sup(probe.xform_self_ty, self_ty) {
1214 Ok(InferOk { obligations, value: () }) => obligations,
1216 debug!("--> cannot relate self-types");
1217 return ProbeResult::NoMatch;
1221 let mut result = ProbeResult::Match;
1222 let selcx = &mut traits::SelectionContext::new(self);
1223 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1225 // If so, impls may carry other conditions (e.g., where
1226 // clauses) that must be considered. Make sure that those
1227 // match as well (or at least may match, sometimes we
1228 // don't have enough information to fully evaluate).
1229 let candidate_obligations : Vec<_> = match probe.kind {
1230 InherentImplCandidate(ref substs, ref ref_obligations) => {
1231 // Check whether the impl imposes obligations we have to worry about.
1232 let impl_def_id = probe.item.container.id();
1233 let impl_bounds = self.tcx.predicates_of(impl_def_id);
1234 let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1235 let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1236 traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
1238 // Convert the bounds into obligations.
1239 let impl_obligations = traits::predicates_for_generics(
1240 cause, self.param_env, &impl_bounds);
1242 debug!("impl_obligations={:?}", impl_obligations);
1243 impl_obligations.into_iter()
1244 .chain(norm_obligations.into_iter())
1245 .chain(ref_obligations.iter().cloned())
1250 WhereClauseCandidate(..) => {
1251 // These have no additional conditions to check.
1255 TraitCandidate(trait_ref) => {
1256 let predicate = trait_ref.to_predicate();
1258 traits::Obligation::new(cause, self.param_env, predicate);
1259 if !self.predicate_may_hold(&obligation) {
1260 if self.probe(|_| self.select_trait_candidate(trait_ref).is_err()) {
1261 // This candidate's primary obligation doesn't even
1262 // select - don't bother registering anything in
1263 // `potentially_unsatisfied_predicates`.
1264 return ProbeResult::NoMatch;
1266 // Some nested subobligation of this predicate
1269 // FIXME: try to find the exact nested subobligation
1270 // and point at it rather than reporting the entire
1272 result = ProbeResult::NoMatch;
1273 let trait_ref = self.resolve_type_vars_if_possible(&trait_ref);
1274 possibly_unsatisfied_predicates.push(trait_ref);
1281 debug!("consider_probe - candidate_obligations={:?} sub_obligations={:?}",
1282 candidate_obligations, sub_obligations);
1284 // Evaluate those obligations to see if they might possibly hold.
1285 for o in candidate_obligations.into_iter().chain(sub_obligations) {
1286 let o = self.resolve_type_vars_if_possible(&o);
1287 if !self.predicate_may_hold(&o) {
1288 result = ProbeResult::NoMatch;
1289 if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1290 possibly_unsatisfied_predicates.push(pred.skip_binder().trait_ref);
1295 if let ProbeResult::Match = result {
1296 if let (Some(return_ty), Some(xform_ret_ty)) =
1297 (self.return_type, probe.xform_ret_ty)
1299 let xform_ret_ty = self.resolve_type_vars_if_possible(&xform_ret_ty);
1300 debug!("comparing return_ty {:?} with xform ret ty {:?}",
1302 probe.xform_ret_ty);
1303 if self.at(&ObligationCause::dummy(), self.param_env)
1304 .sup(return_ty, xform_ret_ty)
1307 return ProbeResult::BadReturnType;
1316 /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1317 /// same trait, but we don't know which impl to use. In this case, since in all cases the
1318 /// external interface of the method can be determined from the trait, it's ok not to decide.
1319 /// We can basically just collapse all of the probes for various impls into one where-clause
1320 /// probe. This will result in a pending obligation so when more type-info is available we can
1321 /// make the final decision.
1323 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1326 /// trait Foo { ... }
1327 /// impl Foo for Vec<int> { ... }
1328 /// impl Foo for Vec<usize> { ... }
1331 /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1332 /// use, so it's ok to just commit to "using the method from the trait Foo".
1333 fn collapse_candidates_to_trait_pick(&self, probes: &[(&Candidate<'tcx>, ProbeResult)])
1334 -> Option<Pick<'tcx>>
1336 // Do all probes correspond to the same trait?
1337 let container = probes[0].0.item.container;
1338 if let ty::ImplContainer(_) = container {
1341 if probes[1..].iter().any(|&(p, _)| p.item.container != container) {
1345 // FIXME: check the return type here somehow.
1346 // If so, just use this trait and call it a day.
1348 item: probes[0].0.item.clone(),
1350 import_id: probes[0].0.import_id,
1357 /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
1358 /// candidate method where the method name may have been misspelt. Similarly to other
1359 /// Levenshtein based suggestions, we provide at most one such suggestion.
1360 fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssociatedItem>, MethodError<'tcx>> {
1361 debug!("Probing for method names similar to {:?}",
1364 let steps = self.steps.clone();
1366 let mut pcx = ProbeContext::new(self.fcx, self.span, self.mode, self.method_name,
1368 self.orig_steps_var_values.clone(),
1369 steps, IsSuggestion(true));
1370 pcx.allow_similar_names = true;
1371 pcx.assemble_inherent_candidates();
1372 pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)?;
1374 let method_names = pcx.candidate_method_names();
1375 pcx.allow_similar_names = false;
1376 let applicable_close_candidates: Vec<ty::AssociatedItem> = method_names
1378 .filter_map(|&method_name| {
1380 pcx.method_name = Some(method_name);
1381 pcx.assemble_inherent_candidates();
1382 pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)
1383 .ok().map_or(None, |_| {
1385 .and_then(|pick| pick.ok())
1386 .and_then(|pick| Some(pick.item))
1391 if applicable_close_candidates.is_empty() {
1395 let names = applicable_close_candidates.iter().map(|cand| &cand.ident.name);
1396 find_best_match_for_name(names,
1397 &self.method_name.unwrap().as_str(),
1400 Ok(applicable_close_candidates
1402 .find(|method| method.ident.name == best_name))
1407 ///////////////////////////////////////////////////////////////////////////
1409 fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1410 // "Fast track" -- check for usage of sugar when in method call
1413 // In Path mode (i.e., resolving a value like `T::next`), consider any
1414 // associated value (i.e., methods, constants) but not types.
1416 Mode::MethodCall => item.method_has_self_argument,
1417 Mode::Path => match item.kind {
1418 ty::AssociatedKind::Existential |
1419 ty::AssociatedKind::Type => false,
1420 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1423 // FIXME -- check for types that deref to `Self`,
1424 // like `Rc<Self>` and so on.
1426 // Note also that the current code will break if this type
1427 // includes any of the type parameters defined on the method
1428 // -- but this could be overcome.
1431 fn record_static_candidate(&mut self, source: CandidateSource) {
1432 self.static_candidates.push(source);
1435 fn xform_self_ty(&self,
1436 item: &ty::AssociatedItem,
1438 substs: &Substs<'tcx>)
1439 -> (Ty<'tcx>, Option<Ty<'tcx>>) {
1440 if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1441 let sig = self.xform_method_sig(item.def_id, substs);
1442 (sig.inputs()[0], Some(sig.output()))
1448 fn xform_method_sig(&self,
1450 substs: &Substs<'tcx>)
1453 let fn_sig = self.tcx.fn_sig(method);
1454 debug!("xform_self_ty(fn_sig={:?}, substs={:?})",
1458 assert!(!substs.has_escaping_bound_vars());
1460 // It is possible for type parameters or early-bound lifetimes
1461 // to appear in the signature of `self`. The substitutions we
1462 // are given do not include type/lifetime parameters for the
1463 // method yet. So create fresh variables here for those too,
1464 // if there are any.
1465 let generics = self.tcx.generics_of(method);
1466 assert_eq!(substs.len(), generics.parent_count as usize);
1468 // Erase any late-bound regions from the method and substitute
1469 // in the values from the substitution.
1470 let xform_fn_sig = self.erase_late_bound_regions(&fn_sig);
1472 if generics.params.is_empty() {
1473 xform_fn_sig.subst(self.tcx, substs)
1475 let substs = Substs::for_item(self.tcx, method, |param, _| {
1476 let i = param.index as usize;
1477 if i < substs.len() {
1481 GenericParamDefKind::Lifetime => {
1482 // In general, during probe we erase regions. See
1483 // `impl_self_ty()` for an explanation.
1484 self.tcx.types.re_erased.into()
1486 GenericParamDefKind::Type {..} => self.var_for_def(self.span, param),
1490 xform_fn_sig.subst(self.tcx, substs)
1494 /// Get the type of an impl and generate substitutions with placeholders.
1495 fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
1496 (self.tcx.type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1499 fn fresh_item_substs(&self, def_id: DefId) -> &'tcx Substs<'tcx> {
1500 Substs::for_item(self.tcx, def_id, |param, _| {
1502 GenericParamDefKind::Lifetime => self.tcx.types.re_erased.into(),
1503 GenericParamDefKind::Type {..} => {
1504 self.next_ty_var(TypeVariableOrigin::SubstitutionPlaceholder(
1505 self.tcx.def_span(def_id))).into()
1511 /// Replace late-bound-regions bound by `value` with `'static` using
1512 /// `ty::erase_late_bound_regions`.
1514 /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1515 /// method matching. It is reasonable during the probe phase because we don't consider region
1516 /// relationships at all. Therefore, we can just replace all the region variables with 'static
1517 /// rather than creating fresh region variables. This is nice for two reasons:
1519 /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1520 /// particular method call, it winds up creating fewer types overall, which helps for memory
1521 /// usage. (Admittedly, this is a rather small effect, though measurable.)
1523 /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1524 /// late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1525 /// regions with actual region variables as is proper, we'd have to ensure that the same
1526 /// region got replaced with the same variable, which requires a bit more coordination
1527 /// and/or tracking the substitution and
1529 fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1530 where T: TypeFoldable<'tcx>
1532 self.tcx.erase_late_bound_regions(value)
1535 /// Find the method with the appropriate name (or return type, as the case may be). If
1536 /// `allow_similar_names` is set, find methods with close-matching names.
1537 fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1538 if let Some(name) = self.method_name {
1539 if self.allow_similar_names {
1540 let max_dist = max(name.as_str().len(), 3) / 3;
1541 self.tcx.associated_items(def_id)
1543 let dist = lev_distance(&*name.as_str(), &x.ident.as_str());
1544 Namespace::from(x.kind) == Namespace::Value && dist > 0
1550 .associated_item(def_id, name, Namespace::Value)
1551 .map_or(Vec::new(), |x| vec![x])
1554 self.tcx.associated_items(def_id).collect()
1559 impl<'tcx> Candidate<'tcx> {
1560 fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1562 item: self.item.clone(),
1563 kind: match self.kind {
1564 InherentImplCandidate(..) => InherentImplPick,
1565 ObjectCandidate => ObjectPick,
1566 TraitCandidate(_) => TraitPick,
1567 WhereClauseCandidate(ref trait_ref) => {
1568 // Only trait derived from where-clauses should
1569 // appear here, so they should not contain any
1570 // inference variables or other artifacts. This
1571 // means they are safe to put into the
1572 // `WhereClausePick`.
1574 !trait_ref.skip_binder().substs.needs_infer()
1575 && !trait_ref.skip_binder().substs.has_placeholders()
1578 WhereClausePick(trait_ref.clone())
1581 import_id: self.import_id,