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}
;
21 use rustc
::ty
::{self, Ty, ToPolyTraitRef, TraitRef, TypeFoldable}
;
22 use rustc
::infer
::{InferOk, TypeOrigin}
;
23 use rustc
::util
::nodemap
::FnvHashSet
;
25 use syntax_pos
::{Span, DUMMY_SP}
;
31 use self::CandidateKind
::*;
32 pub use self::PickKind
::*;
34 struct ProbeContext
<'a
, 'gcx
: 'a
+ 'tcx
, 'tcx
: 'a
> {
35 fcx
: &'a FnCtxt
<'a
, 'gcx
, 'tcx
>,
39 steps
: Rc
<Vec
<CandidateStep
<'tcx
>>>,
40 opt_simplified_steps
: Option
<Vec
<ty
::fast_reject
::SimplifiedType
>>,
41 inherent_candidates
: Vec
<Candidate
<'tcx
>>,
42 extension_candidates
: Vec
<Candidate
<'tcx
>>,
43 impl_dups
: FnvHashSet
<DefId
>,
44 import_id
: Option
<ast
::NodeId
>,
46 /// Collects near misses when the candidate functions are missing a `self` keyword and is only
47 /// used for error reporting
48 static_candidates
: Vec
<CandidateSource
>,
50 /// Some(candidate) if there is a private candidate
51 private_candidate
: Option
<Def
>,
53 /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
54 /// for error reporting
55 unsatisfied_predicates
: Vec
<TraitRef
<'tcx
>>,
58 impl<'a
, 'gcx
, 'tcx
> Deref
for ProbeContext
<'a
, 'gcx
, 'tcx
> {
59 type Target
= FnCtxt
<'a
, 'gcx
, 'tcx
>;
60 fn deref(&self) -> &Self::Target
{
66 struct CandidateStep
<'tcx
> {
73 struct Candidate
<'tcx
> {
74 xform_self_ty
: Ty
<'tcx
>,
75 item
: ty
::ImplOrTraitItem
<'tcx
>,
76 kind
: CandidateKind
<'tcx
>,
77 import_id
: Option
<ast
::NodeId
>,
81 enum CandidateKind
<'tcx
> {
82 InherentImplCandidate(&'tcx Substs
<'tcx
>,
83 // Normalize obligations
84 Vec
<traits
::PredicateObligation
<'tcx
>>),
85 ExtensionImplCandidate(// Impl
88 // Normalize obligations
89 Vec
<traits
::PredicateObligation
<'tcx
>>),
92 WhereClauseCandidate(// Trait
93 ty
::PolyTraitRef
<'tcx
>),
97 pub struct Pick
<'tcx
> {
98 pub item
: ty
::ImplOrTraitItem
<'tcx
>,
99 pub kind
: PickKind
<'tcx
>,
100 pub import_id
: Option
<ast
::NodeId
>,
102 // Indicates that the source expression should be autoderef'd N times
104 // A = expr | *expr | **expr | ...
105 pub autoderefs
: usize,
107 // Indicates that an autoref is applied after the optional autoderefs
109 // B = A | &A | &mut A
110 pub autoref
: Option
<hir
::Mutability
>,
112 // Indicates that the source expression should be "unsized" to a
113 // target type. This should probably eventually go away in favor
114 // of just coercing method receivers.
117 pub unsize
: Option
<Ty
<'tcx
>>,
120 #[derive(Clone,Debug)]
121 pub enum PickKind
<'tcx
> {
123 ExtensionImplPick(// Impl
127 WhereClausePick(// Trait
128 ty
::PolyTraitRef
<'tcx
>),
131 pub type PickResult
<'tcx
> = Result
<Pick
<'tcx
>, MethodError
<'tcx
>>;
133 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
135 // An expression of the form `receiver.method_name(...)`.
136 // Autoderefs are performed on `receiver`, lookup is done based on the
137 // `self` argument of the method, and static methods aren't considered.
139 // An expression of the form `Type::item` or `<T>::item`.
140 // No autoderefs are performed, lookup is done based on the type each
141 // implementation is for, and static methods are included.
145 impl<'a
, 'gcx
, 'tcx
> FnCtxt
<'a
, 'gcx
, 'tcx
> {
146 pub fn probe_method(&self,
149 item_name
: ast
::Name
,
151 scope_expr_id
: ast
::NodeId
)
152 -> PickResult
<'tcx
> {
153 debug
!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
158 // FIXME(#18741) -- right now, creating the steps involves evaluating the
159 // `*` operator, which registers obligations that then escape into
160 // the global fulfillment context and thus has global
161 // side-effects. This is a bit of a pain to refactor. So just let
162 // it ride, although it's really not great, and in fact could I
163 // think cause spurious errors. Really though this part should
164 // take place in the `self.probe` below.
165 let steps
= if mode
== Mode
::MethodCall
{
166 match self.create_steps(span
, self_ty
) {
167 Some(steps
) => steps
,
169 return Err(MethodError
::NoMatch(NoMatchData
::new(Vec
::new(),
183 // Create a list of simplified self types, if we can.
184 let mut simplified_steps
= Vec
::new();
186 match ty
::fast_reject
::simplify_type(self.tcx
, step
.self_ty
, true) {
190 Some(simplified_type
) => {
191 simplified_steps
.push(simplified_type
);
195 let opt_simplified_steps
= if simplified_steps
.len() < steps
.len() {
196 None
// failed to convert at least one of the steps
198 Some(simplified_steps
)
201 debug
!("ProbeContext: steps for self_ty={:?} are {:?}",
205 // this creates one big transaction so that all type variables etc
206 // that we create during the probe process are removed later
209 ProbeContext
::new(self, span
, mode
, item_name
, steps
, opt_simplified_steps
);
210 probe_cx
.assemble_inherent_candidates();
211 probe_cx
.assemble_extension_candidates_for_traits_in_scope(scope_expr_id
)?
;
216 fn create_steps(&self, span
: Span
, self_ty
: Ty
<'tcx
>) -> Option
<Vec
<CandidateStep
<'tcx
>>> {
217 // FIXME: we don't need to create the entire steps in one pass
219 let mut autoderef
= self.autoderef(span
, self_ty
);
220 let mut steps
: Vec
<_
> = autoderef
.by_ref()
230 let final_ty
= autoderef
.unambiguous_final_ty();
232 ty
::TyArray(elem_ty
, _
) => {
233 let dereferences
= steps
.len() - 1;
235 steps
.push(CandidateStep
{
236 self_ty
: self.tcx
.mk_slice(elem_ty
),
237 autoderefs
: dereferences
,
241 ty
::TyError
=> return None
,
245 debug
!("create_steps: steps={:?}", steps
);
251 impl<'a
, 'gcx
, 'tcx
> ProbeContext
<'a
, 'gcx
, 'tcx
> {
252 fn new(fcx
: &'a FnCtxt
<'a
, 'gcx
, 'tcx
>,
255 item_name
: ast
::Name
,
256 steps
: Vec
<CandidateStep
<'tcx
>>,
257 opt_simplified_steps
: Option
<Vec
<ty
::fast_reject
::SimplifiedType
>>)
258 -> ProbeContext
<'a
, 'gcx
, 'tcx
> {
263 item_name
: item_name
,
264 inherent_candidates
: Vec
::new(),
265 extension_candidates
: Vec
::new(),
266 impl_dups
: FnvHashSet(),
268 steps
: Rc
::new(steps
),
269 opt_simplified_steps
: opt_simplified_steps
,
270 static_candidates
: Vec
::new(),
271 private_candidate
: None
,
272 unsatisfied_predicates
: Vec
::new(),
276 fn reset(&mut self) {
277 self.inherent_candidates
.clear();
278 self.extension_candidates
.clear();
279 self.impl_dups
.clear();
280 self.static_candidates
.clear();
281 self.private_candidate
= None
;
284 ///////////////////////////////////////////////////////////////////////////
285 // CANDIDATE ASSEMBLY
287 fn assemble_inherent_candidates(&mut self) {
288 let steps
= self.steps
.clone();
289 for step
in steps
.iter() {
290 self.assemble_probe(step
.self_ty
);
294 fn assemble_probe(&mut self, self_ty
: Ty
<'tcx
>) {
295 debug
!("assemble_probe: self_ty={:?}", self_ty
);
298 ty
::TyTrait(box ref data
) => {
299 self.assemble_inherent_candidates_from_object(self_ty
, data
.principal
);
300 self.assemble_inherent_impl_candidates_for_type(data
.principal
.def_id());
302 ty
::TyAdt(def
, _
) => {
303 self.assemble_inherent_impl_candidates_for_type(def
.did
);
306 if let Some(box_did
) = self.tcx
.lang_items
.owned_box() {
307 self.assemble_inherent_impl_candidates_for_type(box_did
);
311 self.assemble_inherent_candidates_from_param(self_ty
, p
);
314 let lang_def_id
= self.tcx
.lang_items
.char_impl();
315 self.assemble_inherent_impl_for_primitive(lang_def_id
);
318 let lang_def_id
= self.tcx
.lang_items
.str_impl();
319 self.assemble_inherent_impl_for_primitive(lang_def_id
);
322 let lang_def_id
= self.tcx
.lang_items
.slice_impl();
323 self.assemble_inherent_impl_for_primitive(lang_def_id
);
325 ty
::TyRawPtr(ty
::TypeAndMut { ty: _, mutbl: hir::MutImmutable }
) => {
326 let lang_def_id
= self.tcx
.lang_items
.const_ptr_impl();
327 self.assemble_inherent_impl_for_primitive(lang_def_id
);
329 ty
::TyRawPtr(ty
::TypeAndMut { ty: _, mutbl: hir::MutMutable }
) => {
330 let lang_def_id
= self.tcx
.lang_items
.mut_ptr_impl();
331 self.assemble_inherent_impl_for_primitive(lang_def_id
);
333 ty
::TyInt(ast
::IntTy
::I8
) => {
334 let lang_def_id
= self.tcx
.lang_items
.i8_impl();
335 self.assemble_inherent_impl_for_primitive(lang_def_id
);
337 ty
::TyInt(ast
::IntTy
::I16
) => {
338 let lang_def_id
= self.tcx
.lang_items
.i16_impl();
339 self.assemble_inherent_impl_for_primitive(lang_def_id
);
341 ty
::TyInt(ast
::IntTy
::I32
) => {
342 let lang_def_id
= self.tcx
.lang_items
.i32_impl();
343 self.assemble_inherent_impl_for_primitive(lang_def_id
);
345 ty
::TyInt(ast
::IntTy
::I64
) => {
346 let lang_def_id
= self.tcx
.lang_items
.i64_impl();
347 self.assemble_inherent_impl_for_primitive(lang_def_id
);
349 ty
::TyInt(ast
::IntTy
::Is
) => {
350 let lang_def_id
= self.tcx
.lang_items
.isize_impl();
351 self.assemble_inherent_impl_for_primitive(lang_def_id
);
353 ty
::TyUint(ast
::UintTy
::U8
) => {
354 let lang_def_id
= self.tcx
.lang_items
.u8_impl();
355 self.assemble_inherent_impl_for_primitive(lang_def_id
);
357 ty
::TyUint(ast
::UintTy
::U16
) => {
358 let lang_def_id
= self.tcx
.lang_items
.u16_impl();
359 self.assemble_inherent_impl_for_primitive(lang_def_id
);
361 ty
::TyUint(ast
::UintTy
::U32
) => {
362 let lang_def_id
= self.tcx
.lang_items
.u32_impl();
363 self.assemble_inherent_impl_for_primitive(lang_def_id
);
365 ty
::TyUint(ast
::UintTy
::U64
) => {
366 let lang_def_id
= self.tcx
.lang_items
.u64_impl();
367 self.assemble_inherent_impl_for_primitive(lang_def_id
);
369 ty
::TyUint(ast
::UintTy
::Us
) => {
370 let lang_def_id
= self.tcx
.lang_items
.usize_impl();
371 self.assemble_inherent_impl_for_primitive(lang_def_id
);
373 ty
::TyFloat(ast
::FloatTy
::F32
) => {
374 let lang_def_id
= self.tcx
.lang_items
.f32_impl();
375 self.assemble_inherent_impl_for_primitive(lang_def_id
);
377 ty
::TyFloat(ast
::FloatTy
::F64
) => {
378 let lang_def_id
= self.tcx
.lang_items
.f64_impl();
379 self.assemble_inherent_impl_for_primitive(lang_def_id
);
385 fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id
: Option
<DefId
>) {
386 if let Some(impl_def_id
) = lang_def_id
{
387 self.tcx
.populate_implementations_for_primitive_if_necessary(impl_def_id
);
389 self.assemble_inherent_impl_probe(impl_def_id
);
393 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id
: DefId
) {
394 // Read the inherent implementation candidates for this type from the
395 // metadata if necessary.
396 self.tcx
.populate_inherent_implementations_for_type_if_necessary(def_id
);
398 if let Some(impl_infos
) = self.tcx
.inherent_impls
.borrow().get(&def_id
) {
399 for &impl_def_id
in impl_infos
.iter() {
400 self.assemble_inherent_impl_probe(impl_def_id
);
405 fn assemble_inherent_impl_probe(&mut self, impl_def_id
: DefId
) {
406 if !self.impl_dups
.insert(impl_def_id
) {
407 return; // already visited
410 debug
!("assemble_inherent_impl_probe {:?}", impl_def_id
);
412 let item
= match self.impl_or_trait_item(impl_def_id
) {
416 } // No method with correct name on this impl
419 if !self.has_applicable_self(&item
) {
420 // No receiver declared. Not a candidate.
421 return self.record_static_candidate(ImplSource(impl_def_id
));
424 if !item
.vis().is_accessible_from(self.body_id
, &self.tcx
.map
) {
425 self.private_candidate
= Some(item
.def());
429 let (impl_ty
, impl_substs
) = self.impl_ty_and_substs(impl_def_id
);
430 let impl_ty
= impl_ty
.subst(self.tcx
, impl_substs
);
432 // Determine the receiver type that the method itself expects.
433 let xform_self_ty
= self.xform_self_ty(&item
, impl_ty
, impl_substs
);
435 // We can't use normalize_associated_types_in as it will pollute the
436 // fcx's fulfillment context after this probe is over.
437 let cause
= traits
::ObligationCause
::misc(self.span
, self.body_id
);
438 let mut selcx
= &mut traits
::SelectionContext
::new(self.fcx
);
439 let traits
::Normalized { value: xform_self_ty, obligations }
=
440 traits
::normalize(selcx
, cause
, &xform_self_ty
);
441 debug
!("assemble_inherent_impl_probe: xform_self_ty = {:?}",
444 self.inherent_candidates
.push(Candidate
{
445 xform_self_ty
: xform_self_ty
,
447 kind
: InherentImplCandidate(impl_substs
, obligations
),
448 import_id
: self.import_id
,
452 fn assemble_inherent_candidates_from_object(&mut self,
454 principal
: ty
::PolyExistentialTraitRef
<'tcx
>) {
455 debug
!("assemble_inherent_candidates_from_object(self_ty={:?})",
458 // It is illegal to invoke a method on a trait instance that
459 // refers to the `Self` type. An error will be reported by
460 // `enforce_object_limitations()` if the method refers to the
461 // `Self` type anywhere other than the receiver. Here, we use
462 // a substitution that replaces `Self` with the object type
463 // itself. Hence, a `&self` method will wind up with an
464 // argument type like `&Trait`.
465 let trait_ref
= principal
.with_self_ty(self.tcx
, self_ty
);
466 self.elaborate_bounds(&[trait_ref
], |this
, new_trait_ref
, item
| {
467 let new_trait_ref
= this
.erase_late_bound_regions(&new_trait_ref
);
470 this
.xform_self_ty(&item
, new_trait_ref
.self_ty(), new_trait_ref
.substs
);
472 this
.inherent_candidates
.push(Candidate
{
473 xform_self_ty
: xform_self_ty
,
475 kind
: ObjectCandidate
,
476 import_id
: this
.import_id
,
481 fn assemble_inherent_candidates_from_param(&mut self,
483 param_ty
: ty
::ParamTy
) {
484 // FIXME -- Do we want to commit to this behavior for param bounds?
486 let bounds
: Vec
<_
> = self.parameter_environment
489 .filter_map(|predicate
| {
491 ty
::Predicate
::Trait(ref trait_predicate
) => {
492 match trait_predicate
.0.trait_ref
.self_ty().sty
{
493 ty
::TyParam(ref p
) if *p
== param_ty
=> {
494 Some(trait_predicate
.to_poly_trait_ref())
499 ty
::Predicate
::Equate(..) |
500 ty
::Predicate
::Projection(..) |
501 ty
::Predicate
::RegionOutlives(..) |
502 ty
::Predicate
::WellFormed(..) |
503 ty
::Predicate
::ObjectSafe(..) |
504 ty
::Predicate
::ClosureKind(..) |
505 ty
::Predicate
::TypeOutlives(..) => None
,
510 self.elaborate_bounds(&bounds
, |this
, poly_trait_ref
, item
| {
511 let trait_ref
= this
.erase_late_bound_regions(&poly_trait_ref
);
513 let xform_self_ty
= this
.xform_self_ty(&item
, trait_ref
.self_ty(), trait_ref
.substs
);
515 if let Some(ref m
) = item
.as_opt_method() {
516 debug
!("found match: trait_ref={:?} substs={:?} m={:?}",
520 assert_eq
!(m
.generics
.parent_types
as usize,
521 trait_ref
.substs
.types().count());
522 assert_eq
!(m
.generics
.parent_regions
as usize,
523 trait_ref
.substs
.regions().count());
526 // Because this trait derives from a where-clause, it
527 // should not contain any inference variables or other
528 // artifacts. This means it is safe to put into the
529 // `WhereClauseCandidate` and (eventually) into the
530 // `WhereClausePick`.
531 assert
!(!trait_ref
.substs
.needs_infer());
533 this
.inherent_candidates
.push(Candidate
{
534 xform_self_ty
: xform_self_ty
,
536 kind
: WhereClauseCandidate(poly_trait_ref
),
537 import_id
: this
.import_id
,
542 // Do a search through a list of bounds, using a callback to actually
543 // create the candidates.
544 fn elaborate_bounds
<F
>(&mut self, bounds
: &[ty
::PolyTraitRef
<'tcx
>], mut mk_cand
: F
)
545 where F
: for<'b
> FnMut(&mut ProbeContext
<'b
, 'gcx
, 'tcx
>,
546 ty
::PolyTraitRef
<'tcx
>,
547 ty
::ImplOrTraitItem
<'tcx
>)
549 debug
!("elaborate_bounds(bounds={:?})", bounds
);
552 for bound_trait_ref
in traits
::transitive_bounds(tcx
, bounds
) {
553 let item
= match self.impl_or_trait_item(bound_trait_ref
.def_id()) {
560 if !self.has_applicable_self(&item
) {
561 self.record_static_candidate(TraitSource(bound_trait_ref
.def_id()));
563 mk_cand(self, bound_trait_ref
, item
);
568 fn assemble_extension_candidates_for_traits_in_scope(&mut self,
569 expr_id
: ast
::NodeId
)
570 -> Result
<(), MethodError
<'tcx
>> {
571 let mut duplicates
= FnvHashSet();
572 let opt_applicable_traits
= self.tcx
.trait_map
.get(&expr_id
);
573 if let Some(applicable_traits
) = opt_applicable_traits
{
574 for trait_candidate
in applicable_traits
{
575 let trait_did
= trait_candidate
.def_id
;
576 if duplicates
.insert(trait_did
) {
577 self.import_id
= trait_candidate
.import_id
;
578 let result
= self.assemble_extension_candidates_for_trait(trait_did
);
579 self.import_id
= None
;
587 fn assemble_extension_candidates_for_all_traits(&mut self) -> Result
<(), MethodError
<'tcx
>> {
588 let mut duplicates
= FnvHashSet();
589 for trait_info
in suggest
::all_traits(self.ccx
) {
590 if duplicates
.insert(trait_info
.def_id
) {
591 self.assemble_extension_candidates_for_trait(trait_info
.def_id
)?
;
597 fn assemble_extension_candidates_for_trait(&mut self,
599 -> Result
<(), MethodError
<'tcx
>> {
600 debug
!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
603 // Check whether `trait_def_id` defines a method with suitable name:
604 let trait_items
= self.tcx
.trait_items(trait_def_id
);
605 let maybe_item
= trait_items
.iter()
606 .find(|item
| item
.name() == self.item_name
);
607 let item
= match maybe_item
{
614 // Check whether `trait_def_id` defines a method with suitable name:
615 if !self.has_applicable_self(item
) {
616 debug
!("method has inapplicable self");
617 self.record_static_candidate(TraitSource(trait_def_id
));
621 self.assemble_extension_candidates_for_trait_impls(trait_def_id
, item
.clone());
623 self.assemble_closure_candidates(trait_def_id
, item
.clone())?
;
625 self.assemble_projection_candidates(trait_def_id
, item
.clone());
627 self.assemble_where_clause_candidates(trait_def_id
, item
.clone());
632 fn assemble_extension_candidates_for_trait_impls(&mut self,
634 item
: ty
::ImplOrTraitItem
<'tcx
>) {
635 let trait_def
= self.tcx
.lookup_trait_def(trait_def_id
);
637 // FIXME(arielb1): can we use for_each_relevant_impl here?
638 trait_def
.for_each_impl(self.tcx
, |impl_def_id
| {
639 debug
!("assemble_extension_candidates_for_trait_impl: trait_def_id={:?} \
644 if !self.impl_can_possibly_match(impl_def_id
) {
648 let (_
, impl_substs
) = self.impl_ty_and_substs(impl_def_id
);
650 debug
!("impl_substs={:?}", impl_substs
);
652 let impl_trait_ref
= self.tcx
.impl_trait_ref(impl_def_id
)
653 .unwrap() // we know this is a trait impl
654 .subst(self.tcx
, impl_substs
);
656 debug
!("impl_trait_ref={:?}", impl_trait_ref
);
658 // Determine the receiver type that the method itself expects.
660 self.xform_self_ty(&item
, impl_trait_ref
.self_ty(), impl_trait_ref
.substs
);
662 // Normalize the receiver. We can't use normalize_associated_types_in
663 // as it will pollute the fcx's fulfillment context after this probe
665 let cause
= traits
::ObligationCause
::misc(self.span
, self.body_id
);
666 let mut selcx
= &mut traits
::SelectionContext
::new(self.fcx
);
667 let traits
::Normalized { value: xform_self_ty, obligations }
=
668 traits
::normalize(selcx
, cause
, &xform_self_ty
);
670 debug
!("xform_self_ty={:?}", xform_self_ty
);
672 self.extension_candidates
.push(Candidate
{
673 xform_self_ty
: xform_self_ty
,
675 kind
: ExtensionImplCandidate(impl_def_id
, impl_substs
, obligations
),
676 import_id
: self.import_id
,
681 fn impl_can_possibly_match(&self, impl_def_id
: DefId
) -> bool
{
682 let simplified_steps
= match self.opt_simplified_steps
{
683 Some(ref simplified_steps
) => simplified_steps
,
689 let impl_type
= self.tcx
.lookup_item_type(impl_def_id
);
690 let impl_simplified_type
=
691 match ty
::fast_reject
::simplify_type(self.tcx
, impl_type
.ty
, false) {
692 Some(simplified_type
) => simplified_type
,
698 simplified_steps
.contains(&impl_simplified_type
)
701 fn assemble_closure_candidates(&mut self,
703 item
: ty
::ImplOrTraitItem
<'tcx
>)
704 -> Result
<(), MethodError
<'tcx
>> {
705 // Check if this is one of the Fn,FnMut,FnOnce traits.
707 let kind
= if Some(trait_def_id
) == tcx
.lang_items
.fn_trait() {
709 } else if Some(trait_def_id
) == tcx
.lang_items
.fn_mut_trait() {
710 ty
::ClosureKind
::FnMut
711 } else if Some(trait_def_id
) == tcx
.lang_items
.fn_once_trait() {
712 ty
::ClosureKind
::FnOnce
717 // Check if there is an unboxed-closure self-type in the list of receivers.
718 // If so, add "synthetic impls".
719 let steps
= self.steps
.clone();
720 for step
in steps
.iter() {
721 let closure_def_id
= match step
.self_ty
.sty
{
722 ty
::TyClosure(a
, _
) => a
,
726 let closure_kinds
= &self.tables
.borrow().closure_kinds
;
727 let closure_kind
= match closure_kinds
.get(&closure_def_id
) {
730 return Err(MethodError
::ClosureAmbiguity(trait_def_id
));
734 // this closure doesn't implement the right kind of `Fn` trait
735 if !closure_kind
.extends(kind
) {
739 // create some substitutions for the argument/return type;
740 // for the purposes of our method lookup, we only take
741 // receiver type into account, so we can just substitute
742 // fresh types here to use during substitution and subtyping.
743 let substs
= Substs
::for_item(self.tcx
,
745 |def
, _
| self.region_var_for_def(self.span
, def
),
750 self.type_var_for_def(self.span
, def
, substs
)
754 let xform_self_ty
= self.xform_self_ty(&item
, step
.self_ty
, substs
);
755 self.inherent_candidates
.push(Candidate
{
756 xform_self_ty
: xform_self_ty
,
758 kind
: TraitCandidate
,
759 import_id
: self.import_id
,
766 fn assemble_projection_candidates(&mut self,
768 item
: ty
::ImplOrTraitItem
<'tcx
>) {
769 debug
!("assemble_projection_candidates(\
775 for step
in self.steps
.iter() {
776 debug
!("assemble_projection_candidates: step={:?}", step
);
778 let (def_id
, substs
) = match step
.self_ty
.sty
{
779 ty
::TyProjection(ref data
) => (data
.trait_ref
.def_id
, data
.trait_ref
.substs
),
780 ty
::TyAnon(def_id
, substs
) => (def_id
, substs
),
784 debug
!("assemble_projection_candidates: def_id={:?} substs={:?}",
788 let trait_predicates
= self.tcx
.lookup_predicates(def_id
);
789 let bounds
= trait_predicates
.instantiate(self.tcx
, substs
);
790 let predicates
= bounds
.predicates
;
791 debug
!("assemble_projection_candidates: predicates={:?}",
793 for poly_bound
in traits
::elaborate_predicates(self.tcx
, predicates
)
794 .filter_map(|p
| p
.to_opt_poly_trait_ref())
795 .filter(|b
| b
.def_id() == trait_def_id
) {
796 let bound
= self.erase_late_bound_regions(&poly_bound
);
798 debug
!("assemble_projection_candidates: def_id={:?} substs={:?} bound={:?}",
803 if self.can_equate(&step
.self_ty
, &bound
.self_ty()).is_ok() {
804 let xform_self_ty
= self.xform_self_ty(&item
, bound
.self_ty(), bound
.substs
);
806 debug
!("assemble_projection_candidates: bound={:?} xform_self_ty={:?}",
810 self.extension_candidates
.push(Candidate
{
811 xform_self_ty
: xform_self_ty
,
813 kind
: TraitCandidate
,
814 import_id
: self.import_id
,
821 fn assemble_where_clause_candidates(&mut self,
823 item
: ty
::ImplOrTraitItem
<'tcx
>) {
824 debug
!("assemble_where_clause_candidates(trait_def_id={:?})",
827 let caller_predicates
= self.parameter_environment
.caller_bounds
.clone();
828 for poly_bound
in traits
::elaborate_predicates(self.tcx
, caller_predicates
)
829 .filter_map(|p
| p
.to_opt_poly_trait_ref())
830 .filter(|b
| b
.def_id() == trait_def_id
) {
831 let bound
= self.erase_late_bound_regions(&poly_bound
);
832 let xform_self_ty
= self.xform_self_ty(&item
, bound
.self_ty(), bound
.substs
);
834 debug
!("assemble_where_clause_candidates: bound={:?} xform_self_ty={:?}",
838 self.extension_candidates
.push(Candidate
{
839 xform_self_ty
: xform_self_ty
,
841 kind
: WhereClauseCandidate(poly_bound
),
842 import_id
: self.import_id
,
847 ///////////////////////////////////////////////////////////////////////////
850 fn pick(mut self) -> PickResult
<'tcx
> {
851 if let Some(r
) = self.pick_core() {
855 let static_candidates
= mem
::replace(&mut self.static_candidates
, vec
![]);
856 let private_candidate
= mem
::replace(&mut self.private_candidate
, None
);
857 let unsatisfied_predicates
= mem
::replace(&mut self.unsatisfied_predicates
, vec
![]);
859 // things failed, so lets look at all traits, for diagnostic purposes now:
862 let span
= self.span
;
865 self.assemble_extension_candidates_for_all_traits()?
;
867 let out_of_scope_traits
= match self.pick_core() {
868 Some(Ok(p
)) => vec
![p
.item
.container().id()],
869 Some(Err(MethodError
::Ambiguity(v
))) => {
873 TraitSource(id
) => id
,
874 ImplSource(impl_id
) => {
875 match tcx
.trait_id_of_impl(impl_id
) {
879 "found inherent method when looking at traits")
887 Some(Err(MethodError
::NoMatch(NoMatchData { out_of_scope_traits: others, .. }
))) => {
888 assert
!(others
.is_empty());
891 Some(Err(MethodError
::ClosureAmbiguity(..))) => {
892 // this error only occurs when assembling candidates
893 span_bug
!(span
, "encountered ClosureAmbiguity from pick_core");
898 if let Some(def
) = private_candidate
{
899 return Err(MethodError
::PrivateMatch(def
));
902 Err(MethodError
::NoMatch(NoMatchData
::new(static_candidates
,
903 unsatisfied_predicates
,
908 fn pick_core(&mut self) -> Option
<PickResult
<'tcx
>> {
909 let steps
= self.steps
.clone();
911 // find the first step that works
912 steps
.iter().filter_map(|step
| self.pick_step(step
)).next()
915 fn pick_step(&mut self, step
: &CandidateStep
<'tcx
>) -> Option
<PickResult
<'tcx
>> {
916 debug
!("pick_step: step={:?}", step
);
918 if step
.self_ty
.references_error() {
922 if let Some(result
) = self.pick_by_value_method(step
) {
926 self.pick_autorefd_method(step
)
929 fn pick_by_value_method(&mut self, step
: &CandidateStep
<'tcx
>) -> Option
<PickResult
<'tcx
>> {
930 //! For each type `T` in the step list, this attempts to find a
931 //! method where the (transformed) self type is exactly `T`. We
932 //! do however do one transformation on the adjustment: if we
933 //! are passing a region pointer in, we will potentially
934 //! *reborrow* it to a shorter lifetime. This allows us to
935 //! transparently pass `&mut` pointers, in particular, without
936 //! consuming them for their entire lifetime.
942 self.pick_method(step
.self_ty
).map(|r
| {
944 pick
.autoderefs
= step
.autoderefs
;
946 // Insert a `&*` or `&mut *` if this is a reference type:
947 if let ty
::TyRef(_
, mt
) = step
.self_ty
.sty
{
948 pick
.autoderefs
+= 1;
949 pick
.autoref
= Some(mt
.mutbl
);
957 fn pick_autorefd_method(&mut self, step
: &CandidateStep
<'tcx
>) -> Option
<PickResult
<'tcx
>> {
960 // In general, during probing we erase regions. See
961 // `impl_self_ty()` for an explanation.
962 let region
= tcx
.mk_region(ty
::ReErased
);
964 // Search through mutabilities in order to find one where pick works:
965 [hir
::MutImmutable
, hir
::MutMutable
]
968 let autoref_ty
= tcx
.mk_ref(region
,
973 self.pick_method(autoref_ty
).map(|r
| {
975 pick
.autoderefs
= step
.autoderefs
;
976 pick
.autoref
= Some(m
);
977 pick
.unsize
= if step
.unsize
{
989 fn pick_method(&mut self, self_ty
: Ty
<'tcx
>) -> Option
<PickResult
<'tcx
>> {
990 debug
!("pick_method(self_ty={})", self.ty_to_string(self_ty
));
992 let mut possibly_unsatisfied_predicates
= Vec
::new();
994 debug
!("searching inherent candidates");
995 if let Some(pick
) = self.consider_candidates(self_ty
,
996 &self.inherent_candidates
,
997 &mut possibly_unsatisfied_predicates
) {
1001 debug
!("searching extension candidates");
1002 let res
= self.consider_candidates(self_ty
,
1003 &self.extension_candidates
,
1004 &mut possibly_unsatisfied_predicates
);
1006 self.unsatisfied_predicates
.extend(possibly_unsatisfied_predicates
);
1011 fn consider_candidates(&self,
1013 probes
: &[Candidate
<'tcx
>],
1014 possibly_unsatisfied_predicates
: &mut Vec
<TraitRef
<'tcx
>>)
1015 -> Option
<PickResult
<'tcx
>> {
1016 let mut applicable_candidates
: Vec
<_
> = probes
.iter()
1017 .filter(|&probe
| self.consider_probe(self_ty
, probe
, possibly_unsatisfied_predicates
))
1020 debug
!("applicable_candidates: {:?}", applicable_candidates
);
1022 if applicable_candidates
.len() > 1 {
1023 match self.collapse_candidates_to_trait_pick(&applicable_candidates
[..]) {
1025 return Some(Ok(pick
));
1031 if applicable_candidates
.len() > 1 {
1032 let sources
= probes
.iter().map(|p
| p
.to_source()).collect();
1033 return Some(Err(MethodError
::Ambiguity(sources
)));
1036 applicable_candidates
.pop().map(|probe
| Ok(probe
.to_unadjusted_pick()))
1039 fn consider_probe(&self,
1041 probe
: &Candidate
<'tcx
>,
1042 possibly_unsatisfied_predicates
: &mut Vec
<TraitRef
<'tcx
>>)
1044 debug
!("consider_probe: self_ty={:?} probe={:?}", self_ty
, probe
);
1047 // First check that the self type can be related.
1048 match self.sub_types(false,
1049 TypeOrigin
::Misc(DUMMY_SP
),
1051 probe
.xform_self_ty
) {
1052 Ok(InferOk { obligations, .. }
) => {
1053 // FIXME(#32730) propagate obligations
1054 assert
!(obligations
.is_empty())
1057 debug
!("--> cannot relate self-types");
1062 // If so, impls may carry other conditions (e.g., where
1063 // clauses) that must be considered. Make sure that those
1064 // match as well (or at least may match, sometimes we
1065 // don't have enough information to fully evaluate).
1066 let (impl_def_id
, substs
, ref_obligations
) = match probe
.kind
{
1067 InherentImplCandidate(ref substs
, ref ref_obligations
) => {
1068 (probe
.item
.container().id(), substs
, ref_obligations
)
1071 ExtensionImplCandidate(impl_def_id
, ref substs
, ref ref_obligations
) => {
1072 (impl_def_id
, substs
, ref_obligations
)
1077 WhereClauseCandidate(..) => {
1078 // These have no additional conditions to check.
1083 let selcx
= &mut traits
::SelectionContext
::new(self);
1084 let cause
= traits
::ObligationCause
::misc(self.span
, self.body_id
);
1086 // Check whether the impl imposes obligations we have to worry about.
1087 let impl_bounds
= self.tcx
.lookup_predicates(impl_def_id
);
1088 let impl_bounds
= impl_bounds
.instantiate(self.tcx
, substs
);
1089 let traits
::Normalized { value: impl_bounds, obligations: norm_obligations }
=
1090 traits
::normalize(selcx
, cause
.clone(), &impl_bounds
);
1092 // Convert the bounds into obligations.
1093 let obligations
= traits
::predicates_for_generics(cause
.clone(), &impl_bounds
);
1094 debug
!("impl_obligations={:?}", obligations
);
1096 // Evaluate those obligations to see if they might possibly hold.
1097 let mut all_true
= true;
1098 for o
in obligations
.iter()
1099 .chain(norm_obligations
.iter())
1100 .chain(ref_obligations
.iter()) {
1101 if !selcx
.evaluate_obligation(o
) {
1103 if let &ty
::Predicate
::Trait(ref pred
) = &o
.predicate
{
1104 possibly_unsatisfied_predicates
.push(pred
.0.trait_ref
);
1112 /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1113 /// same trait, but we don't know which impl to use. In this case, since in all cases the
1114 /// external interface of the method can be determined from the trait, it's ok not to decide.
1115 /// We can basically just collapse all of the probes for various impls into one where-clause
1116 /// probe. This will result in a pending obligation so when more type-info is available we can
1117 /// make the final decision.
1119 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1122 /// trait Foo { ... }
1123 /// impl Foo for Vec<int> { ... }
1124 /// impl Foo for Vec<usize> { ... }
1127 /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1128 /// use, so it's ok to just commit to "using the method from the trait Foo".
1129 fn collapse_candidates_to_trait_pick(&self, probes
: &[&Candidate
<'tcx
>]) -> Option
<Pick
<'tcx
>> {
1130 // Do all probes correspond to the same trait?
1131 let container
= probes
[0].item
.container();
1133 ty
::TraitContainer(_
) => {}
1134 ty
::ImplContainer(_
) => return None
,
1136 if probes
[1..].iter().any(|p
| p
.item
.container() != container
) {
1140 // If so, just use this trait and call it a day.
1142 item
: probes
[0].item
.clone(),
1144 import_id
: probes
[0].import_id
,
1151 ///////////////////////////////////////////////////////////////////////////
1153 fn has_applicable_self(&self, item
: &ty
::ImplOrTraitItem
) -> bool
{
1154 // "fast track" -- check for usage of sugar
1156 ty
::ImplOrTraitItem
::MethodTraitItem(ref method
) => {
1157 match method
.explicit_self
{
1158 ty
::ExplicitSelfCategory
::Static
=> self.mode
== Mode
::Path
,
1159 ty
::ExplicitSelfCategory
::ByValue
|
1160 ty
::ExplicitSelfCategory
::ByReference(..) |
1161 ty
::ExplicitSelfCategory
::ByBox
=> true,
1164 ty
::ImplOrTraitItem
::ConstTraitItem(..) => self.mode
== Mode
::Path
,
1167 // FIXME -- check for types that deref to `Self`,
1168 // like `Rc<Self>` and so on.
1170 // Note also that the current code will break if this type
1171 // includes any of the type parameters defined on the method
1172 // -- but this could be overcome.
1175 fn record_static_candidate(&mut self, source
: CandidateSource
) {
1176 self.static_candidates
.push(source
);
1179 fn xform_self_ty(&self,
1180 item
: &ty
::ImplOrTraitItem
<'tcx
>,
1182 substs
: &Substs
<'tcx
>)
1184 match item
.as_opt_method() {
1185 Some(ref method
) => self.xform_method_self_ty(method
, impl_ty
, substs
),
1190 fn xform_method_self_ty(&self,
1191 method
: &Rc
<ty
::Method
<'tcx
>>,
1193 substs
: &Substs
<'tcx
>)
1195 debug
!("xform_self_ty(impl_ty={:?}, self_ty={:?}, substs={:?})",
1197 method
.fty
.sig
.0.inputs
.get(0),
1200 assert
!(!substs
.has_escaping_regions());
1202 // It is possible for type parameters or early-bound lifetimes
1203 // to appear in the signature of `self`. The substitutions we
1204 // are given do not include type/lifetime parameters for the
1205 // method yet. So create fresh variables here for those too,
1206 // if there are any.
1207 assert_eq
!(substs
.types().count(),
1208 method
.generics
.parent_types
as usize);
1209 assert_eq
!(substs
.regions().count(),
1210 method
.generics
.parent_regions
as usize);
1212 if self.mode
== Mode
::Path
{
1216 // Erase any late-bound regions from the method and substitute
1217 // in the values from the substitution.
1218 let xform_self_ty
= method
.fty
.sig
.input(0);
1219 let xform_self_ty
= self.erase_late_bound_regions(&xform_self_ty
);
1221 if method
.generics
.types
.is_empty() && method
.generics
.regions
.is_empty() {
1222 xform_self_ty
.subst(self.tcx
, substs
)
1224 let substs
= Substs
::for_item(self.tcx
,
1227 let i
= def
.index
as usize;
1228 if i
< substs
.params().len() {
1231 // In general, during probe we erase regions. See
1232 // `impl_self_ty()` for an explanation.
1233 self.tcx
.mk_region(ty
::ReErased
)
1237 let i
= def
.index
as usize;
1238 if i
< substs
.params().len() {
1241 self.type_var_for_def(self.span
, def
, cur_substs
)
1244 xform_self_ty
.subst(self.tcx
, substs
)
1248 /// Get the type of an impl and generate substitutions with placeholders.
1249 fn impl_ty_and_substs(&self, impl_def_id
: DefId
) -> (Ty
<'tcx
>, &'tcx Substs
<'tcx
>) {
1250 let impl_ty
= self.tcx
.lookup_item_type(impl_def_id
).ty
;
1252 let substs
= Substs
::for_item(self.tcx
,
1254 |_
, _
| self.tcx
.mk_region(ty
::ReErased
),
1255 |_
, _
| self.next_ty_var());
1260 /// Replace late-bound-regions bound by `value` with `'static` using
1261 /// `ty::erase_late_bound_regions`.
1263 /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1264 /// method matching. It is reasonable during the probe phase because we don't consider region
1265 /// relationships at all. Therefore, we can just replace all the region variables with 'static
1266 /// rather than creating fresh region variables. This is nice for two reasons:
1268 /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1269 /// particular method call, it winds up creating fewer types overall, which helps for memory
1270 /// usage. (Admittedly, this is a rather small effect, though measureable.)
1272 /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1273 /// late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1274 /// regions with actual region variables as is proper, we'd have to ensure that the same
1275 /// region got replaced with the same variable, which requires a bit more coordination
1276 /// and/or tracking the substitution and
1278 fn erase_late_bound_regions
<T
>(&self, value
: &ty
::Binder
<T
>) -> T
1279 where T
: TypeFoldable
<'tcx
>
1281 self.tcx
.erase_late_bound_regions(value
)
1284 /// Find item with name `item_name` defined in impl/trait `def_id`
1285 /// and return it, or `None`, if no such item was defined there.
1286 fn impl_or_trait_item(&self, def_id
: DefId
) -> Option
<ty
::ImplOrTraitItem
<'tcx
>> {
1287 self.fcx
.impl_or_trait_item(def_id
, self.item_name
)
1291 impl<'tcx
> Candidate
<'tcx
> {
1292 fn to_unadjusted_pick(&self) -> Pick
<'tcx
> {
1294 item
: self.item
.clone(),
1295 kind
: match self.kind
{
1296 InherentImplCandidate(..) => InherentImplPick
,
1297 ExtensionImplCandidate(def_id
, ..) => ExtensionImplPick(def_id
),
1298 ObjectCandidate
=> ObjectPick
,
1299 TraitCandidate
=> TraitPick
,
1300 WhereClauseCandidate(ref trait_ref
) => {
1301 // Only trait derived from where-clauses should
1302 // appear here, so they should not contain any
1303 // inference variables or other artifacts. This
1304 // means they are safe to put into the
1305 // `WhereClausePick`.
1306 assert
!(!trait_ref
.substs().needs_infer());
1308 WhereClausePick(trait_ref
.clone())
1311 import_id
: self.import_id
,
1318 fn to_source(&self) -> CandidateSource
{
1320 InherentImplCandidate(..) => ImplSource(self.item
.container().id()),
1321 ExtensionImplCandidate(def_id
, ..) => ImplSource(def_id
),
1324 WhereClauseCandidate(_
) => TraitSource(self.item
.container().id()),