]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/method/probe.rs
Auto merge of #104376 - compiler-errors:thin-metadata-implies-thin-ptr, r=wesleywiser
[rust.git] / compiler / rustc_hir_typeck / src / method / probe.rs
1 use super::suggest;
2 use super::CandidateSource;
3 use super::MethodError;
4 use super::NoMatchData;
5
6 use crate::errors::MethodCallOnUnknownType;
7 use crate::FnCtxt;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::Applicability;
10 use rustc_hir as hir;
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,
29 };
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,
37 };
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;
42 use std::cmp::max;
43 use std::iter;
44 use std::ops::Deref;
45
46 use smallvec::{smallvec, SmallVec};
47
48 use self::CandidateKind::*;
49 pub use self::PickKind::*;
50
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);
55
56 struct ProbeContext<'a, 'tcx> {
57     fcx: &'a FnCtxt<'a, 'tcx>,
58     span: Span,
59     mode: Mode,
60     method_name: Option<Ident>,
61     return_type: Option<Ty<'tcx>>,
62
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>],
67
68     inherent_candidates: Vec<Candidate<'tcx>>,
69     extension_candidates: Vec<Candidate<'tcx>>,
70     impl_dups: FxHashSet<DefId>,
71
72     /// When probing for names, include names that are close to the
73     /// requested name (by Levenshtein distance)
74     allow_similar_names: bool,
75
76     /// Some(candidate) if there is a private candidate
77     private_candidate: Option<(DefKind, DefId)>,
78
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>>,
82
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>>)>,
87     >,
88
89     scope_expr_id: hir::HirId,
90 }
91
92 impl<'a, 'tcx> Deref for ProbeContext<'a, 'tcx> {
93     type Target = FnCtxt<'a, 'tcx>;
94     fn deref(&self) -> &Self::Target {
95         self.fcx
96     }
97 }
98
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).
103     //
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.
109     //
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".
115     //
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.
119     //
120     // For example, if we have this candidate:
121     // ```
122     //    trait Foo {
123     //        fn foo(&self) where Self: Sized;
124     //    }
125     // ```
126     //
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
131     // if `T: Sized`.
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]>,
137 }
138
139 #[derive(Debug, Clone)]
140 pub(crate) enum CandidateKind<'tcx> {
141     InherentImplCandidate(
142         SubstsRef<'tcx>,
143         // Normalize obligations
144         Vec<traits::PredicateObligation<'tcx>>,
145     ),
146     ObjectCandidate,
147     TraitCandidate(ty::TraitRef<'tcx>),
148     WhereClauseCandidate(
149         // Trait
150         ty::PolyTraitRef<'tcx>,
151     ),
152 }
153
154 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
155 enum ProbeResult {
156     NoMatch,
157     BadReturnType,
158     Match,
159 }
160
161 /// When adjusting a receiver we often want to do one of
162 ///
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`
165 ///
166 /// This type tells us which one to do.
167 ///
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.
177     Autoref {
178         mutbl: hir::Mutability,
179
180         /// Indicates that the source expression should be "unsized" to a target type.
181         /// This is special-cased for just arrays unsizing to slices.
182         unsize: bool,
183     },
184     /// Receiver has type `*mut T`, convert to `*const T`
185     ToConstPtr,
186 }
187
188 impl AutorefOrPtrAdjustment {
189     fn get_unsize(&self) -> bool {
190         match self {
191             AutorefOrPtrAdjustment::Autoref { mutbl: _, unsize } => *unsize,
192             AutorefOrPtrAdjustment::ToConstPtr => false,
193         }
194     }
195 }
196
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]>,
202
203     /// Indicates that the source expression should be autoderef'd N times
204     /// ```ignore (not-rust)
205     /// A = expr | *expr | **expr | ...
206     /// ```
207     pub autoderefs: usize,
208
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>,
213
214     /// Unstable candidates alongside the stable ones.
215     unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
216 }
217
218 #[derive(Clone, Debug, PartialEq, Eq)]
219 pub enum PickKind<'tcx> {
220     InherentImplPick,
221     ObjectPick,
222     TraitPick,
223     WhereClausePick(
224         // Trait
225         ty::PolyTraitRef<'tcx>,
226     ),
227 }
228
229 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
230
231 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
232 pub enum Mode {
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.
236     MethodCall,
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.
240     Path,
241 }
242
243 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
244 pub enum ProbeScope {
245     // Assemble candidates coming only from traits in scope.
246     TraitsInScope,
247
248     // Assemble candidates coming from all traits.
249     AllTraits,
250 }
251
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(
261         &self,
262         span: Span,
263         mode: Mode,
264         return_type: Ty<'tcx>,
265         self_ty: 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
270             .probe_op(
271                 span,
272                 mode,
273                 None,
274                 Some(return_type),
275                 IsSuggestion(true),
276                 self_ty,
277                 scope_expr_id,
278                 ProbeScope::AllTraits,
279                 |probe_cx| Ok(probe_cx.candidate_method_names(candidate_filter)),
280             )
281             .unwrap_or_default();
282         method_names
283             .iter()
284             .flat_map(|&method_name| {
285                 self.probe_op(
286                     span,
287                     mode,
288                     Some(method_name),
289                     Some(return_type),
290                     IsSuggestion(true),
291                     self_ty,
292                     scope_expr_id,
293                     ProbeScope::AllTraits,
294                     |probe_cx| probe_cx.pick(),
295                 )
296                 .ok()
297                 .map(|pick| pick.item)
298             })
299             .collect()
300     }
301
302     #[instrument(level = "debug", skip(self))]
303     pub fn probe_for_name(
304         &self,
305         mode: Mode,
306         item_name: Ident,
307         is_suggestion: IsSuggestion,
308         self_ty: Ty<'tcx>,
309         scope_expr_id: hir::HirId,
310         scope: ProbeScope,
311     ) -> PickResult<'tcx> {
312         self.probe_op(
313             item_name.span,
314             mode,
315             Some(item_name),
316             None,
317             is_suggestion,
318             self_ty,
319             scope_expr_id,
320             scope,
321             |probe_cx| probe_cx.pick(),
322         )
323     }
324
325     #[instrument(level = "debug", skip(self))]
326     pub(crate) fn probe_for_name_many(
327         &self,
328         mode: Mode,
329         item_name: Ident,
330         is_suggestion: IsSuggestion,
331         self_ty: Ty<'tcx>,
332         scope_expr_id: hir::HirId,
333         scope: ProbeScope,
334     ) -> Vec<Candidate<'tcx>> {
335         self.probe_op(
336             item_name.span,
337             mode,
338             Some(item_name),
339             None,
340             is_suggestion,
341             self_ty,
342             scope_expr_id,
343             scope,
344             |probe_cx| {
345                 Ok(probe_cx
346                     .inherent_candidates
347                     .into_iter()
348                     .chain(probe_cx.extension_candidates)
349                     .collect())
350             },
351         )
352         .unwrap()
353     }
354
355     fn probe_op<OP, R>(
356         &'a self,
357         span: Span,
358         mode: Mode,
359         method_name: Option<Ident>,
360         return_type: Option<Ty<'tcx>>,
361         is_suggestion: IsSuggestion,
362         self_ty: Ty<'tcx>,
363         scope_expr_id: hir::HirId,
364         scope: ProbeScope,
365         op: OP,
366     ) -> Result<R, MethodError<'tcx>>
367     where
368         OP: FnOnce(ProbeContext<'_, 'tcx>) -> Result<R, MethodError<'tcx>>,
369     {
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 },
373             &mut orig_values,
374         );
375
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.
383
384                 let infcx = &self.infcx;
385                 let (ParamEnvAnd { param_env: _, value: self_ty }, canonical_inference_vars) =
386                     infcx.instantiate_canonical_with_fresh_inference_vars(
387                         span,
388                         &param_env_and_self_ty,
389                     );
390                 debug!(
391                     "probe_op: Mode::Path, param_env_and_self_ty={:?} self_ty={:?}",
392                     param_env_and_self_ty, self_ty
393                 );
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,
398                             self_ty,
399                         ),
400                         autoderefs: 0,
401                         from_unsafe_deref: false,
402                         unsize: false,
403                     }]),
404                     opt_bad_ty: None,
405                     reached_recursion_limit: false,
406                 }
407             }),
408         };
409
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 {
414             self.probe(|_| {
415                 let ty = &steps
416                     .steps
417                     .last()
418                     .unwrap_or_else(|| span_bug!(span, "reached the recursion limit in 0 steps?"))
419                     .self_ty;
420                 let ty = self
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);
424             });
425         }
426
427         // If we encountered an `_` type or an error type during autoderef, this is
428         // ambiguous.
429         if let Some(bad_ty) = &steps.opt_bad_ty {
430             if is_suggestion.0 {
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 });
439                 } else {
440                     self.tcx.struct_span_lint_hir(
441                         lint::builtin::TYVAR_BEHIND_RAW_POINTER,
442                         scope_expr_id,
443                         span,
444                         "type annotations needed",
445                         |lint| lint,
446                     );
447                 }
448             } else {
449                 // Encountered a real ambiguity, so abort the lookup. If `ty` is not
450                 // an `Err`, report the right "type annotations needed" error pointing
451                 // to it.
452                 let ty = &bad_ty.ty;
453                 let ty = self
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(),
462                     lev_candidate: None,
463                     mode,
464                 }));
465             }
466         }
467
468         debug!("ProbeContext: steps for self_ty={:?} are {:?}", self_ty, steps);
469
470         // this creates one big transaction so that all type variables etc
471         // that we create during the probe process are removed later
472         self.probe(|_| {
473             let mut probe_cx = ProbeContext::new(
474                 self,
475                 span,
476                 mode,
477                 method_name,
478                 return_type,
479                 &orig_values,
480                 steps.steps,
481                 scope_expr_id,
482             );
483
484             probe_cx.assemble_inherent_candidates();
485             match scope {
486                 ProbeScope::TraitsInScope => {
487                     probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)
488                 }
489                 ProbeScope::AllTraits => probe_cx.assemble_extension_candidates_for_all_traits(),
490             };
491             op(probe_cx)
492         })
493     }
494 }
495
496 pub fn provide(providers: &mut ty::query::Providers) {
497     providers.method_autoderef_steps = method_autoderef_steps;
498 }
499
500 fn method_autoderef_steps<'tcx>(
501     tcx: TyCtxt<'tcx>,
502     goal: CanonicalTyGoal<'tcx>,
503 ) -> MethodAutoderefStepsResult<'tcx> {
504     debug!("method_autoderef_steps({:?})", goal);
505
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;
508
509     let mut autoderef = Autoderef::new(infcx, param_env, hir::CRATE_HIR_ID, DUMMY_SP, self_ty)
510         .include_raw_pointers()
511         .silence_errors();
512     let mut reached_raw_pointer = false;
513     let mut steps: Vec<_> = autoderef
514         .by_ref()
515         .map(|(ty, d)| {
516             let step = CandidateStep {
517                 self_ty: infcx
518                     .make_query_response_ignoring_pending_obligations(inference_vars.clone(), ty),
519                 autoderefs: d,
520                 from_unsafe_deref: reached_raw_pointer,
521                 unsize: false,
522             };
523             if let ty::RawPtr(_) = ty.kind() {
524                 // all the subsequent steps will be from_unsafe_deref
525                 reached_raw_pointer = true;
526             }
527             step
528         })
529         .collect();
530
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 {
534             reached_raw_pointer,
535             ty: infcx.make_query_response_ignoring_pending_obligations(inference_vars, final_ty),
536         }),
537         ty::Array(elem_ty, _) => {
538             let dereferences = steps.len() - 1;
539
540             steps.push(CandidateStep {
541                 self_ty: infcx.make_query_response_ignoring_pending_obligations(
542                     inference_vars,
543                     infcx.tcx.mk_slice(*elem_ty),
544                 ),
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,
549                 unsize: true,
550             });
551
552             None
553         }
554         _ => None,
555     };
556
557     debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
558
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(),
563     }
564 }
565
566 impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
567     fn new(
568         fcx: &'a FnCtxt<'a, 'tcx>,
569         span: Span,
570         mode: Mode,
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> {
577         ProbeContext {
578             fcx,
579             span,
580             mode,
581             method_name,
582             return_type,
583             inherent_candidates: Vec::new(),
584             extension_candidates: Vec::new(),
585             impl_dups: FxHashSet::default(),
586             orig_steps_var_values,
587             steps,
588             allow_similar_names: false,
589             private_candidate: None,
590             static_candidates: RefCell::new(Vec::new()),
591             unsatisfied_predicates: RefCell::new(Vec::new()),
592             scope_expr_id,
593         }
594     }
595
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();
603     }
604
605     ///////////////////////////////////////////////////////////////////////////
606     // CANDIDATE ASSEMBLY
607
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;
611             let def_scope = self
612                 .tcx
613                 .adjust_ident_and_get_scope(name, item.container_id(self.tcx), self.body_id)
614                 .1;
615             item.visibility(self.tcx).is_accessible_from(def_scope, self.tcx)
616         } else {
617             true
618         };
619         if is_accessible {
620             if is_inherent {
621                 self.inherent_candidates.push(candidate);
622             } else {
623                 self.extension_candidates.push(candidate);
624             }
625         } else if self.private_candidate.is_none() {
626             self.private_candidate =
627                 Some((candidate.item.kind.as_def_kind(), candidate.item.def_id));
628         }
629     }
630
631     fn assemble_inherent_candidates(&mut self) {
632         for step in self.steps.iter() {
633             self.assemble_probe(&step.self_ty);
634         }
635     }
636
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).
645                 //
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.
653                 //
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) =
660                     self.fcx
661                         .instantiate_canonical_with_fresh_inference_vars(self.span, self_ty);
662
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);
667                 }
668             }
669             ty::Adt(def, _) => {
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);
674                 }
675             }
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);
680                 }
681             }
682             ty::Param(p) => {
683                 self.assemble_inherent_candidates_from_param(p);
684             }
685             ty::Bool
686             | ty::Char
687             | ty::Int(_)
688             | ty::Uint(_)
689             | ty::Float(_)
690             | ty::Str
691             | ty::Array(..)
692             | ty::Slice(_)
693             | ty::RawPtr(_)
694             | ty::Ref(..)
695             | ty::Never
696             | ty::Tuple(..) => self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty),
697             _ => {}
698         }
699     }
700
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)
704         };
705         for &impl_def_id in self.tcx.incoherent_impls(simp) {
706             self.assemble_inherent_impl_probe(impl_def_id);
707         }
708     }
709
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);
714         }
715     }
716
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
720         }
721
722         debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
723
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));
728                 continue;
729             }
730
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);
733
734             debug!("impl_ty: {:?}", impl_ty);
735
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);
739
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,
748             // see issue #89650
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);
752
753             debug!(
754                 "assemble_inherent_impl_probe after normalization: xform_self_ty = {:?}/{:?}",
755                 xform_self_ty, xform_ret_ty
756             );
757
758             self.push_candidate(
759                 Candidate {
760                     xform_self_ty,
761                     xform_ret_ty,
762                     item,
763                     kind: InherentImplCandidate(impl_substs, obligations),
764                     import_ids: smallvec![],
765                 },
766                 true,
767             );
768         }
769     }
770
771     fn assemble_inherent_candidates_from_object(&mut self, self_ty: Ty<'tcx>) {
772         debug!("assemble_inherent_candidates_from_object(self_ty={:?})", self_ty);
773
774         let principal = match self_ty.kind() {
775             ty::Dynamic(ref data, ..) => Some(data),
776             _ => None,
777         }
778         .and_then(|data| data.principal())
779         .unwrap_or_else(|| {
780             span_bug!(
781                 self.span,
782                 "non-object {:?} in assemble_inherent_candidates_from_object",
783                 self_ty
784             )
785         });
786
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);
796
797             let (xform_self_ty, xform_ret_ty) =
798                 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
799             this.push_candidate(
800                 Candidate {
801                     xform_self_ty,
802                     xform_ret_ty,
803                     item,
804                     kind: ObjectCandidate,
805                     import_ids: smallvec![],
806                 },
807                 true,
808             );
809         });
810     }
811
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);
815
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))
823                         }
824                         _ => None,
825                     }
826                 }
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,
839             }
840         });
841
842         self.elaborate_bounds(bounds, |this, poly_trait_ref, item| {
843             let trait_ref = this.erase_late_bound_regions(poly_trait_ref);
844
845             let (xform_self_ty, xform_ret_ty) =
846                 this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
847
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());
854
855             this.push_candidate(
856                 Candidate {
857                     xform_self_ty,
858                     xform_ret_ty,
859                     item,
860                     kind: WhereClauseCandidate(poly_trait_ref),
861                     import_ids: smallvec![],
862                 },
863                 true,
864             );
865         });
866     }
867
868     // Do a search through a list of bounds, using a callback to actually
869     // create the candidates.
870     fn elaborate_bounds<F>(
871         &mut self,
872         bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
873         mut mk_cand: F,
874     ) where
875         F: for<'b> FnMut(&mut ProbeContext<'b, 'tcx>, ty::PolyTraitRef<'tcx>, ty::AssocItem),
876     {
877         let tcx = self.tcx;
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()));
883                 } else {
884                     mk_cand(self, bound_trait_ref, item);
885                 }
886             }
887         }
888     }
889
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,
899                         trait_did,
900                     );
901                 }
902             }
903         }
904     }
905
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);
911             }
912         }
913     }
914
915     fn matches_return_type(
916         &self,
917         method: &ty::AssocItem,
918         self_ty: Option<Ty<'tcx>>,
919         expected: Ty<'tcx>,
920     ) -> bool {
921         match method.kind {
922             ty::AssocKind::Fn => {
923                 let fty = self.tcx.bound_fn_sig(method.def_id);
924                 self.probe(|_| {
925                     let substs = self.fresh_substs_for_item(self.span, method.def_id);
926                     let fty = fty.subst(self.tcx, substs);
927                     let fty =
928                         self.replace_bound_vars_with_fresh_vars(self.span, infer::FnCall, fty);
929
930                     if let Some(self_ty) = self_ty {
931                         if self
932                             .at(&ObligationCause::dummy(), self.param_env)
933                             .sup(fty.inputs()[0], self_ty)
934                             .is_err()
935                         {
936                             return false;
937                         }
938                     }
939                     self.can_sub(self.param_env, fty.output(), expected).is_ok()
940                 })
941             }
942             _ => false,
943         }
944     }
945
946     fn assemble_extension_candidates_for_trait(
947         &mut self,
948         import_ids: &SmallVec<[LocalDefId; 1]>,
949         trait_def_id: DefId,
950     ) {
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);
954
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);
960
961                 let (xform_self_ty, xform_ret_ty) =
962                     this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
963                 this.push_candidate(
964                     Candidate {
965                         xform_self_ty,
966                         xform_ret_ty,
967                         item,
968                         import_ids: import_ids.clone(),
969                         kind: TraitCandidate(new_trait_ref),
970                     },
971                     false,
972                 );
973             });
974         } else {
975             debug_assert!(self.tcx.is_trait(trait_def_id));
976             if self.tcx.trait_is_auto(trait_def_id) {
977                 return;
978             }
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));
984                     continue;
985                 }
986
987                 let (xform_self_ty, xform_ret_ty) =
988                     self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
989                 self.push_candidate(
990                     Candidate {
991                         xform_self_ty,
992                         xform_ret_ty,
993                         item,
994                         import_ids: import_ids.clone(),
995                         kind: TraitCandidate(trait_ref),
996                     },
997                     false,
998                 );
999             }
1000         }
1001     }
1002
1003     fn candidate_method_names(
1004         &self,
1005         candidate_filter: impl Fn(&ty::AssocItem) -> bool,
1006     ) -> Vec<Ident> {
1007         let mut set = FxHashSet::default();
1008         let mut names: Vec<_> = self
1009             .inherent_candidates
1010             .iter()
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)
1016                 } else {
1017                     true
1018                 }
1019             })
1020             .map(|candidate| candidate.item.ident(self.tcx))
1021             .filter(|&name| set.insert(name))
1022             .collect();
1023
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());
1026         names
1027     }
1028
1029     ///////////////////////////////////////////////////////////////////////////
1030     // THE ACTUAL SEARCH
1031
1032     fn pick(mut self) -> PickResult<'tcx> {
1033         assert!(self.method_name.is_some());
1034
1035         if let Some(r) = self.pick_core() {
1036             return r;
1037         }
1038
1039         debug!("pick: actual search failed, assemble diagnostics");
1040
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());
1044
1045         // things failed, so lets look at all traits, for diagnostic purposes now:
1046         self.reset();
1047
1048         let span = self.span;
1049         let tcx = self.tcx;
1050
1051         self.assemble_extension_candidates_for_all_traits();
1052
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
1056                 .into_iter()
1057                 .map(|source| match source {
1058                     CandidateSource::Trait(id) => id,
1059                     CandidateSource::Impl(impl_id) => match tcx.trait_id_of_impl(impl_id) {
1060                         Some(id) => id,
1061                         None => span_bug!(span, "found inherent method when looking at traits"),
1062                     },
1063                 })
1064                 .collect(),
1065             Some(Err(MethodError::NoMatch(NoMatchData {
1066                 out_of_scope_traits: others, ..
1067             }))) => {
1068                 assert!(others.is_empty());
1069                 vec![]
1070             }
1071             _ => vec![],
1072         };
1073
1074         if let Some((kind, def_id)) = private_candidate {
1075             return Err(MethodError::PrivateMatch(kind, def_id, out_of_scope_traits));
1076         }
1077         let lev_candidate = self.probe_for_lev_candidate()?;
1078
1079         Err(MethodError::NoMatch(NoMatchData {
1080             static_candidates,
1081             unsatisfied_predicates,
1082             out_of_scope_traits,
1083             lev_candidate,
1084             mode: self.mode,
1085         }))
1086     }
1087
1088     fn pick_core(&self) -> Option<PickResult<'tcx>> {
1089         let pick = self.pick_all_method(Some(&mut vec![]));
1090
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 {
1093             return pick;
1094         }
1095
1096         if pick.is_none() {
1097             return self.pick_all_method(None);
1098         }
1099         pick
1100     }
1101
1102     fn pick_all_method(
1103         &self,
1104         mut unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1105     ) -> Option<PickResult<'tcx>> {
1106         self.steps
1107             .iter()
1108             .filter(|step| {
1109                 debug!("pick_all_method: step={:?}", step);
1110                 // skip types that are from a type error or that would require dereferencing
1111                 // a raw pointer
1112                 !step.self_ty.references_error() && !step.from_unsafe_deref
1113             })
1114             .find_map(|step| {
1115                 let InferOk { value: self_ty, obligations: _ } = self
1116                     .fcx
1117                     .probe_instantiate_query_response(
1118                         self.span,
1119                         &self.orig_steps_var_values,
1120                         &step.self_ty,
1121                     )
1122                     .unwrap_or_else(|_| {
1123                         span_bug!(self.span, "{:?} was applicable but now isn't?", step.self_ty)
1124                     });
1125                 self.pick_by_value_method(step, self_ty, unstable_candidates.as_deref_mut())
1126                     .or_else(|| {
1127                         self.pick_autorefd_method(
1128                             step,
1129                             self_ty,
1130                             hir::Mutability::Not,
1131                             unstable_candidates.as_deref_mut(),
1132                         )
1133                         .or_else(|| {
1134                             self.pick_autorefd_method(
1135                                 step,
1136                                 self_ty,
1137                                 hir::Mutability::Mut,
1138                                 unstable_candidates.as_deref_mut(),
1139                             )
1140                         })
1141                         .or_else(|| {
1142                             self.pick_const_ptr_method(
1143                                 step,
1144                                 self_ty,
1145                                 unstable_candidates.as_deref_mut(),
1146                             )
1147                         })
1148                     })
1149             })
1150     }
1151
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(
1159         &self,
1160         step: &CandidateStep<'tcx>,
1161         self_ty: Ty<'tcx>,
1162         unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1163     ) -> Option<PickResult<'tcx>> {
1164         if step.unsize {
1165             return None;
1166         }
1167
1168         self.pick_method(self_ty, unstable_candidates).map(|r| {
1169             r.map(|mut pick| {
1170                 pick.autoderefs = step.autoderefs;
1171
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 {
1176                         mutbl,
1177                         unsize: pick.autoref_or_ptr_adjustment.map_or(false, |a| a.get_unsize()),
1178                     })
1179                 }
1180
1181                 pick
1182             })
1183         })
1184     }
1185
1186     fn pick_autorefd_method(
1187         &self,
1188         step: &CandidateStep<'tcx>,
1189         self_ty: Ty<'tcx>,
1190         mutbl: hir::Mutability,
1191         unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1192     ) -> Option<PickResult<'tcx>> {
1193         let tcx = self.tcx;
1194
1195         // In general, during probing we erase regions.
1196         let region = tcx.lifetimes.re_erased;
1197
1198         let autoref_ty = tcx.mk_ref(region, ty::TypeAndMut { ty: self_ty, mutbl });
1199         self.pick_method(autoref_ty, unstable_candidates).map(|r| {
1200             r.map(|mut pick| {
1201                 pick.autoderefs = step.autoderefs;
1202                 pick.autoref_or_ptr_adjustment =
1203                     Some(AutorefOrPtrAdjustment::Autoref { mutbl, unsize: step.unsize });
1204                 pick
1205             })
1206         })
1207     }
1208
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(
1213         &self,
1214         step: &CandidateStep<'tcx>,
1215         self_ty: Ty<'tcx>,
1216         unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1217     ) -> Option<PickResult<'tcx>> {
1218         // Don't convert an unsized reference to ptr
1219         if step.unsize {
1220             return None;
1221         }
1222
1223         let &ty::RawPtr(ty::TypeAndMut { ty, mutbl: hir::Mutability::Mut }) = self_ty.kind() else {
1224             return None;
1225         };
1226
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| {
1230             r.map(|mut pick| {
1231                 pick.autoderefs = step.autoderefs;
1232                 pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::ToConstPtr);
1233                 pick
1234             })
1235         })
1236     }
1237
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));
1240
1241         let mut possibly_unsatisfied_predicates = Vec::new();
1242
1243         for (kind, candidates) in
1244             &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1245         {
1246             debug!("searching {} candidates", kind);
1247             let res = self.consider_candidates(
1248                 self_ty,
1249                 candidates,
1250                 &mut possibly_unsatisfied_predicates,
1251                 Some(&mut vec![]),
1252             );
1253             if res.is_some() {
1254                 return res;
1255             }
1256         }
1257
1258         for (kind, candidates) in
1259             &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1260         {
1261             debug!("searching unstable {kind} candidates");
1262             let res = self.consider_candidates(
1263                 self_ty,
1264                 candidates,
1265                 &mut possibly_unsatisfied_predicates,
1266                 None,
1267             );
1268             if res.is_some() {
1269                 return res;
1270             }
1271         }
1272
1273         self.unsatisfied_predicates.borrow_mut().extend(possibly_unsatisfied_predicates);
1274         None
1275     }
1276
1277     fn pick_method(
1278         &self,
1279         self_ty: Ty<'tcx>,
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);
1284         }
1285
1286         debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1287
1288         let mut possibly_unsatisfied_predicates = Vec::new();
1289
1290         for (kind, candidates) in
1291             &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1292         {
1293             debug!("searching {} candidates", kind);
1294             let res = self.consider_candidates(
1295                 self_ty,
1296                 candidates,
1297                 &mut possibly_unsatisfied_predicates,
1298                 unstable_candidates.as_deref_mut(),
1299             );
1300             if let Some(pick) = res {
1301                 return Some(pick);
1302             }
1303         }
1304
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);
1309         }
1310         None
1311     }
1312
1313     fn consider_candidates(
1314         &self,
1315         self_ty: Ty<'tcx>,
1316         candidates: &[Candidate<'tcx>],
1317         possibly_unsatisfied_predicates: &mut Vec<(
1318             ty::Predicate<'tcx>,
1319             Option<ty::Predicate<'tcx>>,
1320             Option<ObligationCause<'tcx>>,
1321         )>,
1322         mut unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
1323     ) -> Option<PickResult<'tcx>> {
1324         let mut applicable_candidates: Vec<_> = candidates
1325             .iter()
1326             .map(|probe| {
1327                 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1328             })
1329             .filter(|&(_, status)| status != ProbeResult::NoMatch)
1330             .collect();
1331
1332         debug!("applicable_candidates: {:?}", applicable_candidates);
1333
1334         if applicable_candidates.len() > 1 {
1335             if let Some(pick) =
1336                 self.collapse_candidates_to_trait_pick(self_ty, &applicable_candidates)
1337             {
1338                 return Some(Ok(pick));
1339             }
1340         }
1341
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)
1346                 {
1347                     uc.push((candidate.clone(), feature));
1348                     return false;
1349                 }
1350                 true
1351             });
1352         }
1353
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)));
1357         }
1358
1359         applicable_candidates.pop().map(|(probe, status)| {
1360             if status == ProbeResult::Match {
1361                 Ok(probe
1362                     .to_unadjusted_pick(self_ty, unstable_candidates.cloned().unwrap_or_default()))
1363             } else {
1364                 Err(MethodError::BadReturnType)
1365             }
1366         })
1367     }
1368 }
1369
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 {
1376         let Self {
1377             item:
1378                 AssocItem {
1379                     def_id,
1380                     name: _,
1381                     kind: _,
1382                     container: _,
1383                     trait_item_def_id: _,
1384                     fn_has_self_parameter: _,
1385                 },
1386             kind: _,
1387             import_ids: _,
1388             autoderefs: _,
1389             autoref_or_ptr_adjustment: _,
1390             self_ty,
1391             unstable_candidates: _,
1392         } = *self;
1393         self_ty != other.self_ty || def_id != other.item.def_id
1394     }
1395
1396     /// In case there were unstable name collisions, emit them as a lint.
1397     pub fn maybe_emit_unstable_name_collision_hint(
1398         &self,
1399         tcx: TyCtxt<'tcx>,
1400         span: Span,
1401         scope_expr_id: hir::HirId,
1402     ) {
1403         if self.unstable_candidates.is_empty() {
1404             return;
1405         }
1406         let def_kind = self.item.kind.as_def_kind();
1407         tcx.struct_span_lint_hir(
1408             lint::builtin::UNSTABLE_NAME_COLLISIONS,
1409             scope_expr_id,
1410             span,
1411             format!(
1412                 "{} {} with this name may be added to the standard library in the future",
1413                 def_kind.article(),
1414                 def_kind.descr(self.item.def_id),
1415             ),
1416             |lint| {
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()`.
1423                         lint.help(&format!(
1424                             "call with fully qualified syntax `{}(...)` to keep using the current \
1425                              method",
1426                             tcx.def_path_str(self.item.def_id),
1427                         ));
1428                     }
1429                     (ty::AssocKind::Const, ty::AssocItemContainer::TraitContainer) => {
1430                         let def_id = self.item.container_id(tcx);
1431                         lint.span_suggestion(
1432                             span,
1433                             "use the fully qualified path to the associated const",
1434                             format!(
1435                                 "<{} as {}>::{}",
1436                                 self.self_ty,
1437                                 tcx.def_path_str(def_id),
1438                                 self.item.name
1439                             ),
1440                             Applicability::MachineApplicable,
1441                         );
1442                     }
1443                     _ => {}
1444                 }
1445                 if tcx.sess.is_nightly_build() {
1446                     for (candidate, feature) in &self.unstable_candidates {
1447                         lint.help(&format!(
1448                             "add `#![feature({})]` to the crate attributes to enable `{}`",
1449                             feature,
1450                             tcx.def_path_str(candidate.item.def_id),
1451                         ));
1452                     }
1453                 }
1454
1455                 lint
1456             },
1457         );
1458     }
1459 }
1460
1461 impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
1462     fn select_trait_candidate(
1463         &self,
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)
1470     }
1471
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))
1476             }
1477             ObjectCandidate | WhereClauseCandidate(_) => {
1478                 CandidateSource::Trait(candidate.item.container_id(self.tcx))
1479             }
1480             TraitCandidate(trait_ref) => self.probe(|_| {
1481                 let _ = self
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
1488                         // to that impl.
1489                         CandidateSource::Impl(impl_data.impl_def_id)
1490                     }
1491                     _ => CandidateSource::Trait(candidate.item.container_id(self.tcx)),
1492                 }
1493             }),
1494         }
1495     }
1496
1497     fn consider_probe(
1498         &self,
1499         self_ty: Ty<'tcx>,
1500         probe: &Candidate<'tcx>,
1501         possibly_unsatisfied_predicates: &mut Vec<(
1502             ty::Predicate<'tcx>,
1503             Option<ty::Predicate<'tcx>>,
1504             Option<ObligationCause<'tcx>>,
1505         )>,
1506     ) -> ProbeResult {
1507         debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1508
1509         self.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)
1515             {
1516                 Ok(InferOk { obligations, value: () }) => obligations,
1517                 Err(err) => {
1518                     debug!("--> cannot relate self-types {:?}", err);
1519                     return ProbeResult::NoMatch;
1520                 }
1521             };
1522
1523             let mut result = ProbeResult::Match;
1524             let mut xform_ret_ty = probe.xform_ret_ty;
1525             debug!(?xform_ret_ty);
1526
1527             let cause = traits::ObligationCause::misc(self.span, self.body_id);
1528
1529             let mut parent_pred = None;
1530
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).
1535             match probe.kind {
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
1540                     let InferOk {
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);
1546
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);
1551
1552                     let InferOk { value: impl_bounds, obligations: norm_obligations } =
1553                         self.fcx.at(&cause, self.param_env).normalize(impl_bounds);
1554
1555                     // Convert the bounds into obligations.
1556                     let impl_obligations = traits::predicates_for_generics(
1557                         move |_, _| cause.clone(),
1558                         self.param_env,
1559                         impl_bounds,
1560                     );
1561
1562                     let candidate_obligations = impl_obligations
1563                         .chain(norm_obligations.into_iter())
1564                         .chain(ref_obligations.iter().cloned())
1565                         .chain(normalization_obligations.into_iter());
1566
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((
1573                                 o.predicate,
1574                                 None,
1575                                 Some(o.cause),
1576                             ));
1577                         }
1578                     }
1579                 }
1580
1581                 ObjectCandidate | WhereClauseCandidate(..) => {
1582                     // These have no additional conditions to check.
1583                 }
1584
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;
1593                             }
1594                         }
1595                     }
1596                     let predicate =
1597                         ty::Binder::dummy(trait_ref).without_const().to_predicate(self.tcx);
1598                     parent_pred = Some(predicate);
1599                     let obligation =
1600                         traits::Obligation::new(self.tcx, cause, self.param_env, predicate);
1601                     if !self.predicate_may_hold(&obligation) {
1602                         result = ProbeResult::NoMatch;
1603                         if self.probe(|_| {
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() =>
1608                                 {
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);
1615                                             let 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.
1620                                                 None
1621                                             } else {
1622                                                 Some(predicate)
1623                                             };
1624                                             possibly_unsatisfied_predicates.push((
1625                                                 nested_predicate,
1626                                                 p,
1627                                                 Some(obligation.cause.clone()),
1628                                             ));
1629                                         }
1630                                     }
1631                                 }
1632                                 _ => {
1633                                     // Some nested subobligation of this predicate
1634                                     // failed.
1635                                     let predicate = self.resolve_vars_if_possible(predicate);
1636                                     possibly_unsatisfied_predicates.push((predicate, None, None));
1637                                 }
1638                             }
1639                             false
1640                         }) {
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;
1645                         }
1646                     }
1647                 }
1648             }
1649
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)));
1656                 }
1657             }
1658
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);
1662                     debug!(
1663                         "comparing return_ty {:?} with xform ret ty {:?}",
1664                         return_ty, probe.xform_ret_ty
1665                     );
1666                     if self
1667                         .at(&ObligationCause::dummy(), self.param_env)
1668                         .define_opaque_types(false)
1669                         .sup(return_ty, xform_ret_ty)
1670                         .is_err()
1671                     {
1672                         return ProbeResult::BadReturnType;
1673                     }
1674                 }
1675             }
1676
1677             result
1678         })
1679     }
1680
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.
1687     ///
1688     /// Example (`src/test/ui/method-two-trait-defer-resolution-1.rs`):
1689     ///
1690     /// ```ignore (illustrative)
1691     /// trait Foo { ... }
1692     /// impl Foo for Vec<i32> { ... }
1693     /// impl Foo for Vec<usize> { ... }
1694     /// ```
1695     ///
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(
1699         &self,
1700         self_ty: Ty<'tcx>,
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 {
1708                 return None;
1709             }
1710         }
1711
1712         // FIXME: check the return type here somehow.
1713         // If so, just use this trait and call it a day.
1714         Some(Pick {
1715             item: probes[0].0.item,
1716             kind: TraitPick,
1717             import_ids: probes[0].0.import_ids.clone(),
1718             autoderefs: 0,
1719             autoref_or_ptr_adjustment: None,
1720             self_ty,
1721             unstable_candidates: vec![],
1722         })
1723     }
1724
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);
1730
1731         let steps = self.steps.clone();
1732         self.probe(|_| {
1733             let mut pcx = ProbeContext::new(
1734                 self.fcx,
1735                 self.span,
1736                 self.mode,
1737                 self.method_name,
1738                 self.return_type,
1739                 &self.orig_steps_var_values,
1740                 steps,
1741                 self.scope_expr_id,
1742             );
1743             pcx.allow_similar_names = true;
1744             pcx.assemble_inherent_candidates();
1745
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
1749                 .iter()
1750                 .filter_map(|&method_name| {
1751                     pcx.reset();
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)
1755                 })
1756                 .collect();
1757
1758             if applicable_close_candidates.is_empty() {
1759                 Ok(None)
1760             } else {
1761                 let best_name = {
1762                     let names = applicable_close_candidates
1763                         .iter()
1764                         .map(|cand| cand.name)
1765                         .collect::<Vec<Symbol>>();
1766                     find_best_match_for_name_with_substrings(
1767                         &names,
1768                         self.method_name.unwrap().name,
1769                         None,
1770                     )
1771                 }
1772                 .unwrap();
1773                 Ok(applicable_close_candidates.into_iter().find(|method| method.name == best_name))
1774             }
1775         })
1776     }
1777
1778     ///////////////////////////////////////////////////////////////////////////
1779     // MISCELLANY
1780     fn has_applicable_self(&self, item: &ty::AssocItem) -> bool {
1781         // "Fast track" -- check for usage of sugar when in method call
1782         // mode.
1783         //
1784         // In Path mode (i.e., resolving a value like `T::next`), consider any
1785         // associated value (i.e., methods, constants) but not types.
1786         match self.mode {
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,
1791             },
1792         }
1793         // FIXME -- check for types that deref to `Self`,
1794         // like `Rc<Self>` and so on.
1795         //
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.
1799     }
1800
1801     fn record_static_candidate(&self, source: CandidateSource) {
1802         self.static_candidates.borrow_mut().push(source);
1803     }
1804
1805     #[instrument(level = "debug", skip(self))]
1806     fn xform_self_ty(
1807         &self,
1808         item: &ty::AssocItem,
1809         impl_ty: Ty<'tcx>,
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()))
1815         } else {
1816             (impl_ty, None)
1817         }
1818     }
1819
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);
1823         debug!(?fn_sig);
1824
1825         assert!(!substs.has_escaping_bound_vars());
1826
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);
1834
1835         let xform_fn_sig = if generics.params.is_empty() {
1836             fn_sig.subst(self.tcx, substs)
1837         } else {
1838             let substs = InternalSubsts::for_item(self.tcx, method, |param, _| {
1839                 let i = param.index as usize;
1840                 if i < substs.len() {
1841                     substs[i]
1842                 } else {
1843                     match param.kind {
1844                         GenericParamDefKind::Lifetime => {
1845                             // In general, during probe we erase regions.
1846                             self.tcx.lifetimes.re_erased.into()
1847                         }
1848                         GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
1849                             self.var_for_def(self.span, param)
1850                         }
1851                     }
1852                 }
1853             });
1854             fn_sig.subst(self.tcx, substs)
1855         };
1856
1857         self.erase_late_bound_regions(xform_fn_sig)
1858     }
1859
1860     /// Gets the type of an impl and generate substitutions with inference vars.
1861     fn impl_ty_and_substs(
1862         &self,
1863         impl_def_id: DefId,
1864     ) -> (ty::EarlyBinder<Ty<'tcx>>, SubstsRef<'tcx>) {
1865         (self.tcx.bound_type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1866     }
1867
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),
1875                 })
1876                 .into(),
1877             GenericParamDefKind::Const { .. } => {
1878                 let span = self.tcx.def_span(def_id);
1879                 let origin = ConstVariableOrigin {
1880                     kind: ConstVariableOriginKind::SubstitutionPlaceholder,
1881                     span,
1882                 };
1883                 self.next_const_var(self.tcx.type_of(param.def_id), origin).into()
1884             }
1885         })
1886     }
1887
1888     /// Replaces late-bound-regions bound by `value` with `'static` using
1889     /// `ty::erase_late_bound_regions`.
1890     ///
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:
1895     ///
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.)
1899     ///
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
1905     ///    so forth.
1906     fn erase_late_bound_regions<T>(&self, value: ty::Binder<'tcx, T>) -> T
1907     where
1908         T: TypeFoldable<'tcx>,
1909     {
1910         self.tcx.erase_late_bound_regions(value)
1911     }
1912
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,
1918             _ => false,
1919         }
1920     }
1921
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;
1930                 self.tcx
1931                     .associated_items(def_id)
1932                     .in_definition_order()
1933                     .filter(|x| {
1934                         if !self.is_relevant_kind_for_mode(x.kind) {
1935                             return false;
1936                         }
1937                         match lev_distance_with_substrings(name.as_str(), x.name.as_str(), max_dist)
1938                         {
1939                             Some(d) => d > 0,
1940                             None => false,
1941                         }
1942                     })
1943                     .copied()
1944                     .collect()
1945             } else {
1946                 self.fcx
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]))
1950             }
1951         } else {
1952             self.tcx
1953                 .associated_items(def_id)
1954                 .in_definition_order()
1955                 .filter(|x| self.is_relevant_kind_for_mode(x.kind))
1956                 .copied()
1957                 .collect()
1958         }
1959     }
1960 }
1961
1962 impl<'tcx> Candidate<'tcx> {
1963     fn to_unadjusted_pick(
1964         &self,
1965         self_ty: Ty<'tcx>,
1966         unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
1967     ) -> Pick<'tcx> {
1968         Pick {
1969             item: self.item,
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`.
1980                     assert!(
1981                         !trait_ref.skip_binder().substs.needs_infer()
1982                             && !trait_ref.skip_binder().substs.has_placeholders()
1983                     );
1984
1985                     WhereClausePick(*trait_ref)
1986                 }
1987             },
1988             import_ids: self.import_ids.clone(),
1989             autoderefs: 0,
1990             autoref_or_ptr_adjustment: None,
1991             self_ty,
1992             unstable_candidates,
1993         }
1994     }
1995 }