2 use super::CandidateSource;
3 use super::MethodError;
4 use super::NoMatchData;
6 use crate::errors::MethodCallOnUnknownType;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::Applicability;
11 use rustc_hir::def::DefKind;
12 use rustc_infer::infer::canonical::OriginalQueryValues;
13 use rustc_infer::infer::canonical::{Canonical, QueryResponse};
14 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
15 use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
16 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
17 use rustc_middle::middle::stability;
18 use rustc_middle::ty::fast_reject::{simplify_type, TreatParams};
19 use rustc_middle::ty::AssocItem;
20 use rustc_middle::ty::GenericParamDefKind;
21 use rustc_middle::ty::ToPredicate;
22 use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeFoldable, TypeVisitable};
23 use rustc_middle::ty::{InternalSubsts, SubstsRef};
24 use rustc_session::lint;
25 use rustc_span::def_id::DefId;
26 use rustc_span::def_id::LocalDefId;
27 use rustc_span::lev_distance::{
28 find_best_match_for_name_with_substrings, lev_distance_with_substrings,
30 use rustc_span::symbol::sym;
31 use rustc_span::{symbol::Ident, Span, Symbol, DUMMY_SP};
32 use rustc_trait_selection::autoderef::{self, Autoderef};
33 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
34 use rustc_trait_selection::traits::query::method_autoderef::MethodAutoderefBadTy;
35 use rustc_trait_selection::traits::query::method_autoderef::{
36 CandidateStep, MethodAutoderefStepsResult,
38 use rustc_trait_selection::traits::query::CanonicalTyGoal;
39 use rustc_trait_selection::traits::NormalizeExt;
40 use rustc_trait_selection::traits::{self, ObligationCause};
41 use std::cell::RefCell;
46 use smallvec::{smallvec, SmallVec};
48 use self::CandidateKind::*;
49 pub use self::PickKind::*;
51 /// Boolean flag used to indicate if this search is for a suggestion
52 /// or not. If true, we can allow ambiguity and so forth.
53 #[derive(Clone, Copy, Debug)]
54 pub struct IsSuggestion(pub bool);
56 struct ProbeContext<'a, 'tcx> {
57 fcx: &'a FnCtxt<'a, 'tcx>,
60 method_name: Option<Ident>,
61 return_type: Option<Ty<'tcx>>,
63 /// This is the OriginalQueryValues for the steps queries
64 /// that are answered in steps.
65 orig_steps_var_values: &'a OriginalQueryValues<'tcx>,
66 steps: &'tcx [CandidateStep<'tcx>],
68 inherent_candidates: Vec<Candidate<'tcx>>,
69 extension_candidates: Vec<Candidate<'tcx>>,
70 impl_dups: FxHashSet<DefId>,
72 /// When probing for names, include names that are close to the
73 /// requested name (by Levenshtein distance)
74 allow_similar_names: bool,
76 /// Some(candidate) if there is a private candidate
77 private_candidate: Option<(DefKind, DefId)>,
79 /// Collects near misses when the candidate functions are missing a `self` keyword and is only
80 /// used for error reporting
81 static_candidates: RefCell<Vec<CandidateSource>>,
83 /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
84 /// for error reporting
85 unsatisfied_predicates: RefCell<
86 Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>,
89 scope_expr_id: hir::HirId,
92 impl<'a, 'tcx> Deref for ProbeContext<'a, 'tcx> {
93 type Target = FnCtxt<'a, 'tcx>;
94 fn deref(&self) -> &Self::Target {
99 #[derive(Debug, Clone)]
100 pub(crate) struct Candidate<'tcx> {
101 // Candidates are (I'm not quite sure, but they are mostly) basically
102 // some metadata on top of a `ty::AssocItem` (without substs).
104 // However, method probing wants to be able to evaluate the predicates
105 // for a function with the substs applied - for example, if a function
106 // has `where Self: Sized`, we don't want to consider it unless `Self`
107 // is actually `Sized`, and similarly, return-type suggestions want
108 // to consider the "actual" return type.
110 // The way this is handled is through `xform_self_ty`. It contains
111 // the receiver type of this candidate, but `xform_self_ty`,
112 // `xform_ret_ty` and `kind` (which contains the predicates) have the
113 // generic parameters of this candidate substituted with the *same set*
114 // of inference variables, which acts as some weird sort of "query".
116 // When we check out a candidate, we require `xform_self_ty` to be
117 // a subtype of the passed-in self-type, and this equates the type
118 // variables in the rest of the fields.
120 // For example, if we have this candidate:
123 // fn foo(&self) where Self: Sized;
127 // Then `xform_self_ty` will be `&'erased ?X` and `kind` will contain
128 // the predicate `?X: Sized`, so if we are evaluating `Foo` for a
129 // the receiver `&T`, we'll do the subtyping which will make `?X`
130 // get the right value, then when we evaluate the predicate we'll check
132 xform_self_ty: Ty<'tcx>,
133 xform_ret_ty: Option<Ty<'tcx>>,
134 pub(crate) item: ty::AssocItem,
135 pub(crate) kind: CandidateKind<'tcx>,
136 pub(crate) import_ids: SmallVec<[LocalDefId; 1]>,
139 #[derive(Debug, Clone)]
140 pub(crate) enum CandidateKind<'tcx> {
141 InherentImplCandidate(
143 // Normalize obligations
144 Vec<traits::PredicateObligation<'tcx>>,
147 TraitCandidate(ty::TraitRef<'tcx>),
148 WhereClauseCandidate(
150 ty::PolyTraitRef<'tcx>,
154 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
161 /// When adjusting a receiver we often want to do one of
163 /// - Add a `&` (or `&mut`), converting the receiver from `T` to `&T` (or `&mut T`)
164 /// - If the receiver has type `*mut T`, convert it to `*const T`
166 /// This type tells us which one to do.
168 /// Note that in principle we could do both at the same time. For example, when the receiver has
169 /// type `T`, we could autoref it to `&T`, then convert to `*const T`. Or, when it has type `*mut
170 /// T`, we could convert it to `*const T`, then autoref to `&*const T`. However, currently we do
171 /// (at most) one of these. Either the receiver has type `T` and we convert it to `&T` (or with
172 /// `mut`), or it has type `*mut T` and we convert it to `*const T`.
173 #[derive(Debug, PartialEq, Copy, Clone)]
174 pub enum AutorefOrPtrAdjustment {
175 /// Receiver has type `T`, add `&` or `&mut` (it `T` is `mut`), and maybe also "unsize" it.
176 /// Unsizing is used to convert a `[T; N]` to `[T]`, which only makes sense when autorefing.
178 mutbl: hir::Mutability,
180 /// Indicates that the source expression should be "unsized" to a target type.
181 /// This is special-cased for just arrays unsizing to slices.
184 /// Receiver has type `*mut T`, convert to `*const T`
188 impl AutorefOrPtrAdjustment {
189 fn get_unsize(&self) -> bool {
191 AutorefOrPtrAdjustment::Autoref { mutbl: _, unsize } => *unsize,
192 AutorefOrPtrAdjustment::ToConstPtr => false,
197 #[derive(Debug, Clone)]
198 pub struct Pick<'tcx> {
199 pub item: ty::AssocItem,
200 pub kind: PickKind<'tcx>,
201 pub import_ids: SmallVec<[LocalDefId; 1]>,
203 /// Indicates that the source expression should be autoderef'd N times
204 /// ```ignore (not-rust)
205 /// A = expr | *expr | **expr | ...
207 pub autoderefs: usize,
209 /// Indicates that we want to add an autoref (and maybe also unsize it), or if the receiver is
210 /// `*mut T`, convert it to `*const T`.
211 pub autoref_or_ptr_adjustment: Option<AutorefOrPtrAdjustment>,
212 pub self_ty: Ty<'tcx>,
214 /// Unstable candidates alongside the stable ones.
215 unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
218 #[derive(Clone, Debug, PartialEq, Eq)]
219 pub enum PickKind<'tcx> {
225 ty::PolyTraitRef<'tcx>,
229 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
231 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
233 // An expression of the form `receiver.method_name(...)`.
234 // Autoderefs are performed on `receiver`, lookup is done based on the
235 // `self` argument of the method, and static methods aren't considered.
237 // An expression of the form `Type::item` or `<T>::item`.
238 // No autoderefs are performed, lookup is done based on the type each
239 // implementation is for, and static methods are included.
243 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
244 pub enum ProbeScope {
245 // Assemble candidates coming only from traits in scope.
248 // Assemble candidates coming from all traits.
252 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
253 /// This is used to offer suggestions to users. It returns methods
254 /// that could have been called which have the desired return
255 /// type. Some effort is made to rule out methods that, if called,
256 /// would result in an error (basically, the same criteria we
257 /// would use to decide if a method is a plausible fit for
258 /// ambiguity purposes).
259 #[instrument(level = "debug", skip(self, candidate_filter))]
260 pub fn probe_for_return_type(
264 return_type: Ty<'tcx>,
266 scope_expr_id: hir::HirId,
267 candidate_filter: impl Fn(&ty::AssocItem) -> bool,
268 ) -> Vec<ty::AssocItem> {
269 let method_names = self
278 ProbeScope::AllTraits,
279 |probe_cx| Ok(probe_cx.candidate_method_names(candidate_filter)),
281 .unwrap_or_default();
284 .flat_map(|&method_name| {
293 ProbeScope::AllTraits,
294 |probe_cx| probe_cx.pick(),
297 .map(|pick| pick.item)
302 #[instrument(level = "debug", skip(self))]
303 pub fn probe_for_name(
307 is_suggestion: IsSuggestion,
309 scope_expr_id: hir::HirId,
311 ) -> PickResult<'tcx> {
321 |probe_cx| probe_cx.pick(),
325 #[instrument(level = "debug", skip(self))]
326 pub(crate) fn probe_for_name_many(
330 is_suggestion: IsSuggestion,
332 scope_expr_id: hir::HirId,
334 ) -> Vec<Candidate<'tcx>> {
348 .chain(probe_cx.extension_candidates)
359 method_name: Option<Ident>,
360 return_type: Option<Ty<'tcx>>,
361 is_suggestion: IsSuggestion,
363 scope_expr_id: hir::HirId,
366 ) -> Result<R, MethodError<'tcx>>
368 OP: FnOnce(ProbeContext<'_, 'tcx>) -> Result<R, MethodError<'tcx>>,
370 let mut orig_values = OriginalQueryValues::default();
371 let param_env_and_self_ty = self.canonicalize_query(
372 ParamEnvAnd { param_env: self.param_env, value: self_ty },
376 let steps = match mode {
377 Mode::MethodCall => self.tcx.method_autoderef_steps(param_env_and_self_ty),
378 Mode::Path => self.probe(|_| {
379 // Mode::Path - the deref steps is "trivial". This turns
380 // our CanonicalQuery into a "trivial" QueryResponse. This
381 // is a bit inefficient, but I don't think that writing
382 // special handling for this "trivial case" is a good idea.
384 let infcx = &self.infcx;
385 let (ParamEnvAnd { param_env: _, value: self_ty }, canonical_inference_vars) =
386 infcx.instantiate_canonical_with_fresh_inference_vars(
388 ¶m_env_and_self_ty,
391 "probe_op: Mode::Path, param_env_and_self_ty={:?} self_ty={:?}",
392 param_env_and_self_ty, self_ty
394 MethodAutoderefStepsResult {
395 steps: infcx.tcx.arena.alloc_from_iter([CandidateStep {
396 self_ty: self.make_query_response_ignoring_pending_obligations(
397 canonical_inference_vars,
401 from_unsafe_deref: false,
405 reached_recursion_limit: false,
410 // If our autoderef loop had reached the recursion limit,
411 // report an overflow error, but continue going on with
412 // the truncated autoderef list.
413 if steps.reached_recursion_limit {
418 .unwrap_or_else(|| span_bug!(span, "reached the recursion limit in 0 steps?"))
421 .probe_instantiate_query_response(span, &orig_values, ty)
422 .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
423 autoderef::report_autoderef_recursion_limit_error(self.tcx, span, ty.value);
427 // If we encountered an `_` type or an error type during autoderef, this is
429 if let Some(bad_ty) = &steps.opt_bad_ty {
431 // Ambiguity was encountered during a suggestion. Just keep going.
432 debug!("ProbeContext: encountered ambiguity in suggestion");
433 } else if bad_ty.reached_raw_pointer && !self.tcx.features().arbitrary_self_types {
434 // this case used to be allowed by the compiler,
435 // so we do a future-compat lint here for the 2015 edition
436 // (see https://github.com/rust-lang/rust/issues/46906)
437 if self.tcx.sess.rust_2018() {
438 self.tcx.sess.emit_err(MethodCallOnUnknownType { span });
440 self.tcx.struct_span_lint_hir(
441 lint::builtin::TYVAR_BEHIND_RAW_POINTER,
444 "type annotations needed",
449 // Encountered a real ambiguity, so abort the lookup. If `ty` is not
450 // an `Err`, report the right "type annotations needed" error pointing
454 .probe_instantiate_query_response(span, &orig_values, ty)
455 .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
456 let ty = self.structurally_resolved_type(span, ty.value);
457 assert!(matches!(ty.kind(), ty::Error(_)));
458 return Err(MethodError::NoMatch(NoMatchData {
459 static_candidates: Vec::new(),
460 unsatisfied_predicates: Vec::new(),
461 out_of_scope_traits: Vec::new(),
468 debug!("ProbeContext: steps for self_ty={:?} are {:?}", self_ty, steps);
470 // this creates one big transaction so that all type variables etc
471 // that we create during the probe process are removed later
473 let mut probe_cx = ProbeContext::new(
484 probe_cx.assemble_inherent_candidates();
486 ProbeScope::TraitsInScope => {
487 probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)
489 ProbeScope::AllTraits => probe_cx.assemble_extension_candidates_for_all_traits(),
496 pub fn provide(providers: &mut ty::query::Providers) {
497 providers.method_autoderef_steps = method_autoderef_steps;
500 fn method_autoderef_steps<'tcx>(
502 goal: CanonicalTyGoal<'tcx>,
503 ) -> MethodAutoderefStepsResult<'tcx> {
504 debug!("method_autoderef_steps({:?})", goal);
506 let (ref infcx, goal, inference_vars) = tcx.infer_ctxt().build_with_canonical(DUMMY_SP, &goal);
507 let ParamEnvAnd { param_env, value: self_ty } = goal;
509 let mut autoderef = Autoderef::new(infcx, param_env, hir::CRATE_HIR_ID, DUMMY_SP, self_ty)
510 .include_raw_pointers()
512 let mut reached_raw_pointer = false;
513 let mut steps: Vec<_> = autoderef
516 let step = CandidateStep {
518 .make_query_response_ignoring_pending_obligations(inference_vars.clone(), ty),
520 from_unsafe_deref: reached_raw_pointer,
523 if let ty::RawPtr(_) = ty.kind() {
524 // all the subsequent steps will be from_unsafe_deref
525 reached_raw_pointer = true;
531 let final_ty = autoderef.final_ty(true);
532 let opt_bad_ty = match final_ty.kind() {
533 ty::Infer(ty::TyVar(_)) | ty::Error(_) => Some(MethodAutoderefBadTy {
535 ty: infcx.make_query_response_ignoring_pending_obligations(inference_vars, final_ty),
537 ty::Array(elem_ty, _) => {
538 let dereferences = steps.len() - 1;
540 steps.push(CandidateStep {
541 self_ty: infcx.make_query_response_ignoring_pending_obligations(
543 infcx.tcx.mk_slice(*elem_ty),
545 autoderefs: dereferences,
546 // this could be from an unsafe deref if we had
547 // a *mut/const [T; N]
548 from_unsafe_deref: reached_raw_pointer,
557 debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
559 MethodAutoderefStepsResult {
560 steps: tcx.arena.alloc_from_iter(steps),
561 opt_bad_ty: opt_bad_ty.map(|ty| &*tcx.arena.alloc(ty)),
562 reached_recursion_limit: autoderef.reached_recursion_limit(),
566 impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
568 fcx: &'a FnCtxt<'a, 'tcx>,
571 method_name: Option<Ident>,
572 return_type: Option<Ty<'tcx>>,
573 orig_steps_var_values: &'a OriginalQueryValues<'tcx>,
574 steps: &'tcx [CandidateStep<'tcx>],
575 scope_expr_id: hir::HirId,
576 ) -> ProbeContext<'a, 'tcx> {
583 inherent_candidates: Vec::new(),
584 extension_candidates: Vec::new(),
585 impl_dups: FxHashSet::default(),
586 orig_steps_var_values,
588 allow_similar_names: false,
589 private_candidate: None,
590 static_candidates: RefCell::new(Vec::new()),
591 unsatisfied_predicates: RefCell::new(Vec::new()),
596 fn reset(&mut self) {
597 self.inherent_candidates.clear();
598 self.extension_candidates.clear();
599 self.impl_dups.clear();
600 self.private_candidate = None;
601 self.static_candidates.borrow_mut().clear();
602 self.unsatisfied_predicates.borrow_mut().clear();
605 ///////////////////////////////////////////////////////////////////////////
606 // CANDIDATE ASSEMBLY
608 fn push_candidate(&mut self, candidate: Candidate<'tcx>, is_inherent: bool) {
609 let is_accessible = if let Some(name) = self.method_name {
610 let item = candidate.item;
613 .adjust_ident_and_get_scope(name, item.container_id(self.tcx), self.body_id)
615 item.visibility(self.tcx).is_accessible_from(def_scope, self.tcx)
621 self.inherent_candidates.push(candidate);
623 self.extension_candidates.push(candidate);
625 } else if self.private_candidate.is_none() {
626 self.private_candidate =
627 Some((candidate.item.kind.as_def_kind(), candidate.item.def_id));
631 fn assemble_inherent_candidates(&mut self) {
632 for step in self.steps.iter() {
633 self.assemble_probe(&step.self_ty);
637 fn assemble_probe(&mut self, self_ty: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>) {
638 debug!("assemble_probe: self_ty={:?}", self_ty);
639 let raw_self_ty = self_ty.value.value;
640 match *raw_self_ty.kind() {
641 ty::Dynamic(data, ..) if let Some(p) = data.principal() => {
642 // Subtle: we can't use `instantiate_query_response` here: using it will
643 // commit to all of the type equalities assumed by inference going through
644 // autoderef (see the `method-probe-no-guessing` test).
646 // However, in this code, it is OK if we end up with an object type that is
647 // "more general" than the object type that we are evaluating. For *every*
648 // object type `MY_OBJECT`, a function call that goes through a trait-ref
649 // of the form `<MY_OBJECT as SuperTraitOf(MY_OBJECT)>::func` is a valid
650 // `ObjectCandidate`, and it should be discoverable "exactly" through one
651 // of the iterations in the autoderef loop, so there is no problem with it
652 // being discoverable in another one of these iterations.
654 // Using `instantiate_canonical_with_fresh_inference_vars` on our
655 // `Canonical<QueryResponse<Ty<'tcx>>>` and then *throwing away* the
656 // `CanonicalVarValues` will exactly give us such a generalization - it
657 // will still match the original object type, but it won't pollute our
658 // type variables in any form, so just do that!
659 let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) =
661 .instantiate_canonical_with_fresh_inference_vars(self.span, self_ty);
663 self.assemble_inherent_candidates_from_object(generalized_self_ty);
664 self.assemble_inherent_impl_candidates_for_type(p.def_id());
665 if self.tcx.has_attr(p.def_id(), sym::rustc_has_incoherent_inherent_impls) {
666 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty);
670 let def_id = def.did();
671 self.assemble_inherent_impl_candidates_for_type(def_id);
672 if self.tcx.has_attr(def_id, sym::rustc_has_incoherent_inherent_impls) {
673 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty);
676 ty::Foreign(did) => {
677 self.assemble_inherent_impl_candidates_for_type(did);
678 if self.tcx.has_attr(did, sym::rustc_has_incoherent_inherent_impls) {
679 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty);
683 self.assemble_inherent_candidates_from_param(p);
696 | ty::Tuple(..) => self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty),
701 fn assemble_inherent_candidates_for_incoherent_ty(&mut self, self_ty: Ty<'tcx>) {
702 let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::AsInfer) else {
703 bug!("unexpected incoherent type: {:?}", self_ty)
705 for &impl_def_id in self.tcx.incoherent_impls(simp) {
706 self.assemble_inherent_impl_probe(impl_def_id);
710 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
711 let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
712 for &impl_def_id in impl_def_ids.iter() {
713 self.assemble_inherent_impl_probe(impl_def_id);
717 fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
718 if !self.impl_dups.insert(impl_def_id) {
719 return; // already visited
722 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
724 for item in self.impl_or_trait_item(impl_def_id) {
725 if !self.has_applicable_self(&item) {
726 // No receiver declared. Not a candidate.
727 self.record_static_candidate(CandidateSource::Impl(impl_def_id));
731 let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
732 let impl_ty = impl_ty.subst(self.tcx, impl_substs);
734 debug!("impl_ty: {:?}", impl_ty);
736 // Determine the receiver type that the method itself expects.
737 let (xform_self_ty, xform_ret_ty) = self.xform_self_ty(&item, impl_ty, impl_substs);
738 debug!("xform_self_ty: {:?}, xform_ret_ty: {:?}", xform_self_ty, xform_ret_ty);
740 // We can't use normalize_associated_types_in as it will pollute the
741 // fcx's fulfillment context after this probe is over.
742 // Note: we only normalize `xform_self_ty` here since the normalization
743 // of the return type can lead to inference results that prohibit
744 // valid candidates from being found, see issue #85671
745 // FIXME Postponing the normalization of the return type likely only hides a deeper bug,
746 // which might be caused by the `param_env` itself. The clauses of the `param_env`
747 // maybe shouldn't include `Param`s, but rather fresh variables or be canonicalized,
749 let cause = traits::ObligationCause::misc(self.span, self.body_id);
750 let InferOk { value: xform_self_ty, obligations } =
751 self.fcx.at(&cause, self.param_env).normalize(xform_self_ty);
754 "assemble_inherent_impl_probe after normalization: xform_self_ty = {:?}/{:?}",
755 xform_self_ty, xform_ret_ty
763 kind: InherentImplCandidate(impl_substs, obligations),
764 import_ids: smallvec![],
771 fn assemble_inherent_candidates_from_object(&mut self, self_ty: Ty<'tcx>) {
772 debug!("assemble_inherent_candidates_from_object(self_ty={:?})", self_ty);
774 let principal = match self_ty.kind() {
775 ty::Dynamic(ref data, ..) => Some(data),
778 .and_then(|data| data.principal())
782 "non-object {:?} in assemble_inherent_candidates_from_object",
787 // It is illegal to invoke a method on a trait instance that refers to
788 // the `Self` type. An [`ObjectSafetyViolation::SupertraitSelf`] error
789 // will be reported by `object_safety.rs` if the method refers to the
790 // `Self` type anywhere other than the receiver. Here, we use a
791 // substitution that replaces `Self` with the object type itself. Hence,
792 // a `&self` method will wind up with an argument type like `&dyn Trait`.
793 let trait_ref = principal.with_self_ty(self.tcx, self_ty);
794 self.elaborate_bounds(iter::once(trait_ref), |this, new_trait_ref, item| {
795 let new_trait_ref = this.erase_late_bound_regions(new_trait_ref);
797 let (xform_self_ty, xform_ret_ty) =
798 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
804 kind: ObjectCandidate,
805 import_ids: smallvec![],
812 fn assemble_inherent_candidates_from_param(&mut self, param_ty: ty::ParamTy) {
813 // FIXME: do we want to commit to this behavior for param bounds?
814 debug!("assemble_inherent_candidates_from_param(param_ty={:?})", param_ty);
816 let bounds = self.param_env.caller_bounds().iter().filter_map(|predicate| {
817 let bound_predicate = predicate.kind();
818 match bound_predicate.skip_binder() {
819 ty::PredicateKind::Clause(ty::Clause::Trait(trait_predicate)) => {
820 match *trait_predicate.trait_ref.self_ty().kind() {
821 ty::Param(p) if p == param_ty => {
822 Some(bound_predicate.rebind(trait_predicate.trait_ref))
827 ty::PredicateKind::Subtype(..)
828 | ty::PredicateKind::Coerce(..)
829 | ty::PredicateKind::Clause(ty::Clause::Projection(..))
830 | ty::PredicateKind::Clause(ty::Clause::RegionOutlives(..))
831 | ty::PredicateKind::WellFormed(..)
832 | ty::PredicateKind::ObjectSafe(..)
833 | ty::PredicateKind::ClosureKind(..)
834 | ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
835 | ty::PredicateKind::ConstEvaluatable(..)
836 | ty::PredicateKind::ConstEquate(..)
837 | ty::PredicateKind::Ambiguous
838 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
842 self.elaborate_bounds(bounds, |this, poly_trait_ref, item| {
843 let trait_ref = this.erase_late_bound_regions(poly_trait_ref);
845 let (xform_self_ty, xform_ret_ty) =
846 this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
848 // Because this trait derives from a where-clause, it
849 // should not contain any inference variables or other
850 // artifacts. This means it is safe to put into the
851 // `WhereClauseCandidate` and (eventually) into the
852 // `WhereClausePick`.
853 assert!(!trait_ref.substs.needs_infer());
860 kind: WhereClauseCandidate(poly_trait_ref),
861 import_ids: smallvec![],
868 // Do a search through a list of bounds, using a callback to actually
869 // create the candidates.
870 fn elaborate_bounds<F>(
872 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
875 F: for<'b> FnMut(&mut ProbeContext<'b, 'tcx>, ty::PolyTraitRef<'tcx>, ty::AssocItem),
878 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
879 debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref);
880 for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
881 if !self.has_applicable_self(&item) {
882 self.record_static_candidate(CandidateSource::Trait(bound_trait_ref.def_id()));
884 mk_cand(self, bound_trait_ref, item);
890 fn assemble_extension_candidates_for_traits_in_scope(&mut self, expr_hir_id: hir::HirId) {
891 let mut duplicates = FxHashSet::default();
892 let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
893 if let Some(applicable_traits) = opt_applicable_traits {
894 for trait_candidate in applicable_traits.iter() {
895 let trait_did = trait_candidate.def_id;
896 if duplicates.insert(trait_did) {
897 self.assemble_extension_candidates_for_trait(
898 &trait_candidate.import_ids,
906 fn assemble_extension_candidates_for_all_traits(&mut self) {
907 let mut duplicates = FxHashSet::default();
908 for trait_info in suggest::all_traits(self.tcx) {
909 if duplicates.insert(trait_info.def_id) {
910 self.assemble_extension_candidates_for_trait(&smallvec![], trait_info.def_id);
915 fn matches_return_type(
917 method: &ty::AssocItem,
918 self_ty: Option<Ty<'tcx>>,
922 ty::AssocKind::Fn => {
923 let fty = self.tcx.bound_fn_sig(method.def_id);
925 let substs = self.fresh_substs_for_item(self.span, method.def_id);
926 let fty = fty.subst(self.tcx, substs);
928 self.replace_bound_vars_with_fresh_vars(self.span, infer::FnCall, fty);
930 if let Some(self_ty) = self_ty {
932 .at(&ObligationCause::dummy(), self.param_env)
933 .sup(fty.inputs()[0], self_ty)
939 self.can_sub(self.param_env, fty.output(), expected).is_ok()
946 fn assemble_extension_candidates_for_trait(
948 import_ids: &SmallVec<[LocalDefId; 1]>,
951 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})", trait_def_id);
952 let trait_substs = self.fresh_item_substs(trait_def_id);
953 let trait_ref = self.tcx.mk_trait_ref(trait_def_id, trait_substs);
955 if self.tcx.is_trait_alias(trait_def_id) {
956 // For trait aliases, assume all supertraits are relevant.
957 let bounds = iter::once(ty::Binder::dummy(trait_ref));
958 self.elaborate_bounds(bounds, |this, new_trait_ref, item| {
959 let new_trait_ref = this.erase_late_bound_regions(new_trait_ref);
961 let (xform_self_ty, xform_ret_ty) =
962 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
968 import_ids: import_ids.clone(),
969 kind: TraitCandidate(new_trait_ref),
975 debug_assert!(self.tcx.is_trait(trait_def_id));
976 if self.tcx.trait_is_auto(trait_def_id) {
979 for item in self.impl_or_trait_item(trait_def_id) {
980 // Check whether `trait_def_id` defines a method with suitable name.
981 if !self.has_applicable_self(&item) {
982 debug!("method has inapplicable self");
983 self.record_static_candidate(CandidateSource::Trait(trait_def_id));
987 let (xform_self_ty, xform_ret_ty) =
988 self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
994 import_ids: import_ids.clone(),
995 kind: TraitCandidate(trait_ref),
1003 fn candidate_method_names(
1005 candidate_filter: impl Fn(&ty::AssocItem) -> bool,
1007 let mut set = FxHashSet::default();
1008 let mut names: Vec<_> = self
1009 .inherent_candidates
1011 .chain(&self.extension_candidates)
1012 .filter(|candidate| candidate_filter(&candidate.item))
1013 .filter(|candidate| {
1014 if let Some(return_ty) = self.return_type {
1015 self.matches_return_type(&candidate.item, None, return_ty)
1020 .map(|candidate| candidate.item.ident(self.tcx))
1021 .filter(|&name| set.insert(name))
1024 // Sort them by the name so we have a stable result.
1025 names.sort_by(|a, b| a.as_str().partial_cmp(b.as_str()).unwrap());
1029 ///////////////////////////////////////////////////////////////////////////
1030 // THE ACTUAL SEARCH
1032 fn pick(mut self) -> PickResult<'tcx> {
1033 assert!(self.method_name.is_some());
1035 if let Some(r) = self.pick_core() {
1039 debug!("pick: actual search failed, assemble diagnostics");
1041 let static_candidates = std::mem::take(self.static_candidates.get_mut());
1042 let private_candidate = self.private_candidate.take();
1043 let unsatisfied_predicates = std::mem::take(self.unsatisfied_predicates.get_mut());
1045 // things failed, so lets look at all traits, for diagnostic purposes now:
1048 let span = self.span;
1051 self.assemble_extension_candidates_for_all_traits();
1053 let out_of_scope_traits = match self.pick_core() {
1054 Some(Ok(p)) => vec![p.item.container_id(self.tcx)],
1055 Some(Err(MethodError::Ambiguity(v))) => v
1057 .map(|source| match source {
1058 CandidateSource::Trait(id) => id,
1059 CandidateSource::Impl(impl_id) => match tcx.trait_id_of_impl(impl_id) {
1061 None => span_bug!(span, "found inherent method when looking at traits"),
1065 Some(Err(MethodError::NoMatch(NoMatchData {
1066 out_of_scope_traits: others, ..
1068 assert!(others.is_empty());
1074 if let Some((kind, def_id)) = private_candidate {
1075 return Err(MethodError::PrivateMatch(kind, def_id, out_of_scope_traits));
1077 let lev_candidate = self.probe_for_lev_candidate()?;
1079 Err(MethodError::NoMatch(NoMatchData {
1081 unsatisfied_predicates,
1082 out_of_scope_traits,
1088 fn pick_core(&self) -> Option<PickResult<'tcx>> {
1089 let pick = self.pick_all_method(Some(&mut vec![]));
1091 // In this case unstable picking is done by `pick_method`.
1092 if !self.tcx.sess.opts.unstable_opts.pick_stable_methods_before_any_unstable {
1097 return self.pick_all_method(None);
1104 mut unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1105 ) -> Option<PickResult<'tcx>> {
1109 debug!("pick_all_method: step={:?}", step);
1110 // skip types that are from a type error or that would require dereferencing
1112 !step.self_ty.references_error() && !step.from_unsafe_deref
1115 let InferOk { value: self_ty, obligations: _ } = self
1117 .probe_instantiate_query_response(
1119 &self.orig_steps_var_values,
1122 .unwrap_or_else(|_| {
1123 span_bug!(self.span, "{:?} was applicable but now isn't?", step.self_ty)
1125 self.pick_by_value_method(step, self_ty, unstable_candidates.as_deref_mut())
1127 self.pick_autorefd_method(
1130 hir::Mutability::Not,
1131 unstable_candidates.as_deref_mut(),
1134 self.pick_autorefd_method(
1137 hir::Mutability::Mut,
1138 unstable_candidates.as_deref_mut(),
1142 self.pick_const_ptr_method(
1145 unstable_candidates.as_deref_mut(),
1152 /// For each type `T` in the step list, this attempts to find a method where
1153 /// the (transformed) self type is exactly `T`. We do however do one
1154 /// transformation on the adjustment: if we are passing a region pointer in,
1155 /// we will potentially *reborrow* it to a shorter lifetime. This allows us
1156 /// to transparently pass `&mut` pointers, in particular, without consuming
1157 /// them for their entire lifetime.
1158 fn pick_by_value_method(
1160 step: &CandidateStep<'tcx>,
1162 unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1163 ) -> Option<PickResult<'tcx>> {
1168 self.pick_method(self_ty, unstable_candidates).map(|r| {
1170 pick.autoderefs = step.autoderefs;
1172 // Insert a `&*` or `&mut *` if this is a reference type:
1173 if let ty::Ref(_, _, mutbl) = *step.self_ty.value.value.kind() {
1174 pick.autoderefs += 1;
1175 pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::Autoref {
1177 unsize: pick.autoref_or_ptr_adjustment.map_or(false, |a| a.get_unsize()),
1186 fn pick_autorefd_method(
1188 step: &CandidateStep<'tcx>,
1190 mutbl: hir::Mutability,
1191 unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1192 ) -> Option<PickResult<'tcx>> {
1195 // In general, during probing we erase regions.
1196 let region = tcx.lifetimes.re_erased;
1198 let autoref_ty = tcx.mk_ref(region, ty::TypeAndMut { ty: self_ty, mutbl });
1199 self.pick_method(autoref_ty, unstable_candidates).map(|r| {
1201 pick.autoderefs = step.autoderefs;
1202 pick.autoref_or_ptr_adjustment =
1203 Some(AutorefOrPtrAdjustment::Autoref { mutbl, unsize: step.unsize });
1209 /// If `self_ty` is `*mut T` then this picks `*const T` methods. The reason why we have a
1210 /// special case for this is because going from `*mut T` to `*const T` with autoderefs and
1211 /// autorefs would require dereferencing the pointer, which is not safe.
1212 fn pick_const_ptr_method(
1214 step: &CandidateStep<'tcx>,
1216 unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1217 ) -> Option<PickResult<'tcx>> {
1218 // Don't convert an unsized reference to ptr
1223 let &ty::RawPtr(ty::TypeAndMut { ty, mutbl: hir::Mutability::Mut }) = self_ty.kind() else {
1227 let const_self_ty = ty::TypeAndMut { ty, mutbl: hir::Mutability::Not };
1228 let const_ptr_ty = self.tcx.mk_ptr(const_self_ty);
1229 self.pick_method(const_ptr_ty, unstable_candidates).map(|r| {
1231 pick.autoderefs = step.autoderefs;
1232 pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::ToConstPtr);
1238 fn pick_method_with_unstable(&self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
1239 debug!("pick_method_with_unstable(self_ty={})", self.ty_to_string(self_ty));
1241 let mut possibly_unsatisfied_predicates = Vec::new();
1243 for (kind, candidates) in
1244 &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1246 debug!("searching {} candidates", kind);
1247 let res = self.consider_candidates(
1250 &mut possibly_unsatisfied_predicates,
1258 for (kind, candidates) in
1259 &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1261 debug!("searching unstable {kind} candidates");
1262 let res = self.consider_candidates(
1265 &mut possibly_unsatisfied_predicates,
1273 self.unsatisfied_predicates.borrow_mut().extend(possibly_unsatisfied_predicates);
1280 mut unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1281 ) -> Option<PickResult<'tcx>> {
1282 if !self.tcx.sess.opts.unstable_opts.pick_stable_methods_before_any_unstable {
1283 return self.pick_method_with_unstable(self_ty);
1286 debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1288 let mut possibly_unsatisfied_predicates = Vec::new();
1290 for (kind, candidates) in
1291 &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1293 debug!("searching {} candidates", kind);
1294 let res = self.consider_candidates(
1297 &mut possibly_unsatisfied_predicates,
1298 unstable_candidates.as_deref_mut(),
1300 if let Some(pick) = res {
1305 // `pick_method` may be called twice for the same self_ty if no stable methods
1306 // match. Only extend once.
1307 if unstable_candidates.is_some() {
1308 self.unsatisfied_predicates.borrow_mut().extend(possibly_unsatisfied_predicates);
1313 fn consider_candidates(
1316 candidates: &[Candidate<'tcx>],
1317 possibly_unsatisfied_predicates: &mut Vec<(
1318 ty::Predicate<'tcx>,
1319 Option<ty::Predicate<'tcx>>,
1320 Option<ObligationCause<'tcx>>,
1322 mut unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1323 ) -> Option<PickResult<'tcx>> {
1324 let mut applicable_candidates: Vec<_> = candidates
1327 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1329 .filter(|&(_, status)| status != ProbeResult::NoMatch)
1332 debug!("applicable_candidates: {:?}", applicable_candidates);
1334 if applicable_candidates.len() > 1 {
1336 self.collapse_candidates_to_trait_pick(self_ty, &applicable_candidates)
1338 return Some(Ok(pick));
1342 if let Some(uc) = &mut unstable_candidates {
1343 applicable_candidates.retain(|&(candidate, _)| {
1344 if let stability::EvalResult::Deny { feature, .. } =
1345 self.tcx.eval_stability(candidate.item.def_id, None, self.span, None)
1347 uc.push((candidate.clone(), feature));
1354 if applicable_candidates.len() > 1 {
1355 let sources = candidates.iter().map(|p| self.candidate_source(p, self_ty)).collect();
1356 return Some(Err(MethodError::Ambiguity(sources)));
1359 applicable_candidates.pop().map(|(probe, status)| {
1360 if status == ProbeResult::Match {
1362 .to_unadjusted_pick(self_ty, unstable_candidates.cloned().unwrap_or_default()))
1364 Err(MethodError::BadReturnType)
1370 impl<'tcx> Pick<'tcx> {
1371 /// In case there were unstable name collisions, emit them as a lint.
1372 /// Checks whether two picks do not refer to the same trait item for the same `Self` type.
1373 /// Only useful for comparisons of picks in order to improve diagnostics.
1374 /// Do not use for type checking.
1375 pub fn differs_from(&self, other: &Self) -> bool {
1383 trait_item_def_id: _,
1384 fn_has_self_parameter: _,
1389 autoref_or_ptr_adjustment: _,
1391 unstable_candidates: _,
1393 self_ty != other.self_ty || def_id != other.item.def_id
1396 /// In case there were unstable name collisions, emit them as a lint.
1397 pub fn maybe_emit_unstable_name_collision_hint(
1401 scope_expr_id: hir::HirId,
1403 if self.unstable_candidates.is_empty() {
1406 let def_kind = self.item.kind.as_def_kind();
1407 tcx.struct_span_lint_hir(
1408 lint::builtin::UNSTABLE_NAME_COLLISIONS,
1412 "{} {} with this name may be added to the standard library in the future",
1414 def_kind.descr(self.item.def_id),
1417 match (self.item.kind, self.item.container) {
1418 (ty::AssocKind::Fn, _) => {
1419 // FIXME: This should be a `span_suggestion` instead of `help`
1420 // However `self.span` only
1421 // highlights the method name, so we can't use it. Also consider reusing
1422 // the code from `report_method_error()`.
1424 "call with fully qualified syntax `{}(...)` to keep using the current \
1426 tcx.def_path_str(self.item.def_id),
1429 (ty::AssocKind::Const, ty::AssocItemContainer::TraitContainer) => {
1430 let def_id = self.item.container_id(tcx);
1431 lint.span_suggestion(
1433 "use the fully qualified path to the associated const",
1437 tcx.def_path_str(def_id),
1440 Applicability::MachineApplicable,
1445 if tcx.sess.is_nightly_build() {
1446 for (candidate, feature) in &self.unstable_candidates {
1448 "add `#![feature({})]` to the crate attributes to enable `{}`",
1450 tcx.def_path_str(candidate.item.def_id),
1461 impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
1462 fn select_trait_candidate(
1464 trait_ref: ty::TraitRef<'tcx>,
1465 ) -> traits::SelectionResult<'tcx, traits::Selection<'tcx>> {
1466 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1467 let predicate = ty::Binder::dummy(trait_ref);
1468 let obligation = traits::Obligation::new(self.tcx, cause, self.param_env, predicate);
1469 traits::SelectionContext::new(self).select(&obligation)
1472 fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>) -> CandidateSource {
1473 match candidate.kind {
1474 InherentImplCandidate(..) => {
1475 CandidateSource::Impl(candidate.item.container_id(self.tcx))
1477 ObjectCandidate | WhereClauseCandidate(_) => {
1478 CandidateSource::Trait(candidate.item.container_id(self.tcx))
1480 TraitCandidate(trait_ref) => self.probe(|_| {
1482 .at(&ObligationCause::dummy(), self.param_env)
1483 .define_opaque_types(false)
1484 .sup(candidate.xform_self_ty, self_ty);
1485 match self.select_trait_candidate(trait_ref) {
1486 Ok(Some(traits::ImplSource::UserDefined(ref impl_data))) => {
1487 // If only a single impl matches, make the error message point
1489 CandidateSource::Impl(impl_data.impl_def_id)
1491 _ => CandidateSource::Trait(candidate.item.container_id(self.tcx)),
1500 probe: &Candidate<'tcx>,
1501 possibly_unsatisfied_predicates: &mut Vec<(
1502 ty::Predicate<'tcx>,
1503 Option<ty::Predicate<'tcx>>,
1504 Option<ObligationCause<'tcx>>,
1507 debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1510 // First check that the self type can be related.
1511 let sub_obligations = match self
1512 .at(&ObligationCause::dummy(), self.param_env)
1513 .define_opaque_types(false)
1514 .sup(probe.xform_self_ty, self_ty)
1516 Ok(InferOk { obligations, value: () }) => obligations,
1518 debug!("--> cannot relate self-types {:?}", err);
1519 return ProbeResult::NoMatch;
1523 let mut result = ProbeResult::Match;
1524 let mut xform_ret_ty = probe.xform_ret_ty;
1525 debug!(?xform_ret_ty);
1527 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1529 let mut parent_pred = None;
1531 // If so, impls may carry other conditions (e.g., where
1532 // clauses) that must be considered. Make sure that those
1533 // match as well (or at least may match, sometimes we
1534 // don't have enough information to fully evaluate).
1536 InherentImplCandidate(ref substs, ref ref_obligations) => {
1537 // `xform_ret_ty` hasn't been normalized yet, only `xform_self_ty`,
1538 // see the reasons mentioned in the comments in `assemble_inherent_impl_probe`
1539 // for why this is necessary
1541 value: normalized_xform_ret_ty,
1542 obligations: normalization_obligations,
1543 } = self.fcx.at(&cause, self.param_env).normalize(probe.xform_ret_ty);
1544 xform_ret_ty = normalized_xform_ret_ty;
1545 debug!("xform_ret_ty after normalization: {:?}", xform_ret_ty);
1547 // Check whether the impl imposes obligations we have to worry about.
1548 let impl_def_id = probe.item.container_id(self.tcx);
1549 let impl_bounds = self.tcx.predicates_of(impl_def_id);
1550 let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1552 let InferOk { value: impl_bounds, obligations: norm_obligations } =
1553 self.fcx.at(&cause, self.param_env).normalize(impl_bounds);
1555 // Convert the bounds into obligations.
1556 let impl_obligations = traits::predicates_for_generics(
1557 move |_, _| cause.clone(),
1562 let candidate_obligations = impl_obligations
1563 .chain(norm_obligations.into_iter())
1564 .chain(ref_obligations.iter().cloned())
1565 .chain(normalization_obligations.into_iter());
1567 // Evaluate those obligations to see if they might possibly hold.
1568 for o in candidate_obligations {
1569 let o = self.resolve_vars_if_possible(o);
1570 if !self.predicate_may_hold(&o) {
1571 result = ProbeResult::NoMatch;
1572 possibly_unsatisfied_predicates.push((
1581 ObjectCandidate | WhereClauseCandidate(..) => {
1582 // These have no additional conditions to check.
1585 TraitCandidate(trait_ref) => {
1586 if let Some(method_name) = self.method_name {
1587 // Some trait methods are excluded for arrays before 2021.
1588 // (`array.into_iter()` wants a slice iterator for compatibility.)
1589 if self_ty.is_array() && !method_name.span.rust_2021() {
1590 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1591 if trait_def.skip_array_during_method_dispatch {
1592 return ProbeResult::NoMatch;
1597 ty::Binder::dummy(trait_ref).without_const().to_predicate(self.tcx);
1598 parent_pred = Some(predicate);
1600 traits::Obligation::new(self.tcx, cause, self.param_env, predicate);
1601 if !self.predicate_may_hold(&obligation) {
1602 result = ProbeResult::NoMatch;
1604 match self.select_trait_candidate(trait_ref) {
1605 Err(_) => return true,
1606 Ok(Some(impl_source))
1607 if !impl_source.borrow_nested_obligations().is_empty() =>
1609 for obligation in impl_source.borrow_nested_obligations() {
1610 // Determine exactly which obligation wasn't met, so
1611 // that we can give more context in the error.
1612 if !self.predicate_may_hold(obligation) {
1613 let nested_predicate =
1614 self.resolve_vars_if_possible(obligation.predicate);
1616 self.resolve_vars_if_possible(predicate);
1617 let p = if predicate == nested_predicate {
1618 // Avoid "`MyStruct: Foo` which is required by
1619 // `MyStruct: Foo`" in E0599.
1624 possibly_unsatisfied_predicates.push((
1627 Some(obligation.cause.clone()),
1633 // Some nested subobligation of this predicate
1635 let predicate = self.resolve_vars_if_possible(predicate);
1636 possibly_unsatisfied_predicates.push((predicate, None, None));
1641 // This candidate's primary obligation doesn't even
1642 // select - don't bother registering anything in
1643 // `potentially_unsatisfied_predicates`.
1644 return ProbeResult::NoMatch;
1650 // Evaluate those obligations to see if they might possibly hold.
1651 for o in sub_obligations {
1652 let o = self.resolve_vars_if_possible(o);
1653 if !self.predicate_may_hold(&o) {
1654 result = ProbeResult::NoMatch;
1655 possibly_unsatisfied_predicates.push((o.predicate, parent_pred, Some(o.cause)));
1659 if let ProbeResult::Match = result {
1660 if let (Some(return_ty), Some(xform_ret_ty)) = (self.return_type, xform_ret_ty) {
1661 let xform_ret_ty = self.resolve_vars_if_possible(xform_ret_ty);
1663 "comparing return_ty {:?} with xform ret ty {:?}",
1664 return_ty, probe.xform_ret_ty
1667 .at(&ObligationCause::dummy(), self.param_env)
1668 .define_opaque_types(false)
1669 .sup(return_ty, xform_ret_ty)
1672 return ProbeResult::BadReturnType;
1681 /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1682 /// same trait, but we don't know which impl to use. In this case, since in all cases the
1683 /// external interface of the method can be determined from the trait, it's ok not to decide.
1684 /// We can basically just collapse all of the probes for various impls into one where-clause
1685 /// probe. This will result in a pending obligation so when more type-info is available we can
1686 /// make the final decision.
1688 /// Example (`src/test/ui/method-two-trait-defer-resolution-1.rs`):
1690 /// ```ignore (illustrative)
1691 /// trait Foo { ... }
1692 /// impl Foo for Vec<i32> { ... }
1693 /// impl Foo for Vec<usize> { ... }
1696 /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1697 /// use, so it's ok to just commit to "using the method from the trait Foo".
1698 fn collapse_candidates_to_trait_pick(
1701 probes: &[(&Candidate<'tcx>, ProbeResult)],
1702 ) -> Option<Pick<'tcx>> {
1703 // Do all probes correspond to the same trait?
1704 let container = probes[0].0.item.trait_container(self.tcx)?;
1705 for (p, _) in &probes[1..] {
1706 let p_container = p.item.trait_container(self.tcx)?;
1707 if p_container != container {
1712 // FIXME: check the return type here somehow.
1713 // If so, just use this trait and call it a day.
1715 item: probes[0].0.item,
1717 import_ids: probes[0].0.import_ids.clone(),
1719 autoref_or_ptr_adjustment: None,
1721 unstable_candidates: vec![],
1725 /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
1726 /// candidate method where the method name may have been misspelled. Similarly to other
1727 /// Levenshtein based suggestions, we provide at most one such suggestion.
1728 fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssocItem>, MethodError<'tcx>> {
1729 debug!("probing for method names similar to {:?}", self.method_name);
1731 let steps = self.steps.clone();
1733 let mut pcx = ProbeContext::new(
1739 &self.orig_steps_var_values,
1743 pcx.allow_similar_names = true;
1744 pcx.assemble_inherent_candidates();
1746 let method_names = pcx.candidate_method_names(|_| true);
1747 pcx.allow_similar_names = false;
1748 let applicable_close_candidates: Vec<ty::AssocItem> = method_names
1750 .filter_map(|&method_name| {
1752 pcx.method_name = Some(method_name);
1753 pcx.assemble_inherent_candidates();
1754 pcx.pick_core().and_then(|pick| pick.ok()).map(|pick| pick.item)
1758 if applicable_close_candidates.is_empty() {
1762 let names = applicable_close_candidates
1764 .map(|cand| cand.name)
1765 .collect::<Vec<Symbol>>();
1766 find_best_match_for_name_with_substrings(
1768 self.method_name.unwrap().name,
1773 Ok(applicable_close_candidates.into_iter().find(|method| method.name == best_name))
1778 ///////////////////////////////////////////////////////////////////////////
1780 fn has_applicable_self(&self, item: &ty::AssocItem) -> bool {
1781 // "Fast track" -- check for usage of sugar when in method call
1784 // In Path mode (i.e., resolving a value like `T::next`), consider any
1785 // associated value (i.e., methods, constants) but not types.
1787 Mode::MethodCall => item.fn_has_self_parameter,
1788 Mode::Path => match item.kind {
1789 ty::AssocKind::Type => false,
1790 ty::AssocKind::Fn | ty::AssocKind::Const => true,
1793 // FIXME -- check for types that deref to `Self`,
1794 // like `Rc<Self>` and so on.
1796 // Note also that the current code will break if this type
1797 // includes any of the type parameters defined on the method
1798 // -- but this could be overcome.
1801 fn record_static_candidate(&self, source: CandidateSource) {
1802 self.static_candidates.borrow_mut().push(source);
1805 #[instrument(level = "debug", skip(self))]
1808 item: &ty::AssocItem,
1810 substs: SubstsRef<'tcx>,
1811 ) -> (Ty<'tcx>, Option<Ty<'tcx>>) {
1812 if item.kind == ty::AssocKind::Fn && self.mode == Mode::MethodCall {
1813 let sig = self.xform_method_sig(item.def_id, substs);
1814 (sig.inputs()[0], Some(sig.output()))
1820 #[instrument(level = "debug", skip(self))]
1821 fn xform_method_sig(&self, method: DefId, substs: SubstsRef<'tcx>) -> ty::FnSig<'tcx> {
1822 let fn_sig = self.tcx.bound_fn_sig(method);
1825 assert!(!substs.has_escaping_bound_vars());
1827 // It is possible for type parameters or early-bound lifetimes
1828 // to appear in the signature of `self`. The substitutions we
1829 // are given do not include type/lifetime parameters for the
1830 // method yet. So create fresh variables here for those too,
1831 // if there are any.
1832 let generics = self.tcx.generics_of(method);
1833 assert_eq!(substs.len(), generics.parent_count as usize);
1835 let xform_fn_sig = if generics.params.is_empty() {
1836 fn_sig.subst(self.tcx, substs)
1838 let substs = InternalSubsts::for_item(self.tcx, method, |param, _| {
1839 let i = param.index as usize;
1840 if i < substs.len() {
1844 GenericParamDefKind::Lifetime => {
1845 // In general, during probe we erase regions.
1846 self.tcx.lifetimes.re_erased.into()
1848 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
1849 self.var_for_def(self.span, param)
1854 fn_sig.subst(self.tcx, substs)
1857 self.erase_late_bound_regions(xform_fn_sig)
1860 /// Gets the type of an impl and generate substitutions with inference vars.
1861 fn impl_ty_and_substs(
1864 ) -> (ty::EarlyBinder<Ty<'tcx>>, SubstsRef<'tcx>) {
1865 (self.tcx.bound_type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1868 fn fresh_item_substs(&self, def_id: DefId) -> SubstsRef<'tcx> {
1869 InternalSubsts::for_item(self.tcx, def_id, |param, _| match param.kind {
1870 GenericParamDefKind::Lifetime => self.tcx.lifetimes.re_erased.into(),
1871 GenericParamDefKind::Type { .. } => self
1872 .next_ty_var(TypeVariableOrigin {
1873 kind: TypeVariableOriginKind::SubstitutionPlaceholder,
1874 span: self.tcx.def_span(def_id),
1877 GenericParamDefKind::Const { .. } => {
1878 let span = self.tcx.def_span(def_id);
1879 let origin = ConstVariableOrigin {
1880 kind: ConstVariableOriginKind::SubstitutionPlaceholder,
1883 self.next_const_var(self.tcx.type_of(param.def_id), origin).into()
1888 /// Replaces late-bound-regions bound by `value` with `'static` using
1889 /// `ty::erase_late_bound_regions`.
1891 /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1892 /// method matching. It is reasonable during the probe phase because we don't consider region
1893 /// relationships at all. Therefore, we can just replace all the region variables with 'static
1894 /// rather than creating fresh region variables. This is nice for two reasons:
1896 /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1897 /// particular method call, it winds up creating fewer types overall, which helps for memory
1898 /// usage. (Admittedly, this is a rather small effect, though measurable.)
1900 /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1901 /// late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1902 /// regions with actual region variables as is proper, we'd have to ensure that the same
1903 /// region got replaced with the same variable, which requires a bit more coordination
1904 /// and/or tracking the substitution and
1906 fn erase_late_bound_regions<T>(&self, value: ty::Binder<'tcx, T>) -> T
1908 T: TypeFoldable<'tcx>,
1910 self.tcx.erase_late_bound_regions(value)
1913 /// Determine if the given associated item type is relevant in the current context.
1914 fn is_relevant_kind_for_mode(&self, kind: ty::AssocKind) -> bool {
1915 match (self.mode, kind) {
1916 (Mode::MethodCall, ty::AssocKind::Fn) => true,
1917 (Mode::Path, ty::AssocKind::Const | ty::AssocKind::Fn) => true,
1922 /// Finds the method with the appropriate name (or return type, as the case may be). If
1923 /// `allow_similar_names` is set, find methods with close-matching names.
1924 // The length of the returned iterator is nearly always 0 or 1 and this
1925 // method is fairly hot.
1926 fn impl_or_trait_item(&self, def_id: DefId) -> SmallVec<[ty::AssocItem; 1]> {
1927 if let Some(name) = self.method_name {
1928 if self.allow_similar_names {
1929 let max_dist = max(name.as_str().len(), 3) / 3;
1931 .associated_items(def_id)
1932 .in_definition_order()
1934 if !self.is_relevant_kind_for_mode(x.kind) {
1937 match lev_distance_with_substrings(name.as_str(), x.name.as_str(), max_dist)
1947 .associated_value(def_id, name)
1948 .filter(|x| self.is_relevant_kind_for_mode(x.kind))
1949 .map_or_else(SmallVec::new, |x| SmallVec::from_buf([x]))
1953 .associated_items(def_id)
1954 .in_definition_order()
1955 .filter(|x| self.is_relevant_kind_for_mode(x.kind))
1962 impl<'tcx> Candidate<'tcx> {
1963 fn to_unadjusted_pick(
1966 unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
1970 kind: match self.kind {
1971 InherentImplCandidate(..) => InherentImplPick,
1972 ObjectCandidate => ObjectPick,
1973 TraitCandidate(_) => TraitPick,
1974 WhereClauseCandidate(ref trait_ref) => {
1975 // Only trait derived from where-clauses should
1976 // appear here, so they should not contain any
1977 // inference variables or other artifacts. This
1978 // means they are safe to put into the
1979 // `WhereClausePick`.
1981 !trait_ref.skip_binder().substs.needs_infer()
1982 && !trait_ref.skip_binder().substs.has_placeholders()
1985 WhereClausePick(*trait_ref)
1988 import_ids: self.import_ids.clone(),
1990 autoref_or_ptr_adjustment: None,
1992 unstable_candidates,