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
13 pub use self::MethodMatchResult::*;
14 pub use self::MethodMatchedData::*;
15 use self::SelectionCandidate::*;
16 use self::BuiltinBoundConditions::*;
17 use self::EvaluationResult::*;
20 use super::DerivedObligationCause;
22 use super::project::{normalize_with_depth, Normalized};
23 use super::{PredicateObligation, TraitObligation, ObligationCause};
24 use super::report_overflow_error;
25 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
26 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
27 use super::{ObjectCastObligation, Obligation};
28 use super::ProjectionMode;
29 use super::TraitNotObjectSafe;
31 use super::SelectionResult;
32 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure,
33 VtableFnPointer, VtableObject, VtableDefaultImpl};
34 use super::{VtableImplData, VtableObjectData, VtableBuiltinData,
35 VtableClosureData, VtableDefaultImplData};
36 use super::object_safety;
39 use hir::def_id::DefId;
41 use infer::{InferCtxt, InferOk, TypeFreshener, TypeOrigin};
42 use ty::subst::{Subst, Substs, TypeSpace};
43 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
46 use ty::relate::TypeRelation;
48 use std::cell::RefCell;
53 use util::common::ErrorReported;
54 use util::nodemap::FnvHashMap;
56 pub struct SelectionContext<'cx, 'tcx:'cx> {
57 infcx: &'cx InferCtxt<'cx, 'tcx>,
59 /// Freshener used specifically for skolemizing entries on the
60 /// obligation stack. This ensures that all entries on the stack
61 /// at one time will have the same set of skolemized entries,
62 /// which is important for checking for trait bounds that
63 /// recursively require themselves.
64 freshener: TypeFreshener<'cx, 'tcx>,
66 /// If true, indicates that the evaluation should be conservative
67 /// and consider the possibility of types outside this crate.
68 /// This comes up primarily when resolving ambiguity. Imagine
69 /// there is some trait reference `$0 : Bar` where `$0` is an
70 /// inference variable. If `intercrate` is true, then we can never
71 /// say for sure that this reference is not implemented, even if
72 /// there are *no impls at all for `Bar`*, because `$0` could be
73 /// bound to some type that in a downstream crate that implements
74 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
75 /// though, we set this to false, because we are only interested
76 /// in types that the user could actually have written --- in
77 /// other words, we consider `$0 : Bar` to be unimplemented if
78 /// there is no type that the user could *actually name* that
79 /// would satisfy it. This avoids crippling inference, basically.
83 // A stack that walks back up the stack frame.
84 struct TraitObligationStack<'prev, 'tcx: 'prev> {
85 obligation: &'prev TraitObligation<'tcx>,
87 /// Trait ref from `obligation` but skolemized with the
88 /// selection-context's freshener. Used to check for recursion.
89 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
91 previous: TraitObligationStackList<'prev, 'tcx>,
95 pub struct SelectionCache<'tcx> {
96 hashmap: RefCell<FnvHashMap<ty::TraitRef<'tcx>,
97 SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
100 pub enum MethodMatchResult {
101 MethodMatched(MethodMatchedData),
102 MethodAmbiguous(/* list of impls that could apply */ Vec<DefId>),
106 #[derive(Copy, Clone, Debug)]
107 pub enum MethodMatchedData {
108 // In the case of a precise match, we don't really need to store
109 // how the match was found. So don't.
112 // In the case of a coercion, we need to know the precise impl so
113 // that we can determine the type to which things were coerced.
114 CoerciveMethodMatch(/* impl we matched */ DefId)
117 /// The selection process begins by considering all impls, where
118 /// clauses, and so forth that might resolve an obligation. Sometimes
119 /// we'll be able to say definitively that (e.g.) an impl does not
120 /// apply to the obligation: perhaps it is defined for `usize` but the
121 /// obligation is for `int`. In that case, we drop the impl out of the
122 /// list. But the other cases are considered *candidates*.
124 /// For selection to succeed, there must be exactly one matching
125 /// candidate. If the obligation is fully known, this is guaranteed
126 /// by coherence. However, if the obligation contains type parameters
127 /// or variables, there may be multiple such impls.
129 /// It is not a real problem if multiple matching impls exist because
130 /// of type variables - it just means the obligation isn't sufficiently
131 /// elaborated. In that case we report an ambiguity, and the caller can
132 /// try again after more type information has been gathered or report a
133 /// "type annotations required" error.
135 /// However, with type parameters, this can be a real problem - type
136 /// parameters don't unify with regular types, but they *can* unify
137 /// with variables from blanket impls, and (unless we know its bounds
138 /// will always be satisfied) picking the blanket impl will be wrong
139 /// for at least *some* substitutions. To make this concrete, if we have
141 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
142 /// impl<T: fmt::Debug> AsDebug for T {
144 /// fn debug(self) -> fmt::Debug { self }
146 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
148 /// we can't just use the impl to resolve the <T as AsDebug> obligation
149 /// - a type from another crate (that doesn't implement fmt::Debug) could
150 /// implement AsDebug.
152 /// Because where-clauses match the type exactly, multiple clauses can
153 /// only match if there are unresolved variables, and we can mostly just
154 /// report this ambiguity in that case. This is still a problem - we can't
155 /// *do anything* with ambiguities that involve only regions. This is issue
158 /// If a single where-clause matches and there are no inference
159 /// variables left, then it definitely matches and we can just select
162 /// In fact, we even select the where-clause when the obligation contains
163 /// inference variables. The can lead to inference making "leaps of logic",
164 /// for example in this situation:
166 /// pub trait Foo<T> { fn foo(&self) -> T; }
167 /// impl<T> Foo<()> for T { fn foo(&self) { } }
168 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
170 /// pub fn foo<T>(t: T) where T: Foo<bool> {
171 /// println!("{:?}", <T as Foo<_>>::foo(&t));
173 /// fn main() { foo(false); }
175 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
176 /// impl and the where-clause. We select the where-clause and unify $0=bool,
177 /// so the program prints "false". However, if the where-clause is omitted,
178 /// the blanket impl is selected, we unify $0=(), and the program prints
181 /// Exactly the same issues apply to projection and object candidates, except
182 /// that we can have both a projection candidate and a where-clause candidate
183 /// for the same obligation. In that case either would do (except that
184 /// different "leaps of logic" would occur if inference variables are
185 /// present), and we just pick the where-clause. This is, for example,
186 /// required for associated types to work in default impls, as the bounds
187 /// are visible both as projection bounds and as where-clauses from the
188 /// parameter environment.
189 #[derive(PartialEq,Eq,Debug,Clone)]
190 enum SelectionCandidate<'tcx> {
191 BuiltinCandidate(ty::BuiltinBound),
192 ParamCandidate(ty::PolyTraitRef<'tcx>),
193 ImplCandidate(DefId),
194 DefaultImplCandidate(DefId),
195 DefaultImplObjectCandidate(DefId),
197 /// This is a trait matching with a projected type as `Self`, and
198 /// we found an applicable bound in the trait definition.
201 /// Implementation of a `Fn`-family trait by one of the anonymous types
202 /// generated for a `||` expression. The ty::ClosureKind informs the
203 /// confirmation step what ClosureKind obligation to emit.
204 ClosureCandidate(/* closure */ DefId, &'tcx ty::ClosureSubsts<'tcx>, ty::ClosureKind),
206 /// Implementation of a `Fn`-family trait by one of the anonymous
207 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
212 BuiltinObjectCandidate,
214 BuiltinUnsizeCandidate,
217 struct SelectionCandidateSet<'tcx> {
218 // a list of candidates that definitely apply to the current
219 // obligation (meaning: types unify).
220 vec: Vec<SelectionCandidate<'tcx>>,
222 // if this is true, then there were candidates that might or might
223 // not have applied, but we couldn't tell. This occurs when some
224 // of the input types are type variables, in which case there are
225 // various "builtin" rules that might or might not trigger.
229 #[derive(PartialEq,Eq,Debug,Clone)]
230 struct EvaluatedCandidate<'tcx> {
231 candidate: SelectionCandidate<'tcx>,
232 evaluation: EvaluationResult,
235 enum BuiltinBoundConditions<'tcx> {
236 If(ty::Binder<Vec<Ty<'tcx>>>),
241 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
242 /// The result of trait evaluation. The order is important
243 /// here as the evaluation of a list is the maximum of the
245 enum EvaluationResult {
246 /// Evaluation successful
248 /// Evaluation failed because of recursion - treated as ambiguous
250 /// Evaluation is known to be ambiguous
252 /// Evaluation failed
257 pub struct EvaluationCache<'tcx> {
258 hashmap: RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, EvaluationResult>>
261 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
262 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
265 freshener: infcx.freshener(),
270 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
273 freshener: infcx.freshener(),
278 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
282 pub fn tcx(&self) -> &'cx TyCtxt<'tcx> {
286 pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'cx, 'tcx> {
287 self.infcx.param_env()
290 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
294 pub fn projection_mode(&self) -> ProjectionMode {
295 self.infcx.projection_mode()
298 ///////////////////////////////////////////////////////////////////////////
301 // The selection phase tries to identify *how* an obligation will
302 // be resolved. For example, it will identify which impl or
303 // parameter bound is to be used. The process can be inconclusive
304 // if the self type in the obligation is not fully inferred. Selection
305 // can result in an error in one of two ways:
307 // 1. If no applicable impl or parameter bound can be found.
308 // 2. If the output type parameters in the obligation do not match
309 // those specified by the impl/bound. For example, if the obligation
310 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
311 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
313 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
314 /// type environment by performing unification.
315 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
316 -> SelectionResult<'tcx, Selection<'tcx>> {
317 debug!("select({:?})", obligation);
318 assert!(!obligation.predicate.has_escaping_regions());
320 let dep_node = obligation.predicate.dep_node();
321 let _task = self.tcx().dep_graph.in_task(dep_node);
323 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
324 match self.candidate_from_obligation(&stack)? {
326 Some(candidate) => Ok(Some(self.confirm_candidate(obligation, candidate)?)),
330 ///////////////////////////////////////////////////////////////////////////
333 // Tests whether an obligation can be selected or whether an impl
334 // can be applied to particular types. It skips the "confirmation"
335 // step and hence completely ignores output type parameters.
337 // The result is "true" if the obligation *may* hold and "false" if
338 // we can be sure it does not.
340 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
341 pub fn evaluate_obligation(&mut self,
342 obligation: &PredicateObligation<'tcx>)
345 debug!("evaluate_obligation({:?})",
348 self.infcx.probe(|_| {
349 self.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
354 /// Evaluates whether the obligation `obligation` can be satisfied,
355 /// and returns `false` if not certain. However, this is not entirely
356 /// accurate if inference variables are involved.
357 pub fn evaluate_obligation_conservatively(&mut self,
358 obligation: &PredicateObligation<'tcx>)
361 debug!("evaluate_obligation_conservatively({:?})",
364 self.infcx.probe(|_| {
365 self.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
370 /// Evaluates the predicates in `predicates` recursively. Note that
371 /// this applies projections in the predicates, and therefore
372 /// is run within an inference probe.
373 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
374 stack: TraitObligationStackList<'o, 'tcx>,
377 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
379 let mut result = EvaluatedToOk;
380 for obligation in predicates {
381 let eval = self.evaluate_predicate_recursively(stack, obligation);
382 debug!("evaluate_predicate_recursively({:?}) = {:?}",
385 EvaluatedToErr => { return EvaluatedToErr; }
386 EvaluatedToAmbig => { result = EvaluatedToAmbig; }
387 EvaluatedToUnknown => {
388 if result < EvaluatedToUnknown {
389 result = EvaluatedToUnknown;
398 fn evaluate_predicate_recursively<'o>(&mut self,
399 previous_stack: TraitObligationStackList<'o, 'tcx>,
400 obligation: &PredicateObligation<'tcx>)
403 debug!("evaluate_predicate_recursively({:?})",
406 // Check the cache from the tcx of predicates that we know
407 // have been proven elsewhere. This cache only contains
408 // predicates that are global in scope and hence unaffected by
409 // the current environment.
410 if self.tcx().fulfilled_predicates.borrow().check_duplicate(&obligation.predicate) {
411 return EvaluatedToOk;
414 match obligation.predicate {
415 ty::Predicate::Trait(ref t) => {
416 assert!(!t.has_escaping_regions());
417 let obligation = obligation.with(t.clone());
418 self.evaluate_obligation_recursively(previous_stack, &obligation)
421 ty::Predicate::Equate(ref p) => {
422 // does this code ever run?
423 match self.infcx.equality_predicate(obligation.cause.span, p) {
424 Ok(InferOk { obligations, .. }) => {
425 // FIXME(#32730) propagate obligations
426 assert!(obligations.is_empty());
429 Err(_) => EvaluatedToErr
433 ty::Predicate::WellFormed(ty) => {
434 match ty::wf::obligations(self.infcx, obligation.cause.body_id,
435 ty, obligation.cause.span) {
437 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
443 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
444 // we do not consider region relationships when
445 // evaluating trait matches
449 ty::Predicate::ObjectSafe(trait_def_id) => {
450 if object_safety::is_object_safe(self.tcx(), trait_def_id) {
457 ty::Predicate::Projection(ref data) => {
458 let project_obligation = obligation.with(data.clone());
459 match project::poly_project_and_unify_type(self, &project_obligation) {
460 Ok(Some(subobligations)) => {
461 self.evaluate_predicates_recursively(previous_stack,
462 subobligations.iter())
473 ty::Predicate::ClosureKind(closure_def_id, kind) => {
474 match self.infcx.closure_kind(closure_def_id) {
475 Some(closure_kind) => {
476 if closure_kind.extends(kind) {
490 fn evaluate_obligation_recursively<'o>(&mut self,
491 previous_stack: TraitObligationStackList<'o, 'tcx>,
492 obligation: &TraitObligation<'tcx>)
495 debug!("evaluate_obligation_recursively({:?})",
498 let stack = self.push_stack(previous_stack, obligation);
499 let fresh_trait_ref = stack.fresh_trait_ref;
500 if let Some(result) = self.check_evaluation_cache(fresh_trait_ref) {
501 debug!("CACHE HIT: EVAL({:?})={:?}",
507 let result = self.evaluate_stack(&stack);
509 debug!("CACHE MISS: EVAL({:?})={:?}",
512 self.insert_evaluation_cache(fresh_trait_ref, result);
517 fn evaluate_stack<'o>(&mut self,
518 stack: &TraitObligationStack<'o, 'tcx>)
521 // In intercrate mode, whenever any of the types are unbound,
522 // there can always be an impl. Even if there are no impls in
523 // this crate, perhaps the type would be unified with
524 // something from another crate that does provide an impl.
526 // In intra mode, we must still be conservative. The reason is
527 // that we want to avoid cycles. Imagine an impl like:
529 // impl<T:Eq> Eq for Vec<T>
531 // and a trait reference like `$0 : Eq` where `$0` is an
532 // unbound variable. When we evaluate this trait-reference, we
533 // will unify `$0` with `Vec<$1>` (for some fresh variable
534 // `$1`), on the condition that `$1 : Eq`. We will then wind
535 // up with many candidates (since that are other `Eq` impls
536 // that apply) and try to winnow things down. This results in
537 // a recursive evaluation that `$1 : Eq` -- as you can
538 // imagine, this is just where we started. To avoid that, we
539 // check for unbound variables and return an ambiguous (hence possible)
540 // match if we've seen this trait before.
542 // This suffices to allow chains like `FnMut` implemented in
543 // terms of `Fn` etc, but we could probably make this more
545 let input_types = stack.fresh_trait_ref.0.input_types();
546 let unbound_input_types = input_types.iter().any(|ty| ty.is_fresh());
547 if unbound_input_types && self.intercrate {
548 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
549 stack.fresh_trait_ref);
550 return EvaluatedToAmbig;
552 if unbound_input_types &&
553 stack.iter().skip(1).any(
554 |prev| self.match_fresh_trait_refs(&stack.fresh_trait_ref,
555 &prev.fresh_trait_ref))
557 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
558 stack.fresh_trait_ref);
559 return EvaluatedToUnknown;
562 // If there is any previous entry on the stack that precisely
563 // matches this obligation, then we can assume that the
564 // obligation is satisfied for now (still all other conditions
565 // must be met of course). One obvious case this comes up is
566 // marker traits like `Send`. Think of a linked list:
568 // struct List<T> { data: T, next: Option<Box<List<T>>> {
570 // `Box<List<T>>` will be `Send` if `T` is `Send` and
571 // `Option<Box<List<T>>>` is `Send`, and in turn
572 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
575 // Note that we do this comparison using the `fresh_trait_ref`
576 // fields. Because these have all been skolemized using
577 // `self.freshener`, we can be sure that (a) this will not
578 // affect the inferencer state and (b) that if we see two
579 // skolemized types with the same index, they refer to the
580 // same unbound type variable.
583 .skip(1) // skip top-most frame
584 .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref)
586 debug!("evaluate_stack({:?}) --> recursive",
587 stack.fresh_trait_ref);
588 return EvaluatedToOk;
591 match self.candidate_from_obligation(stack) {
592 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
593 Ok(None) => EvaluatedToAmbig,
594 Err(..) => EvaluatedToErr
598 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
599 /// obligations are met. Returns true if `candidate` remains viable after this further
601 fn evaluate_candidate<'o>(&mut self,
602 stack: &TraitObligationStack<'o, 'tcx>,
603 candidate: &SelectionCandidate<'tcx>)
606 debug!("evaluate_candidate: depth={} candidate={:?}",
607 stack.obligation.recursion_depth, candidate);
608 let result = self.infcx.probe(|_| {
609 let candidate = (*candidate).clone();
610 match self.confirm_candidate(stack.obligation, candidate) {
612 self.evaluate_predicates_recursively(
614 selection.nested_obligations().iter())
616 Err(..) => EvaluatedToErr
619 debug!("evaluate_candidate: depth={} result={:?}",
620 stack.obligation.recursion_depth, result);
624 fn pick_evaluation_cache(&self) -> &EvaluationCache<'tcx> {
625 // see comment in `pick_candidate_cache`
626 if self.intercrate ||
627 !self.param_env().caller_bounds.is_empty()
629 &self.param_env().evaluation_cache
632 &self.tcx().evaluation_cache
636 fn check_evaluation_cache(&self, trait_ref: ty::PolyTraitRef<'tcx>)
637 -> Option<EvaluationResult>
639 let cache = self.pick_evaluation_cache();
640 cache.hashmap.borrow().get(&trait_ref).cloned()
643 fn insert_evaluation_cache(&mut self,
644 trait_ref: ty::PolyTraitRef<'tcx>,
645 result: EvaluationResult)
647 // Avoid caching results that depend on more than just the trait-ref:
648 // The stack can create EvaluatedToUnknown, and closure signatures
649 // being yet uninferred can create "spurious" EvaluatedToAmbig
650 // and EvaluatedToOk.
651 if result == EvaluatedToUnknown ||
652 ((result == EvaluatedToAmbig || result == EvaluatedToOk)
653 && trait_ref.has_closure_types())
658 let cache = self.pick_evaluation_cache();
659 cache.hashmap.borrow_mut().insert(trait_ref, result);
662 ///////////////////////////////////////////////////////////////////////////
663 // CANDIDATE ASSEMBLY
665 // The selection process begins by examining all in-scope impls,
666 // caller obligations, and so forth and assembling a list of
667 // candidates. See `README.md` and the `Candidate` type for more
670 fn candidate_from_obligation<'o>(&mut self,
671 stack: &TraitObligationStack<'o, 'tcx>)
672 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
674 // Watch out for overflow. This intentionally bypasses (and does
675 // not update) the cache.
676 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
677 if stack.obligation.recursion_depth >= recursion_limit {
678 report_overflow_error(self.infcx(), &stack.obligation, true);
681 // Check the cache. Note that we skolemize the trait-ref
682 // separately rather than using `stack.fresh_trait_ref` -- this
683 // is because we want the unbound variables to be replaced
684 // with fresh skolemized types starting from index 0.
685 let cache_fresh_trait_pred =
686 self.infcx.freshen(stack.obligation.predicate.clone());
687 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
688 cache_fresh_trait_pred,
690 assert!(!stack.obligation.predicate.has_escaping_regions());
692 match self.check_candidate_cache(&cache_fresh_trait_pred) {
694 debug!("CACHE HIT: SELECT({:?})={:?}",
695 cache_fresh_trait_pred,
702 // If no match, compute result and insert into cache.
703 let candidate = self.candidate_from_obligation_no_cache(stack);
705 if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
706 debug!("CACHE MISS: SELECT({:?})={:?}",
707 cache_fresh_trait_pred, candidate);
708 self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone());
714 // Treat negative impls as unimplemented
715 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
716 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
717 if let ImplCandidate(def_id) = candidate {
718 if self.tcx().trait_impl_polarity(def_id) == Some(hir::ImplPolarity::Negative) {
719 return Err(Unimplemented)
725 fn candidate_from_obligation_no_cache<'o>(&mut self,
726 stack: &TraitObligationStack<'o, 'tcx>)
727 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
729 if stack.obligation.predicate.references_error() {
730 // If we encounter a `TyError`, we generally prefer the
731 // most "optimistic" result in response -- that is, the
732 // one least likely to report downstream errors. But
733 // because this routine is shared by coherence and by
734 // trait selection, there isn't an obvious "right" choice
735 // here in that respect, so we opt to just return
736 // ambiguity and let the upstream clients sort it out.
740 if !self.is_knowable(stack) {
741 debug!("coherence stage: not knowable");
745 let candidate_set = self.assemble_candidates(stack)?;
747 if candidate_set.ambiguous {
748 debug!("candidate set contains ambig");
752 let mut candidates = candidate_set.vec;
754 debug!("assembled {} candidates for {:?}: {:?}",
759 // At this point, we know that each of the entries in the
760 // candidate set is *individually* applicable. Now we have to
761 // figure out if they contain mutual incompatibilities. This
762 // frequently arises if we have an unconstrained input type --
763 // for example, we are looking for $0:Eq where $0 is some
764 // unconstrained type variable. In that case, we'll get a
765 // candidate which assumes $0 == int, one that assumes $0 ==
766 // usize, etc. This spells an ambiguity.
768 // If there is more than one candidate, first winnow them down
769 // by considering extra conditions (nested obligations and so
770 // forth). We don't winnow if there is exactly one
771 // candidate. This is a relatively minor distinction but it
772 // can lead to better inference and error-reporting. An
773 // example would be if there was an impl:
775 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
777 // and we were to see some code `foo.push_clone()` where `boo`
778 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
779 // we were to winnow, we'd wind up with zero candidates.
780 // Instead, we select the right impl now but report `Bar does
781 // not implement Clone`.
782 if candidates.len() == 1 {
783 return self.filter_negative_impls(candidates.pop().unwrap());
786 // Winnow, but record the exact outcome of evaluation, which
787 // is needed for specialization.
788 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
789 let eval = self.evaluate_candidate(stack, &c);
790 if eval.may_apply() {
791 Some(EvaluatedCandidate {
800 // If there are STILL multiple candidate, we can further
801 // reduce the list by dropping duplicates -- including
802 // resolving specializations.
803 if candidates.len() > 1 {
805 while i < candidates.len() {
807 (0..candidates.len())
809 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
812 debug!("Dropping candidate #{}/{}: {:?}",
813 i, candidates.len(), candidates[i]);
814 candidates.swap_remove(i);
816 debug!("Retaining candidate #{}/{}: {:?}",
817 i, candidates.len(), candidates[i]);
823 // If there are *STILL* multiple candidates, give up and
825 if candidates.len() > 1 {
826 debug!("multiple matches, ambig");
830 // If there are *NO* candidates, then there are no impls --
831 // that we know of, anyway. Note that in the case where there
832 // are unbound type variables within the obligation, it might
833 // be the case that you could still satisfy the obligation
834 // from another crate by instantiating the type variables with
835 // a type from another crate that does have an impl. This case
836 // is checked for in `evaluate_stack` (and hence users
837 // who might care about this case, like coherence, should use
839 if candidates.is_empty() {
840 return Err(Unimplemented);
843 // Just one candidate left.
844 self.filter_negative_impls(candidates.pop().unwrap().candidate)
847 fn is_knowable<'o>(&mut self,
848 stack: &TraitObligationStack<'o, 'tcx>)
851 debug!("is_knowable(intercrate={})", self.intercrate);
853 if !self.intercrate {
857 let obligation = &stack.obligation;
858 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
860 // ok to skip binder because of the nature of the
861 // trait-ref-is-knowable check, which does not care about
863 let trait_ref = &predicate.skip_binder().trait_ref;
865 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
868 fn pick_candidate_cache(&self) -> &SelectionCache<'tcx> {
869 // If there are any where-clauses in scope, then we always use
870 // a cache local to this particular scope. Otherwise, we
871 // switch to a global cache. We used to try and draw
872 // finer-grained distinctions, but that led to a serious of
873 // annoying and weird bugs like #22019 and #18290. This simple
874 // rule seems to be pretty clearly safe and also still retains
875 // a very high hit rate (~95% when compiling rustc).
876 if !self.param_env().caller_bounds.is_empty() {
877 return &self.param_env().selection_cache;
880 // Avoid using the master cache during coherence and just rely
881 // on the local cache. This effectively disables caching
882 // during coherence. It is really just a simplification to
883 // avoid us having to fear that coherence results "pollute"
884 // the master cache. Since coherence executes pretty quickly,
885 // it's not worth going to more trouble to increase the
886 // hit-rate I don't think.
888 return &self.param_env().selection_cache;
891 // Otherwise, we can use the global cache.
892 &self.tcx().selection_cache
895 fn check_candidate_cache(&mut self,
896 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
897 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
899 let cache = self.pick_candidate_cache();
900 let hashmap = cache.hashmap.borrow();
901 hashmap.get(&cache_fresh_trait_pred.0.trait_ref).cloned()
904 fn insert_candidate_cache(&mut self,
905 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
906 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
908 let cache = self.pick_candidate_cache();
909 let mut hashmap = cache.hashmap.borrow_mut();
910 hashmap.insert(cache_fresh_trait_pred.0.trait_ref.clone(), candidate);
913 fn should_update_candidate_cache(&mut self,
914 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
915 candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
918 // In general, it's a good idea to cache results, even
919 // ambiguous ones, to save us some trouble later. But we have
920 // to be careful not to cache results that could be
921 // invalidated later by advances in inference. Normally, this
922 // is not an issue, because any inference variables whose
923 // types are not yet bound are "freshened" in the cache key,
924 // which means that if we later get the same request once that
925 // type variable IS bound, we'll have a different cache key.
926 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
927 // not yet known, we may cache the result as `None`. But if
928 // later `_#0t` is bound to `Bar`, then when we freshen we'll
929 // have `Vec<Bar> : Foo` as the cache key.
931 // HOWEVER, it CAN happen that we get an ambiguity result in
932 // one particular case around closures where the cache key
933 // would not change. That is when the precise types of the
934 // upvars that a closure references have not yet been figured
935 // out (i.e., because it is not yet known if they are captured
936 // by ref, and if by ref, what kind of ref). In these cases,
937 // when matching a builtin bound, we will yield back an
938 // ambiguous result. But the *cache key* is just the closure type,
939 // it doesn't capture the state of the upvar computation.
941 // To avoid this trap, just don't cache ambiguous results if
942 // the self-type contains no inference byproducts (that really
943 // shouldn't happen in other circumstances anyway, given
947 Ok(Some(_)) | Err(_) => true,
949 cache_fresh_trait_pred.0.trait_ref.substs.types.has_infer_types()
954 fn assemble_candidates<'o>(&mut self,
955 stack: &TraitObligationStack<'o, 'tcx>)
956 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
958 let TraitObligationStack { obligation, .. } = *stack;
959 let ref obligation = Obligation {
960 cause: obligation.cause.clone(),
961 recursion_depth: obligation.recursion_depth,
962 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
965 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
966 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
968 // This is somewhat problematic, as the current scheme can't really
969 // handle it turning to be a projection. This does end up as truly
970 // ambiguous in most cases anyway.
972 // Until this is fixed, take the fast path out - this also improves
973 // performance by preventing assemble_candidates_from_impls from
974 // matching every impl for this trait.
975 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
978 let mut candidates = SelectionCandidateSet {
983 // Other bounds. Consider both in-scope bounds from fn decl
984 // and applicable impls. There is a certain set of precedence rules here.
986 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
987 Some(ty::BoundCopy) => {
988 debug!("obligation self ty is {:?}",
989 obligation.predicate.0.self_ty());
991 // User-defined copy impls are permitted, but only for
992 // structs and enums.
993 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
995 // For other types, we'll use the builtin rules.
996 self.assemble_builtin_bound_candidates(ty::BoundCopy,
1000 Some(bound @ ty::BoundSized) => {
1001 // Sized is never implementable by end-users, it is
1002 // always automatically computed.
1003 self.assemble_builtin_bound_candidates(bound,
1008 None if self.tcx().lang_items.unsize_trait() ==
1009 Some(obligation.predicate.def_id()) => {
1010 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1013 Some(ty::BoundSend) |
1014 Some(ty::BoundSync) |
1016 self.assemble_closure_candidates(obligation, &mut candidates)?;
1017 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1018 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1019 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1023 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1024 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1025 // Default implementations have lower priority, so we only
1026 // consider triggering a default if there is no other impl that can apply.
1027 if candidates.vec.is_empty() {
1028 self.assemble_candidates_from_default_impls(obligation, &mut candidates)?;
1030 debug!("candidate list size: {}", candidates.vec.len());
1034 fn assemble_candidates_from_projected_tys(&mut self,
1035 obligation: &TraitObligation<'tcx>,
1036 candidates: &mut SelectionCandidateSet<'tcx>)
1038 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1040 // FIXME(#20297) -- just examining the self-type is very simplistic
1042 // before we go into the whole skolemization thing, just
1043 // quickly check if the self-type is a projection at all.
1044 let trait_def_id = match obligation.predicate.0.trait_ref.self_ty().sty {
1045 ty::TyProjection(ref data) => data.trait_ref.def_id,
1046 ty::TyInfer(ty::TyVar(_)) => {
1047 span_bug!(obligation.cause.span,
1048 "Self=_ should have been handled by assemble_candidates");
1053 debug!("assemble_candidates_for_projected_tys: trait_def_id={:?}",
1056 let result = self.infcx.probe(|snapshot| {
1057 self.match_projection_obligation_against_bounds_from_trait(obligation,
1062 candidates.vec.push(ProjectionCandidate);
1066 fn match_projection_obligation_against_bounds_from_trait(
1068 obligation: &TraitObligation<'tcx>,
1069 snapshot: &infer::CombinedSnapshot)
1072 let poly_trait_predicate =
1073 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1074 let (skol_trait_predicate, skol_map) =
1075 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1076 debug!("match_projection_obligation_against_bounds_from_trait: \
1077 skol_trait_predicate={:?} skol_map={:?}",
1078 skol_trait_predicate,
1081 let projection_trait_ref = match skol_trait_predicate.trait_ref.self_ty().sty {
1082 ty::TyProjection(ref data) => &data.trait_ref,
1085 obligation.cause.span,
1086 "match_projection_obligation_against_bounds_from_trait() called \
1087 but self-ty not a projection: {:?}",
1088 skol_trait_predicate.trait_ref.self_ty());
1091 debug!("match_projection_obligation_against_bounds_from_trait: \
1092 projection_trait_ref={:?}",
1093 projection_trait_ref);
1095 let trait_predicates = self.tcx().lookup_predicates(projection_trait_ref.def_id);
1096 let bounds = trait_predicates.instantiate(self.tcx(), projection_trait_ref.substs);
1097 debug!("match_projection_obligation_against_bounds_from_trait: \
1101 let matching_bound =
1102 util::elaborate_predicates(self.tcx(), bounds.predicates.into_vec())
1105 |bound| self.infcx.probe(
1106 |_| self.match_projection(obligation,
1108 skol_trait_predicate.trait_ref.clone(),
1112 debug!("match_projection_obligation_against_bounds_from_trait: \
1113 matching_bound={:?}",
1115 match matching_bound {
1118 // Repeat the successful match, if any, this time outside of a probe.
1119 let result = self.match_projection(obligation,
1121 skol_trait_predicate.trait_ref.clone(),
1130 fn match_projection(&mut self,
1131 obligation: &TraitObligation<'tcx>,
1132 trait_bound: ty::PolyTraitRef<'tcx>,
1133 skol_trait_ref: ty::TraitRef<'tcx>,
1134 skol_map: &infer::SkolemizationMap,
1135 snapshot: &infer::CombinedSnapshot)
1138 assert!(!skol_trait_ref.has_escaping_regions());
1139 let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
1140 match self.infcx.sub_poly_trait_refs(false,
1142 trait_bound.clone(),
1143 ty::Binder(skol_trait_ref.clone())) {
1144 Ok(InferOk { obligations, .. }) => {
1145 // FIXME(#32730) propagate obligations
1146 assert!(obligations.is_empty());
1148 Err(_) => { return false; }
1151 self.infcx.leak_check(skol_map, snapshot).is_ok()
1154 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1155 /// supplied to find out whether it is listed among them.
1157 /// Never affects inference environment.
1158 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1159 stack: &TraitObligationStack<'o, 'tcx>,
1160 candidates: &mut SelectionCandidateSet<'tcx>)
1161 -> Result<(),SelectionError<'tcx>>
1163 debug!("assemble_candidates_from_caller_bounds({:?})",
1167 self.param_env().caller_bounds
1169 .filter_map(|o| o.to_opt_poly_trait_ref());
1171 let matching_bounds =
1173 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1175 let param_candidates =
1176 matching_bounds.map(|bound| ParamCandidate(bound));
1178 candidates.vec.extend(param_candidates);
1183 fn evaluate_where_clause<'o>(&mut self,
1184 stack: &TraitObligationStack<'o, 'tcx>,
1185 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1188 self.infcx().probe(move |_| {
1189 match self.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1190 Ok(obligations) => {
1191 self.evaluate_predicates_recursively(stack.list(), obligations.iter())
1193 Err(()) => EvaluatedToErr
1198 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1199 /// FnMut<..>` where `X` is a closure type.
1201 /// Note: the type parameters on a closure candidate are modeled as *output* type
1202 /// parameters and hence do not affect whether this trait is a match or not. They will be
1203 /// unified during the confirmation step.
1204 fn assemble_closure_candidates(&mut self,
1205 obligation: &TraitObligation<'tcx>,
1206 candidates: &mut SelectionCandidateSet<'tcx>)
1207 -> Result<(),SelectionError<'tcx>>
1209 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1211 None => { return Ok(()); }
1214 // ok to skip binder because the substs on closure types never
1215 // touch bound regions, they just capture the in-scope
1216 // type/region parameters
1217 let self_ty = *obligation.self_ty().skip_binder();
1218 let (closure_def_id, substs) = match self_ty.sty {
1219 ty::TyClosure(id, ref substs) => (id, substs),
1220 ty::TyInfer(ty::TyVar(_)) => {
1221 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1222 candidates.ambiguous = true;
1225 _ => { return Ok(()); }
1228 debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1233 match self.infcx.closure_kind(closure_def_id) {
1234 Some(closure_kind) => {
1235 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1236 if closure_kind.extends(kind) {
1237 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1241 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1242 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1249 /// Implement one of the `Fn()` family for a fn pointer.
1250 fn assemble_fn_pointer_candidates(&mut self,
1251 obligation: &TraitObligation<'tcx>,
1252 candidates: &mut SelectionCandidateSet<'tcx>)
1253 -> Result<(),SelectionError<'tcx>>
1255 // We provide impl of all fn traits for fn pointers.
1256 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1260 // ok to skip binder because what we are inspecting doesn't involve bound regions
1261 let self_ty = *obligation.self_ty().skip_binder();
1263 ty::TyInfer(ty::TyVar(_)) => {
1264 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1265 candidates.ambiguous = true; // could wind up being a fn() type
1268 // provide an impl, but only for suitable `fn` pointers
1269 ty::TyFnDef(_, _, &ty::BareFnTy {
1270 unsafety: hir::Unsafety::Normal,
1272 sig: ty::Binder(ty::FnSig {
1274 output: ty::FnConverging(_),
1278 ty::TyFnPtr(&ty::BareFnTy {
1279 unsafety: hir::Unsafety::Normal,
1281 sig: ty::Binder(ty::FnSig {
1283 output: ty::FnConverging(_),
1287 candidates.vec.push(FnPointerCandidate);
1296 /// Search for impls that might apply to `obligation`.
1297 fn assemble_candidates_from_impls(&mut self,
1298 obligation: &TraitObligation<'tcx>,
1299 candidates: &mut SelectionCandidateSet<'tcx>)
1300 -> Result<(), SelectionError<'tcx>>
1302 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1304 let def = self.tcx().lookup_trait_def(obligation.predicate.def_id());
1306 def.for_each_relevant_impl(
1308 obligation.predicate.0.trait_ref.self_ty(),
1310 self.infcx.probe(|snapshot| {
1311 if let Ok(_) = self.match_impl(impl_def_id, obligation, snapshot) {
1312 candidates.vec.push(ImplCandidate(impl_def_id));
1321 fn assemble_candidates_from_default_impls(&mut self,
1322 obligation: &TraitObligation<'tcx>,
1323 candidates: &mut SelectionCandidateSet<'tcx>)
1324 -> Result<(), SelectionError<'tcx>>
1326 // OK to skip binder here because the tests we do below do not involve bound regions
1327 let self_ty = *obligation.self_ty().skip_binder();
1328 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1330 let def_id = obligation.predicate.def_id();
1332 if self.tcx().trait_has_default_impl(def_id) {
1334 ty::TyTrait(..) => {
1335 // For object types, we don't know what the closed
1336 // over types are. For most traits, this means we
1337 // conservatively say nothing; a candidate may be
1338 // added by `assemble_candidates_from_object_ty`.
1339 // However, for the kind of magic reflect trait,
1340 // we consider it to be implemented even for
1341 // object types, because it just lets you reflect
1342 // onto the object type, not into the object's
1344 if self.tcx().has_attr(def_id, "rustc_reflect_like") {
1345 candidates.vec.push(DefaultImplObjectCandidate(def_id));
1349 ty::TyProjection(..) => {
1350 // In these cases, we don't know what the actual
1351 // type is. Therefore, we cannot break it down
1352 // into its constituent types. So we don't
1353 // consider the `..` impl but instead just add no
1354 // candidates: this means that typeck will only
1355 // succeed if there is another reason to believe
1356 // that this obligation holds. That could be a
1357 // where-clause or, in the case of an object type,
1358 // it could be that the object type lists the
1359 // trait (e.g. `Foo+Send : Send`). See
1360 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1361 // for an example of a test case that exercises
1364 ty::TyInfer(ty::TyVar(_)) => {
1365 // the defaulted impl might apply, we don't know
1366 candidates.ambiguous = true;
1369 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1377 /// Search for impls that might apply to `obligation`.
1378 fn assemble_candidates_from_object_ty(&mut self,
1379 obligation: &TraitObligation<'tcx>,
1380 candidates: &mut SelectionCandidateSet<'tcx>)
1382 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1383 obligation.self_ty().skip_binder());
1385 // Object-safety candidates are only applicable to object-safe
1386 // traits. Including this check is useful because it helps
1387 // inference in cases of traits like `BorrowFrom`, which are
1388 // not object-safe, and which rely on being able to infer the
1389 // self-type from one of the other inputs. Without this check,
1390 // these cases wind up being considered ambiguous due to a
1391 // (spurious) ambiguity introduced here.
1392 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1393 if !object_safety::is_object_safe(self.tcx(), predicate_trait_ref.def_id()) {
1397 self.infcx.commit_if_ok(|snapshot| {
1399 self.infcx().skolemize_late_bound_regions(&obligation.self_ty(), snapshot);
1400 let poly_trait_ref = match self_ty.sty {
1401 ty::TyTrait(ref data) => {
1402 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
1403 Some(bound @ ty::BoundSend) | Some(bound @ ty::BoundSync) => {
1404 if data.bounds.builtin_bounds.contains(&bound) {
1405 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1406 pushing candidate");
1407 candidates.vec.push(BuiltinObjectCandidate);
1414 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
1416 ty::TyInfer(ty::TyVar(_)) => {
1417 debug!("assemble_candidates_from_object_ty: ambiguous");
1418 candidates.ambiguous = true; // could wind up being an object type
1426 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1429 // Count only those upcast versions that match the trait-ref
1430 // we are looking for. Specifically, do not only check for the
1431 // correct trait, but also the correct type parameters.
1432 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1433 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1434 let upcast_trait_refs =
1435 util::supertraits(self.tcx(), poly_trait_ref)
1436 .filter(|upcast_trait_ref| {
1437 self.infcx.probe(|_| {
1438 let upcast_trait_ref = upcast_trait_ref.clone();
1439 self.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1444 if upcast_trait_refs > 1 {
1445 // can be upcast in many ways; need more type information
1446 candidates.ambiguous = true;
1447 } else if upcast_trait_refs == 1 {
1448 candidates.vec.push(ObjectCandidate);
1455 /// Search for unsizing that might apply to `obligation`.
1456 fn assemble_candidates_for_unsizing(&mut self,
1457 obligation: &TraitObligation<'tcx>,
1458 candidates: &mut SelectionCandidateSet<'tcx>) {
1459 // We currently never consider higher-ranked obligations e.g.
1460 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1461 // because they are a priori invalid, and we could potentially add support
1462 // for them later, it's just that there isn't really a strong need for it.
1463 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1464 // impl, and those are generally applied to concrete types.
1466 // That said, one might try to write a fn with a where clause like
1467 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1468 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1469 // Still, you'd be more likely to write that where clause as
1471 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1472 // obligation above. Should be possible to extend this in the future.
1473 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1476 // Don't add any candidates if there are bound regions.
1480 let target = obligation.predicate.0.input_types()[0];
1482 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1485 let may_apply = match (&source.sty, &target.sty) {
1486 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1487 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
1488 // Upcasts permit two things:
1490 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1491 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1493 // Note that neither of these changes requires any
1494 // change at runtime. Eventually this will be
1497 // We always upcast when we can because of reason
1498 // #2 (region bounds).
1499 data_a.principal.def_id() == data_a.principal.def_id() &&
1500 data_a.bounds.builtin_bounds.is_superset(&data_b.bounds.builtin_bounds)
1504 (_, &ty::TyTrait(_)) => true,
1506 // Ambiguous handling is below T -> Trait, because inference
1507 // variables can still implement Unsize<Trait> and nested
1508 // obligations will have the final say (likely deferred).
1509 (&ty::TyInfer(ty::TyVar(_)), _) |
1510 (_, &ty::TyInfer(ty::TyVar(_))) => {
1511 debug!("assemble_candidates_for_unsizing: ambiguous");
1512 candidates.ambiguous = true;
1517 (&ty::TyArray(_, _), &ty::TySlice(_)) => true,
1519 // Struct<T> -> Struct<U>.
1520 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
1521 def_id_a == def_id_b
1528 candidates.vec.push(BuiltinUnsizeCandidate);
1532 ///////////////////////////////////////////////////////////////////////////
1535 // Winnowing is the process of attempting to resolve ambiguity by
1536 // probing further. During the winnowing process, we unify all
1537 // type variables (ignoring skolemization) and then we also
1538 // attempt to evaluate recursive bounds to see if they are
1541 /// Returns true if `candidate_i` should be dropped in favor of
1542 /// `candidate_j`. Generally speaking we will drop duplicate
1543 /// candidates and prefer where-clause candidates.
1544 /// Returns true if `victim` should be dropped in favor of
1545 /// `other`. Generally speaking we will drop duplicate
1546 /// candidates and prefer where-clause candidates.
1548 /// See the comment for "SelectionCandidate" for more details.
1549 fn candidate_should_be_dropped_in_favor_of<'o>(
1551 victim: &EvaluatedCandidate<'tcx>,
1552 other: &EvaluatedCandidate<'tcx>)
1555 if victim.candidate == other.candidate {
1559 match other.candidate {
1561 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1562 DefaultImplCandidate(..) => {
1564 "default implementations shouldn't be recorded \
1565 when there are other valid candidates");
1568 ClosureCandidate(..) |
1569 FnPointerCandidate |
1570 BuiltinObjectCandidate |
1571 BuiltinUnsizeCandidate |
1572 DefaultImplObjectCandidate(..) |
1573 BuiltinCandidate(..) => {
1574 // We have a where-clause so don't go around looking
1579 ProjectionCandidate => {
1580 // Arbitrarily give param candidates priority
1581 // over projection and object candidates.
1584 ParamCandidate(..) => false,
1586 ImplCandidate(other_def) => {
1587 // See if we can toss out `victim` based on specialization.
1588 // This requires us to know *for sure* that the `other` impl applies
1589 // i.e. EvaluatedToOk:
1590 if other.evaluation == EvaluatedToOk {
1591 if let ImplCandidate(victim_def) = victim.candidate {
1592 return traits::specializes(self.tcx(), other_def, victim_def);
1602 ///////////////////////////////////////////////////////////////////////////
1605 // These cover the traits that are built-in to the language
1606 // itself. This includes `Copy` and `Sized` for sure. For the
1607 // moment, it also includes `Send` / `Sync` and a few others, but
1608 // those will hopefully change to library-defined traits in the
1611 fn assemble_builtin_bound_candidates<'o>(&mut self,
1612 bound: ty::BuiltinBound,
1613 obligation: &TraitObligation<'tcx>,
1614 candidates: &mut SelectionCandidateSet<'tcx>)
1615 -> Result<(),SelectionError<'tcx>>
1617 match self.builtin_bound(bound, obligation) {
1619 debug!("builtin_bound: bound={:?}",
1621 candidates.vec.push(BuiltinCandidate(bound));
1624 Ok(ParameterBuiltin) => { Ok(()) }
1625 Ok(AmbiguousBuiltin) => {
1626 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1627 Ok(candidates.ambiguous = true)
1629 Err(e) => { Err(e) }
1633 fn builtin_bound(&mut self,
1634 bound: ty::BuiltinBound,
1635 obligation: &TraitObligation<'tcx>)
1636 -> Result<BuiltinBoundConditions<'tcx>,SelectionError<'tcx>>
1638 // Note: these tests operate on types that may contain bound
1639 // regions. To be proper, we ought to skolemize here, but we
1640 // forego the skolemization and defer it until the
1641 // confirmation step.
1643 let self_ty = self.infcx.shallow_resolve(obligation.predicate.0.self_ty());
1644 return match self_ty.sty {
1645 ty::TyInfer(ty::IntVar(_)) |
1646 ty::TyInfer(ty::FloatVar(_)) |
1654 // safe for everything
1658 ty::TyBox(_) => { // Box<T>
1660 ty::BoundCopy => Err(Unimplemented),
1662 ty::BoundSized => ok_if(Vec::new()),
1664 ty::BoundSync | ty::BoundSend => {
1665 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1670 ty::TyRawPtr(..) => { // *const T, *mut T
1672 ty::BoundCopy | ty::BoundSized => ok_if(Vec::new()),
1674 ty::BoundSync | ty::BoundSend => {
1675 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1680 ty::TyTrait(ref data) => {
1682 ty::BoundSized => Err(Unimplemented),
1684 if data.bounds.builtin_bounds.contains(&bound) {
1687 // Recursively check all supertraits to find out if any further
1688 // bounds are required and thus we must fulfill.
1690 data.principal_trait_ref_with_self_ty(self.tcx(),
1691 self.tcx().types.err);
1692 let copy_def_id = obligation.predicate.def_id();
1693 for tr in util::supertraits(self.tcx(), principal) {
1694 if tr.def_id() == copy_def_id {
1695 return ok_if(Vec::new())
1702 ty::BoundSync | ty::BoundSend => {
1703 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1708 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl }) => {
1713 // &mut T is affine and hence never `Copy`
1714 hir::MutMutable => Err(Unimplemented),
1716 // &T is always copyable
1717 hir::MutImmutable => ok_if(Vec::new()),
1721 ty::BoundSized => ok_if(Vec::new()),
1723 ty::BoundSync | ty::BoundSend => {
1724 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1729 ty::TyArray(element_ty, _) => {
1732 ty::BoundCopy => ok_if(vec![element_ty]),
1733 ty::BoundSized => ok_if(Vec::new()),
1734 ty::BoundSync | ty::BoundSend => {
1735 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1740 ty::TyStr | ty::TySlice(_) => {
1742 ty::BoundSync | ty::BoundSend => {
1743 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1746 ty::BoundCopy | ty::BoundSized => Err(Unimplemented),
1750 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1751 ty::TyTuple(ref tys) => ok_if(tys.clone()),
1753 ty::TyClosure(_, ref substs) => {
1754 // FIXME -- This case is tricky. In the case of by-ref
1755 // closures particularly, we need the results of
1756 // inference to decide how to reflect the type of each
1757 // upvar (the upvar may have type `T`, but the runtime
1758 // type could be `&mut`, `&`, or just `T`). For now,
1759 // though, we'll do this unsoundly and assume that all
1760 // captures are by value. Really what we ought to do
1761 // is reserve judgement and then intertwine this
1762 // analysis with closure inference.
1764 // Unboxed closures shouldn't be
1765 // implicitly copyable
1766 if bound == ty::BoundCopy {
1767 return Ok(ParameterBuiltin);
1770 // Upvars are always local variables or references to
1771 // local variables, and local variables cannot be
1772 // unsized, so the closure struct as a whole must be
1774 if bound == ty::BoundSized {
1775 return ok_if(Vec::new());
1778 ok_if(substs.upvar_tys.clone())
1781 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1782 let types: Vec<Ty> = def.all_fields().map(|f| {
1783 f.ty(self.tcx(), substs)
1785 nominal(bound, types)
1788 ty::TyProjection(_) | ty::TyParam(_) => {
1789 // Note: A type parameter is only considered to meet a
1790 // particular bound if there is a where clause telling
1791 // us that it does, and that case is handled by
1792 // `assemble_candidates_from_caller_bounds()`.
1793 Ok(ParameterBuiltin)
1796 ty::TyInfer(ty::TyVar(_)) => {
1797 // Unbound type variable. Might or might not have
1798 // applicable impls and so forth, depending on what
1799 // those type variables wind up being bound to.
1800 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1801 Ok(AmbiguousBuiltin)
1804 ty::TyError => ok_if(Vec::new()),
1806 ty::TyInfer(ty::FreshTy(_))
1807 | ty::TyInfer(ty::FreshIntTy(_))
1808 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1809 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1814 fn ok_if<'tcx>(v: Vec<Ty<'tcx>>)
1815 -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>> {
1816 Ok(If(ty::Binder(v)))
1819 fn nominal<'cx, 'tcx>(bound: ty::BuiltinBound,
1820 types: Vec<Ty<'tcx>>)
1821 -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>>
1823 // First check for markers and other nonsense.
1825 // Fallback to whatever user-defined impls exist in this case.
1826 ty::BoundCopy => Ok(ParameterBuiltin),
1828 // Sized if all the component types are sized.
1829 ty::BoundSized => ok_if(types),
1831 // Shouldn't be coming through here.
1832 ty::BoundSend | ty::BoundSync => bug!(),
1837 /// For default impls, we need to break apart a type into its
1838 /// "constituent types" -- meaning, the types that it contains.
1840 /// Here are some (simple) examples:
1843 /// (i32, u32) -> [i32, u32]
1844 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1845 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1846 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1848 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1858 ty::TyInfer(ty::IntVar(_)) |
1859 ty::TyInfer(ty::FloatVar(_)) |
1866 ty::TyProjection(..) |
1867 ty::TyInfer(ty::TyVar(_)) |
1868 ty::TyInfer(ty::FreshTy(_)) |
1869 ty::TyInfer(ty::FreshIntTy(_)) |
1870 ty::TyInfer(ty::FreshFloatTy(_)) => {
1871 bug!("asked to assemble constituent types of unexpected type: {:?}",
1875 ty::TyBox(referent_ty) => { // Box<T>
1879 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
1880 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
1884 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
1888 ty::TyTuple(ref tys) => {
1889 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1893 ty::TyClosure(_, ref substs) => {
1894 // FIXME(#27086). We are invariant w/r/t our
1895 // substs.func_substs, but we don't see them as
1896 // constituent types; this seems RIGHT but also like
1897 // something that a normal type couldn't simulate. Is
1898 // this just a gap with the way that PhantomData and
1899 // OIBIT interact? That is, there is no way to say
1900 // "make me invariant with respect to this TYPE, but
1901 // do not act as though I can reach it"
1902 substs.upvar_tys.clone()
1905 // for `PhantomData<T>`, we pass `T`
1906 ty::TyStruct(def, substs) if def.is_phantom_data() => {
1907 substs.types.get_slice(TypeSpace).to_vec()
1910 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1912 .map(|f| f.ty(self.tcx(), substs))
1918 fn collect_predicates_for_types(&mut self,
1919 obligation: &TraitObligation<'tcx>,
1920 trait_def_id: DefId,
1921 types: ty::Binder<Vec<Ty<'tcx>>>)
1922 -> Vec<PredicateObligation<'tcx>>
1924 let derived_cause = match self.tcx().lang_items.to_builtin_kind(trait_def_id) {
1926 self.derived_cause(obligation, BuiltinDerivedObligation)
1929 self.derived_cause(obligation, ImplDerivedObligation)
1933 // Because the types were potentially derived from
1934 // higher-ranked obligations they may reference late-bound
1935 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1936 // yield a type like `for<'a> &'a int`. In general, we
1937 // maintain the invariant that we never manipulate bound
1938 // regions, so we have to process these bound regions somehow.
1940 // The strategy is to:
1942 // 1. Instantiate those regions to skolemized regions (e.g.,
1943 // `for<'a> &'a int` becomes `&0 int`.
1944 // 2. Produce something like `&'0 int : Copy`
1945 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1947 // Move the binder into the individual types
1948 let bound_types: Vec<ty::Binder<Ty<'tcx>>> =
1951 .map(|&nested_ty| ty::Binder(nested_ty))
1954 // For each type, produce a vector of resulting obligations
1955 let obligations: Result<Vec<Vec<_>>, _> = bound_types.iter().map(|nested_ty| {
1956 self.infcx.commit_if_ok(|snapshot| {
1957 let (skol_ty, skol_map) =
1958 self.infcx().skolemize_late_bound_regions(nested_ty, snapshot);
1959 let Normalized { value: normalized_ty, mut obligations } =
1960 project::normalize_with_depth(self,
1961 obligation.cause.clone(),
1962 obligation.recursion_depth + 1,
1964 let skol_obligation =
1965 util::predicate_for_trait_def(self.tcx(),
1966 derived_cause.clone(),
1968 obligation.recursion_depth + 1,
1971 obligations.push(skol_obligation);
1972 Ok(self.infcx().plug_leaks(skol_map, snapshot, &obligations))
1976 // Flatten those vectors (couldn't do it above due `collect`)
1978 Ok(obligations) => obligations.into_iter().flat_map(|o| o).collect(),
1979 Err(ErrorReported) => Vec::new(),
1983 ///////////////////////////////////////////////////////////////////////////
1986 // Confirmation unifies the output type parameters of the trait
1987 // with the values found in the obligation, possibly yielding a
1988 // type error. See `README.md` for more details.
1990 fn confirm_candidate(&mut self,
1991 obligation: &TraitObligation<'tcx>,
1992 candidate: SelectionCandidate<'tcx>)
1993 -> Result<Selection<'tcx>,SelectionError<'tcx>>
1995 debug!("confirm_candidate({:?}, {:?})",
2000 BuiltinCandidate(builtin_bound) => {
2002 self.confirm_builtin_candidate(obligation, builtin_bound)?))
2005 ParamCandidate(param) => {
2006 let obligations = self.confirm_param_candidate(obligation, param);
2007 Ok(VtableParam(obligations))
2010 DefaultImplCandidate(trait_def_id) => {
2011 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2012 Ok(VtableDefaultImpl(data))
2015 DefaultImplObjectCandidate(trait_def_id) => {
2016 let data = self.confirm_default_impl_object_candidate(obligation, trait_def_id);
2017 Ok(VtableDefaultImpl(data))
2020 ImplCandidate(impl_def_id) => {
2022 self.confirm_impl_candidate(obligation, impl_def_id)?;
2023 Ok(VtableImpl(vtable_impl))
2026 ClosureCandidate(closure_def_id, substs, kind) => {
2027 let vtable_closure =
2028 self.confirm_closure_candidate(obligation, closure_def_id, substs, kind)?;
2029 Ok(VtableClosure(vtable_closure))
2032 BuiltinObjectCandidate => {
2033 // This indicates something like `(Trait+Send) :
2034 // Send`. In this case, we know that this holds
2035 // because that's what the object type is telling us,
2036 // and there's really no additional obligations to
2037 // prove and no types in particular to unify etc.
2038 Ok(VtableParam(Vec::new()))
2041 ObjectCandidate => {
2042 let data = self.confirm_object_candidate(obligation);
2043 Ok(VtableObject(data))
2046 FnPointerCandidate => {
2048 self.confirm_fn_pointer_candidate(obligation)?;
2049 Ok(VtableFnPointer(fn_type))
2052 ProjectionCandidate => {
2053 self.confirm_projection_candidate(obligation);
2054 Ok(VtableParam(Vec::new()))
2057 BuiltinUnsizeCandidate => {
2058 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2059 Ok(VtableBuiltin(data))
2064 fn confirm_projection_candidate(&mut self,
2065 obligation: &TraitObligation<'tcx>)
2067 let _: Result<(),()> =
2068 self.infcx.commit_if_ok(|snapshot| {
2070 self.match_projection_obligation_against_bounds_from_trait(obligation,
2077 fn confirm_param_candidate(&mut self,
2078 obligation: &TraitObligation<'tcx>,
2079 param: ty::PolyTraitRef<'tcx>)
2080 -> Vec<PredicateObligation<'tcx>>
2082 debug!("confirm_param_candidate({:?},{:?})",
2086 // During evaluation, we already checked that this
2087 // where-clause trait-ref could be unified with the obligation
2088 // trait-ref. Repeat that unification now without any
2089 // transactional boundary; it should not fail.
2090 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2091 Ok(obligations) => obligations,
2093 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2100 fn confirm_builtin_candidate(&mut self,
2101 obligation: &TraitObligation<'tcx>,
2102 bound: ty::BuiltinBound)
2103 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2104 SelectionError<'tcx>>
2106 debug!("confirm_builtin_candidate({:?})",
2109 match self.builtin_bound(bound, obligation)? {
2110 If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)),
2111 AmbiguousBuiltin | ParameterBuiltin => {
2113 obligation.cause.span,
2114 "builtin bound for {:?} was ambig",
2120 fn vtable_builtin_data(&mut self,
2121 obligation: &TraitObligation<'tcx>,
2122 bound: ty::BuiltinBound,
2123 nested: ty::Binder<Vec<Ty<'tcx>>>)
2124 -> VtableBuiltinData<PredicateObligation<'tcx>>
2126 debug!("vtable_builtin_data(obligation={:?}, bound={:?}, nested={:?})",
2127 obligation, bound, nested);
2129 let trait_def = match self.tcx().lang_items.from_builtin_kind(bound) {
2130 Ok(def_id) => def_id,
2132 bug!("builtin trait definition not found");
2136 let obligations = self.collect_predicates_for_types(obligation, trait_def, nested);
2138 debug!("vtable_builtin_data: obligations={:?}",
2141 VtableBuiltinData { nested: obligations }
2144 /// This handles the case where a `impl Foo for ..` impl is being used.
2145 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2147 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2148 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2149 fn confirm_default_impl_candidate(&mut self,
2150 obligation: &TraitObligation<'tcx>,
2151 trait_def_id: DefId)
2152 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2154 debug!("confirm_default_impl_candidate({:?}, {:?})",
2158 // binder is moved below
2159 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2160 let types = self.constituent_types_for_ty(self_ty);
2161 self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2164 fn confirm_default_impl_object_candidate(&mut self,
2165 obligation: &TraitObligation<'tcx>,
2166 trait_def_id: DefId)
2167 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2169 debug!("confirm_default_impl_object_candidate({:?}, {:?})",
2173 assert!(self.tcx().has_attr(trait_def_id, "rustc_reflect_like"));
2175 // OK to skip binder, it is reintroduced below
2176 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2178 ty::TyTrait(ref data) => {
2179 // OK to skip the binder, it is reintroduced below
2180 let input_types = data.principal.skip_binder().substs.types.get_slice(TypeSpace);
2181 let assoc_types = data.bounds.projection_bounds
2183 .map(|pb| pb.skip_binder().ty);
2184 let all_types: Vec<_> = input_types.iter().cloned()
2188 // reintroduce the two binding levels we skipped, then flatten into one
2189 let all_types = ty::Binder(ty::Binder(all_types));
2190 let all_types = self.tcx().flatten_late_bound_regions(&all_types);
2192 self.vtable_default_impl(obligation, trait_def_id, all_types)
2195 bug!("asked to confirm default object implementation for non-object type: {:?}",
2201 /// See `confirm_default_impl_candidate`
2202 fn vtable_default_impl(&mut self,
2203 obligation: &TraitObligation<'tcx>,
2204 trait_def_id: DefId,
2205 nested: ty::Binder<Vec<Ty<'tcx>>>)
2206 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2208 debug!("vtable_default_impl_data: nested={:?}", nested);
2210 let mut obligations = self.collect_predicates_for_types(obligation,
2214 let trait_obligations: Result<Vec<_>,()> = self.infcx.commit_if_ok(|snapshot| {
2215 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2216 let (trait_ref, skol_map) =
2217 self.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2218 Ok(self.impl_or_trait_obligations(obligation.cause.clone(),
2219 obligation.recursion_depth + 1,
2226 // no Errors in that code above
2227 obligations.append(&mut trait_obligations.unwrap());
2229 debug!("vtable_default_impl_data: obligations={:?}", obligations);
2231 VtableDefaultImplData {
2232 trait_def_id: trait_def_id,
2237 fn confirm_impl_candidate(&mut self,
2238 obligation: &TraitObligation<'tcx>,
2240 -> Result<VtableImplData<'tcx, PredicateObligation<'tcx>>,
2241 SelectionError<'tcx>>
2243 debug!("confirm_impl_candidate({:?},{:?})",
2247 // First, create the substitutions by matching the impl again,
2248 // this time not in a probe.
2249 self.infcx.commit_if_ok(|snapshot| {
2250 let (substs, skol_map) =
2251 self.rematch_impl(impl_def_id, obligation,
2253 debug!("confirm_impl_candidate substs={:?}", substs);
2254 Ok(self.vtable_impl(impl_def_id, substs, obligation.cause.clone(),
2255 obligation.recursion_depth + 1, skol_map, snapshot))
2259 fn vtable_impl(&mut self,
2261 mut substs: Normalized<'tcx, Substs<'tcx>>,
2262 cause: ObligationCause<'tcx>,
2263 recursion_depth: usize,
2264 skol_map: infer::SkolemizationMap,
2265 snapshot: &infer::CombinedSnapshot)
2266 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2268 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2274 let mut impl_obligations =
2275 self.impl_or_trait_obligations(cause,
2282 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2286 // Because of RFC447, the impl-trait-ref and obligations
2287 // are sufficient to determine the impl substs, without
2288 // relying on projections in the impl-trait-ref.
2290 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2291 impl_obligations.append(&mut substs.obligations);
2293 VtableImplData { impl_def_id: impl_def_id,
2294 substs: self.tcx().mk_substs(substs.value),
2295 nested: impl_obligations }
2298 fn confirm_object_candidate(&mut self,
2299 obligation: &TraitObligation<'tcx>)
2300 -> VtableObjectData<'tcx>
2302 debug!("confirm_object_candidate({:?})",
2305 // FIXME skipping binder here seems wrong -- we should
2306 // probably flatten the binder from the obligation and the
2307 // binder from the object. Have to try to make a broken test
2308 // case that results. -nmatsakis
2309 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2310 let poly_trait_ref = match self_ty.sty {
2311 ty::TyTrait(ref data) => {
2312 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
2315 span_bug!(obligation.cause.span,
2316 "object candidate with non-object");
2320 let mut upcast_trait_ref = None;
2324 // We want to find the first supertrait in the list of
2325 // supertraits that we can unify with, and do that
2326 // unification. We know that there is exactly one in the list
2327 // where we can unify because otherwise select would have
2328 // reported an ambiguity. (When we do find a match, also
2329 // record it for later.)
2331 util::supertraits(self.tcx(), poly_trait_ref)
2334 self.infcx.commit_if_ok(
2335 |_| self.match_poly_trait_ref(obligation, t))
2337 Ok(_) => { upcast_trait_ref = Some(t); false }
2342 // Additionally, for each of the nonmatching predicates that
2343 // we pass over, we sum up the set of number of vtable
2344 // entries, so that we can compute the offset for the selected
2347 nonmatching.map(|t| util::count_own_vtable_entries(self.tcx(), t))
2353 upcast_trait_ref: upcast_trait_ref.unwrap(),
2354 vtable_base: vtable_base,
2358 fn confirm_fn_pointer_candidate(&mut self,
2359 obligation: &TraitObligation<'tcx>)
2360 -> Result<ty::Ty<'tcx>,SelectionError<'tcx>>
2362 debug!("confirm_fn_pointer_candidate({:?})",
2365 // ok to skip binder; it is reintroduced below
2366 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2367 let sig = self_ty.fn_sig();
2369 util::closure_trait_ref_and_return_type(self.tcx(),
2370 obligation.predicate.def_id(),
2373 util::TupleArgumentsFlag::Yes)
2374 .map_bound(|(trait_ref, _)| trait_ref);
2376 self.confirm_poly_trait_refs(obligation.cause.clone(),
2377 obligation.predicate.to_poly_trait_ref(),
2382 fn confirm_closure_candidate(&mut self,
2383 obligation: &TraitObligation<'tcx>,
2384 closure_def_id: DefId,
2385 substs: &ty::ClosureSubsts<'tcx>,
2386 kind: ty::ClosureKind)
2387 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2388 SelectionError<'tcx>>
2390 debug!("confirm_closure_candidate({:?},{:?},{:?})",
2398 } = self.closure_trait_ref(obligation, closure_def_id, substs);
2400 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2405 self.confirm_poly_trait_refs(obligation.cause.clone(),
2406 obligation.predicate.to_poly_trait_ref(),
2409 obligations.push(Obligation::new(
2410 obligation.cause.clone(),
2411 ty::Predicate::ClosureKind(closure_def_id, kind)));
2413 Ok(VtableClosureData {
2414 closure_def_id: closure_def_id,
2415 substs: substs.clone(),
2420 /// In the case of closure types and fn pointers,
2421 /// we currently treat the input type parameters on the trait as
2422 /// outputs. This means that when we have a match we have only
2423 /// considered the self type, so we have to go back and make sure
2424 /// to relate the argument types too. This is kind of wrong, but
2425 /// since we control the full set of impls, also not that wrong,
2426 /// and it DOES yield better error messages (since we don't report
2427 /// errors as if there is no applicable impl, but rather report
2428 /// errors are about mismatched argument types.
2430 /// Here is an example. Imagine we have a closure expression
2431 /// and we desugared it so that the type of the expression is
2432 /// `Closure`, and `Closure` expects an int as argument. Then it
2433 /// is "as if" the compiler generated this impl:
2435 /// impl Fn(int) for Closure { ... }
2437 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2438 /// we have matched the self-type `Closure`. At this point we'll
2439 /// compare the `int` to `usize` and generate an error.
2441 /// Note that this checking occurs *after* the impl has selected,
2442 /// because these output type parameters should not affect the
2443 /// selection of the impl. Therefore, if there is a mismatch, we
2444 /// report an error to the user.
2445 fn confirm_poly_trait_refs(&mut self,
2446 obligation_cause: ObligationCause,
2447 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2448 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2449 -> Result<(), SelectionError<'tcx>>
2451 let origin = TypeOrigin::RelateOutputImplTypes(obligation_cause.span);
2453 let obligation_trait_ref = obligation_trait_ref.clone();
2454 self.infcx.sub_poly_trait_refs(false,
2456 expected_trait_ref.clone(),
2457 obligation_trait_ref.clone())
2458 // FIXME(#32730) propagate obligations
2459 .map(|InferOk { obligations, .. }| assert!(obligations.is_empty()))
2460 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2463 fn confirm_builtin_unsize_candidate(&mut self,
2464 obligation: &TraitObligation<'tcx>,)
2465 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2466 SelectionError<'tcx>> {
2467 let tcx = self.tcx();
2469 // assemble_candidates_for_unsizing should ensure there are no late bound
2470 // regions here. See the comment there for more details.
2471 let source = self.infcx.shallow_resolve(
2472 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2473 let target = self.infcx.shallow_resolve(obligation.predicate.0.input_types()[0]);
2475 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2478 let mut nested = vec![];
2479 match (&source.sty, &target.sty) {
2480 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2481 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
2482 // See assemble_candidates_for_unsizing for more info.
2483 let bounds = ty::ExistentialBounds {
2484 region_bound: data_b.bounds.region_bound,
2485 builtin_bounds: data_b.bounds.builtin_bounds,
2486 projection_bounds: data_a.bounds.projection_bounds.clone(),
2489 let new_trait = tcx.mk_trait(data_a.principal.clone(), bounds);
2490 let origin = TypeOrigin::Misc(obligation.cause.span);
2491 let InferOk { obligations, .. } =
2492 self.infcx.sub_types(false, origin, new_trait, target)
2493 .map_err(|_| Unimplemented)?;
2494 // FIXME(#32730) propagate obligations
2495 assert!(obligations.is_empty());
2497 // Register one obligation for 'a: 'b.
2498 let cause = ObligationCause::new(obligation.cause.span,
2499 obligation.cause.body_id,
2500 ObjectCastObligation(target));
2501 let outlives = ty::OutlivesPredicate(data_a.bounds.region_bound,
2502 data_b.bounds.region_bound);
2503 nested.push(Obligation::with_depth(cause,
2504 obligation.recursion_depth + 1,
2505 ty::Binder(outlives).to_predicate()));
2509 (_, &ty::TyTrait(ref data)) => {
2510 let object_did = data.principal_def_id();
2511 if !object_safety::is_object_safe(tcx, object_did) {
2512 return Err(TraitNotObjectSafe(object_did));
2515 let cause = ObligationCause::new(obligation.cause.span,
2516 obligation.cause.body_id,
2517 ObjectCastObligation(target));
2518 let mut push = |predicate| {
2519 nested.push(Obligation::with_depth(cause.clone(),
2520 obligation.recursion_depth + 1,
2524 // Create the obligation for casting from T to Trait.
2525 push(data.principal_trait_ref_with_self_ty(tcx, source).to_predicate());
2527 // We can only make objects from sized types.
2528 let mut builtin_bounds = data.bounds.builtin_bounds;
2529 builtin_bounds.insert(ty::BoundSized);
2531 // Create additional obligations for all the various builtin
2532 // bounds attached to the object cast. (In other words, if the
2533 // object type is Foo+Send, this would create an obligation
2534 // for the Send check.)
2535 for bound in &builtin_bounds {
2536 if let Ok(tr) = util::trait_ref_for_builtin_bound(tcx, bound, source) {
2537 push(tr.to_predicate());
2539 return Err(Unimplemented);
2543 // Create obligations for the projection predicates.
2544 for bound in data.projection_bounds_with_self_ty(tcx, source) {
2545 push(bound.to_predicate());
2548 // If the type is `Foo+'a`, ensures that the type
2549 // being cast to `Foo+'a` outlives `'a`:
2550 let outlives = ty::OutlivesPredicate(source,
2551 data.bounds.region_bound);
2552 push(ty::Binder(outlives).to_predicate());
2556 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2557 let origin = TypeOrigin::Misc(obligation.cause.span);
2558 let InferOk { obligations, .. } =
2559 self.infcx.sub_types(false, origin, a, b)
2560 .map_err(|_| Unimplemented)?;
2561 // FIXME(#32730) propagate obligations
2562 assert!(obligations.is_empty());
2565 // Struct<T> -> Struct<U>.
2566 (&ty::TyStruct(def, substs_a), &ty::TyStruct(_, substs_b)) => {
2569 .map(|f| f.unsubst_ty())
2570 .collect::<Vec<_>>();
2572 // The last field of the structure has to exist and contain type parameters.
2573 let field = if let Some(&field) = fields.last() {
2576 return Err(Unimplemented);
2578 let mut ty_params = vec![];
2579 for ty in field.walk() {
2580 if let ty::TyParam(p) = ty.sty {
2581 assert!(p.space == TypeSpace);
2582 let idx = p.idx as usize;
2583 if !ty_params.contains(&idx) {
2584 ty_params.push(idx);
2588 if ty_params.is_empty() {
2589 return Err(Unimplemented);
2592 // Replace type parameters used in unsizing with
2593 // TyError and ensure they do not affect any other fields.
2594 // This could be checked after type collection for any struct
2595 // with a potentially unsized trailing field.
2596 let mut new_substs = substs_a.clone();
2597 for &i in &ty_params {
2598 new_substs.types.get_mut_slice(TypeSpace)[i] = tcx.types.err;
2600 for &ty in fields.split_last().unwrap().1 {
2601 if ty.subst(tcx, &new_substs).references_error() {
2602 return Err(Unimplemented);
2606 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2607 let inner_source = field.subst(tcx, substs_a);
2608 let inner_target = field.subst(tcx, substs_b);
2610 // Check that the source structure with the target's
2611 // type parameters is a subtype of the target.
2612 for &i in &ty_params {
2613 let param_b = *substs_b.types.get(TypeSpace, i);
2614 new_substs.types.get_mut_slice(TypeSpace)[i] = param_b;
2616 let new_struct = tcx.mk_struct(def, tcx.mk_substs(new_substs));
2617 let origin = TypeOrigin::Misc(obligation.cause.span);
2618 let InferOk { obligations, .. } =
2619 self.infcx.sub_types(false, origin, new_struct, target)
2620 .map_err(|_| Unimplemented)?;
2621 // FIXME(#32730) propagate obligations
2622 assert!(obligations.is_empty());
2624 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2625 nested.push(util::predicate_for_trait_def(tcx,
2626 obligation.cause.clone(),
2627 obligation.predicate.def_id(),
2628 obligation.recursion_depth + 1,
2630 vec![inner_target]));
2636 Ok(VtableBuiltinData { nested: nested })
2639 ///////////////////////////////////////////////////////////////////////////
2642 // Matching is a common path used for both evaluation and
2643 // confirmation. It basically unifies types that appear in impls
2644 // and traits. This does affect the surrounding environment;
2645 // therefore, when used during evaluation, match routines must be
2646 // run inside of a `probe()` so that their side-effects are
2649 fn rematch_impl(&mut self,
2651 obligation: &TraitObligation<'tcx>,
2652 snapshot: &infer::CombinedSnapshot)
2653 -> (Normalized<'tcx, Substs<'tcx>>, infer::SkolemizationMap)
2655 match self.match_impl(impl_def_id, obligation, snapshot) {
2656 Ok((substs, skol_map)) => (substs, skol_map),
2658 bug!("Impl {:?} was matchable against {:?} but now is not",
2665 fn match_impl(&mut self,
2667 obligation: &TraitObligation<'tcx>,
2668 snapshot: &infer::CombinedSnapshot)
2669 -> Result<(Normalized<'tcx, Substs<'tcx>>,
2670 infer::SkolemizationMap), ()>
2672 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2674 // Before we create the substitutions and everything, first
2675 // consider a "quick reject". This avoids creating more types
2676 // and so forth that we need to.
2677 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2681 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2682 &obligation.predicate,
2684 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2686 let impl_substs = util::fresh_type_vars_for_impl(self.infcx,
2687 obligation.cause.span,
2690 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2693 let impl_trait_ref =
2694 project::normalize_with_depth(self,
2695 obligation.cause.clone(),
2696 obligation.recursion_depth + 1,
2699 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2700 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2704 skol_obligation_trait_ref);
2706 let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
2707 let InferOk { obligations, .. } =
2708 self.infcx.eq_trait_refs(false,
2710 impl_trait_ref.value.clone(),
2711 skol_obligation_trait_ref)
2713 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2716 // FIXME(#32730) propagate obligations
2717 assert!(obligations.is_empty());
2719 if let Err(e) = self.infcx.leak_check(&skol_map, snapshot) {
2720 debug!("match_impl: failed leak check due to `{}`", e);
2724 debug!("match_impl: success impl_substs={:?}", impl_substs);
2727 obligations: impl_trait_ref.obligations
2731 fn fast_reject_trait_refs(&mut self,
2732 obligation: &TraitObligation,
2733 impl_trait_ref: &ty::TraitRef)
2736 // We can avoid creating type variables and doing the full
2737 // substitution if we find that any of the input types, when
2738 // simplified, do not match.
2740 obligation.predicate.0.input_types().iter()
2741 .zip(impl_trait_ref.input_types())
2742 .any(|(&obligation_ty, &impl_ty)| {
2743 let simplified_obligation_ty =
2744 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2745 let simplified_impl_ty =
2746 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2748 simplified_obligation_ty.is_some() &&
2749 simplified_impl_ty.is_some() &&
2750 simplified_obligation_ty != simplified_impl_ty
2754 /// Normalize `where_clause_trait_ref` and try to match it against
2755 /// `obligation`. If successful, return any predicates that
2756 /// result from the normalization. Normalization is necessary
2757 /// because where-clauses are stored in the parameter environment
2759 fn match_where_clause_trait_ref(&mut self,
2760 obligation: &TraitObligation<'tcx>,
2761 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2762 -> Result<Vec<PredicateObligation<'tcx>>,()>
2764 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
2768 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2769 /// obligation is satisfied.
2770 fn match_poly_trait_ref(&self,
2771 obligation: &TraitObligation<'tcx>,
2772 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2775 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2779 let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
2780 self.infcx.sub_poly_trait_refs(false,
2783 obligation.predicate.to_poly_trait_ref())
2784 // FIXME(#32730) propagate obligations
2785 .map(|InferOk { obligations, .. }| assert!(obligations.is_empty()))
2789 ///////////////////////////////////////////////////////////////////////////
2792 fn match_fresh_trait_refs(&self,
2793 previous: &ty::PolyTraitRef<'tcx>,
2794 current: &ty::PolyTraitRef<'tcx>)
2797 let mut matcher = ty::_match::Match::new(self.tcx());
2798 matcher.relate(previous, current).is_ok()
2801 fn push_stack<'o,'s:'o>(&mut self,
2802 previous_stack: TraitObligationStackList<'s, 'tcx>,
2803 obligation: &'o TraitObligation<'tcx>)
2804 -> TraitObligationStack<'o, 'tcx>
2806 let fresh_trait_ref =
2807 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2809 TraitObligationStack {
2810 obligation: obligation,
2811 fresh_trait_ref: fresh_trait_ref,
2812 previous: previous_stack,
2816 fn closure_trait_ref_unnormalized(&mut self,
2817 obligation: &TraitObligation<'tcx>,
2818 closure_def_id: DefId,
2819 substs: &ty::ClosureSubsts<'tcx>)
2820 -> ty::PolyTraitRef<'tcx>
2822 let closure_type = self.infcx.closure_type(closure_def_id, substs);
2823 let ty::Binder((trait_ref, _)) =
2824 util::closure_trait_ref_and_return_type(self.tcx(),
2825 obligation.predicate.def_id(),
2826 obligation.predicate.0.self_ty(), // (1)
2828 util::TupleArgumentsFlag::No);
2829 // (1) Feels icky to skip the binder here, but OTOH we know
2830 // that the self-type is an unboxed closure type and hence is
2831 // in fact unparameterized (or at least does not reference any
2832 // regions bound in the obligation). Still probably some
2833 // refactoring could make this nicer.
2835 ty::Binder(trait_ref)
2838 fn closure_trait_ref(&mut self,
2839 obligation: &TraitObligation<'tcx>,
2840 closure_def_id: DefId,
2841 substs: &ty::ClosureSubsts<'tcx>)
2842 -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
2844 let trait_ref = self.closure_trait_ref_unnormalized(
2845 obligation, closure_def_id, substs);
2847 // A closure signature can contain associated types which
2848 // must be normalized.
2849 normalize_with_depth(self,
2850 obligation.cause.clone(),
2851 obligation.recursion_depth+1,
2855 /// Returns the obligations that are implied by instantiating an
2856 /// impl or trait. The obligations are substituted and fully
2857 /// normalized. This is used when confirming an impl or default
2859 fn impl_or_trait_obligations(&mut self,
2860 cause: ObligationCause<'tcx>,
2861 recursion_depth: usize,
2862 def_id: DefId, // of impl or trait
2863 substs: &Substs<'tcx>, // for impl or trait
2864 skol_map: infer::SkolemizationMap,
2865 snapshot: &infer::CombinedSnapshot)
2866 -> Vec<PredicateObligation<'tcx>>
2868 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2869 let tcx = self.tcx();
2871 // To allow for one-pass evaluation of the nested obligation,
2872 // each predicate must be preceded by the obligations required
2874 // for example, if we have:
2875 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2876 // the impl will have the following predicates:
2877 // <V as Iterator>::Item = U,
2878 // U: Iterator, U: Sized,
2879 // V: Iterator, V: Sized,
2880 // <U as Iterator>::Item: Copy
2881 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2882 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2883 // `$1: Copy`, so we must ensure the obligations are emitted in
2885 let predicates = tcx
2886 .lookup_predicates(def_id)
2888 .flat_map(|predicate| {
2890 normalize_with_depth(self, cause.clone(), recursion_depth,
2891 &predicate.subst(tcx, substs));
2892 predicate.obligations.into_iter().chain(
2894 cause: cause.clone(),
2895 recursion_depth: recursion_depth,
2896 predicate: predicate.value
2899 self.infcx().plug_leaks(skol_map, snapshot, &predicates)
2902 #[allow(unused_comparisons)]
2903 fn derived_cause(&self,
2904 obligation: &TraitObligation<'tcx>,
2905 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2906 -> ObligationCause<'tcx>
2909 * Creates a cause for obligations that are derived from
2910 * `obligation` by a recursive search (e.g., for a builtin
2911 * bound, or eventually a `impl Foo for ..`). If `obligation`
2912 * is itself a derived obligation, this is just a clone, but
2913 * otherwise we create a "derived obligation" cause so as to
2914 * keep track of the original root obligation for error
2918 // NOTE(flaper87): As of now, it keeps track of the whole error
2919 // chain. Ideally, we should have a way to configure this either
2920 // by using -Z verbose or just a CLI argument.
2921 if obligation.recursion_depth >= 0 {
2922 let derived_cause = DerivedObligationCause {
2923 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2924 parent_code: Rc::new(obligation.cause.code.clone())
2926 let derived_code = variant(derived_cause);
2927 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2929 obligation.cause.clone()
2934 impl<'tcx> SelectionCache<'tcx> {
2935 pub fn new() -> SelectionCache<'tcx> {
2937 hashmap: RefCell::new(FnvHashMap())
2942 impl<'tcx> EvaluationCache<'tcx> {
2943 pub fn new() -> EvaluationCache<'tcx> {
2945 hashmap: RefCell::new(FnvHashMap())
2950 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
2951 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
2952 TraitObligationStackList::with(self)
2955 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
2960 #[derive(Copy, Clone)]
2961 struct TraitObligationStackList<'o,'tcx:'o> {
2962 head: Option<&'o TraitObligationStack<'o,'tcx>>
2965 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
2966 fn empty() -> TraitObligationStackList<'o,'tcx> {
2967 TraitObligationStackList { head: None }
2970 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
2971 TraitObligationStackList { head: Some(r) }
2975 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
2976 type Item = &'o TraitObligationStack<'o,'tcx>;
2978 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
2989 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
2990 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2991 write!(f, "TraitObligationStack({:?})", self.obligation)
2995 impl EvaluationResult {
2996 fn may_apply(&self) -> bool {
3000 EvaluatedToUnknown => true,
3002 EvaluatedToErr => false
3007 impl MethodMatchResult {
3008 pub fn may_apply(&self) -> bool {
3010 MethodMatched(_) => true,
3011 MethodAmbiguous(_) => true,
3012 MethodDidNotMatch => false,