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 `README.md` 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::*;
21 use super::DerivedObligationCause;
23 use super::project::{normalize_with_depth, Normalized};
24 use super::{PredicateObligation, TraitObligation, ObligationCause};
25 use super::report_overflow_error;
26 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
27 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
28 use super::{ObjectCastObligation, Obligation};
29 use super::TraitNotObjectSafe;
30 use super::RFC1214Warning;
32 use super::SelectionResult;
33 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure,
34 VtableFnPointer, VtableObject, VtableDefaultImpl};
35 use super::{VtableImplData, VtableObjectData, VtableBuiltinData,
36 VtableClosureData, VtableDefaultImplData};
37 use super::object_safety;
40 use metadata::cstore::LOCAL_CRATE;
41 use middle::def_id::DefId;
43 use middle::infer::{InferCtxt, TypeFreshener};
44 use middle::subst::{Subst, Substs, TypeSpace};
45 use middle::ty::{self, ToPredicate, RegionEscape, ToPolyTraitRef, Ty, HasTypeFlags};
46 use middle::ty::fast_reject;
47 use middle::ty::fold::TypeFoldable;
48 use middle::ty::relate::TypeRelation;
50 use std::cell::RefCell;
55 use util::common::ErrorReported;
56 use util::nodemap::FnvHashMap;
58 pub struct SelectionContext<'cx, 'tcx:'cx> {
59 infcx: &'cx InferCtxt<'cx, 'tcx>,
61 /// Freshener used specifically for skolemizing entries on the
62 /// obligation stack. This ensures that all entries on the stack
63 /// at one time will have the same set of skolemized entries,
64 /// which is important for checking for trait bounds that
65 /// recursively require themselves.
66 freshener: TypeFreshener<'cx, 'tcx>,
68 /// If true, indicates that the evaluation should be conservative
69 /// and consider the possibility of types outside this crate.
70 /// This comes up primarily when resolving ambiguity. Imagine
71 /// there is some trait reference `$0 : Bar` where `$0` is an
72 /// inference variable. If `intercrate` is true, then we can never
73 /// say for sure that this reference is not implemented, even if
74 /// there are *no impls at all for `Bar`*, because `$0` could be
75 /// bound to some type that in a downstream crate that implements
76 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
77 /// though, we set this to false, because we are only interested
78 /// in types that the user could actually have written --- in
79 /// other words, we consider `$0 : Bar` to be unimplemented if
80 /// there is no type that the user could *actually name* that
81 /// would satisfy it. This avoids crippling inference, basically.
86 // A stack that walks back up the stack frame.
87 struct TraitObligationStack<'prev, 'tcx: 'prev> {
88 obligation: &'prev TraitObligation<'tcx>,
90 /// Trait ref from `obligation` but skolemized with the
91 /// selection-context's freshener. Used to check for recursion.
92 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
94 previous: TraitObligationStackList<'prev, 'tcx>,
98 pub struct SelectionCache<'tcx> {
99 hashmap: RefCell<FnvHashMap<ty::TraitRef<'tcx>,
100 SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
103 pub enum MethodMatchResult {
104 MethodMatched(MethodMatchedData),
105 MethodAmbiguous(/* list of impls that could apply */ Vec<DefId>),
109 #[derive(Copy, Clone, Debug)]
110 pub enum MethodMatchedData {
111 // In the case of a precise match, we don't really need to store
112 // how the match was found. So don't.
115 // In the case of a coercion, we need to know the precise impl so
116 // that we can determine the type to which things were coerced.
117 CoerciveMethodMatch(/* impl we matched */ DefId)
120 /// The selection process begins by considering all impls, where
121 /// clauses, and so forth that might resolve an obligation. Sometimes
122 /// we'll be able to say definitively that (e.g.) an impl does not
123 /// apply to the obligation: perhaps it is defined for `usize` but the
124 /// obligation is for `int`. In that case, we drop the impl out of the
125 /// list. But the other cases are considered *candidates*.
127 /// For selection to succeed, there must be exactly one matching
128 /// candidate. If the obligation is fully known, this is guaranteed
129 /// by coherence. However, if the obligation contains type parameters
130 /// or variables, there may be multiple such impls.
132 /// It is not a real problem if multiple matching impls exist because
133 /// of type variables - it just means the obligation isn't sufficiently
134 /// elaborated. In that case we report an ambiguity, and the caller can
135 /// try again after more type information has been gathered or report a
136 /// "type annotations required" error.
138 /// However, with type parameters, this can be a real problem - type
139 /// parameters don't unify with regular types, but they *can* unify
140 /// with variables from blanket impls, and (unless we know its bounds
141 /// will always be satisfied) picking the blanket impl will be wrong
142 /// for at least *some* substitutions. To make this concrete, if we have
144 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
145 /// impl<T: fmt::Debug> AsDebug for T {
147 /// fn debug(self) -> fmt::Debug { self }
149 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
151 /// we can't just use the impl to resolve the <T as AsDebug> obligation
152 /// - a type from another crate (that doesn't implement fmt::Debug) could
153 /// implement AsDebug.
155 /// Because where-clauses match the type exactly, multiple clauses can
156 /// only match if there are unresolved variables, and we can mostly just
157 /// report this ambiguity in that case. This is still a problem - we can't
158 /// *do anything* with ambiguities that involve only regions. This is issue
161 /// If a single where-clause matches and there are no inference
162 /// variables left, then it definitely matches and we can just select
165 /// In fact, we even select the where-clause when the obligation contains
166 /// inference variables. The can lead to inference making "leaps of logic",
167 /// for example in this situation:
169 /// pub trait Foo<T> { fn foo(&self) -> T; }
170 /// impl<T> Foo<()> for T { fn foo(&self) { } }
171 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
173 /// pub fn foo<T>(t: T) where T: Foo<bool> {
174 /// println!("{:?}", <T as Foo<_>>::foo(&t));
176 /// fn main() { foo(false); }
178 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
179 /// impl and the where-clause. We select the where-clause and unify $0=bool,
180 /// so the program prints "false". However, if the where-clause is omitted,
181 /// the blanket impl is selected, we unify $0=(), and the program prints
184 /// Exactly the same issues apply to projection and object candidates, except
185 /// that we can have both a projection candidate and a where-clause candidate
186 /// for the same obligation. In that case either would do (except that
187 /// different "leaps of logic" would occur if inference variables are
188 /// present), and we just pick the where-clause. This is, for example,
189 /// required for associated types to work in default impls, as the bounds
190 /// are visible both as projection bounds and as where-clauses from the
191 /// parameter environment.
192 #[derive(PartialEq,Eq,Debug,Clone)]
193 enum SelectionCandidate<'tcx> {
195 BuiltinCandidate(ty::BuiltinBound),
196 ParamCandidate(ty::PolyTraitRef<'tcx>),
197 ImplCandidate(DefId),
198 DefaultImplCandidate(DefId),
199 DefaultImplObjectCandidate(DefId),
201 /// This is a trait matching with a projected type as `Self`, and
202 /// we found an applicable bound in the trait definition.
205 /// Implementation of a `Fn`-family trait by one of the
206 /// anonymous types generated for a `||` expression.
207 ClosureCandidate(/* closure */ DefId, &'tcx ty::ClosureSubsts<'tcx>),
209 /// Implementation of a `Fn`-family trait by one of the anonymous
210 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
215 BuiltinObjectCandidate,
217 BuiltinUnsizeCandidate,
222 struct SelectionCandidateSet<'tcx> {
223 // a list of candidates that definitely apply to the current
224 // obligation (meaning: types unify).
225 vec: Vec<SelectionCandidate<'tcx>>,
227 // if this is true, then there were candidates that might or might
228 // not have applied, but we couldn't tell. This occurs when some
229 // of the input types are type variables, in which case there are
230 // various "builtin" rules that might or might not trigger.
234 enum BuiltinBoundConditions<'tcx> {
235 If(ty::Binder<Vec<Ty<'tcx>>>),
241 enum EvaluationResult<'tcx> {
244 EvaluatedToErr(SelectionError<'tcx>),
247 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
248 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>)
249 -> SelectionContext<'cx, 'tcx> {
252 freshener: infcx.freshener(),
257 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>)
258 -> SelectionContext<'cx, 'tcx> {
261 freshener: infcx.freshener(),
266 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
270 pub fn tcx(&self) -> &'cx ty::ctxt<'tcx> {
274 pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'cx, 'tcx> {
275 self.infcx.param_env()
278 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
282 ///////////////////////////////////////////////////////////////////////////
285 // The selection phase tries to identify *how* an obligation will
286 // be resolved. For example, it will identify which impl or
287 // parameter bound is to be used. The process can be inconclusive
288 // if the self type in the obligation is not fully inferred. Selection
289 // can result in an error in one of two ways:
291 // 1. If no applicable impl or parameter bound can be found.
292 // 2. If the output type parameters in the obligation do not match
293 // those specified by the impl/bound. For example, if the obligation
294 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
295 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
297 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
298 /// type environment by performing unification.
299 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
300 -> SelectionResult<'tcx, Selection<'tcx>> {
301 debug!("select({:?})", obligation);
302 assert!(!obligation.predicate.has_escaping_regions());
304 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
305 match try!(self.candidate_from_obligation(&stack)) {
307 self.consider_unification_despite_ambiguity(obligation);
310 Some(candidate) => Ok(Some(try!(self.confirm_candidate(obligation, candidate)))),
314 /// In the particular case of unboxed closure obligations, we can
315 /// sometimes do some amount of unification for the
316 /// argument/return types even though we can't yet fully match obligation.
317 /// The particular case we are interesting in is an obligation of the form:
321 /// where `C` is an unboxed closure type and `FnFoo` is one of the
322 /// `Fn` traits. Because we know that users cannot write impls for closure types
323 /// themselves, the only way that `C : FnFoo` can fail to match is under two
326 /// 1. The closure kind for `C` is not yet known, because inference isn't complete.
327 /// 2. The closure kind for `C` *is* known, but doesn't match what is needed.
328 /// For example, `C` may be a `FnOnce` closure, but a `Fn` closure is needed.
330 /// In either case, we always know what argument types are
331 /// expected by `C`, no matter what kind of `Fn` trait it
332 /// eventually matches. So we can go ahead and unify the argument
333 /// types, even though the end result is ambiguous.
335 /// Note that this is safe *even if* the trait would never be
336 /// matched (case 2 above). After all, in that case, an error will
337 /// result, so it kind of doesn't matter what we do --- unifying
338 /// the argument types can only be helpful to the user, because
339 /// once they patch up the kind of closure that is expected, the
340 /// argment types won't really change.
341 fn consider_unification_despite_ambiguity(&mut self, obligation: &TraitObligation<'tcx>) {
342 // Is this a `C : FnFoo(...)` trait reference for some trait binding `FnFoo`?
343 match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
348 // Is the self-type a closure type? We ignore bindings here
349 // because if it is a closure type, it must be a closure type from
350 // within this current fn, and hence none of the higher-ranked
351 // lifetimes can appear inside the self-type.
352 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
353 let (closure_def_id, substs) = match self_ty.sty {
354 ty::TyClosure(id, ref substs) => (id, substs),
357 assert!(!substs.has_escaping_regions());
359 // It is OK to call the unnormalized variant here - this is only
360 // reached for TyClosure: Fn inputs where the closure kind is
361 // still unknown, which should only occur in typeck where the
362 // closure type is already normalized.
363 let closure_trait_ref = self.closure_trait_ref_unnormalized(obligation,
367 match self.confirm_poly_trait_refs(obligation.cause.clone(),
368 obligation.predicate.to_poly_trait_ref(),
371 Err(_) => { /* Silently ignore errors. */ }
375 ///////////////////////////////////////////////////////////////////////////
378 // Tests whether an obligation can be selected or whether an impl
379 // can be applied to particular types. It skips the "confirmation"
380 // step and hence completely ignores output type parameters.
382 // The result is "true" if the obligation *may* hold and "false" if
383 // we can be sure it does not.
385 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
386 pub fn evaluate_obligation(&mut self,
387 obligation: &PredicateObligation<'tcx>)
390 debug!("evaluate_obligation({:?})",
393 self.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
397 fn evaluate_builtin_bound_recursively<'o>(&mut self,
398 bound: ty::BuiltinBound,
399 previous_stack: &TraitObligationStack<'o, 'tcx>,
401 -> EvaluationResult<'tcx>
404 util::predicate_for_builtin_bound(
406 previous_stack.obligation.cause.clone(),
408 previous_stack.obligation.recursion_depth + 1,
413 self.evaluate_predicate_recursively(previous_stack.list(), &obligation)
415 Err(ErrorReported) => {
421 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
422 stack: TraitObligationStackList<'o, 'tcx>,
424 -> EvaluationResult<'tcx>
425 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
427 let mut result = EvaluatedToOk;
428 for obligation in predicates {
429 match self.evaluate_predicate_recursively(stack, obligation) {
430 EvaluatedToErr(e) => { return EvaluatedToErr(e); }
431 EvaluatedToAmbig => { result = EvaluatedToAmbig; }
438 fn evaluate_predicate_recursively<'o>(&mut self,
439 previous_stack: TraitObligationStackList<'o, 'tcx>,
440 obligation: &PredicateObligation<'tcx>)
441 -> EvaluationResult<'tcx>
443 debug!("evaluate_predicate_recursively({:?})",
446 // Check the cache from the tcx of predicates that we know
447 // have been proven elsewhere. This cache only contains
448 // predicates that are global in scope and hence unaffected by
449 // the current environment.
450 let w = RFC1214Warning(false);
451 if self.tcx().fulfilled_predicates.borrow().is_duplicate(w, &obligation.predicate) {
452 return EvaluatedToOk;
455 match obligation.predicate {
456 ty::Predicate::Trait(ref t) => {
457 assert!(!t.has_escaping_regions());
458 let obligation = obligation.with(t.clone());
459 self.evaluate_obligation_recursively(previous_stack, &obligation)
462 ty::Predicate::Equate(ref p) => {
463 let result = self.infcx.probe(|_| {
464 self.infcx.equality_predicate(obligation.cause.span, p)
467 Ok(()) => EvaluatedToOk,
468 Err(_) => EvaluatedToErr(Unimplemented),
472 ty::Predicate::WellFormed(ty) => {
473 match ty::wf::obligations(self.infcx, obligation.cause.body_id,
474 ty, obligation.cause.span,
475 obligation.cause.code.is_rfc1214()) {
477 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
483 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
484 // we do not consider region relationships when
485 // evaluating trait matches
489 ty::Predicate::ObjectSafe(trait_def_id) => {
490 if object_safety::is_object_safe(self.tcx(), trait_def_id) {
493 EvaluatedToErr(Unimplemented)
497 ty::Predicate::Projection(ref data) => {
498 self.infcx.probe(|_| {
499 let project_obligation = obligation.with(data.clone());
500 match project::poly_project_and_unify_type(self, &project_obligation) {
501 Ok(Some(subobligations)) => {
502 self.evaluate_predicates_recursively(previous_stack,
503 subobligations.iter())
509 EvaluatedToErr(Unimplemented)
517 fn evaluate_obligation_recursively<'o>(&mut self,
518 previous_stack: TraitObligationStackList<'o, 'tcx>,
519 obligation: &TraitObligation<'tcx>)
520 -> EvaluationResult<'tcx>
522 debug!("evaluate_obligation_recursively({:?})",
525 let stack = self.push_stack(previous_stack, obligation);
527 let result = self.evaluate_stack(&stack);
529 debug!("result: {:?}", result);
533 fn evaluate_stack<'o>(&mut self,
534 stack: &TraitObligationStack<'o, 'tcx>)
535 -> EvaluationResult<'tcx>
537 // In intercrate mode, whenever any of the types are unbound,
538 // there can always be an impl. Even if there are no impls in
539 // this crate, perhaps the type would be unified with
540 // something from another crate that does provide an impl.
542 // In intracrate mode, we must still be conservative. The reason is
543 // that we want to avoid cycles. Imagine an impl like:
545 // impl<T:Eq> Eq for Vec<T>
547 // and a trait reference like `$0 : Eq` where `$0` is an
548 // unbound variable. When we evaluate this trait-reference, we
549 // will unify `$0` with `Vec<$1>` (for some fresh variable
550 // `$1`), on the condition that `$1 : Eq`. We will then wind
551 // up with many candidates (since that are other `Eq` impls
552 // that apply) and try to winnow things down. This results in
553 // a recursive evaluation that `$1 : Eq` -- as you can
554 // imagine, this is just where we started. To avoid that, we
555 // check for unbound variables and return an ambiguous (hence possible)
556 // match if we've seen this trait before.
558 // This suffices to allow chains like `FnMut` implemented in
559 // terms of `Fn` etc, but we could probably make this more
561 let input_types = stack.fresh_trait_ref.0.input_types();
562 let unbound_input_types = input_types.iter().any(|ty| ty.is_fresh());
564 unbound_input_types &&
566 stack.iter().skip(1).any(
567 |prev| self.match_fresh_trait_refs(&stack.fresh_trait_ref,
568 &prev.fresh_trait_ref)))
570 debug!("evaluate_stack({:?}) --> unbound argument, recursion --> ambiguous",
571 stack.fresh_trait_ref);
572 return EvaluatedToAmbig;
575 // If there is any previous entry on the stack that precisely
576 // matches this obligation, then we can assume that the
577 // obligation is satisfied for now (still all other conditions
578 // must be met of course). One obvious case this comes up is
579 // marker traits like `Send`. Think of a linked list:
581 // struct List<T> { data: T, next: Option<Box<List<T>>> {
583 // `Box<List<T>>` will be `Send` if `T` is `Send` and
584 // `Option<Box<List<T>>>` is `Send`, and in turn
585 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
588 // Note that we do this comparison using the `fresh_trait_ref`
589 // fields. Because these have all been skolemized using
590 // `self.freshener`, we can be sure that (a) this will not
591 // affect the inferencer state and (b) that if we see two
592 // skolemized types with the same index, they refer to the
593 // same unbound type variable.
596 .skip(1) // skip top-most frame
597 .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref)
599 debug!("evaluate_stack({:?}) --> recursive",
600 stack.fresh_trait_ref);
601 return EvaluatedToOk;
604 match self.candidate_from_obligation(stack) {
605 Ok(Some(c)) => self.winnow_candidate(stack, &c),
606 Ok(None) => EvaluatedToAmbig,
607 Err(e) => EvaluatedToErr(e),
611 /// Evaluates whether the impl with id `impl_def_id` could be applied to the self type
612 /// `obligation_self_ty`. This can be used either for trait or inherent impls.
613 pub fn evaluate_impl(&mut self,
615 obligation: &TraitObligation<'tcx>)
618 debug!("evaluate_impl(impl_def_id={:?}, obligation={:?})",
622 self.infcx.probe(|snapshot| {
623 match self.match_impl(impl_def_id, obligation, snapshot) {
624 Ok((substs, skol_map)) => {
625 let vtable_impl = self.vtable_impl(impl_def_id,
627 obligation.cause.clone(),
628 obligation.recursion_depth + 1,
631 self.winnow_selection(TraitObligationStackList::empty(),
632 VtableImpl(vtable_impl)).may_apply()
641 ///////////////////////////////////////////////////////////////////////////
642 // CANDIDATE ASSEMBLY
644 // The selection process begins by examining all in-scope impls,
645 // caller obligations, and so forth and assembling a list of
646 // candidates. See `README.md` and the `Candidate` type for more
649 fn candidate_from_obligation<'o>(&mut self,
650 stack: &TraitObligationStack<'o, 'tcx>)
651 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
653 // Watch out for overflow. This intentionally bypasses (and does
654 // not update) the cache.
655 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
656 if stack.obligation.recursion_depth >= recursion_limit {
657 report_overflow_error(self.infcx(), &stack.obligation);
660 // Check the cache. Note that we skolemize the trait-ref
661 // separately rather than using `stack.fresh_trait_ref` -- this
662 // is because we want the unbound variables to be replaced
663 // with fresh skolemized types starting from index 0.
664 let cache_fresh_trait_pred =
665 self.infcx.freshen(stack.obligation.predicate.clone());
666 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
667 cache_fresh_trait_pred,
669 assert!(!stack.obligation.predicate.has_escaping_regions());
671 match self.check_candidate_cache(&cache_fresh_trait_pred) {
673 debug!("CACHE HIT: cache_fresh_trait_pred={:?}, candidate={:?}",
674 cache_fresh_trait_pred,
681 // If no match, compute result and insert into cache.
682 let candidate = self.candidate_from_obligation_no_cache(stack);
684 if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
685 debug!("CACHE MISS: cache_fresh_trait_pred={:?}, candidate={:?}",
686 cache_fresh_trait_pred, candidate);
687 self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone());
693 fn candidate_from_obligation_no_cache<'o>(&mut self,
694 stack: &TraitObligationStack<'o, 'tcx>)
695 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
697 if stack.obligation.predicate.0.self_ty().references_error() {
698 return Ok(Some(ErrorCandidate));
701 if !self.is_knowable(stack) {
702 debug!("intercrate not knowable");
706 let candidate_set = try!(self.assemble_candidates(stack));
708 if candidate_set.ambiguous {
709 debug!("candidate set contains ambig");
713 let mut candidates = candidate_set.vec;
715 debug!("assembled {} candidates for {:?}: {:?}",
720 // At this point, we know that each of the entries in the
721 // candidate set is *individually* applicable. Now we have to
722 // figure out if they contain mutual incompatibilities. This
723 // frequently arises if we have an unconstrained input type --
724 // for example, we are looking for $0:Eq where $0 is some
725 // unconstrained type variable. In that case, we'll get a
726 // candidate which assumes $0 == int, one that assumes $0 ==
727 // usize, etc. This spells an ambiguity.
729 // If there is more than one candidate, first winnow them down
730 // by considering extra conditions (nested obligations and so
731 // forth). We don't winnow if there is exactly one
732 // candidate. This is a relatively minor distinction but it
733 // can lead to better inference and error-reporting. An
734 // example would be if there was an impl:
736 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
738 // and we were to see some code `foo.push_clone()` where `boo`
739 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
740 // we were to winnow, we'd wind up with zero candidates.
741 // Instead, we select the right impl now but report `Bar does
742 // not implement Clone`.
743 if candidates.len() > 1 {
744 candidates.retain(|c| self.winnow_candidate(stack, c).may_apply())
747 // If there are STILL multiple candidate, we can further reduce
748 // the list by dropping duplicates.
749 if candidates.len() > 1 {
751 while i < candidates.len() {
753 (0..candidates.len())
755 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
758 debug!("Dropping candidate #{}/{}: {:?}",
759 i, candidates.len(), candidates[i]);
760 candidates.swap_remove(i);
762 debug!("Retaining candidate #{}/{}: {:?}",
763 i, candidates.len(), candidates[i]);
769 // If there are *STILL* multiple candidates, give up and
771 if candidates.len() > 1 {
772 debug!("multiple matches, ambig");
777 // If there are *NO* candidates, that there are no impls --
778 // that we know of, anyway. Note that in the case where there
779 // are unbound type variables within the obligation, it might
780 // be the case that you could still satisfy the obligation
781 // from another crate by instantiating the type variables with
782 // a type from another crate that does have an impl. This case
783 // is checked for in `evaluate_stack` (and hence users
784 // who might care about this case, like coherence, should use
786 if candidates.is_empty() {
787 return Err(Unimplemented);
790 // Just one candidate left.
791 let candidate = candidates.pop().unwrap();
794 ImplCandidate(def_id) => {
795 match self.tcx().trait_impl_polarity(def_id) {
796 Some(hir::ImplPolarity::Negative) => return Err(Unimplemented),
806 fn is_knowable<'o>(&mut self,
807 stack: &TraitObligationStack<'o, 'tcx>)
810 debug!("is_knowable(intercrate={})", self.intercrate);
812 if !self.intercrate {
816 let obligation = &stack.obligation;
817 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
819 // ok to skip binder because of the nature of the
820 // trait-ref-is-knowable check, which does not care about
822 let trait_ref = &predicate.skip_binder().trait_ref;
824 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
827 fn pick_candidate_cache(&self) -> &SelectionCache<'tcx> {
828 // If there are any where-clauses in scope, then we always use
829 // a cache local to this particular scope. Otherwise, we
830 // switch to a global cache. We used to try and draw
831 // finer-grained distinctions, but that led to a serious of
832 // annoying and weird bugs like #22019 and #18290. This simple
833 // rule seems to be pretty clearly safe and also still retains
834 // a very high hit rate (~95% when compiling rustc).
835 if !self.param_env().caller_bounds.is_empty() {
836 return &self.param_env().selection_cache;
839 // Avoid using the master cache during coherence and just rely
840 // on the local cache. This effectively disables caching
841 // during coherence. It is really just a simplification to
842 // avoid us having to fear that coherence results "pollute"
843 // the master cache. Since coherence executes pretty quickly,
844 // it's not worth going to more trouble to increase the
845 // hit-rate I don't think.
847 return &self.param_env().selection_cache;
850 // Otherwise, we can use the global cache.
851 &self.tcx().selection_cache
854 fn check_candidate_cache(&mut self,
855 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
856 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
858 let cache = self.pick_candidate_cache();
859 let hashmap = cache.hashmap.borrow();
860 hashmap.get(&cache_fresh_trait_pred.0.trait_ref).cloned()
863 fn insert_candidate_cache(&mut self,
864 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
865 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
867 let cache = self.pick_candidate_cache();
868 let mut hashmap = cache.hashmap.borrow_mut();
869 hashmap.insert(cache_fresh_trait_pred.0.trait_ref.clone(), candidate);
872 fn should_update_candidate_cache(&mut self,
873 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
874 candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
877 // In general, it's a good idea to cache results, even
878 // ambiguous ones, to save us some trouble later. But we have
879 // to be careful not to cache results that could be
880 // invalidated later by advances in inference. Normally, this
881 // is not an issue, because any inference variables whose
882 // types are not yet bound are "freshened" in the cache key,
883 // which means that if we later get the same request once that
884 // type variable IS bound, we'll have a different cache key.
885 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
886 // not yet known, we may cache the result as `None`. But if
887 // later `_#0t` is bound to `Bar`, then when we freshen we'll
888 // have `Vec<Bar> : Foo` as the cache key.
890 // HOWEVER, it CAN happen that we get an ambiguity result in
891 // one particular case around closures where the cache key
892 // would not change. That is when the precise types of the
893 // upvars that a closure references have not yet been figured
894 // out (i.e., because it is not yet known if they are captured
895 // by ref, and if by ref, what kind of ref). In these cases,
896 // when matching a builtin bound, we will yield back an
897 // ambiguous result. But the *cache key* is just the closure type,
898 // it doesn't capture the state of the upvar computation.
900 // To avoid this trap, just don't cache ambiguous results if
901 // the self-type contains no inference byproducts (that really
902 // shouldn't happen in other circumstances anyway, given
906 Ok(Some(_)) | Err(_) => true,
908 cache_fresh_trait_pred.0.input_types().has_infer_types()
913 fn assemble_candidates<'o>(&mut self,
914 stack: &TraitObligationStack<'o, 'tcx>)
915 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
917 let TraitObligationStack { obligation, .. } = *stack;
918 let ref obligation = Obligation {
919 cause: obligation.cause.clone(),
920 recursion_depth: obligation.recursion_depth,
921 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
924 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
925 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
927 // This is somewhat problematic, as the current scheme can't really
928 // handle it turning to be a projection. This does end up as truly
929 // ambiguous in most cases anyway.
931 // Until this is fixed, take the fast path out - this also improves
932 // performance by preventing assemble_candidates_from_impls from
933 // matching every impl for this trait.
934 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
937 let mut candidates = SelectionCandidateSet {
942 // Other bounds. Consider both in-scope bounds from fn decl
943 // and applicable impls. There is a certain set of precedence rules here.
945 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
946 Some(ty::BoundCopy) => {
947 debug!("obligation self ty is {:?}",
948 obligation.predicate.0.self_ty());
950 // User-defined copy impls are permitted, but only for
951 // structs and enums.
952 try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
954 // For other types, we'll use the builtin rules.
955 try!(self.assemble_builtin_bound_candidates(ty::BoundCopy,
959 Some(bound @ ty::BoundSized) => {
960 // Sized is never implementable by end-users, it is
961 // always automatically computed.
962 try!(self.assemble_builtin_bound_candidates(bound,
967 None if self.tcx().lang_items.unsize_trait() ==
968 Some(obligation.predicate.def_id()) => {
969 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
972 Some(ty::BoundSend) |
973 Some(ty::BoundSync) |
975 try!(self.assemble_closure_candidates(obligation, &mut candidates));
976 try!(self.assemble_fn_pointer_candidates(obligation, &mut candidates));
977 try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
978 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
982 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
983 try!(self.assemble_candidates_from_caller_bounds(stack, &mut candidates));
984 // Default implementations have lower priority, so we only
985 // consider triggering a default if there is no other impl that can apply.
986 if candidates.vec.is_empty() {
987 try!(self.assemble_candidates_from_default_impls(obligation, &mut candidates));
989 debug!("candidate list size: {}", candidates.vec.len());
993 fn assemble_candidates_from_projected_tys(&mut self,
994 obligation: &TraitObligation<'tcx>,
995 candidates: &mut SelectionCandidateSet<'tcx>)
997 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
999 // FIXME(#20297) -- just examining the self-type is very simplistic
1001 // before we go into the whole skolemization thing, just
1002 // quickly check if the self-type is a projection at all.
1003 let trait_def_id = match obligation.predicate.0.trait_ref.self_ty().sty {
1004 ty::TyProjection(ref data) => data.trait_ref.def_id,
1005 ty::TyInfer(ty::TyVar(_)) => {
1006 self.tcx().sess.span_bug(obligation.cause.span,
1007 "Self=_ should have been handled by assemble_candidates");
1012 debug!("assemble_candidates_for_projected_tys: trait_def_id={:?}",
1015 let result = self.infcx.probe(|snapshot| {
1016 self.match_projection_obligation_against_bounds_from_trait(obligation,
1021 candidates.vec.push(ProjectionCandidate);
1025 fn match_projection_obligation_against_bounds_from_trait(
1027 obligation: &TraitObligation<'tcx>,
1028 snapshot: &infer::CombinedSnapshot)
1031 let poly_trait_predicate =
1032 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1033 let (skol_trait_predicate, skol_map) =
1034 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1035 debug!("match_projection_obligation_against_bounds_from_trait: \
1036 skol_trait_predicate={:?} skol_map={:?}",
1037 skol_trait_predicate,
1040 let projection_trait_ref = match skol_trait_predicate.trait_ref.self_ty().sty {
1041 ty::TyProjection(ref data) => &data.trait_ref,
1043 self.tcx().sess.span_bug(
1044 obligation.cause.span,
1045 &format!("match_projection_obligation_against_bounds_from_trait() called \
1046 but self-ty not a projection: {:?}",
1047 skol_trait_predicate.trait_ref.self_ty()));
1050 debug!("match_projection_obligation_against_bounds_from_trait: \
1051 projection_trait_ref={:?}",
1052 projection_trait_ref);
1054 let trait_predicates = self.tcx().lookup_predicates(projection_trait_ref.def_id);
1055 let bounds = trait_predicates.instantiate(self.tcx(), projection_trait_ref.substs);
1056 debug!("match_projection_obligation_against_bounds_from_trait: \
1060 let matching_bound =
1061 util::elaborate_predicates(self.tcx(), bounds.predicates.into_vec())
1064 |bound| self.infcx.probe(
1065 |_| self.match_projection(obligation,
1067 skol_trait_predicate.trait_ref.clone(),
1071 debug!("match_projection_obligation_against_bounds_from_trait: \
1072 matching_bound={:?}",
1074 match matching_bound {
1077 // Repeat the successful match, if any, this time outside of a probe.
1078 let result = self.match_projection(obligation,
1080 skol_trait_predicate.trait_ref.clone(),
1089 fn match_projection(&mut self,
1090 obligation: &TraitObligation<'tcx>,
1091 trait_bound: ty::PolyTraitRef<'tcx>,
1092 skol_trait_ref: ty::TraitRef<'tcx>,
1093 skol_map: &infer::SkolemizationMap,
1094 snapshot: &infer::CombinedSnapshot)
1097 assert!(!skol_trait_ref.has_escaping_regions());
1098 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
1099 match self.infcx.sub_poly_trait_refs(false,
1101 trait_bound.clone(),
1102 ty::Binder(skol_trait_ref.clone())) {
1104 Err(_) => { return false; }
1107 self.infcx.leak_check(skol_map, snapshot).is_ok()
1110 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1111 /// supplied to find out whether it is listed among them.
1113 /// Never affects inference environment.
1114 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1115 stack: &TraitObligationStack<'o, 'tcx>,
1116 candidates: &mut SelectionCandidateSet<'tcx>)
1117 -> Result<(),SelectionError<'tcx>>
1119 debug!("assemble_candidates_from_caller_bounds({:?})",
1123 self.param_env().caller_bounds
1125 .filter_map(|o| o.to_opt_poly_trait_ref());
1127 let matching_bounds =
1129 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1131 let param_candidates =
1132 matching_bounds.map(|bound| ParamCandidate(bound));
1134 candidates.vec.extend(param_candidates);
1139 fn evaluate_where_clause<'o>(&mut self,
1140 stack: &TraitObligationStack<'o, 'tcx>,
1141 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1142 -> EvaluationResult<'tcx>
1144 self.infcx().probe(move |_| {
1145 match self.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1146 Ok(obligations) => {
1147 self.evaluate_predicates_recursively(stack.list(), obligations.iter())
1150 EvaluatedToErr(Unimplemented)
1156 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1157 /// FnMut<..>` where `X` is a closure type.
1159 /// Note: the type parameters on a closure candidate are modeled as *output* type
1160 /// parameters and hence do not affect whether this trait is a match or not. They will be
1161 /// unified during the confirmation step.
1162 fn assemble_closure_candidates(&mut self,
1163 obligation: &TraitObligation<'tcx>,
1164 candidates: &mut SelectionCandidateSet<'tcx>)
1165 -> Result<(),SelectionError<'tcx>>
1167 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1169 None => { return Ok(()); }
1172 // ok to skip binder because the substs on closure types never
1173 // touch bound regions, they just capture the in-scope
1174 // type/region parameters
1175 let self_ty = *obligation.self_ty().skip_binder();
1176 let (closure_def_id, substs) = match self_ty.sty {
1177 ty::TyClosure(id, ref substs) => (id, substs),
1178 ty::TyInfer(ty::TyVar(_)) => {
1179 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1180 candidates.ambiguous = true;
1183 _ => { return Ok(()); }
1186 debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1191 match self.infcx.closure_kind(closure_def_id) {
1192 Some(closure_kind) => {
1193 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1194 if closure_kind.extends(kind) {
1195 candidates.vec.push(ClosureCandidate(closure_def_id, substs));
1199 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1200 candidates.ambiguous = true;
1207 /// Implement one of the `Fn()` family for a fn pointer.
1208 fn assemble_fn_pointer_candidates(&mut self,
1209 obligation: &TraitObligation<'tcx>,
1210 candidates: &mut SelectionCandidateSet<'tcx>)
1211 -> Result<(),SelectionError<'tcx>>
1213 // We provide impl of all fn traits for fn pointers.
1214 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1218 // ok to skip binder because what we are inspecting doesn't involve bound regions
1219 let self_ty = *obligation.self_ty().skip_binder();
1221 ty::TyInfer(ty::TyVar(_)) => {
1222 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1223 candidates.ambiguous = true; // could wind up being a fn() type
1226 // provide an impl, but only for suitable `fn` pointers
1227 ty::TyBareFn(_, &ty::BareFnTy {
1228 unsafety: hir::Unsafety::Normal,
1230 sig: ty::Binder(ty::FnSig {
1232 output: ty::FnConverging(_),
1236 candidates.vec.push(FnPointerCandidate);
1245 /// Search for impls that might apply to `obligation`.
1246 fn assemble_candidates_from_impls(&mut self,
1247 obligation: &TraitObligation<'tcx>,
1248 candidates: &mut SelectionCandidateSet<'tcx>)
1249 -> Result<(), SelectionError<'tcx>>
1251 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1253 let def = self.tcx().lookup_trait_def(obligation.predicate.def_id());
1255 def.for_each_relevant_impl(
1257 obligation.predicate.0.trait_ref.self_ty(),
1259 self.infcx.probe(|snapshot| {
1260 if let Ok(_) = self.match_impl(impl_def_id, obligation, snapshot) {
1261 candidates.vec.push(ImplCandidate(impl_def_id));
1270 fn assemble_candidates_from_default_impls(&mut self,
1271 obligation: &TraitObligation<'tcx>,
1272 candidates: &mut SelectionCandidateSet<'tcx>)
1273 -> Result<(), SelectionError<'tcx>>
1275 // OK to skip binder here because the tests we do below do not involve bound regions
1276 let self_ty = *obligation.self_ty().skip_binder();
1277 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1279 let def_id = obligation.predicate.def_id();
1281 if self.tcx().trait_has_default_impl(def_id) {
1283 ty::TyTrait(..) => {
1284 // For object types, we don't know what the closed
1285 // over types are. For most traits, this means we
1286 // conservatively say nothing; a candidate may be
1287 // added by `assemble_candidates_from_object_ty`.
1288 // However, for the kind of magic reflect trait,
1289 // we consider it to be implemented even for
1290 // object types, because it just lets you reflect
1291 // onto the object type, not into the object's
1293 if self.tcx().has_attr(def_id, "rustc_reflect_like") {
1294 candidates.vec.push(DefaultImplObjectCandidate(def_id));
1298 ty::TyProjection(..) => {
1299 // In these cases, we don't know what the actual
1300 // type is. Therefore, we cannot break it down
1301 // into its constituent types. So we don't
1302 // consider the `..` impl but instead just add no
1303 // candidates: this means that typeck will only
1304 // succeed if there is another reason to believe
1305 // that this obligation holds. That could be a
1306 // where-clause or, in the case of an object type,
1307 // it could be that the object type lists the
1308 // trait (e.g. `Foo+Send : Send`). See
1309 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1310 // for an example of a test case that exercises
1313 ty::TyInfer(ty::TyVar(_)) => {
1314 // the defaulted impl might apply, we don't know
1315 candidates.ambiguous = true;
1318 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1326 /// Search for impls that might apply to `obligation`.
1327 fn assemble_candidates_from_object_ty(&mut self,
1328 obligation: &TraitObligation<'tcx>,
1329 candidates: &mut SelectionCandidateSet<'tcx>)
1331 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1332 obligation.self_ty().skip_binder());
1334 // Object-safety candidates are only applicable to object-safe
1335 // traits. Including this check is useful because it helps
1336 // inference in cases of traits like `BorrowFrom`, which are
1337 // not object-safe, and which rely on being able to infer the
1338 // self-type from one of the other inputs. Without this check,
1339 // these cases wind up being considered ambiguous due to a
1340 // (spurious) ambiguity introduced here.
1341 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1342 if !object_safety::is_object_safe(self.tcx(), predicate_trait_ref.def_id()) {
1346 self.infcx.commit_if_ok(|snapshot| {
1348 self.infcx().skolemize_late_bound_regions(&obligation.self_ty(), snapshot);
1349 let poly_trait_ref = match self_ty.sty {
1350 ty::TyTrait(ref data) => {
1351 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
1352 Some(bound @ ty::BoundSend) | Some(bound @ ty::BoundSync) => {
1353 if data.bounds.builtin_bounds.contains(&bound) {
1354 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1355 pushing candidate");
1356 candidates.vec.push(BuiltinObjectCandidate);
1363 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
1365 ty::TyInfer(ty::TyVar(_)) => {
1366 debug!("assemble_candidates_from_object_ty: ambiguous");
1367 candidates.ambiguous = true; // could wind up being an object type
1375 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1378 // Count only those upcast versions that match the trait-ref
1379 // we are looking for. Specifically, do not only check for the
1380 // correct trait, but also the correct type parameters.
1381 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1382 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1383 let upcast_trait_refs =
1384 util::supertraits(self.tcx(), poly_trait_ref)
1385 .filter(|upcast_trait_ref| {
1386 self.infcx.probe(|_| {
1387 let upcast_trait_ref = upcast_trait_ref.clone();
1388 self.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1393 if upcast_trait_refs > 1 {
1394 // can be upcast in many ways; need more type information
1395 candidates.ambiguous = true;
1396 } else if upcast_trait_refs == 1 {
1397 candidates.vec.push(ObjectCandidate);
1404 /// Search for unsizing that might apply to `obligation`.
1405 fn assemble_candidates_for_unsizing(&mut self,
1406 obligation: &TraitObligation<'tcx>,
1407 candidates: &mut SelectionCandidateSet<'tcx>) {
1408 // We currently never consider higher-ranked obligations e.g.
1409 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1410 // because they are a priori invalid, and we could potentially add support
1411 // for them later, it's just that there isn't really a strong need for it.
1412 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1413 // impl, and those are generally applied to concrete types.
1415 // That said, one might try to write a fn with a where clause like
1416 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1417 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1418 // Still, you'd be more likely to write that where clause as
1420 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1421 // obligation above. Should be possible to extend this in the future.
1422 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1425 // Don't add any candidates if there are bound regions.
1429 let target = obligation.predicate.0.input_types()[0];
1431 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1434 let may_apply = match (&source.sty, &target.sty) {
1435 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1436 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
1437 // Upcasts permit two things:
1439 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1440 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1442 // Note that neither of these changes requires any
1443 // change at runtime. Eventually this will be
1446 // We always upcast when we can because of reason
1447 // #2 (region bounds).
1448 data_a.principal.def_id() == data_a.principal.def_id() &&
1449 data_a.bounds.builtin_bounds.is_superset(&data_b.bounds.builtin_bounds)
1453 (_, &ty::TyTrait(_)) => true,
1455 // Ambiguous handling is below T -> Trait, because inference
1456 // variables can still implement Unsize<Trait> and nested
1457 // obligations will have the final say (likely deferred).
1458 (&ty::TyInfer(ty::TyVar(_)), _) |
1459 (_, &ty::TyInfer(ty::TyVar(_))) => {
1460 debug!("assemble_candidates_for_unsizing: ambiguous");
1461 candidates.ambiguous = true;
1466 (&ty::TyArray(_, _), &ty::TySlice(_)) => true,
1468 // Struct<T> -> Struct<U>.
1469 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
1470 def_id_a == def_id_b
1477 candidates.vec.push(BuiltinUnsizeCandidate);
1481 ///////////////////////////////////////////////////////////////////////////
1484 // Winnowing is the process of attempting to resolve ambiguity by
1485 // probing further. During the winnowing process, we unify all
1486 // type variables (ignoring skolemization) and then we also
1487 // attempt to evaluate recursive bounds to see if they are
1490 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1491 /// obligations are met. Returns true if `candidate` remains viable after this further
1493 fn winnow_candidate<'o>(&mut self,
1494 stack: &TraitObligationStack<'o, 'tcx>,
1495 candidate: &SelectionCandidate<'tcx>)
1496 -> EvaluationResult<'tcx>
1498 debug!("winnow_candidate: candidate={:?}", candidate);
1499 let result = self.infcx.probe(|_| {
1500 let candidate = (*candidate).clone();
1501 match self.confirm_candidate(stack.obligation, candidate) {
1502 Ok(selection) => self.winnow_selection(stack.list(),
1504 Err(error) => EvaluatedToErr(error),
1507 debug!("winnow_candidate depth={} result={:?}",
1508 stack.obligation.recursion_depth, result);
1512 fn winnow_selection<'o>(&mut self,
1513 stack: TraitObligationStackList<'o,'tcx>,
1514 selection: Selection<'tcx>)
1515 -> EvaluationResult<'tcx>
1517 self.evaluate_predicates_recursively(stack,
1518 selection.nested_obligations().iter())
1521 /// Returns true if `candidate_i` should be dropped in favor of
1522 /// `candidate_j`. Generally speaking we will drop duplicate
1523 /// candidates and prefer where-clause candidates.
1524 /// Returns true if `victim` should be dropped in favor of
1525 /// `other`. Generally speaking we will drop duplicate
1526 /// candidates and prefer where-clause candidates.
1528 /// See the comment for "SelectionCandidate" for more details.
1529 fn candidate_should_be_dropped_in_favor_of<'o>(&mut self,
1530 victim: &SelectionCandidate<'tcx>,
1531 other: &SelectionCandidate<'tcx>)
1534 if victim == other {
1539 &ObjectCandidate(..) |
1540 &ParamCandidate(_) | &ProjectionCandidate => match victim {
1541 &DefaultImplCandidate(..) => {
1542 self.tcx().sess.bug(
1543 "default implementations shouldn't be recorded \
1544 when there are other valid candidates");
1546 &PhantomFnCandidate => {
1547 self.tcx().sess.bug("PhantomFn didn't short-circuit selection");
1549 &ImplCandidate(..) |
1550 &ClosureCandidate(..) |
1551 &FnPointerCandidate(..) |
1552 &BuiltinObjectCandidate(..) |
1553 &BuiltinUnsizeCandidate(..) |
1554 &DefaultImplObjectCandidate(..) |
1555 &BuiltinCandidate(..) => {
1556 // We have a where-clause so don't go around looking
1560 &ObjectCandidate(..) |
1561 &ProjectionCandidate => {
1562 // Arbitrarily give param candidates priority
1563 // over projection and object candidates.
1566 &ParamCandidate(..) => false,
1567 &ErrorCandidate => false // propagate errors
1573 ///////////////////////////////////////////////////////////////////////////
1576 // These cover the traits that are built-in to the language
1577 // itself. This includes `Copy` and `Sized` for sure. For the
1578 // moment, it also includes `Send` / `Sync` and a few others, but
1579 // those will hopefully change to library-defined traits in the
1582 fn assemble_builtin_bound_candidates<'o>(&mut self,
1583 bound: ty::BuiltinBound,
1584 obligation: &TraitObligation<'tcx>,
1585 candidates: &mut SelectionCandidateSet<'tcx>)
1586 -> Result<(),SelectionError<'tcx>>
1588 match self.builtin_bound(bound, obligation) {
1590 debug!("builtin_bound: bound={:?}",
1592 candidates.vec.push(BuiltinCandidate(bound));
1595 Ok(ParameterBuiltin) => { Ok(()) }
1596 Ok(AmbiguousBuiltin) => {
1597 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1598 Ok(candidates.ambiguous = true)
1600 Err(e) => { Err(e) }
1604 fn builtin_bound(&mut self,
1605 bound: ty::BuiltinBound,
1606 obligation: &TraitObligation<'tcx>)
1607 -> Result<BuiltinBoundConditions<'tcx>,SelectionError<'tcx>>
1609 // Note: these tests operate on types that may contain bound
1610 // regions. To be proper, we ought to skolemize here, but we
1611 // forego the skolemization and defer it until the
1612 // confirmation step.
1614 let self_ty = self.infcx.shallow_resolve(obligation.predicate.0.self_ty());
1615 return match self_ty.sty {
1616 ty::TyInfer(ty::IntVar(_)) |
1617 ty::TyInfer(ty::FloatVar(_)) |
1624 // safe for everything
1628 ty::TyBox(_) => { // Box<T>
1630 ty::BoundCopy => Err(Unimplemented),
1632 ty::BoundSized => ok_if(Vec::new()),
1634 ty::BoundSync | ty::BoundSend => {
1635 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1640 ty::TyRawPtr(..) => { // *const T, *mut T
1642 ty::BoundCopy | ty::BoundSized => ok_if(Vec::new()),
1644 ty::BoundSync | ty::BoundSend => {
1645 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1650 ty::TyTrait(ref data) => {
1652 ty::BoundSized => Err(Unimplemented),
1654 if data.bounds.builtin_bounds.contains(&bound) {
1657 // Recursively check all supertraits to find out if any further
1658 // bounds are required and thus we must fulfill.
1660 data.principal_trait_ref_with_self_ty(self.tcx(),
1661 self.tcx().types.err);
1662 let copy_def_id = obligation.predicate.def_id();
1663 for tr in util::supertraits(self.tcx(), principal) {
1664 if tr.def_id() == copy_def_id {
1665 return ok_if(Vec::new())
1672 ty::BoundSync | ty::BoundSend => {
1673 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1678 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl }) => {
1683 // &mut T is affine and hence never `Copy`
1684 hir::MutMutable => Err(Unimplemented),
1686 // &T is always copyable
1687 hir::MutImmutable => ok_if(Vec::new()),
1691 ty::BoundSized => ok_if(Vec::new()),
1693 ty::BoundSync | ty::BoundSend => {
1694 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1699 ty::TyArray(element_ty, _) => {
1702 ty::BoundCopy => ok_if(vec![element_ty]),
1703 ty::BoundSized => ok_if(Vec::new()),
1704 ty::BoundSync | ty::BoundSend => {
1705 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1710 ty::TyStr | ty::TySlice(_) => {
1712 ty::BoundSync | ty::BoundSend => {
1713 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1716 ty::BoundCopy | ty::BoundSized => Err(Unimplemented),
1720 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1721 ty::TyTuple(ref tys) => ok_if(tys.clone()),
1723 ty::TyClosure(def_id, ref substs) => {
1724 // FIXME -- This case is tricky. In the case of by-ref
1725 // closures particularly, we need the results of
1726 // inference to decide how to reflect the type of each
1727 // upvar (the upvar may have type `T`, but the runtime
1728 // type could be `&mut`, `&`, or just `T`). For now,
1729 // though, we'll do this unsoundly and assume that all
1730 // captures are by value. Really what we ought to do
1731 // is reserve judgement and then intertwine this
1732 // analysis with closure inference.
1733 assert_eq!(def_id.krate, LOCAL_CRATE);
1735 // Unboxed closures shouldn't be
1736 // implicitly copyable
1737 if bound == ty::BoundCopy {
1738 return Ok(ParameterBuiltin);
1741 // Upvars are always local variables or references to
1742 // local variables, and local variables cannot be
1743 // unsized, so the closure struct as a whole must be
1745 if bound == ty::BoundSized {
1746 return ok_if(Vec::new());
1749 ok_if(substs.upvar_tys.clone())
1752 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1753 let types: Vec<Ty> = def.all_fields().map(|f| {
1754 f.ty(self.tcx(), substs)
1756 nominal(bound, types)
1759 ty::TyProjection(_) | ty::TyParam(_) => {
1760 // Note: A type parameter is only considered to meet a
1761 // particular bound if there is a where clause telling
1762 // us that it does, and that case is handled by
1763 // `assemble_candidates_from_caller_bounds()`.
1764 Ok(ParameterBuiltin)
1767 ty::TyInfer(ty::TyVar(_)) => {
1768 // Unbound type variable. Might or might not have
1769 // applicable impls and so forth, depending on what
1770 // those type variables wind up being bound to.
1771 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1772 Ok(AmbiguousBuiltin)
1775 ty::TyError => ok_if(Vec::new()),
1777 ty::TyInfer(ty::FreshTy(_))
1778 | ty::TyInfer(ty::FreshIntTy(_))
1779 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1780 self.tcx().sess.bug(
1782 "asked to assemble builtin bounds of unexpected type: {:?}",
1787 fn ok_if<'tcx>(v: Vec<Ty<'tcx>>)
1788 -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>> {
1789 Ok(If(ty::Binder(v)))
1792 fn nominal<'cx, 'tcx>(bound: ty::BuiltinBound,
1793 types: Vec<Ty<'tcx>>)
1794 -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>>
1796 // First check for markers and other nonsense.
1798 // Fallback to whatever user-defined impls exist in this case.
1799 ty::BoundCopy => Ok(ParameterBuiltin),
1801 // Sized if all the component types are sized.
1802 ty::BoundSized => ok_if(types),
1804 // Shouldn't be coming through here.
1805 ty::BoundSend | ty::BoundSync => unreachable!(),
1810 /// For default impls, we need to break apart a type into its
1811 /// "constituent types" -- meaning, the types that it contains.
1813 /// Here are some (simple) examples:
1816 /// (i32, u32) -> [i32, u32]
1817 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1818 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1819 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1821 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1830 ty::TyInfer(ty::IntVar(_)) |
1831 ty::TyInfer(ty::FloatVar(_)) |
1838 ty::TyProjection(..) |
1839 ty::TyInfer(ty::TyVar(_)) |
1840 ty::TyInfer(ty::FreshTy(_)) |
1841 ty::TyInfer(ty::FreshIntTy(_)) |
1842 ty::TyInfer(ty::FreshFloatTy(_)) => {
1843 self.tcx().sess.bug(
1845 "asked to assemble constituent types of unexpected type: {:?}",
1849 ty::TyBox(referent_ty) => { // Box<T>
1853 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
1854 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
1858 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
1862 ty::TyTuple(ref tys) => {
1863 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1867 ty::TyClosure(def_id, ref substs) => {
1868 // FIXME(#27086). We are invariant w/r/t our
1869 // substs.func_substs, but we don't see them as
1870 // constituent types; this seems RIGHT but also like
1871 // something that a normal type couldn't simulate. Is
1872 // this just a gap with the way that PhantomData and
1873 // OIBIT interact? That is, there is no way to say
1874 // "make me invariant with respect to this TYPE, but
1875 // do not act as though I can reach it"
1876 assert_eq!(def_id.krate, LOCAL_CRATE);
1877 substs.upvar_tys.clone()
1880 // for `PhantomData<T>`, we pass `T`
1881 ty::TyStruct(def, substs) if def.is_phantom_data() => {
1882 substs.types.get_slice(TypeSpace).to_vec()
1885 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1887 .map(|f| f.ty(self.tcx(), substs))
1893 fn collect_predicates_for_types(&mut self,
1894 obligation: &TraitObligation<'tcx>,
1895 trait_def_id: DefId,
1896 types: ty::Binder<Vec<Ty<'tcx>>>)
1897 -> Vec<PredicateObligation<'tcx>>
1899 let derived_cause = match self.tcx().lang_items.to_builtin_kind(trait_def_id) {
1901 self.derived_cause(obligation, BuiltinDerivedObligation)
1904 self.derived_cause(obligation, ImplDerivedObligation)
1908 // Because the types were potentially derived from
1909 // higher-ranked obligations they may reference late-bound
1910 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1911 // yield a type like `for<'a> &'a int`. In general, we
1912 // maintain the invariant that we never manipulate bound
1913 // regions, so we have to process these bound regions somehow.
1915 // The strategy is to:
1917 // 1. Instantiate those regions to skolemized regions (e.g.,
1918 // `for<'a> &'a int` becomes `&0 int`.
1919 // 2. Produce something like `&'0 int : Copy`
1920 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1922 // Move the binder into the individual types
1923 let bound_types: Vec<ty::Binder<Ty<'tcx>>> =
1926 .map(|&nested_ty| ty::Binder(nested_ty))
1929 // For each type, produce a vector of resulting obligations
1930 let obligations: Result<Vec<Vec<_>>, _> = bound_types.iter().map(|nested_ty| {
1931 self.infcx.commit_if_ok(|snapshot| {
1932 let (skol_ty, skol_map) =
1933 self.infcx().skolemize_late_bound_regions(nested_ty, snapshot);
1934 let Normalized { value: normalized_ty, mut obligations } =
1935 project::normalize_with_depth(self,
1936 obligation.cause.clone(),
1937 obligation.recursion_depth + 1,
1939 let skol_obligation =
1940 util::predicate_for_trait_def(self.tcx(),
1941 derived_cause.clone(),
1943 obligation.recursion_depth + 1,
1946 obligations.push(skol_obligation);
1947 Ok(self.infcx().plug_leaks(skol_map, snapshot, &obligations))
1951 // Flatten those vectors (couldn't do it above due `collect`)
1953 Ok(obligations) => obligations.into_iter().flat_map(|o| o).collect(),
1954 Err(ErrorReported) => Vec::new(),
1958 ///////////////////////////////////////////////////////////////////////////
1961 // Confirmation unifies the output type parameters of the trait
1962 // with the values found in the obligation, possibly yielding a
1963 // type error. See `README.md` for more details.
1965 fn confirm_candidate(&mut self,
1966 obligation: &TraitObligation<'tcx>,
1967 candidate: SelectionCandidate<'tcx>)
1968 -> Result<Selection<'tcx>,SelectionError<'tcx>>
1970 debug!("confirm_candidate({:?}, {:?})",
1975 BuiltinCandidate(builtin_bound) => {
1977 try!(self.confirm_builtin_candidate(obligation, builtin_bound))))
1980 PhantomFnCandidate |
1982 Ok(VtableBuiltin(VtableBuiltinData { nested: vec![] }))
1985 ParamCandidate(param) => {
1986 let obligations = self.confirm_param_candidate(obligation, param);
1987 Ok(VtableParam(obligations))
1990 DefaultImplCandidate(trait_def_id) => {
1991 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
1992 Ok(VtableDefaultImpl(data))
1995 DefaultImplObjectCandidate(trait_def_id) => {
1996 let data = self.confirm_default_impl_object_candidate(obligation, trait_def_id);
1997 Ok(VtableDefaultImpl(data))
2000 ImplCandidate(impl_def_id) => {
2002 try!(self.confirm_impl_candidate(obligation, impl_def_id));
2003 Ok(VtableImpl(vtable_impl))
2006 ClosureCandidate(closure_def_id, substs) => {
2007 let vtable_closure =
2008 try!(self.confirm_closure_candidate(obligation, closure_def_id, substs));
2009 Ok(VtableClosure(vtable_closure))
2012 BuiltinObjectCandidate => {
2013 // This indicates something like `(Trait+Send) :
2014 // Send`. In this case, we know that this holds
2015 // because that's what the object type is telling us,
2016 // and there's really no additional obligations to
2017 // prove and no types in particular to unify etc.
2018 Ok(VtableParam(Vec::new()))
2021 ObjectCandidate => {
2022 let data = self.confirm_object_candidate(obligation);
2023 Ok(VtableObject(data))
2026 FnPointerCandidate => {
2028 try!(self.confirm_fn_pointer_candidate(obligation));
2029 Ok(VtableFnPointer(fn_type))
2032 ProjectionCandidate => {
2033 self.confirm_projection_candidate(obligation);
2034 Ok(VtableParam(Vec::new()))
2037 BuiltinUnsizeCandidate => {
2038 let data = try!(self.confirm_builtin_unsize_candidate(obligation));
2039 Ok(VtableBuiltin(data))
2044 fn confirm_projection_candidate(&mut self,
2045 obligation: &TraitObligation<'tcx>)
2047 let _: Result<(),()> =
2048 self.infcx.commit_if_ok(|snapshot| {
2050 self.match_projection_obligation_against_bounds_from_trait(obligation,
2057 fn confirm_param_candidate(&mut self,
2058 obligation: &TraitObligation<'tcx>,
2059 param: ty::PolyTraitRef<'tcx>)
2060 -> Vec<PredicateObligation<'tcx>>
2062 debug!("confirm_param_candidate({:?},{:?})",
2066 // During evaluation, we already checked that this
2067 // where-clause trait-ref could be unified with the obligation
2068 // trait-ref. Repeat that unification now without any
2069 // transactional boundary; it should not fail.
2070 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2071 Ok(obligations) => obligations,
2073 self.tcx().sess.bug(
2074 &format!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2081 fn confirm_builtin_candidate(&mut self,
2082 obligation: &TraitObligation<'tcx>,
2083 bound: ty::BuiltinBound)
2084 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2085 SelectionError<'tcx>>
2087 debug!("confirm_builtin_candidate({:?})",
2090 match try!(self.builtin_bound(bound, obligation)) {
2091 If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)),
2092 AmbiguousBuiltin | ParameterBuiltin => {
2093 self.tcx().sess.span_bug(
2094 obligation.cause.span,
2095 &format!("builtin bound for {:?} was ambig",
2101 fn vtable_builtin_data(&mut self,
2102 obligation: &TraitObligation<'tcx>,
2103 bound: ty::BuiltinBound,
2104 nested: ty::Binder<Vec<Ty<'tcx>>>)
2105 -> VtableBuiltinData<PredicateObligation<'tcx>>
2107 let trait_def = match self.tcx().lang_items.from_builtin_kind(bound) {
2108 Ok(def_id) => def_id,
2110 self.tcx().sess.bug("builtin trait definition not found");
2114 let obligations = self.collect_predicates_for_types(obligation, trait_def, nested);
2116 debug!("vtable_builtin_data: obligations={:?}",
2119 VtableBuiltinData { nested: obligations }
2122 /// This handles the case where a `impl Foo for ..` impl is being used.
2123 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2125 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2126 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2127 fn confirm_default_impl_candidate(&mut self,
2128 obligation: &TraitObligation<'tcx>,
2129 trait_def_id: DefId)
2130 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2132 debug!("confirm_default_impl_candidate({:?}, {:?})",
2136 // binder is moved below
2137 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2138 let types = self.constituent_types_for_ty(self_ty);
2139 self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2142 fn confirm_default_impl_object_candidate(&mut self,
2143 obligation: &TraitObligation<'tcx>,
2144 trait_def_id: DefId)
2145 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2147 debug!("confirm_default_impl_object_candidate({:?}, {:?})",
2151 assert!(self.tcx().has_attr(trait_def_id, "rustc_reflect_like"));
2153 // OK to skip binder, it is reintroduced below
2154 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2156 ty::TyTrait(ref data) => {
2157 // OK to skip the binder, it is reintroduced below
2158 let input_types = data.principal.skip_binder().substs.types.get_slice(TypeSpace);
2159 let assoc_types = data.bounds.projection_bounds
2161 .map(|pb| pb.skip_binder().ty);
2162 let all_types: Vec<_> = input_types.iter().cloned()
2166 // reintroduce the two binding levels we skipped, then flatten into one
2167 let all_types = ty::Binder(ty::Binder(all_types));
2168 let all_types = self.tcx().flatten_late_bound_regions(&all_types);
2170 self.vtable_default_impl(obligation, trait_def_id, all_types)
2173 self.tcx().sess.bug(
2175 "asked to confirm default object implementation for non-object type: {:?}",
2181 /// See `confirm_default_impl_candidate`
2182 fn vtable_default_impl(&mut self,
2183 obligation: &TraitObligation<'tcx>,
2184 trait_def_id: DefId,
2185 nested: ty::Binder<Vec<Ty<'tcx>>>)
2186 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2188 debug!("vtable_default_impl_data: nested={:?}", nested);
2190 let mut obligations = self.collect_predicates_for_types(obligation,
2194 let trait_obligations: Result<Vec<_>,()> = self.infcx.commit_if_ok(|snapshot| {
2195 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2196 let (trait_ref, skol_map) =
2197 self.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2198 Ok(self.impl_or_trait_obligations(obligation.cause.clone(),
2199 obligation.recursion_depth + 1,
2206 // no Errors in that code above
2207 obligations.append(&mut trait_obligations.unwrap());
2209 debug!("vtable_default_impl_data: obligations={:?}", obligations);
2211 VtableDefaultImplData {
2212 trait_def_id: trait_def_id,
2217 fn confirm_impl_candidate(&mut self,
2218 obligation: &TraitObligation<'tcx>,
2220 -> Result<VtableImplData<'tcx, PredicateObligation<'tcx>>,
2221 SelectionError<'tcx>>
2223 debug!("confirm_impl_candidate({:?},{:?})",
2227 // First, create the substitutions by matching the impl again,
2228 // this time not in a probe.
2229 self.infcx.commit_if_ok(|snapshot| {
2230 let (substs, skol_map) =
2231 self.rematch_impl(impl_def_id, obligation,
2233 debug!("confirm_impl_candidate substs={:?}", substs);
2234 Ok(self.vtable_impl(impl_def_id, substs, obligation.cause.clone(),
2235 obligation.recursion_depth + 1, skol_map, snapshot))
2239 fn vtable_impl(&mut self,
2241 mut substs: Normalized<'tcx, Substs<'tcx>>,
2242 cause: ObligationCause<'tcx>,
2243 recursion_depth: usize,
2244 skol_map: infer::SkolemizationMap,
2245 snapshot: &infer::CombinedSnapshot)
2246 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2248 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2254 let mut impl_obligations =
2255 self.impl_or_trait_obligations(cause,
2262 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2266 impl_obligations.append(&mut substs.obligations);
2268 VtableImplData { impl_def_id: impl_def_id,
2269 substs: substs.value,
2270 nested: impl_obligations }
2273 fn confirm_object_candidate(&mut self,
2274 obligation: &TraitObligation<'tcx>)
2275 -> VtableObjectData<'tcx>
2277 debug!("confirm_object_candidate({:?})",
2280 // FIXME skipping binder here seems wrong -- we should
2281 // probably flatten the binder from the obligation and the
2282 // binder from the object. Have to try to make a broken test
2283 // case that results. -nmatsakis
2284 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2285 let poly_trait_ref = match self_ty.sty {
2286 ty::TyTrait(ref data) => {
2287 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
2290 self.tcx().sess.span_bug(obligation.cause.span,
2291 "object candidate with non-object");
2295 let mut upcast_trait_ref = None;
2299 // We want to find the first supertrait in the list of
2300 // supertraits that we can unify with, and do that
2301 // unification. We know that there is exactly one in the list
2302 // where we can unify because otherwise select would have
2303 // reported an ambiguity. (When we do find a match, also
2304 // record it for later.)
2306 util::supertraits(self.tcx(), poly_trait_ref)
2309 self.infcx.commit_if_ok(
2310 |_| self.match_poly_trait_ref(obligation, t))
2312 Ok(_) => { upcast_trait_ref = Some(t); false }
2317 // Additionally, for each of the nonmatching predicates that
2318 // we pass over, we sum up the set of number of vtable
2319 // entries, so that we can compute the offset for the selected
2322 nonmatching.map(|t| util::count_own_vtable_entries(self.tcx(), t))
2328 upcast_trait_ref: upcast_trait_ref.unwrap(),
2329 vtable_base: vtable_base,
2333 fn confirm_fn_pointer_candidate(&mut self,
2334 obligation: &TraitObligation<'tcx>)
2335 -> Result<ty::Ty<'tcx>,SelectionError<'tcx>>
2337 debug!("confirm_fn_pointer_candidate({:?})",
2340 // ok to skip binder; it is reintroduced below
2341 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2342 let sig = self_ty.fn_sig();
2344 util::closure_trait_ref_and_return_type(self.tcx(),
2345 obligation.predicate.def_id(),
2348 util::TupleArgumentsFlag::Yes)
2349 .map_bound(|(trait_ref, _)| trait_ref);
2351 try!(self.confirm_poly_trait_refs(obligation.cause.clone(),
2352 obligation.predicate.to_poly_trait_ref(),
2357 fn confirm_closure_candidate(&mut self,
2358 obligation: &TraitObligation<'tcx>,
2359 closure_def_id: DefId,
2360 substs: &ty::ClosureSubsts<'tcx>)
2361 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2362 SelectionError<'tcx>>
2364 debug!("confirm_closure_candidate({:?},{:?},{:?})",
2372 } = self.closure_trait_ref(obligation, closure_def_id, substs);
2374 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2379 try!(self.confirm_poly_trait_refs(obligation.cause.clone(),
2380 obligation.predicate.to_poly_trait_ref(),
2383 Ok(VtableClosureData {
2384 closure_def_id: closure_def_id,
2385 substs: substs.clone(),
2390 /// In the case of closure types and fn pointers,
2391 /// we currently treat the input type parameters on the trait as
2392 /// outputs. This means that when we have a match we have only
2393 /// considered the self type, so we have to go back and make sure
2394 /// to relate the argument types too. This is kind of wrong, but
2395 /// since we control the full set of impls, also not that wrong,
2396 /// and it DOES yield better error messages (since we don't report
2397 /// errors as if there is no applicable impl, but rather report
2398 /// errors are about mismatched argument types.
2400 /// Here is an example. Imagine we have an closure expression
2401 /// and we desugared it so that the type of the expression is
2402 /// `Closure`, and `Closure` expects an int as argument. Then it
2403 /// is "as if" the compiler generated this impl:
2405 /// impl Fn(int) for Closure { ... }
2407 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2408 /// we have matched the self-type `Closure`. At this point we'll
2409 /// compare the `int` to `usize` and generate an error.
2411 /// Note that this checking occurs *after* the impl has selected,
2412 /// because these output type parameters should not affect the
2413 /// selection of the impl. Therefore, if there is a mismatch, we
2414 /// report an error to the user.
2415 fn confirm_poly_trait_refs(&mut self,
2416 obligation_cause: ObligationCause,
2417 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2418 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2419 -> Result<(), SelectionError<'tcx>>
2421 let origin = infer::RelateOutputImplTypes(obligation_cause.span);
2423 let obligation_trait_ref = obligation_trait_ref.clone();
2424 match self.infcx.sub_poly_trait_refs(false,
2426 expected_trait_ref.clone(),
2427 obligation_trait_ref.clone()) {
2429 Err(e) => Err(OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2433 fn confirm_builtin_unsize_candidate(&mut self,
2434 obligation: &TraitObligation<'tcx>,)
2435 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2436 SelectionError<'tcx>> {
2437 let tcx = self.tcx();
2439 // assemble_candidates_for_unsizing should ensure there are no late bound
2440 // regions here. See the comment there for more details.
2441 let source = self.infcx.shallow_resolve(
2442 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2443 let target = self.infcx.shallow_resolve(obligation.predicate.0.input_types()[0]);
2445 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2448 let mut nested = vec![];
2449 match (&source.sty, &target.sty) {
2450 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2451 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
2452 // See assemble_candidates_for_unsizing for more info.
2453 let bounds = ty::ExistentialBounds {
2454 region_bound: data_b.bounds.region_bound,
2455 builtin_bounds: data_b.bounds.builtin_bounds,
2456 projection_bounds: data_a.bounds.projection_bounds.clone(),
2459 let new_trait = tcx.mk_trait(data_a.principal.clone(), bounds);
2460 let origin = infer::Misc(obligation.cause.span);
2461 if self.infcx.sub_types(false, origin, new_trait, target).is_err() {
2462 return Err(Unimplemented);
2465 // Register one obligation for 'a: 'b.
2466 let cause = ObligationCause::new(obligation.cause.span,
2467 obligation.cause.body_id,
2468 ObjectCastObligation(target));
2469 let outlives = ty::OutlivesPredicate(data_a.bounds.region_bound,
2470 data_b.bounds.region_bound);
2471 nested.push(Obligation::with_depth(cause,
2472 obligation.recursion_depth + 1,
2473 ty::Binder(outlives).to_predicate()));
2477 (_, &ty::TyTrait(ref data)) => {
2478 let object_did = data.principal_def_id();
2479 if !object_safety::is_object_safe(tcx, object_did) {
2480 return Err(TraitNotObjectSafe(object_did));
2483 let cause = ObligationCause::new(obligation.cause.span,
2484 obligation.cause.body_id,
2485 ObjectCastObligation(target));
2486 let mut push = |predicate| {
2487 nested.push(Obligation::with_depth(cause.clone(),
2488 obligation.recursion_depth + 1,
2492 // Create the obligation for casting from T to Trait.
2493 push(data.principal_trait_ref_with_self_ty(tcx, source).to_predicate());
2495 // We can only make objects from sized types.
2496 let mut builtin_bounds = data.bounds.builtin_bounds;
2497 builtin_bounds.insert(ty::BoundSized);
2499 // Create additional obligations for all the various builtin
2500 // bounds attached to the object cast. (In other words, if the
2501 // object type is Foo+Send, this would create an obligation
2502 // for the Send check.)
2503 for bound in &builtin_bounds {
2504 if let Ok(tr) = util::trait_ref_for_builtin_bound(tcx, bound, source) {
2505 push(tr.to_predicate());
2507 return Err(Unimplemented);
2511 // Create obligations for the projection predicates.
2512 for bound in data.projection_bounds_with_self_ty(tcx, source) {
2513 push(bound.to_predicate());
2516 // If the type is `Foo+'a`, ensures that the type
2517 // being cast to `Foo+'a` outlives `'a`:
2518 let outlives = ty::OutlivesPredicate(source,
2519 data.bounds.region_bound);
2520 push(ty::Binder(outlives).to_predicate());
2524 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2525 let origin = infer::Misc(obligation.cause.span);
2526 if self.infcx.sub_types(false, origin, a, b).is_err() {
2527 return Err(Unimplemented);
2531 // Struct<T> -> Struct<U>.
2532 (&ty::TyStruct(def, substs_a), &ty::TyStruct(_, substs_b)) => {
2535 .map(|f| f.unsubst_ty())
2536 .collect::<Vec<_>>();
2538 // The last field of the structure has to exist and contain type parameters.
2539 let field = if let Some(&field) = fields.last() {
2542 return Err(Unimplemented);
2544 let mut ty_params = vec![];
2545 for ty in field.walk() {
2546 if let ty::TyParam(p) = ty.sty {
2547 assert!(p.space == TypeSpace);
2548 let idx = p.idx as usize;
2549 if !ty_params.contains(&idx) {
2550 ty_params.push(idx);
2554 if ty_params.is_empty() {
2555 return Err(Unimplemented);
2558 // Replace type parameters used in unsizing with
2559 // TyError and ensure they do not affect any other fields.
2560 // This could be checked after type collection for any struct
2561 // with a potentially unsized trailing field.
2562 let mut new_substs = substs_a.clone();
2563 for &i in &ty_params {
2564 new_substs.types.get_mut_slice(TypeSpace)[i] = tcx.types.err;
2566 for &ty in fields.split_last().unwrap().1 {
2567 if ty.subst(tcx, &new_substs).references_error() {
2568 return Err(Unimplemented);
2572 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2573 let inner_source = field.subst(tcx, substs_a);
2574 let inner_target = field.subst(tcx, substs_b);
2576 // Check that the source structure with the target's
2577 // type parameters is a subtype of the target.
2578 for &i in &ty_params {
2579 let param_b = *substs_b.types.get(TypeSpace, i);
2580 new_substs.types.get_mut_slice(TypeSpace)[i] = param_b;
2582 let new_struct = tcx.mk_struct(def, tcx.mk_substs(new_substs));
2583 let origin = infer::Misc(obligation.cause.span);
2584 if self.infcx.sub_types(false, origin, new_struct, target).is_err() {
2585 return Err(Unimplemented);
2588 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2589 nested.push(util::predicate_for_trait_def(tcx,
2590 obligation.cause.clone(),
2591 obligation.predicate.def_id(),
2592 obligation.recursion_depth + 1,
2594 vec![inner_target]));
2600 Ok(VtableBuiltinData { nested: nested })
2603 ///////////////////////////////////////////////////////////////////////////
2606 // Matching is a common path used for both evaluation and
2607 // confirmation. It basically unifies types that appear in impls
2608 // and traits. This does affect the surrounding environment;
2609 // therefore, when used during evaluation, match routines must be
2610 // run inside of a `probe()` so that their side-effects are
2613 fn rematch_impl(&mut self,
2615 obligation: &TraitObligation<'tcx>,
2616 snapshot: &infer::CombinedSnapshot)
2617 -> (Normalized<'tcx, Substs<'tcx>>, infer::SkolemizationMap)
2619 match self.match_impl(impl_def_id, obligation, snapshot) {
2620 Ok((substs, skol_map)) => (substs, skol_map),
2622 self.tcx().sess.bug(
2623 &format!("Impl {:?} was matchable against {:?} but now is not",
2630 fn match_impl(&mut self,
2632 obligation: &TraitObligation<'tcx>,
2633 snapshot: &infer::CombinedSnapshot)
2634 -> Result<(Normalized<'tcx, Substs<'tcx>>,
2635 infer::SkolemizationMap), ()>
2637 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2639 // Before we create the substitutions and everything, first
2640 // consider a "quick reject". This avoids creating more types
2641 // and so forth that we need to.
2642 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2646 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2647 &obligation.predicate,
2649 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2651 let impl_substs = util::fresh_type_vars_for_impl(self.infcx,
2652 obligation.cause.span,
2655 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2658 let impl_trait_ref =
2659 project::normalize_with_depth(self,
2660 obligation.cause.clone(),
2661 obligation.recursion_depth + 1,
2664 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2665 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2669 skol_obligation_trait_ref);
2671 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
2672 if let Err(e) = self.infcx.sub_trait_refs(false,
2674 impl_trait_ref.value.clone(),
2675 skol_obligation_trait_ref) {
2676 debug!("match_impl: failed sub_trait_refs due to `{}`", e);
2680 if let Err(e) = self.infcx.leak_check(&skol_map, snapshot) {
2681 debug!("match_impl: failed leak check due to `{}`", e);
2685 debug!("match_impl: success impl_substs={:?}", impl_substs);
2688 obligations: impl_trait_ref.obligations
2692 fn fast_reject_trait_refs(&mut self,
2693 obligation: &TraitObligation,
2694 impl_trait_ref: &ty::TraitRef)
2697 // We can avoid creating type variables and doing the full
2698 // substitution if we find that any of the input types, when
2699 // simplified, do not match.
2701 obligation.predicate.0.input_types().iter()
2702 .zip(impl_trait_ref.input_types())
2703 .any(|(&obligation_ty, &impl_ty)| {
2704 let simplified_obligation_ty =
2705 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2706 let simplified_impl_ty =
2707 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2709 simplified_obligation_ty.is_some() &&
2710 simplified_impl_ty.is_some() &&
2711 simplified_obligation_ty != simplified_impl_ty
2715 /// Normalize `where_clause_trait_ref` and try to match it against
2716 /// `obligation`. If successful, return any predicates that
2717 /// result from the normalization. Normalization is necessary
2718 /// because where-clauses are stored in the parameter environment
2720 fn match_where_clause_trait_ref(&mut self,
2721 obligation: &TraitObligation<'tcx>,
2722 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2723 -> Result<Vec<PredicateObligation<'tcx>>,()>
2725 try!(self.match_poly_trait_ref(obligation, where_clause_trait_ref));
2729 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2730 /// obligation is satisfied.
2731 fn match_poly_trait_ref(&self,
2732 obligation: &TraitObligation<'tcx>,
2733 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2736 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2740 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
2741 match self.infcx.sub_poly_trait_refs(false,
2744 obligation.predicate.to_poly_trait_ref()) {
2750 /// Determines whether the self type declared against
2751 /// `impl_def_id` matches `obligation_self_ty`. If successful,
2752 /// returns the substitutions used to make them match. See
2753 /// `match_impl()`. For example, if `impl_def_id` is declared
2756 /// impl<T:Copy> Foo for Box<T> { ... }
2758 /// and `obligation_self_ty` is `int`, we'd get back an `Err(_)`
2759 /// result. But if `obligation_self_ty` were `Box<int>`, we'd get
2760 /// back `Ok(T=int)`.
2761 fn match_inherent_impl(&mut self,
2763 obligation_cause: &ObligationCause,
2764 obligation_self_ty: Ty<'tcx>)
2765 -> Result<Substs<'tcx>,()>
2767 // Create fresh type variables for each type parameter declared
2769 let impl_substs = util::fresh_type_vars_for_impl(self.infcx,
2770 obligation_cause.span,
2773 // Find the self type for the impl.
2774 let impl_self_ty = self.tcx().lookup_item_type(impl_def_id).ty;
2775 let impl_self_ty = impl_self_ty.subst(self.tcx(), &impl_substs);
2777 debug!("match_impl_self_types(obligation_self_ty={:?}, impl_self_ty={:?})",
2781 match self.match_self_types(obligation_cause,
2783 obligation_self_ty) {
2785 debug!("Matched impl_substs={:?}", impl_substs);
2795 fn match_self_types(&mut self,
2796 cause: &ObligationCause,
2798 // The self type provided by the impl/caller-obligation:
2799 provided_self_ty: Ty<'tcx>,
2801 // The self type the obligation is for:
2802 required_self_ty: Ty<'tcx>)
2805 // FIXME(#5781) -- equating the types is stronger than
2806 // necessary. Should consider variance of trait w/r/t Self.
2808 let origin = infer::RelateSelfType(cause.span);
2809 match self.infcx.eq_types(false,
2818 ///////////////////////////////////////////////////////////////////////////
2821 fn match_fresh_trait_refs(&self,
2822 previous: &ty::PolyTraitRef<'tcx>,
2823 current: &ty::PolyTraitRef<'tcx>)
2826 let mut matcher = ty::_match::Match::new(self.tcx());
2827 matcher.relate(previous, current).is_ok()
2830 fn push_stack<'o,'s:'o>(&mut self,
2831 previous_stack: TraitObligationStackList<'s, 'tcx>,
2832 obligation: &'o TraitObligation<'tcx>)
2833 -> TraitObligationStack<'o, 'tcx>
2835 let fresh_trait_ref =
2836 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2838 TraitObligationStack {
2839 obligation: obligation,
2840 fresh_trait_ref: fresh_trait_ref,
2841 previous: previous_stack,
2845 fn closure_trait_ref_unnormalized(&mut self,
2846 obligation: &TraitObligation<'tcx>,
2847 closure_def_id: DefId,
2848 substs: &ty::ClosureSubsts<'tcx>)
2849 -> ty::PolyTraitRef<'tcx>
2851 let closure_type = self.infcx.closure_type(closure_def_id, substs);
2852 let ty::Binder((trait_ref, _)) =
2853 util::closure_trait_ref_and_return_type(self.tcx(),
2854 obligation.predicate.def_id(),
2855 obligation.predicate.0.self_ty(), // (1)
2857 util::TupleArgumentsFlag::No);
2858 // (1) Feels icky to skip the binder here, but OTOH we know
2859 // that the self-type is an unboxed closure type and hence is
2860 // in fact unparameterized (or at least does not reference any
2861 // regions bound in the obligation). Still probably some
2862 // refactoring could make this nicer.
2864 ty::Binder(trait_ref)
2867 fn closure_trait_ref(&mut self,
2868 obligation: &TraitObligation<'tcx>,
2869 closure_def_id: DefId,
2870 substs: &ty::ClosureSubsts<'tcx>)
2871 -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
2873 let trait_ref = self.closure_trait_ref_unnormalized(
2874 obligation, closure_def_id, substs);
2876 // A closure signature can contain associated types which
2877 // must be normalized.
2878 normalize_with_depth(self,
2879 obligation.cause.clone(),
2880 obligation.recursion_depth+1,
2884 /// Returns the obligations that are implied by instantiating an
2885 /// impl or trait. The obligations are substituted and fully
2886 /// normalized. This is used when confirming an impl or default
2888 fn impl_or_trait_obligations(&mut self,
2889 cause: ObligationCause<'tcx>,
2890 recursion_depth: usize,
2891 def_id: DefId, // of impl or trait
2892 substs: &Substs<'tcx>, // for impl or trait
2893 skol_map: infer::SkolemizationMap,
2894 snapshot: &infer::CombinedSnapshot)
2895 -> Vec<PredicateObligation<'tcx>>
2897 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2899 let predicates = self.tcx().lookup_predicates(def_id);
2900 let predicates = predicates.instantiate(self.tcx(), substs);
2901 let predicates = normalize_with_depth(self, cause.clone(), recursion_depth, &predicates);
2902 let mut predicates = self.infcx().plug_leaks(skol_map, snapshot, &predicates);
2903 let mut obligations =
2904 util::predicates_for_generics(cause,
2907 obligations.append(&mut predicates.obligations);
2911 #[allow(unused_comparisons)]
2912 fn derived_cause(&self,
2913 obligation: &TraitObligation<'tcx>,
2914 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2915 -> ObligationCause<'tcx>
2918 * Creates a cause for obligations that are derived from
2919 * `obligation` by a recursive search (e.g., for a builtin
2920 * bound, or eventually a `impl Foo for ..`). If `obligation`
2921 * is itself a derived obligation, this is just a clone, but
2922 * otherwise we create a "derived obligation" cause so as to
2923 * keep track of the original root obligation for error
2927 // NOTE(flaper87): As of now, it keeps track of the whole error
2928 // chain. Ideally, we should have a way to configure this either
2929 // by using -Z verbose or just a CLI argument.
2930 if obligation.recursion_depth >= 0 {
2931 let derived_code = match obligation.cause.code {
2932 ObligationCauseCode::RFC1214(ref base_code) => {
2933 let derived_cause = DerivedObligationCause {
2934 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2935 parent_code: base_code.clone(),
2937 ObligationCauseCode::RFC1214(Rc::new(variant(derived_cause)))
2940 let derived_cause = DerivedObligationCause {
2941 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2942 parent_code: Rc::new(obligation.cause.code.clone())
2944 variant(derived_cause)
2947 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2949 obligation.cause.clone()
2954 impl<'tcx> SelectionCache<'tcx> {
2955 pub fn new() -> SelectionCache<'tcx> {
2957 hashmap: RefCell::new(FnvHashMap())
2962 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
2963 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
2964 TraitObligationStackList::with(self)
2967 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
2972 #[derive(Copy, Clone)]
2973 struct TraitObligationStackList<'o,'tcx:'o> {
2974 head: Option<&'o TraitObligationStack<'o,'tcx>>
2977 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
2978 fn empty() -> TraitObligationStackList<'o,'tcx> {
2979 TraitObligationStackList { head: None }
2982 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
2983 TraitObligationStackList { head: Some(r) }
2987 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
2988 type Item = &'o TraitObligationStack<'o,'tcx>;
2990 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3001 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3002 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3003 write!(f, "TraitObligationStack({:?})", self.obligation)
3007 impl<'tcx> EvaluationResult<'tcx> {
3008 fn may_apply(&self) -> bool {
3012 EvaluatedToErr(OutputTypeParameterMismatch(..)) |
3013 EvaluatedToErr(TraitNotObjectSafe(_)) =>
3016 EvaluatedToErr(Unimplemented) =>
3022 impl MethodMatchResult {
3023 pub fn may_apply(&self) -> bool {
3025 MethodMatched(_) => true,
3026 MethodAmbiguous(_) => true,
3027 MethodDidNotMatch => false,