1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use super::MethodError;
12 use super::NoMatchData;
13 use super::{CandidateSource, ImplSource, TraitSource};
17 use hir::def_id::DefId;
19 use rustc::ty::subst::{Subst, Substs};
20 use rustc::traits::{self, ObligationCause};
21 use rustc::ty::{self, Ty, ToPolyTraitRef, TraitRef, TypeFoldable};
22 use rustc::infer::type_variable::TypeVariableOrigin;
23 use rustc::util::nodemap::FxHashSet;
24 use rustc::infer::{self, InferOk};
32 use self::CandidateKind::*;
33 pub use self::PickKind::*;
35 pub enum LookingFor<'tcx> {
36 /// looking for methods with the given name; this is the normal case
37 MethodName(ast::Name),
39 /// looking for methods that return a given type; this is used to
40 /// assemble suggestions
44 /// Boolean flag used to indicate if this search is for a suggestion
45 /// or not. If true, we can allow ambiguity and so forth.
46 pub struct IsSuggestion(pub bool);
48 struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
49 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
52 looking_for: LookingFor<'tcx>,
53 steps: Rc<Vec<CandidateStep<'tcx>>>,
54 opt_simplified_steps: Option<Vec<ty::fast_reject::SimplifiedType>>,
55 inherent_candidates: Vec<Candidate<'tcx>>,
56 extension_candidates: Vec<Candidate<'tcx>>,
57 impl_dups: FxHashSet<DefId>,
59 /// Collects near misses when the candidate functions are missing a `self` keyword and is only
60 /// used for error reporting
61 static_candidates: Vec<CandidateSource>,
63 /// Some(candidate) if there is a private candidate
64 private_candidate: Option<Def>,
66 /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
67 /// for error reporting
68 unsatisfied_predicates: Vec<TraitRef<'tcx>>,
71 impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
72 type Target = FnCtxt<'a, 'gcx, 'tcx>;
73 fn deref(&self) -> &Self::Target {
79 struct CandidateStep<'tcx> {
86 struct Candidate<'tcx> {
87 xform_self_ty: Ty<'tcx>,
88 item: ty::AssociatedItem,
89 kind: CandidateKind<'tcx>,
90 import_id: Option<ast::NodeId>,
94 enum CandidateKind<'tcx> {
95 InherentImplCandidate(&'tcx Substs<'tcx>,
96 // Normalize obligations
97 Vec<traits::PredicateObligation<'tcx>>),
98 ExtensionImplCandidate(// Impl
101 // Normalize obligations
102 Vec<traits::PredicateObligation<'tcx>>),
105 WhereClauseCandidate(// Trait
106 ty::PolyTraitRef<'tcx>),
109 #[derive(Debug, PartialEq, Eq, Clone)]
110 pub struct Pick<'tcx> {
111 pub item: ty::AssociatedItem,
112 pub kind: PickKind<'tcx>,
113 pub import_id: Option<ast::NodeId>,
115 // Indicates that the source expression should be autoderef'd N times
117 // A = expr | *expr | **expr | ...
118 pub autoderefs: usize,
120 // Indicates that an autoref is applied after the optional autoderefs
122 // B = A | &A | &mut A
123 pub autoref: Option<hir::Mutability>,
125 // Indicates that the source expression should be "unsized" to a
126 // target type. This should probably eventually go away in favor
127 // of just coercing method receivers.
130 pub unsize: Option<Ty<'tcx>>,
133 #[derive(Clone, Debug, PartialEq, Eq)]
134 pub enum PickKind<'tcx> {
136 ExtensionImplPick(// Impl
140 WhereClausePick(// Trait
141 ty::PolyTraitRef<'tcx>),
144 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
146 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
148 // An expression of the form `receiver.method_name(...)`.
149 // Autoderefs are performed on `receiver`, lookup is done based on the
150 // `self` argument of the method, and static methods aren't considered.
152 // An expression of the form `Type::item` or `<T>::item`.
153 // No autoderefs are performed, lookup is done based on the type each
154 // implementation is for, and static methods are included.
158 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
159 pub enum ProbeScope {
160 // Assemble candidates coming only from traits in scope.
163 // Assemble candidates coming from all traits.
167 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
168 /// This is used to offer suggestions to users. It returns methods
169 /// that could have been called which have the desired return
170 /// type. Some effort is made to rule out methods that, if called,
171 /// would result in an error (basically, the same criteria we
172 /// would use to decide if a method is a plausible fit for
173 /// ambiguity purposes).
174 pub fn probe_for_return_type(&self,
177 return_type: Ty<'tcx>,
179 scope_expr_id: ast::NodeId)
180 -> Vec<ty::AssociatedItem> {
181 debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
186 self.probe_op(span, mode, LookingFor::ReturnType(return_type), IsSuggestion(true),
187 self_ty, scope_expr_id, ProbeScope::TraitsInScope,
188 |probe_cx| Ok(probe_cx.candidate_method_names()))
192 .flat_map(|&method_name| {
193 match self.probe_for_name(span, mode, method_name, IsSuggestion(true), self_ty,
194 scope_expr_id, ProbeScope::TraitsInScope) {
195 Ok(pick) => Some(pick.item),
202 pub fn probe_for_name(&self,
205 item_name: ast::Name,
206 is_suggestion: IsSuggestion,
208 scope_expr_id: ast::NodeId,
210 -> PickResult<'tcx> {
211 debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
217 LookingFor::MethodName(item_name),
222 |probe_cx| probe_cx.pick())
225 fn probe_op<OP,R>(&'a self,
228 looking_for: LookingFor<'tcx>,
229 is_suggestion: IsSuggestion,
231 scope_expr_id: ast::NodeId,
234 -> Result<R, MethodError<'tcx>>
235 where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
237 // FIXME(#18741) -- right now, creating the steps involves evaluating the
238 // `*` operator, which registers obligations that then escape into
239 // the global fulfillment context and thus has global
240 // side-effects. This is a bit of a pain to refactor. So just let
241 // it ride, although it's really not great, and in fact could I
242 // think cause spurious errors. Really though this part should
243 // take place in the `self.probe` below.
244 let steps = if mode == Mode::MethodCall {
245 match self.create_steps(span, self_ty, is_suggestion) {
246 Some(steps) => steps,
248 return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
262 // Create a list of simplified self types, if we can.
263 let mut simplified_steps = Vec::new();
265 match ty::fast_reject::simplify_type(self.tcx, step.self_ty, true) {
269 Some(simplified_type) => {
270 simplified_steps.push(simplified_type);
274 let opt_simplified_steps = if simplified_steps.len() < steps.len() {
275 None // failed to convert at least one of the steps
277 Some(simplified_steps)
280 debug!("ProbeContext: steps for self_ty={:?} are {:?}",
284 // this creates one big transaction so that all type variables etc
285 // that we create during the probe process are removed later
288 ProbeContext::new(self, span, mode, looking_for,
289 steps, opt_simplified_steps);
291 probe_cx.assemble_inherent_candidates();
293 ProbeScope::TraitsInScope =>
294 probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?,
295 ProbeScope::AllTraits =>
296 probe_cx.assemble_extension_candidates_for_all_traits()?,
302 fn create_steps(&self,
305 is_suggestion: IsSuggestion)
306 -> Option<Vec<CandidateStep<'tcx>>> {
307 // FIXME: we don't need to create the entire steps in one pass
309 let mut autoderef = self.autoderef(span, self_ty);
310 let mut steps: Vec<_> = autoderef.by_ref()
320 let final_ty = autoderef.maybe_ambiguous_final_ty();
322 ty::TyInfer(ty::TyVar(_)) => {
323 // Ended in an inference variable. If we are doing
324 // a real method lookup, this is a hard error (it's an
325 // ambiguity and we can't make progress).
326 if !is_suggestion.0 {
327 let t = self.structurally_resolved_type(span, final_ty);
328 assert_eq!(t, self.tcx.types.err);
331 // If we're just looking for suggestions,
332 // though, ambiguity is no big thing, we can
336 ty::TyArray(elem_ty, _) => {
337 let dereferences = steps.len() - 1;
339 steps.push(CandidateStep {
340 self_ty: self.tcx.mk_slice(elem_ty),
341 autoderefs: dereferences,
345 ty::TyError => return None,
349 debug!("create_steps: steps={:?}", steps);
355 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
356 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
359 looking_for: LookingFor<'tcx>,
360 steps: Vec<CandidateStep<'tcx>>,
361 opt_simplified_steps: Option<Vec<ty::fast_reject::SimplifiedType>>)
362 -> ProbeContext<'a, 'gcx, 'tcx> {
368 inherent_candidates: Vec::new(),
369 extension_candidates: Vec::new(),
370 impl_dups: FxHashSet(),
371 steps: Rc::new(steps),
372 opt_simplified_steps,
373 static_candidates: Vec::new(),
374 private_candidate: None,
375 unsatisfied_predicates: Vec::new(),
379 fn reset(&mut self) {
380 self.inherent_candidates.clear();
381 self.extension_candidates.clear();
382 self.impl_dups.clear();
383 self.static_candidates.clear();
384 self.private_candidate = None;
387 ///////////////////////////////////////////////////////////////////////////
388 // CANDIDATE ASSEMBLY
390 fn push_inherent_candidate(&mut self, xform_self_ty: Ty<'tcx>, item: ty::AssociatedItem,
391 kind: CandidateKind<'tcx>, import_id: Option<ast::NodeId>) {
392 let is_accessible = if let LookingFor::MethodName(name) = self.looking_for {
393 let def_scope = self.tcx.adjust(name, item.container.id(), self.body_id).1;
394 item.vis.is_accessible_from(def_scope, self.tcx)
399 self.inherent_candidates.push(Candidate { xform_self_ty, item, kind, import_id });
400 } else if self.private_candidate.is_none() {
401 self.private_candidate = Some(item.def());
405 fn push_extension_candidate(&mut self, xform_self_ty: Ty<'tcx>, item: ty::AssociatedItem,
406 kind: CandidateKind<'tcx>, import_id: Option<ast::NodeId>) {
407 let is_accessible = if let LookingFor::MethodName(name) = self.looking_for {
408 let def_scope = self.tcx.adjust(name, item.container.id(), self.body_id).1;
409 item.vis.is_accessible_from(def_scope, self.tcx)
414 self.extension_candidates.push(Candidate { xform_self_ty, item, kind, import_id });
415 } else if self.private_candidate.is_none() {
416 self.private_candidate = Some(item.def());
420 fn assemble_inherent_candidates(&mut self) {
421 let steps = self.steps.clone();
422 for step in steps.iter() {
423 self.assemble_probe(step.self_ty);
427 fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
428 debug!("assemble_probe: self_ty={:?}", self_ty);
431 ty::TyDynamic(ref data, ..) => {
432 if let Some(p) = data.principal() {
433 self.assemble_inherent_candidates_from_object(self_ty, p);
434 self.assemble_inherent_impl_candidates_for_type(p.def_id());
437 ty::TyAdt(def, _) => {
438 self.assemble_inherent_impl_candidates_for_type(def.did);
441 self.assemble_inherent_candidates_from_param(self_ty, p);
444 let lang_def_id = self.tcx.lang_items.char_impl();
445 self.assemble_inherent_impl_for_primitive(lang_def_id);
448 let lang_def_id = self.tcx.lang_items.str_impl();
449 self.assemble_inherent_impl_for_primitive(lang_def_id);
452 let lang_def_id = self.tcx.lang_items.slice_impl();
453 self.assemble_inherent_impl_for_primitive(lang_def_id);
455 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
456 let lang_def_id = self.tcx.lang_items.const_ptr_impl();
457 self.assemble_inherent_impl_for_primitive(lang_def_id);
459 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
460 let lang_def_id = self.tcx.lang_items.mut_ptr_impl();
461 self.assemble_inherent_impl_for_primitive(lang_def_id);
463 ty::TyInt(ast::IntTy::I8) => {
464 let lang_def_id = self.tcx.lang_items.i8_impl();
465 self.assemble_inherent_impl_for_primitive(lang_def_id);
467 ty::TyInt(ast::IntTy::I16) => {
468 let lang_def_id = self.tcx.lang_items.i16_impl();
469 self.assemble_inherent_impl_for_primitive(lang_def_id);
471 ty::TyInt(ast::IntTy::I32) => {
472 let lang_def_id = self.tcx.lang_items.i32_impl();
473 self.assemble_inherent_impl_for_primitive(lang_def_id);
475 ty::TyInt(ast::IntTy::I64) => {
476 let lang_def_id = self.tcx.lang_items.i64_impl();
477 self.assemble_inherent_impl_for_primitive(lang_def_id);
479 ty::TyInt(ast::IntTy::I128) => {
480 let lang_def_id = self.tcx.lang_items.i128_impl();
481 self.assemble_inherent_impl_for_primitive(lang_def_id);
483 ty::TyInt(ast::IntTy::Is) => {
484 let lang_def_id = self.tcx.lang_items.isize_impl();
485 self.assemble_inherent_impl_for_primitive(lang_def_id);
487 ty::TyUint(ast::UintTy::U8) => {
488 let lang_def_id = self.tcx.lang_items.u8_impl();
489 self.assemble_inherent_impl_for_primitive(lang_def_id);
491 ty::TyUint(ast::UintTy::U16) => {
492 let lang_def_id = self.tcx.lang_items.u16_impl();
493 self.assemble_inherent_impl_for_primitive(lang_def_id);
495 ty::TyUint(ast::UintTy::U32) => {
496 let lang_def_id = self.tcx.lang_items.u32_impl();
497 self.assemble_inherent_impl_for_primitive(lang_def_id);
499 ty::TyUint(ast::UintTy::U64) => {
500 let lang_def_id = self.tcx.lang_items.u64_impl();
501 self.assemble_inherent_impl_for_primitive(lang_def_id);
503 ty::TyUint(ast::UintTy::U128) => {
504 let lang_def_id = self.tcx.lang_items.u128_impl();
505 self.assemble_inherent_impl_for_primitive(lang_def_id);
507 ty::TyUint(ast::UintTy::Us) => {
508 let lang_def_id = self.tcx.lang_items.usize_impl();
509 self.assemble_inherent_impl_for_primitive(lang_def_id);
511 ty::TyFloat(ast::FloatTy::F32) => {
512 let lang_def_id = self.tcx.lang_items.f32_impl();
513 self.assemble_inherent_impl_for_primitive(lang_def_id);
515 ty::TyFloat(ast::FloatTy::F64) => {
516 let lang_def_id = self.tcx.lang_items.f64_impl();
517 self.assemble_inherent_impl_for_primitive(lang_def_id);
523 fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
524 if let Some(impl_def_id) = lang_def_id {
525 self.assemble_inherent_impl_probe(impl_def_id);
529 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
530 let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
531 for &impl_def_id in impl_def_ids.iter() {
532 self.assemble_inherent_impl_probe(impl_def_id);
536 fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
537 if !self.impl_dups.insert(impl_def_id) {
538 return; // already visited
541 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
543 for item in self.impl_or_trait_item(impl_def_id) {
544 if !self.has_applicable_self(&item) {
545 // No receiver declared. Not a candidate.
546 self.record_static_candidate(ImplSource(impl_def_id));
550 let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
551 let impl_ty = impl_ty.subst(self.tcx, impl_substs);
553 // Determine the receiver type that the method itself expects.
554 let xform_self_ty = self.xform_self_ty(&item, impl_ty, impl_substs);
556 // We can't use normalize_associated_types_in as it will pollute the
557 // fcx's fulfillment context after this probe is over.
558 let cause = traits::ObligationCause::misc(self.span, self.body_id);
559 let selcx = &mut traits::SelectionContext::new(self.fcx);
560 let traits::Normalized { value: xform_self_ty, obligations } =
561 traits::normalize(selcx, self.param_env, cause, &xform_self_ty);
562 debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}",
565 self.push_inherent_candidate(xform_self_ty, item,
566 InherentImplCandidate(impl_substs, obligations), None);
570 fn assemble_inherent_candidates_from_object(&mut self,
572 principal: ty::PolyExistentialTraitRef<'tcx>) {
573 debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
576 // It is illegal to invoke a method on a trait instance that
577 // refers to the `Self` type. An error will be reported by
578 // `enforce_object_limitations()` if the method refers to the
579 // `Self` type anywhere other than the receiver. Here, we use
580 // a substitution that replaces `Self` with the object type
581 // itself. Hence, a `&self` method will wind up with an
582 // argument type like `&Trait`.
583 let trait_ref = principal.with_self_ty(self.tcx, self_ty);
584 self.elaborate_bounds(&[trait_ref], |this, new_trait_ref, item| {
585 let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
588 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
590 this.push_inherent_candidate(xform_self_ty, item, ObjectCandidate, None);
594 fn assemble_inherent_candidates_from_param(&mut self,
596 param_ty: ty::ParamTy) {
597 // FIXME -- Do we want to commit to this behavior for param bounds?
599 let bounds: Vec<_> = self.param_env
602 .filter_map(|predicate| {
604 ty::Predicate::Trait(ref trait_predicate) => {
605 match trait_predicate.0.trait_ref.self_ty().sty {
606 ty::TyParam(ref p) if *p == param_ty => {
607 Some(trait_predicate.to_poly_trait_ref())
612 ty::Predicate::Equate(..) |
613 ty::Predicate::Subtype(..) |
614 ty::Predicate::Projection(..) |
615 ty::Predicate::RegionOutlives(..) |
616 ty::Predicate::WellFormed(..) |
617 ty::Predicate::ObjectSafe(..) |
618 ty::Predicate::ClosureKind(..) |
619 ty::Predicate::TypeOutlives(..) => None,
624 self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
625 let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
627 let xform_self_ty = this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
629 // Because this trait derives from a where-clause, it
630 // should not contain any inference variables or other
631 // artifacts. This means it is safe to put into the
632 // `WhereClauseCandidate` and (eventually) into the
633 // `WhereClausePick`.
634 assert!(!trait_ref.substs.needs_infer());
636 this.push_inherent_candidate(xform_self_ty, item,
637 WhereClauseCandidate(poly_trait_ref), None);
641 // Do a search through a list of bounds, using a callback to actually
642 // create the candidates.
643 fn elaborate_bounds<F>(&mut self, bounds: &[ty::PolyTraitRef<'tcx>], mut mk_cand: F)
644 where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>,
645 ty::PolyTraitRef<'tcx>,
648 debug!("elaborate_bounds(bounds={:?})", bounds);
651 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
652 for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
653 if !self.has_applicable_self(&item) {
654 self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
656 mk_cand(self, bound_trait_ref, item);
662 fn assemble_extension_candidates_for_traits_in_scope(&mut self,
663 expr_id: ast::NodeId)
664 -> Result<(), MethodError<'tcx>> {
665 let mut duplicates = FxHashSet();
666 let opt_applicable_traits = self.tcx.trait_map.get(&expr_id);
667 if let Some(applicable_traits) = opt_applicable_traits {
668 for trait_candidate in applicable_traits {
669 let trait_did = trait_candidate.def_id;
670 if duplicates.insert(trait_did) {
671 let import_id = trait_candidate.import_id;
672 let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
680 fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
681 let mut duplicates = FxHashSet();
682 for trait_info in suggest::all_traits(self.tcx) {
683 if duplicates.insert(trait_info.def_id) {
684 self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
690 pub fn matches_return_type(&self, method: &ty::AssociatedItem,
691 expected: ty::Ty<'tcx>) -> bool {
693 Def::Method(def_id) => {
694 let fty = self.tcx.fn_sig(def_id);
696 let substs = self.fresh_substs_for_item(self.span, method.def_id);
697 let output = fty.output().subst(self.tcx, substs);
698 let (output, _) = self.replace_late_bound_regions_with_fresh_var(
699 self.span, infer::FnCall, &output);
700 self.can_sub(self.param_env, output, expected).is_ok()
707 fn assemble_extension_candidates_for_trait(&mut self,
708 import_id: Option<ast::NodeId>,
710 -> Result<(), MethodError<'tcx>> {
711 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
714 for item in self.impl_or_trait_item(trait_def_id) {
715 // Check whether `trait_def_id` defines a method with suitable name:
716 if !self.has_applicable_self(&item) {
717 debug!("method has inapplicable self");
718 self.record_static_candidate(TraitSource(trait_def_id));
722 self.assemble_builtin_candidates(import_id, trait_def_id, item.clone());
724 self.assemble_extension_candidates_for_trait_impls(import_id, trait_def_id,
727 self.assemble_closure_candidates(import_id, trait_def_id, item.clone())?;
729 self.assemble_generator_candidates(import_id, trait_def_id, item.clone())?;
731 self.assemble_projection_candidates(import_id, trait_def_id, item.clone());
733 self.assemble_where_clause_candidates(import_id, trait_def_id, item.clone());
739 fn assemble_builtin_candidates(&mut self,
740 import_id: Option<ast::NodeId>,
742 item: ty::AssociatedItem) {
743 if Some(trait_def_id) == self.tcx.lang_items.clone_trait() {
744 self.assemble_builtin_clone_candidates(import_id, trait_def_id, item);
748 fn assemble_builtin_clone_candidates(&mut self,
749 import_id: Option<ast::NodeId>,
751 item: ty::AssociatedItem) {
752 for step in Rc::clone(&self.steps).iter() {
753 match step.self_ty.sty {
754 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
755 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
756 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
757 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
758 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) |
759 ty::TyArray(..) | ty::TyTuple(..) => {
766 let substs = Substs::for_item(self.tcx,
768 |def, _| self.region_var_for_def(self.span, def),
773 self.type_var_for_def(self.span, def, substs)
777 let xform_self_ty = self.xform_self_ty(&item, step.self_ty, substs);
778 self.push_inherent_candidate(xform_self_ty, item, TraitCandidate, import_id);
782 fn assemble_extension_candidates_for_trait_impls(&mut self,
783 import_id: Option<ast::NodeId>,
785 item: ty::AssociatedItem) {
786 // FIXME(arielb1): can we use for_each_relevant_impl here?
787 self.tcx.for_each_impl(trait_def_id, |impl_def_id| {
788 debug!("assemble_extension_candidates_for_trait_impl: trait_def_id={:?} \
793 if !self.impl_can_possibly_match(impl_def_id) {
797 let (_, impl_substs) = self.impl_ty_and_substs(impl_def_id);
799 debug!("impl_substs={:?}", impl_substs);
801 let impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id)
802 .unwrap() // we know this is a trait impl
803 .subst(self.tcx, impl_substs);
805 debug!("impl_trait_ref={:?}", impl_trait_ref);
807 // Determine the receiver type that the method itself expects.
809 self.xform_self_ty(&item, impl_trait_ref.self_ty(), impl_trait_ref.substs);
811 // Normalize the receiver. We can't use normalize_associated_types_in
812 // as it will pollute the fcx's fulfillment context after this probe
814 let cause = traits::ObligationCause::misc(self.span, self.body_id);
815 let selcx = &mut traits::SelectionContext::new(self.fcx);
816 let traits::Normalized { value: xform_self_ty, obligations } =
817 traits::normalize(selcx, self.param_env, cause, &xform_self_ty);
819 debug!("xform_self_ty={:?}", xform_self_ty);
821 self.push_extension_candidate(xform_self_ty, item,
822 ExtensionImplCandidate(impl_def_id, impl_substs, obligations), import_id);
826 fn impl_can_possibly_match(&self, impl_def_id: DefId) -> bool {
827 let simplified_steps = match self.opt_simplified_steps {
828 Some(ref simplified_steps) => simplified_steps,
834 let impl_type = self.tcx.type_of(impl_def_id);
835 let impl_simplified_type =
836 match ty::fast_reject::simplify_type(self.tcx, impl_type, false) {
837 Some(simplified_type) => simplified_type,
843 simplified_steps.contains(&impl_simplified_type)
846 fn assemble_closure_candidates(&mut self,
847 import_id: Option<ast::NodeId>,
849 item: ty::AssociatedItem)
850 -> Result<(), MethodError<'tcx>> {
851 // Check if this is one of the Fn,FnMut,FnOnce traits.
853 let kind = if Some(trait_def_id) == tcx.lang_items.fn_trait() {
855 } else if Some(trait_def_id) == tcx.lang_items.fn_mut_trait() {
856 ty::ClosureKind::FnMut
857 } else if Some(trait_def_id) == tcx.lang_items.fn_once_trait() {
858 ty::ClosureKind::FnOnce
863 // Check if there is an unboxed-closure self-type in the list of receivers.
864 // If so, add "synthetic impls".
865 let steps = self.steps.clone();
866 for step in steps.iter() {
867 let closure_id = match step.self_ty.sty {
868 ty::TyClosure(def_id, _) => {
869 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
870 self.tcx.hir.node_to_hir_id(id)
879 match self.tables.borrow().closure_kinds().get(closure_id) {
882 return Err(MethodError::ClosureAmbiguity(trait_def_id));
887 // this closure doesn't implement the right kind of `Fn` trait
888 if !closure_kind.extends(kind) {
892 // create some substitutions for the argument/return type;
893 // for the purposes of our method lookup, we only take
894 // receiver type into account, so we can just substitute
895 // fresh types here to use during substitution and subtyping.
896 let substs = Substs::for_item(self.tcx,
898 |def, _| self.region_var_for_def(self.span, def),
903 self.type_var_for_def(self.span, def, substs)
907 let xform_self_ty = self.xform_self_ty(&item, step.self_ty, substs);
908 self.push_inherent_candidate(xform_self_ty, item, TraitCandidate, import_id);
914 fn assemble_generator_candidates(&mut self,
915 import_id: Option<ast::NodeId>,
917 item: ty::AssociatedItem)
918 -> Result<(), MethodError<'tcx>> {
919 // Check if this is the Generator trait.
921 if Some(trait_def_id) != tcx.lang_items.gen_trait() {
925 // Check if there is an generator self-type in the list of receivers.
926 // If so, add "synthetic impls".
927 let steps = self.steps.clone();
928 for step in steps.iter() {
929 match step.self_ty.sty {
930 ty::TyGenerator(..) => (),
934 // create some substitutions for the argument/return type;
935 // for the purposes of our method lookup, we only take
936 // receiver type into account, so we can just substitute
937 // fresh types here to use during substitution and subtyping.
938 let substs = Substs::for_item(self.tcx,
940 |def, _| self.region_var_for_def(self.span, def),
945 self.type_var_for_def(self.span, def, substs)
949 let xform_self_ty = self.xform_self_ty(&item, step.self_ty, substs);
950 self.push_inherent_candidate(xform_self_ty, item, TraitCandidate, import_id);
956 fn assemble_projection_candidates(&mut self,
957 import_id: Option<ast::NodeId>,
959 item: ty::AssociatedItem) {
960 debug!("assemble_projection_candidates(\
966 for step in Rc::clone(&self.steps).iter() {
967 debug!("assemble_projection_candidates: step={:?}", step);
969 let (def_id, substs) = match step.self_ty.sty {
970 ty::TyProjection(ref data) => {
971 let trait_ref = data.trait_ref(self.tcx);
972 (trait_ref.def_id, trait_ref.substs)
974 ty::TyAnon(def_id, substs) => (def_id, substs),
978 debug!("assemble_projection_candidates: def_id={:?} substs={:?}",
982 let trait_predicates = self.tcx.predicates_of(def_id);
983 let bounds = trait_predicates.instantiate(self.tcx, substs);
984 let predicates = bounds.predicates;
985 debug!("assemble_projection_candidates: predicates={:?}",
987 for poly_bound in traits::elaborate_predicates(self.tcx, predicates)
988 .filter_map(|p| p.to_opt_poly_trait_ref())
989 .filter(|b| b.def_id() == trait_def_id) {
990 let bound = self.erase_late_bound_regions(&poly_bound);
992 debug!("assemble_projection_candidates: def_id={:?} substs={:?} bound={:?}",
997 if self.can_eq(self.param_env, step.self_ty, bound.self_ty()).is_ok() {
998 let xform_self_ty = self.xform_self_ty(&item, bound.self_ty(), bound.substs);
1000 debug!("assemble_projection_candidates: bound={:?} xform_self_ty={:?}",
1004 self.push_extension_candidate(xform_self_ty, item, TraitCandidate, import_id);
1010 fn assemble_where_clause_candidates(&mut self,
1011 import_id: Option<ast::NodeId>,
1012 trait_def_id: DefId,
1013 item: ty::AssociatedItem) {
1014 debug!("assemble_where_clause_candidates(trait_def_id={:?})",
1017 let caller_predicates = self.param_env.caller_bounds.to_vec();
1018 for poly_bound in traits::elaborate_predicates(self.tcx, caller_predicates)
1019 .filter_map(|p| p.to_opt_poly_trait_ref())
1020 .filter(|b| b.def_id() == trait_def_id) {
1021 let bound = self.erase_late_bound_regions(&poly_bound);
1022 let xform_self_ty = self.xform_self_ty(&item, bound.self_ty(), bound.substs);
1024 debug!("assemble_where_clause_candidates: bound={:?} xform_self_ty={:?}",
1028 self.push_extension_candidate(xform_self_ty, item,
1029 WhereClauseCandidate(poly_bound), import_id);
1033 fn candidate_method_names(&self) -> Vec<ast::Name> {
1034 let mut set = FxHashSet();
1035 let mut names: Vec<_> =
1036 self.inherent_candidates
1038 .chain(&self.extension_candidates)
1039 .map(|candidate| candidate.item.name)
1040 .filter(|&name| set.insert(name))
1043 // sort them by the name so we have a stable result
1044 names.sort_by_key(|n| n.as_str());
1048 ///////////////////////////////////////////////////////////////////////////
1049 // THE ACTUAL SEARCH
1051 fn pick(mut self) -> PickResult<'tcx> {
1052 assert!(match self.looking_for {
1053 LookingFor::MethodName(_) => true,
1054 LookingFor::ReturnType(_) => false,
1057 if let Some(r) = self.pick_core() {
1061 let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
1062 let private_candidate = mem::replace(&mut self.private_candidate, None);
1063 let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
1065 // things failed, so lets look at all traits, for diagnostic purposes now:
1068 let span = self.span;
1071 self.assemble_extension_candidates_for_all_traits()?;
1073 let out_of_scope_traits = match self.pick_core() {
1074 Some(Ok(p)) => vec![p.item.container.id()],
1075 //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
1076 Some(Err(MethodError::Ambiguity(v))) => {
1080 TraitSource(id) => id,
1081 ImplSource(impl_id) => {
1082 match tcx.trait_id_of_impl(impl_id) {
1086 "found inherent method when looking at traits")
1094 Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
1095 assert!(others.is_empty());
1098 Some(Err(MethodError::ClosureAmbiguity(..))) => {
1099 // this error only occurs when assembling candidates
1100 span_bug!(span, "encountered ClosureAmbiguity from pick_core");
1105 if let Some(def) = private_candidate {
1106 return Err(MethodError::PrivateMatch(def, out_of_scope_traits));
1109 Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
1110 unsatisfied_predicates,
1111 out_of_scope_traits,
1115 fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
1116 let steps = self.steps.clone();
1118 // find the first step that works
1122 debug!("pick_core: step={:?}", step);
1123 !step.self_ty.references_error()
1124 }).flat_map(|step| {
1125 self.pick_by_value_method(step).or_else(|| {
1126 self.pick_autorefd_method(step, hir::MutImmutable).or_else(|| {
1127 self.pick_autorefd_method(step, hir::MutMutable)
1132 fn pick_by_value_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
1133 //! For each type `T` in the step list, this attempts to find a
1134 //! method where the (transformed) self type is exactly `T`. We
1135 //! do however do one transformation on the adjustment: if we
1136 //! are passing a region pointer in, we will potentially
1137 //! *reborrow* it to a shorter lifetime. This allows us to
1138 //! transparently pass `&mut` pointers, in particular, without
1139 //! consuming them for their entire lifetime.
1145 self.pick_method(step.self_ty).map(|r| {
1147 pick.autoderefs = step.autoderefs;
1149 // Insert a `&*` or `&mut *` if this is a reference type:
1150 if let ty::TyRef(_, mt) = step.self_ty.sty {
1151 pick.autoderefs += 1;
1152 pick.autoref = Some(mt.mutbl);
1160 fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>, mutbl: hir::Mutability)
1161 -> Option<PickResult<'tcx>> {
1164 // In general, during probing we erase regions. See
1165 // `impl_self_ty()` for an explanation.
1166 let region = tcx.types.re_erased;
1168 let autoref_ty = tcx.mk_ref(region,
1170 ty: step.self_ty, mutbl
1172 self.pick_method(autoref_ty).map(|r| {
1174 pick.autoderefs = step.autoderefs;
1175 pick.autoref = Some(mutbl);
1176 pick.unsize = if step.unsize {
1186 fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
1187 debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1189 let mut possibly_unsatisfied_predicates = Vec::new();
1191 debug!("searching inherent candidates");
1192 if let Some(pick) = self.consider_candidates(self_ty,
1193 &self.inherent_candidates,
1194 &mut possibly_unsatisfied_predicates) {
1198 debug!("searching extension candidates");
1199 let res = self.consider_candidates(self_ty,
1200 &self.extension_candidates,
1201 &mut possibly_unsatisfied_predicates);
1203 self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1208 fn consider_candidates(&self,
1210 probes: &[Candidate<'tcx>],
1211 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1212 -> Option<PickResult<'tcx>> {
1213 let mut applicable_candidates: Vec<_> = probes.iter()
1214 .filter(|&probe| self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
1217 debug!("applicable_candidates: {:?}", applicable_candidates);
1219 if applicable_candidates.len() > 1 {
1220 match self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1222 return Some(Ok(pick));
1228 if applicable_candidates.len() > 1 {
1229 let sources = probes.iter().map(|p| p.to_source()).collect();
1230 return Some(Err(MethodError::Ambiguity(sources)));
1233 applicable_candidates.pop().map(|probe| Ok(probe.to_unadjusted_pick()))
1236 fn consider_probe(&self,
1238 probe: &Candidate<'tcx>,
1239 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1241 debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1244 // First check that the self type can be related.
1245 let sub_obligations = match self.at(&ObligationCause::dummy(), self.param_env)
1246 .sup(probe.xform_self_ty, self_ty) {
1247 Ok(InferOk { obligations, value: () }) => obligations,
1249 debug!("--> cannot relate self-types");
1254 // If so, impls may carry other conditions (e.g., where
1255 // clauses) that must be considered. Make sure that those
1256 // match as well (or at least may match, sometimes we
1257 // don't have enough information to fully evaluate).
1258 let (impl_def_id, substs, ref_obligations) = match probe.kind {
1259 InherentImplCandidate(ref substs, ref ref_obligations) => {
1260 (probe.item.container.id(), substs, ref_obligations)
1263 ExtensionImplCandidate(impl_def_id, ref substs, ref ref_obligations) => {
1264 (impl_def_id, substs, ref_obligations)
1269 WhereClauseCandidate(..) => {
1270 // These have no additional conditions to check.
1275 let selcx = &mut traits::SelectionContext::new(self);
1276 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1278 // Check whether the impl imposes obligations we have to worry about.
1279 let impl_bounds = self.tcx.predicates_of(impl_def_id);
1280 let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1281 let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
1282 traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
1284 // Convert the bounds into obligations.
1285 let obligations = traits::predicates_for_generics(cause.clone(),
1288 debug!("impl_obligations={:?}", obligations);
1290 // Evaluate those obligations to see if they might possibly hold.
1291 let mut all_true = true;
1292 for o in obligations.iter()
1293 .chain(sub_obligations.iter())
1294 .chain(norm_obligations.iter())
1295 .chain(ref_obligations.iter()) {
1296 if !selcx.evaluate_obligation(o) {
1298 if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1299 possibly_unsatisfied_predicates.push(pred.0.trait_ref);
1307 /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1308 /// same trait, but we don't know which impl to use. In this case, since in all cases the
1309 /// external interface of the method can be determined from the trait, it's ok not to decide.
1310 /// We can basically just collapse all of the probes for various impls into one where-clause
1311 /// probe. This will result in a pending obligation so when more type-info is available we can
1312 /// make the final decision.
1314 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1317 /// trait Foo { ... }
1318 /// impl Foo for Vec<int> { ... }
1319 /// impl Foo for Vec<usize> { ... }
1322 /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1323 /// use, so it's ok to just commit to "using the method from the trait Foo".
1324 fn collapse_candidates_to_trait_pick(&self, probes: &[&Candidate<'tcx>]) -> Option<Pick<'tcx>> {
1325 // Do all probes correspond to the same trait?
1326 let container = probes[0].item.container;
1328 ty::TraitContainer(_) => {}
1329 ty::ImplContainer(_) => return None,
1331 if probes[1..].iter().any(|p| p.item.container != container) {
1335 // If so, just use this trait and call it a day.
1337 item: probes[0].item.clone(),
1339 import_id: probes[0].import_id,
1346 ///////////////////////////////////////////////////////////////////////////
1348 fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
1349 // "Fast track" -- check for usage of sugar when in method call
1352 // In Path mode (i.e., resolving a value like `T::next`), consider any
1353 // associated value (i.e., methods, constants) but not types.
1355 Mode::MethodCall => item.method_has_self_argument,
1356 Mode::Path => match item.kind {
1357 ty::AssociatedKind::Type => false,
1358 ty::AssociatedKind::Method | ty::AssociatedKind::Const => true
1361 // FIXME -- check for types that deref to `Self`,
1362 // like `Rc<Self>` and so on.
1364 // Note also that the current code will break if this type
1365 // includes any of the type parameters defined on the method
1366 // -- but this could be overcome.
1369 fn record_static_candidate(&mut self, source: CandidateSource) {
1370 self.static_candidates.push(source);
1373 fn xform_self_ty(&self,
1374 item: &ty::AssociatedItem,
1376 substs: &Substs<'tcx>)
1378 if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
1379 self.xform_method_self_ty(item.def_id, impl_ty, substs)
1385 fn xform_method_self_ty(&self,
1388 substs: &Substs<'tcx>)
1390 let self_ty = self.tcx.fn_sig(method).input(0);
1391 debug!("xform_self_ty(impl_ty={:?}, self_ty={:?}, substs={:?})",
1396 assert!(!substs.has_escaping_regions());
1398 // It is possible for type parameters or early-bound lifetimes
1399 // to appear in the signature of `self`. The substitutions we
1400 // are given do not include type/lifetime parameters for the
1401 // method yet. So create fresh variables here for those too,
1402 // if there are any.
1403 let generics = self.tcx.generics_of(method);
1404 assert_eq!(substs.types().count(), generics.parent_types as usize);
1405 assert_eq!(substs.regions().count(), generics.parent_regions as usize);
1407 // Erase any late-bound regions from the method and substitute
1408 // in the values from the substitution.
1409 let xform_self_ty = self.erase_late_bound_regions(&self_ty);
1411 if generics.types.is_empty() && generics.regions.is_empty() {
1412 xform_self_ty.subst(self.tcx, substs)
1414 let substs = Substs::for_item(self.tcx, method, |def, _| {
1415 let i = def.index as usize;
1416 if i < substs.len() {
1419 // In general, during probe we erase regions. See
1420 // `impl_self_ty()` for an explanation.
1421 self.tcx.types.re_erased
1423 }, |def, cur_substs| {
1424 let i = def.index as usize;
1425 if i < substs.len() {
1428 self.type_var_for_def(self.span, def, cur_substs)
1431 xform_self_ty.subst(self.tcx, substs)
1435 /// Get the type of an impl and generate substitutions with placeholders.
1436 fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
1437 let impl_ty = self.tcx.type_of(impl_def_id);
1439 let substs = Substs::for_item(self.tcx,
1441 |_, _| self.tcx.types.re_erased,
1442 |_, _| self.next_ty_var(
1443 TypeVariableOrigin::SubstitutionPlaceholder(
1444 self.tcx.def_span(impl_def_id))));
1449 /// Replace late-bound-regions bound by `value` with `'static` using
1450 /// `ty::erase_late_bound_regions`.
1452 /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1453 /// method matching. It is reasonable during the probe phase because we don't consider region
1454 /// relationships at all. Therefore, we can just replace all the region variables with 'static
1455 /// rather than creating fresh region variables. This is nice for two reasons:
1457 /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1458 /// particular method call, it winds up creating fewer types overall, which helps for memory
1459 /// usage. (Admittedly, this is a rather small effect, though measureable.)
1461 /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1462 /// late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1463 /// regions with actual region variables as is proper, we'd have to ensure that the same
1464 /// region got replaced with the same variable, which requires a bit more coordination
1465 /// and/or tracking the substitution and
1467 fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1468 where T: TypeFoldable<'tcx>
1470 self.tcx.erase_late_bound_regions(value)
1473 /// Find the method with the appropriate name (or return type, as the case may be).
1474 fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
1475 match self.looking_for {
1476 LookingFor::MethodName(name) => {
1477 self.fcx.associated_item(def_id, name).map_or(Vec::new(), |x| vec![x])
1479 LookingFor::ReturnType(return_ty) => {
1481 .associated_items(def_id)
1482 .map(|did| self.tcx.associated_item(did.def_id))
1483 .filter(|m| self.matches_return_type(m, return_ty))
1490 impl<'tcx> Candidate<'tcx> {
1491 fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1493 item: self.item.clone(),
1494 kind: match self.kind {
1495 InherentImplCandidate(..) => InherentImplPick,
1496 ExtensionImplCandidate(def_id, ..) => ExtensionImplPick(def_id),
1497 ObjectCandidate => ObjectPick,
1498 TraitCandidate => TraitPick,
1499 WhereClauseCandidate(ref trait_ref) => {
1500 // Only trait derived from where-clauses should
1501 // appear here, so they should not contain any
1502 // inference variables or other artifacts. This
1503 // means they are safe to put into the
1504 // `WhereClausePick`.
1505 assert!(!trait_ref.substs().needs_infer());
1507 WhereClausePick(trait_ref.clone())
1510 import_id: self.import_id,
1517 fn to_source(&self) -> CandidateSource {
1519 InherentImplCandidate(..) => ImplSource(self.item.container.id()),
1520 ExtensionImplCandidate(def_id, ..) => ImplSource(def_id),
1523 WhereClauseCandidate(_) => TraitSource(self.item.container.id()),