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 //! See `doc.rs` for high-level documentation
12 #![allow(dead_code)] // FIXME -- just temporarily
14 pub use self::MethodMatchResult::*;
15 pub use self::MethodMatchedData::*;
16 use self::SelectionCandidate::*;
17 use self::BuiltinBoundConditions::*;
18 use self::EvaluationResult::*;
20 use super::{DerivedObligationCause};
22 use super::{PredicateObligation, Obligation, TraitObligation, ObligationCause};
23 use super::{ObligationCauseCode, BuiltinDerivedObligation};
24 use super::{SelectionError, Unimplemented, Overflow, OutputTypeParameterMismatch};
25 use super::{Selection};
26 use super::{SelectionResult};
27 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableUnboxedClosure,
28 VtableFnPointer, VtableObject};
29 use super::{VtableImplData, VtableObjectData, VtableBuiltinData};
30 use super::object_safety;
33 use middle::fast_reject;
34 use middle::mem_categorization::Typer;
35 use middle::subst::{Subst, Substs, TypeSpace, VecPerParamSpace};
36 use middle::ty::{self, AsPredicate, RegionEscape, ToPolyTraitRef, Ty};
38 use middle::infer::{InferCtxt, TypeFreshener};
39 use middle::ty_fold::TypeFoldable;
40 use std::cell::RefCell;
41 use std::collections::hash_map::HashMap;
43 use syntax::{abi, ast};
44 use util::common::ErrorReported;
45 use util::ppaux::Repr;
47 pub struct SelectionContext<'cx, 'tcx:'cx> {
48 infcx: &'cx InferCtxt<'cx, 'tcx>,
49 closure_typer: &'cx (ty::UnboxedClosureTyper<'tcx>+'cx),
51 /// Freshener used specifically for skolemizing entries on the
52 /// obligation stack. This ensures that all entries on the stack
53 /// at one time will have the same set of skolemized entries,
54 /// which is important for checking for trait bounds that
55 /// recursively require themselves.
56 freshener: TypeFreshener<'cx, 'tcx>,
58 /// If true, indicates that the evaluation should be conservative
59 /// and consider the possibility of types outside this crate.
60 /// This comes up primarily when resolving ambiguity. Imagine
61 /// there is some trait reference `$0 : Bar` where `$0` is an
62 /// inference variable. If `intercrate` is true, then we can never
63 /// say for sure that this reference is not implemented, even if
64 /// there are *no impls at all for `Bar`*, because `$0` could be
65 /// bound to some type that in a downstream crate that implements
66 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
67 /// though, we set this to false, because we are only interested
68 /// in types that the user could actually have written --- in
69 /// other words, we consider `$0 : Bar` to be unimplemented if
70 /// there is no type that the user could *actually name* that
71 /// would satisfy it. This avoids crippling inference, basically.
75 // A stack that walks back up the stack frame.
76 struct TraitObligationStack<'prev, 'tcx: 'prev> {
77 obligation: &'prev TraitObligation<'tcx>,
79 /// Trait ref from `obligation` but skolemized with the
80 /// selection-context's freshener. Used to check for recursion.
81 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
83 previous: Option<&'prev TraitObligationStack<'prev, 'tcx>>
87 pub struct SelectionCache<'tcx> {
88 hashmap: RefCell<HashMap<Rc<ty::TraitRef<'tcx>>,
89 SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
92 pub enum MethodMatchResult {
93 MethodMatched(MethodMatchedData),
94 MethodAmbiguous(/* list of impls that could apply */ Vec<ast::DefId>),
99 pub enum MethodMatchedData {
100 // In the case of a precise match, we don't really need to store
101 // how the match was found. So don't.
104 // In the case of a coercion, we need to know the precise impl so
105 // that we can determine the type to which things were coerced.
106 CoerciveMethodMatch(/* impl we matched */ ast::DefId)
109 /// The selection process begins by considering all impls, where
110 /// clauses, and so forth that might resolve an obligation. Sometimes
111 /// we'll be able to say definitively that (e.g.) an impl does not
112 /// apply to the obligation: perhaps it is defined for `uint` but the
113 /// obligation is for `int`. In that case, we drop the impl out of the
114 /// list. But the other cases are considered *candidates*.
116 /// Candidates can either be definitive or ambiguous. An ambiguous
117 /// candidate is one that might match or might not, depending on how
118 /// type variables wind up being resolved. This only occurs during inference.
120 /// For selection to succeed, there must be exactly one non-ambiguous
121 /// candidate. Usually, it is not possible to have more than one
122 /// definitive candidate, due to the coherence rules. However, there is
123 /// one case where it could occur: if there is a blanket impl for a
124 /// trait (that is, an impl applied to all T), and a type parameter
125 /// with a where clause. In that case, we can have a candidate from the
126 /// where clause and a second candidate from the impl. This is not a
127 /// problem because coherence guarantees us that the impl which would
128 /// be used to satisfy the where clause is the same one that we see
129 /// now. To resolve this issue, therefore, we ignore impls if we find a
130 /// matching where clause. Part of the reason for this is that where
131 /// clauses can give additional information (like, the types of output
132 /// parameters) that would have to be inferred from the impl.
133 #[derive(PartialEq,Eq,Show,Clone)]
134 enum SelectionCandidate<'tcx> {
135 BuiltinCandidate(ty::BuiltinBound),
136 ParamCandidate(ty::PolyTraitRef<'tcx>),
137 ImplCandidate(ast::DefId),
139 /// This is a trait matching with a projected type as `Self`, and
140 /// we found an applicable bound in the trait definition.
143 /// Implementation of a `Fn`-family trait by one of the
144 /// anonymous types generated for a `||` expression.
145 UnboxedClosureCandidate(/* closure */ ast::DefId, Substs<'tcx>),
147 /// Implementation of a `Fn`-family trait by one of the anonymous
148 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
156 struct SelectionCandidateSet<'tcx> {
157 // a list of candidates that definitely apply to the current
158 // obligation (meaning: types unify).
159 vec: Vec<SelectionCandidate<'tcx>>,
161 // if this is true, then there were candidates that might or might
162 // not have applied, but we couldn't tell. This occurs when some
163 // of the input types are type variables, in which case there are
164 // various "builtin" rules that might or might not trigger.
168 enum BuiltinBoundConditions<'tcx> {
175 enum EvaluationResult<'tcx> {
178 EvaluatedToErr(SelectionError<'tcx>),
181 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
182 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>,
183 closure_typer: &'cx ty::UnboxedClosureTyper<'tcx>)
184 -> SelectionContext<'cx, 'tcx> {
187 closure_typer: closure_typer,
188 freshener: infcx.freshener(),
193 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>,
194 closure_typer: &'cx ty::UnboxedClosureTyper<'tcx>)
195 -> SelectionContext<'cx, 'tcx> {
198 closure_typer: closure_typer,
199 freshener: infcx.freshener(),
204 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
208 pub fn tcx(&self) -> &'cx ty::ctxt<'tcx> {
212 pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'cx, 'tcx> {
213 self.closure_typer.param_env()
216 ///////////////////////////////////////////////////////////////////////////
219 // The selection phase tries to identify *how* an obligation will
220 // be resolved. For example, it will identify which impl or
221 // parameter bound is to be used. The process can be inconclusive
222 // if the self type in the obligation is not fully inferred. Selection
223 // can result in an error in one of two ways:
225 // 1. If no applicable impl or parameter bound can be found.
226 // 2. If the output type parameters in the obligation do not match
227 // those specified by the impl/bound. For example, if the obligation
228 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
229 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
231 /// Evaluates whether the obligation can be satisfied. Returns an indication of whether the
232 /// obligation can be satisfied and, if so, by what means. Never affects surrounding typing
234 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
235 -> SelectionResult<'tcx, Selection<'tcx>> {
236 debug!("select({})", obligation.repr(self.tcx()));
237 assert!(!obligation.predicate.has_escaping_regions());
239 let stack = self.push_stack(None, obligation);
240 match try!(self.candidate_from_obligation(&stack)) {
242 Some(candidate) => Ok(Some(try!(self.confirm_candidate(obligation, candidate)))),
246 ///////////////////////////////////////////////////////////////////////////
249 // Tests whether an obligation can be selected or whether an impl
250 // can be applied to particular types. It skips the "confirmation"
251 // step and hence completely ignores output type parameters.
253 // The result is "true" if the obligation *may* hold and "false" if
254 // we can be sure it does not.
256 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
257 pub fn evaluate_obligation(&mut self,
258 obligation: &PredicateObligation<'tcx>)
261 debug!("evaluate_obligation({})",
262 obligation.repr(self.tcx()));
264 self.evaluate_predicate_recursively(None, obligation).may_apply()
267 fn evaluate_builtin_bound_recursively<'o>(&mut self,
268 bound: ty::BuiltinBound,
269 previous_stack: &TraitObligationStack<'o, 'tcx>,
271 -> EvaluationResult<'tcx>
274 util::predicate_for_builtin_bound(
276 previous_stack.obligation.cause.clone(),
278 previous_stack.obligation.recursion_depth + 1,
283 self.evaluate_predicate_recursively(Some(previous_stack), &obligation)
285 Err(ErrorReported) => {
291 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
292 stack: Option<&TraitObligationStack<'o, 'tcx>>,
294 -> EvaluationResult<'tcx>
295 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
297 let mut result = EvaluatedToOk;
298 for obligation in predicates {
299 match self.evaluate_predicate_recursively(stack, obligation) {
300 EvaluatedToErr(e) => { return EvaluatedToErr(e); }
301 EvaluatedToAmbig => { result = EvaluatedToAmbig; }
308 fn evaluate_predicate_recursively<'o>(&mut self,
309 previous_stack: Option<&TraitObligationStack<'o, 'tcx>>,
310 obligation: &PredicateObligation<'tcx>)
311 -> EvaluationResult<'tcx>
313 debug!("evaluate_predicate_recursively({})",
314 obligation.repr(self.tcx()));
316 match obligation.predicate {
317 ty::Predicate::Trait(ref t) => {
318 assert!(!t.has_escaping_regions());
319 let obligation = obligation.with(t.clone());
320 self.evaluate_obligation_recursively(previous_stack, &obligation)
323 ty::Predicate::Equate(ref p) => {
324 let result = self.infcx.probe(|_| {
325 self.infcx.equality_predicate(obligation.cause.span, p)
328 Ok(()) => EvaluatedToOk,
329 Err(_) => EvaluatedToErr(Unimplemented),
333 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
334 // we do not consider region relationships when
335 // evaluating trait matches
339 ty::Predicate::Projection(ref data) => {
340 self.infcx.probe(|_| {
341 let project_obligation = obligation.with(data.clone());
342 match project::poly_project_and_unify_type(self, &project_obligation) {
343 Ok(Some(subobligations)) => {
344 self.evaluate_predicates_recursively(previous_stack,
345 subobligations.iter())
351 EvaluatedToErr(Unimplemented)
359 fn evaluate_obligation_recursively<'o>(&mut self,
360 previous_stack: Option<&TraitObligationStack<'o, 'tcx>>,
361 obligation: &TraitObligation<'tcx>)
362 -> EvaluationResult<'tcx>
364 debug!("evaluate_obligation_recursively({})",
365 obligation.repr(self.tcx()));
367 let stack = self.push_stack(previous_stack.map(|x| x), obligation);
369 let result = self.evaluate_stack(&stack);
371 debug!("result: {}", result);
375 fn evaluate_stack<'o>(&mut self,
376 stack: &TraitObligationStack<'o, 'tcx>)
377 -> EvaluationResult<'tcx>
379 // In intercrate mode, whenever any of the types are unbound,
380 // there can always be an impl. Even if there are no impls in
381 // this crate, perhaps the type would be unified with
382 // something from another crate that does provide an impl.
384 // In intracrate mode, we must still be conservative. The reason is
385 // that we want to avoid cycles. Imagine an impl like:
387 // impl<T:Eq> Eq for Vec<T>
389 // and a trait reference like `$0 : Eq` where `$0` is an
390 // unbound variable. When we evaluate this trait-reference, we
391 // will unify `$0` with `Vec<$1>` (for some fresh variable
392 // `$1`), on the condition that `$1 : Eq`. We will then wind
393 // up with many candidates (since that are other `Eq` impls
394 // that apply) and try to winnow things down. This results in
395 // a recurssive evaluation that `$1 : Eq` -- as you can
396 // imagine, this is just where we started. To avoid that, we
397 // check for unbound variables and return an ambiguous (hence possible)
398 // match if we've seen this trait before.
400 // This suffices to allow chains like `FnMut` implemented in
401 // terms of `Fn` etc, but we could probably make this more
403 let input_types = stack.fresh_trait_ref.0.input_types();
404 let unbound_input_types = input_types.iter().any(|&t| ty::type_is_fresh(t));
406 unbound_input_types &&
408 stack.iter().skip(1).any(
409 |prev| stack.fresh_trait_ref.def_id() == prev.fresh_trait_ref.def_id()))
411 debug!("evaluate_stack({}) --> unbound argument, recursion --> ambiguous",
412 stack.fresh_trait_ref.repr(self.tcx()));
413 return EvaluatedToAmbig;
416 // If there is any previous entry on the stack that precisely
417 // matches this obligation, then we can assume that the
418 // obligation is satisfied for now (still all other conditions
419 // must be met of course). One obvious case this comes up is
420 // marker traits like `Send`. Think of a linked list:
422 // struct List<T> { data: T, next: Option<Box<List<T>>> {
424 // `Box<List<T>>` will be `Send` if `T` is `Send` and
425 // `Option<Box<List<T>>>` is `Send`, and in turn
426 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
429 // Note that we do this comparison using the `fresh_trait_ref`
430 // fields. Because these have all been skolemized using
431 // `self.freshener`, we can be sure that (a) this will not
432 // affect the inferencer state and (b) that if we see two
433 // skolemized types with the same index, they refer to the
434 // same unbound type variable.
437 .skip(1) // skip top-most frame
438 .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref)
440 debug!("evaluate_stack({}) --> recursive",
441 stack.fresh_trait_ref.repr(self.tcx()));
442 return EvaluatedToOk;
445 match self.candidate_from_obligation(stack) {
446 Ok(Some(c)) => self.winnow_candidate(stack, &c),
447 Ok(None) => EvaluatedToAmbig,
448 Err(e) => EvaluatedToErr(e),
452 /// Evaluates whether the impl with id `impl_def_id` could be applied to the self type
453 /// `obligation_self_ty`. This can be used either for trait or inherent impls.
454 pub fn evaluate_impl(&mut self,
455 impl_def_id: ast::DefId,
456 obligation: &TraitObligation<'tcx>)
459 debug!("evaluate_impl(impl_def_id={}, obligation={})",
460 impl_def_id.repr(self.tcx()),
461 obligation.repr(self.tcx()));
463 self.infcx.probe(|snapshot| {
464 let (skol_obligation_trait_ref, skol_map) =
465 self.infcx().skolemize_late_bound_regions(&obligation.predicate, snapshot);
466 match self.match_impl(impl_def_id, obligation, snapshot,
467 &skol_map, skol_obligation_trait_ref.trait_ref.clone()) {
469 let vtable_impl = self.vtable_impl(impl_def_id,
471 obligation.cause.clone(),
472 obligation.recursion_depth + 1,
475 self.winnow_selection(None, VtableImpl(vtable_impl)).may_apply()
484 ///////////////////////////////////////////////////////////////////////////
485 // CANDIDATE ASSEMBLY
487 // The selection process begins by examining all in-scope impls,
488 // caller obligations, and so forth and assembling a list of
489 // candidates. See `doc.rs` and the `Candidate` type for more details.
491 fn candidate_from_obligation<'o>(&mut self,
492 stack: &TraitObligationStack<'o, 'tcx>)
493 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
495 // Watch out for overflow. This intentionally bypasses (and does
496 // not update) the cache.
497 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
498 if stack.obligation.recursion_depth >= recursion_limit {
499 debug!("{} --> overflow (limit={})",
500 stack.obligation.repr(self.tcx()),
505 // Check the cache. Note that we skolemize the trait-ref
506 // separately rather than using `stack.fresh_trait_ref` -- this
507 // is because we want the unbound variables to be replaced
508 // with fresh skolemized types starting from index 0.
509 let cache_fresh_trait_pred =
510 self.infcx.freshen(stack.obligation.predicate.clone());
511 debug!("candidate_from_obligation(cache_fresh_trait_pred={}, obligation={})",
512 cache_fresh_trait_pred.repr(self.tcx()),
513 stack.repr(self.tcx()));
514 assert!(!stack.obligation.predicate.has_escaping_regions());
516 match self.check_candidate_cache(&cache_fresh_trait_pred) {
518 debug!("CACHE HIT: cache_fresh_trait_pred={}, candidate={}",
519 cache_fresh_trait_pred.repr(self.tcx()),
526 // If no match, compute result and insert into cache.
527 let candidate = self.candidate_from_obligation_no_cache(stack);
528 debug!("CACHE MISS: cache_fresh_trait_pred={}, candidate={}",
529 cache_fresh_trait_pred.repr(self.tcx()), candidate.repr(self.tcx()));
530 self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone());
534 fn candidate_from_obligation_no_cache<'o>(&mut self,
535 stack: &TraitObligationStack<'o, 'tcx>)
536 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
538 if ty::type_is_error(stack.obligation.predicate.0.self_ty()) {
539 return Ok(Some(ErrorCandidate));
542 let candidate_set = try!(self.assemble_candidates(stack));
544 if candidate_set.ambiguous {
545 debug!("candidate set contains ambig");
549 let mut candidates = candidate_set.vec;
551 debug!("assembled {} candidates for {}: {}",
553 stack.repr(self.tcx()),
554 candidates.repr(self.tcx()));
556 // At this point, we know that each of the entries in the
557 // candidate set is *individually* applicable. Now we have to
558 // figure out if they contain mutual incompatibilities. This
559 // frequently arises if we have an unconstrained input type --
560 // for example, we are looking for $0:Eq where $0 is some
561 // unconstrained type variable. In that case, we'll get a
562 // candidate which assumes $0 == int, one that assumes $0 ==
563 // uint, etc. This spells an ambiguity.
565 // If there is more than one candidate, first winnow them down
566 // by considering extra conditions (nested obligations and so
567 // forth). We don't winnow if there is exactly one
568 // candidate. This is a relatively minor distinction but it
569 // can lead to better inference and error-reporting. An
570 // example would be if there was an impl:
572 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
574 // and we were to see some code `foo.push_clone()` where `boo`
575 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
576 // we were to winnow, we'd wind up with zero candidates.
577 // Instead, we select the right impl now but report `Bar does
578 // not implement Clone`.
579 if candidates.len() > 1 {
580 candidates.retain(|c| self.winnow_candidate(stack, c).may_apply())
583 // If there are STILL multiple candidate, we can further reduce
584 // the list by dropping duplicates.
585 if candidates.len() > 1 {
587 while i < candidates.len() {
589 range(0, candidates.len())
591 .any(|j| self.candidate_should_be_dropped_in_favor_of(stack,
595 debug!("Dropping candidate #{}/{}: {}",
596 i, candidates.len(), candidates[i].repr(self.tcx()));
597 candidates.swap_remove(i);
599 debug!("Retaining candidate #{}/{}: {}",
600 i, candidates.len(), candidates[i].repr(self.tcx()));
606 // If there are *STILL* multiple candidates, give up and
607 // report ambiguiuty.
608 if candidates.len() > 1 {
609 debug!("multiple matches, ambig");
613 // If there are *NO* candidates, that there are no impls --
614 // that we know of, anyway. Note that in the case where there
615 // are unbound type variables within the obligation, it might
616 // be the case that you could still satisfy the obligation
617 // from another crate by instantiating the type variables with
618 // a type from another crate that does have an impl. This case
619 // is checked for in `evaluate_stack` (and hence users
620 // who might care about this case, like coherence, should use
622 if candidates.len() == 0 {
623 return Err(Unimplemented);
626 // Just one candidate left.
627 let candidate = candidates.pop().unwrap();
631 fn pick_candidate_cache(&self,
632 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
633 -> &SelectionCache<'tcx>
635 // High-level idea: we have to decide whether to consult the
636 // cache that is specific to this scope, or to consult the
637 // global cache. We want the cache that is specific to this
638 // scope whenever where clauses might affect the result.
640 // Avoid using the master cache during coherence and just rely
641 // on the local cache. This effectively disables caching
642 // during coherence. It is really just a simplification to
643 // avoid us having to fear that coherence results "pollute"
644 // the master cache. Since coherence executes pretty quickly,
645 // it's not worth going to more trouble to increase the
646 // hit-rate I don't think.
648 return &self.param_env().selection_cache;
651 // If the trait refers to any parameters in scope, then use
652 // the cache of the param-environment.
654 cache_fresh_trait_pred.0.input_types().iter().any(
655 |&t| ty::type_has_self(t) || ty::type_has_params(t))
657 return &self.param_env().selection_cache;
660 // If the trait refers to unbound type variables, and there
661 // are where clauses in scope, then use the local environment.
662 // If there are no where clauses in scope, which is a very
663 // common case, then we can use the global environment.
664 // See the discussion in doc.rs for more details.
666 !self.param_env().caller_bounds.is_empty() &&
667 cache_fresh_trait_pred.0.input_types().iter().any(
668 |&t| ty::type_has_ty_infer(t))
670 return &self.param_env().selection_cache;
673 // Otherwise, we can use the global cache.
674 &self.tcx().selection_cache
677 fn check_candidate_cache(&mut self,
678 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
679 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
681 let cache = self.pick_candidate_cache(cache_fresh_trait_pred);
682 let hashmap = cache.hashmap.borrow();
683 hashmap.get(&cache_fresh_trait_pred.0.trait_ref).map(|c| (*c).clone())
686 fn insert_candidate_cache(&mut self,
687 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
688 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
690 let cache = self.pick_candidate_cache(&cache_fresh_trait_pred);
691 let mut hashmap = cache.hashmap.borrow_mut();
692 hashmap.insert(cache_fresh_trait_pred.0.trait_ref.clone(), candidate);
695 fn assemble_candidates<'o>(&mut self,
696 stack: &TraitObligationStack<'o, 'tcx>)
697 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
699 // Check for overflow.
701 let TraitObligationStack { obligation, .. } = *stack;
703 let mut candidates = SelectionCandidateSet {
708 // Other bounds. Consider both in-scope bounds from fn decl
709 // and applicable impls. There is a certain set of precedence rules here.
711 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
712 Some(ty::BoundCopy) => {
713 debug!("obligation self ty is {}",
714 obligation.predicate.0.self_ty().repr(self.tcx()));
716 // If the user has asked for the older, compatibility
717 // behavior, ignore user-defined impls here. This will
718 // go away by the time 1.0 is released.
719 if !self.tcx().sess.features.borrow().opt_out_copy {
720 try!(self.assemble_candidates_from_impls(obligation, &mut candidates.vec));
723 try!(self.assemble_builtin_bound_candidates(ty::BoundCopy,
727 Some(bound @ ty::BoundSend) |
728 Some(bound @ ty::BoundSync) => {
729 try!(self.assemble_candidates_from_impls(obligation, &mut candidates.vec));
731 // No explicit impls were declared for this type, consider the fallback rules.
732 if candidates.vec.is_empty() {
733 try!(self.assemble_builtin_bound_candidates(bound, stack, &mut candidates));
737 Some(bound @ ty::BoundSized) => {
738 // Sized and Copy are always automatically computed.
739 try!(self.assemble_builtin_bound_candidates(bound, stack, &mut candidates));
743 // For the time being, we ignore user-defined impls for builtin-bounds, other than
745 // (And unboxed candidates only apply to the Fn/FnMut/etc traits.)
746 try!(self.assemble_unboxed_closure_candidates(obligation, &mut candidates));
747 try!(self.assemble_fn_pointer_candidates(obligation, &mut candidates));
748 try!(self.assemble_candidates_from_impls(obligation, &mut candidates.vec));
749 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
753 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
754 try!(self.assemble_candidates_from_caller_bounds(obligation, &mut candidates));
755 debug!("candidate list size: {}", candidates.vec.len());
759 fn assemble_candidates_from_projected_tys(&mut self,
760 obligation: &TraitObligation<'tcx>,
761 candidates: &mut SelectionCandidateSet<'tcx>)
763 let poly_trait_predicate =
764 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
766 debug!("assemble_candidates_for_projected_tys({},{})",
767 obligation.repr(self.tcx()),
768 poly_trait_predicate.repr(self.tcx()));
770 // FIXME(#20297) -- just examining the self-type is very simplistic
772 // before we go into the whole skolemization thing, just
773 // quickly check if the self-type is a projection at all.
774 let trait_def_id = match poly_trait_predicate.0.trait_ref.self_ty().sty {
775 ty::ty_projection(ref data) => data.trait_ref.def_id,
776 ty::ty_infer(ty::TyVar(_)) => {
777 // If the self-type is an inference variable, then it MAY wind up
778 // being a projected type, so induce an ambiguity.
780 // FIXME(#20297) -- being strict about this can cause
781 // inference failures with BorrowFrom, which is
782 // unfortunate. Can we do better here?
783 candidates.ambiguous = true;
789 debug!("assemble_candidates_for_projected_tys: trait_def_id={}",
790 trait_def_id.repr(self.tcx()));
792 let result = self.infcx.probe(|snapshot| {
793 self.match_projection_obligation_against_bounds_from_trait(obligation,
798 candidates.vec.push(ProjectionCandidate);
802 fn match_projection_obligation_against_bounds_from_trait(
804 obligation: &TraitObligation<'tcx>,
805 snapshot: &infer::CombinedSnapshot)
808 let poly_trait_predicate =
809 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
810 let (skol_trait_predicate, skol_map) =
811 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
812 debug!("match_projection_obligation_against_bounds_from_trait: \
813 skol_trait_predicate={} skol_map={}",
814 skol_trait_predicate.repr(self.tcx()),
815 skol_map.repr(self.tcx()));
817 let projection_trait_ref = match skol_trait_predicate.trait_ref.self_ty().sty {
818 ty::ty_projection(ref data) => &data.trait_ref,
820 self.tcx().sess.span_bug(
821 obligation.cause.span,
822 format!("match_projection_obligation_against_bounds_from_trait() called \
823 but self-ty not a projection: {}",
824 skol_trait_predicate.trait_ref.self_ty().repr(self.tcx())).as_slice());
827 debug!("match_projection_obligation_against_bounds_from_trait: \
828 projection_trait_ref={}",
829 projection_trait_ref.repr(self.tcx()));
831 let trait_def = ty::lookup_trait_def(self.tcx(), projection_trait_ref.def_id);
832 let bounds = trait_def.generics.to_bounds(self.tcx(), projection_trait_ref.substs);
833 debug!("match_projection_obligation_against_bounds_from_trait: \
835 bounds.repr(self.tcx()));
838 util::elaborate_predicates(self.tcx(), bounds.predicates.to_vec())
841 |bound| self.infcx.probe(
842 |_| self.match_projection(obligation,
844 skol_trait_predicate.trait_ref.clone(),
848 debug!("match_projection_obligation_against_bounds_from_trait: \
850 matching_bound.repr(self.tcx()));
851 match matching_bound {
854 // Repeat the successful match, if any, this time outside of a probe.
855 let result = self.match_projection(obligation,
857 skol_trait_predicate.trait_ref.clone(),
866 fn match_projection(&mut self,
867 obligation: &TraitObligation<'tcx>,
868 trait_bound: ty::PolyTraitRef<'tcx>,
869 skol_trait_ref: Rc<ty::TraitRef<'tcx>>,
870 skol_map: &infer::SkolemizationMap,
871 snapshot: &infer::CombinedSnapshot)
874 assert!(!skol_trait_ref.has_escaping_regions());
875 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
876 match self.infcx.sub_poly_trait_refs(false,
879 ty::Binder(skol_trait_ref.clone())) {
881 Err(_) => { return false; }
884 self.infcx.leak_check(skol_map, snapshot).is_ok()
887 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
888 /// supplied to find out whether it is listed among them.
890 /// Never affects inference environment.
891 fn assemble_candidates_from_caller_bounds(&mut self,
892 obligation: &TraitObligation<'tcx>,
893 candidates: &mut SelectionCandidateSet<'tcx>)
894 -> Result<(),SelectionError<'tcx>>
896 debug!("assemble_candidates_from_caller_bounds({})",
897 obligation.repr(self.tcx()));
899 let caller_trait_refs: Vec<_> =
900 self.param_env().caller_bounds.predicates.iter()
901 .filter_map(|o| o.to_opt_poly_trait_ref())
905 util::transitive_bounds(
906 self.tcx(), caller_trait_refs[]);
908 let matching_bounds =
910 |bound| self.infcx.probe(
911 |_| self.match_poly_trait_ref(obligation, bound.clone())).is_ok());
913 let param_candidates =
914 matching_bounds.map(|bound| ParamCandidate(bound));
916 candidates.vec.extend(param_candidates);
921 /// Check for the artificial impl that the compiler will create for an obligation like `X :
922 /// FnMut<..>` where `X` is an unboxed closure type.
924 /// Note: the type parameters on an unboxed closure candidate are modeled as *output* type
925 /// parameters and hence do not affect whether this trait is a match or not. They will be
926 /// unified during the confirmation step.
927 fn assemble_unboxed_closure_candidates(&mut self,
928 obligation: &TraitObligation<'tcx>,
929 candidates: &mut SelectionCandidateSet<'tcx>)
930 -> Result<(),SelectionError<'tcx>>
932 let kind = match self.fn_family_trait_kind(obligation.predicate.0.def_id()) {
934 None => { return Ok(()); }
937 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
938 let (closure_def_id, substs) = match self_ty.sty {
939 ty::ty_unboxed_closure(id, _, ref substs) => (id, substs.clone()),
940 ty::ty_infer(ty::TyVar(_)) => {
941 candidates.ambiguous = true;
944 _ => { return Ok(()); }
947 debug!("assemble_unboxed_candidates: self_ty={} kind={} obligation={}",
948 self_ty.repr(self.tcx()),
950 obligation.repr(self.tcx()));
952 let closure_kind = self.closure_typer.unboxed_closure_kind(closure_def_id);
954 debug!("closure_kind = {}", closure_kind);
956 if closure_kind == kind {
957 candidates.vec.push(UnboxedClosureCandidate(closure_def_id, substs.clone()));
963 /// Implement one of the `Fn()` family for a fn pointer.
964 fn assemble_fn_pointer_candidates(&mut self,
965 obligation: &TraitObligation<'tcx>,
966 candidates: &mut SelectionCandidateSet<'tcx>)
967 -> Result<(),SelectionError<'tcx>>
969 // We provide a `Fn` impl for fn pointers. There is no need to provide
970 // the other traits (e.g. `FnMut`) since those are provided by blanket
972 if Some(obligation.predicate.def_id()) != self.tcx().lang_items.fn_trait() {
976 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
978 ty::ty_infer(ty::TyVar(_)) => {
979 candidates.ambiguous = true; // could wind up being a fn() type
982 // provide an impl, but only for suitable `fn` pointers
983 ty::ty_bare_fn(_, &ty::BareFnTy {
984 unsafety: ast::Unsafety::Normal,
986 sig: ty::Binder(ty::FnSig {
988 output: ty::FnConverging(_),
992 candidates.vec.push(FnPointerCandidate);
1001 /// Search for impls that might apply to `obligation`.
1002 fn assemble_candidates_from_impls(&mut self,
1003 obligation: &TraitObligation<'tcx>,
1004 candidate_vec: &mut Vec<SelectionCandidate<'tcx>>)
1005 -> Result<(), SelectionError<'tcx>>
1007 let all_impls = self.all_impls(obligation.predicate.def_id());
1008 for &impl_def_id in all_impls.iter() {
1009 self.infcx.probe(|snapshot| {
1010 let (skol_obligation_trait_pred, skol_map) =
1011 self.infcx().skolemize_late_bound_regions(&obligation.predicate, snapshot);
1012 match self.match_impl(impl_def_id, obligation, snapshot,
1013 &skol_map, skol_obligation_trait_pred.trait_ref.clone()) {
1015 candidate_vec.push(ImplCandidate(impl_def_id));
1024 /// Search for impls that might apply to `obligation`.
1025 fn assemble_candidates_from_object_ty(&mut self,
1026 obligation: &TraitObligation<'tcx>,
1027 candidates: &mut SelectionCandidateSet<'tcx>)
1029 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1031 debug!("assemble_candidates_from_object_ty(self_ty={})",
1032 self_ty.repr(self.tcx()));
1034 // Object-safety candidates are only applicable to object-safe
1035 // traits. Including this check is useful because it helps
1036 // inference in cases of traits like `BorrowFrom`, which are
1037 // not object-safe, and which rely on being able to infer the
1038 // self-type from one of the other inputs. Without this check,
1039 // these cases wind up being considered ambiguous due to a
1040 // (spurious) ambiguity introduced here.
1041 if !object_safety::is_object_safe(self.tcx(), obligation.predicate.to_poly_trait_ref()) {
1045 let poly_trait_ref = match self_ty.sty {
1046 ty::ty_trait(ref data) => {
1047 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
1049 ty::ty_infer(ty::TyVar(_)) => {
1050 debug!("assemble_candidates_from_object_ty: ambiguous");
1051 candidates.ambiguous = true; // could wind up being an object type
1059 debug!("assemble_candidates_from_object_ty: poly_trait_ref={}",
1060 poly_trait_ref.repr(self.tcx()));
1062 // see whether the object trait can be upcast to the trait we are looking for
1063 let obligation_def_id = obligation.predicate.def_id();
1064 let upcast_trait_ref = match util::upcast(self.tcx(), poly_trait_ref, obligation_def_id) {
1069 debug!("assemble_candidates_from_object_ty: upcast_trait_ref={}",
1070 upcast_trait_ref.repr(self.tcx()));
1072 // check whether the upcast version of the trait-ref matches what we are looking for
1073 if let Ok(()) = self.infcx.probe(|_| self.match_poly_trait_ref(obligation,
1074 upcast_trait_ref.clone())) {
1075 debug!("assemble_candidates_from_object_ty: matched, pushing candidate");
1076 candidates.vec.push(ObjectCandidate);
1080 ///////////////////////////////////////////////////////////////////////////
1083 // Winnowing is the process of attempting to resolve ambiguity by
1084 // probing further. During the winnowing process, we unify all
1085 // type variables (ignoring skolemization) and then we also
1086 // attempt to evaluate recursive bounds to see if they are
1089 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1090 /// obligations are met. Returns true if `candidate` remains viable after this further
1092 fn winnow_candidate<'o>(&mut self,
1093 stack: &TraitObligationStack<'o, 'tcx>,
1094 candidate: &SelectionCandidate<'tcx>)
1095 -> EvaluationResult<'tcx>
1097 debug!("winnow_candidate: candidate={}", candidate.repr(self.tcx()));
1098 let result = self.infcx.probe(|_| {
1099 let candidate = (*candidate).clone();
1100 match self.confirm_candidate(stack.obligation, candidate) {
1101 Ok(selection) => self.winnow_selection(Some(stack), selection),
1102 Err(error) => EvaluatedToErr(error),
1105 debug!("winnow_candidate depth={} result={}",
1106 stack.obligation.recursion_depth, result);
1110 fn winnow_selection<'o>(&mut self,
1111 stack: Option<&TraitObligationStack<'o, 'tcx>>,
1112 selection: Selection<'tcx>)
1113 -> EvaluationResult<'tcx>
1115 self.evaluate_predicates_recursively(stack, selection.iter_nested())
1118 /// Returns true if `candidate_i` should be dropped in favor of `candidate_j`.
1120 /// This is generally true if either:
1121 /// - candidate i and candidate j are equivalent; or,
1122 /// - candidate i is a conrete impl and candidate j is a where clause bound,
1123 /// and the concrete impl is applicable to the types in the where clause bound.
1125 /// The last case refers to cases where there are blanket impls (often conditional
1126 /// blanket impls) as well as a where clause. This can come down to one of two cases:
1128 /// - The impl is truly unconditional (it has no where clauses
1129 /// of its own), in which case the where clause is
1130 /// unnecessary, because coherence requires that we would
1131 /// pick that particular impl anyhow (at least so long as we
1132 /// don't have specialization).
1134 /// - The impl is conditional, in which case we may not have winnowed it out
1135 /// because we don't know if the conditions apply, but the where clause is basically
1136 /// telling us taht there is some impl, though not necessarily the one we see.
1138 /// In both cases we prefer to take the where clause, which is
1139 /// essentially harmless. See issue #18453 for more details of
1140 /// a case where doing the opposite caused us harm.
1141 fn candidate_should_be_dropped_in_favor_of<'o>(&mut self,
1142 stack: &TraitObligationStack<'o, 'tcx>,
1143 candidate_i: &SelectionCandidate<'tcx>,
1144 candidate_j: &SelectionCandidate<'tcx>)
1147 match (candidate_i, candidate_j) {
1148 (&ImplCandidate(impl_def_id), &ParamCandidate(ref bound)) => {
1149 debug!("Considering whether to drop param {} in favor of impl {}",
1150 candidate_i.repr(self.tcx()),
1151 candidate_j.repr(self.tcx()));
1153 self.infcx.probe(|snapshot| {
1154 let (skol_obligation_trait_ref, skol_map) =
1155 self.infcx().skolemize_late_bound_regions(
1156 &stack.obligation.predicate, snapshot);
1158 self.rematch_impl(impl_def_id, stack.obligation, snapshot,
1159 &skol_map, skol_obligation_trait_ref.trait_ref.clone());
1160 let impl_trait_ref =
1161 ty::impl_trait_ref(self.tcx(), impl_def_id).unwrap();
1162 let impl_trait_ref =
1163 impl_trait_ref.subst(self.tcx(), &impl_substs);
1164 let poly_impl_trait_ref =
1165 ty::Binder(impl_trait_ref);
1167 infer::RelateOutputImplTypes(stack.obligation.cause.span);
1169 .sub_poly_trait_refs(false, origin, poly_impl_trait_ref, bound.clone())
1173 (&ProjectionCandidate, &ParamCandidate(_)) => {
1174 // FIXME(#20297) -- this gives where clauses precedent
1175 // over projections. Really these are just two means
1176 // of deducing information (one based on the where
1177 // clauses on the trait definition; one based on those
1178 // on the enclosing scope), and it'd be better to
1179 // integrate them more intelligently. But for now this
1180 // seems ok. If we DON'T give where clauses
1181 // precedence, we run into trouble in default methods,
1182 // where both the projection bounds for `Self::A` and
1183 // the where clauses are in scope.
1187 *candidate_i == *candidate_j
1192 ///////////////////////////////////////////////////////////////////////////
1195 // These cover the traits that are built-in to the language
1196 // itself. This includes `Copy` and `Sized` for sure. For the
1197 // moment, it also includes `Send` / `Sync` and a few others, but
1198 // those will hopefully change to library-defined traits in the
1201 fn assemble_builtin_bound_candidates<'o>(&mut self,
1202 bound: ty::BuiltinBound,
1203 stack: &TraitObligationStack<'o, 'tcx>,
1204 candidates: &mut SelectionCandidateSet<'tcx>)
1205 -> Result<(),SelectionError<'tcx>>
1207 match self.builtin_bound(bound, stack.obligation) {
1209 debug!("builtin_bound: bound={}",
1210 bound.repr(self.tcx()));
1211 candidates.vec.push(BuiltinCandidate(bound));
1214 Ok(ParameterBuiltin) => { Ok(()) }
1215 Ok(AmbiguousBuiltin) => { Ok(candidates.ambiguous = true) }
1216 Err(e) => { Err(e) }
1220 fn builtin_bound(&mut self,
1221 bound: ty::BuiltinBound,
1222 obligation: &TraitObligation<'tcx>)
1223 -> Result<BuiltinBoundConditions<'tcx>,SelectionError<'tcx>>
1225 // Note: these tests operate on types that may contain bound
1226 // regions. To be proper, we ought to skolemize here, but we
1227 // forego the skolemization and defer it until the
1228 // confirmation step.
1230 let self_ty = self.infcx.shallow_resolve(obligation.predicate.0.self_ty());
1231 return match self_ty.sty {
1232 ty::ty_infer(ty::IntVar(_)) |
1233 ty::ty_infer(ty::FloatVar(_)) |
1238 ty::ty_bare_fn(..) |
1240 // safe for everything
1244 ty::ty_uniq(referent_ty) => { // Box<T>
1256 Ok(If(vec![referent_ty]))
1261 ty::ty_ptr(..) => { // *const T, *mut T
1270 // sync and send are not implemented for *const, *mut
1276 ty::ty_closure(ref c) => {
1278 ty::UniqTraitStore => {
1279 // proc: Equivalent to `Box<FnOnce>`
1291 if c.bounds.builtin_bounds.contains(&bound) {
1299 ty::RegionTraitStore(_, mutbl) => {
1300 // ||: Equivalent to `&FnMut` or `&mut FnMut` or something like that.
1304 ast::MutMutable => {
1308 ast::MutImmutable => {
1309 // &T is copyable, no matter what T is
1321 if c.bounds.builtin_bounds.contains(&bound) {
1332 ty::ty_trait(ref data) => {
1337 ty::BoundCopy | ty::BoundSync | ty::BoundSend => {
1338 if data.bounds.builtin_bounds.contains(&bound) {
1341 // Recursively check all supertraits to find out if any further
1342 // bounds are required and thus we must fulfill.
1344 data.principal_trait_ref_with_self_ty(self.tcx(),
1345 self.tcx().types.err);
1346 for tr in util::supertraits(self.tcx(), principal) {
1347 let td = ty::lookup_trait_def(self.tcx(), tr.def_id());
1348 if td.bounds.builtin_bounds.contains(&bound) {
1349 return Ok(If(Vec::new()))
1359 ty::ty_rptr(_, ty::mt { ty: referent_ty, mutbl }) => {
1364 // &mut T is affine and hence never `Copy`
1365 ast::MutMutable => {
1369 // &T is always copyable
1370 ast::MutImmutable => {
1382 // Note: technically, a region pointer is only
1383 // sendable if it has lifetime
1384 // `'static`. However, we don't take regions
1385 // into account when doing trait matching:
1386 // instead, when we decide that `T : Send`, we
1387 // will register a separate constraint with
1388 // the region inferencer that `T : 'static`
1389 // holds as well (because the trait `Send`
1390 // requires it). This will ensure that there
1391 // is no borrowed data in `T` (or else report
1392 // an inference error). The reason we do it
1393 // this way is that we do not yet *know* what
1394 // lifetime the borrowed reference has, since
1395 // we haven't finished running inference -- in
1396 // other words, there's a kind of
1397 // chicken-and-egg problem.
1398 Ok(If(vec![referent_ty]))
1403 ty::ty_vec(element_ty, ref len) => {
1409 // [T, ..n] is copy iff T is copy
1410 Ok(If(vec![element_ty]))
1413 // [T] is unsized and hence affine
1429 Ok(If(vec![element_ty]))
1435 // Equivalent to [u8]
1449 ty::ty_tup(ref tys) => {
1450 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1454 ty::ty_unboxed_closure(def_id, _, substs) => {
1455 // FIXME -- This case is tricky. In the case of by-ref
1456 // closures particularly, we need the results of
1457 // inference to decide how to reflect the type of each
1458 // upvar (the upvar may have type `T`, but the runtime
1459 // type could be `&mut`, `&`, or just `T`). For now,
1460 // though, we'll do this unsoundly and assume that all
1461 // captures are by value. Really what we ought to do
1462 // is reserve judgement and then intertwine this
1463 // analysis with closure inference.
1464 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
1466 // Unboxed closures shouldn't be
1467 // implicitly copyable
1468 if bound == ty::BoundCopy {
1469 return Ok(ParameterBuiltin);
1472 match self.closure_typer.unboxed_closure_upvars(def_id, substs) {
1474 Ok(If(upvars.iter().map(|c| c.ty).collect()))
1477 Ok(AmbiguousBuiltin)
1482 ty::ty_struct(def_id, substs) => {
1483 let types: Vec<Ty> =
1484 ty::struct_fields(self.tcx(), def_id, substs).iter()
1487 nominal(self, bound, def_id, types)
1490 ty::ty_enum(def_id, substs) => {
1491 let types: Vec<Ty> =
1492 ty::substd_enum_variants(self.tcx(), def_id, substs)
1494 .flat_map(|variant| variant.args.iter())
1497 nominal(self, bound, def_id, types)
1500 ty::ty_projection(_) |
1501 ty::ty_param(_) => {
1502 // Note: A type parameter is only considered to meet a
1503 // particular bound if there is a where clause telling
1504 // us that it does, and that case is handled by
1505 // `assemble_candidates_from_caller_bounds()`.
1506 Ok(ParameterBuiltin)
1509 ty::ty_infer(ty::TyVar(_)) => {
1510 // Unbound type variable. Might or might not have
1511 // applicable impls and so forth, depending on what
1512 // those type variables wind up being bound to.
1513 Ok(AmbiguousBuiltin)
1521 ty::ty_infer(ty::FreshTy(_)) |
1522 ty::ty_infer(ty::FreshIntTy(_)) => {
1523 self.tcx().sess.bug(
1525 "asked to assemble builtin bounds of unexpected type: {}",
1526 self_ty.repr(self.tcx()))[]);
1530 fn nominal<'cx, 'tcx>(this: &mut SelectionContext<'cx, 'tcx>,
1531 bound: ty::BuiltinBound,
1533 types: Vec<Ty<'tcx>>)
1534 -> Result<BuiltinBoundConditions<'tcx>,SelectionError<'tcx>>
1536 // First check for markers and other nonsense.
1537 let tcx = this.tcx();
1541 Some(def_id) == tcx.lang_items.no_send_bound() ||
1542 Some(def_id) == tcx.lang_items.managed_bound()
1544 return Err(Unimplemented)
1549 // This is an Opt-In Built-In Trait. So, unless
1550 // the user is asking for the old behavior, we
1551 // don't supply any form of builtin impl.
1552 if !this.tcx().sess.features.borrow().opt_out_copy {
1553 return Ok(ParameterBuiltin)
1555 // Older, backwards compatibility behavior:
1557 Some(def_id) == tcx.lang_items.no_copy_bound() ||
1558 Some(def_id) == tcx.lang_items.managed_bound() ||
1559 ty::has_dtor(tcx, def_id)
1561 return Err(Unimplemented);
1568 Some(def_id) == tcx.lang_items.no_sync_bound() ||
1569 Some(def_id) == tcx.lang_items.managed_bound() ||
1570 Some(def_id) == tcx.lang_items.unsafe_type()
1572 return Err(Unimplemented)
1576 ty::BoundSized => { }
1583 ///////////////////////////////////////////////////////////////////////////
1586 // Confirmation unifies the output type parameters of the trait
1587 // with the values found in the obligation, possibly yielding a
1588 // type error. See `doc.rs` for more details.
1590 fn confirm_candidate(&mut self,
1591 obligation: &TraitObligation<'tcx>,
1592 candidate: SelectionCandidate<'tcx>)
1593 -> Result<Selection<'tcx>,SelectionError<'tcx>>
1595 debug!("confirm_candidate({}, {})",
1596 obligation.repr(self.tcx()),
1597 candidate.repr(self.tcx()));
1600 BuiltinCandidate(builtin_bound) => {
1602 try!(self.confirm_builtin_candidate(obligation, builtin_bound))))
1606 Ok(VtableBuiltin(VtableBuiltinData { nested: VecPerParamSpace::empty() }))
1609 ParamCandidate(param) => {
1610 self.confirm_param_candidate(obligation, param);
1614 ImplCandidate(impl_def_id) => {
1616 try!(self.confirm_impl_candidate(obligation, impl_def_id));
1617 Ok(VtableImpl(vtable_impl))
1620 UnboxedClosureCandidate(closure_def_id, substs) => {
1621 try!(self.confirm_unboxed_closure_candidate(obligation, closure_def_id, &substs));
1622 Ok(VtableUnboxedClosure(closure_def_id, substs))
1625 ObjectCandidate => {
1626 let data = self.confirm_object_candidate(obligation);
1627 Ok(VtableObject(data))
1630 FnPointerCandidate => {
1632 try!(self.confirm_fn_pointer_candidate(obligation));
1633 Ok(VtableFnPointer(fn_type))
1636 ProjectionCandidate => {
1637 self.confirm_projection_candidate(obligation);
1643 fn confirm_projection_candidate(&mut self,
1644 obligation: &TraitObligation<'tcx>)
1646 let _: Result<(),()> =
1647 self.infcx.try(|snapshot| {
1649 self.match_projection_obligation_against_bounds_from_trait(obligation,
1656 fn confirm_param_candidate(&mut self,
1657 obligation: &TraitObligation<'tcx>,
1658 param: ty::PolyTraitRef<'tcx>)
1660 debug!("confirm_param_candidate({},{})",
1661 obligation.repr(self.tcx()),
1662 param.repr(self.tcx()));
1664 // During evaluation, we already checked that this
1665 // where-clause trait-ref could be unified with the obligation
1666 // trait-ref. Repeat that unification now without any
1667 // transactional boundary; it should not fail.
1668 match self.confirm_poly_trait_refs(obligation.cause.clone(),
1669 obligation.predicate.to_poly_trait_ref(),
1673 self.tcx().sess.bug(
1674 format!("Where clause `{}` was applicable to `{}` but now is not",
1675 param.repr(self.tcx()),
1676 obligation.repr(self.tcx())).as_slice());
1681 fn confirm_builtin_candidate(&mut self,
1682 obligation: &TraitObligation<'tcx>,
1683 bound: ty::BuiltinBound)
1684 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
1685 SelectionError<'tcx>>
1687 debug!("confirm_builtin_candidate({})",
1688 obligation.repr(self.tcx()));
1690 match try!(self.builtin_bound(bound, obligation)) {
1691 If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)),
1692 AmbiguousBuiltin | ParameterBuiltin => {
1693 self.tcx().sess.span_bug(
1694 obligation.cause.span,
1695 format!("builtin bound for {} was ambig",
1696 obligation.repr(self.tcx()))[]);
1701 fn vtable_builtin_data(&mut self,
1702 obligation: &TraitObligation<'tcx>,
1703 bound: ty::BuiltinBound,
1704 nested: Vec<Ty<'tcx>>)
1705 -> VtableBuiltinData<PredicateObligation<'tcx>>
1707 let derived_cause = self.derived_cause(obligation, BuiltinDerivedObligation);
1708 let obligations = nested.iter().map(|&bound_ty| {
1709 // the obligation might be higher-ranked, e.g. for<'a> &'a
1710 // int : Copy. In that case, we will wind up with
1711 // late-bound regions in the `nested` vector. So for each
1712 // one we instantiate to a skolemized region, do our work
1713 // to produce something like `&'0 int : Copy`, and then
1714 // re-bind it. This is a bit of busy-work but preserves
1715 // the invariant that we only manipulate free regions, not
1717 self.infcx.try(|snapshot| {
1718 let (skol_ty, skol_map) =
1719 self.infcx().skolemize_late_bound_regions(&ty::Binder(bound_ty), snapshot);
1720 let skol_predicate =
1721 util::predicate_for_builtin_bound(
1723 derived_cause.clone(),
1725 obligation.recursion_depth + 1,
1727 match skol_predicate {
1728 Ok(skol_predicate) => Ok(self.infcx().plug_leaks(skol_map, snapshot,
1730 Err(ErrorReported) => Err(ErrorReported)
1733 }).collect::<Result<_, _>>();
1734 let mut obligations = match obligations {
1736 Err(ErrorReported) => Vec::new()
1739 // as a special case, `Send` requires `'static`
1740 if bound == ty::BoundSend {
1741 obligations.push(Obligation {
1742 cause: obligation.cause.clone(),
1743 recursion_depth: obligation.recursion_depth+1,
1744 predicate: ty::Binder(ty::OutlivesPredicate(obligation.self_ty(),
1745 ty::ReStatic)).as_predicate(),
1749 let obligations = VecPerParamSpace::new(obligations, Vec::new(), Vec::new());
1751 debug!("vtable_builtin_data: obligations={}",
1752 obligations.repr(self.tcx()));
1754 VtableBuiltinData { nested: obligations }
1757 fn confirm_impl_candidate(&mut self,
1758 obligation: &TraitObligation<'tcx>,
1759 impl_def_id: ast::DefId)
1760 -> Result<VtableImplData<'tcx, PredicateObligation<'tcx>>,
1761 SelectionError<'tcx>>
1763 debug!("confirm_impl_candidate({},{})",
1764 obligation.repr(self.tcx()),
1765 impl_def_id.repr(self.tcx()));
1767 // First, create the substitutions by matching the impl again,
1768 // this time not in a probe.
1769 self.infcx.try(|snapshot| {
1770 let (skol_obligation_trait_ref, skol_map) =
1771 self.infcx().skolemize_late_bound_regions(&obligation.predicate, snapshot);
1773 self.rematch_impl(impl_def_id, obligation,
1774 snapshot, &skol_map, skol_obligation_trait_ref.trait_ref);
1775 debug!("confirm_impl_candidate substs={}", substs);
1776 Ok(self.vtable_impl(impl_def_id, substs, obligation.cause.clone(),
1777 obligation.recursion_depth + 1, skol_map, snapshot))
1781 fn vtable_impl(&mut self,
1782 impl_def_id: ast::DefId,
1783 substs: Substs<'tcx>,
1784 cause: ObligationCause<'tcx>,
1785 recursion_depth: uint,
1786 skol_map: infer::SkolemizationMap,
1787 snapshot: &infer::CombinedSnapshot)
1788 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
1790 debug!("vtable_impl(impl_def_id={}, substs={}, recursion_depth={}, skol_map={})",
1791 impl_def_id.repr(self.tcx()),
1792 substs.repr(self.tcx()),
1794 skol_map.repr(self.tcx()));
1796 let impl_predicates =
1797 self.impl_predicates(cause,
1804 debug!("vtable_impl: impl_def_id={} impl_predicates={}",
1805 impl_def_id.repr(self.tcx()),
1806 impl_predicates.repr(self.tcx()));
1808 VtableImplData { impl_def_id: impl_def_id,
1810 nested: impl_predicates }
1813 fn confirm_object_candidate(&mut self,
1814 obligation: &TraitObligation<'tcx>)
1815 -> VtableObjectData<'tcx>
1817 debug!("confirm_object_candidate({})",
1818 obligation.repr(self.tcx()));
1820 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1821 let poly_trait_ref = match self_ty.sty {
1822 ty::ty_trait(ref data) => {
1823 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
1826 self.tcx().sess.span_bug(obligation.cause.span,
1827 "object candidate with non-object");
1831 let obligation_def_id = obligation.predicate.def_id();
1832 let upcast_trait_ref = match util::upcast(self.tcx(),
1833 poly_trait_ref.clone(),
1834 obligation_def_id) {
1837 self.tcx().sess.span_bug(obligation.cause.span,
1838 format!("unable to upcast from {} to {}",
1839 poly_trait_ref.repr(self.tcx()),
1840 obligation_def_id.repr(self.tcx())).as_slice());
1844 match self.match_poly_trait_ref(obligation, upcast_trait_ref) {
1847 self.tcx().sess.span_bug(obligation.cause.span,
1848 "failed to match trait refs");
1852 VtableObjectData { object_ty: self_ty }
1855 fn confirm_fn_pointer_candidate(&mut self,
1856 obligation: &TraitObligation<'tcx>)
1857 -> Result<ty::Ty<'tcx>,SelectionError<'tcx>>
1859 debug!("confirm_fn_pointer_candidate({})",
1860 obligation.repr(self.tcx()));
1862 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1863 let sig = match self_ty.sty {
1864 ty::ty_bare_fn(_, &ty::BareFnTy {
1865 unsafety: ast::Unsafety::Normal,
1872 self.tcx().sess.span_bug(
1873 obligation.cause.span,
1874 format!("Fn pointer candidate for inappropriate self type: {}",
1875 self_ty.repr(self.tcx()))[]);
1879 let arguments_tuple = ty::mk_tup(self.tcx(), sig.0.inputs.to_vec());
1880 let output_type = sig.0.output.unwrap();
1883 vec![arguments_tuple, output_type],
1886 let trait_ref = ty::Binder(Rc::new(ty::TraitRef {
1887 def_id: obligation.predicate.def_id(),
1888 substs: self.tcx().mk_substs(substs),
1891 try!(self.confirm_poly_trait_refs(obligation.cause.clone(),
1892 obligation.predicate.to_poly_trait_ref(),
1897 fn confirm_unboxed_closure_candidate(&mut self,
1898 obligation: &TraitObligation<'tcx>,
1899 closure_def_id: ast::DefId,
1900 substs: &Substs<'tcx>)
1901 -> Result<(),SelectionError<'tcx>>
1903 debug!("confirm_unboxed_closure_candidate({},{},{})",
1904 obligation.repr(self.tcx()),
1905 closure_def_id.repr(self.tcx()),
1906 substs.repr(self.tcx()));
1908 let closure_type = self.closure_typer.unboxed_closure_type(closure_def_id, substs);
1910 debug!("confirm_unboxed_closure_candidate: closure_def_id={} closure_type={}",
1911 closure_def_id.repr(self.tcx()),
1912 closure_type.repr(self.tcx()));
1914 let closure_sig = &closure_type.sig;
1915 let arguments_tuple = closure_sig.0.inputs[0];
1918 vec![arguments_tuple, closure_sig.0.output.unwrap()],
1920 obligation.self_ty());
1921 let trait_ref = ty::Binder(Rc::new(ty::TraitRef {
1922 def_id: obligation.predicate.def_id(),
1923 substs: self.tcx().mk_substs(trait_substs),
1926 debug!("confirm_unboxed_closure_candidate(closure_def_id={}, trait_ref={})",
1927 closure_def_id.repr(self.tcx()),
1928 trait_ref.repr(self.tcx()));
1930 self.confirm_poly_trait_refs(obligation.cause.clone(),
1931 obligation.predicate.to_poly_trait_ref(),
1935 /// In the case of unboxed closure types and fn pointers,
1936 /// we currently treat the input type parameters on the trait as
1937 /// outputs. This means that when we have a match we have only
1938 /// considered the self type, so we have to go back and make sure
1939 /// to relate the argument types too. This is kind of wrong, but
1940 /// since we control the full set of impls, also not that wrong,
1941 /// and it DOES yield better error messages (since we don't report
1942 /// errors as if there is no applicable impl, but rather report
1943 /// errors are about mismatched argument types.
1945 /// Here is an example. Imagine we have an unboxed closure expression
1946 /// and we desugared it so that the type of the expression is
1947 /// `Closure`, and `Closure` expects an int as argument. Then it
1948 /// is "as if" the compiler generated this impl:
1950 /// impl Fn(int) for Closure { ... }
1952 /// Now imagine our obligation is `Fn(uint) for Closure`. So far
1953 /// we have matched the self-type `Closure`. At this point we'll
1954 /// compare the `int` to `uint` and generate an error.
1956 /// Note that this checking occurs *after* the impl has selected,
1957 /// because these output type parameters should not affect the
1958 /// selection of the impl. Therefore, if there is a mismatch, we
1959 /// report an error to the user.
1960 fn confirm_poly_trait_refs(&mut self,
1961 obligation_cause: ObligationCause,
1962 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
1963 expected_trait_ref: ty::PolyTraitRef<'tcx>)
1964 -> Result<(), SelectionError<'tcx>>
1966 let origin = infer::RelateOutputImplTypes(obligation_cause.span);
1968 let obligation_trait_ref = obligation_trait_ref.clone();
1969 match self.infcx.sub_poly_trait_refs(false,
1971 expected_trait_ref.clone(),
1972 obligation_trait_ref.clone()) {
1974 Err(e) => Err(OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
1978 ///////////////////////////////////////////////////////////////////////////
1981 // Matching is a common path used for both evaluation and
1982 // confirmation. It basically unifies types that appear in impls
1983 // and traits. This does affect the surrounding environment;
1984 // therefore, when used during evaluation, match routines must be
1985 // run inside of a `probe()` so that their side-effects are
1988 fn rematch_impl(&mut self,
1989 impl_def_id: ast::DefId,
1990 obligation: &TraitObligation<'tcx>,
1991 snapshot: &infer::CombinedSnapshot,
1992 skol_map: &infer::SkolemizationMap,
1993 skol_obligation_trait_ref: Rc<ty::TraitRef<'tcx>>)
1996 match self.match_impl(impl_def_id, obligation, snapshot,
1997 skol_map, skol_obligation_trait_ref) {
2002 self.tcx().sess.bug(
2003 format!("Impl {} was matchable against {} but now is not",
2004 impl_def_id.repr(self.tcx()),
2005 obligation.repr(self.tcx()))[]);
2010 fn match_impl(&mut self,
2011 impl_def_id: ast::DefId,
2012 obligation: &TraitObligation<'tcx>,
2013 snapshot: &infer::CombinedSnapshot,
2014 skol_map: &infer::SkolemizationMap,
2015 skol_obligation_trait_ref: Rc<ty::TraitRef<'tcx>>)
2016 -> Result<Substs<'tcx>, ()>
2018 let impl_trait_ref = ty::impl_trait_ref(self.tcx(), impl_def_id).unwrap();
2020 // Before we create the substitutions and everything, first
2021 // consider a "quick reject". This avoids creating more types
2022 // and so forth that we need to.
2023 if self.fast_reject_trait_refs(obligation, &*impl_trait_ref) {
2027 let impl_substs = util::fresh_substs_for_impl(self.infcx,
2028 obligation.cause.span,
2031 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2034 debug!("match_impl(impl_def_id={}, obligation={}, \
2035 impl_trait_ref={}, skol_obligation_trait_ref={})",
2036 impl_def_id.repr(self.tcx()),
2037 obligation.repr(self.tcx()),
2038 impl_trait_ref.repr(self.tcx()),
2039 skol_obligation_trait_ref.repr(self.tcx()));
2041 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
2042 match self.infcx.sub_trait_refs(false,
2045 skol_obligation_trait_ref) {
2048 debug!("match_impl: failed sub_trait_refs due to `{}`",
2049 ty::type_err_to_str(self.tcx(), &e));
2054 match self.infcx.leak_check(skol_map, snapshot) {
2057 debug!("match_impl: failed leak check due to `{}`",
2058 ty::type_err_to_str(self.tcx(), &e));
2063 debug!("match_impl: success impl_substs={}", impl_substs.repr(self.tcx()));
2067 fn fast_reject_trait_refs(&mut self,
2068 obligation: &TraitObligation,
2069 impl_trait_ref: &ty::TraitRef)
2072 // We can avoid creating type variables and doing the full
2073 // substitution if we find that any of the input types, when
2074 // simplified, do not match.
2076 obligation.predicate.0.input_types().iter()
2077 .zip(impl_trait_ref.input_types().iter())
2078 .any(|(&obligation_ty, &impl_ty)| {
2079 let simplified_obligation_ty =
2080 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2081 let simplified_impl_ty =
2082 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2084 simplified_obligation_ty.is_some() &&
2085 simplified_impl_ty.is_some() &&
2086 simplified_obligation_ty != simplified_impl_ty
2090 fn match_poly_trait_ref(&mut self,
2091 obligation: &TraitObligation<'tcx>,
2092 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2095 debug!("match_poly_trait_ref: obligation={} where_clause_trait_ref={}",
2096 obligation.repr(self.tcx()),
2097 where_clause_trait_ref.repr(self.tcx()));
2099 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
2100 match self.infcx.sub_poly_trait_refs(false,
2102 where_clause_trait_ref,
2103 obligation.predicate.to_poly_trait_ref()) {
2109 /// Determines whether the self type declared against
2110 /// `impl_def_id` matches `obligation_self_ty`. If successful,
2111 /// returns the substitutions used to make them match. See
2112 /// `match_impl()`. For example, if `impl_def_id` is declared
2115 /// impl<T:Copy> Foo for ~T { ... }
2117 /// and `obligation_self_ty` is `int`, we'd back an `Err(_)`
2118 /// result. But if `obligation_self_ty` were `~int`, we'd get
2119 /// back `Ok(T=int)`.
2120 fn match_inherent_impl(&mut self,
2121 impl_def_id: ast::DefId,
2122 obligation_cause: &ObligationCause,
2123 obligation_self_ty: Ty<'tcx>)
2124 -> Result<Substs<'tcx>,()>
2126 // Create fresh type variables for each type parameter declared
2128 let impl_substs = util::fresh_substs_for_impl(self.infcx,
2129 obligation_cause.span,
2132 // Find the self type for the impl.
2133 let impl_self_ty = ty::lookup_item_type(self.tcx(), impl_def_id).ty;
2134 let impl_self_ty = impl_self_ty.subst(self.tcx(), &impl_substs);
2136 debug!("match_impl_self_types(obligation_self_ty={}, impl_self_ty={})",
2137 obligation_self_ty.repr(self.tcx()),
2138 impl_self_ty.repr(self.tcx()));
2140 match self.match_self_types(obligation_cause,
2142 obligation_self_ty) {
2144 debug!("Matched impl_substs={}", impl_substs.repr(self.tcx()));
2154 fn match_self_types(&mut self,
2155 cause: &ObligationCause,
2157 // The self type provided by the impl/caller-obligation:
2158 provided_self_ty: Ty<'tcx>,
2160 // The self type the obligation is for:
2161 required_self_ty: Ty<'tcx>)
2164 // FIXME(#5781) -- equating the types is stronger than
2165 // necessary. Should consider variance of trait w/r/t Self.
2167 let origin = infer::RelateSelfType(cause.span);
2168 match self.infcx.eq_types(false,
2177 ///////////////////////////////////////////////////////////////////////////
2180 fn push_stack<'o,'s:'o>(&mut self,
2181 previous_stack: Option<&'s TraitObligationStack<'s, 'tcx>>,
2182 obligation: &'o TraitObligation<'tcx>)
2183 -> TraitObligationStack<'o, 'tcx>
2185 let fresh_trait_ref =
2186 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2188 TraitObligationStack {
2189 obligation: obligation,
2190 fresh_trait_ref: fresh_trait_ref,
2191 previous: previous_stack.map(|p| p), // FIXME variance
2195 /// Returns set of all impls for a given trait.
2196 fn all_impls(&self, trait_def_id: ast::DefId) -> Vec<ast::DefId> {
2197 ty::populate_implementations_for_trait_if_necessary(self.tcx(),
2199 match self.tcx().trait_impls.borrow().get(&trait_def_id) {
2201 Some(impls) => impls.borrow().clone()
2205 fn impl_predicates(&mut self,
2206 cause: ObligationCause<'tcx>,
2207 recursion_depth: uint,
2208 impl_def_id: ast::DefId,
2209 impl_substs: &Substs<'tcx>,
2210 skol_map: infer::SkolemizationMap,
2211 snapshot: &infer::CombinedSnapshot)
2212 -> VecPerParamSpace<PredicateObligation<'tcx>>
2214 let impl_generics = ty::lookup_item_type(self.tcx(), impl_def_id).generics;
2215 let bounds = impl_generics.to_bounds(self.tcx(), impl_substs);
2216 let normalized_bounds =
2217 project::normalize_with_depth(self, cause.clone(), recursion_depth, &bounds);
2218 let normalized_bounds =
2219 self.infcx().plug_leaks(skol_map, snapshot, &normalized_bounds);
2220 let mut impl_obligations =
2221 util::predicates_for_generics(self.tcx(),
2224 &normalized_bounds.value);
2225 for obligation in normalized_bounds.obligations.into_iter() {
2226 impl_obligations.push(TypeSpace, obligation);
2231 fn fn_family_trait_kind(&self,
2232 trait_def_id: ast::DefId)
2233 -> Option<ty::UnboxedClosureKind>
2235 let tcx = self.tcx();
2236 if Some(trait_def_id) == tcx.lang_items.fn_trait() {
2237 Some(ty::FnUnboxedClosureKind)
2238 } else if Some(trait_def_id) == tcx.lang_items.fn_mut_trait() {
2239 Some(ty::FnMutUnboxedClosureKind)
2240 } else if Some(trait_def_id) == tcx.lang_items.fn_once_trait() {
2241 Some(ty::FnOnceUnboxedClosureKind)
2247 #[allow(unused_comparisons)]
2248 fn derived_cause(&self,
2249 obligation: &TraitObligation<'tcx>,
2250 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2251 -> ObligationCause<'tcx>
2254 * Creates a cause for obligations that are derived from
2255 * `obligation` by a recursive search (e.g., for a builtin
2256 * bound, or eventually a `impl Foo for ..`). If `obligation`
2257 * is itself a derived obligation, this is just a clone, but
2258 * otherwise we create a "derived obligation" cause so as to
2259 * keep track of the original root obligation for error
2263 // NOTE(flaper87): As of now, it keeps track of the whole error
2264 // chain. Ideally, we should have a way to configure this either
2265 // by using -Z verbose or just a CLI argument.
2266 if obligation.recursion_depth >= 0 {
2267 let derived_cause = DerivedObligationCause {
2268 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2269 parent_code: Rc::new(obligation.cause.code.clone()),
2271 ObligationCause::new(obligation.cause.span,
2272 obligation.cause.body_id,
2273 variant(derived_cause))
2275 obligation.cause.clone()
2280 impl<'tcx> Repr<'tcx> for SelectionCandidate<'tcx> {
2281 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
2283 ErrorCandidate => format!("ErrorCandidate"),
2284 BuiltinCandidate(b) => format!("BuiltinCandidate({})", b),
2285 ParamCandidate(ref a) => format!("ParamCandidate({})", a.repr(tcx)),
2286 ImplCandidate(a) => format!("ImplCandidate({})", a.repr(tcx)),
2287 ProjectionCandidate => format!("ProjectionCandidate"),
2288 FnPointerCandidate => format!("FnPointerCandidate"),
2289 ObjectCandidate => {
2290 format!("ObjectCandidate")
2292 UnboxedClosureCandidate(c, ref s) => {
2293 format!("UnboxedClosureCandidate({},{})", c, s.repr(tcx))
2299 impl<'tcx> SelectionCache<'tcx> {
2300 pub fn new() -> SelectionCache<'tcx> {
2302 hashmap: RefCell::new(HashMap::new())
2307 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2308 fn iter(&self) -> Option<&TraitObligationStack<'o, 'tcx>> {
2313 impl<'o, 'tcx> Iterator for Option<&'o TraitObligationStack<'o, 'tcx>> {
2314 type Item = &'o TraitObligationStack<'o,'tcx>;
2316 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2329 impl<'o, 'tcx> Repr<'tcx> for TraitObligationStack<'o, 'tcx> {
2330 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
2331 format!("TraitObligationStack({})",
2332 self.obligation.repr(tcx))
2336 impl<'tcx> EvaluationResult<'tcx> {
2337 fn may_apply(&self) -> bool {
2341 EvaluatedToErr(Overflow) |
2342 EvaluatedToErr(OutputTypeParameterMismatch(..)) => {
2345 EvaluatedToErr(Unimplemented) => {
2352 impl MethodMatchResult {
2353 pub fn may_apply(&self) -> bool {
2355 MethodMatched(_) => true,
2356 MethodAmbiguous(_) => true,
2357 MethodDidNotMatch => false,