]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/check/method/probe.rs
New upstream version 1.14.0+dfsg1
[rustc.git] / src / librustc_typeck / check / method / probe.rs
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.
4 //
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.
10
11 use super::MethodError;
12 use super::NoMatchData;
13 use super::{CandidateSource, ImplSource, TraitSource};
14 use super::suggest;
15
16 use check::FnCtxt;
17 use hir::def_id::DefId;
18 use hir::def::Def;
19 use rustc::ty::subst::{Subst, Substs};
20 use rustc::traits;
21 use rustc::ty::{self, Ty, ToPolyTraitRef, TraitRef, TypeFoldable};
22 use rustc::infer::{InferOk, TypeOrigin};
23 use rustc::util::nodemap::FnvHashSet;
24 use syntax::ast;
25 use syntax_pos::{Span, DUMMY_SP};
26 use rustc::hir;
27 use std::mem;
28 use std::ops::Deref;
29 use std::rc::Rc;
30
31 use self::CandidateKind::*;
32 pub use self::PickKind::*;
33
34 struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
35 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
36 span: Span,
37 mode: Mode,
38 item_name: ast::Name,
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>,
45
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>,
49
50 /// Some(candidate) if there is a private candidate
51 private_candidate: Option<Def>,
52
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>>,
56 }
57
58 impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
59 type Target = FnCtxt<'a, 'gcx, 'tcx>;
60 fn deref(&self) -> &Self::Target {
61 &self.fcx
62 }
63 }
64
65 #[derive(Debug)]
66 struct CandidateStep<'tcx> {
67 self_ty: Ty<'tcx>,
68 autoderefs: usize,
69 unsize: bool,
70 }
71
72 #[derive(Debug)]
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>,
78 }
79
80 #[derive(Debug)]
81 enum CandidateKind<'tcx> {
82 InherentImplCandidate(&'tcx Substs<'tcx>,
83 // Normalize obligations
84 Vec<traits::PredicateObligation<'tcx>>),
85 ExtensionImplCandidate(// Impl
86 DefId,
87 &'tcx Substs<'tcx>,
88 // Normalize obligations
89 Vec<traits::PredicateObligation<'tcx>>),
90 ObjectCandidate,
91 TraitCandidate,
92 WhereClauseCandidate(// Trait
93 ty::PolyTraitRef<'tcx>),
94 }
95
96 #[derive(Debug)]
97 pub struct Pick<'tcx> {
98 pub item: ty::ImplOrTraitItem<'tcx>,
99 pub kind: PickKind<'tcx>,
100 pub import_id: Option<ast::NodeId>,
101
102 // Indicates that the source expression should be autoderef'd N times
103 //
104 // A = expr | *expr | **expr | ...
105 pub autoderefs: usize,
106
107 // Indicates that an autoref is applied after the optional autoderefs
108 //
109 // B = A | &A | &mut A
110 pub autoref: Option<hir::Mutability>,
111
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.
115 //
116 // C = B | unsize(B)
117 pub unsize: Option<Ty<'tcx>>,
118 }
119
120 #[derive(Clone,Debug)]
121 pub enum PickKind<'tcx> {
122 InherentImplPick,
123 ExtensionImplPick(// Impl
124 DefId),
125 ObjectPick,
126 TraitPick,
127 WhereClausePick(// Trait
128 ty::PolyTraitRef<'tcx>),
129 }
130
131 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
132
133 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
134 pub enum Mode {
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.
138 MethodCall,
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.
142 Path,
143 }
144
145 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
146 pub fn probe_method(&self,
147 span: Span,
148 mode: Mode,
149 item_name: ast::Name,
150 self_ty: Ty<'tcx>,
151 scope_expr_id: ast::NodeId)
152 -> PickResult<'tcx> {
153 debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
154 self_ty,
155 item_name,
156 scope_expr_id);
157
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,
168 None => {
169 return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
170 Vec::new(),
171 Vec::new(),
172 mode)))
173 }
174 }
175 } else {
176 vec![CandidateStep {
177 self_ty: self_ty,
178 autoderefs: 0,
179 unsize: false,
180 }]
181 };
182
183 // Create a list of simplified self types, if we can.
184 let mut simplified_steps = Vec::new();
185 for step in &steps {
186 match ty::fast_reject::simplify_type(self.tcx, step.self_ty, true) {
187 None => {
188 break;
189 }
190 Some(simplified_type) => {
191 simplified_steps.push(simplified_type);
192 }
193 }
194 }
195 let opt_simplified_steps = if simplified_steps.len() < steps.len() {
196 None // failed to convert at least one of the steps
197 } else {
198 Some(simplified_steps)
199 };
200
201 debug!("ProbeContext: steps for self_ty={:?} are {:?}",
202 self_ty,
203 steps);
204
205 // this creates one big transaction so that all type variables etc
206 // that we create during the probe process are removed later
207 self.probe(|_| {
208 let mut probe_cx =
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)?;
212 probe_cx.pick()
213 })
214 }
215
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
218
219 let mut autoderef = self.autoderef(span, self_ty);
220 let mut steps: Vec<_> = autoderef.by_ref()
221 .map(|(ty, d)| {
222 CandidateStep {
223 self_ty: ty,
224 autoderefs: d,
225 unsize: false,
226 }
227 })
228 .collect();
229
230 let final_ty = autoderef.unambiguous_final_ty();
231 match final_ty.sty {
232 ty::TyArray(elem_ty, _) => {
233 let dereferences = steps.len() - 1;
234
235 steps.push(CandidateStep {
236 self_ty: self.tcx.mk_slice(elem_ty),
237 autoderefs: dereferences,
238 unsize: true,
239 });
240 }
241 ty::TyError => return None,
242 _ => (),
243 }
244
245 debug!("create_steps: steps={:?}", steps);
246
247 Some(steps)
248 }
249 }
250
251 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
252 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
253 span: Span,
254 mode: Mode,
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> {
259 ProbeContext {
260 fcx: fcx,
261 span: span,
262 mode: mode,
263 item_name: item_name,
264 inherent_candidates: Vec::new(),
265 extension_candidates: Vec::new(),
266 impl_dups: FnvHashSet(),
267 import_id: None,
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(),
273 }
274 }
275
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;
282 }
283
284 ///////////////////////////////////////////////////////////////////////////
285 // CANDIDATE ASSEMBLY
286
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);
291 }
292 }
293
294 fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
295 debug!("assemble_probe: self_ty={:?}", self_ty);
296
297 match self_ty.sty {
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());
301 }
302 ty::TyAdt(def, _) => {
303 self.assemble_inherent_impl_candidates_for_type(def.did);
304 }
305 ty::TyBox(_) => {
306 if let Some(box_did) = self.tcx.lang_items.owned_box() {
307 self.assemble_inherent_impl_candidates_for_type(box_did);
308 }
309 }
310 ty::TyParam(p) => {
311 self.assemble_inherent_candidates_from_param(self_ty, p);
312 }
313 ty::TyChar => {
314 let lang_def_id = self.tcx.lang_items.char_impl();
315 self.assemble_inherent_impl_for_primitive(lang_def_id);
316 }
317 ty::TyStr => {
318 let lang_def_id = self.tcx.lang_items.str_impl();
319 self.assemble_inherent_impl_for_primitive(lang_def_id);
320 }
321 ty::TySlice(_) => {
322 let lang_def_id = self.tcx.lang_items.slice_impl();
323 self.assemble_inherent_impl_for_primitive(lang_def_id);
324 }
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);
328 }
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);
332 }
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);
336 }
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);
340 }
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);
344 }
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);
348 }
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);
352 }
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);
356 }
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);
360 }
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);
364 }
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);
368 }
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);
372 }
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);
376 }
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);
380 }
381 _ => {}
382 }
383 }
384
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);
388
389 self.assemble_inherent_impl_probe(impl_def_id);
390 }
391 }
392
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);
397
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);
401 }
402 }
403 }
404
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
408 }
409
410 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
411
412 let item = match self.impl_or_trait_item(impl_def_id) {
413 Some(m) => m,
414 None => {
415 return;
416 } // No method with correct name on this impl
417 };
418
419 if !self.has_applicable_self(&item) {
420 // No receiver declared. Not a candidate.
421 return self.record_static_candidate(ImplSource(impl_def_id));
422 }
423
424 if !item.vis().is_accessible_from(self.body_id, &self.tcx.map) {
425 self.private_candidate = Some(item.def());
426 return;
427 }
428
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);
431
432 // Determine the receiver type that the method itself expects.
433 let xform_self_ty = self.xform_self_ty(&item, impl_ty, impl_substs);
434
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 = {:?}",
442 xform_self_ty);
443
444 self.inherent_candidates.push(Candidate {
445 xform_self_ty: xform_self_ty,
446 item: item,
447 kind: InherentImplCandidate(impl_substs, obligations),
448 import_id: self.import_id,
449 });
450 }
451
452 fn assemble_inherent_candidates_from_object(&mut self,
453 self_ty: Ty<'tcx>,
454 principal: ty::PolyExistentialTraitRef<'tcx>) {
455 debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
456 self_ty);
457
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);
468
469 let xform_self_ty =
470 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
471
472 this.inherent_candidates.push(Candidate {
473 xform_self_ty: xform_self_ty,
474 item: item,
475 kind: ObjectCandidate,
476 import_id: this.import_id,
477 });
478 });
479 }
480
481 fn assemble_inherent_candidates_from_param(&mut self,
482 _rcvr_ty: Ty<'tcx>,
483 param_ty: ty::ParamTy) {
484 // FIXME -- Do we want to commit to this behavior for param bounds?
485
486 let bounds: Vec<_> = self.parameter_environment
487 .caller_bounds
488 .iter()
489 .filter_map(|predicate| {
490 match *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())
495 }
496 _ => None,
497 }
498 }
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,
506 }
507 })
508 .collect();
509
510 self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
511 let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
512
513 let xform_self_ty = this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
514
515 if let Some(ref m) = item.as_opt_method() {
516 debug!("found match: trait_ref={:?} substs={:?} m={:?}",
517 trait_ref,
518 trait_ref.substs,
519 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());
524 }
525
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());
532
533 this.inherent_candidates.push(Candidate {
534 xform_self_ty: xform_self_ty,
535 item: item,
536 kind: WhereClauseCandidate(poly_trait_ref),
537 import_id: this.import_id,
538 });
539 });
540 }
541
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>)
548 {
549 debug!("elaborate_bounds(bounds={:?})", bounds);
550
551 let tcx = self.tcx;
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()) {
554 Some(v) => v,
555 None => {
556 continue;
557 }
558 };
559
560 if !self.has_applicable_self(&item) {
561 self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
562 } else {
563 mk_cand(self, bound_trait_ref, item);
564 }
565 }
566 }
567
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;
580 result?;
581 }
582 }
583 }
584 Ok(())
585 }
586
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)?;
592 }
593 }
594 Ok(())
595 }
596
597 fn assemble_extension_candidates_for_trait(&mut self,
598 trait_def_id: DefId)
599 -> Result<(), MethodError<'tcx>> {
600 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
601 trait_def_id);
602
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 {
608 Some(i) => i,
609 None => {
610 return Ok(());
611 }
612 };
613
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));
618 return Ok(());
619 }
620
621 self.assemble_extension_candidates_for_trait_impls(trait_def_id, item.clone());
622
623 self.assemble_closure_candidates(trait_def_id, item.clone())?;
624
625 self.assemble_projection_candidates(trait_def_id, item.clone());
626
627 self.assemble_where_clause_candidates(trait_def_id, item.clone());
628
629 Ok(())
630 }
631
632 fn assemble_extension_candidates_for_trait_impls(&mut self,
633 trait_def_id: DefId,
634 item: ty::ImplOrTraitItem<'tcx>) {
635 let trait_def = self.tcx.lookup_trait_def(trait_def_id);
636
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={:?} \
640 impl_def_id={:?}",
641 trait_def_id,
642 impl_def_id);
643
644 if !self.impl_can_possibly_match(impl_def_id) {
645 return;
646 }
647
648 let (_, impl_substs) = self.impl_ty_and_substs(impl_def_id);
649
650 debug!("impl_substs={:?}", impl_substs);
651
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);
655
656 debug!("impl_trait_ref={:?}", impl_trait_ref);
657
658 // Determine the receiver type that the method itself expects.
659 let xform_self_ty =
660 self.xform_self_ty(&item, impl_trait_ref.self_ty(), impl_trait_ref.substs);
661
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
664 // is over.
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);
669
670 debug!("xform_self_ty={:?}", xform_self_ty);
671
672 self.extension_candidates.push(Candidate {
673 xform_self_ty: xform_self_ty,
674 item: item.clone(),
675 kind: ExtensionImplCandidate(impl_def_id, impl_substs, obligations),
676 import_id: self.import_id,
677 });
678 });
679 }
680
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,
684 None => {
685 return true;
686 }
687 };
688
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,
693 None => {
694 return true;
695 }
696 };
697
698 simplified_steps.contains(&impl_simplified_type)
699 }
700
701 fn assemble_closure_candidates(&mut self,
702 trait_def_id: DefId,
703 item: ty::ImplOrTraitItem<'tcx>)
704 -> Result<(), MethodError<'tcx>> {
705 // Check if this is one of the Fn,FnMut,FnOnce traits.
706 let tcx = self.tcx;
707 let kind = if Some(trait_def_id) == tcx.lang_items.fn_trait() {
708 ty::ClosureKind::Fn
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
713 } else {
714 return Ok(());
715 };
716
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,
723 _ => continue,
724 };
725
726 let closure_kinds = &self.tables.borrow().closure_kinds;
727 let closure_kind = match closure_kinds.get(&closure_def_id) {
728 Some(&k) => k,
729 None => {
730 return Err(MethodError::ClosureAmbiguity(trait_def_id));
731 }
732 };
733
734 // this closure doesn't implement the right kind of `Fn` trait
735 if !closure_kind.extends(kind) {
736 continue;
737 }
738
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,
744 trait_def_id,
745 |def, _| self.region_var_for_def(self.span, def),
746 |def, substs| {
747 if def.index == 0 {
748 step.self_ty
749 } else {
750 self.type_var_for_def(self.span, def, substs)
751 }
752 });
753
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,
757 item: item.clone(),
758 kind: TraitCandidate,
759 import_id: self.import_id,
760 });
761 }
762
763 Ok(())
764 }
765
766 fn assemble_projection_candidates(&mut self,
767 trait_def_id: DefId,
768 item: ty::ImplOrTraitItem<'tcx>) {
769 debug!("assemble_projection_candidates(\
770 trait_def_id={:?}, \
771 item={:?})",
772 trait_def_id,
773 item);
774
775 for step in self.steps.iter() {
776 debug!("assemble_projection_candidates: step={:?}", step);
777
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),
781 _ => continue,
782 };
783
784 debug!("assemble_projection_candidates: def_id={:?} substs={:?}",
785 def_id,
786 substs);
787
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={:?}",
792 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);
797
798 debug!("assemble_projection_candidates: def_id={:?} substs={:?} bound={:?}",
799 def_id,
800 substs,
801 bound);
802
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);
805
806 debug!("assemble_projection_candidates: bound={:?} xform_self_ty={:?}",
807 bound,
808 xform_self_ty);
809
810 self.extension_candidates.push(Candidate {
811 xform_self_ty: xform_self_ty,
812 item: item.clone(),
813 kind: TraitCandidate,
814 import_id: self.import_id,
815 });
816 }
817 }
818 }
819 }
820
821 fn assemble_where_clause_candidates(&mut self,
822 trait_def_id: DefId,
823 item: ty::ImplOrTraitItem<'tcx>) {
824 debug!("assemble_where_clause_candidates(trait_def_id={:?})",
825 trait_def_id);
826
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);
833
834 debug!("assemble_where_clause_candidates: bound={:?} xform_self_ty={:?}",
835 bound,
836 xform_self_ty);
837
838 self.extension_candidates.push(Candidate {
839 xform_self_ty: xform_self_ty,
840 item: item.clone(),
841 kind: WhereClauseCandidate(poly_bound),
842 import_id: self.import_id,
843 });
844 }
845 }
846
847 ///////////////////////////////////////////////////////////////////////////
848 // THE ACTUAL SEARCH
849
850 fn pick(mut self) -> PickResult<'tcx> {
851 if let Some(r) = self.pick_core() {
852 return r;
853 }
854
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![]);
858
859 // things failed, so lets look at all traits, for diagnostic purposes now:
860 self.reset();
861
862 let span = self.span;
863 let tcx = self.tcx;
864
865 self.assemble_extension_candidates_for_all_traits()?;
866
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))) => {
870 v.into_iter()
871 .map(|source| {
872 match source {
873 TraitSource(id) => id,
874 ImplSource(impl_id) => {
875 match tcx.trait_id_of_impl(impl_id) {
876 Some(id) => id,
877 None => {
878 span_bug!(span,
879 "found inherent method when looking at traits")
880 }
881 }
882 }
883 }
884 })
885 .collect()
886 }
887 Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
888 assert!(others.is_empty());
889 vec![]
890 }
891 Some(Err(MethodError::ClosureAmbiguity(..))) => {
892 // this error only occurs when assembling candidates
893 span_bug!(span, "encountered ClosureAmbiguity from pick_core");
894 }
895 _ => vec![],
896 };
897
898 if let Some(def) = private_candidate {
899 return Err(MethodError::PrivateMatch(def));
900 }
901
902 Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
903 unsatisfied_predicates,
904 out_of_scope_traits,
905 self.mode)))
906 }
907
908 fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
909 let steps = self.steps.clone();
910
911 // find the first step that works
912 steps.iter().filter_map(|step| self.pick_step(step)).next()
913 }
914
915 fn pick_step(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
916 debug!("pick_step: step={:?}", step);
917
918 if step.self_ty.references_error() {
919 return None;
920 }
921
922 if let Some(result) = self.pick_by_value_method(step) {
923 return Some(result);
924 }
925
926 self.pick_autorefd_method(step)
927 }
928
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.
937
938 if step.unsize {
939 return None;
940 }
941
942 self.pick_method(step.self_ty).map(|r| {
943 r.map(|mut pick| {
944 pick.autoderefs = step.autoderefs;
945
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);
950 }
951
952 pick
953 })
954 })
955 }
956
957 fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
958 let tcx = self.tcx;
959
960 // In general, during probing we erase regions. See
961 // `impl_self_ty()` for an explanation.
962 let region = tcx.mk_region(ty::ReErased);
963
964 // Search through mutabilities in order to find one where pick works:
965 [hir::MutImmutable, hir::MutMutable]
966 .iter()
967 .filter_map(|&m| {
968 let autoref_ty = tcx.mk_ref(region,
969 ty::TypeAndMut {
970 ty: step.self_ty,
971 mutbl: m,
972 });
973 self.pick_method(autoref_ty).map(|r| {
974 r.map(|mut pick| {
975 pick.autoderefs = step.autoderefs;
976 pick.autoref = Some(m);
977 pick.unsize = if step.unsize {
978 Some(step.self_ty)
979 } else {
980 None
981 };
982 pick
983 })
984 })
985 })
986 .nth(0)
987 }
988
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));
991
992 let mut possibly_unsatisfied_predicates = Vec::new();
993
994 debug!("searching inherent candidates");
995 if let Some(pick) = self.consider_candidates(self_ty,
996 &self.inherent_candidates,
997 &mut possibly_unsatisfied_predicates) {
998 return Some(pick);
999 }
1000
1001 debug!("searching extension candidates");
1002 let res = self.consider_candidates(self_ty,
1003 &self.extension_candidates,
1004 &mut possibly_unsatisfied_predicates);
1005 if let None = res {
1006 self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1007 }
1008 res
1009 }
1010
1011 fn consider_candidates(&self,
1012 self_ty: Ty<'tcx>,
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))
1018 .collect();
1019
1020 debug!("applicable_candidates: {:?}", applicable_candidates);
1021
1022 if applicable_candidates.len() > 1 {
1023 match self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1024 Some(pick) => {
1025 return Some(Ok(pick));
1026 }
1027 None => {}
1028 }
1029 }
1030
1031 if applicable_candidates.len() > 1 {
1032 let sources = probes.iter().map(|p| p.to_source()).collect();
1033 return Some(Err(MethodError::Ambiguity(sources)));
1034 }
1035
1036 applicable_candidates.pop().map(|probe| Ok(probe.to_unadjusted_pick()))
1037 }
1038
1039 fn consider_probe(&self,
1040 self_ty: Ty<'tcx>,
1041 probe: &Candidate<'tcx>,
1042 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1043 -> bool {
1044 debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
1045
1046 self.probe(|_| {
1047 // First check that the self type can be related.
1048 match self.sub_types(false,
1049 TypeOrigin::Misc(DUMMY_SP),
1050 self_ty,
1051 probe.xform_self_ty) {
1052 Ok(InferOk { obligations, .. }) => {
1053 // FIXME(#32730) propagate obligations
1054 assert!(obligations.is_empty())
1055 }
1056 Err(_) => {
1057 debug!("--> cannot relate self-types");
1058 return false;
1059 }
1060 }
1061
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)
1069 }
1070
1071 ExtensionImplCandidate(impl_def_id, ref substs, ref ref_obligations) => {
1072 (impl_def_id, substs, ref_obligations)
1073 }
1074
1075 ObjectCandidate |
1076 TraitCandidate |
1077 WhereClauseCandidate(..) => {
1078 // These have no additional conditions to check.
1079 return true;
1080 }
1081 };
1082
1083 let selcx = &mut traits::SelectionContext::new(self);
1084 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1085
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);
1091
1092 // Convert the bounds into obligations.
1093 let obligations = traits::predicates_for_generics(cause.clone(), &impl_bounds);
1094 debug!("impl_obligations={:?}", obligations);
1095
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) {
1102 all_true = false;
1103 if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1104 possibly_unsatisfied_predicates.push(pred.0.trait_ref);
1105 }
1106 }
1107 }
1108 all_true
1109 })
1110 }
1111
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.
1118 ///
1119 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1120 ///
1121 /// ```
1122 /// trait Foo { ... }
1123 /// impl Foo for Vec<int> { ... }
1124 /// impl Foo for Vec<usize> { ... }
1125 /// ```
1126 ///
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();
1132 match container {
1133 ty::TraitContainer(_) => {}
1134 ty::ImplContainer(_) => return None,
1135 }
1136 if probes[1..].iter().any(|p| p.item.container() != container) {
1137 return None;
1138 }
1139
1140 // If so, just use this trait and call it a day.
1141 Some(Pick {
1142 item: probes[0].item.clone(),
1143 kind: TraitPick,
1144 import_id: probes[0].import_id,
1145 autoderefs: 0,
1146 autoref: None,
1147 unsize: None,
1148 })
1149 }
1150
1151 ///////////////////////////////////////////////////////////////////////////
1152 // MISCELLANY
1153 fn has_applicable_self(&self, item: &ty::ImplOrTraitItem) -> bool {
1154 // "fast track" -- check for usage of sugar
1155 match *item {
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,
1162 }
1163 }
1164 ty::ImplOrTraitItem::ConstTraitItem(..) => self.mode == Mode::Path,
1165 _ => false,
1166 }
1167 // FIXME -- check for types that deref to `Self`,
1168 // like `Rc<Self>` and so on.
1169 //
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.
1173 }
1174
1175 fn record_static_candidate(&mut self, source: CandidateSource) {
1176 self.static_candidates.push(source);
1177 }
1178
1179 fn xform_self_ty(&self,
1180 item: &ty::ImplOrTraitItem<'tcx>,
1181 impl_ty: Ty<'tcx>,
1182 substs: &Substs<'tcx>)
1183 -> Ty<'tcx> {
1184 match item.as_opt_method() {
1185 Some(ref method) => self.xform_method_self_ty(method, impl_ty, substs),
1186 None => impl_ty,
1187 }
1188 }
1189
1190 fn xform_method_self_ty(&self,
1191 method: &Rc<ty::Method<'tcx>>,
1192 impl_ty: Ty<'tcx>,
1193 substs: &Substs<'tcx>)
1194 -> Ty<'tcx> {
1195 debug!("xform_self_ty(impl_ty={:?}, self_ty={:?}, substs={:?})",
1196 impl_ty,
1197 method.fty.sig.0.inputs.get(0),
1198 substs);
1199
1200 assert!(!substs.has_escaping_regions());
1201
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);
1211
1212 if self.mode == Mode::Path {
1213 return impl_ty;
1214 }
1215
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);
1220
1221 if method.generics.types.is_empty() && method.generics.regions.is_empty() {
1222 xform_self_ty.subst(self.tcx, substs)
1223 } else {
1224 let substs = Substs::for_item(self.tcx,
1225 method.def_id,
1226 |def, _| {
1227 let i = def.index as usize;
1228 if i < substs.params().len() {
1229 substs.region_at(i)
1230 } else {
1231 // In general, during probe we erase regions. See
1232 // `impl_self_ty()` for an explanation.
1233 self.tcx.mk_region(ty::ReErased)
1234 }
1235 },
1236 |def, cur_substs| {
1237 let i = def.index as usize;
1238 if i < substs.params().len() {
1239 substs.type_at(i)
1240 } else {
1241 self.type_var_for_def(self.span, def, cur_substs)
1242 }
1243 });
1244 xform_self_ty.subst(self.tcx, substs)
1245 }
1246 }
1247
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;
1251
1252 let substs = Substs::for_item(self.tcx,
1253 impl_def_id,
1254 |_, _| self.tcx.mk_region(ty::ReErased),
1255 |_, _| self.next_ty_var());
1256
1257 (impl_ty, substs)
1258 }
1259
1260 /// Replace late-bound-regions bound by `value` with `'static` using
1261 /// `ty::erase_late_bound_regions`.
1262 ///
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:
1267 ///
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.)
1271 ///
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
1277 /// so forth.
1278 fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1279 where T: TypeFoldable<'tcx>
1280 {
1281 self.tcx.erase_late_bound_regions(value)
1282 }
1283
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)
1288 }
1289 }
1290
1291 impl<'tcx> Candidate<'tcx> {
1292 fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1293 Pick {
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());
1307
1308 WhereClausePick(trait_ref.clone())
1309 }
1310 },
1311 import_id: self.import_id,
1312 autoderefs: 0,
1313 autoref: None,
1314 unsize: None,
1315 }
1316 }
1317
1318 fn to_source(&self) -> CandidateSource {
1319 match self.kind {
1320 InherentImplCandidate(..) => ImplSource(self.item.container().id()),
1321 ExtensionImplCandidate(def_id, ..) => ImplSource(def_id),
1322 ObjectCandidate |
1323 TraitCandidate |
1324 WhereClauseCandidate(_) => TraitSource(self.item.container().id()),
1325 }
1326 }
1327 }