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 use self::SelectionCandidate::*;
14 use self::EvaluationResult::*;
17 use super::DerivedObligationCause;
19 use super::project::{normalize_with_depth, Normalized};
20 use super::{PredicateObligation, TraitObligation, ObligationCause};
21 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
22 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
23 use super::{ObjectCastObligation, Obligation};
25 use super::TraitNotObjectSafe;
27 use super::SelectionResult;
28 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure,
29 VtableFnPointer, VtableObject, VtableDefaultImpl};
30 use super::{VtableImplData, VtableObjectData, VtableBuiltinData,
31 VtableClosureData, VtableDefaultImplData, VtableFnPointerData};
34 use hir::def_id::DefId;
36 use infer::{InferCtxt, InferOk, TypeFreshener};
37 use ty::subst::{Kind, Subst, Substs};
38 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
41 use ty::relate::TypeRelation;
42 use middle::lang_items;
44 use rustc_data_structures::bitvec::BitVector;
45 use rustc_data_structures::snapshot_vec::{SnapshotVecDelegate, SnapshotVec};
46 use std::cell::RefCell;
48 use std::marker::PhantomData;
54 use util::nodemap::FxHashMap;
56 struct InferredObligationsSnapshotVecDelegate<'tcx> {
57 phantom: PhantomData<&'tcx i32>,
59 impl<'tcx> SnapshotVecDelegate for InferredObligationsSnapshotVecDelegate<'tcx> {
60 type Value = PredicateObligation<'tcx>;
62 fn reverse(_: &mut Vec<Self::Value>, _: Self::Undo) {}
65 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
66 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
68 /// Freshener used specifically for skolemizing entries on the
69 /// obligation stack. This ensures that all entries on the stack
70 /// at one time will have the same set of skolemized entries,
71 /// which is important for checking for trait bounds that
72 /// recursively require themselves.
73 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
75 /// If true, indicates that the evaluation should be conservative
76 /// and consider the possibility of types outside this crate.
77 /// This comes up primarily when resolving ambiguity. Imagine
78 /// there is some trait reference `$0 : Bar` where `$0` is an
79 /// inference variable. If `intercrate` is true, then we can never
80 /// say for sure that this reference is not implemented, even if
81 /// there are *no impls at all for `Bar`*, because `$0` could be
82 /// bound to some type that in a downstream crate that implements
83 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
84 /// though, we set this to false, because we are only interested
85 /// in types that the user could actually have written --- in
86 /// other words, we consider `$0 : Bar` to be unimplemented if
87 /// there is no type that the user could *actually name* that
88 /// would satisfy it. This avoids crippling inference, basically.
91 inferred_obligations: SnapshotVec<InferredObligationsSnapshotVecDelegate<'tcx>>,
94 // A stack that walks back up the stack frame.
95 struct TraitObligationStack<'prev, 'tcx: 'prev> {
96 obligation: &'prev TraitObligation<'tcx>,
98 /// Trait ref from `obligation` but skolemized with the
99 /// selection-context's freshener. Used to check for recursion.
100 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
102 previous: TraitObligationStackList<'prev, 'tcx>,
106 pub struct SelectionCache<'tcx> {
107 hashmap: RefCell<FxHashMap<ty::TraitRef<'tcx>,
108 SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
111 /// The selection process begins by considering all impls, where
112 /// clauses, and so forth that might resolve an obligation. Sometimes
113 /// we'll be able to say definitively that (e.g.) an impl does not
114 /// apply to the obligation: perhaps it is defined for `usize` but the
115 /// obligation is for `int`. In that case, we drop the impl out of the
116 /// list. But the other cases are considered *candidates*.
118 /// For selection to succeed, there must be exactly one matching
119 /// candidate. If the obligation is fully known, this is guaranteed
120 /// by coherence. However, if the obligation contains type parameters
121 /// or variables, there may be multiple such impls.
123 /// It is not a real problem if multiple matching impls exist because
124 /// of type variables - it just means the obligation isn't sufficiently
125 /// elaborated. In that case we report an ambiguity, and the caller can
126 /// try again after more type information has been gathered or report a
127 /// "type annotations required" error.
129 /// However, with type parameters, this can be a real problem - type
130 /// parameters don't unify with regular types, but they *can* unify
131 /// with variables from blanket impls, and (unless we know its bounds
132 /// will always be satisfied) picking the blanket impl will be wrong
133 /// for at least *some* substitutions. To make this concrete, if we have
135 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
136 /// impl<T: fmt::Debug> AsDebug for T {
138 /// fn debug(self) -> fmt::Debug { self }
140 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
142 /// we can't just use the impl to resolve the <T as AsDebug> obligation
143 /// - a type from another crate (that doesn't implement fmt::Debug) could
144 /// implement AsDebug.
146 /// Because where-clauses match the type exactly, multiple clauses can
147 /// only match if there are unresolved variables, and we can mostly just
148 /// report this ambiguity in that case. This is still a problem - we can't
149 /// *do anything* with ambiguities that involve only regions. This is issue
152 /// If a single where-clause matches and there are no inference
153 /// variables left, then it definitely matches and we can just select
156 /// In fact, we even select the where-clause when the obligation contains
157 /// inference variables. The can lead to inference making "leaps of logic",
158 /// for example in this situation:
160 /// pub trait Foo<T> { fn foo(&self) -> T; }
161 /// impl<T> Foo<()> for T { fn foo(&self) { } }
162 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
164 /// pub fn foo<T>(t: T) where T: Foo<bool> {
165 /// println!("{:?}", <T as Foo<_>>::foo(&t));
167 /// fn main() { foo(false); }
169 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
170 /// impl and the where-clause. We select the where-clause and unify $0=bool,
171 /// so the program prints "false". However, if the where-clause is omitted,
172 /// the blanket impl is selected, we unify $0=(), and the program prints
175 /// Exactly the same issues apply to projection and object candidates, except
176 /// that we can have both a projection candidate and a where-clause candidate
177 /// for the same obligation. In that case either would do (except that
178 /// different "leaps of logic" would occur if inference variables are
179 /// present), and we just pick the where-clause. This is, for example,
180 /// required for associated types to work in default impls, as the bounds
181 /// are visible both as projection bounds and as where-clauses from the
182 /// parameter environment.
183 #[derive(PartialEq,Eq,Debug,Clone)]
184 enum SelectionCandidate<'tcx> {
185 BuiltinCandidate { has_nested: bool },
186 ParamCandidate(ty::PolyTraitRef<'tcx>),
187 ImplCandidate(DefId),
188 DefaultImplCandidate(DefId),
190 /// This is a trait matching with a projected type as `Self`, and
191 /// we found an applicable bound in the trait definition.
194 /// Implementation of a `Fn`-family trait by one of the anonymous types
195 /// generated for a `||` expression. The ty::ClosureKind informs the
196 /// confirmation step what ClosureKind obligation to emit.
197 ClosureCandidate(/* closure */ DefId, ty::ClosureSubsts<'tcx>, ty::ClosureKind),
199 /// Implementation of a `Fn`-family trait by one of the anonymous
200 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
205 BuiltinObjectCandidate,
207 BuiltinUnsizeCandidate,
210 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
211 type Lifted = SelectionCandidate<'tcx>;
212 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
214 BuiltinCandidate { has_nested } => {
216 has_nested: has_nested
219 ImplCandidate(def_id) => ImplCandidate(def_id),
220 DefaultImplCandidate(def_id) => DefaultImplCandidate(def_id),
221 ProjectionCandidate => ProjectionCandidate,
222 FnPointerCandidate => FnPointerCandidate,
223 ObjectCandidate => ObjectCandidate,
224 BuiltinObjectCandidate => BuiltinObjectCandidate,
225 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
227 ParamCandidate(ref trait_ref) => {
228 return tcx.lift(trait_ref).map(ParamCandidate);
230 ClosureCandidate(def_id, ref substs, kind) => {
231 return tcx.lift(substs).map(|substs| {
232 ClosureCandidate(def_id, substs, kind)
239 struct SelectionCandidateSet<'tcx> {
240 // a list of candidates that definitely apply to the current
241 // obligation (meaning: types unify).
242 vec: Vec<SelectionCandidate<'tcx>>,
244 // if this is true, then there were candidates that might or might
245 // not have applied, but we couldn't tell. This occurs when some
246 // of the input types are type variables, in which case there are
247 // various "builtin" rules that might or might not trigger.
251 #[derive(PartialEq,Eq,Debug,Clone)]
252 struct EvaluatedCandidate<'tcx> {
253 candidate: SelectionCandidate<'tcx>,
254 evaluation: EvaluationResult,
257 /// When does the builtin impl for `T: Trait` apply?
258 enum BuiltinImplConditions<'tcx> {
259 /// The impl is conditional on T1,T2,.. : Trait
260 Where(ty::Binder<Vec<Ty<'tcx>>>),
261 /// There is no built-in impl. There may be some other
262 /// candidate (a where-clause or user-defined impl).
264 /// There is *no* impl for this, builtin or not. Ignore
265 /// all where-clauses.
267 /// It is unknown whether there is an impl.
271 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
272 /// The result of trait evaluation. The order is important
273 /// here as the evaluation of a list is the maximum of the
275 enum EvaluationResult {
276 /// Evaluation successful
278 /// Evaluation failed because of recursion - treated as ambiguous
280 /// Evaluation is known to be ambiguous
282 /// Evaluation failed
287 pub struct EvaluationCache<'tcx> {
288 hashmap: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, EvaluationResult>>
291 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
292 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
295 freshener: infcx.freshener(),
297 inferred_obligations: SnapshotVec::new(),
301 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
304 freshener: infcx.freshener(),
306 inferred_obligations: SnapshotVec::new(),
310 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
314 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
318 pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'gcx> {
319 self.infcx.param_env()
322 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
326 pub fn projection_mode(&self) -> Reveal {
327 self.infcx.projection_mode()
330 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
332 fn in_snapshot<R, F>(&mut self, f: F) -> R
333 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
335 // The irrefutable nature of the operation means we don't need to snapshot the
336 // inferred_obligations vector.
337 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
340 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
342 fn probe<R, F>(&mut self, f: F) -> R
343 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
345 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
346 let result = self.infcx.probe(|snapshot| f(self, snapshot));
347 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
351 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
352 /// the transaction fails and s.t. old obligations are retained.
353 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
354 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
356 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
357 match self.infcx.commit_if_ok(|snapshot| f(self, snapshot)) {
359 self.inferred_obligations.commit(inferred_obligations_snapshot);
363 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
370 ///////////////////////////////////////////////////////////////////////////
373 // The selection phase tries to identify *how* an obligation will
374 // be resolved. For example, it will identify which impl or
375 // parameter bound is to be used. The process can be inconclusive
376 // if the self type in the obligation is not fully inferred. Selection
377 // can result in an error in one of two ways:
379 // 1. If no applicable impl or parameter bound can be found.
380 // 2. If the output type parameters in the obligation do not match
381 // those specified by the impl/bound. For example, if the obligation
382 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
383 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
385 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
386 /// type environment by performing unification.
387 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
388 -> SelectionResult<'tcx, Selection<'tcx>> {
389 debug!("select({:?})", obligation);
390 assert!(!obligation.predicate.has_escaping_regions());
392 let tcx = self.tcx();
393 let dep_node = obligation.predicate.dep_node();
394 let _task = tcx.dep_graph.in_task(dep_node);
396 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
397 let ret = match self.candidate_from_obligation(&stack)? {
400 let mut candidate = self.confirm_candidate(obligation, candidate)?;
401 let inferred_obligations = (*self.inferred_obligations).into_iter().cloned();
402 candidate.nested_obligations_mut().extend(inferred_obligations);
407 // Test whether this is a `()` which was produced by defaulting a
408 // diverging type variable with `!` disabled. If so, we may need
409 // to raise a warning.
410 if obligation.predicate.skip_binder().self_ty().is_defaulted_unit() {
411 let mut raise_warning = true;
412 // Don't raise a warning if the trait is implemented for ! and only
413 // permits a trivial implementation for !. This stops us warning
414 // about (for example) `(): Clone` becoming `!: Clone` because such
415 // a switch can't cause code to stop compiling or execute
417 let mut never_obligation = obligation.clone();
418 let def_id = never_obligation.predicate.skip_binder().trait_ref.def_id;
419 never_obligation.predicate = never_obligation.predicate.map_bound(|mut trait_pred| {
420 // Swap out () with ! so we can check if the trait is impld for !
422 let mut trait_ref = &mut trait_pred.trait_ref;
423 let unit_substs = trait_ref.substs;
424 let mut never_substs = Vec::with_capacity(unit_substs.len());
425 never_substs.push(From::from(tcx.types.never));
426 never_substs.extend(&unit_substs[1..]);
427 trait_ref.substs = tcx.intern_substs(&never_substs);
431 if let Ok(Some(..)) = self.select(&never_obligation) {
432 if !tcx.trait_relevant_for_never(def_id) {
433 // The trait is also implemented for ! and the resulting
434 // implementation cannot actually be invoked in any way.
435 raise_warning = false;
440 tcx.sess.add_lint(lint::builtin::RESOLVE_TRAIT_ON_DEFAULTED_UNIT,
441 obligation.cause.body_id,
442 obligation.cause.span,
443 format!("code relies on type inference rules which are likely \
450 ///////////////////////////////////////////////////////////////////////////
453 // Tests whether an obligation can be selected or whether an impl
454 // can be applied to particular types. It skips the "confirmation"
455 // step and hence completely ignores output type parameters.
457 // The result is "true" if the obligation *may* hold and "false" if
458 // we can be sure it does not.
460 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
461 pub fn evaluate_obligation(&mut self,
462 obligation: &PredicateObligation<'tcx>)
465 debug!("evaluate_obligation({:?})",
468 self.probe(|this, _| {
469 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
474 /// Evaluates whether the obligation `obligation` can be satisfied,
475 /// and returns `false` if not certain. However, this is not entirely
476 /// accurate if inference variables are involved.
477 pub fn evaluate_obligation_conservatively(&mut self,
478 obligation: &PredicateObligation<'tcx>)
481 debug!("evaluate_obligation_conservatively({:?})",
484 self.probe(|this, _| {
485 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
490 /// Evaluates the predicates in `predicates` recursively. Note that
491 /// this applies projections in the predicates, and therefore
492 /// is run within an inference probe.
493 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
494 stack: TraitObligationStackList<'o, 'tcx>,
497 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
499 let mut result = EvaluatedToOk;
500 for obligation in predicates {
501 let eval = self.evaluate_predicate_recursively(stack, obligation);
502 debug!("evaluate_predicate_recursively({:?}) = {:?}",
505 EvaluatedToErr => { return EvaluatedToErr; }
506 EvaluatedToAmbig => { result = EvaluatedToAmbig; }
507 EvaluatedToUnknown => {
508 if result < EvaluatedToUnknown {
509 result = EvaluatedToUnknown;
518 fn evaluate_predicate_recursively<'o>(&mut self,
519 previous_stack: TraitObligationStackList<'o, 'tcx>,
520 obligation: &PredicateObligation<'tcx>)
523 debug!("evaluate_predicate_recursively({:?})",
526 // Check the cache from the tcx of predicates that we know
527 // have been proven elsewhere. This cache only contains
528 // predicates that are global in scope and hence unaffected by
529 // the current environment.
530 if self.tcx().fulfilled_predicates.borrow().check_duplicate(&obligation.predicate) {
531 return EvaluatedToOk;
534 match obligation.predicate {
535 ty::Predicate::Trait(ref t) => {
536 assert!(!t.has_escaping_regions());
537 let obligation = obligation.with(t.clone());
538 self.evaluate_obligation_recursively(previous_stack, &obligation)
541 ty::Predicate::Equate(ref p) => {
542 // does this code ever run?
543 match self.infcx.equality_predicate(&obligation.cause, p) {
544 Ok(InferOk { obligations, .. }) => {
545 self.inferred_obligations.extend(obligations);
548 Err(_) => EvaluatedToErr
552 ty::Predicate::Subtype(ref p) => {
553 // does this code ever run?
554 match self.infcx.subtype_predicate(&obligation.cause, p) {
555 Some(Ok(InferOk { obligations, .. })) => {
556 self.inferred_obligations.extend(obligations);
559 Some(Err(_)) => EvaluatedToErr,
560 None => EvaluatedToAmbig,
564 ty::Predicate::WellFormed(ty) => {
565 match ty::wf::obligations(self.infcx, obligation.cause.body_id,
566 ty, obligation.cause.span) {
568 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
574 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
575 // we do not consider region relationships when
576 // evaluating trait matches
580 ty::Predicate::ObjectSafe(trait_def_id) => {
581 if self.tcx().is_object_safe(trait_def_id) {
588 ty::Predicate::Projection(ref data) => {
589 let project_obligation = obligation.with(data.clone());
590 match project::poly_project_and_unify_type(self, &project_obligation) {
591 Ok(Some(subobligations)) => {
592 self.evaluate_predicates_recursively(previous_stack,
593 subobligations.iter())
604 ty::Predicate::ClosureKind(closure_def_id, kind) => {
605 match self.infcx.closure_kind(closure_def_id) {
606 Some(closure_kind) => {
607 if closure_kind.extends(kind) {
621 fn evaluate_obligation_recursively<'o>(&mut self,
622 previous_stack: TraitObligationStackList<'o, 'tcx>,
623 obligation: &TraitObligation<'tcx>)
626 debug!("evaluate_obligation_recursively({:?})",
629 let stack = self.push_stack(previous_stack, obligation);
630 let fresh_trait_ref = stack.fresh_trait_ref;
631 if let Some(result) = self.check_evaluation_cache(fresh_trait_ref) {
632 debug!("CACHE HIT: EVAL({:?})={:?}",
638 let result = self.evaluate_stack(&stack);
640 debug!("CACHE MISS: EVAL({:?})={:?}",
643 self.insert_evaluation_cache(fresh_trait_ref, result);
648 fn evaluate_stack<'o>(&mut self,
649 stack: &TraitObligationStack<'o, 'tcx>)
652 // In intercrate mode, whenever any of the types are unbound,
653 // there can always be an impl. Even if there are no impls in
654 // this crate, perhaps the type would be unified with
655 // something from another crate that does provide an impl.
657 // In intra mode, we must still be conservative. The reason is
658 // that we want to avoid cycles. Imagine an impl like:
660 // impl<T:Eq> Eq for Vec<T>
662 // and a trait reference like `$0 : Eq` where `$0` is an
663 // unbound variable. When we evaluate this trait-reference, we
664 // will unify `$0` with `Vec<$1>` (for some fresh variable
665 // `$1`), on the condition that `$1 : Eq`. We will then wind
666 // up with many candidates (since that are other `Eq` impls
667 // that apply) and try to winnow things down. This results in
668 // a recursive evaluation that `$1 : Eq` -- as you can
669 // imagine, this is just where we started. To avoid that, we
670 // check for unbound variables and return an ambiguous (hence possible)
671 // match if we've seen this trait before.
673 // This suffices to allow chains like `FnMut` implemented in
674 // terms of `Fn` etc, but we could probably make this more
676 let unbound_input_types = stack.fresh_trait_ref.input_types().any(|ty| ty.is_fresh());
677 if unbound_input_types && self.intercrate {
678 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
679 stack.fresh_trait_ref);
680 return EvaluatedToAmbig;
682 if unbound_input_types &&
683 stack.iter().skip(1).any(
684 |prev| self.match_fresh_trait_refs(&stack.fresh_trait_ref,
685 &prev.fresh_trait_ref))
687 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
688 stack.fresh_trait_ref);
689 return EvaluatedToUnknown;
692 // If there is any previous entry on the stack that precisely
693 // matches this obligation, then we can assume that the
694 // obligation is satisfied for now (still all other conditions
695 // must be met of course). One obvious case this comes up is
696 // marker traits like `Send`. Think of a linked list:
698 // struct List<T> { data: T, next: Option<Box<List<T>>> {
700 // `Box<List<T>>` will be `Send` if `T` is `Send` and
701 // `Option<Box<List<T>>>` is `Send`, and in turn
702 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
705 // Note that we do this comparison using the `fresh_trait_ref`
706 // fields. Because these have all been skolemized using
707 // `self.freshener`, we can be sure that (a) this will not
708 // affect the inferencer state and (b) that if we see two
709 // skolemized types with the same index, they refer to the
710 // same unbound type variable.
713 .skip(1) // skip top-most frame
714 .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref)
716 debug!("evaluate_stack({:?}) --> recursive",
717 stack.fresh_trait_ref);
718 return EvaluatedToOk;
721 match self.candidate_from_obligation(stack) {
722 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
723 Ok(None) => EvaluatedToAmbig,
724 Err(..) => EvaluatedToErr
728 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
729 /// obligations are met. Returns true if `candidate` remains viable after this further
731 fn evaluate_candidate<'o>(&mut self,
732 stack: &TraitObligationStack<'o, 'tcx>,
733 candidate: &SelectionCandidate<'tcx>)
736 debug!("evaluate_candidate: depth={} candidate={:?}",
737 stack.obligation.recursion_depth, candidate);
738 let result = self.probe(|this, _| {
739 let candidate = (*candidate).clone();
740 match this.confirm_candidate(stack.obligation, candidate) {
742 this.evaluate_predicates_recursively(
744 selection.nested_obligations().iter())
746 Err(..) => EvaluatedToErr
749 debug!("evaluate_candidate: depth={} result={:?}",
750 stack.obligation.recursion_depth, result);
754 fn check_evaluation_cache(&self, trait_ref: ty::PolyTraitRef<'tcx>)
755 -> Option<EvaluationResult>
757 if self.can_use_global_caches() {
758 let cache = self.tcx().evaluation_cache.hashmap.borrow();
759 if let Some(cached) = cache.get(&trait_ref) {
760 return Some(cached.clone());
763 self.infcx.evaluation_cache.hashmap.borrow().get(&trait_ref).cloned()
766 fn insert_evaluation_cache(&mut self,
767 trait_ref: ty::PolyTraitRef<'tcx>,
768 result: EvaluationResult)
770 // Avoid caching results that depend on more than just the trait-ref:
771 // The stack can create EvaluatedToUnknown, and closure signatures
772 // being yet uninferred can create "spurious" EvaluatedToAmbig
773 // and EvaluatedToOk.
774 if result == EvaluatedToUnknown ||
775 ((result == EvaluatedToAmbig || result == EvaluatedToOk)
776 && trait_ref.has_closure_types())
781 if self.can_use_global_caches() {
782 let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
783 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
784 cache.insert(trait_ref, result);
789 self.infcx.evaluation_cache.hashmap.borrow_mut().insert(trait_ref, result);
792 ///////////////////////////////////////////////////////////////////////////
793 // CANDIDATE ASSEMBLY
795 // The selection process begins by examining all in-scope impls,
796 // caller obligations, and so forth and assembling a list of
797 // candidates. See `README.md` and the `Candidate` type for more
800 fn candidate_from_obligation<'o>(&mut self,
801 stack: &TraitObligationStack<'o, 'tcx>)
802 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
804 // Watch out for overflow. This intentionally bypasses (and does
805 // not update) the cache.
806 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
807 if stack.obligation.recursion_depth >= recursion_limit {
808 self.infcx().report_overflow_error(&stack.obligation, true);
811 // Check the cache. Note that we skolemize the trait-ref
812 // separately rather than using `stack.fresh_trait_ref` -- this
813 // is because we want the unbound variables to be replaced
814 // with fresh skolemized types starting from index 0.
815 let cache_fresh_trait_pred =
816 self.infcx.freshen(stack.obligation.predicate.clone());
817 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
818 cache_fresh_trait_pred,
820 assert!(!stack.obligation.predicate.has_escaping_regions());
822 if let Some(c) = self.check_candidate_cache(&cache_fresh_trait_pred) {
823 debug!("CACHE HIT: SELECT({:?})={:?}",
824 cache_fresh_trait_pred,
829 // If no match, compute result and insert into cache.
830 let candidate = self.candidate_from_obligation_no_cache(stack);
832 if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
833 debug!("CACHE MISS: SELECT({:?})={:?}",
834 cache_fresh_trait_pred, candidate);
835 self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone());
841 // Treat negative impls as unimplemented
842 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
843 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
844 if let ImplCandidate(def_id) = candidate {
845 if self.tcx().trait_impl_polarity(def_id) == hir::ImplPolarity::Negative {
846 return Err(Unimplemented)
852 fn candidate_from_obligation_no_cache<'o>(&mut self,
853 stack: &TraitObligationStack<'o, 'tcx>)
854 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
856 if stack.obligation.predicate.references_error() {
857 // If we encounter a `TyError`, we generally prefer the
858 // most "optimistic" result in response -- that is, the
859 // one least likely to report downstream errors. But
860 // because this routine is shared by coherence and by
861 // trait selection, there isn't an obvious "right" choice
862 // here in that respect, so we opt to just return
863 // ambiguity and let the upstream clients sort it out.
867 if !self.is_knowable(stack) {
868 debug!("coherence stage: not knowable");
872 let candidate_set = self.assemble_candidates(stack)?;
874 if candidate_set.ambiguous {
875 debug!("candidate set contains ambig");
879 let mut candidates = candidate_set.vec;
881 debug!("assembled {} candidates for {:?}: {:?}",
886 // At this point, we know that each of the entries in the
887 // candidate set is *individually* applicable. Now we have to
888 // figure out if they contain mutual incompatibilities. This
889 // frequently arises if we have an unconstrained input type --
890 // for example, we are looking for $0:Eq where $0 is some
891 // unconstrained type variable. In that case, we'll get a
892 // candidate which assumes $0 == int, one that assumes $0 ==
893 // usize, etc. This spells an ambiguity.
895 // If there is more than one candidate, first winnow them down
896 // by considering extra conditions (nested obligations and so
897 // forth). We don't winnow if there is exactly one
898 // candidate. This is a relatively minor distinction but it
899 // can lead to better inference and error-reporting. An
900 // example would be if there was an impl:
902 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
904 // and we were to see some code `foo.push_clone()` where `boo`
905 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
906 // we were to winnow, we'd wind up with zero candidates.
907 // Instead, we select the right impl now but report `Bar does
908 // not implement Clone`.
909 if candidates.len() == 1 {
910 return self.filter_negative_impls(candidates.pop().unwrap());
913 // Winnow, but record the exact outcome of evaluation, which
914 // is needed for specialization.
915 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
916 let eval = self.evaluate_candidate(stack, &c);
917 if eval.may_apply() {
918 Some(EvaluatedCandidate {
927 // If there are STILL multiple candidate, we can further
928 // reduce the list by dropping duplicates -- including
929 // resolving specializations.
930 if candidates.len() > 1 {
932 while i < candidates.len() {
934 (0..candidates.len())
936 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
939 debug!("Dropping candidate #{}/{}: {:?}",
940 i, candidates.len(), candidates[i]);
941 candidates.swap_remove(i);
943 debug!("Retaining candidate #{}/{}: {:?}",
944 i, candidates.len(), candidates[i]);
950 // If there are *STILL* multiple candidates, give up and
952 if candidates.len() > 1 {
953 debug!("multiple matches, ambig");
957 // If there are *NO* candidates, then there are no impls --
958 // that we know of, anyway. Note that in the case where there
959 // are unbound type variables within the obligation, it might
960 // be the case that you could still satisfy the obligation
961 // from another crate by instantiating the type variables with
962 // a type from another crate that does have an impl. This case
963 // is checked for in `evaluate_stack` (and hence users
964 // who might care about this case, like coherence, should use
966 if candidates.is_empty() {
967 return Err(Unimplemented);
970 // Just one candidate left.
971 self.filter_negative_impls(candidates.pop().unwrap().candidate)
974 fn is_knowable<'o>(&mut self,
975 stack: &TraitObligationStack<'o, 'tcx>)
978 debug!("is_knowable(intercrate={})", self.intercrate);
980 if !self.intercrate {
984 let obligation = &stack.obligation;
985 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
987 // ok to skip binder because of the nature of the
988 // trait-ref-is-knowable check, which does not care about
990 let trait_ref = &predicate.skip_binder().trait_ref;
992 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
995 /// Returns true if the global caches can be used.
996 /// Do note that if the type itself is not in the
997 /// global tcx, the local caches will be used.
998 fn can_use_global_caches(&self) -> bool {
999 // If there are any where-clauses in scope, then we always use
1000 // a cache local to this particular scope. Otherwise, we
1001 // switch to a global cache. We used to try and draw
1002 // finer-grained distinctions, but that led to a serious of
1003 // annoying and weird bugs like #22019 and #18290. This simple
1004 // rule seems to be pretty clearly safe and also still retains
1005 // a very high hit rate (~95% when compiling rustc).
1006 if !self.param_env().caller_bounds.is_empty() {
1010 // Avoid using the master cache during coherence and just rely
1011 // on the local cache. This effectively disables caching
1012 // during coherence. It is really just a simplification to
1013 // avoid us having to fear that coherence results "pollute"
1014 // the master cache. Since coherence executes pretty quickly,
1015 // it's not worth going to more trouble to increase the
1016 // hit-rate I don't think.
1017 if self.intercrate {
1021 // Otherwise, we can use the global cache.
1025 fn check_candidate_cache(&mut self,
1026 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1027 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1029 let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1030 if self.can_use_global_caches() {
1031 let cache = self.tcx().selection_cache.hashmap.borrow();
1032 if let Some(cached) = cache.get(&trait_ref) {
1033 return Some(cached.clone());
1036 self.infcx.selection_cache.hashmap.borrow().get(trait_ref).cloned()
1039 fn insert_candidate_cache(&mut self,
1040 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1041 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1043 let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1044 if self.can_use_global_caches() {
1045 let mut cache = self.tcx().selection_cache.hashmap.borrow_mut();
1046 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1047 if let Some(candidate) = self.tcx().lift_to_global(&candidate) {
1048 cache.insert(trait_ref, candidate);
1054 self.infcx.selection_cache.hashmap.borrow_mut().insert(trait_ref, candidate);
1057 fn should_update_candidate_cache(&mut self,
1058 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1059 candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1062 // In general, it's a good idea to cache results, even
1063 // ambiguous ones, to save us some trouble later. But we have
1064 // to be careful not to cache results that could be
1065 // invalidated later by advances in inference. Normally, this
1066 // is not an issue, because any inference variables whose
1067 // types are not yet bound are "freshened" in the cache key,
1068 // which means that if we later get the same request once that
1069 // type variable IS bound, we'll have a different cache key.
1070 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
1071 // not yet known, we may cache the result as `None`. But if
1072 // later `_#0t` is bound to `Bar`, then when we freshen we'll
1073 // have `Vec<Bar> : Foo` as the cache key.
1075 // HOWEVER, it CAN happen that we get an ambiguity result in
1076 // one particular case around closures where the cache key
1077 // would not change. That is when the precise types of the
1078 // upvars that a closure references have not yet been figured
1079 // out (i.e., because it is not yet known if they are captured
1080 // by ref, and if by ref, what kind of ref). In these cases,
1081 // when matching a builtin bound, we will yield back an
1082 // ambiguous result. But the *cache key* is just the closure type,
1083 // it doesn't capture the state of the upvar computation.
1085 // To avoid this trap, just don't cache ambiguous results if
1086 // the self-type contains no inference byproducts (that really
1087 // shouldn't happen in other circumstances anyway, given
1091 Ok(Some(_)) | Err(_) => true,
1092 Ok(None) => cache_fresh_trait_pred.has_infer_types()
1096 fn assemble_candidates<'o>(&mut self,
1097 stack: &TraitObligationStack<'o, 'tcx>)
1098 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1100 let TraitObligationStack { obligation, .. } = *stack;
1101 let ref obligation = Obligation {
1102 cause: obligation.cause.clone(),
1103 recursion_depth: obligation.recursion_depth,
1104 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1107 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1108 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1110 // This is somewhat problematic, as the current scheme can't really
1111 // handle it turning to be a projection. This does end up as truly
1112 // ambiguous in most cases anyway.
1114 // Until this is fixed, take the fast path out - this also improves
1115 // performance by preventing assemble_candidates_from_impls from
1116 // matching every impl for this trait.
1117 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1120 let mut candidates = SelectionCandidateSet {
1125 // Other bounds. Consider both in-scope bounds from fn decl
1126 // and applicable impls. There is a certain set of precedence rules here.
1128 let def_id = obligation.predicate.def_id();
1129 if self.tcx().lang_items.copy_trait() == Some(def_id) {
1130 debug!("obligation self ty is {:?}",
1131 obligation.predicate.0.self_ty());
1133 // User-defined copy impls are permitted, but only for
1134 // structs and enums.
1135 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1137 // For other types, we'll use the builtin rules.
1138 let copy_conditions = self.copy_conditions(obligation);
1139 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1140 } else if self.tcx().lang_items.sized_trait() == Some(def_id) {
1141 // Sized is never implementable by end-users, it is
1142 // always automatically computed.
1143 let sized_conditions = self.sized_conditions(obligation);
1144 self.assemble_builtin_bound_candidates(sized_conditions,
1146 } else if self.tcx().lang_items.unsize_trait() == Some(def_id) {
1147 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1149 self.assemble_closure_candidates(obligation, &mut candidates)?;
1150 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1151 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1152 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1155 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1156 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1157 // Default implementations have lower priority, so we only
1158 // consider triggering a default if there is no other impl that can apply.
1159 if candidates.vec.is_empty() {
1160 self.assemble_candidates_from_default_impls(obligation, &mut candidates)?;
1162 debug!("candidate list size: {}", candidates.vec.len());
1166 fn assemble_candidates_from_projected_tys(&mut self,
1167 obligation: &TraitObligation<'tcx>,
1168 candidates: &mut SelectionCandidateSet<'tcx>)
1170 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1172 // FIXME(#20297) -- just examining the self-type is very simplistic
1174 // before we go into the whole skolemization thing, just
1175 // quickly check if the self-type is a projection at all.
1176 match obligation.predicate.0.trait_ref.self_ty().sty {
1177 ty::TyProjection(_) | ty::TyAnon(..) => {}
1178 ty::TyInfer(ty::TyVar(_)) => {
1179 span_bug!(obligation.cause.span,
1180 "Self=_ should have been handled by assemble_candidates");
1185 let result = self.probe(|this, snapshot| {
1186 this.match_projection_obligation_against_definition_bounds(obligation,
1191 candidates.vec.push(ProjectionCandidate);
1195 fn match_projection_obligation_against_definition_bounds(
1197 obligation: &TraitObligation<'tcx>,
1198 snapshot: &infer::CombinedSnapshot)
1201 let poly_trait_predicate =
1202 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1203 let (skol_trait_predicate, skol_map) =
1204 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1205 debug!("match_projection_obligation_against_definition_bounds: \
1206 skol_trait_predicate={:?} skol_map={:?}",
1207 skol_trait_predicate,
1210 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1211 ty::TyProjection(ref data) => (data.trait_ref.def_id, data.trait_ref.substs),
1212 ty::TyAnon(def_id, substs) => (def_id, substs),
1215 obligation.cause.span,
1216 "match_projection_obligation_against_definition_bounds() called \
1217 but self-ty not a projection: {:?}",
1218 skol_trait_predicate.trait_ref.self_ty());
1221 debug!("match_projection_obligation_against_definition_bounds: \
1222 def_id={:?}, substs={:?}",
1225 let item_predicates = self.tcx().item_predicates(def_id);
1226 let bounds = item_predicates.instantiate(self.tcx(), substs);
1227 debug!("match_projection_obligation_against_definition_bounds: \
1231 let matching_bound =
1232 util::elaborate_predicates(self.tcx(), bounds.predicates)
1236 |this, _| this.match_projection(obligation,
1238 skol_trait_predicate.trait_ref.clone(),
1242 debug!("match_projection_obligation_against_definition_bounds: \
1243 matching_bound={:?}",
1245 match matching_bound {
1248 // Repeat the successful match, if any, this time outside of a probe.
1249 let result = self.match_projection(obligation,
1251 skol_trait_predicate.trait_ref.clone(),
1255 self.infcx.pop_skolemized(skol_map, snapshot);
1263 fn match_projection(&mut self,
1264 obligation: &TraitObligation<'tcx>,
1265 trait_bound: ty::PolyTraitRef<'tcx>,
1266 skol_trait_ref: ty::TraitRef<'tcx>,
1267 skol_map: &infer::SkolemizationMap<'tcx>,
1268 snapshot: &infer::CombinedSnapshot)
1271 assert!(!skol_trait_ref.has_escaping_regions());
1272 let cause = obligation.cause.clone();
1273 match self.infcx.sub_poly_trait_refs(false,
1275 trait_bound.clone(),
1276 ty::Binder(skol_trait_ref.clone())) {
1277 Ok(InferOk { obligations, .. }) => {
1278 self.inferred_obligations.extend(obligations);
1280 Err(_) => { return false; }
1283 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1286 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1287 /// supplied to find out whether it is listed among them.
1289 /// Never affects inference environment.
1290 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1291 stack: &TraitObligationStack<'o, 'tcx>,
1292 candidates: &mut SelectionCandidateSet<'tcx>)
1293 -> Result<(),SelectionError<'tcx>>
1295 debug!("assemble_candidates_from_caller_bounds({:?})",
1299 self.param_env().caller_bounds
1301 .filter_map(|o| o.to_opt_poly_trait_ref());
1303 let matching_bounds =
1305 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1307 let param_candidates =
1308 matching_bounds.map(|bound| ParamCandidate(bound));
1310 candidates.vec.extend(param_candidates);
1315 fn evaluate_where_clause<'o>(&mut self,
1316 stack: &TraitObligationStack<'o, 'tcx>,
1317 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1320 self.probe(move |this, _| {
1321 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1322 Ok(obligations) => {
1323 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1325 Err(()) => EvaluatedToErr
1330 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1331 /// FnMut<..>` where `X` is a closure type.
1333 /// Note: the type parameters on a closure candidate are modeled as *output* type
1334 /// parameters and hence do not affect whether this trait is a match or not. They will be
1335 /// unified during the confirmation step.
1336 fn assemble_closure_candidates(&mut self,
1337 obligation: &TraitObligation<'tcx>,
1338 candidates: &mut SelectionCandidateSet<'tcx>)
1339 -> Result<(),SelectionError<'tcx>>
1341 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1343 None => { return Ok(()); }
1346 // ok to skip binder because the substs on closure types never
1347 // touch bound regions, they just capture the in-scope
1348 // type/region parameters
1349 let self_ty = *obligation.self_ty().skip_binder();
1350 let (closure_def_id, substs) = match self_ty.sty {
1351 ty::TyClosure(id, substs) => (id, substs),
1352 ty::TyInfer(ty::TyVar(_)) => {
1353 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1354 candidates.ambiguous = true;
1357 _ => { return Ok(()); }
1360 debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1365 match self.infcx.closure_kind(closure_def_id) {
1366 Some(closure_kind) => {
1367 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1368 if closure_kind.extends(kind) {
1369 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1373 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1374 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1381 /// Implement one of the `Fn()` family for a fn pointer.
1382 fn assemble_fn_pointer_candidates(&mut self,
1383 obligation: &TraitObligation<'tcx>,
1384 candidates: &mut SelectionCandidateSet<'tcx>)
1385 -> Result<(),SelectionError<'tcx>>
1387 // We provide impl of all fn traits for fn pointers.
1388 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1392 // ok to skip binder because what we are inspecting doesn't involve bound regions
1393 let self_ty = *obligation.self_ty().skip_binder();
1395 ty::TyInfer(ty::TyVar(_)) => {
1396 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1397 candidates.ambiguous = true; // could wind up being a fn() type
1400 // provide an impl, but only for suitable `fn` pointers
1401 ty::TyFnDef(.., ty::Binder(ty::FnSig {
1402 unsafety: hir::Unsafety::Normal,
1407 ty::TyFnPtr(ty::Binder(ty::FnSig {
1408 unsafety: hir::Unsafety::Normal,
1413 candidates.vec.push(FnPointerCandidate);
1422 /// Search for impls that might apply to `obligation`.
1423 fn assemble_candidates_from_impls(&mut self,
1424 obligation: &TraitObligation<'tcx>,
1425 candidates: &mut SelectionCandidateSet<'tcx>)
1426 -> Result<(), SelectionError<'tcx>>
1428 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1430 let def = self.tcx().lookup_trait_def(obligation.predicate.def_id());
1432 def.for_each_relevant_impl(
1434 obligation.predicate.0.trait_ref.self_ty(),
1436 self.probe(|this, snapshot| { /* [1] */
1437 match this.match_impl(impl_def_id, obligation, snapshot) {
1439 candidates.vec.push(ImplCandidate(impl_def_id));
1441 // NB: we can safely drop the skol map
1442 // since we are in a probe [1]
1443 mem::drop(skol_map);
1454 fn assemble_candidates_from_default_impls(&mut self,
1455 obligation: &TraitObligation<'tcx>,
1456 candidates: &mut SelectionCandidateSet<'tcx>)
1457 -> Result<(), SelectionError<'tcx>>
1459 // OK to skip binder here because the tests we do below do not involve bound regions
1460 let self_ty = *obligation.self_ty().skip_binder();
1461 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1463 let def_id = obligation.predicate.def_id();
1465 if self.tcx().trait_has_default_impl(def_id) {
1467 ty::TyDynamic(..) => {
1468 // For object types, we don't know what the closed
1469 // over types are. This means we conservatively
1470 // say nothing; a candidate may be added by
1471 // `assemble_candidates_from_object_ty`.
1474 ty::TyProjection(..) => {
1475 // In these cases, we don't know what the actual
1476 // type is. Therefore, we cannot break it down
1477 // into its constituent types. So we don't
1478 // consider the `..` impl but instead just add no
1479 // candidates: this means that typeck will only
1480 // succeed if there is another reason to believe
1481 // that this obligation holds. That could be a
1482 // where-clause or, in the case of an object type,
1483 // it could be that the object type lists the
1484 // trait (e.g. `Foo+Send : Send`). See
1485 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1486 // for an example of a test case that exercises
1489 ty::TyInfer(ty::TyVar(_)) => {
1490 // the defaulted impl might apply, we don't know
1491 candidates.ambiguous = true;
1494 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1502 /// Search for impls that might apply to `obligation`.
1503 fn assemble_candidates_from_object_ty(&mut self,
1504 obligation: &TraitObligation<'tcx>,
1505 candidates: &mut SelectionCandidateSet<'tcx>)
1507 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1508 obligation.self_ty().skip_binder());
1510 // Object-safety candidates are only applicable to object-safe
1511 // traits. Including this check is useful because it helps
1512 // inference in cases of traits like `BorrowFrom`, which are
1513 // not object-safe, and which rely on being able to infer the
1514 // self-type from one of the other inputs. Without this check,
1515 // these cases wind up being considered ambiguous due to a
1516 // (spurious) ambiguity introduced here.
1517 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1518 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1522 self.probe(|this, _snapshot| {
1523 // the code below doesn't care about regions, and the
1524 // self-ty here doesn't escape this probe, so just erase
1526 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1527 let poly_trait_ref = match self_ty.sty {
1528 ty::TyDynamic(ref data, ..) => {
1529 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1530 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1531 pushing candidate");
1532 candidates.vec.push(BuiltinObjectCandidate);
1536 match data.principal() {
1537 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1541 ty::TyInfer(ty::TyVar(_)) => {
1542 debug!("assemble_candidates_from_object_ty: ambiguous");
1543 candidates.ambiguous = true; // could wind up being an object type
1551 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1554 // Count only those upcast versions that match the trait-ref
1555 // we are looking for. Specifically, do not only check for the
1556 // correct trait, but also the correct type parameters.
1557 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1558 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1559 let upcast_trait_refs =
1560 util::supertraits(this.tcx(), poly_trait_ref)
1561 .filter(|upcast_trait_ref| {
1562 this.probe(|this, _| {
1563 let upcast_trait_ref = upcast_trait_ref.clone();
1564 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1569 if upcast_trait_refs > 1 {
1570 // can be upcast in many ways; need more type information
1571 candidates.ambiguous = true;
1572 } else if upcast_trait_refs == 1 {
1573 candidates.vec.push(ObjectCandidate);
1578 /// Search for unsizing that might apply to `obligation`.
1579 fn assemble_candidates_for_unsizing(&mut self,
1580 obligation: &TraitObligation<'tcx>,
1581 candidates: &mut SelectionCandidateSet<'tcx>) {
1582 // We currently never consider higher-ranked obligations e.g.
1583 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1584 // because they are a priori invalid, and we could potentially add support
1585 // for them later, it's just that there isn't really a strong need for it.
1586 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1587 // impl, and those are generally applied to concrete types.
1589 // That said, one might try to write a fn with a where clause like
1590 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1591 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1592 // Still, you'd be more likely to write that where clause as
1594 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1595 // obligation above. Should be possible to extend this in the future.
1596 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1599 // Don't add any candidates if there are bound regions.
1603 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1605 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1608 let may_apply = match (&source.sty, &target.sty) {
1609 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1610 (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1611 // Upcasts permit two things:
1613 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1614 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1616 // Note that neither of these changes requires any
1617 // change at runtime. Eventually this will be
1620 // We always upcast when we can because of reason
1621 // #2 (region bounds).
1622 match (data_a.principal(), data_b.principal()) {
1623 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1624 data_b.auto_traits()
1625 // All of a's auto traits need to be in b's auto traits.
1626 .all(|b| data_a.auto_traits().any(|a| a == b)),
1632 (_, &ty::TyDynamic(..)) => true,
1634 // Ambiguous handling is below T -> Trait, because inference
1635 // variables can still implement Unsize<Trait> and nested
1636 // obligations will have the final say (likely deferred).
1637 (&ty::TyInfer(ty::TyVar(_)), _) |
1638 (_, &ty::TyInfer(ty::TyVar(_))) => {
1639 debug!("assemble_candidates_for_unsizing: ambiguous");
1640 candidates.ambiguous = true;
1645 (&ty::TyArray(..), &ty::TySlice(_)) => true,
1647 // Struct<T> -> Struct<U>.
1648 (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1649 def_id_a == def_id_b
1656 candidates.vec.push(BuiltinUnsizeCandidate);
1660 ///////////////////////////////////////////////////////////////////////////
1663 // Winnowing is the process of attempting to resolve ambiguity by
1664 // probing further. During the winnowing process, we unify all
1665 // type variables (ignoring skolemization) and then we also
1666 // attempt to evaluate recursive bounds to see if they are
1669 /// Returns true if `candidate_i` should be dropped in favor of
1670 /// `candidate_j`. Generally speaking we will drop duplicate
1671 /// candidates and prefer where-clause candidates.
1672 /// Returns true if `victim` should be dropped in favor of
1673 /// `other`. Generally speaking we will drop duplicate
1674 /// candidates and prefer where-clause candidates.
1676 /// See the comment for "SelectionCandidate" for more details.
1677 fn candidate_should_be_dropped_in_favor_of<'o>(
1679 victim: &EvaluatedCandidate<'tcx>,
1680 other: &EvaluatedCandidate<'tcx>)
1683 if victim.candidate == other.candidate {
1687 match other.candidate {
1689 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1690 DefaultImplCandidate(..) => {
1692 "default implementations shouldn't be recorded \
1693 when there are other valid candidates");
1696 ClosureCandidate(..) |
1697 FnPointerCandidate |
1698 BuiltinObjectCandidate |
1699 BuiltinUnsizeCandidate |
1700 BuiltinCandidate { .. } => {
1701 // We have a where-clause so don't go around looking
1706 ProjectionCandidate => {
1707 // Arbitrarily give param candidates priority
1708 // over projection and object candidates.
1711 ParamCandidate(..) => false,
1713 ImplCandidate(other_def) => {
1714 // See if we can toss out `victim` based on specialization.
1715 // This requires us to know *for sure* that the `other` impl applies
1716 // i.e. EvaluatedToOk:
1717 if other.evaluation == EvaluatedToOk {
1718 if let ImplCandidate(victim_def) = victim.candidate {
1719 let tcx = self.tcx().global_tcx();
1720 return traits::specializes(tcx, other_def, victim_def) ||
1721 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
1731 ///////////////////////////////////////////////////////////////////////////
1734 // These cover the traits that are built-in to the language
1735 // itself. This includes `Copy` and `Sized` for sure. For the
1736 // moment, it also includes `Send` / `Sync` and a few others, but
1737 // those will hopefully change to library-defined traits in the
1740 // HACK: if this returns an error, selection exits without considering
1742 fn assemble_builtin_bound_candidates<'o>(&mut self,
1743 conditions: BuiltinImplConditions<'tcx>,
1744 candidates: &mut SelectionCandidateSet<'tcx>)
1745 -> Result<(),SelectionError<'tcx>>
1748 BuiltinImplConditions::Where(nested) => {
1749 debug!("builtin_bound: nested={:?}", nested);
1750 candidates.vec.push(BuiltinCandidate {
1751 has_nested: nested.skip_binder().len() > 0
1755 BuiltinImplConditions::None => { Ok(()) }
1756 BuiltinImplConditions::Ambiguous => {
1757 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1758 Ok(candidates.ambiguous = true)
1760 BuiltinImplConditions::Never => { Err(Unimplemented) }
1764 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1765 -> BuiltinImplConditions<'tcx>
1767 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1769 // NOTE: binder moved to (*)
1770 let self_ty = self.infcx.shallow_resolve(
1771 obligation.predicate.skip_binder().self_ty());
1774 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1775 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1776 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
1777 ty::TyChar | ty::TyRef(..) |
1778 ty::TyArray(..) | ty::TyClosure(..) | ty::TyNever |
1780 // safe for everything
1781 Where(ty::Binder(Vec::new()))
1784 ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) => Never,
1786 ty::TyTuple(tys, _) => {
1787 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
1790 ty::TyAdt(def, substs) => {
1791 let sized_crit = def.sized_constraint(self.tcx());
1792 // (*) binder moved here
1793 Where(ty::Binder(match sized_crit.sty {
1794 ty::TyTuple(tys, _) => tys.to_vec().subst(self.tcx(), substs),
1795 ty::TyBool => vec![],
1796 _ => vec![sized_crit.subst(self.tcx(), substs)]
1800 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
1801 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
1803 ty::TyInfer(ty::FreshTy(_))
1804 | ty::TyInfer(ty::FreshIntTy(_))
1805 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1806 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1812 fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1813 -> BuiltinImplConditions<'tcx>
1815 // NOTE: binder moved to (*)
1816 let self_ty = self.infcx.shallow_resolve(
1817 obligation.predicate.skip_binder().self_ty());
1819 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1822 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1823 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1824 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1825 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
1826 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
1827 Where(ty::Binder(Vec::new()))
1830 ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
1832 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
1836 ty::TyArray(element_ty, _) => {
1837 // (*) binder moved here
1838 Where(ty::Binder(vec![element_ty]))
1841 ty::TyTuple(tys, _) => {
1842 // (*) binder moved here
1843 Where(ty::Binder(tys.to_vec()))
1846 ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
1847 // Fallback to whatever user-defined impls exist in this case.
1851 ty::TyInfer(ty::TyVar(_)) => {
1852 // Unbound type variable. Might or might not have
1853 // applicable impls and so forth, depending on what
1854 // those type variables wind up being bound to.
1858 ty::TyInfer(ty::FreshTy(_))
1859 | ty::TyInfer(ty::FreshIntTy(_))
1860 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1861 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1867 /// For default impls, we need to break apart a type into its
1868 /// "constituent types" -- meaning, the types that it contains.
1870 /// Here are some (simple) examples:
1873 /// (i32, u32) -> [i32, u32]
1874 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1875 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1876 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1878 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1888 ty::TyInfer(ty::IntVar(_)) |
1889 ty::TyInfer(ty::FloatVar(_)) |
1897 ty::TyProjection(..) |
1898 ty::TyInfer(ty::TyVar(_)) |
1899 ty::TyInfer(ty::FreshTy(_)) |
1900 ty::TyInfer(ty::FreshIntTy(_)) |
1901 ty::TyInfer(ty::FreshFloatTy(_)) => {
1902 bug!("asked to assemble constituent types of unexpected type: {:?}",
1906 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
1907 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
1911 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
1915 ty::TyTuple(ref tys, _) => {
1916 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1920 ty::TyClosure(def_id, ref substs) => {
1921 // FIXME(#27086). We are invariant w/r/t our
1922 // func_substs, but we don't see them as
1923 // constituent types; this seems RIGHT but also like
1924 // something that a normal type couldn't simulate. Is
1925 // this just a gap with the way that PhantomData and
1926 // OIBIT interact? That is, there is no way to say
1927 // "make me invariant with respect to this TYPE, but
1928 // do not act as though I can reach it"
1929 substs.upvar_tys(def_id, self.tcx()).collect()
1932 // for `PhantomData<T>`, we pass `T`
1933 ty::TyAdt(def, substs) if def.is_phantom_data() => {
1934 substs.types().collect()
1937 ty::TyAdt(def, substs) => {
1939 .map(|f| f.ty(self.tcx(), substs))
1943 ty::TyAnon(def_id, substs) => {
1944 // We can resolve the `impl Trait` to its concrete type,
1945 // which enforces a DAG between the functions requiring
1946 // the auto trait bounds in question.
1947 vec![self.tcx().item_type(def_id).subst(self.tcx(), substs)]
1952 fn collect_predicates_for_types(&mut self,
1953 cause: ObligationCause<'tcx>,
1954 recursion_depth: usize,
1955 trait_def_id: DefId,
1956 types: ty::Binder<Vec<Ty<'tcx>>>)
1957 -> Vec<PredicateObligation<'tcx>>
1959 // Because the types were potentially derived from
1960 // higher-ranked obligations they may reference late-bound
1961 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1962 // yield a type like `for<'a> &'a int`. In general, we
1963 // maintain the invariant that we never manipulate bound
1964 // regions, so we have to process these bound regions somehow.
1966 // The strategy is to:
1968 // 1. Instantiate those regions to skolemized regions (e.g.,
1969 // `for<'a> &'a int` becomes `&0 int`.
1970 // 2. Produce something like `&'0 int : Copy`
1971 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1973 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
1974 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
1976 self.in_snapshot(|this, snapshot| {
1977 let (skol_ty, skol_map) =
1978 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
1979 let Normalized { value: normalized_ty, mut obligations } =
1980 project::normalize_with_depth(this,
1984 let skol_obligation =
1985 this.tcx().predicate_for_trait_def(
1991 obligations.push(skol_obligation);
1992 this.infcx().plug_leaks(skol_map, snapshot, obligations)
1997 ///////////////////////////////////////////////////////////////////////////
2000 // Confirmation unifies the output type parameters of the trait
2001 // with the values found in the obligation, possibly yielding a
2002 // type error. See `README.md` for more details.
2004 fn confirm_candidate(&mut self,
2005 obligation: &TraitObligation<'tcx>,
2006 candidate: SelectionCandidate<'tcx>)
2007 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2009 debug!("confirm_candidate({:?}, {:?})",
2014 BuiltinCandidate { has_nested } => {
2016 self.confirm_builtin_candidate(obligation, has_nested)))
2019 ParamCandidate(param) => {
2020 let obligations = self.confirm_param_candidate(obligation, param);
2021 Ok(VtableParam(obligations))
2024 DefaultImplCandidate(trait_def_id) => {
2025 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2026 Ok(VtableDefaultImpl(data))
2029 ImplCandidate(impl_def_id) => {
2030 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2033 ClosureCandidate(closure_def_id, substs, kind) => {
2034 let vtable_closure =
2035 self.confirm_closure_candidate(obligation, closure_def_id, substs, kind)?;
2036 Ok(VtableClosure(vtable_closure))
2039 BuiltinObjectCandidate => {
2040 // This indicates something like `(Trait+Send) :
2041 // Send`. In this case, we know that this holds
2042 // because that's what the object type is telling us,
2043 // and there's really no additional obligations to
2044 // prove and no types in particular to unify etc.
2045 Ok(VtableParam(Vec::new()))
2048 ObjectCandidate => {
2049 let data = self.confirm_object_candidate(obligation);
2050 Ok(VtableObject(data))
2053 FnPointerCandidate => {
2055 self.confirm_fn_pointer_candidate(obligation)?;
2056 Ok(VtableFnPointer(data))
2059 ProjectionCandidate => {
2060 self.confirm_projection_candidate(obligation);
2061 Ok(VtableParam(Vec::new()))
2064 BuiltinUnsizeCandidate => {
2065 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2066 Ok(VtableBuiltin(data))
2071 fn confirm_projection_candidate(&mut self,
2072 obligation: &TraitObligation<'tcx>)
2074 self.in_snapshot(|this, snapshot| {
2076 this.match_projection_obligation_against_definition_bounds(obligation,
2082 fn confirm_param_candidate(&mut self,
2083 obligation: &TraitObligation<'tcx>,
2084 param: ty::PolyTraitRef<'tcx>)
2085 -> Vec<PredicateObligation<'tcx>>
2087 debug!("confirm_param_candidate({:?},{:?})",
2091 // During evaluation, we already checked that this
2092 // where-clause trait-ref could be unified with the obligation
2093 // trait-ref. Repeat that unification now without any
2094 // transactional boundary; it should not fail.
2095 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2096 Ok(obligations) => obligations,
2098 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2105 fn confirm_builtin_candidate(&mut self,
2106 obligation: &TraitObligation<'tcx>,
2108 -> VtableBuiltinData<PredicateObligation<'tcx>>
2110 debug!("confirm_builtin_candidate({:?}, {:?})",
2111 obligation, has_nested);
2113 let obligations = if has_nested {
2114 let trait_def = obligation.predicate.def_id();
2115 let conditions = match trait_def {
2116 _ if Some(trait_def) == self.tcx().lang_items.sized_trait() => {
2117 self.sized_conditions(obligation)
2119 _ if Some(trait_def) == self.tcx().lang_items.copy_trait() => {
2120 self.copy_conditions(obligation)
2122 _ => bug!("unexpected builtin trait {:?}", trait_def)
2124 let nested = match conditions {
2125 BuiltinImplConditions::Where(nested) => nested,
2126 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2130 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2131 self.collect_predicates_for_types(cause,
2132 obligation.recursion_depth+1,
2139 debug!("confirm_builtin_candidate: 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 /// See `confirm_default_impl_candidate`
2165 fn vtable_default_impl(&mut self,
2166 obligation: &TraitObligation<'tcx>,
2167 trait_def_id: DefId,
2168 nested: ty::Binder<Vec<Ty<'tcx>>>)
2169 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2171 debug!("vtable_default_impl: nested={:?}", nested);
2173 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2174 let mut obligations = self.collect_predicates_for_types(
2176 obligation.recursion_depth+1,
2180 let trait_obligations = self.in_snapshot(|this, snapshot| {
2181 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2182 let (trait_ref, skol_map) =
2183 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2184 let cause = obligation.derived_cause(ImplDerivedObligation);
2185 this.impl_or_trait_obligations(cause,
2186 obligation.recursion_depth + 1,
2193 obligations.extend(trait_obligations);
2195 debug!("vtable_default_impl: obligations={:?}", obligations);
2197 VtableDefaultImplData {
2198 trait_def_id: trait_def_id,
2203 fn confirm_impl_candidate(&mut self,
2204 obligation: &TraitObligation<'tcx>,
2206 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2208 debug!("confirm_impl_candidate({:?},{:?})",
2212 // First, create the substitutions by matching the impl again,
2213 // this time not in a probe.
2214 self.in_snapshot(|this, snapshot| {
2215 let (substs, skol_map) =
2216 this.rematch_impl(impl_def_id, obligation,
2218 debug!("confirm_impl_candidate substs={:?}", substs);
2219 let cause = obligation.derived_cause(ImplDerivedObligation);
2220 this.vtable_impl(impl_def_id, substs, cause,
2221 obligation.recursion_depth + 1,
2226 fn vtable_impl(&mut self,
2228 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2229 cause: ObligationCause<'tcx>,
2230 recursion_depth: usize,
2231 skol_map: infer::SkolemizationMap<'tcx>,
2232 snapshot: &infer::CombinedSnapshot)
2233 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2235 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2241 let mut impl_obligations =
2242 self.impl_or_trait_obligations(cause,
2249 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2253 // Because of RFC447, the impl-trait-ref and obligations
2254 // are sufficient to determine the impl substs, without
2255 // relying on projections in the impl-trait-ref.
2257 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2258 impl_obligations.append(&mut substs.obligations);
2260 VtableImplData { impl_def_id: impl_def_id,
2261 substs: substs.value,
2262 nested: impl_obligations }
2265 fn confirm_object_candidate(&mut self,
2266 obligation: &TraitObligation<'tcx>)
2267 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2269 debug!("confirm_object_candidate({:?})",
2272 // FIXME skipping binder here seems wrong -- we should
2273 // probably flatten the binder from the obligation and the
2274 // binder from the object. Have to try to make a broken test
2275 // case that results. -nmatsakis
2276 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2277 let poly_trait_ref = match self_ty.sty {
2278 ty::TyDynamic(ref data, ..) => {
2279 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2282 span_bug!(obligation.cause.span,
2283 "object candidate with non-object");
2287 let mut upcast_trait_ref = None;
2291 let tcx = self.tcx();
2293 // We want to find the first supertrait in the list of
2294 // supertraits that we can unify with, and do that
2295 // unification. We know that there is exactly one in the list
2296 // where we can unify because otherwise select would have
2297 // reported an ambiguity. (When we do find a match, also
2298 // record it for later.)
2300 util::supertraits(tcx, poly_trait_ref)
2304 |this, _| this.match_poly_trait_ref(obligation, t))
2306 Ok(_) => { upcast_trait_ref = Some(t); false }
2311 // Additionally, for each of the nonmatching predicates that
2312 // we pass over, we sum up the set of number of vtable
2313 // entries, so that we can compute the offset for the selected
2316 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2322 upcast_trait_ref: upcast_trait_ref.unwrap(),
2323 vtable_base: vtable_base,
2328 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2329 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2331 debug!("confirm_fn_pointer_candidate({:?})",
2334 // ok to skip binder; it is reintroduced below
2335 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2336 let sig = self_ty.fn_sig();
2338 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2341 util::TupleArgumentsFlag::Yes)
2342 .map_bound(|(trait_ref, _)| trait_ref);
2344 self.confirm_poly_trait_refs(obligation.cause.clone(),
2345 obligation.predicate.to_poly_trait_ref(),
2347 Ok(VtableFnPointerData { fn_ty: self_ty, nested: vec![] })
2350 fn confirm_closure_candidate(&mut self,
2351 obligation: &TraitObligation<'tcx>,
2352 closure_def_id: DefId,
2353 substs: ty::ClosureSubsts<'tcx>,
2354 kind: ty::ClosureKind)
2355 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2356 SelectionError<'tcx>>
2358 debug!("confirm_closure_candidate({:?},{:?},{:?})",
2366 } = self.closure_trait_ref(obligation, closure_def_id, substs);
2368 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2373 self.confirm_poly_trait_refs(obligation.cause.clone(),
2374 obligation.predicate.to_poly_trait_ref(),
2377 obligations.push(Obligation::new(
2378 obligation.cause.clone(),
2379 ty::Predicate::ClosureKind(closure_def_id, kind)));
2381 Ok(VtableClosureData {
2382 closure_def_id: closure_def_id,
2383 substs: substs.clone(),
2388 /// In the case of closure types and fn pointers,
2389 /// we currently treat the input type parameters on the trait as
2390 /// outputs. This means that when we have a match we have only
2391 /// considered the self type, so we have to go back and make sure
2392 /// to relate the argument types too. This is kind of wrong, but
2393 /// since we control the full set of impls, also not that wrong,
2394 /// and it DOES yield better error messages (since we don't report
2395 /// errors as if there is no applicable impl, but rather report
2396 /// errors are about mismatched argument types.
2398 /// Here is an example. Imagine we have a closure expression
2399 /// and we desugared it so that the type of the expression is
2400 /// `Closure`, and `Closure` expects an int as argument. Then it
2401 /// is "as if" the compiler generated this impl:
2403 /// impl Fn(int) for Closure { ... }
2405 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2406 /// we have matched the self-type `Closure`. At this point we'll
2407 /// compare the `int` to `usize` and generate an error.
2409 /// Note that this checking occurs *after* the impl has selected,
2410 /// because these output type parameters should not affect the
2411 /// selection of the impl. Therefore, if there is a mismatch, we
2412 /// report an error to the user.
2413 fn confirm_poly_trait_refs(&mut self,
2414 obligation_cause: ObligationCause<'tcx>,
2415 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2416 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2417 -> Result<(), SelectionError<'tcx>>
2419 let obligation_trait_ref = obligation_trait_ref.clone();
2420 self.infcx.sub_poly_trait_refs(false,
2421 obligation_cause.clone(),
2422 expected_trait_ref.clone(),
2423 obligation_trait_ref.clone())
2424 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2425 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2428 fn confirm_builtin_unsize_candidate(&mut self,
2429 obligation: &TraitObligation<'tcx>,)
2430 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2431 SelectionError<'tcx>> {
2432 let tcx = self.tcx();
2434 // assemble_candidates_for_unsizing should ensure there are no late bound
2435 // regions here. See the comment there for more details.
2436 let source = self.infcx.shallow_resolve(
2437 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2438 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2439 let target = self.infcx.shallow_resolve(target);
2441 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2444 let mut nested = vec![];
2445 match (&source.sty, &target.sty) {
2446 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2447 (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2448 // See assemble_candidates_for_unsizing for more info.
2449 // Binders reintroduced below in call to mk_existential_predicates.
2450 let principal = data_a.skip_binder().principal();
2451 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2452 .chain(data_a.skip_binder().projection_bounds()
2453 .map(|x| ty::ExistentialPredicate::Projection(x)))
2454 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2455 let new_trait = tcx.mk_dynamic(
2456 ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2457 let InferOk { obligations, .. } =
2458 self.infcx.eq_types(false, &obligation.cause, new_trait, target)
2459 .map_err(|_| Unimplemented)?;
2460 self.inferred_obligations.extend(obligations);
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(r_a, r_b);
2467 nested.push(Obligation::with_depth(cause,
2468 obligation.recursion_depth + 1,
2469 ty::Binder(outlives).to_predicate()));
2473 (_, &ty::TyDynamic(ref data, r)) => {
2474 let mut object_dids =
2475 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2476 if let Some(did) = object_dids.find(|did| {
2477 !tcx.is_object_safe(*did)
2479 return Err(TraitNotObjectSafe(did))
2482 let cause = ObligationCause::new(obligation.cause.span,
2483 obligation.cause.body_id,
2484 ObjectCastObligation(target));
2485 let mut push = |predicate| {
2486 nested.push(Obligation::with_depth(cause.clone(),
2487 obligation.recursion_depth + 1,
2491 // Create obligations:
2492 // - Casting T to Trait
2493 // - For all the various builtin bounds attached to the object cast. (In other
2494 // words, if the object type is Foo+Send, this would create an obligation for the
2496 // - Projection predicates
2497 for predicate in data.iter() {
2498 push(predicate.with_self_ty(tcx, source));
2501 // We can only make objects from sized types.
2502 let tr = ty::TraitRef {
2503 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2504 substs: tcx.mk_substs_trait(source, &[]),
2506 push(tr.to_predicate());
2508 // If the type is `Foo+'a`, ensures that the type
2509 // being cast to `Foo+'a` outlives `'a`:
2510 let outlives = ty::OutlivesPredicate(source, r);
2511 push(ty::Binder(outlives).to_predicate());
2515 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2516 let InferOk { obligations, .. } =
2517 self.infcx.eq_types(false, &obligation.cause, a, b)
2518 .map_err(|_| Unimplemented)?;
2519 self.inferred_obligations.extend(obligations);
2522 // Struct<T> -> Struct<U>.
2523 (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2526 .map(|f| tcx.item_type(f.did))
2527 .collect::<Vec<_>>();
2529 // The last field of the structure has to exist and contain type parameters.
2530 let field = if let Some(&field) = fields.last() {
2533 return Err(Unimplemented);
2535 let mut ty_params = BitVector::new(substs_a.types().count());
2536 let mut found = false;
2537 for ty in field.walk() {
2538 if let ty::TyParam(p) = ty.sty {
2539 ty_params.insert(p.idx as usize);
2544 return Err(Unimplemented);
2547 // Replace type parameters used in unsizing with
2548 // TyError and ensure they do not affect any other fields.
2549 // This could be checked after type collection for any struct
2550 // with a potentially unsized trailing field.
2551 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2552 if ty_params.contains(i) {
2553 Kind::from(tcx.types.err)
2558 let substs = tcx.mk_substs(params);
2559 for &ty in fields.split_last().unwrap().1 {
2560 if ty.subst(tcx, substs).references_error() {
2561 return Err(Unimplemented);
2565 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2566 let inner_source = field.subst(tcx, substs_a);
2567 let inner_target = field.subst(tcx, substs_b);
2569 // Check that the source structure with the target's
2570 // type parameters is a subtype of the target.
2571 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2572 if ty_params.contains(i) {
2573 Kind::from(substs_b.type_at(i))
2578 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
2579 let InferOk { obligations, .. } =
2580 self.infcx.eq_types(false, &obligation.cause, new_struct, target)
2581 .map_err(|_| Unimplemented)?;
2582 self.inferred_obligations.extend(obligations);
2584 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2585 nested.push(tcx.predicate_for_trait_def(
2586 obligation.cause.clone(),
2587 obligation.predicate.def_id(),
2588 obligation.recursion_depth + 1,
2596 Ok(VtableBuiltinData { nested: nested })
2599 ///////////////////////////////////////////////////////////////////////////
2602 // Matching is a common path used for both evaluation and
2603 // confirmation. It basically unifies types that appear in impls
2604 // and traits. This does affect the surrounding environment;
2605 // therefore, when used during evaluation, match routines must be
2606 // run inside of a `probe()` so that their side-effects are
2609 fn rematch_impl(&mut self,
2611 obligation: &TraitObligation<'tcx>,
2612 snapshot: &infer::CombinedSnapshot)
2613 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
2614 infer::SkolemizationMap<'tcx>)
2616 match self.match_impl(impl_def_id, obligation, snapshot) {
2617 Ok((substs, skol_map)) => (substs, skol_map),
2619 bug!("Impl {:?} was matchable against {:?} but now is not",
2626 fn match_impl(&mut self,
2628 obligation: &TraitObligation<'tcx>,
2629 snapshot: &infer::CombinedSnapshot)
2630 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
2631 infer::SkolemizationMap<'tcx>), ()>
2633 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2635 // Before we create the substitutions and everything, first
2636 // consider a "quick reject". This avoids creating more types
2637 // and so forth that we need to.
2638 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2642 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2643 &obligation.predicate,
2645 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2647 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
2650 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2653 let impl_trait_ref =
2654 project::normalize_with_depth(self,
2655 obligation.cause.clone(),
2656 obligation.recursion_depth + 1,
2659 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2660 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2664 skol_obligation_trait_ref);
2666 let InferOk { obligations, .. } =
2667 self.infcx.eq_trait_refs(false,
2669 impl_trait_ref.value.clone(),
2670 skol_obligation_trait_ref)
2672 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2675 self.inferred_obligations.extend(obligations);
2677 if let Err(e) = self.infcx.leak_check(false,
2678 obligation.cause.span,
2681 debug!("match_impl: failed leak check due to `{}`", e);
2685 debug!("match_impl: success impl_substs={:?}", impl_substs);
2688 obligations: impl_trait_ref.obligations
2692 fn fast_reject_trait_refs(&mut self,
2693 obligation: &TraitObligation,
2694 impl_trait_ref: &ty::TraitRef)
2697 // We can avoid creating type variables and doing the full
2698 // substitution if we find that any of the input types, when
2699 // simplified, do not match.
2701 obligation.predicate.skip_binder().input_types()
2702 .zip(impl_trait_ref.input_types())
2703 .any(|(obligation_ty, impl_ty)| {
2704 let simplified_obligation_ty =
2705 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2706 let simplified_impl_ty =
2707 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2709 simplified_obligation_ty.is_some() &&
2710 simplified_impl_ty.is_some() &&
2711 simplified_obligation_ty != simplified_impl_ty
2715 /// Normalize `where_clause_trait_ref` and try to match it against
2716 /// `obligation`. If successful, return any predicates that
2717 /// result from the normalization. Normalization is necessary
2718 /// because where-clauses are stored in the parameter environment
2720 fn match_where_clause_trait_ref(&mut self,
2721 obligation: &TraitObligation<'tcx>,
2722 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2723 -> Result<Vec<PredicateObligation<'tcx>>,()>
2725 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
2729 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2730 /// obligation is satisfied.
2731 fn match_poly_trait_ref(&mut self,
2732 obligation: &TraitObligation<'tcx>,
2733 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2736 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2740 self.infcx.sub_poly_trait_refs(false,
2741 obligation.cause.clone(),
2743 obligation.predicate.to_poly_trait_ref())
2744 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2748 ///////////////////////////////////////////////////////////////////////////
2751 fn match_fresh_trait_refs(&self,
2752 previous: &ty::PolyTraitRef<'tcx>,
2753 current: &ty::PolyTraitRef<'tcx>)
2756 let mut matcher = ty::_match::Match::new(self.tcx());
2757 matcher.relate(previous, current).is_ok()
2760 fn push_stack<'o,'s:'o>(&mut self,
2761 previous_stack: TraitObligationStackList<'s, 'tcx>,
2762 obligation: &'o TraitObligation<'tcx>)
2763 -> TraitObligationStack<'o, 'tcx>
2765 let fresh_trait_ref =
2766 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2768 TraitObligationStack {
2769 obligation: obligation,
2770 fresh_trait_ref: fresh_trait_ref,
2771 previous: previous_stack,
2775 fn closure_trait_ref_unnormalized(&mut self,
2776 obligation: &TraitObligation<'tcx>,
2777 closure_def_id: DefId,
2778 substs: ty::ClosureSubsts<'tcx>)
2779 -> ty::PolyTraitRef<'tcx>
2781 let closure_type = self.infcx.closure_type(closure_def_id)
2782 .subst(self.tcx(), substs.substs);
2783 let ty::Binder((trait_ref, _)) =
2784 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2785 obligation.predicate.0.self_ty(), // (1)
2787 util::TupleArgumentsFlag::No);
2788 // (1) Feels icky to skip the binder here, but OTOH we know
2789 // that the self-type is an unboxed closure type and hence is
2790 // in fact unparameterized (or at least does not reference any
2791 // regions bound in the obligation). Still probably some
2792 // refactoring could make this nicer.
2794 ty::Binder(trait_ref)
2797 fn closure_trait_ref(&mut self,
2798 obligation: &TraitObligation<'tcx>,
2799 closure_def_id: DefId,
2800 substs: ty::ClosureSubsts<'tcx>)
2801 -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
2803 let trait_ref = self.closure_trait_ref_unnormalized(
2804 obligation, closure_def_id, substs);
2806 // A closure signature can contain associated types which
2807 // must be normalized.
2808 normalize_with_depth(self,
2809 obligation.cause.clone(),
2810 obligation.recursion_depth+1,
2814 /// Returns the obligations that are implied by instantiating an
2815 /// impl or trait. The obligations are substituted and fully
2816 /// normalized. This is used when confirming an impl or default
2818 fn impl_or_trait_obligations(&mut self,
2819 cause: ObligationCause<'tcx>,
2820 recursion_depth: usize,
2821 def_id: DefId, // of impl or trait
2822 substs: &Substs<'tcx>, // for impl or trait
2823 skol_map: infer::SkolemizationMap<'tcx>,
2824 snapshot: &infer::CombinedSnapshot)
2825 -> Vec<PredicateObligation<'tcx>>
2827 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2828 let tcx = self.tcx();
2830 // To allow for one-pass evaluation of the nested obligation,
2831 // each predicate must be preceded by the obligations required
2833 // for example, if we have:
2834 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2835 // the impl will have the following predicates:
2836 // <V as Iterator>::Item = U,
2837 // U: Iterator, U: Sized,
2838 // V: Iterator, V: Sized,
2839 // <U as Iterator>::Item: Copy
2840 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2841 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2842 // `$1: Copy`, so we must ensure the obligations are emitted in
2844 let predicates = tcx.item_predicates(def_id);
2845 assert_eq!(predicates.parent, None);
2846 let predicates = predicates.predicates.iter().flat_map(|predicate| {
2847 let predicate = normalize_with_depth(self, cause.clone(), recursion_depth,
2848 &predicate.subst(tcx, substs));
2849 predicate.obligations.into_iter().chain(
2851 cause: cause.clone(),
2852 recursion_depth: recursion_depth,
2853 predicate: predicate.value
2856 self.infcx().plug_leaks(skol_map, snapshot, predicates)
2860 impl<'tcx> TraitObligation<'tcx> {
2861 #[allow(unused_comparisons)]
2862 pub fn derived_cause(&self,
2863 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2864 -> ObligationCause<'tcx>
2867 * Creates a cause for obligations that are derived from
2868 * `obligation` by a recursive search (e.g., for a builtin
2869 * bound, or eventually a `impl Foo for ..`). If `obligation`
2870 * is itself a derived obligation, this is just a clone, but
2871 * otherwise we create a "derived obligation" cause so as to
2872 * keep track of the original root obligation for error
2876 let obligation = self;
2878 // NOTE(flaper87): As of now, it keeps track of the whole error
2879 // chain. Ideally, we should have a way to configure this either
2880 // by using -Z verbose or just a CLI argument.
2881 if obligation.recursion_depth >= 0 {
2882 let derived_cause = DerivedObligationCause {
2883 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2884 parent_code: Rc::new(obligation.cause.code.clone())
2886 let derived_code = variant(derived_cause);
2887 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2889 obligation.cause.clone()
2894 impl<'tcx> SelectionCache<'tcx> {
2895 pub fn new() -> SelectionCache<'tcx> {
2897 hashmap: RefCell::new(FxHashMap())
2902 impl<'tcx> EvaluationCache<'tcx> {
2903 pub fn new() -> EvaluationCache<'tcx> {
2905 hashmap: RefCell::new(FxHashMap())
2910 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
2911 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
2912 TraitObligationStackList::with(self)
2915 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
2920 #[derive(Copy, Clone)]
2921 struct TraitObligationStackList<'o,'tcx:'o> {
2922 head: Option<&'o TraitObligationStack<'o,'tcx>>
2925 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
2926 fn empty() -> TraitObligationStackList<'o,'tcx> {
2927 TraitObligationStackList { head: None }
2930 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
2931 TraitObligationStackList { head: Some(r) }
2935 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
2936 type Item = &'o TraitObligationStack<'o,'tcx>;
2938 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
2949 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
2950 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2951 write!(f, "TraitObligationStack({:?})", self.obligation)
2955 impl EvaluationResult {
2956 fn may_apply(&self) -> bool {
2960 EvaluatedToUnknown => true,
2962 EvaluatedToErr => false