]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/check/method/probe.rs
New upstream version 1.12.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;
20 use rustc::ty::subst::Subst;
21 use rustc::traits;
22 use rustc::ty::{self, Ty, ToPolyTraitRef, TraitRef, TypeFoldable};
23 use rustc::infer::{InferOk, TypeOrigin};
24 use syntax::ast;
25 use syntax_pos::{Span, DUMMY_SP};
26 use rustc::hir;
27 use std::collections::HashSet;
28 use std::mem;
29 use std::ops::Deref;
30 use std::rc::Rc;
31
32 use self::CandidateKind::*;
33 pub use self::PickKind::*;
34
35 struct ProbeContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
36 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
37 span: Span,
38 mode: Mode,
39 item_name: ast::Name,
40 steps: Rc<Vec<CandidateStep<'tcx>>>,
41 opt_simplified_steps: Option<Vec<ty::fast_reject::SimplifiedType>>,
42 inherent_candidates: Vec<Candidate<'tcx>>,
43 extension_candidates: Vec<Candidate<'tcx>>,
44 impl_dups: HashSet<DefId>,
45 import_id: Option<ast::NodeId>,
46
47 /// Collects near misses when the candidate functions are missing a `self` keyword and is only
48 /// used for error reporting
49 static_candidates: Vec<CandidateSource>,
50
51 /// Some(candidate) if there is a private candidate
52 private_candidate: Option<Def>,
53
54 /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
55 /// for error reporting
56 unsatisfied_predicates: Vec<TraitRef<'tcx>>
57 }
58
59 impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
60 type Target = FnCtxt<'a, 'gcx, 'tcx>;
61 fn deref(&self) -> &Self::Target {
62 &self.fcx
63 }
64 }
65
66 #[derive(Debug)]
67 struct CandidateStep<'tcx> {
68 self_ty: Ty<'tcx>,
69 autoderefs: usize,
70 unsize: bool
71 }
72
73 #[derive(Debug)]
74 struct Candidate<'tcx> {
75 xform_self_ty: Ty<'tcx>,
76 item: ty::ImplOrTraitItem<'tcx>,
77 kind: CandidateKind<'tcx>,
78 import_id: Option<ast::NodeId>,
79 }
80
81 #[derive(Debug)]
82 enum CandidateKind<'tcx> {
83 InherentImplCandidate(subst::Substs<'tcx>,
84 /* Normalize obligations */ Vec<traits::PredicateObligation<'tcx>>),
85 ExtensionImplCandidate(/* Impl */ DefId, subst::Substs<'tcx>,
86 /* Normalize obligations */ Vec<traits::PredicateObligation<'tcx>>),
87 ObjectCandidate,
88 TraitCandidate,
89 WhereClauseCandidate(/* Trait */ ty::PolyTraitRef<'tcx>),
90 }
91
92 #[derive(Debug)]
93 pub struct Pick<'tcx> {
94 pub item: ty::ImplOrTraitItem<'tcx>,
95 pub kind: PickKind<'tcx>,
96 pub import_id: Option<ast::NodeId>,
97
98 // Indicates that the source expression should be autoderef'd N times
99 //
100 // A = expr | *expr | **expr | ...
101 pub autoderefs: usize,
102
103 // Indicates that an autoref is applied after the optional autoderefs
104 //
105 // B = A | &A | &mut A
106 pub autoref: Option<hir::Mutability>,
107
108 // Indicates that the source expression should be "unsized" to a
109 // target type. This should probably eventually go away in favor
110 // of just coercing method receivers.
111 //
112 // C = B | unsize(B)
113 pub unsize: Option<Ty<'tcx>>,
114 }
115
116 #[derive(Clone,Debug)]
117 pub enum PickKind<'tcx> {
118 InherentImplPick,
119 ExtensionImplPick(/* Impl */ DefId),
120 ObjectPick,
121 TraitPick,
122 WhereClausePick(/* Trait */ ty::PolyTraitRef<'tcx>),
123 }
124
125 pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
126
127 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
128 pub enum Mode {
129 // An expression of the form `receiver.method_name(...)`.
130 // Autoderefs are performed on `receiver`, lookup is done based on the
131 // `self` argument of the method, and static methods aren't considered.
132 MethodCall,
133 // An expression of the form `Type::item` or `<T>::item`.
134 // No autoderefs are performed, lookup is done based on the type each
135 // implementation is for, and static methods are included.
136 Path
137 }
138
139 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
140 pub fn probe_method(&self,
141 span: Span,
142 mode: Mode,
143 item_name: ast::Name,
144 self_ty: Ty<'tcx>,
145 scope_expr_id: ast::NodeId)
146 -> PickResult<'tcx>
147 {
148 debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
149 self_ty,
150 item_name,
151 scope_expr_id);
152
153 // FIXME(#18741) -- right now, creating the steps involves evaluating the
154 // `*` operator, which registers obligations that then escape into
155 // the global fulfillment context and thus has global
156 // side-effects. This is a bit of a pain to refactor. So just let
157 // it ride, although it's really not great, and in fact could I
158 // think cause spurious errors. Really though this part should
159 // take place in the `self.probe` below.
160 let steps = if mode == Mode::MethodCall {
161 match self.create_steps(span, self_ty) {
162 Some(steps) => steps,
163 None =>return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(), Vec::new(),
164 Vec::new(), mode))),
165 }
166 } else {
167 vec![CandidateStep {
168 self_ty: self_ty,
169 autoderefs: 0,
170 unsize: false
171 }]
172 };
173
174 // Create a list of simplified self types, if we can.
175 let mut simplified_steps = Vec::new();
176 for step in &steps {
177 match ty::fast_reject::simplify_type(self.tcx, step.self_ty, true) {
178 None => { break; }
179 Some(simplified_type) => { simplified_steps.push(simplified_type); }
180 }
181 }
182 let opt_simplified_steps =
183 if simplified_steps.len() < steps.len() {
184 None // failed to convert at least one of the steps
185 } else {
186 Some(simplified_steps)
187 };
188
189 debug!("ProbeContext: steps for self_ty={:?} are {:?}",
190 self_ty,
191 steps);
192
193 // this creates one big transaction so that all type variables etc
194 // that we create during the probe process are removed later
195 self.probe(|_| {
196 let mut probe_cx = ProbeContext::new(self,
197 span,
198 mode,
199 item_name,
200 steps,
201 opt_simplified_steps);
202 probe_cx.assemble_inherent_candidates();
203 probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?;
204 probe_cx.pick()
205 })
206 }
207
208 fn create_steps(&self,
209 span: Span,
210 self_ty: Ty<'tcx>)
211 -> Option<Vec<CandidateStep<'tcx>>>
212 {
213 // FIXME: we don't need to create the entire steps in one pass
214
215 let mut autoderef = self.autoderef(span, self_ty);
216 let mut steps: Vec<_> = autoderef.by_ref().map(|(ty, d)| CandidateStep {
217 self_ty: ty,
218 autoderefs: d,
219 unsize: false
220 }).collect();
221
222 let final_ty = autoderef.unambiguous_final_ty();
223 match final_ty.sty {
224 ty::TyArray(elem_ty, _) => {
225 let dereferences = steps.len() - 1;
226
227 steps.push(CandidateStep {
228 self_ty: self.tcx.mk_slice(elem_ty),
229 autoderefs: dereferences,
230 unsize: true
231 });
232 }
233 ty::TyError => return None,
234 _ => (),
235 }
236
237 debug!("create_steps: steps={:?}", steps);
238
239 Some(steps)
240 }
241 }
242
243 impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
244 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
245 span: Span,
246 mode: Mode,
247 item_name: ast::Name,
248 steps: Vec<CandidateStep<'tcx>>,
249 opt_simplified_steps: Option<Vec<ty::fast_reject::SimplifiedType>>)
250 -> ProbeContext<'a, 'gcx, 'tcx>
251 {
252 ProbeContext {
253 fcx: fcx,
254 span: span,
255 mode: mode,
256 item_name: item_name,
257 inherent_candidates: Vec::new(),
258 extension_candidates: Vec::new(),
259 impl_dups: HashSet::new(),
260 import_id: None,
261 steps: Rc::new(steps),
262 opt_simplified_steps: opt_simplified_steps,
263 static_candidates: Vec::new(),
264 private_candidate: None,
265 unsatisfied_predicates: Vec::new(),
266 }
267 }
268
269 fn reset(&mut self) {
270 self.inherent_candidates.clear();
271 self.extension_candidates.clear();
272 self.impl_dups.clear();
273 self.static_candidates.clear();
274 self.private_candidate = None;
275 }
276
277 ///////////////////////////////////////////////////////////////////////////
278 // CANDIDATE ASSEMBLY
279
280 fn assemble_inherent_candidates(&mut self) {
281 let steps = self.steps.clone();
282 for step in steps.iter() {
283 self.assemble_probe(step.self_ty);
284 }
285 }
286
287 fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
288 debug!("assemble_probe: self_ty={:?}",
289 self_ty);
290
291 match self_ty.sty {
292 ty::TyTrait(box ref data) => {
293 self.assemble_inherent_candidates_from_object(self_ty, data);
294 self.assemble_inherent_impl_candidates_for_type(data.principal_def_id());
295 }
296 ty::TyEnum(def, _) |
297 ty::TyStruct(def, _) => {
298 self.assemble_inherent_impl_candidates_for_type(def.did);
299 }
300 ty::TyBox(_) => {
301 if let Some(box_did) = self.tcx.lang_items.owned_box() {
302 self.assemble_inherent_impl_candidates_for_type(box_did);
303 }
304 }
305 ty::TyParam(p) => {
306 self.assemble_inherent_candidates_from_param(self_ty, p);
307 }
308 ty::TyChar => {
309 let lang_def_id = self.tcx.lang_items.char_impl();
310 self.assemble_inherent_impl_for_primitive(lang_def_id);
311 }
312 ty::TyStr => {
313 let lang_def_id = self.tcx.lang_items.str_impl();
314 self.assemble_inherent_impl_for_primitive(lang_def_id);
315 }
316 ty::TySlice(_) => {
317 let lang_def_id = self.tcx.lang_items.slice_impl();
318 self.assemble_inherent_impl_for_primitive(lang_def_id);
319 }
320 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
321 let lang_def_id = self.tcx.lang_items.const_ptr_impl();
322 self.assemble_inherent_impl_for_primitive(lang_def_id);
323 }
324 ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
325 let lang_def_id = self.tcx.lang_items.mut_ptr_impl();
326 self.assemble_inherent_impl_for_primitive(lang_def_id);
327 }
328 ty::TyInt(ast::IntTy::I8) => {
329 let lang_def_id = self.tcx.lang_items.i8_impl();
330 self.assemble_inherent_impl_for_primitive(lang_def_id);
331 }
332 ty::TyInt(ast::IntTy::I16) => {
333 let lang_def_id = self.tcx.lang_items.i16_impl();
334 self.assemble_inherent_impl_for_primitive(lang_def_id);
335 }
336 ty::TyInt(ast::IntTy::I32) => {
337 let lang_def_id = self.tcx.lang_items.i32_impl();
338 self.assemble_inherent_impl_for_primitive(lang_def_id);
339 }
340 ty::TyInt(ast::IntTy::I64) => {
341 let lang_def_id = self.tcx.lang_items.i64_impl();
342 self.assemble_inherent_impl_for_primitive(lang_def_id);
343 }
344 ty::TyInt(ast::IntTy::Is) => {
345 let lang_def_id = self.tcx.lang_items.isize_impl();
346 self.assemble_inherent_impl_for_primitive(lang_def_id);
347 }
348 ty::TyUint(ast::UintTy::U8) => {
349 let lang_def_id = self.tcx.lang_items.u8_impl();
350 self.assemble_inherent_impl_for_primitive(lang_def_id);
351 }
352 ty::TyUint(ast::UintTy::U16) => {
353 let lang_def_id = self.tcx.lang_items.u16_impl();
354 self.assemble_inherent_impl_for_primitive(lang_def_id);
355 }
356 ty::TyUint(ast::UintTy::U32) => {
357 let lang_def_id = self.tcx.lang_items.u32_impl();
358 self.assemble_inherent_impl_for_primitive(lang_def_id);
359 }
360 ty::TyUint(ast::UintTy::U64) => {
361 let lang_def_id = self.tcx.lang_items.u64_impl();
362 self.assemble_inherent_impl_for_primitive(lang_def_id);
363 }
364 ty::TyUint(ast::UintTy::Us) => {
365 let lang_def_id = self.tcx.lang_items.usize_impl();
366 self.assemble_inherent_impl_for_primitive(lang_def_id);
367 }
368 ty::TyFloat(ast::FloatTy::F32) => {
369 let lang_def_id = self.tcx.lang_items.f32_impl();
370 self.assemble_inherent_impl_for_primitive(lang_def_id);
371 }
372 ty::TyFloat(ast::FloatTy::F64) => {
373 let lang_def_id = self.tcx.lang_items.f64_impl();
374 self.assemble_inherent_impl_for_primitive(lang_def_id);
375 }
376 _ => {
377 }
378 }
379 }
380
381 fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
382 if let Some(impl_def_id) = lang_def_id {
383 self.tcx.populate_implementations_for_primitive_if_necessary(impl_def_id);
384
385 self.assemble_inherent_impl_probe(impl_def_id);
386 }
387 }
388
389 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
390 // Read the inherent implementation candidates for this type from the
391 // metadata if necessary.
392 self.tcx.populate_inherent_implementations_for_type_if_necessary(def_id);
393
394 if let Some(impl_infos) = self.tcx.inherent_impls.borrow().get(&def_id) {
395 for &impl_def_id in impl_infos.iter() {
396 self.assemble_inherent_impl_probe(impl_def_id);
397 }
398 }
399 }
400
401 fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
402 if !self.impl_dups.insert(impl_def_id) {
403 return; // already visited
404 }
405
406 debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
407
408 let item = match self.impl_item(impl_def_id) {
409 Some(m) => m,
410 None => { return; } // No method with correct name on this impl
411 };
412
413 if !self.has_applicable_self(&item) {
414 // No receiver declared. Not a candidate.
415 return self.record_static_candidate(ImplSource(impl_def_id));
416 }
417
418 if !item.vis().is_accessible_from(self.body_id, &self.tcx.map) {
419 self.private_candidate = Some(item.def());
420 return
421 }
422
423 let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
424 let impl_ty = impl_ty.subst(self.tcx, &impl_substs);
425
426 // Determine the receiver type that the method itself expects.
427 let xform_self_ty = self.xform_self_ty(&item, impl_ty, &impl_substs);
428
429 // We can't use normalize_associated_types_in as it will pollute the
430 // fcx's fulfillment context after this probe is over.
431 let cause = traits::ObligationCause::misc(self.span, self.body_id);
432 let mut selcx = &mut traits::SelectionContext::new(self.fcx);
433 let traits::Normalized { value: xform_self_ty, obligations } =
434 traits::normalize(selcx, cause, &xform_self_ty);
435 debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}",
436 xform_self_ty);
437
438 self.inherent_candidates.push(Candidate {
439 xform_self_ty: xform_self_ty,
440 item: item,
441 kind: InherentImplCandidate(impl_substs, obligations),
442 import_id: self.import_id,
443 });
444 }
445
446 fn assemble_inherent_candidates_from_object(&mut self,
447 self_ty: Ty<'tcx>,
448 data: &ty::TraitTy<'tcx>) {
449 debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
450 self_ty);
451
452 // It is illegal to invoke a method on a trait instance that
453 // refers to the `Self` type. An error will be reported by
454 // `enforce_object_limitations()` if the method refers to the
455 // `Self` type anywhere other than the receiver. Here, we use
456 // a substitution that replaces `Self` with the object type
457 // itself. Hence, a `&self` method will wind up with an
458 // argument type like `&Trait`.
459 let trait_ref = data.principal_trait_ref_with_self_ty(self.tcx, self_ty);
460 self.elaborate_bounds(&[trait_ref], |this, new_trait_ref, item| {
461 let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
462
463 let xform_self_ty = this.xform_self_ty(&item,
464 new_trait_ref.self_ty(),
465 new_trait_ref.substs);
466
467 this.inherent_candidates.push(Candidate {
468 xform_self_ty: xform_self_ty,
469 item: item,
470 kind: ObjectCandidate,
471 import_id: this.import_id,
472 });
473 });
474 }
475
476 fn assemble_inherent_candidates_from_param(&mut self,
477 _rcvr_ty: Ty<'tcx>,
478 param_ty: ty::ParamTy) {
479 // FIXME -- Do we want to commit to this behavior for param bounds?
480
481 let bounds: Vec<_> =
482 self.parameter_environment.caller_bounds
483 .iter()
484 .filter_map(|predicate| {
485 match *predicate {
486 ty::Predicate::Trait(ref trait_predicate) => {
487 match trait_predicate.0.trait_ref.self_ty().sty {
488 ty::TyParam(ref p) if *p == param_ty => {
489 Some(trait_predicate.to_poly_trait_ref())
490 }
491 _ => None
492 }
493 }
494 ty::Predicate::Equate(..) |
495 ty::Predicate::Projection(..) |
496 ty::Predicate::RegionOutlives(..) |
497 ty::Predicate::WellFormed(..) |
498 ty::Predicate::ObjectSafe(..) |
499 ty::Predicate::ClosureKind(..) |
500 ty::Predicate::Rfc1592(..) |
501 ty::Predicate::TypeOutlives(..) => {
502 None
503 }
504 }
505 })
506 .collect();
507
508 self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
509 let trait_ref =
510 this.erase_late_bound_regions(&poly_trait_ref);
511
512 let xform_self_ty =
513 this.xform_self_ty(&item,
514 trait_ref.self_ty(),
515 trait_ref.substs);
516
517 if let Some(ref m) = item.as_opt_method() {
518 debug!("found match: trait_ref={:?} substs={:?} m={:?}",
519 trait_ref,
520 trait_ref.substs,
521 m);
522 assert_eq!(m.generics.types.get_slice(subst::TypeSpace).len(),
523 trait_ref.substs.types.get_slice(subst::TypeSpace).len());
524 assert_eq!(m.generics.regions.get_slice(subst::TypeSpace).len(),
525 trait_ref.substs.regions.get_slice(subst::TypeSpace).len());
526 assert_eq!(m.generics.types.get_slice(subst::SelfSpace).len(),
527 trait_ref.substs.types.get_slice(subst::SelfSpace).len());
528 assert_eq!(m.generics.regions.get_slice(subst::SelfSpace).len(),
529 trait_ref.substs.regions.get_slice(subst::SelfSpace).len());
530 }
531
532 // Because this trait derives from a where-clause, it
533 // should not contain any inference variables or other
534 // artifacts. This means it is safe to put into the
535 // `WhereClauseCandidate` and (eventually) into the
536 // `WhereClausePick`.
537 assert!(!trait_ref.substs.types.needs_infer());
538
539 this.inherent_candidates.push(Candidate {
540 xform_self_ty: xform_self_ty,
541 item: item,
542 kind: WhereClauseCandidate(poly_trait_ref),
543 import_id: this.import_id,
544 });
545 });
546 }
547
548 // Do a search through a list of bounds, using a callback to actually
549 // create the candidates.
550 fn elaborate_bounds<F>(
551 &mut self,
552 bounds: &[ty::PolyTraitRef<'tcx>],
553 mut mk_cand: F,
554 ) where
555 F: for<'b> FnMut(
556 &mut ProbeContext<'b, 'gcx, 'tcx>,
557 ty::PolyTraitRef<'tcx>,
558 ty::ImplOrTraitItem<'tcx>,
559 ),
560 {
561 debug!("elaborate_bounds(bounds={:?})", bounds);
562
563 let tcx = self.tcx;
564 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
565 let item = match self.trait_item(bound_trait_ref.def_id()) {
566 Some(v) => v,
567 None => { continue; }
568 };
569
570 if !self.has_applicable_self(&item) {
571 self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
572 } else {
573 mk_cand(self, bound_trait_ref, item);
574 }
575 }
576 }
577
578 fn assemble_extension_candidates_for_traits_in_scope(&mut self,
579 expr_id: ast::NodeId)
580 -> Result<(), MethodError<'tcx>>
581 {
582 let mut duplicates = HashSet::new();
583 let opt_applicable_traits = self.tcx.trait_map.get(&expr_id);
584 if let Some(applicable_traits) = opt_applicable_traits {
585 for trait_candidate in applicable_traits {
586 let trait_did = trait_candidate.def_id;
587 if duplicates.insert(trait_did) {
588 self.import_id = trait_candidate.import_id;
589 let result = self.assemble_extension_candidates_for_trait(trait_did);
590 self.import_id = None;
591 result?;
592 }
593 }
594 }
595 Ok(())
596 }
597
598 fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
599 let mut duplicates = HashSet::new();
600 for trait_info in suggest::all_traits(self.ccx) {
601 if duplicates.insert(trait_info.def_id) {
602 self.assemble_extension_candidates_for_trait(trait_info.def_id)?;
603 }
604 }
605 Ok(())
606 }
607
608 fn assemble_extension_candidates_for_trait(&mut self,
609 trait_def_id: DefId)
610 -> Result<(), MethodError<'tcx>>
611 {
612 debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
613 trait_def_id);
614
615 // Check whether `trait_def_id` defines a method with suitable name:
616 let trait_items =
617 self.tcx.trait_items(trait_def_id);
618 let maybe_item =
619 trait_items.iter()
620 .find(|item| item.name() == self.item_name);
621 let item = match maybe_item {
622 Some(i) => i,
623 None => { return Ok(()); }
624 };
625
626 // Check whether `trait_def_id` defines a method with suitable name:
627 if !self.has_applicable_self(item) {
628 debug!("method has inapplicable self");
629 self.record_static_candidate(TraitSource(trait_def_id));
630 return Ok(());
631 }
632
633 self.assemble_extension_candidates_for_trait_impls(trait_def_id, item.clone());
634
635 self.assemble_closure_candidates(trait_def_id, item.clone())?;
636
637 self.assemble_projection_candidates(trait_def_id, item.clone());
638
639 self.assemble_where_clause_candidates(trait_def_id, item.clone());
640
641 Ok(())
642 }
643
644 fn assemble_extension_candidates_for_trait_impls(&mut self,
645 trait_def_id: DefId,
646 item: ty::ImplOrTraitItem<'tcx>)
647 {
648 let trait_def = self.tcx.lookup_trait_def(trait_def_id);
649
650 // FIXME(arielb1): can we use for_each_relevant_impl here?
651 trait_def.for_each_impl(self.tcx, |impl_def_id| {
652 debug!("assemble_extension_candidates_for_trait_impl: trait_def_id={:?} \
653 impl_def_id={:?}",
654 trait_def_id,
655 impl_def_id);
656
657 if !self.impl_can_possibly_match(impl_def_id) {
658 return;
659 }
660
661 let (_, impl_substs) = self.impl_ty_and_substs(impl_def_id);
662
663 debug!("impl_substs={:?}", impl_substs);
664
665 let impl_trait_ref =
666 self.tcx.impl_trait_ref(impl_def_id)
667 .unwrap() // we know this is a trait impl
668 .subst(self.tcx, &impl_substs);
669
670 debug!("impl_trait_ref={:?}", impl_trait_ref);
671
672 // Determine the receiver type that the method itself expects.
673 let xform_self_ty =
674 self.xform_self_ty(&item,
675 impl_trait_ref.self_ty(),
676 impl_trait_ref.substs);
677
678 // Normalize the receiver. We can't use normalize_associated_types_in
679 // as it will pollute the fcx's fulfillment context after this probe
680 // is over.
681 let cause = traits::ObligationCause::misc(self.span, self.body_id);
682 let mut selcx = &mut traits::SelectionContext::new(self.fcx);
683 let traits::Normalized { value: xform_self_ty, obligations } =
684 traits::normalize(selcx, cause, &xform_self_ty);
685
686 debug!("xform_self_ty={:?}", xform_self_ty);
687
688 self.extension_candidates.push(Candidate {
689 xform_self_ty: xform_self_ty,
690 item: item.clone(),
691 kind: ExtensionImplCandidate(impl_def_id, impl_substs, obligations),
692 import_id: self.import_id,
693 });
694 });
695 }
696
697 fn impl_can_possibly_match(&self, impl_def_id: DefId) -> bool {
698 let simplified_steps = match self.opt_simplified_steps {
699 Some(ref simplified_steps) => simplified_steps,
700 None => { return true; }
701 };
702
703 let impl_type = self.tcx.lookup_item_type(impl_def_id);
704 let impl_simplified_type =
705 match ty::fast_reject::simplify_type(self.tcx, impl_type.ty, false) {
706 Some(simplified_type) => simplified_type,
707 None => { return true; }
708 };
709
710 simplified_steps.contains(&impl_simplified_type)
711 }
712
713 fn assemble_closure_candidates(&mut self,
714 trait_def_id: DefId,
715 item: ty::ImplOrTraitItem<'tcx>)
716 -> Result<(), MethodError<'tcx>>
717 {
718 // Check if this is one of the Fn,FnMut,FnOnce traits.
719 let tcx = self.tcx;
720 let kind = if Some(trait_def_id) == tcx.lang_items.fn_trait() {
721 ty::ClosureKind::Fn
722 } else if Some(trait_def_id) == tcx.lang_items.fn_mut_trait() {
723 ty::ClosureKind::FnMut
724 } else if Some(trait_def_id) == tcx.lang_items.fn_once_trait() {
725 ty::ClosureKind::FnOnce
726 } else {
727 return Ok(());
728 };
729
730 // Check if there is an unboxed-closure self-type in the list of receivers.
731 // If so, add "synthetic impls".
732 let steps = self.steps.clone();
733 for step in steps.iter() {
734 let closure_def_id = match step.self_ty.sty {
735 ty::TyClosure(a, _) => a,
736 _ => continue,
737 };
738
739 let closure_kinds = &self.tables.borrow().closure_kinds;
740 let closure_kind = match closure_kinds.get(&closure_def_id) {
741 Some(&k) => k,
742 None => {
743 return Err(MethodError::ClosureAmbiguity(trait_def_id));
744 }
745 };
746
747 // this closure doesn't implement the right kind of `Fn` trait
748 if !closure_kind.extends(kind) {
749 continue;
750 }
751
752 // create some substitutions for the argument/return type;
753 // for the purposes of our method lookup, we only take
754 // receiver type into account, so we can just substitute
755 // fresh types here to use during substitution and subtyping.
756 let trait_def = self.tcx.lookup_trait_def(trait_def_id);
757 let substs = self.fresh_substs_for_trait(self.span,
758 &trait_def.generics,
759 step.self_ty);
760
761 let xform_self_ty = self.xform_self_ty(&item,
762 step.self_ty,
763 &substs);
764 self.inherent_candidates.push(Candidate {
765 xform_self_ty: xform_self_ty,
766 item: item.clone(),
767 kind: TraitCandidate,
768 import_id: self.import_id,
769 });
770 }
771
772 Ok(())
773 }
774
775 fn assemble_projection_candidates(&mut self,
776 trait_def_id: DefId,
777 item: ty::ImplOrTraitItem<'tcx>)
778 {
779 debug!("assemble_projection_candidates(\
780 trait_def_id={:?}, \
781 item={:?})",
782 trait_def_id,
783 item);
784
785 for step in self.steps.iter() {
786 debug!("assemble_projection_candidates: step={:?}",
787 step);
788
789 let (def_id, substs) = match step.self_ty.sty {
790 ty::TyProjection(ref data) => {
791 (data.trait_ref.def_id, data.trait_ref.substs)
792 }
793 ty::TyAnon(def_id, substs) => (def_id, substs),
794 _ => continue,
795 };
796
797 debug!("assemble_projection_candidates: def_id={:?} substs={:?}",
798 def_id, substs);
799
800 let trait_predicates = self.tcx.lookup_predicates(def_id);
801 let bounds = trait_predicates.instantiate(self.tcx, substs);
802 let predicates = bounds.predicates.into_vec();
803 debug!("assemble_projection_candidates: predicates={:?}",
804 predicates);
805 for poly_bound in
806 traits::elaborate_predicates(self.tcx, predicates)
807 .filter_map(|p| p.to_opt_poly_trait_ref())
808 .filter(|b| b.def_id() == trait_def_id)
809 {
810 let bound = self.erase_late_bound_regions(&poly_bound);
811
812 debug!("assemble_projection_candidates: def_id={:?} substs={:?} bound={:?}",
813 def_id, substs, bound);
814
815 if self.can_equate(&step.self_ty, &bound.self_ty()).is_ok() {
816 let xform_self_ty = self.xform_self_ty(&item,
817 bound.self_ty(),
818 bound.substs);
819
820 debug!("assemble_projection_candidates: bound={:?} xform_self_ty={:?}",
821 bound,
822 xform_self_ty);
823
824 self.extension_candidates.push(Candidate {
825 xform_self_ty: xform_self_ty,
826 item: item.clone(),
827 kind: TraitCandidate,
828 import_id: self.import_id,
829 });
830 }
831 }
832 }
833 }
834
835 fn assemble_where_clause_candidates(&mut self,
836 trait_def_id: DefId,
837 item: ty::ImplOrTraitItem<'tcx>)
838 {
839 debug!("assemble_where_clause_candidates(trait_def_id={:?})",
840 trait_def_id);
841
842 let caller_predicates = self.parameter_environment.caller_bounds.clone();
843 for poly_bound in traits::elaborate_predicates(self.tcx, caller_predicates)
844 .filter_map(|p| p.to_opt_poly_trait_ref())
845 .filter(|b| b.def_id() == trait_def_id)
846 {
847 let bound = self.erase_late_bound_regions(&poly_bound);
848 let xform_self_ty = self.xform_self_ty(&item,
849 bound.self_ty(),
850 bound.substs);
851
852 debug!("assemble_where_clause_candidates: bound={:?} xform_self_ty={:?}",
853 bound,
854 xform_self_ty);
855
856 self.extension_candidates.push(Candidate {
857 xform_self_ty: xform_self_ty,
858 item: item.clone(),
859 kind: WhereClauseCandidate(poly_bound),
860 import_id: self.import_id,
861 });
862 }
863 }
864
865 ///////////////////////////////////////////////////////////////////////////
866 // THE ACTUAL SEARCH
867
868 fn pick(mut self) -> PickResult<'tcx> {
869 if let Some(r) = self.pick_core() {
870 return r;
871 }
872
873 let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
874 let private_candidate = mem::replace(&mut self.private_candidate, None);
875 let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
876
877 // things failed, so lets look at all traits, for diagnostic purposes now:
878 self.reset();
879
880 let span = self.span;
881 let tcx = self.tcx;
882
883 self.assemble_extension_candidates_for_all_traits()?;
884
885 let out_of_scope_traits = match self.pick_core() {
886 Some(Ok(p)) => vec![p.item.container().id()],
887 Some(Err(MethodError::Ambiguity(v))) => v.into_iter().map(|source| {
888 match source {
889 TraitSource(id) => id,
890 ImplSource(impl_id) => {
891 match tcx.trait_id_of_impl(impl_id) {
892 Some(id) => id,
893 None =>
894 span_bug!(span,
895 "found inherent method when looking at traits")
896 }
897 }
898 }
899 }).collect(),
900 Some(Err(MethodError::NoMatch(NoMatchData { out_of_scope_traits: others, .. }))) => {
901 assert!(others.is_empty());
902 vec![]
903 }
904 Some(Err(MethodError::ClosureAmbiguity(..))) => {
905 // this error only occurs when assembling candidates
906 span_bug!(span, "encountered ClosureAmbiguity from pick_core");
907 }
908 _ => vec![],
909 };
910
911 if let Some(def) = private_candidate {
912 return Err(MethodError::PrivateMatch(def));
913 }
914
915 Err(MethodError::NoMatch(NoMatchData::new(static_candidates, unsatisfied_predicates,
916 out_of_scope_traits, self.mode)))
917 }
918
919 fn pick_core(&mut self) -> Option<PickResult<'tcx>> {
920 let steps = self.steps.clone();
921
922 // find the first step that works
923 steps.iter().filter_map(|step| self.pick_step(step)).next()
924 }
925
926 fn pick_step(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
927 debug!("pick_step: step={:?}", step);
928
929 if step.self_ty.references_error() {
930 return None;
931 }
932
933 if let Some(result) = self.pick_by_value_method(step) {
934 return Some(result);
935 }
936
937 self.pick_autorefd_method(step)
938 }
939
940 fn pick_by_value_method(&mut self,
941 step: &CandidateStep<'tcx>)
942 -> Option<PickResult<'tcx>>
943 {
944 /*!
945 * For each type `T` in the step list, this attempts to find a
946 * method where the (transformed) self type is exactly `T`. We
947 * do however do one transformation on the adjustment: if we
948 * are passing a region pointer in, we will potentially
949 * *reborrow* it to a shorter lifetime. This allows us to
950 * transparently pass `&mut` pointers, in particular, without
951 * consuming them for their entire lifetime.
952 */
953
954 if step.unsize {
955 return None;
956 }
957
958 self.pick_method(step.self_ty).map(|r| r.map(|mut pick| {
959 pick.autoderefs = step.autoderefs;
960
961 // Insert a `&*` or `&mut *` if this is a reference type:
962 if let ty::TyRef(_, mt) = step.self_ty.sty {
963 pick.autoderefs += 1;
964 pick.autoref = Some(mt.mutbl);
965 }
966
967 pick
968 }))
969 }
970
971 fn pick_autorefd_method(&mut self,
972 step: &CandidateStep<'tcx>)
973 -> Option<PickResult<'tcx>>
974 {
975 let tcx = self.tcx;
976
977 // In general, during probing we erase regions. See
978 // `impl_self_ty()` for an explanation.
979 let region = tcx.mk_region(ty::ReErased);
980
981 // Search through mutabilities in order to find one where pick works:
982 [hir::MutImmutable, hir::MutMutable].iter().filter_map(|&m| {
983 let autoref_ty = tcx.mk_ref(region, ty::TypeAndMut {
984 ty: step.self_ty,
985 mutbl: m
986 });
987 self.pick_method(autoref_ty).map(|r| r.map(|mut pick| {
988 pick.autoderefs = step.autoderefs;
989 pick.autoref = Some(m);
990 pick.unsize = if step.unsize {
991 Some(step.self_ty)
992 } else {
993 None
994 };
995 pick
996 }))
997 }).nth(0)
998 }
999
1000 fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
1001 debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1002
1003 let mut possibly_unsatisfied_predicates = Vec::new();
1004
1005 debug!("searching inherent candidates");
1006 if let Some(pick) = self.consider_candidates(self_ty,
1007 &self.inherent_candidates,
1008 &mut possibly_unsatisfied_predicates) {
1009 return Some(pick);
1010 }
1011
1012 debug!("searching extension candidates");
1013 let res = self.consider_candidates(self_ty, &self.extension_candidates,
1014 &mut possibly_unsatisfied_predicates);
1015 if let None = res {
1016 self.unsatisfied_predicates.extend(possibly_unsatisfied_predicates);
1017 }
1018 res
1019 }
1020
1021 fn consider_candidates(&self,
1022 self_ty: Ty<'tcx>,
1023 probes: &[Candidate<'tcx>],
1024 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
1025 -> Option<PickResult<'tcx>> {
1026 let mut applicable_candidates: Vec<_> =
1027 probes.iter()
1028 .filter(|&probe| self.consider_probe(self_ty,
1029 probe,possibly_unsatisfied_predicates))
1030 .collect();
1031
1032 debug!("applicable_candidates: {:?}", applicable_candidates);
1033
1034 if applicable_candidates.len() > 1 {
1035 match self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
1036 Some(pick) => { return Some(Ok(pick)); }
1037 None => { }
1038 }
1039 }
1040
1041 if applicable_candidates.len() > 1 {
1042 let sources = probes.iter().map(|p| p.to_source()).collect();
1043 return Some(Err(MethodError::Ambiguity(sources)));
1044 }
1045
1046 applicable_candidates.pop().map(|probe| {
1047 Ok(probe.to_unadjusted_pick())
1048 })
1049 }
1050
1051 fn consider_probe(&self, self_ty: Ty<'tcx>, probe: &Candidate<'tcx>,
1052 possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>) -> bool {
1053 debug!("consider_probe: self_ty={:?} probe={:?}",
1054 self_ty,
1055 probe);
1056
1057 self.probe(|_| {
1058 // First check that the self type can be related.
1059 match self.sub_types(false, TypeOrigin::Misc(DUMMY_SP),
1060 self_ty, probe.xform_self_ty) {
1061 Ok(InferOk { obligations, .. }) => {
1062 // FIXME(#32730) propagate obligations
1063 assert!(obligations.is_empty())
1064 }
1065 Err(_) => {
1066 debug!("--> cannot relate self-types");
1067 return false;
1068 }
1069 }
1070
1071 // If so, impls may carry other conditions (e.g., where
1072 // clauses) that must be considered. Make sure that those
1073 // match as well (or at least may match, sometimes we
1074 // don't have enough information to fully evaluate).
1075 let (impl_def_id, substs, ref_obligations) = match probe.kind {
1076 InherentImplCandidate(ref substs, ref ref_obligations) => {
1077 (probe.item.container().id(), substs, ref_obligations)
1078 }
1079
1080 ExtensionImplCandidate(impl_def_id, ref substs, ref ref_obligations) => {
1081 (impl_def_id, substs, ref_obligations)
1082 }
1083
1084 ObjectCandidate |
1085 TraitCandidate |
1086 WhereClauseCandidate(..) => {
1087 // These have no additional conditions to check.
1088 return true;
1089 }
1090 };
1091
1092 let selcx = &mut traits::SelectionContext::new(self);
1093 let cause = traits::ObligationCause::misc(self.span, self.body_id);
1094
1095 // Check whether the impl imposes obligations we have to worry about.
1096 let impl_bounds = self.tcx.lookup_predicates(impl_def_id);
1097 let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
1098 let traits::Normalized { value: impl_bounds,
1099 obligations: norm_obligations } =
1100 traits::normalize(selcx, cause.clone(), &impl_bounds);
1101
1102 // Convert the bounds into obligations.
1103 let obligations =
1104 traits::predicates_for_generics(cause.clone(),
1105 &impl_bounds);
1106 debug!("impl_obligations={:?}", obligations);
1107
1108 // Evaluate those obligations to see if they might possibly hold.
1109 let mut all_true = true;
1110 for o in obligations.iter()
1111 .chain(norm_obligations.iter())
1112 .chain(ref_obligations.iter()) {
1113 if !selcx.evaluate_obligation(o) {
1114 all_true = false;
1115 if let &ty::Predicate::Trait(ref pred) = &o.predicate {
1116 possibly_unsatisfied_predicates.push(pred.0.trait_ref);
1117 }
1118 }
1119 }
1120 all_true
1121 })
1122 }
1123
1124 /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1125 /// same trait, but we don't know which impl to use. In this case, since in all cases the
1126 /// external interface of the method can be determined from the trait, it's ok not to decide.
1127 /// We can basically just collapse all of the probes for various impls into one where-clause
1128 /// probe. This will result in a pending obligation so when more type-info is available we can
1129 /// make the final decision.
1130 ///
1131 /// Example (`src/test/run-pass/method-two-trait-defer-resolution-1.rs`):
1132 ///
1133 /// ```
1134 /// trait Foo { ... }
1135 /// impl Foo for Vec<int> { ... }
1136 /// impl Foo for Vec<usize> { ... }
1137 /// ```
1138 ///
1139 /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1140 /// use, so it's ok to just commit to "using the method from the trait Foo".
1141 fn collapse_candidates_to_trait_pick(&self,
1142 probes: &[&Candidate<'tcx>])
1143 -> Option<Pick<'tcx>> {
1144 // Do all probes correspond to the same trait?
1145 let container = probes[0].item.container();
1146 match container {
1147 ty::TraitContainer(_) => {}
1148 ty::ImplContainer(_) => return None
1149 }
1150 if probes[1..].iter().any(|p| p.item.container() != container) {
1151 return None;
1152 }
1153
1154 // If so, just use this trait and call it a day.
1155 Some(Pick {
1156 item: probes[0].item.clone(),
1157 kind: TraitPick,
1158 import_id: probes[0].import_id,
1159 autoderefs: 0,
1160 autoref: None,
1161 unsize: None
1162 })
1163 }
1164
1165 ///////////////////////////////////////////////////////////////////////////
1166 // MISCELLANY
1167 fn has_applicable_self(&self, item: &ty::ImplOrTraitItem) -> bool {
1168 // "fast track" -- check for usage of sugar
1169 match *item {
1170 ty::ImplOrTraitItem::MethodTraitItem(ref method) =>
1171 match method.explicit_self {
1172 ty::ExplicitSelfCategory::Static => self.mode == Mode::Path,
1173 ty::ExplicitSelfCategory::ByValue |
1174 ty::ExplicitSelfCategory::ByReference(..) |
1175 ty::ExplicitSelfCategory::ByBox => true,
1176 },
1177 ty::ImplOrTraitItem::ConstTraitItem(..) => self.mode == Mode::Path,
1178 _ => false,
1179 }
1180 // FIXME -- check for types that deref to `Self`,
1181 // like `Rc<Self>` and so on.
1182 //
1183 // Note also that the current code will break if this type
1184 // includes any of the type parameters defined on the method
1185 // -- but this could be overcome.
1186 }
1187
1188 fn record_static_candidate(&mut self, source: CandidateSource) {
1189 self.static_candidates.push(source);
1190 }
1191
1192 fn xform_self_ty(&self,
1193 item: &ty::ImplOrTraitItem<'tcx>,
1194 impl_ty: Ty<'tcx>,
1195 substs: &subst::Substs<'tcx>)
1196 -> Ty<'tcx>
1197 {
1198 match item.as_opt_method() {
1199 Some(ref method) => self.xform_method_self_ty(method, impl_ty,
1200 substs),
1201 None => impl_ty,
1202 }
1203 }
1204
1205 fn xform_method_self_ty(&self,
1206 method: &Rc<ty::Method<'tcx>>,
1207 impl_ty: Ty<'tcx>,
1208 substs: &subst::Substs<'tcx>)
1209 -> Ty<'tcx>
1210 {
1211 debug!("xform_self_ty(impl_ty={:?}, self_ty={:?}, substs={:?})",
1212 impl_ty,
1213 method.fty.sig.0.inputs.get(0),
1214 substs);
1215
1216 assert!(!substs.has_escaping_regions());
1217
1218 // It is possible for type parameters or early-bound lifetimes
1219 // to appear in the signature of `self`. The substitutions we
1220 // are given do not include type/lifetime parameters for the
1221 // method yet. So create fresh variables here for those too,
1222 // if there are any.
1223 assert_eq!(substs.types.len(subst::FnSpace), 0);
1224 assert_eq!(substs.regions.len(subst::FnSpace), 0);
1225
1226 if self.mode == Mode::Path {
1227 return impl_ty;
1228 }
1229
1230 let mut placeholder;
1231 let mut substs = substs;
1232 if
1233 !method.generics.types.is_empty_in(subst::FnSpace) ||
1234 !method.generics.regions.is_empty_in(subst::FnSpace)
1235 {
1236 // In general, during probe we erase regions. See
1237 // `impl_self_ty()` for an explanation.
1238 let method_regions =
1239 method.generics.regions.get_slice(subst::FnSpace)
1240 .iter()
1241 .map(|_| ty::ReErased)
1242 .collect();
1243
1244 placeholder = (*substs).clone().with_method(Vec::new(), method_regions);
1245
1246 self.type_vars_for_defs(
1247 self.span,
1248 subst::FnSpace,
1249 &mut placeholder,
1250 method.generics.types.get_slice(subst::FnSpace));
1251
1252 substs = &placeholder;
1253 }
1254
1255 // Erase any late-bound regions from the method and substitute
1256 // in the values from the substitution.
1257 let xform_self_ty = method.fty.sig.input(0);
1258 let xform_self_ty = self.erase_late_bound_regions(&xform_self_ty);
1259 let xform_self_ty = xform_self_ty.subst(self.tcx, substs);
1260
1261 xform_self_ty
1262 }
1263
1264 /// Get the type of an impl and generate substitutions with placeholders.
1265 fn impl_ty_and_substs(&self,
1266 impl_def_id: DefId)
1267 -> (Ty<'tcx>, subst::Substs<'tcx>)
1268 {
1269 let impl_pty = self.tcx.lookup_item_type(impl_def_id);
1270
1271 let type_vars =
1272 impl_pty.generics.types.map(
1273 |_| self.next_ty_var());
1274
1275 let region_placeholders =
1276 impl_pty.generics.regions.map(
1277 |_| ty::ReErased); // see erase_late_bound_regions() for an expl of why 'erased
1278
1279 let substs = subst::Substs::new(type_vars, region_placeholders);
1280 (impl_pty.ty, substs)
1281 }
1282
1283 /// Replace late-bound-regions bound by `value` with `'static` using
1284 /// `ty::erase_late_bound_regions`.
1285 ///
1286 /// This is only a reasonable thing to do during the *probe* phase, not the *confirm* phase, of
1287 /// method matching. It is reasonable during the probe phase because we don't consider region
1288 /// relationships at all. Therefore, we can just replace all the region variables with 'static
1289 /// rather than creating fresh region variables. This is nice for two reasons:
1290 ///
1291 /// 1. Because the numbers of the region variables would otherwise be fairly unique to this
1292 /// particular method call, it winds up creating fewer types overall, which helps for memory
1293 /// usage. (Admittedly, this is a rather small effect, though measureable.)
1294 ///
1295 /// 2. It makes it easier to deal with higher-ranked trait bounds, because we can replace any
1296 /// late-bound regions with 'static. Otherwise, if we were going to replace late-bound
1297 /// regions with actual region variables as is proper, we'd have to ensure that the same
1298 /// region got replaced with the same variable, which requires a bit more coordination
1299 /// and/or tracking the substitution and
1300 /// so forth.
1301 fn erase_late_bound_regions<T>(&self, value: &ty::Binder<T>) -> T
1302 where T : TypeFoldable<'tcx>
1303 {
1304 self.tcx.erase_late_bound_regions(value)
1305 }
1306
1307 fn impl_item(&self, impl_def_id: DefId)
1308 -> Option<ty::ImplOrTraitItem<'tcx>>
1309 {
1310 self.fcx.impl_item(impl_def_id, self.item_name)
1311 }
1312
1313 /// Find item with name `item_name` defined in `trait_def_id`
1314 /// and return it, or `None`, if no such item.
1315 fn trait_item(&self, trait_def_id: DefId)
1316 -> Option<ty::ImplOrTraitItem<'tcx>>
1317 {
1318 self.fcx.trait_item(trait_def_id, self.item_name)
1319 }
1320 }
1321
1322 impl<'tcx> Candidate<'tcx> {
1323 fn to_unadjusted_pick(&self) -> Pick<'tcx> {
1324 Pick {
1325 item: self.item.clone(),
1326 kind: match self.kind {
1327 InherentImplCandidate(_, _) => InherentImplPick,
1328 ExtensionImplCandidate(def_id, _, _) => {
1329 ExtensionImplPick(def_id)
1330 }
1331 ObjectCandidate => ObjectPick,
1332 TraitCandidate => TraitPick,
1333 WhereClauseCandidate(ref trait_ref) => {
1334 // Only trait derived from where-clauses should
1335 // appear here, so they should not contain any
1336 // inference variables or other artifacts. This
1337 // means they are safe to put into the
1338 // `WhereClausePick`.
1339 assert!(!trait_ref.substs().types.needs_infer());
1340
1341 WhereClausePick(trait_ref.clone())
1342 }
1343 },
1344 import_id: self.import_id,
1345 autoderefs: 0,
1346 autoref: None,
1347 unsize: None
1348 }
1349 }
1350
1351 fn to_source(&self) -> CandidateSource {
1352 match self.kind {
1353 InherentImplCandidate(_, _) => {
1354 ImplSource(self.item.container().id())
1355 }
1356 ExtensionImplCandidate(def_id, _, _) => ImplSource(def_id),
1357 ObjectCandidate |
1358 TraitCandidate |
1359 WhereClauseCandidate(_) => TraitSource(self.item.container().id()),
1360 }
1361 }
1362 }