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 middle::def_id::DefId;
42 use middle::infer::{InferCtxt, TypeFreshener};
43 use middle::subst::{Subst, Substs, TypeSpace};
44 use middle::ty::{self, ToPredicate, RegionEscape, ToPolyTraitRef, Ty, HasTypeFlags};
45 use middle::ty::fast_reject;
46 use middle::ty::fold::TypeFoldable;
47 use middle::ty::relate::TypeRelation;
49 use std::cell::RefCell;
54 use util::common::ErrorReported;
55 use util::nodemap::FnvHashMap;
57 pub struct SelectionContext<'cx, 'tcx:'cx> {
58 infcx: &'cx InferCtxt<'cx, 'tcx>,
60 /// Freshener used specifically for skolemizing entries on the
61 /// obligation stack. This ensures that all entries on the stack
62 /// at one time will have the same set of skolemized entries,
63 /// which is important for checking for trait bounds that
64 /// recursively require themselves.
65 freshener: TypeFreshener<'cx, 'tcx>,
67 /// If true, indicates that the evaluation should be conservative
68 /// and consider the possibility of types outside this crate.
69 /// This comes up primarily when resolving ambiguity. Imagine
70 /// there is some trait reference `$0 : Bar` where `$0` is an
71 /// inference variable. If `intercrate` is true, then we can never
72 /// say for sure that this reference is not implemented, even if
73 /// there are *no impls at all for `Bar`*, because `$0` could be
74 /// bound to some type that in a downstream crate that implements
75 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
76 /// though, we set this to false, because we are only interested
77 /// in types that the user could actually have written --- in
78 /// other words, we consider `$0 : Bar` to be unimplemented if
79 /// there is no type that the user could *actually name* that
80 /// would satisfy it. This avoids crippling inference, basically.
85 // A stack that walks back up the stack frame.
86 struct TraitObligationStack<'prev, 'tcx: 'prev> {
87 obligation: &'prev TraitObligation<'tcx>,
89 /// Trait ref from `obligation` but skolemized with the
90 /// selection-context's freshener. Used to check for recursion.
91 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
93 previous: TraitObligationStackList<'prev, 'tcx>,
97 pub struct SelectionCache<'tcx> {
98 hashmap: RefCell<FnvHashMap<ty::TraitRef<'tcx>,
99 SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
102 pub enum MethodMatchResult {
103 MethodMatched(MethodMatchedData),
104 MethodAmbiguous(/* list of impls that could apply */ Vec<DefId>),
108 #[derive(Copy, Clone, Debug)]
109 pub enum MethodMatchedData {
110 // In the case of a precise match, we don't really need to store
111 // how the match was found. So don't.
114 // In the case of a coercion, we need to know the precise impl so
115 // that we can determine the type to which things were coerced.
116 CoerciveMethodMatch(/* impl we matched */ DefId)
119 /// The selection process begins by considering all impls, where
120 /// clauses, and so forth that might resolve an obligation. Sometimes
121 /// we'll be able to say definitively that (e.g.) an impl does not
122 /// apply to the obligation: perhaps it is defined for `usize` but the
123 /// obligation is for `int`. In that case, we drop the impl out of the
124 /// list. But the other cases are considered *candidates*.
126 /// For selection to succeed, there must be exactly one matching
127 /// candidate. If the obligation is fully known, this is guaranteed
128 /// by coherence. However, if the obligation contains type parameters
129 /// or variables, there may be multiple such impls.
131 /// It is not a real problem if multiple matching impls exist because
132 /// of type variables - it just means the obligation isn't sufficiently
133 /// elaborated. In that case we report an ambiguity, and the caller can
134 /// try again after more type information has been gathered or report a
135 /// "type annotations required" error.
137 /// However, with type parameters, this can be a real problem - type
138 /// parameters don't unify with regular types, but they *can* unify
139 /// with variables from blanket impls, and (unless we know its bounds
140 /// will always be satisfied) picking the blanket impl will be wrong
141 /// for at least *some* substitutions. To make this concrete, if we have
143 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
144 /// impl<T: fmt::Debug> AsDebug for T {
146 /// fn debug(self) -> fmt::Debug { self }
148 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
150 /// we can't just use the impl to resolve the <T as AsDebug> obligation
151 /// - a type from another crate (that doesn't implement fmt::Debug) could
152 /// implement AsDebug.
154 /// Because where-clauses match the type exactly, multiple clauses can
155 /// only match if there are unresolved variables, and we can mostly just
156 /// report this ambiguity in that case. This is still a problem - we can't
157 /// *do anything* with ambiguities that involve only regions. This is issue
160 /// If a single where-clause matches and there are no inference
161 /// variables left, then it definitely matches and we can just select
164 /// In fact, we even select the where-clause when the obligation contains
165 /// inference variables. The can lead to inference making "leaps of logic",
166 /// for example in this situation:
168 /// pub trait Foo<T> { fn foo(&self) -> T; }
169 /// impl<T> Foo<()> for T { fn foo(&self) { } }
170 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
172 /// pub fn foo<T>(t: T) where T: Foo<bool> {
173 /// println!("{:?}", <T as Foo<_>>::foo(&t));
175 /// fn main() { foo(false); }
177 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
178 /// impl and the where-clause. We select the where-clause and unify $0=bool,
179 /// so the program prints "false". However, if the where-clause is omitted,
180 /// the blanket impl is selected, we unify $0=(), and the program prints
183 /// Exactly the same issues apply to projection and object candidates, except
184 /// that we can have both a projection candidate and a where-clause candidate
185 /// for the same obligation. In that case either would do (except that
186 /// different "leaps of logic" would occur if inference variables are
187 /// present), and we just pick the where-clause. This is, for example,
188 /// required for associated types to work in default impls, as the bounds
189 /// are visible both as projection bounds and as where-clauses from the
190 /// parameter environment.
191 #[derive(PartialEq,Eq,Debug,Clone)]
192 enum SelectionCandidate<'tcx> {
194 BuiltinCandidate(ty::BuiltinBound),
195 ParamCandidate(ty::PolyTraitRef<'tcx>),
196 ImplCandidate(DefId),
197 DefaultImplCandidate(DefId),
198 DefaultImplObjectCandidate(DefId),
200 /// This is a trait matching with a projected type as `Self`, and
201 /// we found an applicable bound in the trait definition.
204 /// Implementation of a `Fn`-family trait by one of the
205 /// anonymous types generated for a `||` expression.
206 ClosureCandidate(/* closure */ DefId, &'tcx ty::ClosureSubsts<'tcx>),
208 /// Implementation of a `Fn`-family trait by one of the anonymous
209 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
214 BuiltinObjectCandidate,
216 BuiltinUnsizeCandidate,
221 struct SelectionCandidateSet<'tcx> {
222 // a list of candidates that definitely apply to the current
223 // obligation (meaning: types unify).
224 vec: Vec<SelectionCandidate<'tcx>>,
226 // if this is true, then there were candidates that might or might
227 // not have applied, but we couldn't tell. This occurs when some
228 // of the input types are type variables, in which case there are
229 // various "builtin" rules that might or might not trigger.
233 enum BuiltinBoundConditions<'tcx> {
234 If(ty::Binder<Vec<Ty<'tcx>>>),
240 enum EvaluationResult<'tcx> {
243 EvaluatedToErr(SelectionError<'tcx>),
246 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
247 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>)
248 -> SelectionContext<'cx, 'tcx> {
251 freshener: infcx.freshener(),
256 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>)
257 -> SelectionContext<'cx, 'tcx> {
260 freshener: infcx.freshener(),
265 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
269 pub fn tcx(&self) -> &'cx ty::ctxt<'tcx> {
273 pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'cx, 'tcx> {
274 self.infcx.param_env()
277 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
281 ///////////////////////////////////////////////////////////////////////////
284 // The selection phase tries to identify *how* an obligation will
285 // be resolved. For example, it will identify which impl or
286 // parameter bound is to be used. The process can be inconclusive
287 // if the self type in the obligation is not fully inferred. Selection
288 // can result in an error in one of two ways:
290 // 1. If no applicable impl or parameter bound can be found.
291 // 2. If the output type parameters in the obligation do not match
292 // those specified by the impl/bound. For example, if the obligation
293 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
294 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
296 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
297 /// type environment by performing unification.
298 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
299 -> SelectionResult<'tcx, Selection<'tcx>> {
300 debug!("select({:?})", obligation);
301 assert!(!obligation.predicate.has_escaping_regions());
303 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
304 match try!(self.candidate_from_obligation(&stack)) {
306 self.consider_unification_despite_ambiguity(obligation);
309 Some(candidate) => Ok(Some(try!(self.confirm_candidate(obligation, candidate)))),
313 /// In the particular case of unboxed closure obligations, we can
314 /// sometimes do some amount of unification for the
315 /// argument/return types even though we can't yet fully match obligation.
316 /// The particular case we are interesting in is an obligation of the form:
320 /// where `C` is an unboxed closure type and `FnFoo` is one of the
321 /// `Fn` traits. Because we know that users cannot write impls for closure types
322 /// themselves, the only way that `C : FnFoo` can fail to match is under two
325 /// 1. The closure kind for `C` is not yet known, because inference isn't complete.
326 /// 2. The closure kind for `C` *is* known, but doesn't match what is needed.
327 /// For example, `C` may be a `FnOnce` closure, but a `Fn` closure is needed.
329 /// In either case, we always know what argument types are
330 /// expected by `C`, no matter what kind of `Fn` trait it
331 /// eventually matches. So we can go ahead and unify the argument
332 /// types, even though the end result is ambiguous.
334 /// Note that this is safe *even if* the trait would never be
335 /// matched (case 2 above). After all, in that case, an error will
336 /// result, so it kind of doesn't matter what we do --- unifying
337 /// the argument types can only be helpful to the user, because
338 /// once they patch up the kind of closure that is expected, the
339 /// argment types won't really change.
340 fn consider_unification_despite_ambiguity(&mut self, obligation: &TraitObligation<'tcx>) {
341 // Is this a `C : FnFoo(...)` trait reference for some trait binding `FnFoo`?
342 match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
347 // Is the self-type a closure type? We ignore bindings here
348 // because if it is a closure type, it must be a closure type from
349 // within this current fn, and hence none of the higher-ranked
350 // lifetimes can appear inside the self-type.
351 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
352 let (closure_def_id, substs) = match self_ty.sty {
353 ty::TyClosure(id, ref substs) => (id, substs),
356 assert!(!substs.has_escaping_regions());
358 // It is OK to call the unnormalized variant here - this is only
359 // reached for TyClosure: Fn inputs where the closure kind is
360 // still unknown, which should only occur in typeck where the
361 // closure type is already normalized.
362 let closure_trait_ref = self.closure_trait_ref_unnormalized(obligation,
366 match self.confirm_poly_trait_refs(obligation.cause.clone(),
367 obligation.predicate.to_poly_trait_ref(),
370 Err(_) => { /* Silently ignore errors. */ }
374 ///////////////////////////////////////////////////////////////////////////
377 // Tests whether an obligation can be selected or whether an impl
378 // can be applied to particular types. It skips the "confirmation"
379 // step and hence completely ignores output type parameters.
381 // The result is "true" if the obligation *may* hold and "false" if
382 // we can be sure it does not.
384 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
385 pub fn evaluate_obligation(&mut self,
386 obligation: &PredicateObligation<'tcx>)
389 debug!("evaluate_obligation({:?})",
392 self.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
396 fn evaluate_builtin_bound_recursively<'o>(&mut self,
397 bound: ty::BuiltinBound,
398 previous_stack: &TraitObligationStack<'o, 'tcx>,
400 -> EvaluationResult<'tcx>
403 util::predicate_for_builtin_bound(
405 previous_stack.obligation.cause.clone(),
407 previous_stack.obligation.recursion_depth + 1,
412 self.evaluate_predicate_recursively(previous_stack.list(), &obligation)
414 Err(ErrorReported) => {
420 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
421 stack: TraitObligationStackList<'o, 'tcx>,
423 -> EvaluationResult<'tcx>
424 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
426 let mut result = EvaluatedToOk;
427 for obligation in predicates {
428 match self.evaluate_predicate_recursively(stack, obligation) {
429 EvaluatedToErr(e) => { return EvaluatedToErr(e); }
430 EvaluatedToAmbig => { result = EvaluatedToAmbig; }
437 fn evaluate_predicate_recursively<'o>(&mut self,
438 previous_stack: TraitObligationStackList<'o, 'tcx>,
439 obligation: &PredicateObligation<'tcx>)
440 -> EvaluationResult<'tcx>
442 debug!("evaluate_predicate_recursively({:?})",
445 // Check the cache from the tcx of predicates that we know
446 // have been proven elsewhere. This cache only contains
447 // predicates that are global in scope and hence unaffected by
448 // the current environment.
449 let w = RFC1214Warning(false);
450 if self.tcx().fulfilled_predicates.borrow().is_duplicate(w, &obligation.predicate) {
451 return EvaluatedToOk;
454 match obligation.predicate {
455 ty::Predicate::Trait(ref t) => {
456 assert!(!t.has_escaping_regions());
457 let obligation = obligation.with(t.clone());
458 self.evaluate_obligation_recursively(previous_stack, &obligation)
461 ty::Predicate::Equate(ref p) => {
462 let result = self.infcx.probe(|_| {
463 self.infcx.equality_predicate(obligation.cause.span, p)
466 Ok(()) => EvaluatedToOk,
467 Err(_) => EvaluatedToErr(Unimplemented),
471 ty::Predicate::WellFormed(ty) => {
472 match ty::wf::obligations(self.infcx, obligation.cause.body_id,
473 ty, obligation.cause.span,
474 obligation.cause.code.is_rfc1214()) {
476 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
482 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
483 // we do not consider region relationships when
484 // evaluating trait matches
488 ty::Predicate::ObjectSafe(trait_def_id) => {
489 if object_safety::is_object_safe(self.tcx(), trait_def_id) {
492 EvaluatedToErr(Unimplemented)
496 ty::Predicate::Projection(ref data) => {
497 self.infcx.probe(|_| {
498 let project_obligation = obligation.with(data.clone());
499 match project::poly_project_and_unify_type(self, &project_obligation) {
500 Ok(Some(subobligations)) => {
501 self.evaluate_predicates_recursively(previous_stack,
502 subobligations.iter())
508 EvaluatedToErr(Unimplemented)
516 fn evaluate_obligation_recursively<'o>(&mut self,
517 previous_stack: TraitObligationStackList<'o, 'tcx>,
518 obligation: &TraitObligation<'tcx>)
519 -> EvaluationResult<'tcx>
521 debug!("evaluate_obligation_recursively({:?})",
524 let stack = self.push_stack(previous_stack, obligation);
526 let result = self.evaluate_stack(&stack);
528 debug!("result: {:?}", result);
532 fn evaluate_stack<'o>(&mut self,
533 stack: &TraitObligationStack<'o, 'tcx>)
534 -> EvaluationResult<'tcx>
536 // In intercrate mode, whenever any of the types are unbound,
537 // there can always be an impl. Even if there are no impls in
538 // this crate, perhaps the type would be unified with
539 // something from another crate that does provide an impl.
541 // In intracrate mode, we must still be conservative. The reason is
542 // that we want to avoid cycles. Imagine an impl like:
544 // impl<T:Eq> Eq for Vec<T>
546 // and a trait reference like `$0 : Eq` where `$0` is an
547 // unbound variable. When we evaluate this trait-reference, we
548 // will unify `$0` with `Vec<$1>` (for some fresh variable
549 // `$1`), on the condition that `$1 : Eq`. We will then wind
550 // up with many candidates (since that are other `Eq` impls
551 // that apply) and try to winnow things down. This results in
552 // a recursive evaluation that `$1 : Eq` -- as you can
553 // imagine, this is just where we started. To avoid that, we
554 // check for unbound variables and return an ambiguous (hence possible)
555 // match if we've seen this trait before.
557 // This suffices to allow chains like `FnMut` implemented in
558 // terms of `Fn` etc, but we could probably make this more
560 let input_types = stack.fresh_trait_ref.0.input_types();
561 let unbound_input_types = input_types.iter().any(|ty| ty.is_fresh());
563 unbound_input_types &&
565 stack.iter().skip(1).any(
566 |prev| self.match_fresh_trait_refs(&stack.fresh_trait_ref,
567 &prev.fresh_trait_ref)))
569 debug!("evaluate_stack({:?}) --> unbound argument, recursion --> ambiguous",
570 stack.fresh_trait_ref);
571 return EvaluatedToAmbig;
574 // If there is any previous entry on the stack that precisely
575 // matches this obligation, then we can assume that the
576 // obligation is satisfied for now (still all other conditions
577 // must be met of course). One obvious case this comes up is
578 // marker traits like `Send`. Think of a linked list:
580 // struct List<T> { data: T, next: Option<Box<List<T>>> {
582 // `Box<List<T>>` will be `Send` if `T` is `Send` and
583 // `Option<Box<List<T>>>` is `Send`, and in turn
584 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
587 // Note that we do this comparison using the `fresh_trait_ref`
588 // fields. Because these have all been skolemized using
589 // `self.freshener`, we can be sure that (a) this will not
590 // affect the inferencer state and (b) that if we see two
591 // skolemized types with the same index, they refer to the
592 // same unbound type variable.
595 .skip(1) // skip top-most frame
596 .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref)
598 debug!("evaluate_stack({:?}) --> recursive",
599 stack.fresh_trait_ref);
600 return EvaluatedToOk;
603 match self.candidate_from_obligation(stack) {
604 Ok(Some(c)) => self.winnow_candidate(stack, &c),
605 Ok(None) => EvaluatedToAmbig,
606 Err(e) => EvaluatedToErr(e),
610 /// Evaluates whether the impl with id `impl_def_id` could be applied to the self type
611 /// `obligation_self_ty`. This can be used either for trait or inherent impls.
612 pub fn evaluate_impl(&mut self,
614 obligation: &TraitObligation<'tcx>)
617 debug!("evaluate_impl(impl_def_id={:?}, obligation={:?})",
621 self.infcx.probe(|snapshot| {
622 match self.match_impl(impl_def_id, obligation, snapshot) {
623 Ok((substs, skol_map)) => {
624 let vtable_impl = self.vtable_impl(impl_def_id,
626 obligation.cause.clone(),
627 obligation.recursion_depth + 1,
630 self.winnow_selection(TraitObligationStackList::empty(),
631 VtableImpl(vtable_impl)).may_apply()
640 ///////////////////////////////////////////////////////////////////////////
641 // CANDIDATE ASSEMBLY
643 // The selection process begins by examining all in-scope impls,
644 // caller obligations, and so forth and assembling a list of
645 // candidates. See `README.md` and the `Candidate` type for more
648 fn candidate_from_obligation<'o>(&mut self,
649 stack: &TraitObligationStack<'o, 'tcx>)
650 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
652 // Watch out for overflow. This intentionally bypasses (and does
653 // not update) the cache.
654 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
655 if stack.obligation.recursion_depth >= recursion_limit {
656 report_overflow_error(self.infcx(), &stack.obligation);
659 // Check the cache. Note that we skolemize the trait-ref
660 // separately rather than using `stack.fresh_trait_ref` -- this
661 // is because we want the unbound variables to be replaced
662 // with fresh skolemized types starting from index 0.
663 let cache_fresh_trait_pred =
664 self.infcx.freshen(stack.obligation.predicate.clone());
665 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
666 cache_fresh_trait_pred,
668 assert!(!stack.obligation.predicate.has_escaping_regions());
670 match self.check_candidate_cache(&cache_fresh_trait_pred) {
672 debug!("CACHE HIT: cache_fresh_trait_pred={:?}, candidate={:?}",
673 cache_fresh_trait_pred,
680 // If no match, compute result and insert into cache.
681 let candidate = self.candidate_from_obligation_no_cache(stack);
683 if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
684 debug!("CACHE MISS: cache_fresh_trait_pred={:?}, candidate={:?}",
685 cache_fresh_trait_pred, candidate);
686 self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone());
692 fn candidate_from_obligation_no_cache<'o>(&mut self,
693 stack: &TraitObligationStack<'o, 'tcx>)
694 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
696 if stack.obligation.predicate.0.self_ty().references_error() {
697 return Ok(Some(ErrorCandidate));
700 if !self.is_knowable(stack) {
701 debug!("intercrate not knowable");
705 let candidate_set = try!(self.assemble_candidates(stack));
707 if candidate_set.ambiguous {
708 debug!("candidate set contains ambig");
712 let mut candidates = candidate_set.vec;
714 debug!("assembled {} candidates for {:?}: {:?}",
719 // At this point, we know that each of the entries in the
720 // candidate set is *individually* applicable. Now we have to
721 // figure out if they contain mutual incompatibilities. This
722 // frequently arises if we have an unconstrained input type --
723 // for example, we are looking for $0:Eq where $0 is some
724 // unconstrained type variable. In that case, we'll get a
725 // candidate which assumes $0 == int, one that assumes $0 ==
726 // usize, etc. This spells an ambiguity.
728 // If there is more than one candidate, first winnow them down
729 // by considering extra conditions (nested obligations and so
730 // forth). We don't winnow if there is exactly one
731 // candidate. This is a relatively minor distinction but it
732 // can lead to better inference and error-reporting. An
733 // example would be if there was an impl:
735 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
737 // and we were to see some code `foo.push_clone()` where `boo`
738 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
739 // we were to winnow, we'd wind up with zero candidates.
740 // Instead, we select the right impl now but report `Bar does
741 // not implement Clone`.
742 if candidates.len() > 1 {
743 candidates.retain(|c| self.winnow_candidate(stack, c).may_apply())
746 // If there are STILL multiple candidate, we can further reduce
747 // the list by dropping duplicates.
748 if candidates.len() > 1 {
750 while i < candidates.len() {
752 (0..candidates.len())
754 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
757 debug!("Dropping candidate #{}/{}: {:?}",
758 i, candidates.len(), candidates[i]);
759 candidates.swap_remove(i);
761 debug!("Retaining candidate #{}/{}: {:?}",
762 i, candidates.len(), candidates[i]);
768 // If there are *STILL* multiple candidates, give up and
770 if candidates.len() > 1 {
771 debug!("multiple matches, ambig");
776 // If there are *NO* candidates, that there are no impls --
777 // that we know of, anyway. Note that in the case where there
778 // are unbound type variables within the obligation, it might
779 // be the case that you could still satisfy the obligation
780 // from another crate by instantiating the type variables with
781 // a type from another crate that does have an impl. This case
782 // is checked for in `evaluate_stack` (and hence users
783 // who might care about this case, like coherence, should use
785 if candidates.is_empty() {
786 return Err(Unimplemented);
789 // Just one candidate left.
790 let candidate = candidates.pop().unwrap();
793 ImplCandidate(def_id) => {
794 match self.tcx().trait_impl_polarity(def_id) {
795 Some(hir::ImplPolarity::Negative) => return Err(Unimplemented),
805 fn is_knowable<'o>(&mut self,
806 stack: &TraitObligationStack<'o, 'tcx>)
809 debug!("is_knowable(intercrate={})", self.intercrate);
811 if !self.intercrate {
815 let obligation = &stack.obligation;
816 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
818 // ok to skip binder because of the nature of the
819 // trait-ref-is-knowable check, which does not care about
821 let trait_ref = &predicate.skip_binder().trait_ref;
823 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
826 fn pick_candidate_cache(&self) -> &SelectionCache<'tcx> {
827 // If there are any where-clauses in scope, then we always use
828 // a cache local to this particular scope. Otherwise, we
829 // switch to a global cache. We used to try and draw
830 // finer-grained distinctions, but that led to a serious of
831 // annoying and weird bugs like #22019 and #18290. This simple
832 // rule seems to be pretty clearly safe and also still retains
833 // a very high hit rate (~95% when compiling rustc).
834 if !self.param_env().caller_bounds.is_empty() {
835 return &self.param_env().selection_cache;
838 // Avoid using the master cache during coherence and just rely
839 // on the local cache. This effectively disables caching
840 // during coherence. It is really just a simplification to
841 // avoid us having to fear that coherence results "pollute"
842 // the master cache. Since coherence executes pretty quickly,
843 // it's not worth going to more trouble to increase the
844 // hit-rate I don't think.
846 return &self.param_env().selection_cache;
849 // Otherwise, we can use the global cache.
850 &self.tcx().selection_cache
853 fn check_candidate_cache(&mut self,
854 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
855 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
857 let cache = self.pick_candidate_cache();
858 let hashmap = cache.hashmap.borrow();
859 hashmap.get(&cache_fresh_trait_pred.0.trait_ref).cloned()
862 fn insert_candidate_cache(&mut self,
863 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
864 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
866 let cache = self.pick_candidate_cache();
867 let mut hashmap = cache.hashmap.borrow_mut();
868 hashmap.insert(cache_fresh_trait_pred.0.trait_ref.clone(), candidate);
871 fn should_update_candidate_cache(&mut self,
872 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
873 candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
876 // In general, it's a good idea to cache results, even
877 // ambiguous ones, to save us some trouble later. But we have
878 // to be careful not to cache results that could be
879 // invalidated later by advances in inference. Normally, this
880 // is not an issue, because any inference variables whose
881 // types are not yet bound are "freshened" in the cache key,
882 // which means that if we later get the same request once that
883 // type variable IS bound, we'll have a different cache key.
884 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
885 // not yet known, we may cache the result as `None`. But if
886 // later `_#0t` is bound to `Bar`, then when we freshen we'll
887 // have `Vec<Bar> : Foo` as the cache key.
889 // HOWEVER, it CAN happen that we get an ambiguity result in
890 // one particular case around closures where the cache key
891 // would not change. That is when the precise types of the
892 // upvars that a closure references have not yet been figured
893 // out (i.e., because it is not yet known if they are captured
894 // by ref, and if by ref, what kind of ref). In these cases,
895 // when matching a builtin bound, we will yield back an
896 // ambiguous result. But the *cache key* is just the closure type,
897 // it doesn't capture the state of the upvar computation.
899 // To avoid this trap, just don't cache ambiguous results if
900 // the self-type contains no inference byproducts (that really
901 // shouldn't happen in other circumstances anyway, given
905 Ok(Some(_)) | Err(_) => true,
907 cache_fresh_trait_pred.0.input_types().has_infer_types()
912 fn assemble_candidates<'o>(&mut self,
913 stack: &TraitObligationStack<'o, 'tcx>)
914 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
916 let TraitObligationStack { obligation, .. } = *stack;
917 let ref obligation = Obligation {
918 cause: obligation.cause.clone(),
919 recursion_depth: obligation.recursion_depth,
920 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
923 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
924 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
926 // This is somewhat problematic, as the current scheme can't really
927 // handle it turning to be a projection. This does end up as truly
928 // ambiguous in most cases anyway.
930 // Until this is fixed, take the fast path out - this also improves
931 // performance by preventing assemble_candidates_from_impls from
932 // matching every impl for this trait.
933 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
936 let mut candidates = SelectionCandidateSet {
941 // Other bounds. Consider both in-scope bounds from fn decl
942 // and applicable impls. There is a certain set of precedence rules here.
944 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
945 Some(ty::BoundCopy) => {
946 debug!("obligation self ty is {:?}",
947 obligation.predicate.0.self_ty());
949 // User-defined copy impls are permitted, but only for
950 // structs and enums.
951 try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
953 // For other types, we'll use the builtin rules.
954 try!(self.assemble_builtin_bound_candidates(ty::BoundCopy,
958 Some(bound @ ty::BoundSized) => {
959 // Sized is never implementable by end-users, it is
960 // always automatically computed.
961 try!(self.assemble_builtin_bound_candidates(bound,
966 None if self.tcx().lang_items.unsize_trait() ==
967 Some(obligation.predicate.def_id()) => {
968 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
971 Some(ty::BoundSend) |
972 Some(ty::BoundSync) |
974 try!(self.assemble_closure_candidates(obligation, &mut candidates));
975 try!(self.assemble_fn_pointer_candidates(obligation, &mut candidates));
976 try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
977 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
981 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
982 try!(self.assemble_candidates_from_caller_bounds(stack, &mut candidates));
983 // Default implementations have lower priority, so we only
984 // consider triggering a default if there is no other impl that can apply.
985 if candidates.vec.is_empty() {
986 try!(self.assemble_candidates_from_default_impls(obligation, &mut candidates));
988 debug!("candidate list size: {}", candidates.vec.len());
992 fn assemble_candidates_from_projected_tys(&mut self,
993 obligation: &TraitObligation<'tcx>,
994 candidates: &mut SelectionCandidateSet<'tcx>)
996 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
998 // FIXME(#20297) -- just examining the self-type is very simplistic
1000 // before we go into the whole skolemization thing, just
1001 // quickly check if the self-type is a projection at all.
1002 let trait_def_id = match obligation.predicate.0.trait_ref.self_ty().sty {
1003 ty::TyProjection(ref data) => data.trait_ref.def_id,
1004 ty::TyInfer(ty::TyVar(_)) => {
1005 self.tcx().sess.span_bug(obligation.cause.span,
1006 "Self=_ should have been handled by assemble_candidates");
1011 debug!("assemble_candidates_for_projected_tys: trait_def_id={:?}",
1014 let result = self.infcx.probe(|snapshot| {
1015 self.match_projection_obligation_against_bounds_from_trait(obligation,
1020 candidates.vec.push(ProjectionCandidate);
1024 fn match_projection_obligation_against_bounds_from_trait(
1026 obligation: &TraitObligation<'tcx>,
1027 snapshot: &infer::CombinedSnapshot)
1030 let poly_trait_predicate =
1031 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1032 let (skol_trait_predicate, skol_map) =
1033 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1034 debug!("match_projection_obligation_against_bounds_from_trait: \
1035 skol_trait_predicate={:?} skol_map={:?}",
1036 skol_trait_predicate,
1039 let projection_trait_ref = match skol_trait_predicate.trait_ref.self_ty().sty {
1040 ty::TyProjection(ref data) => &data.trait_ref,
1042 self.tcx().sess.span_bug(
1043 obligation.cause.span,
1044 &format!("match_projection_obligation_against_bounds_from_trait() called \
1045 but self-ty not a projection: {:?}",
1046 skol_trait_predicate.trait_ref.self_ty()));
1049 debug!("match_projection_obligation_against_bounds_from_trait: \
1050 projection_trait_ref={:?}",
1051 projection_trait_ref);
1053 let trait_predicates = self.tcx().lookup_predicates(projection_trait_ref.def_id);
1054 let bounds = trait_predicates.instantiate(self.tcx(), projection_trait_ref.substs);
1055 debug!("match_projection_obligation_against_bounds_from_trait: \
1059 let matching_bound =
1060 util::elaborate_predicates(self.tcx(), bounds.predicates.into_vec())
1063 |bound| self.infcx.probe(
1064 |_| self.match_projection(obligation,
1066 skol_trait_predicate.trait_ref.clone(),
1070 debug!("match_projection_obligation_against_bounds_from_trait: \
1071 matching_bound={:?}",
1073 match matching_bound {
1076 // Repeat the successful match, if any, this time outside of a probe.
1077 let result = self.match_projection(obligation,
1079 skol_trait_predicate.trait_ref.clone(),
1088 fn match_projection(&mut self,
1089 obligation: &TraitObligation<'tcx>,
1090 trait_bound: ty::PolyTraitRef<'tcx>,
1091 skol_trait_ref: ty::TraitRef<'tcx>,
1092 skol_map: &infer::SkolemizationMap,
1093 snapshot: &infer::CombinedSnapshot)
1096 assert!(!skol_trait_ref.has_escaping_regions());
1097 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
1098 match self.infcx.sub_poly_trait_refs(false,
1100 trait_bound.clone(),
1101 ty::Binder(skol_trait_ref.clone())) {
1103 Err(_) => { return false; }
1106 self.infcx.leak_check(skol_map, snapshot).is_ok()
1109 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1110 /// supplied to find out whether it is listed among them.
1112 /// Never affects inference environment.
1113 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1114 stack: &TraitObligationStack<'o, 'tcx>,
1115 candidates: &mut SelectionCandidateSet<'tcx>)
1116 -> Result<(),SelectionError<'tcx>>
1118 debug!("assemble_candidates_from_caller_bounds({:?})",
1122 self.param_env().caller_bounds
1124 .filter_map(|o| o.to_opt_poly_trait_ref());
1126 let matching_bounds =
1128 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1130 let param_candidates =
1131 matching_bounds.map(|bound| ParamCandidate(bound));
1133 candidates.vec.extend(param_candidates);
1138 fn evaluate_where_clause<'o>(&mut self,
1139 stack: &TraitObligationStack<'o, 'tcx>,
1140 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1141 -> EvaluationResult<'tcx>
1143 self.infcx().probe(move |_| {
1144 match self.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1145 Ok(obligations) => {
1146 self.evaluate_predicates_recursively(stack.list(), obligations.iter())
1149 EvaluatedToErr(Unimplemented)
1155 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1156 /// FnMut<..>` where `X` is a closure type.
1158 /// Note: the type parameters on a closure candidate are modeled as *output* type
1159 /// parameters and hence do not affect whether this trait is a match or not. They will be
1160 /// unified during the confirmation step.
1161 fn assemble_closure_candidates(&mut self,
1162 obligation: &TraitObligation<'tcx>,
1163 candidates: &mut SelectionCandidateSet<'tcx>)
1164 -> Result<(),SelectionError<'tcx>>
1166 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1168 None => { return Ok(()); }
1171 // ok to skip binder because the substs on closure types never
1172 // touch bound regions, they just capture the in-scope
1173 // type/region parameters
1174 let self_ty = *obligation.self_ty().skip_binder();
1175 let (closure_def_id, substs) = match self_ty.sty {
1176 ty::TyClosure(id, ref substs) => (id, substs),
1177 ty::TyInfer(ty::TyVar(_)) => {
1178 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1179 candidates.ambiguous = true;
1182 _ => { return Ok(()); }
1185 debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1190 match self.infcx.closure_kind(closure_def_id) {
1191 Some(closure_kind) => {
1192 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1193 if closure_kind.extends(kind) {
1194 candidates.vec.push(ClosureCandidate(closure_def_id, substs));
1198 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1199 candidates.ambiguous = true;
1206 /// Implement one of the `Fn()` family for a fn pointer.
1207 fn assemble_fn_pointer_candidates(&mut self,
1208 obligation: &TraitObligation<'tcx>,
1209 candidates: &mut SelectionCandidateSet<'tcx>)
1210 -> Result<(),SelectionError<'tcx>>
1212 // We provide impl of all fn traits for fn pointers.
1213 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1217 // ok to skip binder because what we are inspecting doesn't involve bound regions
1218 let self_ty = *obligation.self_ty().skip_binder();
1220 ty::TyInfer(ty::TyVar(_)) => {
1221 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1222 candidates.ambiguous = true; // could wind up being a fn() type
1225 // provide an impl, but only for suitable `fn` pointers
1226 ty::TyBareFn(_, &ty::BareFnTy {
1227 unsafety: hir::Unsafety::Normal,
1229 sig: ty::Binder(ty::FnSig {
1231 output: ty::FnConverging(_),
1235 candidates.vec.push(FnPointerCandidate);
1244 /// Search for impls that might apply to `obligation`.
1245 fn assemble_candidates_from_impls(&mut self,
1246 obligation: &TraitObligation<'tcx>,
1247 candidates: &mut SelectionCandidateSet<'tcx>)
1248 -> Result<(), SelectionError<'tcx>>
1250 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1252 let def = self.tcx().lookup_trait_def(obligation.predicate.def_id());
1254 def.for_each_relevant_impl(
1256 obligation.predicate.0.trait_ref.self_ty(),
1258 self.infcx.probe(|snapshot| {
1259 if let Ok(_) = self.match_impl(impl_def_id, obligation, snapshot) {
1260 candidates.vec.push(ImplCandidate(impl_def_id));
1269 fn assemble_candidates_from_default_impls(&mut self,
1270 obligation: &TraitObligation<'tcx>,
1271 candidates: &mut SelectionCandidateSet<'tcx>)
1272 -> Result<(), SelectionError<'tcx>>
1274 // OK to skip binder here because the tests we do below do not involve bound regions
1275 let self_ty = *obligation.self_ty().skip_binder();
1276 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1278 let def_id = obligation.predicate.def_id();
1280 if self.tcx().trait_has_default_impl(def_id) {
1282 ty::TyTrait(..) => {
1283 // For object types, we don't know what the closed
1284 // over types are. For most traits, this means we
1285 // conservatively say nothing; a candidate may be
1286 // added by `assemble_candidates_from_object_ty`.
1287 // However, for the kind of magic reflect trait,
1288 // we consider it to be implemented even for
1289 // object types, because it just lets you reflect
1290 // onto the object type, not into the object's
1292 if self.tcx().has_attr(def_id, "rustc_reflect_like") {
1293 candidates.vec.push(DefaultImplObjectCandidate(def_id));
1297 ty::TyProjection(..) => {
1298 // In these cases, we don't know what the actual
1299 // type is. Therefore, we cannot break it down
1300 // into its constituent types. So we don't
1301 // consider the `..` impl but instead just add no
1302 // candidates: this means that typeck will only
1303 // succeed if there is another reason to believe
1304 // that this obligation holds. That could be a
1305 // where-clause or, in the case of an object type,
1306 // it could be that the object type lists the
1307 // trait (e.g. `Foo+Send : Send`). See
1308 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1309 // for an example of a test case that exercises
1312 ty::TyInfer(ty::TyVar(_)) => {
1313 // the defaulted impl might apply, we don't know
1314 candidates.ambiguous = true;
1317 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1325 /// Search for impls that might apply to `obligation`.
1326 fn assemble_candidates_from_object_ty(&mut self,
1327 obligation: &TraitObligation<'tcx>,
1328 candidates: &mut SelectionCandidateSet<'tcx>)
1330 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1331 obligation.self_ty().skip_binder());
1333 // Object-safety candidates are only applicable to object-safe
1334 // traits. Including this check is useful because it helps
1335 // inference in cases of traits like `BorrowFrom`, which are
1336 // not object-safe, and which rely on being able to infer the
1337 // self-type from one of the other inputs. Without this check,
1338 // these cases wind up being considered ambiguous due to a
1339 // (spurious) ambiguity introduced here.
1340 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1341 if !object_safety::is_object_safe(self.tcx(), predicate_trait_ref.def_id()) {
1345 self.infcx.commit_if_ok(|snapshot| {
1347 self.infcx().skolemize_late_bound_regions(&obligation.self_ty(), snapshot);
1348 let poly_trait_ref = match self_ty.sty {
1349 ty::TyTrait(ref data) => {
1350 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
1351 Some(bound @ ty::BoundSend) | Some(bound @ ty::BoundSync) => {
1352 if data.bounds.builtin_bounds.contains(&bound) {
1353 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1354 pushing candidate");
1355 candidates.vec.push(BuiltinObjectCandidate);
1362 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
1364 ty::TyInfer(ty::TyVar(_)) => {
1365 debug!("assemble_candidates_from_object_ty: ambiguous");
1366 candidates.ambiguous = true; // could wind up being an object type
1374 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1377 // Count only those upcast versions that match the trait-ref
1378 // we are looking for. Specifically, do not only check for the
1379 // correct trait, but also the correct type parameters.
1380 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1381 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1382 let upcast_trait_refs =
1383 util::supertraits(self.tcx(), poly_trait_ref)
1384 .filter(|upcast_trait_ref| {
1385 self.infcx.probe(|_| {
1386 let upcast_trait_ref = upcast_trait_ref.clone();
1387 self.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1392 if upcast_trait_refs > 1 {
1393 // can be upcast in many ways; need more type information
1394 candidates.ambiguous = true;
1395 } else if upcast_trait_refs == 1 {
1396 candidates.vec.push(ObjectCandidate);
1403 /// Search for unsizing that might apply to `obligation`.
1404 fn assemble_candidates_for_unsizing(&mut self,
1405 obligation: &TraitObligation<'tcx>,
1406 candidates: &mut SelectionCandidateSet<'tcx>) {
1407 // We currently never consider higher-ranked obligations e.g.
1408 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1409 // because they are a priori invalid, and we could potentially add support
1410 // for them later, it's just that there isn't really a strong need for it.
1411 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1412 // impl, and those are generally applied to concrete types.
1414 // That said, one might try to write a fn with a where clause like
1415 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1416 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1417 // Still, you'd be more likely to write that where clause as
1419 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1420 // obligation above. Should be possible to extend this in the future.
1421 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1424 // Don't add any candidates if there are bound regions.
1428 let target = obligation.predicate.0.input_types()[0];
1430 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1433 let may_apply = match (&source.sty, &target.sty) {
1434 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1435 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
1436 // Upcasts permit two things:
1438 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1439 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1441 // Note that neither of these changes requires any
1442 // change at runtime. Eventually this will be
1445 // We always upcast when we can because of reason
1446 // #2 (region bounds).
1447 data_a.principal.def_id() == data_a.principal.def_id() &&
1448 data_a.bounds.builtin_bounds.is_superset(&data_b.bounds.builtin_bounds)
1452 (_, &ty::TyTrait(_)) => true,
1454 // Ambiguous handling is below T -> Trait, because inference
1455 // variables can still implement Unsize<Trait> and nested
1456 // obligations will have the final say (likely deferred).
1457 (&ty::TyInfer(ty::TyVar(_)), _) |
1458 (_, &ty::TyInfer(ty::TyVar(_))) => {
1459 debug!("assemble_candidates_for_unsizing: ambiguous");
1460 candidates.ambiguous = true;
1465 (&ty::TyArray(_, _), &ty::TySlice(_)) => true,
1467 // Struct<T> -> Struct<U>.
1468 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
1469 def_id_a == def_id_b
1476 candidates.vec.push(BuiltinUnsizeCandidate);
1480 ///////////////////////////////////////////////////////////////////////////
1483 // Winnowing is the process of attempting to resolve ambiguity by
1484 // probing further. During the winnowing process, we unify all
1485 // type variables (ignoring skolemization) and then we also
1486 // attempt to evaluate recursive bounds to see if they are
1489 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1490 /// obligations are met. Returns true if `candidate` remains viable after this further
1492 fn winnow_candidate<'o>(&mut self,
1493 stack: &TraitObligationStack<'o, 'tcx>,
1494 candidate: &SelectionCandidate<'tcx>)
1495 -> EvaluationResult<'tcx>
1497 debug!("winnow_candidate: candidate={:?}", candidate);
1498 let result = self.infcx.probe(|_| {
1499 let candidate = (*candidate).clone();
1500 match self.confirm_candidate(stack.obligation, candidate) {
1501 Ok(selection) => self.winnow_selection(stack.list(),
1503 Err(error) => EvaluatedToErr(error),
1506 debug!("winnow_candidate depth={} result={:?}",
1507 stack.obligation.recursion_depth, result);
1511 fn winnow_selection<'o>(&mut self,
1512 stack: TraitObligationStackList<'o,'tcx>,
1513 selection: Selection<'tcx>)
1514 -> EvaluationResult<'tcx>
1516 self.evaluate_predicates_recursively(stack,
1517 selection.nested_obligations().iter())
1520 /// Returns true if `candidate_i` should be dropped in favor of
1521 /// `candidate_j`. Generally speaking we will drop duplicate
1522 /// candidates and prefer where-clause candidates.
1523 /// Returns true if `victim` should be dropped in favor of
1524 /// `other`. Generally speaking we will drop duplicate
1525 /// candidates and prefer where-clause candidates.
1527 /// See the comment for "SelectionCandidate" for more details.
1528 fn candidate_should_be_dropped_in_favor_of<'o>(&mut self,
1529 victim: &SelectionCandidate<'tcx>,
1530 other: &SelectionCandidate<'tcx>)
1533 if victim == other {
1538 &ObjectCandidate(..) |
1539 &ParamCandidate(_) | &ProjectionCandidate => match victim {
1540 &DefaultImplCandidate(..) => {
1541 self.tcx().sess.bug(
1542 "default implementations shouldn't be recorded \
1543 when there are other valid candidates");
1545 &PhantomFnCandidate => {
1546 self.tcx().sess.bug("PhantomFn didn't short-circuit selection");
1548 &ImplCandidate(..) |
1549 &ClosureCandidate(..) |
1550 &FnPointerCandidate(..) |
1551 &BuiltinObjectCandidate(..) |
1552 &BuiltinUnsizeCandidate(..) |
1553 &DefaultImplObjectCandidate(..) |
1554 &BuiltinCandidate(..) => {
1555 // We have a where-clause so don't go around looking
1559 &ObjectCandidate(..) |
1560 &ProjectionCandidate => {
1561 // Arbitrarily give param candidates priority
1562 // over projection and object candidates.
1565 &ParamCandidate(..) => false,
1566 &ErrorCandidate => false // propagate errors
1572 ///////////////////////////////////////////////////////////////////////////
1575 // These cover the traits that are built-in to the language
1576 // itself. This includes `Copy` and `Sized` for sure. For the
1577 // moment, it also includes `Send` / `Sync` and a few others, but
1578 // those will hopefully change to library-defined traits in the
1581 fn assemble_builtin_bound_candidates<'o>(&mut self,
1582 bound: ty::BuiltinBound,
1583 obligation: &TraitObligation<'tcx>,
1584 candidates: &mut SelectionCandidateSet<'tcx>)
1585 -> Result<(),SelectionError<'tcx>>
1587 match self.builtin_bound(bound, obligation) {
1589 debug!("builtin_bound: bound={:?}",
1591 candidates.vec.push(BuiltinCandidate(bound));
1594 Ok(ParameterBuiltin) => { Ok(()) }
1595 Ok(AmbiguousBuiltin) => {
1596 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1597 Ok(candidates.ambiguous = true)
1599 Err(e) => { Err(e) }
1603 fn builtin_bound(&mut self,
1604 bound: ty::BuiltinBound,
1605 obligation: &TraitObligation<'tcx>)
1606 -> Result<BuiltinBoundConditions<'tcx>,SelectionError<'tcx>>
1608 // Note: these tests operate on types that may contain bound
1609 // regions. To be proper, we ought to skolemize here, but we
1610 // forego the skolemization and defer it until the
1611 // confirmation step.
1613 let self_ty = self.infcx.shallow_resolve(obligation.predicate.0.self_ty());
1614 return match self_ty.sty {
1615 ty::TyInfer(ty::IntVar(_)) |
1616 ty::TyInfer(ty::FloatVar(_)) |
1623 // safe for everything
1627 ty::TyBox(_) => { // Box<T>
1629 ty::BoundCopy => Err(Unimplemented),
1631 ty::BoundSized => ok_if(Vec::new()),
1633 ty::BoundSync | ty::BoundSend => {
1634 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1639 ty::TyRawPtr(..) => { // *const T, *mut T
1641 ty::BoundCopy | ty::BoundSized => ok_if(Vec::new()),
1643 ty::BoundSync | ty::BoundSend => {
1644 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1649 ty::TyTrait(ref data) => {
1651 ty::BoundSized => Err(Unimplemented),
1653 if data.bounds.builtin_bounds.contains(&bound) {
1656 // Recursively check all supertraits to find out if any further
1657 // bounds are required and thus we must fulfill.
1659 data.principal_trait_ref_with_self_ty(self.tcx(),
1660 self.tcx().types.err);
1661 let copy_def_id = obligation.predicate.def_id();
1662 for tr in util::supertraits(self.tcx(), principal) {
1663 if tr.def_id() == copy_def_id {
1664 return ok_if(Vec::new())
1671 ty::BoundSync | ty::BoundSend => {
1672 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1677 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl }) => {
1682 // &mut T is affine and hence never `Copy`
1683 hir::MutMutable => Err(Unimplemented),
1685 // &T is always copyable
1686 hir::MutImmutable => ok_if(Vec::new()),
1690 ty::BoundSized => ok_if(Vec::new()),
1692 ty::BoundSync | ty::BoundSend => {
1693 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1698 ty::TyArray(element_ty, _) => {
1701 ty::BoundCopy => ok_if(vec![element_ty]),
1702 ty::BoundSized => ok_if(Vec::new()),
1703 ty::BoundSync | ty::BoundSend => {
1704 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1709 ty::TyStr | ty::TySlice(_) => {
1711 ty::BoundSync | ty::BoundSend => {
1712 self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()");
1715 ty::BoundCopy | ty::BoundSized => Err(Unimplemented),
1719 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1720 ty::TyTuple(ref tys) => ok_if(tys.clone()),
1722 ty::TyClosure(_, ref substs) => {
1723 // FIXME -- This case is tricky. In the case of by-ref
1724 // closures particularly, we need the results of
1725 // inference to decide how to reflect the type of each
1726 // upvar (the upvar may have type `T`, but the runtime
1727 // type could be `&mut`, `&`, or just `T`). For now,
1728 // though, we'll do this unsoundly and assume that all
1729 // captures are by value. Really what we ought to do
1730 // is reserve judgement and then intertwine this
1731 // analysis with closure inference.
1733 // Unboxed closures shouldn't be
1734 // implicitly copyable
1735 if bound == ty::BoundCopy {
1736 return Ok(ParameterBuiltin);
1739 // Upvars are always local variables or references to
1740 // local variables, and local variables cannot be
1741 // unsized, so the closure struct as a whole must be
1743 if bound == ty::BoundSized {
1744 return ok_if(Vec::new());
1747 ok_if(substs.upvar_tys.clone())
1750 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1751 let types: Vec<Ty> = def.all_fields().map(|f| {
1752 f.ty(self.tcx(), substs)
1754 nominal(bound, types)
1757 ty::TyProjection(_) | ty::TyParam(_) => {
1758 // Note: A type parameter is only considered to meet a
1759 // particular bound if there is a where clause telling
1760 // us that it does, and that case is handled by
1761 // `assemble_candidates_from_caller_bounds()`.
1762 Ok(ParameterBuiltin)
1765 ty::TyInfer(ty::TyVar(_)) => {
1766 // Unbound type variable. Might or might not have
1767 // applicable impls and so forth, depending on what
1768 // those type variables wind up being bound to.
1769 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1770 Ok(AmbiguousBuiltin)
1773 ty::TyError => ok_if(Vec::new()),
1775 ty::TyInfer(ty::FreshTy(_))
1776 | ty::TyInfer(ty::FreshIntTy(_))
1777 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1778 self.tcx().sess.bug(
1780 "asked to assemble builtin bounds of unexpected type: {:?}",
1785 fn ok_if<'tcx>(v: Vec<Ty<'tcx>>)
1786 -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>> {
1787 Ok(If(ty::Binder(v)))
1790 fn nominal<'cx, 'tcx>(bound: ty::BuiltinBound,
1791 types: Vec<Ty<'tcx>>)
1792 -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>>
1794 // First check for markers and other nonsense.
1796 // Fallback to whatever user-defined impls exist in this case.
1797 ty::BoundCopy => Ok(ParameterBuiltin),
1799 // Sized if all the component types are sized.
1800 ty::BoundSized => ok_if(types),
1802 // Shouldn't be coming through here.
1803 ty::BoundSend | ty::BoundSync => unreachable!(),
1808 /// For default impls, we need to break apart a type into its
1809 /// "constituent types" -- meaning, the types that it contains.
1811 /// Here are some (simple) examples:
1814 /// (i32, u32) -> [i32, u32]
1815 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1816 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1817 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1819 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1828 ty::TyInfer(ty::IntVar(_)) |
1829 ty::TyInfer(ty::FloatVar(_)) |
1836 ty::TyProjection(..) |
1837 ty::TyInfer(ty::TyVar(_)) |
1838 ty::TyInfer(ty::FreshTy(_)) |
1839 ty::TyInfer(ty::FreshIntTy(_)) |
1840 ty::TyInfer(ty::FreshFloatTy(_)) => {
1841 self.tcx().sess.bug(
1843 "asked to assemble constituent types of unexpected type: {:?}",
1847 ty::TyBox(referent_ty) => { // Box<T>
1851 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
1852 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
1856 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
1860 ty::TyTuple(ref tys) => {
1861 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1865 ty::TyClosure(_, ref substs) => {
1866 // FIXME(#27086). We are invariant w/r/t our
1867 // substs.func_substs, but we don't see them as
1868 // constituent types; this seems RIGHT but also like
1869 // something that a normal type couldn't simulate. Is
1870 // this just a gap with the way that PhantomData and
1871 // OIBIT interact? That is, there is no way to say
1872 // "make me invariant with respect to this TYPE, but
1873 // do not act as though I can reach it"
1874 substs.upvar_tys.clone()
1877 // for `PhantomData<T>`, we pass `T`
1878 ty::TyStruct(def, substs) if def.is_phantom_data() => {
1879 substs.types.get_slice(TypeSpace).to_vec()
1882 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1884 .map(|f| f.ty(self.tcx(), substs))
1890 fn collect_predicates_for_types(&mut self,
1891 obligation: &TraitObligation<'tcx>,
1892 trait_def_id: DefId,
1893 types: ty::Binder<Vec<Ty<'tcx>>>)
1894 -> Vec<PredicateObligation<'tcx>>
1896 let derived_cause = match self.tcx().lang_items.to_builtin_kind(trait_def_id) {
1898 self.derived_cause(obligation, BuiltinDerivedObligation)
1901 self.derived_cause(obligation, ImplDerivedObligation)
1905 // Because the types were potentially derived from
1906 // higher-ranked obligations they may reference late-bound
1907 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1908 // yield a type like `for<'a> &'a int`. In general, we
1909 // maintain the invariant that we never manipulate bound
1910 // regions, so we have to process these bound regions somehow.
1912 // The strategy is to:
1914 // 1. Instantiate those regions to skolemized regions (e.g.,
1915 // `for<'a> &'a int` becomes `&0 int`.
1916 // 2. Produce something like `&'0 int : Copy`
1917 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1919 // Move the binder into the individual types
1920 let bound_types: Vec<ty::Binder<Ty<'tcx>>> =
1923 .map(|&nested_ty| ty::Binder(nested_ty))
1926 // For each type, produce a vector of resulting obligations
1927 let obligations: Result<Vec<Vec<_>>, _> = bound_types.iter().map(|nested_ty| {
1928 self.infcx.commit_if_ok(|snapshot| {
1929 let (skol_ty, skol_map) =
1930 self.infcx().skolemize_late_bound_regions(nested_ty, snapshot);
1931 let Normalized { value: normalized_ty, mut obligations } =
1932 project::normalize_with_depth(self,
1933 obligation.cause.clone(),
1934 obligation.recursion_depth + 1,
1936 let skol_obligation =
1937 util::predicate_for_trait_def(self.tcx(),
1938 derived_cause.clone(),
1940 obligation.recursion_depth + 1,
1943 obligations.push(skol_obligation);
1944 Ok(self.infcx().plug_leaks(skol_map, snapshot, &obligations))
1948 // Flatten those vectors (couldn't do it above due `collect`)
1950 Ok(obligations) => obligations.into_iter().flat_map(|o| o).collect(),
1951 Err(ErrorReported) => Vec::new(),
1955 ///////////////////////////////////////////////////////////////////////////
1958 // Confirmation unifies the output type parameters of the trait
1959 // with the values found in the obligation, possibly yielding a
1960 // type error. See `README.md` for more details.
1962 fn confirm_candidate(&mut self,
1963 obligation: &TraitObligation<'tcx>,
1964 candidate: SelectionCandidate<'tcx>)
1965 -> Result<Selection<'tcx>,SelectionError<'tcx>>
1967 debug!("confirm_candidate({:?}, {:?})",
1972 BuiltinCandidate(builtin_bound) => {
1974 try!(self.confirm_builtin_candidate(obligation, builtin_bound))))
1977 PhantomFnCandidate |
1979 Ok(VtableBuiltin(VtableBuiltinData { nested: vec![] }))
1982 ParamCandidate(param) => {
1983 let obligations = self.confirm_param_candidate(obligation, param);
1984 Ok(VtableParam(obligations))
1987 DefaultImplCandidate(trait_def_id) => {
1988 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
1989 Ok(VtableDefaultImpl(data))
1992 DefaultImplObjectCandidate(trait_def_id) => {
1993 let data = self.confirm_default_impl_object_candidate(obligation, trait_def_id);
1994 Ok(VtableDefaultImpl(data))
1997 ImplCandidate(impl_def_id) => {
1999 try!(self.confirm_impl_candidate(obligation, impl_def_id));
2000 Ok(VtableImpl(vtable_impl))
2003 ClosureCandidate(closure_def_id, substs) => {
2004 let vtable_closure =
2005 try!(self.confirm_closure_candidate(obligation, closure_def_id, substs));
2006 Ok(VtableClosure(vtable_closure))
2009 BuiltinObjectCandidate => {
2010 // This indicates something like `(Trait+Send) :
2011 // Send`. In this case, we know that this holds
2012 // because that's what the object type is telling us,
2013 // and there's really no additional obligations to
2014 // prove and no types in particular to unify etc.
2015 Ok(VtableParam(Vec::new()))
2018 ObjectCandidate => {
2019 let data = self.confirm_object_candidate(obligation);
2020 Ok(VtableObject(data))
2023 FnPointerCandidate => {
2025 try!(self.confirm_fn_pointer_candidate(obligation));
2026 Ok(VtableFnPointer(fn_type))
2029 ProjectionCandidate => {
2030 self.confirm_projection_candidate(obligation);
2031 Ok(VtableParam(Vec::new()))
2034 BuiltinUnsizeCandidate => {
2035 let data = try!(self.confirm_builtin_unsize_candidate(obligation));
2036 Ok(VtableBuiltin(data))
2041 fn confirm_projection_candidate(&mut self,
2042 obligation: &TraitObligation<'tcx>)
2044 let _: Result<(),()> =
2045 self.infcx.commit_if_ok(|snapshot| {
2047 self.match_projection_obligation_against_bounds_from_trait(obligation,
2054 fn confirm_param_candidate(&mut self,
2055 obligation: &TraitObligation<'tcx>,
2056 param: ty::PolyTraitRef<'tcx>)
2057 -> Vec<PredicateObligation<'tcx>>
2059 debug!("confirm_param_candidate({:?},{:?})",
2063 // During evaluation, we already checked that this
2064 // where-clause trait-ref could be unified with the obligation
2065 // trait-ref. Repeat that unification now without any
2066 // transactional boundary; it should not fail.
2067 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2068 Ok(obligations) => obligations,
2070 self.tcx().sess.bug(
2071 &format!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2078 fn confirm_builtin_candidate(&mut self,
2079 obligation: &TraitObligation<'tcx>,
2080 bound: ty::BuiltinBound)
2081 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2082 SelectionError<'tcx>>
2084 debug!("confirm_builtin_candidate({:?})",
2087 match try!(self.builtin_bound(bound, obligation)) {
2088 If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)),
2089 AmbiguousBuiltin | ParameterBuiltin => {
2090 self.tcx().sess.span_bug(
2091 obligation.cause.span,
2092 &format!("builtin bound for {:?} was ambig",
2098 fn vtable_builtin_data(&mut self,
2099 obligation: &TraitObligation<'tcx>,
2100 bound: ty::BuiltinBound,
2101 nested: ty::Binder<Vec<Ty<'tcx>>>)
2102 -> VtableBuiltinData<PredicateObligation<'tcx>>
2104 let trait_def = match self.tcx().lang_items.from_builtin_kind(bound) {
2105 Ok(def_id) => def_id,
2107 self.tcx().sess.bug("builtin trait definition not found");
2111 let obligations = self.collect_predicates_for_types(obligation, trait_def, nested);
2113 debug!("vtable_builtin_data: obligations={:?}",
2116 VtableBuiltinData { nested: obligations }
2119 /// This handles the case where a `impl Foo for ..` impl is being used.
2120 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2122 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2123 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2124 fn confirm_default_impl_candidate(&mut self,
2125 obligation: &TraitObligation<'tcx>,
2126 trait_def_id: DefId)
2127 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2129 debug!("confirm_default_impl_candidate({:?}, {:?})",
2133 // binder is moved below
2134 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2135 let types = self.constituent_types_for_ty(self_ty);
2136 self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2139 fn confirm_default_impl_object_candidate(&mut self,
2140 obligation: &TraitObligation<'tcx>,
2141 trait_def_id: DefId)
2142 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2144 debug!("confirm_default_impl_object_candidate({:?}, {:?})",
2148 assert!(self.tcx().has_attr(trait_def_id, "rustc_reflect_like"));
2150 // OK to skip binder, it is reintroduced below
2151 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2153 ty::TyTrait(ref data) => {
2154 // OK to skip the binder, it is reintroduced below
2155 let input_types = data.principal.skip_binder().substs.types.get_slice(TypeSpace);
2156 let assoc_types = data.bounds.projection_bounds
2158 .map(|pb| pb.skip_binder().ty);
2159 let all_types: Vec<_> = input_types.iter().cloned()
2163 // reintroduce the two binding levels we skipped, then flatten into one
2164 let all_types = ty::Binder(ty::Binder(all_types));
2165 let all_types = self.tcx().flatten_late_bound_regions(&all_types);
2167 self.vtable_default_impl(obligation, trait_def_id, all_types)
2170 self.tcx().sess.bug(
2172 "asked to confirm default object implementation for non-object type: {:?}",
2178 /// See `confirm_default_impl_candidate`
2179 fn vtable_default_impl(&mut self,
2180 obligation: &TraitObligation<'tcx>,
2181 trait_def_id: DefId,
2182 nested: ty::Binder<Vec<Ty<'tcx>>>)
2183 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2185 debug!("vtable_default_impl_data: nested={:?}", nested);
2187 let mut obligations = self.collect_predicates_for_types(obligation,
2191 let trait_obligations: Result<Vec<_>,()> = self.infcx.commit_if_ok(|snapshot| {
2192 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2193 let (trait_ref, skol_map) =
2194 self.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2195 Ok(self.impl_or_trait_obligations(obligation.cause.clone(),
2196 obligation.recursion_depth + 1,
2203 // no Errors in that code above
2204 obligations.append(&mut trait_obligations.unwrap());
2206 debug!("vtable_default_impl_data: obligations={:?}", obligations);
2208 VtableDefaultImplData {
2209 trait_def_id: trait_def_id,
2214 fn confirm_impl_candidate(&mut self,
2215 obligation: &TraitObligation<'tcx>,
2217 -> Result<VtableImplData<'tcx, PredicateObligation<'tcx>>,
2218 SelectionError<'tcx>>
2220 debug!("confirm_impl_candidate({:?},{:?})",
2224 // First, create the substitutions by matching the impl again,
2225 // this time not in a probe.
2226 self.infcx.commit_if_ok(|snapshot| {
2227 let (substs, skol_map) =
2228 self.rematch_impl(impl_def_id, obligation,
2230 debug!("confirm_impl_candidate substs={:?}", substs);
2231 Ok(self.vtable_impl(impl_def_id, substs, obligation.cause.clone(),
2232 obligation.recursion_depth + 1, skol_map, snapshot))
2236 fn vtable_impl(&mut self,
2238 mut substs: Normalized<'tcx, Substs<'tcx>>,
2239 cause: ObligationCause<'tcx>,
2240 recursion_depth: usize,
2241 skol_map: infer::SkolemizationMap,
2242 snapshot: &infer::CombinedSnapshot)
2243 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2245 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2251 let mut impl_obligations =
2252 self.impl_or_trait_obligations(cause,
2259 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2263 impl_obligations.append(&mut substs.obligations);
2265 VtableImplData { impl_def_id: impl_def_id,
2266 substs: substs.value,
2267 nested: impl_obligations }
2270 fn confirm_object_candidate(&mut self,
2271 obligation: &TraitObligation<'tcx>)
2272 -> VtableObjectData<'tcx>
2274 debug!("confirm_object_candidate({:?})",
2277 // FIXME skipping binder here seems wrong -- we should
2278 // probably flatten the binder from the obligation and the
2279 // binder from the object. Have to try to make a broken test
2280 // case that results. -nmatsakis
2281 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2282 let poly_trait_ref = match self_ty.sty {
2283 ty::TyTrait(ref data) => {
2284 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
2287 self.tcx().sess.span_bug(obligation.cause.span,
2288 "object candidate with non-object");
2292 let mut upcast_trait_ref = None;
2296 // We want to find the first supertrait in the list of
2297 // supertraits that we can unify with, and do that
2298 // unification. We know that there is exactly one in the list
2299 // where we can unify because otherwise select would have
2300 // reported an ambiguity. (When we do find a match, also
2301 // record it for later.)
2303 util::supertraits(self.tcx(), poly_trait_ref)
2306 self.infcx.commit_if_ok(
2307 |_| self.match_poly_trait_ref(obligation, t))
2309 Ok(_) => { upcast_trait_ref = Some(t); false }
2314 // Additionally, for each of the nonmatching predicates that
2315 // we pass over, we sum up the set of number of vtable
2316 // entries, so that we can compute the offset for the selected
2319 nonmatching.map(|t| util::count_own_vtable_entries(self.tcx(), t))
2325 upcast_trait_ref: upcast_trait_ref.unwrap(),
2326 vtable_base: vtable_base,
2330 fn confirm_fn_pointer_candidate(&mut self,
2331 obligation: &TraitObligation<'tcx>)
2332 -> Result<ty::Ty<'tcx>,SelectionError<'tcx>>
2334 debug!("confirm_fn_pointer_candidate({:?})",
2337 // ok to skip binder; it is reintroduced below
2338 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2339 let sig = self_ty.fn_sig();
2341 util::closure_trait_ref_and_return_type(self.tcx(),
2342 obligation.predicate.def_id(),
2345 util::TupleArgumentsFlag::Yes)
2346 .map_bound(|(trait_ref, _)| trait_ref);
2348 try!(self.confirm_poly_trait_refs(obligation.cause.clone(),
2349 obligation.predicate.to_poly_trait_ref(),
2354 fn confirm_closure_candidate(&mut self,
2355 obligation: &TraitObligation<'tcx>,
2356 closure_def_id: DefId,
2357 substs: &ty::ClosureSubsts<'tcx>)
2358 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2359 SelectionError<'tcx>>
2361 debug!("confirm_closure_candidate({:?},{:?},{:?})",
2369 } = self.closure_trait_ref(obligation, closure_def_id, substs);
2371 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2376 try!(self.confirm_poly_trait_refs(obligation.cause.clone(),
2377 obligation.predicate.to_poly_trait_ref(),
2380 Ok(VtableClosureData {
2381 closure_def_id: closure_def_id,
2382 substs: substs.clone(),
2387 /// In the case of closure types and fn pointers,
2388 /// we currently treat the input type parameters on the trait as
2389 /// outputs. This means that when we have a match we have only
2390 /// considered the self type, so we have to go back and make sure
2391 /// to relate the argument types too. This is kind of wrong, but
2392 /// since we control the full set of impls, also not that wrong,
2393 /// and it DOES yield better error messages (since we don't report
2394 /// errors as if there is no applicable impl, but rather report
2395 /// errors are about mismatched argument types.
2397 /// Here is an example. Imagine we have an closure expression
2398 /// and we desugared it so that the type of the expression is
2399 /// `Closure`, and `Closure` expects an int as argument. Then it
2400 /// is "as if" the compiler generated this impl:
2402 /// impl Fn(int) for Closure { ... }
2404 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2405 /// we have matched the self-type `Closure`. At this point we'll
2406 /// compare the `int` to `usize` and generate an error.
2408 /// Note that this checking occurs *after* the impl has selected,
2409 /// because these output type parameters should not affect the
2410 /// selection of the impl. Therefore, if there is a mismatch, we
2411 /// report an error to the user.
2412 fn confirm_poly_trait_refs(&mut self,
2413 obligation_cause: ObligationCause,
2414 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2415 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2416 -> Result<(), SelectionError<'tcx>>
2418 let origin = infer::RelateOutputImplTypes(obligation_cause.span);
2420 let obligation_trait_ref = obligation_trait_ref.clone();
2421 match self.infcx.sub_poly_trait_refs(false,
2423 expected_trait_ref.clone(),
2424 obligation_trait_ref.clone()) {
2426 Err(e) => Err(OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2430 fn confirm_builtin_unsize_candidate(&mut self,
2431 obligation: &TraitObligation<'tcx>,)
2432 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2433 SelectionError<'tcx>> {
2434 let tcx = self.tcx();
2436 // assemble_candidates_for_unsizing should ensure there are no late bound
2437 // regions here. See the comment there for more details.
2438 let source = self.infcx.shallow_resolve(
2439 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2440 let target = self.infcx.shallow_resolve(obligation.predicate.0.input_types()[0]);
2442 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2445 let mut nested = vec![];
2446 match (&source.sty, &target.sty) {
2447 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2448 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
2449 // See assemble_candidates_for_unsizing for more info.
2450 let bounds = ty::ExistentialBounds {
2451 region_bound: data_b.bounds.region_bound,
2452 builtin_bounds: data_b.bounds.builtin_bounds,
2453 projection_bounds: data_a.bounds.projection_bounds.clone(),
2456 let new_trait = tcx.mk_trait(data_a.principal.clone(), bounds);
2457 let origin = infer::Misc(obligation.cause.span);
2458 if self.infcx.sub_types(false, origin, new_trait, target).is_err() {
2459 return Err(Unimplemented);
2462 // Register one obligation for 'a: 'b.
2463 let cause = ObligationCause::new(obligation.cause.span,
2464 obligation.cause.body_id,
2465 ObjectCastObligation(target));
2466 let outlives = ty::OutlivesPredicate(data_a.bounds.region_bound,
2467 data_b.bounds.region_bound);
2468 nested.push(Obligation::with_depth(cause,
2469 obligation.recursion_depth + 1,
2470 ty::Binder(outlives).to_predicate()));
2474 (_, &ty::TyTrait(ref data)) => {
2475 let object_did = data.principal_def_id();
2476 if !object_safety::is_object_safe(tcx, object_did) {
2477 return Err(TraitNotObjectSafe(object_did));
2480 let cause = ObligationCause::new(obligation.cause.span,
2481 obligation.cause.body_id,
2482 ObjectCastObligation(target));
2483 let mut push = |predicate| {
2484 nested.push(Obligation::with_depth(cause.clone(),
2485 obligation.recursion_depth + 1,
2489 // Create the obligation for casting from T to Trait.
2490 push(data.principal_trait_ref_with_self_ty(tcx, source).to_predicate());
2492 // We can only make objects from sized types.
2493 let mut builtin_bounds = data.bounds.builtin_bounds;
2494 builtin_bounds.insert(ty::BoundSized);
2496 // Create additional obligations for all the various builtin
2497 // bounds attached to the object cast. (In other words, if the
2498 // object type is Foo+Send, this would create an obligation
2499 // for the Send check.)
2500 for bound in &builtin_bounds {
2501 if let Ok(tr) = util::trait_ref_for_builtin_bound(tcx, bound, source) {
2502 push(tr.to_predicate());
2504 return Err(Unimplemented);
2508 // Create obligations for the projection predicates.
2509 for bound in data.projection_bounds_with_self_ty(tcx, source) {
2510 push(bound.to_predicate());
2513 // If the type is `Foo+'a`, ensures that the type
2514 // being cast to `Foo+'a` outlives `'a`:
2515 let outlives = ty::OutlivesPredicate(source,
2516 data.bounds.region_bound);
2517 push(ty::Binder(outlives).to_predicate());
2521 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2522 let origin = infer::Misc(obligation.cause.span);
2523 if self.infcx.sub_types(false, origin, a, b).is_err() {
2524 return Err(Unimplemented);
2528 // Struct<T> -> Struct<U>.
2529 (&ty::TyStruct(def, substs_a), &ty::TyStruct(_, substs_b)) => {
2532 .map(|f| f.unsubst_ty())
2533 .collect::<Vec<_>>();
2535 // The last field of the structure has to exist and contain type parameters.
2536 let field = if let Some(&field) = fields.last() {
2539 return Err(Unimplemented);
2541 let mut ty_params = vec![];
2542 for ty in field.walk() {
2543 if let ty::TyParam(p) = ty.sty {
2544 assert!(p.space == TypeSpace);
2545 let idx = p.idx as usize;
2546 if !ty_params.contains(&idx) {
2547 ty_params.push(idx);
2551 if ty_params.is_empty() {
2552 return Err(Unimplemented);
2555 // Replace type parameters used in unsizing with
2556 // TyError and ensure they do not affect any other fields.
2557 // This could be checked after type collection for any struct
2558 // with a potentially unsized trailing field.
2559 let mut new_substs = substs_a.clone();
2560 for &i in &ty_params {
2561 new_substs.types.get_mut_slice(TypeSpace)[i] = tcx.types.err;
2563 for &ty in fields.split_last().unwrap().1 {
2564 if ty.subst(tcx, &new_substs).references_error() {
2565 return Err(Unimplemented);
2569 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2570 let inner_source = field.subst(tcx, substs_a);
2571 let inner_target = field.subst(tcx, substs_b);
2573 // Check that the source structure with the target's
2574 // type parameters is a subtype of the target.
2575 for &i in &ty_params {
2576 let param_b = *substs_b.types.get(TypeSpace, i);
2577 new_substs.types.get_mut_slice(TypeSpace)[i] = param_b;
2579 let new_struct = tcx.mk_struct(def, tcx.mk_substs(new_substs));
2580 let origin = infer::Misc(obligation.cause.span);
2581 if self.infcx.sub_types(false, origin, new_struct, target).is_err() {
2582 return Err(Unimplemented);
2585 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2586 nested.push(util::predicate_for_trait_def(tcx,
2587 obligation.cause.clone(),
2588 obligation.predicate.def_id(),
2589 obligation.recursion_depth + 1,
2591 vec![inner_target]));
2597 Ok(VtableBuiltinData { nested: nested })
2600 ///////////////////////////////////////////////////////////////////////////
2603 // Matching is a common path used for both evaluation and
2604 // confirmation. It basically unifies types that appear in impls
2605 // and traits. This does affect the surrounding environment;
2606 // therefore, when used during evaluation, match routines must be
2607 // run inside of a `probe()` so that their side-effects are
2610 fn rematch_impl(&mut self,
2612 obligation: &TraitObligation<'tcx>,
2613 snapshot: &infer::CombinedSnapshot)
2614 -> (Normalized<'tcx, Substs<'tcx>>, infer::SkolemizationMap)
2616 match self.match_impl(impl_def_id, obligation, snapshot) {
2617 Ok((substs, skol_map)) => (substs, skol_map),
2619 self.tcx().sess.bug(
2620 &format!("Impl {:?} was matchable against {:?} but now is not",
2627 fn match_impl(&mut self,
2629 obligation: &TraitObligation<'tcx>,
2630 snapshot: &infer::CombinedSnapshot)
2631 -> Result<(Normalized<'tcx, Substs<'tcx>>,
2632 infer::SkolemizationMap), ()>
2634 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2636 // Before we create the substitutions and everything, first
2637 // consider a "quick reject". This avoids creating more types
2638 // and so forth that we need to.
2639 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2643 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2644 &obligation.predicate,
2646 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2648 let impl_substs = util::fresh_type_vars_for_impl(self.infcx,
2649 obligation.cause.span,
2652 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2655 let impl_trait_ref =
2656 project::normalize_with_depth(self,
2657 obligation.cause.clone(),
2658 obligation.recursion_depth + 1,
2661 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2662 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2666 skol_obligation_trait_ref);
2668 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
2669 if let Err(e) = self.infcx.sub_trait_refs(false,
2671 impl_trait_ref.value.clone(),
2672 skol_obligation_trait_ref) {
2673 debug!("match_impl: failed sub_trait_refs due to `{}`", e);
2677 if let Err(e) = self.infcx.leak_check(&skol_map, snapshot) {
2678 debug!("match_impl: failed leak check due to `{}`", e);
2682 debug!("match_impl: success impl_substs={:?}", impl_substs);
2685 obligations: impl_trait_ref.obligations
2689 fn fast_reject_trait_refs(&mut self,
2690 obligation: &TraitObligation,
2691 impl_trait_ref: &ty::TraitRef)
2694 // We can avoid creating type variables and doing the full
2695 // substitution if we find that any of the input types, when
2696 // simplified, do not match.
2698 obligation.predicate.0.input_types().iter()
2699 .zip(impl_trait_ref.input_types())
2700 .any(|(&obligation_ty, &impl_ty)| {
2701 let simplified_obligation_ty =
2702 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2703 let simplified_impl_ty =
2704 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2706 simplified_obligation_ty.is_some() &&
2707 simplified_impl_ty.is_some() &&
2708 simplified_obligation_ty != simplified_impl_ty
2712 /// Normalize `where_clause_trait_ref` and try to match it against
2713 /// `obligation`. If successful, return any predicates that
2714 /// result from the normalization. Normalization is necessary
2715 /// because where-clauses are stored in the parameter environment
2717 fn match_where_clause_trait_ref(&mut self,
2718 obligation: &TraitObligation<'tcx>,
2719 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2720 -> Result<Vec<PredicateObligation<'tcx>>,()>
2722 try!(self.match_poly_trait_ref(obligation, where_clause_trait_ref));
2726 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2727 /// obligation is satisfied.
2728 fn match_poly_trait_ref(&self,
2729 obligation: &TraitObligation<'tcx>,
2730 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2733 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2737 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
2738 match self.infcx.sub_poly_trait_refs(false,
2741 obligation.predicate.to_poly_trait_ref()) {
2747 /// Determines whether the self type declared against
2748 /// `impl_def_id` matches `obligation_self_ty`. If successful,
2749 /// returns the substitutions used to make them match. See
2750 /// `match_impl()`. For example, if `impl_def_id` is declared
2753 /// impl<T:Copy> Foo for Box<T> { ... }
2755 /// and `obligation_self_ty` is `int`, we'd get back an `Err(_)`
2756 /// result. But if `obligation_self_ty` were `Box<int>`, we'd get
2757 /// back `Ok(T=int)`.
2758 fn match_inherent_impl(&mut self,
2760 obligation_cause: &ObligationCause,
2761 obligation_self_ty: Ty<'tcx>)
2762 -> Result<Substs<'tcx>,()>
2764 // Create fresh type variables for each type parameter declared
2766 let impl_substs = util::fresh_type_vars_for_impl(self.infcx,
2767 obligation_cause.span,
2770 // Find the self type for the impl.
2771 let impl_self_ty = self.tcx().lookup_item_type(impl_def_id).ty;
2772 let impl_self_ty = impl_self_ty.subst(self.tcx(), &impl_substs);
2774 debug!("match_impl_self_types(obligation_self_ty={:?}, impl_self_ty={:?})",
2778 match self.match_self_types(obligation_cause,
2780 obligation_self_ty) {
2782 debug!("Matched impl_substs={:?}", impl_substs);
2792 fn match_self_types(&mut self,
2793 cause: &ObligationCause,
2795 // The self type provided by the impl/caller-obligation:
2796 provided_self_ty: Ty<'tcx>,
2798 // The self type the obligation is for:
2799 required_self_ty: Ty<'tcx>)
2802 // FIXME(#5781) -- equating the types is stronger than
2803 // necessary. Should consider variance of trait w/r/t Self.
2805 let origin = infer::RelateSelfType(cause.span);
2806 match self.infcx.eq_types(false,
2815 ///////////////////////////////////////////////////////////////////////////
2818 fn match_fresh_trait_refs(&self,
2819 previous: &ty::PolyTraitRef<'tcx>,
2820 current: &ty::PolyTraitRef<'tcx>)
2823 let mut matcher = ty::_match::Match::new(self.tcx());
2824 matcher.relate(previous, current).is_ok()
2827 fn push_stack<'o,'s:'o>(&mut self,
2828 previous_stack: TraitObligationStackList<'s, 'tcx>,
2829 obligation: &'o TraitObligation<'tcx>)
2830 -> TraitObligationStack<'o, 'tcx>
2832 let fresh_trait_ref =
2833 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2835 TraitObligationStack {
2836 obligation: obligation,
2837 fresh_trait_ref: fresh_trait_ref,
2838 previous: previous_stack,
2842 fn closure_trait_ref_unnormalized(&mut self,
2843 obligation: &TraitObligation<'tcx>,
2844 closure_def_id: DefId,
2845 substs: &ty::ClosureSubsts<'tcx>)
2846 -> ty::PolyTraitRef<'tcx>
2848 let closure_type = self.infcx.closure_type(closure_def_id, substs);
2849 let ty::Binder((trait_ref, _)) =
2850 util::closure_trait_ref_and_return_type(self.tcx(),
2851 obligation.predicate.def_id(),
2852 obligation.predicate.0.self_ty(), // (1)
2854 util::TupleArgumentsFlag::No);
2855 // (1) Feels icky to skip the binder here, but OTOH we know
2856 // that the self-type is an unboxed closure type and hence is
2857 // in fact unparameterized (or at least does not reference any
2858 // regions bound in the obligation). Still probably some
2859 // refactoring could make this nicer.
2861 ty::Binder(trait_ref)
2864 fn closure_trait_ref(&mut self,
2865 obligation: &TraitObligation<'tcx>,
2866 closure_def_id: DefId,
2867 substs: &ty::ClosureSubsts<'tcx>)
2868 -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
2870 let trait_ref = self.closure_trait_ref_unnormalized(
2871 obligation, closure_def_id, substs);
2873 // A closure signature can contain associated types which
2874 // must be normalized.
2875 normalize_with_depth(self,
2876 obligation.cause.clone(),
2877 obligation.recursion_depth+1,
2881 /// Returns the obligations that are implied by instantiating an
2882 /// impl or trait. The obligations are substituted and fully
2883 /// normalized. This is used when confirming an impl or default
2885 fn impl_or_trait_obligations(&mut self,
2886 cause: ObligationCause<'tcx>,
2887 recursion_depth: usize,
2888 def_id: DefId, // of impl or trait
2889 substs: &Substs<'tcx>, // for impl or trait
2890 skol_map: infer::SkolemizationMap,
2891 snapshot: &infer::CombinedSnapshot)
2892 -> Vec<PredicateObligation<'tcx>>
2894 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2896 let predicates = self.tcx().lookup_predicates(def_id);
2897 let predicates = predicates.instantiate(self.tcx(), substs);
2898 let predicates = normalize_with_depth(self, cause.clone(), recursion_depth, &predicates);
2899 let mut predicates = self.infcx().plug_leaks(skol_map, snapshot, &predicates);
2900 let mut obligations =
2901 util::predicates_for_generics(cause,
2904 obligations.append(&mut predicates.obligations);
2908 #[allow(unused_comparisons)]
2909 fn derived_cause(&self,
2910 obligation: &TraitObligation<'tcx>,
2911 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2912 -> ObligationCause<'tcx>
2915 * Creates a cause for obligations that are derived from
2916 * `obligation` by a recursive search (e.g., for a builtin
2917 * bound, or eventually a `impl Foo for ..`). If `obligation`
2918 * is itself a derived obligation, this is just a clone, but
2919 * otherwise we create a "derived obligation" cause so as to
2920 * keep track of the original root obligation for error
2924 // NOTE(flaper87): As of now, it keeps track of the whole error
2925 // chain. Ideally, we should have a way to configure this either
2926 // by using -Z verbose or just a CLI argument.
2927 if obligation.recursion_depth >= 0 {
2928 let derived_code = match obligation.cause.code {
2929 ObligationCauseCode::RFC1214(ref base_code) => {
2930 let derived_cause = DerivedObligationCause {
2931 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2932 parent_code: base_code.clone(),
2934 ObligationCauseCode::RFC1214(Rc::new(variant(derived_cause)))
2937 let derived_cause = DerivedObligationCause {
2938 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2939 parent_code: Rc::new(obligation.cause.code.clone())
2941 variant(derived_cause)
2944 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2946 obligation.cause.clone()
2951 impl<'tcx> SelectionCache<'tcx> {
2952 pub fn new() -> SelectionCache<'tcx> {
2954 hashmap: RefCell::new(FnvHashMap())
2959 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
2960 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
2961 TraitObligationStackList::with(self)
2964 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
2969 #[derive(Copy, Clone)]
2970 struct TraitObligationStackList<'o,'tcx:'o> {
2971 head: Option<&'o TraitObligationStack<'o,'tcx>>
2974 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
2975 fn empty() -> TraitObligationStackList<'o,'tcx> {
2976 TraitObligationStackList { head: None }
2979 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
2980 TraitObligationStackList { head: Some(r) }
2984 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
2985 type Item = &'o TraitObligationStack<'o,'tcx>;
2987 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
2998 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
2999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3000 write!(f, "TraitObligationStack({:?})", self.obligation)
3004 impl<'tcx> EvaluationResult<'tcx> {
3005 fn may_apply(&self) -> bool {
3009 EvaluatedToErr(OutputTypeParameterMismatch(..)) |
3010 EvaluatedToErr(TraitNotObjectSafe(_)) =>
3013 EvaluatedToErr(Unimplemented) =>
3019 impl MethodMatchResult {
3020 pub fn may_apply(&self) -> bool {
3022 MethodMatched(_) => true,
3023 MethodAmbiguous(_) => true,
3024 MethodDidNotMatch => false,