]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/probe.rs
9c5e3cbc93844a338f77c3c6977b26e59a520e63
[rust.git] / src / librustc_typeck / check / method / probe.rs
1 use super::suggest;
2 use super::MethodError;
3 use super::NoMatchData;
4 use super::{CandidateSource, ImplSource, TraitSource};
5
6 use crate::check::FnCtxt;
7 use crate::hir::def::DefKind;
8 use crate::hir::def_id::DefId;
9
10 use rustc_ast::ast;
11 use rustc_ast::util::lev_distance::{find_best_match_for_name, lev_distance};
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::sync::Lrc;
14 use rustc_errors::struct_span_err;
15 use rustc_hir as hir;
16 use rustc_hir::def::Namespace;
17 use rustc_infer::infer::canonical::OriginalQueryValues;
18 use rustc_infer::infer::canonical::{Canonical, QueryResponse};
19 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
20 use rustc_infer::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
21 use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
22 use rustc_middle::middle::stability;
23 use rustc_middle::ty::subst::{InternalSubsts, Subst, SubstsRef};
24 use rustc_middle::ty::GenericParamDefKind;
25 use rustc_middle::ty::{
26     self, ParamEnvAnd, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
27 };
28 use rustc_session::config::nightly_options;
29 use rustc_session::lint;
30 use rustc_span::def_id::LocalDefId;
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::{self, ObligationCause};
40 use std::cmp::max;
41 use std::iter;
42 use std::mem;
43 use std::ops::Deref;
44
45 use smallvec::{smallvec, SmallVec};
46
47 use self::CandidateKind::*;
48 pub use self::PickKind::*;
49
50 /// Boolean flag used to indicate if this search is for a suggestion
51 /// or not. If true, we can allow ambiguity and so forth.
52 #[derive(Clone, Copy)]
53 pub struct IsSuggestion(pub bool);
54
55 struct ProbeContext<'a, 'tcx> {
56     fcx: &'a FnCtxt<'a, 'tcx>,
57     span: Span,
58     mode: Mode,
59     method_name: Option<Ident>,
60     return_type: Option<Ty<'tcx>>,
61
62     /// This is the OriginalQueryValues for the steps queries
63     /// that are answered in steps.
64     orig_steps_var_values: OriginalQueryValues<'tcx>,
65     steps: Lrc<Vec<CandidateStep<'tcx>>>,
66
67     inherent_candidates: Vec<Candidate<'tcx>>,
68     extension_candidates: Vec<Candidate<'tcx>>,
69     impl_dups: FxHashSet<DefId>,
70
71     /// Collects near misses when the candidate functions are missing a `self` keyword and is only
72     /// used for error reporting
73     static_candidates: Vec<CandidateSource>,
74
75     /// When probing for names, include names that are close to the
76     /// requested name (by Levensthein distance)
77     allow_similar_names: bool,
78
79     /// Some(candidate) if there is a private candidate
80     private_candidate: Option<(DefKind, DefId)>,
81
82     /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
83     /// for error reporting
84     unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
85
86     is_suggestion: IsSuggestion,
87 }
88
89 impl<'a, 'tcx> Deref for ProbeContext<'a, 'tcx> {
90     type Target = FnCtxt<'a, 'tcx>;
91     fn deref(&self) -> &Self::Target {
92         &self.fcx
93     }
94 }
95
96 #[derive(Debug)]
97 struct Candidate<'tcx> {
98     // Candidates are (I'm not quite sure, but they are mostly) basically
99     // some metadata on top of a `ty::AssocItem` (without substs).
100     //
101     // However, method probing wants to be able to evaluate the predicates
102     // for a function with the substs applied - for example, if a function
103     // has `where Self: Sized`, we don't want to consider it unless `Self`
104     // is actually `Sized`, and similarly, return-type suggestions want
105     // to consider the "actual" return type.
106     //
107     // The way this is handled is through `xform_self_ty`. It contains
108     // the receiver type of this candidate, but `xform_self_ty`,
109     // `xform_ret_ty` and `kind` (which contains the predicates) have the
110     // generic parameters of this candidate substituted with the *same set*
111     // of inference variables, which acts as some weird sort of "query".
112     //
113     // When we check out a candidate, we require `xform_self_ty` to be
114     // a subtype of the passed-in self-type, and this equates the type
115     // variables in the rest of the fields.
116     //
117     // For example, if we have this candidate:
118     // ```
119     //    trait Foo {
120     //        fn foo(&self) where Self: Sized;
121     //    }
122     // ```
123     //
124     // Then `xform_self_ty` will be `&'erased ?X` and `kind` will contain
125     // the predicate `?X: Sized`, so if we are evaluating `Foo` for a
126     // the receiver `&T`, we'll do the subtyping which will make `?X`
127     // get the right value, then when we evaluate the predicate we'll check
128     // if `T: Sized`.
129     xform_self_ty: Ty<'tcx>,
130     xform_ret_ty: Option<Ty<'tcx>>,
131     item: ty::AssocItem,
132     kind: CandidateKind<'tcx>,
133     import_ids: SmallVec<[LocalDefId; 1]>,
134 }
135
136 #[derive(Debug)]
137 enum CandidateKind<'tcx> {
138     InherentImplCandidate(
139         SubstsRef<'tcx>,
140         // Normalize obligations
141         Vec<traits::PredicateObligation<'tcx>>,
142     ),
143     ObjectCandidate,
144     TraitCandidate(ty::TraitRef<'tcx>),
145     WhereClauseCandidate(
146         // Trait
147         ty::PolyTraitRef<'tcx>,
148     ),
149 }
150
151 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
152 enum ProbeResult {
153     NoMatch,
154     BadReturnType,
155     Match,
156 }
157
158 #[derive(Debug, PartialEq, Clone)]
159 pub struct Pick<'tcx> {
160     pub item: ty::AssocItem,
161     pub kind: PickKind<'tcx>,
162     pub import_ids: SmallVec<[LocalDefId; 1]>,
163
164     // Indicates that the source expression should be autoderef'd N times
165     //
166     // A = expr | *expr | **expr | ...
167     pub autoderefs: usize,
168
169     // Indicates that an autoref is applied after the optional autoderefs
170     //
171     // B = A | &A | &mut A
172     pub autoref: Option<hir::Mutability>,
173
174     // Indicates that the source expression should be "unsized" to a
175     // target type. This should probably eventually go away in favor
176     // of just coercing method receivers.
177     //
178     // C = B | unsize(B)
179     pub unsize: Option<Ty<'tcx>>,
180 }
181
182 #[derive(Clone, Debug, PartialEq, Eq)]
183 pub enum PickKind<'tcx> {
184     InherentImplPick,
185     ObjectPick,
186     TraitPick,
187     WhereClausePick(
188         // Trait
189         ty::PolyTraitRef<'tcx>,
190     ),
191 }
192
193 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
194
195 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
196 pub enum Mode {
197     // An expression of the form `receiver.method_name(...)`.
198     // Autoderefs are performed on `receiver`, lookup is done based on the
199     // `self` argument  of the method, and static methods aren't considered.
200     MethodCall,
201     // An expression of the form `Type::item` or `<T>::item`.
202     // No autoderefs are performed, lookup is done based on the type each
203     // implementation is for, and static methods are included.
204     Path,
205 }
206
207 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
208 pub enum ProbeScope {
209     // Assemble candidates coming only from traits in scope.
210     TraitsInScope,
211
212     // Assemble candidates coming from all traits.
213     AllTraits,
214 }
215
216 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
217     /// This is used to offer suggestions to users. It returns methods
218     /// that could have been called which have the desired return
219     /// type. Some effort is made to rule out methods that, if called,
220     /// would result in an error (basically, the same criteria we
221     /// would use to decide if a method is a plausible fit for
222     /// ambiguity purposes).
223     pub fn probe_for_return_type(
224         &self,
225         span: Span,
226         mode: Mode,
227         return_type: Ty<'tcx>,
228         self_ty: Ty<'tcx>,
229         scope_expr_id: hir::HirId,
230     ) -> Vec<ty::AssocItem> {
231         debug!(
232             "probe(self_ty={:?}, return_type={}, scope_expr_id={})",
233             self_ty, return_type, scope_expr_id
234         );
235         let method_names = self
236             .probe_op(
237                 span,
238                 mode,
239                 None,
240                 Some(return_type),
241                 IsSuggestion(true),
242                 self_ty,
243                 scope_expr_id,
244                 ProbeScope::AllTraits,
245                 |probe_cx| Ok(probe_cx.candidate_method_names()),
246             )
247             .unwrap_or(vec![]);
248         method_names
249             .iter()
250             .flat_map(|&method_name| {
251                 self.probe_op(
252                     span,
253                     mode,
254                     Some(method_name),
255                     Some(return_type),
256                     IsSuggestion(true),
257                     self_ty,
258                     scope_expr_id,
259                     ProbeScope::AllTraits,
260                     |probe_cx| probe_cx.pick(),
261                 )
262                 .ok()
263                 .map(|pick| pick.item)
264             })
265             .collect()
266     }
267
268     pub fn probe_for_name(
269         &self,
270         span: Span,
271         mode: Mode,
272         item_name: Ident,
273         is_suggestion: IsSuggestion,
274         self_ty: Ty<'tcx>,
275         scope_expr_id: hir::HirId,
276         scope: ProbeScope,
277     ) -> PickResult<'tcx> {
278         debug!(
279             "probe(self_ty={:?}, item_name={}, scope_expr_id={})",
280             self_ty, item_name, scope_expr_id
281         );
282         self.probe_op(
283             span,
284             mode,
285             Some(item_name),
286             None,
287             is_suggestion,
288             self_ty,
289             scope_expr_id,
290             scope,
291             |probe_cx| probe_cx.pick(),
292         )
293     }
294
295     fn probe_op<OP, R>(
296         &'a self,
297         span: Span,
298         mode: Mode,
299         method_name: Option<Ident>,
300         return_type: Option<Ty<'tcx>>,
301         is_suggestion: IsSuggestion,
302         self_ty: Ty<'tcx>,
303         scope_expr_id: hir::HirId,
304         scope: ProbeScope,
305         op: OP,
306     ) -> Result<R, MethodError<'tcx>>
307     where
308         OP: FnOnce(ProbeContext<'a, 'tcx>) -> Result<R, MethodError<'tcx>>,
309     {
310         let mut orig_values = OriginalQueryValues::default();
311         let param_env_and_self_ty = self.infcx.canonicalize_query(
312             &ParamEnvAnd { param_env: self.param_env, value: self_ty },
313             &mut orig_values,
314         );
315
316         let steps = if mode == Mode::MethodCall {
317             self.tcx.method_autoderef_steps(param_env_and_self_ty)
318         } else {
319             self.infcx.probe(|_| {
320                 // Mode::Path - the deref steps is "trivial". This turns
321                 // our CanonicalQuery into a "trivial" QueryResponse. This
322                 // is a bit inefficient, but I don't think that writing
323                 // special handling for this "trivial case" is a good idea.
324
325                 let infcx = &self.infcx;
326                 let (ParamEnvAnd { param_env: _, value: self_ty }, canonical_inference_vars) =
327                     infcx.instantiate_canonical_with_fresh_inference_vars(
328                         span,
329                         &param_env_and_self_ty,
330                     );
331                 debug!(
332                     "probe_op: Mode::Path, param_env_and_self_ty={:?} self_ty={:?}",
333                     param_env_and_self_ty, self_ty
334                 );
335                 MethodAutoderefStepsResult {
336                     steps: Lrc::new(vec![CandidateStep {
337                         self_ty: self.make_query_response_ignoring_pending_obligations(
338                             canonical_inference_vars,
339                             self_ty,
340                         ),
341                         autoderefs: 0,
342                         from_unsafe_deref: false,
343                         unsize: false,
344                     }]),
345                     opt_bad_ty: None,
346                     reached_recursion_limit: false,
347                 }
348             })
349         };
350
351         // If our autoderef loop had reached the recursion limit,
352         // report an overflow error, but continue going on with
353         // the truncated autoderef list.
354         if steps.reached_recursion_limit {
355             self.probe(|_| {
356                 let ty = &steps
357                     .steps
358                     .last()
359                     .unwrap_or_else(|| span_bug!(span, "reached the recursion limit in 0 steps?"))
360                     .self_ty;
361                 let ty = self
362                     .probe_instantiate_query_response(span, &orig_values, ty)
363                     .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
364                 autoderef::report_autoderef_recursion_limit_error(self.tcx, span, ty.value);
365             });
366         }
367
368         // If we encountered an `_` type or an error type during autoderef, this is
369         // ambiguous.
370         if let Some(bad_ty) = &steps.opt_bad_ty {
371             if is_suggestion.0 {
372                 // Ambiguity was encountered during a suggestion. Just keep going.
373                 debug!("ProbeContext: encountered ambiguity in suggestion");
374             } else if bad_ty.reached_raw_pointer && !self.tcx.features().arbitrary_self_types {
375                 // this case used to be allowed by the compiler,
376                 // so we do a future-compat lint here for the 2015 edition
377                 // (see https://github.com/rust-lang/rust/issues/46906)
378                 if self.tcx.sess.rust_2018() {
379                     struct_span_err!(
380                         self.tcx.sess,
381                         span,
382                         E0699,
383                         "the type of this value must be known to call a method on a raw pointer on \
384                          it"
385                     )
386                     .emit();
387                 } else {
388                     self.tcx.struct_span_lint_hir(
389                         lint::builtin::TYVAR_BEHIND_RAW_POINTER,
390                         scope_expr_id,
391                         span,
392                         |lint| lint.build("type annotations needed").emit(),
393                     );
394                 }
395             } else {
396                 // Encountered a real ambiguity, so abort the lookup. If `ty` is not
397                 // an `Err`, report the right "type annotations needed" error pointing
398                 // to it.
399                 let ty = &bad_ty.ty;
400                 let ty = self
401                     .probe_instantiate_query_response(span, &orig_values, ty)
402                     .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
403                 let ty = self.structurally_resolved_type(span, ty.value);
404                 assert!(matches!(ty.kind, ty::Error(_)));
405                 return Err(MethodError::NoMatch(NoMatchData::new(
406                     Vec::new(),
407                     Vec::new(),
408                     Vec::new(),
409                     None,
410                     mode,
411                 )));
412             }
413         }
414
415         debug!("ProbeContext: steps for self_ty={:?} are {:?}", self_ty, steps);
416
417         // this creates one big transaction so that all type variables etc
418         // that we create during the probe process are removed later
419         self.probe(|_| {
420             let mut probe_cx = ProbeContext::new(
421                 self,
422                 span,
423                 mode,
424                 method_name,
425                 return_type,
426                 orig_values,
427                 steps.steps,
428                 is_suggestion,
429             );
430
431             probe_cx.assemble_inherent_candidates();
432             match scope {
433                 ProbeScope::TraitsInScope => {
434                     probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?
435                 }
436                 ProbeScope::AllTraits => probe_cx.assemble_extension_candidates_for_all_traits()?,
437             };
438             op(probe_cx)
439         })
440     }
441 }
442
443 pub fn provide(providers: &mut ty::query::Providers) {
444     providers.method_autoderef_steps = method_autoderef_steps;
445 }
446
447 fn method_autoderef_steps<'tcx>(
448     tcx: TyCtxt<'tcx>,
449     goal: CanonicalTyGoal<'tcx>,
450 ) -> MethodAutoderefStepsResult<'tcx> {
451     debug!("method_autoderef_steps({:?})", goal);
452
453     tcx.infer_ctxt().enter_with_canonical(DUMMY_SP, &goal, |ref infcx, goal, inference_vars| {
454         let ParamEnvAnd { param_env, value: self_ty } = goal;
455
456         let mut autoderef = Autoderef::new(infcx, param_env, hir::CRATE_HIR_ID, DUMMY_SP, self_ty)
457             .include_raw_pointers()
458             .silence_errors();
459         let mut reached_raw_pointer = false;
460         let mut steps: Vec<_> = autoderef
461             .by_ref()
462             .map(|(ty, d)| {
463                 let step = CandidateStep {
464                     self_ty: infcx.make_query_response_ignoring_pending_obligations(
465                         inference_vars.clone(),
466                         ty,
467                     ),
468                     autoderefs: d,
469                     from_unsafe_deref: reached_raw_pointer,
470                     unsize: false,
471                 };
472                 if let ty::RawPtr(_) = ty.kind {
473                     // all the subsequent steps will be from_unsafe_deref
474                     reached_raw_pointer = true;
475                 }
476                 step
477             })
478             .collect();
479
480         let final_ty = autoderef.final_ty(true);
481         let opt_bad_ty = match final_ty.kind {
482             ty::Infer(ty::TyVar(_)) | ty::Error(_) => Some(MethodAutoderefBadTy {
483                 reached_raw_pointer,
484                 ty: infcx
485                     .make_query_response_ignoring_pending_obligations(inference_vars, final_ty),
486             }),
487             ty::Array(elem_ty, _) => {
488                 let dereferences = steps.len() - 1;
489
490                 steps.push(CandidateStep {
491                     self_ty: infcx.make_query_response_ignoring_pending_obligations(
492                         inference_vars,
493                         infcx.tcx.mk_slice(elem_ty),
494                     ),
495                     autoderefs: dereferences,
496                     // this could be from an unsafe deref if we had
497                     // a *mut/const [T; N]
498                     from_unsafe_deref: reached_raw_pointer,
499                     unsize: true,
500                 });
501
502                 None
503             }
504             _ => None,
505         };
506
507         debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
508
509         MethodAutoderefStepsResult {
510             steps: Lrc::new(steps),
511             opt_bad_ty: opt_bad_ty.map(Lrc::new),
512             reached_recursion_limit: autoderef.reached_recursion_limit(),
513         }
514     })
515 }
516
517 impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
518     fn new(
519         fcx: &'a FnCtxt<'a, 'tcx>,
520         span: Span,
521         mode: Mode,
522         method_name: Option<Ident>,
523         return_type: Option<Ty<'tcx>>,
524         orig_steps_var_values: OriginalQueryValues<'tcx>,
525         steps: Lrc<Vec<CandidateStep<'tcx>>>,
526         is_suggestion: IsSuggestion,
527     ) -> ProbeContext<'a, 'tcx> {
528         ProbeContext {
529             fcx,
530             span,
531             mode,
532             method_name,
533             return_type,
534             inherent_candidates: Vec::new(),
535             extension_candidates: Vec::new(),
536             impl_dups: FxHashSet::default(),
537             orig_steps_var_values,
538             steps,
539             static_candidates: Vec::new(),
540             allow_similar_names: false,
541             private_candidate: None,
542             unsatisfied_predicates: Vec::new(),
543             is_suggestion,
544         }
545     }
546
547     fn reset(&mut self) {
548         self.inherent_candidates.clear();
549         self.extension_candidates.clear();
550         self.impl_dups.clear();
551         self.static_candidates.clear();
552         self.private_candidate = None;
553     }
554
555     ///////////////////////////////////////////////////////////////////////////
556     // CANDIDATE ASSEMBLY
557
558     fn push_candidate(&mut self, candidate: Candidate<'tcx>, is_inherent: bool) {
559         let is_accessible = if let Some(name) = self.method_name {
560             let item = candidate.item;
561             let def_scope =
562                 self.tcx.adjust_ident_and_get_scope(name, item.container.id(), self.body_id).1;
563             item.vis.is_accessible_from(def_scope, self.tcx)
564         } else {
565             true
566         };
567         if is_accessible {
568             if is_inherent {
569                 self.inherent_candidates.push(candidate);
570             } else {
571                 self.extension_candidates.push(candidate);
572             }
573         } else if self.private_candidate.is_none() {
574             self.private_candidate =
575                 Some((candidate.item.kind.as_def_kind(), candidate.item.def_id));
576         }
577     }
578
579     fn assemble_inherent_candidates(&mut self) {
580         let steps = Lrc::clone(&self.steps);
581         for step in steps.iter() {
582             self.assemble_probe(&step.self_ty);
583         }
584     }
585
586     fn assemble_probe(&mut self, self_ty: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>) {
587         debug!("assemble_probe: self_ty={:?}", self_ty);
588         let lang_items = self.tcx.lang_items();
589
590         match self_ty.value.value.kind {
591             ty::Dynamic(ref data, ..) => {
592                 if let Some(p) = data.principal() {
593                     // Subtle: we can't use `instantiate_query_response` here: using it will
594                     // commit to all of the type equalities assumed by inference going through
595                     // autoderef (see the `method-probe-no-guessing` test).
596                     //
597                     // However, in this code, it is OK if we end up with an object type that is
598                     // "more general" than the object type that we are evaluating. For *every*
599                     // object type `MY_OBJECT`, a function call that goes through a trait-ref
600                     // of the form `<MY_OBJECT as SuperTraitOf(MY_OBJECT)>::func` is a valid
601                     // `ObjectCandidate`, and it should be discoverable "exactly" through one
602                     // of the iterations in the autoderef loop, so there is no problem with it
603                     // being discoverable in another one of these iterations.
604                     //
605                     // Using `instantiate_canonical_with_fresh_inference_vars` on our
606                     // `Canonical<QueryResponse<Ty<'tcx>>>` and then *throwing away* the
607                     // `CanonicalVarValues` will exactly give us such a generalization - it
608                     // will still match the original object type, but it won't pollute our
609                     // type variables in any form, so just do that!
610                     let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) =
611                         self.fcx
612                             .instantiate_canonical_with_fresh_inference_vars(self.span, &self_ty);
613
614                     self.assemble_inherent_candidates_from_object(generalized_self_ty);
615                     self.assemble_inherent_impl_candidates_for_type(p.def_id());
616                 }
617             }
618             ty::Adt(def, _) => {
619                 self.assemble_inherent_impl_candidates_for_type(def.did);
620             }
621             ty::Foreign(did) => {
622                 self.assemble_inherent_impl_candidates_for_type(did);
623             }
624             ty::Param(p) => {
625                 self.assemble_inherent_candidates_from_param(p);
626             }
627             ty::Bool => {
628                 let lang_def_id = lang_items.bool_impl();
629                 self.assemble_inherent_impl_for_primitive(lang_def_id);
630             }
631             ty::Char => {
632                 let lang_def_id = lang_items.char_impl();
633                 self.assemble_inherent_impl_for_primitive(lang_def_id);
634             }
635             ty::Str => {
636                 let lang_def_id = lang_items.str_impl();
637                 self.assemble_inherent_impl_for_primitive(lang_def_id);
638
639                 let lang_def_id = lang_items.str_alloc_impl();
640                 self.assemble_inherent_impl_for_primitive(lang_def_id);
641             }
642             ty::Slice(_) => {
643                 for &lang_def_id in &[
644                     lang_items.slice_impl(),
645                     lang_items.slice_u8_impl(),
646                     lang_items.slice_alloc_impl(),
647                     lang_items.slice_u8_alloc_impl(),
648                 ] {
649                     self.assemble_inherent_impl_for_primitive(lang_def_id);
650                 }
651             }
652             ty::RawPtr(ty::TypeAndMut { ty: _, mutbl }) => {
653                 let (lang_def_id1, lang_def_id2) = match mutbl {
654                     hir::Mutability::Not => {
655                         (lang_items.const_ptr_impl(), lang_items.const_slice_ptr_impl())
656                     }
657                     hir::Mutability::Mut => {
658                         (lang_items.mut_ptr_impl(), lang_items.mut_slice_ptr_impl())
659                     }
660                 };
661                 self.assemble_inherent_impl_for_primitive(lang_def_id1);
662                 self.assemble_inherent_impl_for_primitive(lang_def_id2);
663             }
664             ty::Int(i) => {
665                 let lang_def_id = match i {
666                     ast::IntTy::I8 => lang_items.i8_impl(),
667                     ast::IntTy::I16 => lang_items.i16_impl(),
668                     ast::IntTy::I32 => lang_items.i32_impl(),
669                     ast::IntTy::I64 => lang_items.i64_impl(),
670                     ast::IntTy::I128 => lang_items.i128_impl(),
671                     ast::IntTy::Isize => lang_items.isize_impl(),
672                 };
673                 self.assemble_inherent_impl_for_primitive(lang_def_id);
674             }
675             ty::Uint(i) => {
676                 let lang_def_id = match i {
677                     ast::UintTy::U8 => lang_items.u8_impl(),
678                     ast::UintTy::U16 => lang_items.u16_impl(),
679                     ast::UintTy::U32 => lang_items.u32_impl(),
680                     ast::UintTy::U64 => lang_items.u64_impl(),
681                     ast::UintTy::U128 => lang_items.u128_impl(),
682                     ast::UintTy::Usize => lang_items.usize_impl(),
683                 };
684                 self.assemble_inherent_impl_for_primitive(lang_def_id);
685             }
686             ty::Float(f) => {
687                 let (lang_def_id1, lang_def_id2) = match f {
688                     ast::FloatTy::F32 => (lang_items.f32_impl(), lang_items.f32_runtime_impl()),
689                     ast::FloatTy::F64 => (lang_items.f64_impl(), lang_items.f64_runtime_impl()),
690                 };
691                 self.assemble_inherent_impl_for_primitive(lang_def_id1);
692                 self.assemble_inherent_impl_for_primitive(lang_def_id2);
693             }
694             _ => {}
695         }
696     }
697
698     fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
699         if let Some(impl_def_id) = lang_def_id {
700             self.assemble_inherent_impl_probe(impl_def_id);
701         }
702     }
703
704     fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
705         let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
706         for &impl_def_id in impl_def_ids.iter() {
707             self.assemble_inherent_impl_probe(impl_def_id);
708         }
709     }
710
711     fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
712         if !self.impl_dups.insert(impl_def_id) {
713             return; // already visited
714         }
715
716         debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
717
718         for item in self.impl_or_trait_item(impl_def_id) {
719             if !self.has_applicable_self(&item) {
720                 // No receiver declared. Not a candidate.
721                 self.record_static_candidate(ImplSource(impl_def_id));
722                 continue;
723             }
724
725             let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
726             let impl_ty = impl_ty.subst(self.tcx, impl_substs);
727
728             // Determine the receiver type that the method itself expects.
729             let xform_tys = self.xform_self_ty(&item, impl_ty, impl_substs);
730
731             // We can't use normalize_associated_types_in as it will pollute the
732             // fcx's fulfillment context after this probe is over.
733             let cause = traits::ObligationCause::misc(self.span, self.body_id);
734             let selcx = &mut traits::SelectionContext::new(self.fcx);
735             let traits::Normalized { value: (xform_self_ty, xform_ret_ty), obligations } =
736                 traits::normalize(selcx, self.param_env, cause, &xform_tys);
737             debug!(
738                 "assemble_inherent_impl_probe: xform_self_ty = {:?}/{:?}",
739                 xform_self_ty, xform_ret_ty
740             );
741
742             self.push_candidate(
743                 Candidate {
744                     xform_self_ty,
745                     xform_ret_ty,
746                     item,
747                     kind: InherentImplCandidate(impl_substs, obligations),
748                     import_ids: smallvec![],
749                 },
750                 true,
751             );
752         }
753     }
754
755     fn assemble_inherent_candidates_from_object(&mut self, self_ty: Ty<'tcx>) {
756         debug!("assemble_inherent_candidates_from_object(self_ty={:?})", self_ty);
757
758         let principal = match self_ty.kind {
759             ty::Dynamic(ref data, ..) => Some(data),
760             _ => None,
761         }
762         .and_then(|data| data.principal())
763         .unwrap_or_else(|| {
764             span_bug!(
765                 self.span,
766                 "non-object {:?} in assemble_inherent_candidates_from_object",
767                 self_ty
768             )
769         });
770
771         // It is illegal to invoke a method on a trait instance that
772         // refers to the `Self` type. An error will be reported by
773         // `enforce_object_limitations()` if the method refers to the
774         // `Self` type anywhere other than the receiver. Here, we use
775         // a substitution that replaces `Self` with the object type
776         // itself. Hence, a `&self` method will wind up with an
777         // argument type like `&Trait`.
778         let trait_ref = principal.with_self_ty(self.tcx, self_ty);
779         self.elaborate_bounds(iter::once(trait_ref), |this, new_trait_ref, item| {
780             let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
781
782             let (xform_self_ty, xform_ret_ty) =
783                 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
784             this.push_candidate(
785                 Candidate {
786                     xform_self_ty,
787                     xform_ret_ty,
788                     item,
789                     kind: ObjectCandidate,
790                     import_ids: smallvec![],
791                 },
792                 true,
793             );
794         });
795     }
796
797     fn assemble_inherent_candidates_from_param(&mut self, param_ty: ty::ParamTy) {
798         // FIXME: do we want to commit to this behavior for param bounds?
799         debug!("assemble_inherent_candidates_from_param(param_ty={:?})", param_ty);
800
801         let bounds = self.param_env.caller_bounds().iter().filter_map(|predicate| match predicate
802             .kind()
803         {
804             ty::PredicateKind::Trait(ref trait_predicate, _) => {
805                 match trait_predicate.skip_binder().trait_ref.self_ty().kind {
806                     ty::Param(ref p) if *p == param_ty => Some(trait_predicate.to_poly_trait_ref()),
807                     _ => None,
808                 }
809             }
810             ty::PredicateKind::Subtype(..)
811             | ty::PredicateKind::Projection(..)
812             | ty::PredicateKind::RegionOutlives(..)
813             | ty::PredicateKind::WellFormed(..)
814             | ty::PredicateKind::ObjectSafe(..)
815             | ty::PredicateKind::ClosureKind(..)
816             | ty::PredicateKind::TypeOutlives(..)
817             | ty::PredicateKind::ConstEvaluatable(..)
818             | ty::PredicateKind::ConstEquate(..) => None,
819         });
820
821         self.elaborate_bounds(bounds, |this, poly_trait_ref, item| {
822             let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
823
824             let (xform_self_ty, xform_ret_ty) =
825                 this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
826
827             // Because this trait derives from a where-clause, it
828             // should not contain any inference variables or other
829             // artifacts. This means it is safe to put into the
830             // `WhereClauseCandidate` and (eventually) into the
831             // `WhereClausePick`.
832             assert!(!trait_ref.substs.needs_infer());
833
834             this.push_candidate(
835                 Candidate {
836                     xform_self_ty,
837                     xform_ret_ty,
838                     item,
839                     kind: WhereClauseCandidate(poly_trait_ref),
840                     import_ids: smallvec![],
841                 },
842                 true,
843             );
844         });
845     }
846
847     // Do a search through a list of bounds, using a callback to actually
848     // create the candidates.
849     fn elaborate_bounds<F>(
850         &mut self,
851         bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
852         mut mk_cand: F,
853     ) where
854         F: for<'b> FnMut(&mut ProbeContext<'b, 'tcx>, ty::PolyTraitRef<'tcx>, ty::AssocItem),
855     {
856         let tcx = self.tcx;
857         for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
858             debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref);
859             for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
860                 if !self.has_applicable_self(&item) {
861                     self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
862                 } else {
863                     mk_cand(self, bound_trait_ref, item);
864                 }
865             }
866         }
867     }
868
869     fn assemble_extension_candidates_for_traits_in_scope(
870         &mut self,
871         expr_hir_id: hir::HirId,
872     ) -> Result<(), MethodError<'tcx>> {
873         let mut duplicates = FxHashSet::default();
874         let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
875         if let Some(applicable_traits) = opt_applicable_traits {
876             for trait_candidate in applicable_traits.iter() {
877                 let trait_did = trait_candidate.def_id;
878                 if duplicates.insert(trait_did) {
879                     let result = self.assemble_extension_candidates_for_trait(
880                         &trait_candidate.import_ids,
881                         trait_did,
882                     );
883                     result?;
884                 }
885             }
886         }
887         Ok(())
888     }
889
890     fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
891         let mut duplicates = FxHashSet::default();
892         for trait_info in suggest::all_traits(self.tcx) {
893             if duplicates.insert(trait_info.def_id) {
894                 self.assemble_extension_candidates_for_trait(&smallvec![], trait_info.def_id)?;
895             }
896         }
897         Ok(())
898     }
899
900     pub fn matches_return_type(
901         &self,
902         method: &ty::AssocItem,
903         self_ty: Option<Ty<'tcx>>,
904         expected: Ty<'tcx>,
905     ) -> bool {
906         match method.kind {
907             ty::AssocKind::Fn => {
908                 let fty = self.tcx.fn_sig(method.def_id);
909                 self.probe(|_| {
910                     let substs = self.fresh_substs_for_item(self.span, method.def_id);
911                     let fty = fty.subst(self.tcx, substs);
912                     let (fty, _) =
913                         self.replace_bound_vars_with_fresh_vars(self.span, infer::FnCall, &fty);
914
915                     if let Some(self_ty) = self_ty {
916                         if self
917                             .at(&ObligationCause::dummy(), self.param_env)
918                             .sup(fty.inputs()[0], self_ty)
919                             .is_err()
920                         {
921                             return false;
922                         }
923                     }
924                     self.can_sub(self.param_env, fty.output(), expected).is_ok()
925                 })
926             }
927             _ => false,
928         }
929     }
930
931     fn assemble_extension_candidates_for_trait(
932         &mut self,
933         import_ids: &SmallVec<[LocalDefId; 1]>,
934         trait_def_id: DefId,
935     ) -> Result<(), MethodError<'tcx>> {
936         debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})", trait_def_id);
937         let trait_substs = self.fresh_item_substs(trait_def_id);
938         let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
939
940         if self.tcx.is_trait_alias(trait_def_id) {
941             // For trait aliases, assume all super-traits are relevant.
942             let bounds = iter::once(trait_ref.to_poly_trait_ref());
943             self.elaborate_bounds(bounds, |this, new_trait_ref, item| {
944                 let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
945
946                 let (xform_self_ty, xform_ret_ty) =
947                     this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
948                 this.push_candidate(
949                     Candidate {
950                         xform_self_ty,
951                         xform_ret_ty,
952                         item,
953                         import_ids: import_ids.clone(),
954                         kind: TraitCandidate(new_trait_ref),
955                     },
956                     false,
957                 );
958             });
959         } else {
960             debug_assert!(self.tcx.is_trait(trait_def_id));
961             for item in self.impl_or_trait_item(trait_def_id) {
962                 // Check whether `trait_def_id` defines a method with suitable name.
963                 if !self.has_applicable_self(&item) {
964                     debug!("method has inapplicable self");
965                     self.record_static_candidate(TraitSource(trait_def_id));
966                     continue;
967                 }
968
969                 let (xform_self_ty, xform_ret_ty) =
970                     self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
971                 self.push_candidate(
972                     Candidate {
973                         xform_self_ty,
974                         xform_ret_ty,
975                         item,
976                         import_ids: import_ids.clone(),
977                         kind: TraitCandidate(trait_ref),
978                     },
979                     false,
980                 );
981             }
982         }
983         Ok(())
984     }
985
986     fn candidate_method_names(&self) -> Vec<Ident> {
987         let mut set = FxHashSet::default();
988         let mut names: Vec<_> = self
989             .inherent_candidates
990             .iter()
991             .chain(&self.extension_candidates)
992             .filter(|candidate| {
993                 if let Some(return_ty) = self.return_type {
994                     self.matches_return_type(&candidate.item, None, return_ty)
995                 } else {
996                     true
997                 }
998             })
999             .map(|candidate| candidate.item.ident)
1000             .filter(|&name| set.insert(name))
1001             .collect();
1002
1003         // Sort them by the name so we have a stable result.
1004         names.sort_by_cached_key(|n| n.as_str());
1005         names
1006     }
1007
1008     ///////////////////////////////////////////////////////////////////////////
1009     // THE ACTUAL SEARCH
1010
1011     fn pick(mut self) -> PickResult<'tcx> {
1012         assert!(self.method_name.is_some());
1013
1014         if let Some(r) = self.pick_core() {
1015             return r;
1016         }
1017
1018         debug!("pick: actual search failed, assemble diagnostics");
1019
1020         let static_candidates = mem::take(&mut self.static_candidates);
1021         let private_candidate = self.private_candidate.take();
1022         let unsatisfied_predicates = mem::take(&mut self.unsatisfied_predicates);
1023
1024         // things failed, so lets look at all traits, for diagnostic purposes now:
1025         self.reset();
1026
1027         let span = self.span;
1028         let tcx = self.tcx;
1029
1030         self.assemble_extension_candidates_for_all_traits()?;
1031
1032         let out_of_scope_traits = match self.pick_core() {
1033             Some(Ok(p)) => vec![p.item.container.id()],
1034             //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
1035             Some(Err(MethodError::Ambiguity(v))) => v
1036                 .into_iter()
1037                 .map(|source| match source {
1038                     TraitSource(id) => id,
1039                     ImplSource(impl_id) => match tcx.trait_id_of_impl(impl_id) {
1040                         Some(id) => id,
1041                         None => span_bug!(span, "found inherent method when looking at traits"),
1042                     },
1043                 })
1044                 .collect(),
1045             Some(Err(MethodError::NoMatch(NoMatchData {
1046                 out_of_scope_traits: others, ..
1047             }))) => {
1048                 assert!(others.is_empty());
1049                 vec![]
1050             }
1051             _ => vec![],
1052         };
1053
1054         if let Some((kind, def_id)) = private_candidate {
1055             return Err(MethodError::PrivateMatch(kind, def_id, out_of_scope_traits));
1056         }
1057         let lev_candidate = self.probe_for_lev_candidate()?;
1058
1059         Err(MethodError::NoMatch(NoMatchData::new(
1060             static_candidates,
1061             unsatisfied_predicates,
1062             out_of_scope_traits,
1063             lev_candidate,
1064             self.mode,
1065         )))
1066     }
1067
1068     fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
1069         let steps = self.steps.clone();
1070
1071         // find the first step that works
1072         steps
1073             .iter()
1074             .filter(|step| {
1075                 debug!("pick_core: step={:?}", step);
1076                 // skip types that are from a type error or that would require dereferencing
1077                 // a raw pointer
1078                 !step.self_ty.references_error() && !step.from_unsafe_deref
1079             })
1080             .flat_map(|step| {
1081                 let InferOk { value: self_ty, obligations: _ } = self
1082                     .fcx
1083                     .probe_instantiate_query_response(
1084                         self.span,
1085                         &self.orig_steps_var_values,
1086                         &step.self_ty,
1087                     )
1088                     .unwrap_or_else(|_| {
1089                         span_bug!(self.span, "{:?} was applicable but now isn't?", step.self_ty)
1090                     });
1091                 self.pick_by_value_method(step, self_ty).or_else(|| {
1092                     self.pick_autorefd_method(step, self_ty, hir::Mutability::Not)
1093                         .or_else(|| self.pick_autorefd_method(step, self_ty, hir::Mutability::Mut))
1094                 })
1095             })
1096             .next()
1097     }
1098
1099     fn pick_by_value_method(
1100         &mut self,
1101         step: &CandidateStep<'tcx>,
1102         self_ty: Ty<'tcx>,
1103     ) -> Option<PickResult<'tcx>> {
1104         //! For each type `T` in the step list, this attempts to find a
1105         //! method where the (transformed) self type is exactly `T`. We
1106         //! do however do one transformation on the adjustment: if we
1107         //! are passing a region pointer in, we will potentially
1108         //! *reborrow* it to a shorter lifetime. This allows us to
1109         //! transparently pass `&mut` pointers, in particular, without
1110         //! consuming them for their entire lifetime.
1111
1112         if step.unsize {
1113             return None;
1114         }
1115
1116         self.pick_method(self_ty).map(|r| {
1117             r.map(|mut pick| {
1118                 pick.autoderefs = step.autoderefs;
1119
1120                 // Insert a `&*` or `&mut *` if this is a reference type:
1121                 if let ty::Ref(_, _, mutbl) = step.self_ty.value.value.kind {
1122                     pick.autoderefs += 1;
1123                     pick.autoref = Some(mutbl);
1124                 }
1125
1126                 pick
1127             })
1128         })
1129     }
1130
1131     fn pick_autorefd_method(
1132         &mut self,
1133         step: &CandidateStep<'tcx>,
1134         self_ty: Ty<'tcx>,
1135         mutbl: hir::Mutability,
1136     ) -> Option<PickResult<'tcx>> {
1137         let tcx = self.tcx;
1138
1139         // In general, during probing we erase regions.
1140         let region = tcx.lifetimes.re_erased;
1141
1142         let autoref_ty = tcx.mk_ref(region, ty::TypeAndMut { ty: self_ty, mutbl });
1143         self.pick_method(autoref_ty).map(|r| {
1144             r.map(|mut pick| {
1145                 pick.autoderefs = step.autoderefs;
1146                 pick.autoref = Some(mutbl);
1147                 pick.unsize = step.unsize.then_some(self_ty);
1148                 pick
1149             })
1150         })
1151     }
1152
1153     fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
1154         debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1155
1156         let mut possibly_unsatisfied_predicates = Vec::new();
1157         let mut unstable_candidates = Vec::new();
1158
1159         for (kind, candidates) in
1160             &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1161         {
1162             debug!("searching {} candidates", kind);
1163             let res = self.consider_candidates(
1164                 self_ty,
1165                 candidates.iter(),
1166                 &mut possibly_unsatisfied_predicates,
1167                 Some(&mut unstable_candidates),
1168             );
1169             if let Some(pick) = res {
1170                 if !self.is_suggestion.0 && !unstable_candidates.is_empty() {
1171                     if let Ok(p) = &pick {
1172                         // Emit a lint if there are unstable candidates alongside the stable ones.
1173                         //
1174                         // We suppress warning if we're picking the method only because it is a
1175                         // suggestion.
1176                         self.emit_unstable_name_collision_hint(p, &unstable_candidates);
1177                     }
1178                 }
1179                 return Some(pick);
1180             }
1181         }
1182
1183         debug!("searching unstable candidates");
1184         let res = self.consider_candidates(
1185             self_ty,
1186             unstable_candidates.into_iter().map(|(c, _)| c),
1187             &mut possibly_unsatisfied_predicates,
1188             None,
1189         );
1190         if res.is_none() {
1191             self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1192         }
1193         res
1194     }
1195
1196     fn consider_candidates<'b, ProbesIter>(
1197         &self,
1198         self_ty: Ty<'tcx>,
1199         probes: ProbesIter,
1200         possibly_unsatisfied_predicates: &mut Vec<(
1201             ty::Predicate<'tcx>,
1202             Option<ty::Predicate<'tcx>>,
1203         )>,
1204         unstable_candidates: Option<&mut Vec<(&'b Candidate<'tcx>, Symbol)>>,
1205     ) -> Option<PickResult<'tcx>>
1206     where
1207         ProbesIter: Iterator<Item = &'b Candidate<'tcx>> + Clone,
1208     {
1209         let mut applicable_candidates: Vec<_> = probes
1210             .clone()
1211             .map(|probe| {
1212                 (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1213             })
1214             .filter(|&(_, status)| status != ProbeResult::NoMatch)
1215             .collect();
1216
1217         debug!("applicable_candidates: {:?}", applicable_candidates);
1218
1219         if applicable_candidates.len() > 1 {
1220             if let Some(pick) = self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1221                 return Some(Ok(pick));
1222             }
1223         }
1224
1225         if let Some(uc) = unstable_candidates {
1226             applicable_candidates.retain(|&(p, _)| {
1227                 if let stability::EvalResult::Deny { feature, .. } =
1228                     self.tcx.eval_stability(p.item.def_id, None, self.span)
1229                 {
1230                     uc.push((p, feature));
1231                     return false;
1232                 }
1233                 true
1234             });
1235         }
1236
1237         if applicable_candidates.len() > 1 {
1238             let sources = probes.map(|p| self.candidate_source(p, self_ty)).collect();
1239             return Some(Err(MethodError::Ambiguity(sources)));
1240         }
1241
1242         applicable_candidates.pop().map(|(probe, status)| {
1243             if status == ProbeResult::Match {
1244                 Ok(probe.to_unadjusted_pick())
1245             } else {
1246                 Err(MethodError::BadReturnType)
1247             }
1248         })
1249     }
1250
1251     fn emit_unstable_name_collision_hint(
1252         &self,
1253         stable_pick: &Pick<'_>,
1254         unstable_candidates: &[(&Candidate<'tcx>, Symbol)],
1255     ) {
1256         self.tcx.struct_span_lint_hir(
1257             lint::builtin::UNSTABLE_NAME_COLLISIONS,
1258             self.fcx.body_id,
1259             self.span,
1260             |lint| {
1261                 let mut diag = lint.build(
1262                     "a method with this name may be added to the standard library in the future",
1263                 );
1264                 // FIXME: This should be a `span_suggestion` instead of `help`
1265                 // However `self.span` only
1266                 // highlights the method name, so we can't use it. Also consider reusing the code from
1267                 // `report_method_error()`.
1268                 diag.help(&format!(
1269                     "call with fully qualified syntax `{}(...)` to keep using the current method",
1270                     self.tcx.def_path_str(stable_pick.item.def_id),
1271                 ));
1272
1273                 if nightly_options::is_nightly_build() {
1274                     for (candidate, feature) in unstable_candidates {
1275                         diag.help(&format!(
1276                             "add `#![feature({})]` to the crate attributes to enable `{}`",
1277                             feature,
1278                             self.tcx.def_path_str(candidate.item.def_id),
1279                         ));
1280                     }
1281                 }
1282
1283                 diag.emit();
1284             },
1285         );
1286     }
1287
1288     fn select_trait_candidate(
1289         &self,
1290         trait_ref: ty::TraitRef<'tcx>,
1291     ) -> traits::SelectionResult<'tcx, traits::Selection<'tcx>> {
1292         let cause = traits::ObligationCause::misc(self.span, self.body_id);
1293         let predicate = trait_ref.to_poly_trait_ref().to_poly_trait_predicate();
1294         let obligation = traits::Obligation::new(cause, self.param_env, predicate);
1295         traits::SelectionContext::new(self).select(&obligation)
1296     }
1297
1298     fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>) -> CandidateSource {
1299         match candidate.kind {
1300             InherentImplCandidate(..) => ImplSource(candidate.item.container.id()),
1301             ObjectCandidate | WhereClauseCandidate(_) => TraitSource(candidate.item.container.id()),
1302             TraitCandidate(trait_ref) => self.probe(|_| {
1303                 let _ = self
1304                     .at(&ObligationCause::dummy(), self.param_env)
1305                     .sup(candidate.xform_self_ty, self_ty);
1306                 match self.select_trait_candidate(trait_ref) {
1307                     Ok(Some(traits::ImplSource::ImplSourceUserDefined(ref impl_data))) => {
1308                         // If only a single impl matches, make the error message point
1309                         // to that impl.
1310                         ImplSource(impl_data.impl_def_id)
1311                     }
1312                     _ => TraitSource(candidate.item.container.id()),
1313                 }
1314             }),
1315         }
1316     }
1317
1318     fn consider_probe(
1319         &self,
1320         self_ty: Ty<'tcx>,
1321         probe: &Candidate<'tcx>,
1322         possibly_unsatisfied_predicates: &mut Vec<(
1323             ty::Predicate<'tcx>,
1324             Option<ty::Predicate<'tcx>>,
1325         )>,
1326     ) -> ProbeResult {
1327         debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1328
1329         self.probe(|_| {
1330             // First check that the self type can be related.
1331             let sub_obligations = match self
1332                 .at(&ObligationCause::dummy(), self.param_env)
1333                 .sup(probe.xform_self_ty, self_ty)
1334             {
1335                 Ok(InferOk { obligations, value: () }) => obligations,
1336                 Err(_) => {
1337                     debug!("--> cannot relate self-types");
1338                     return ProbeResult::NoMatch;
1339                 }
1340             };
1341
1342             let mut result = ProbeResult::Match;
1343             let selcx = &mut traits::SelectionContext::new(self);
1344             let cause = traits::ObligationCause::misc(self.span, self.body_id);
1345
1346             // If so, impls may carry other conditions (e.g., where
1347             // clauses) that must be considered. Make sure that those
1348             // match as well (or at least may match, sometimes we
1349             // don't have enough information to fully evaluate).
1350             match probe.kind {
1351                 InherentImplCandidate(ref substs, ref ref_obligations) => {
1352                     // Check whether the impl imposes obligations we have to worry about.
1353                     let impl_def_id = probe.item.container.id();
1354                     let impl_bounds = self.tcx.predicates_of(impl_def_id);
1355                     let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1356                     let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1357                         traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
1358
1359                     // Convert the bounds into obligations.
1360                     let impl_obligations =
1361                         traits::predicates_for_generics(cause, self.param_env, impl_bounds);
1362
1363                     let candidate_obligations = impl_obligations
1364                         .chain(norm_obligations.into_iter())
1365                         .chain(ref_obligations.iter().cloned());
1366                     // Evaluate those obligations to see if they might possibly hold.
1367                     for o in candidate_obligations {
1368                         let o = self.resolve_vars_if_possible(&o);
1369                         if !self.predicate_may_hold(&o) {
1370                             result = ProbeResult::NoMatch;
1371                             possibly_unsatisfied_predicates.push((o.predicate, None));
1372                         }
1373                     }
1374                 }
1375
1376                 ObjectCandidate | WhereClauseCandidate(..) => {
1377                     // These have no additional conditions to check.
1378                 }
1379
1380                 TraitCandidate(trait_ref) => {
1381                     let predicate = trait_ref.without_const().to_predicate(self.tcx);
1382                     let obligation = traits::Obligation::new(cause, self.param_env, predicate);
1383                     if !self.predicate_may_hold(&obligation) {
1384                         result = ProbeResult::NoMatch;
1385                         if self.probe(|_| {
1386                             match self.select_trait_candidate(trait_ref) {
1387                                 Err(_) => return true,
1388                                 Ok(Some(impl_source))
1389                                     if !impl_source.borrow_nested_obligations().is_empty() =>
1390                                 {
1391                                     for obligation in impl_source.borrow_nested_obligations() {
1392                                         // Determine exactly which obligation wasn't met, so
1393                                         // that we can give more context in the error.
1394                                         if !self.predicate_may_hold(&obligation) {
1395                                             let o = self.resolve_vars_if_possible(obligation);
1396                                             let predicate =
1397                                                 self.resolve_vars_if_possible(&predicate);
1398                                             let p = if predicate == o.predicate {
1399                                                 // Avoid "`MyStruct: Foo` which is required by
1400                                                 // `MyStruct: Foo`" in E0599.
1401                                                 None
1402                                             } else {
1403                                                 Some(predicate)
1404                                             };
1405                                             possibly_unsatisfied_predicates.push((o.predicate, p));
1406                                         }
1407                                     }
1408                                 }
1409                                 _ => {
1410                                     // Some nested subobligation of this predicate
1411                                     // failed.
1412                                     let predicate = self.resolve_vars_if_possible(&predicate);
1413                                     possibly_unsatisfied_predicates.push((predicate, None));
1414                                 }
1415                             }
1416                             false
1417                         }) {
1418                             // This candidate's primary obligation doesn't even
1419                             // select - don't bother registering anything in
1420                             // `potentially_unsatisfied_predicates`.
1421                             return ProbeResult::NoMatch;
1422                         }
1423                     }
1424                 }
1425             }
1426
1427             // Evaluate those obligations to see if they might possibly hold.
1428             for o in sub_obligations {
1429                 let o = self.resolve_vars_if_possible(&o);
1430                 if !self.predicate_may_hold(&o) {
1431                     result = ProbeResult::NoMatch;
1432                     possibly_unsatisfied_predicates.push((o.predicate, None));
1433                 }
1434             }
1435
1436             if let ProbeResult::Match = result {
1437                 if let (Some(return_ty), Some(xform_ret_ty)) =
1438                     (self.return_type, probe.xform_ret_ty)
1439                 {
1440                     let xform_ret_ty = self.resolve_vars_if_possible(&xform_ret_ty);
1441                     debug!(
1442                         "comparing return_ty {:?} with xform ret ty {:?}",
1443                         return_ty, probe.xform_ret_ty
1444                     );
1445                     if self
1446                         .at(&ObligationCause::dummy(), self.param_env)
1447                         .sup(return_ty, xform_ret_ty)
1448                         .is_err()
1449                     {
1450                         return ProbeResult::BadReturnType;
1451                     }
1452                 }
1453             }
1454
1455             result
1456         })
1457     }
1458
1459     /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1460     /// same trait, but we don't know which impl to use. In this case, since in all cases the
1461     /// external interface of the method can be determined from the trait, it's ok not to decide.
1462     /// We can basically just collapse all of the probes for various impls into one where-clause
1463     /// probe. This will result in a pending obligation so when more type-info is available we can
1464     /// make the final decision.
1465     ///
1466     /// Example (`src/test/ui/method-two-trait-defer-resolution-1.rs`):
1467     ///
1468     /// ```
1469     /// trait Foo { ... }
1470     /// impl Foo for Vec<i32> { ... }
1471     /// impl Foo for Vec<usize> { ... }
1472     /// ```
1473     ///
1474     /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1475     /// use, so it's ok to just commit to "using the method from the trait Foo".
1476     fn collapse_candidates_to_trait_pick(
1477         &self,
1478         probes: &[(&Candidate<'tcx>, ProbeResult)],
1479     ) -> Option<Pick<'tcx>> {
1480         // Do all probes correspond to the same trait?
1481         let container = probes[0].0.item.container;
1482         if let ty::ImplContainer(_) = container {
1483             return None;
1484         }
1485         if probes[1..].iter().any(|&(p, _)| p.item.container != container) {
1486             return None;
1487         }
1488
1489         // FIXME: check the return type here somehow.
1490         // If so, just use this trait and call it a day.
1491         Some(Pick {
1492             item: probes[0].0.item,
1493             kind: TraitPick,
1494             import_ids: probes[0].0.import_ids.clone(),
1495             autoderefs: 0,
1496             autoref: None,
1497             unsize: None,
1498         })
1499     }
1500
1501     /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
1502     /// candidate method where the method name may have been misspelt. Similarly to other
1503     /// Levenshtein based suggestions, we provide at most one such suggestion.
1504     fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssocItem>, MethodError<'tcx>> {
1505         debug!("probing for method names similar to {:?}", self.method_name);
1506
1507         let steps = self.steps.clone();
1508         self.probe(|_| {
1509             let mut pcx = ProbeContext::new(
1510                 self.fcx,
1511                 self.span,
1512                 self.mode,
1513                 self.method_name,
1514                 self.return_type,
1515                 self.orig_steps_var_values.clone(),
1516                 steps,
1517                 IsSuggestion(true),
1518             );
1519             pcx.allow_similar_names = true;
1520             pcx.assemble_inherent_candidates();
1521
1522             let method_names = pcx.candidate_method_names();
1523             pcx.allow_similar_names = false;
1524             let applicable_close_candidates: Vec<ty::AssocItem> = method_names
1525                 .iter()
1526                 .filter_map(|&method_name| {
1527                     pcx.reset();
1528                     pcx.method_name = Some(method_name);
1529                     pcx.assemble_inherent_candidates();
1530                     pcx.pick_core().and_then(|pick| pick.ok()).map(|pick| pick.item)
1531                 })
1532                 .collect();
1533
1534             if applicable_close_candidates.is_empty() {
1535                 Ok(None)
1536             } else {
1537                 let best_name = {
1538                     let names = applicable_close_candidates.iter().map(|cand| &cand.ident.name);
1539                     find_best_match_for_name(names, self.method_name.unwrap().name, None)
1540                 }
1541                 .unwrap();
1542                 Ok(applicable_close_candidates
1543                     .into_iter()
1544                     .find(|method| method.ident.name == best_name))
1545             }
1546         })
1547     }
1548
1549     ///////////////////////////////////////////////////////////////////////////
1550     // MISCELLANY
1551     fn has_applicable_self(&self, item: &ty::AssocItem) -> bool {
1552         // "Fast track" -- check for usage of sugar when in method call
1553         // mode.
1554         //
1555         // In Path mode (i.e., resolving a value like `T::next`), consider any
1556         // associated value (i.e., methods, constants) but not types.
1557         match self.mode {
1558             Mode::MethodCall => item.fn_has_self_parameter,
1559             Mode::Path => match item.kind {
1560                 ty::AssocKind::Type => false,
1561                 ty::AssocKind::Fn | ty::AssocKind::Const => true,
1562             },
1563         }
1564         // FIXME -- check for types that deref to `Self`,
1565         // like `Rc<Self>` and so on.
1566         //
1567         // Note also that the current code will break if this type
1568         // includes any of the type parameters defined on the method
1569         // -- but this could be overcome.
1570     }
1571
1572     fn record_static_candidate(&mut self, source: CandidateSource) {
1573         self.static_candidates.push(source);
1574     }
1575
1576     fn xform_self_ty(
1577         &self,
1578         item: &ty::AssocItem,
1579         impl_ty: Ty<'tcx>,
1580         substs: SubstsRef<'tcx>,
1581     ) -> (Ty<'tcx>, Option<Ty<'tcx>>) {
1582         if item.kind == ty::AssocKind::Fn && self.mode == Mode::MethodCall {
1583             let sig = self.xform_method_sig(item.def_id, substs);
1584             (sig.inputs()[0], Some(sig.output()))
1585         } else {
1586             (impl_ty, None)
1587         }
1588     }
1589
1590     fn xform_method_sig(&self, method: DefId, substs: SubstsRef<'tcx>) -> ty::FnSig<'tcx> {
1591         let fn_sig = self.tcx.fn_sig(method);
1592         debug!("xform_self_ty(fn_sig={:?}, substs={:?})", fn_sig, substs);
1593
1594         assert!(!substs.has_escaping_bound_vars());
1595
1596         // It is possible for type parameters or early-bound lifetimes
1597         // to appear in the signature of `self`. The substitutions we
1598         // are given do not include type/lifetime parameters for the
1599         // method yet. So create fresh variables here for those too,
1600         // if there are any.
1601         let generics = self.tcx.generics_of(method);
1602         assert_eq!(substs.len(), generics.parent_count as usize);
1603
1604         // Erase any late-bound regions from the method and substitute
1605         // in the values from the substitution.
1606         let xform_fn_sig = self.erase_late_bound_regions(&fn_sig);
1607
1608         if generics.params.is_empty() {
1609             xform_fn_sig.subst(self.tcx, substs)
1610         } else {
1611             let substs = InternalSubsts::for_item(self.tcx, method, |param, _| {
1612                 let i = param.index as usize;
1613                 if i < substs.len() {
1614                     substs[i]
1615                 } else {
1616                     match param.kind {
1617                         GenericParamDefKind::Lifetime => {
1618                             // In general, during probe we erase regions.
1619                             self.tcx.lifetimes.re_erased.into()
1620                         }
1621                         GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
1622                             self.var_for_def(self.span, param)
1623                         }
1624                     }
1625                 }
1626             });
1627             xform_fn_sig.subst(self.tcx, substs)
1628         }
1629     }
1630
1631     /// Gets the type of an impl and generate substitutions with placeholders.
1632     fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, SubstsRef<'tcx>) {
1633         (self.tcx.type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
1634     }
1635
1636     fn fresh_item_substs(&self, def_id: DefId) -> SubstsRef<'tcx> {
1637         InternalSubsts::for_item(self.tcx, def_id, |param, _| match param.kind {
1638             GenericParamDefKind::Lifetime => self.tcx.lifetimes.re_erased.into(),
1639             GenericParamDefKind::Type { .. } => self
1640                 .next_ty_var(TypeVariableOrigin {
1641                     kind: TypeVariableOriginKind::SubstitutionPlaceholder,
1642                     span: self.tcx.def_span(def_id),
1643                 })
1644                 .into(),
1645             GenericParamDefKind::Const { .. } => {
1646                 let span = self.tcx.def_span(def_id);
1647                 let origin = ConstVariableOrigin {
1648                     kind: ConstVariableOriginKind::SubstitutionPlaceholder,
1649                     span,
1650                 };
1651                 self.next_const_var(self.tcx.type_of(param.def_id), origin).into()
1652             }
1653         })
1654     }
1655
1656     /// Replaces late-bound-regions bound by `value` with `'static` using
1657     /// `ty::erase_late_bound_regions`.
1658     ///
1659     /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1660     /// method matching. It is reasonable during the probe phase because we don't consider region
1661     /// relationships at all. Therefore, we can just replace all the region variables with 'static
1662     /// rather than creating fresh region variables. This is nice for two reasons:
1663     ///
1664     /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1665     ///    particular method call, it winds up creating fewer types overall, which helps for memory
1666     ///    usage. (Admittedly, this is a rather small effect, though measurable.)
1667     ///
1668     /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1669     ///    late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1670     ///    regions with actual region variables as is proper, we'd have to ensure that the same
1671     ///    region got replaced with the same variable, which requires a bit more coordination
1672     ///    and/or tracking the substitution and
1673     ///    so forth.
1674     fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1675     where
1676         T: TypeFoldable<'tcx>,
1677     {
1678         self.tcx.erase_late_bound_regions(value)
1679     }
1680
1681     /// Finds the method with the appropriate name (or return type, as the case may be). If
1682     /// `allow_similar_names` is set, find methods with close-matching names.
1683     fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssocItem> {
1684         if let Some(name) = self.method_name {
1685             if self.allow_similar_names {
1686                 let max_dist = max(name.as_str().len(), 3) / 3;
1687                 self.tcx
1688                     .associated_items(def_id)
1689                     .in_definition_order()
1690                     .filter(|x| {
1691                         let dist = lev_distance(&*name.as_str(), &x.ident.as_str());
1692                         x.kind.namespace() == Namespace::ValueNS && dist > 0 && dist <= max_dist
1693                     })
1694                     .copied()
1695                     .collect()
1696             } else {
1697                 self.fcx
1698                     .associated_item(def_id, name, Namespace::ValueNS)
1699                     .map_or(Vec::new(), |x| vec![x])
1700             }
1701         } else {
1702             self.tcx.associated_items(def_id).in_definition_order().copied().collect()
1703         }
1704     }
1705 }
1706
1707 impl<'tcx> Candidate<'tcx> {
1708     fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1709         Pick {
1710             item: self.item,
1711             kind: match self.kind {
1712                 InherentImplCandidate(..) => InherentImplPick,
1713                 ObjectCandidate => ObjectPick,
1714                 TraitCandidate(_) => TraitPick,
1715                 WhereClauseCandidate(ref trait_ref) => {
1716                     // Only trait derived from where-clauses should
1717                     // appear here, so they should not contain any
1718                     // inference variables or other artifacts. This
1719                     // means they are safe to put into the
1720                     // `WhereClausePick`.
1721                     assert!(
1722                         !trait_ref.skip_binder().substs.needs_infer()
1723                             && !trait_ref.skip_binder().substs.has_placeholders()
1724                     );
1725
1726                     WhereClausePick(*trait_ref)
1727                 }
1728             },
1729             import_ids: self.import_ids.clone(),
1730             autoderefs: 0,
1731             autoref: None,
1732             unsize: None,
1733         }
1734     }
1735 }