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) -> ty::ParamEnv<'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.param_env().reveal
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().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]);
947 // If there are *STILL* multiple candidates, give up
948 // and report ambiguity.
950 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 predicates_of = self.tcx().predicates_of(def_id);
1226 let bounds = predicates_of.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 // micro-optimization: filter out predicates relating to different
1305 let matching_bounds =
1306 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1308 let matching_bounds =
1309 matching_bounds.filter(
1310 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1312 let param_candidates =
1313 matching_bounds.map(|bound| ParamCandidate(bound));
1315 candidates.vec.extend(param_candidates);
1320 fn evaluate_where_clause<'o>(&mut self,
1321 stack: &TraitObligationStack<'o, 'tcx>,
1322 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1325 self.probe(move |this, _| {
1326 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1327 Ok(obligations) => {
1328 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1330 Err(()) => EvaluatedToErr
1335 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1336 /// FnMut<..>` where `X` is a closure type.
1338 /// Note: the type parameters on a closure candidate are modeled as *output* type
1339 /// parameters and hence do not affect whether this trait is a match or not. They will be
1340 /// unified during the confirmation step.
1341 fn assemble_closure_candidates(&mut self,
1342 obligation: &TraitObligation<'tcx>,
1343 candidates: &mut SelectionCandidateSet<'tcx>)
1344 -> Result<(),SelectionError<'tcx>>
1346 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1348 None => { return Ok(()); }
1351 // ok to skip binder because the substs on closure types never
1352 // touch bound regions, they just capture the in-scope
1353 // type/region parameters
1354 let self_ty = *obligation.self_ty().skip_binder();
1355 let (closure_def_id, substs) = match self_ty.sty {
1356 ty::TyClosure(id, substs) => (id, substs),
1357 ty::TyInfer(ty::TyVar(_)) => {
1358 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1359 candidates.ambiguous = true;
1362 _ => { return Ok(()); }
1365 debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1370 match self.infcx.closure_kind(closure_def_id) {
1371 Some(closure_kind) => {
1372 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1373 if closure_kind.extends(kind) {
1374 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1378 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1379 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1386 /// Implement one of the `Fn()` family for a fn pointer.
1387 fn assemble_fn_pointer_candidates(&mut self,
1388 obligation: &TraitObligation<'tcx>,
1389 candidates: &mut SelectionCandidateSet<'tcx>)
1390 -> Result<(),SelectionError<'tcx>>
1392 // We provide impl of all fn traits for fn pointers.
1393 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1397 // ok to skip binder because what we are inspecting doesn't involve bound regions
1398 let self_ty = *obligation.self_ty().skip_binder();
1400 ty::TyInfer(ty::TyVar(_)) => {
1401 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1402 candidates.ambiguous = true; // could wind up being a fn() type
1405 // provide an impl, but only for suitable `fn` pointers
1406 ty::TyFnDef(.., ty::Binder(ty::FnSig {
1407 unsafety: hir::Unsafety::Normal,
1412 ty::TyFnPtr(ty::Binder(ty::FnSig {
1413 unsafety: hir::Unsafety::Normal,
1418 candidates.vec.push(FnPointerCandidate);
1427 /// Search for impls that might apply to `obligation`.
1428 fn assemble_candidates_from_impls(&mut self,
1429 obligation: &TraitObligation<'tcx>,
1430 candidates: &mut SelectionCandidateSet<'tcx>)
1431 -> Result<(), SelectionError<'tcx>>
1433 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1435 let def = self.tcx().trait_def(obligation.predicate.def_id());
1437 def.for_each_relevant_impl(
1439 obligation.predicate.0.trait_ref.self_ty(),
1441 self.probe(|this, snapshot| { /* [1] */
1442 match this.match_impl(impl_def_id, obligation, snapshot) {
1444 candidates.vec.push(ImplCandidate(impl_def_id));
1446 // NB: we can safely drop the skol map
1447 // since we are in a probe [1]
1448 mem::drop(skol_map);
1459 fn assemble_candidates_from_default_impls(&mut self,
1460 obligation: &TraitObligation<'tcx>,
1461 candidates: &mut SelectionCandidateSet<'tcx>)
1462 -> Result<(), SelectionError<'tcx>>
1464 // OK to skip binder here because the tests we do below do not involve bound regions
1465 let self_ty = *obligation.self_ty().skip_binder();
1466 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1468 let def_id = obligation.predicate.def_id();
1470 if self.tcx().trait_has_default_impl(def_id) {
1472 ty::TyDynamic(..) => {
1473 // For object types, we don't know what the closed
1474 // over types are. This means we conservatively
1475 // say nothing; a candidate may be added by
1476 // `assemble_candidates_from_object_ty`.
1479 ty::TyProjection(..) => {
1480 // In these cases, we don't know what the actual
1481 // type is. Therefore, we cannot break it down
1482 // into its constituent types. So we don't
1483 // consider the `..` impl but instead just add no
1484 // candidates: this means that typeck will only
1485 // succeed if there is another reason to believe
1486 // that this obligation holds. That could be a
1487 // where-clause or, in the case of an object type,
1488 // it could be that the object type lists the
1489 // trait (e.g. `Foo+Send : Send`). See
1490 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1491 // for an example of a test case that exercises
1494 ty::TyInfer(ty::TyVar(_)) => {
1495 // the defaulted impl might apply, we don't know
1496 candidates.ambiguous = true;
1499 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1507 /// Search for impls that might apply to `obligation`.
1508 fn assemble_candidates_from_object_ty(&mut self,
1509 obligation: &TraitObligation<'tcx>,
1510 candidates: &mut SelectionCandidateSet<'tcx>)
1512 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1513 obligation.self_ty().skip_binder());
1515 // Object-safety candidates are only applicable to object-safe
1516 // traits. Including this check is useful because it helps
1517 // inference in cases of traits like `BorrowFrom`, which are
1518 // not object-safe, and which rely on being able to infer the
1519 // self-type from one of the other inputs. Without this check,
1520 // these cases wind up being considered ambiguous due to a
1521 // (spurious) ambiguity introduced here.
1522 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1523 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1527 self.probe(|this, _snapshot| {
1528 // the code below doesn't care about regions, and the
1529 // self-ty here doesn't escape this probe, so just erase
1531 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1532 let poly_trait_ref = match self_ty.sty {
1533 ty::TyDynamic(ref data, ..) => {
1534 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1535 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1536 pushing candidate");
1537 candidates.vec.push(BuiltinObjectCandidate);
1541 match data.principal() {
1542 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1546 ty::TyInfer(ty::TyVar(_)) => {
1547 debug!("assemble_candidates_from_object_ty: ambiguous");
1548 candidates.ambiguous = true; // could wind up being an object type
1556 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1559 // Count only those upcast versions that match the trait-ref
1560 // we are looking for. Specifically, do not only check for the
1561 // correct trait, but also the correct type parameters.
1562 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1563 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1564 let upcast_trait_refs =
1565 util::supertraits(this.tcx(), poly_trait_ref)
1566 .filter(|upcast_trait_ref| {
1567 this.probe(|this, _| {
1568 let upcast_trait_ref = upcast_trait_ref.clone();
1569 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1574 if upcast_trait_refs > 1 {
1575 // can be upcast in many ways; need more type information
1576 candidates.ambiguous = true;
1577 } else if upcast_trait_refs == 1 {
1578 candidates.vec.push(ObjectCandidate);
1583 /// Search for unsizing that might apply to `obligation`.
1584 fn assemble_candidates_for_unsizing(&mut self,
1585 obligation: &TraitObligation<'tcx>,
1586 candidates: &mut SelectionCandidateSet<'tcx>) {
1587 // We currently never consider higher-ranked obligations e.g.
1588 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1589 // because they are a priori invalid, and we could potentially add support
1590 // for them later, it's just that there isn't really a strong need for it.
1591 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1592 // impl, and those are generally applied to concrete types.
1594 // That said, one might try to write a fn with a where clause like
1595 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1596 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1597 // Still, you'd be more likely to write that where clause as
1599 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1600 // obligation above. Should be possible to extend this in the future.
1601 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1604 // Don't add any candidates if there are bound regions.
1608 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1610 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1613 let may_apply = match (&source.sty, &target.sty) {
1614 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1615 (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1616 // Upcasts permit two things:
1618 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1619 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1621 // Note that neither of these changes requires any
1622 // change at runtime. Eventually this will be
1625 // We always upcast when we can because of reason
1626 // #2 (region bounds).
1627 match (data_a.principal(), data_b.principal()) {
1628 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1629 data_b.auto_traits()
1630 // All of a's auto traits need to be in b's auto traits.
1631 .all(|b| data_a.auto_traits().any(|a| a == b)),
1637 (_, &ty::TyDynamic(..)) => true,
1639 // Ambiguous handling is below T -> Trait, because inference
1640 // variables can still implement Unsize<Trait> and nested
1641 // obligations will have the final say (likely deferred).
1642 (&ty::TyInfer(ty::TyVar(_)), _) |
1643 (_, &ty::TyInfer(ty::TyVar(_))) => {
1644 debug!("assemble_candidates_for_unsizing: ambiguous");
1645 candidates.ambiguous = true;
1650 (&ty::TyArray(..), &ty::TySlice(_)) => true,
1652 // Struct<T> -> Struct<U>.
1653 (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1654 def_id_a == def_id_b
1661 candidates.vec.push(BuiltinUnsizeCandidate);
1665 ///////////////////////////////////////////////////////////////////////////
1668 // Winnowing is the process of attempting to resolve ambiguity by
1669 // probing further. During the winnowing process, we unify all
1670 // type variables (ignoring skolemization) and then we also
1671 // attempt to evaluate recursive bounds to see if they are
1674 /// Returns true if `candidate_i` should be dropped in favor of
1675 /// `candidate_j`. Generally speaking we will drop duplicate
1676 /// candidates and prefer where-clause candidates.
1677 /// Returns true if `victim` should be dropped in favor of
1678 /// `other`. Generally speaking we will drop duplicate
1679 /// candidates and prefer where-clause candidates.
1681 /// See the comment for "SelectionCandidate" for more details.
1682 fn candidate_should_be_dropped_in_favor_of<'o>(
1684 victim: &EvaluatedCandidate<'tcx>,
1685 other: &EvaluatedCandidate<'tcx>)
1688 if victim.candidate == other.candidate {
1692 match other.candidate {
1694 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1695 DefaultImplCandidate(..) => {
1697 "default implementations shouldn't be recorded \
1698 when there are other valid candidates");
1701 ClosureCandidate(..) |
1702 FnPointerCandidate |
1703 BuiltinObjectCandidate |
1704 BuiltinUnsizeCandidate |
1705 BuiltinCandidate { .. } => {
1706 // We have a where-clause so don't go around looking
1711 ProjectionCandidate => {
1712 // Arbitrarily give param candidates priority
1713 // over projection and object candidates.
1716 ParamCandidate(..) => false,
1718 ImplCandidate(other_def) => {
1719 // See if we can toss out `victim` based on specialization.
1720 // This requires us to know *for sure* that the `other` impl applies
1721 // i.e. EvaluatedToOk:
1722 if other.evaluation == EvaluatedToOk {
1723 if let ImplCandidate(victim_def) = victim.candidate {
1724 let tcx = self.tcx().global_tcx();
1725 return traits::specializes(tcx, other_def, victim_def) ||
1726 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
1736 ///////////////////////////////////////////////////////////////////////////
1739 // These cover the traits that are built-in to the language
1740 // itself. This includes `Copy` and `Sized` for sure. For the
1741 // moment, it also includes `Send` / `Sync` and a few others, but
1742 // those will hopefully change to library-defined traits in the
1745 // HACK: if this returns an error, selection exits without considering
1747 fn assemble_builtin_bound_candidates<'o>(&mut self,
1748 conditions: BuiltinImplConditions<'tcx>,
1749 candidates: &mut SelectionCandidateSet<'tcx>)
1750 -> Result<(),SelectionError<'tcx>>
1753 BuiltinImplConditions::Where(nested) => {
1754 debug!("builtin_bound: nested={:?}", nested);
1755 candidates.vec.push(BuiltinCandidate {
1756 has_nested: nested.skip_binder().len() > 0
1760 BuiltinImplConditions::None => { Ok(()) }
1761 BuiltinImplConditions::Ambiguous => {
1762 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1763 Ok(candidates.ambiguous = true)
1765 BuiltinImplConditions::Never => { Err(Unimplemented) }
1769 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1770 -> BuiltinImplConditions<'tcx>
1772 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1774 // NOTE: binder moved to (*)
1775 let self_ty = self.infcx.shallow_resolve(
1776 obligation.predicate.skip_binder().self_ty());
1779 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1780 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1781 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
1782 ty::TyChar | ty::TyRef(..) |
1783 ty::TyArray(..) | ty::TyClosure(..) | ty::TyNever |
1785 // safe for everything
1786 Where(ty::Binder(Vec::new()))
1789 ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) => Never,
1791 ty::TyTuple(tys, _) => {
1792 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
1795 ty::TyAdt(def, substs) => {
1796 let sized_crit = def.sized_constraint(self.tcx());
1797 // (*) binder moved here
1799 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1803 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
1804 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
1806 ty::TyInfer(ty::FreshTy(_))
1807 | ty::TyInfer(ty::FreshIntTy(_))
1808 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1809 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1815 fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1816 -> BuiltinImplConditions<'tcx>
1818 // NOTE: binder moved to (*)
1819 let self_ty = self.infcx.shallow_resolve(
1820 obligation.predicate.skip_binder().self_ty());
1822 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1825 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1826 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1827 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1828 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
1829 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
1830 Where(ty::Binder(Vec::new()))
1833 ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
1835 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
1839 ty::TyArray(element_ty, _) => {
1840 // (*) binder moved here
1841 Where(ty::Binder(vec![element_ty]))
1844 ty::TyTuple(tys, _) => {
1845 // (*) binder moved here
1846 Where(ty::Binder(tys.to_vec()))
1849 ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
1850 // Fallback to whatever user-defined impls exist in this case.
1854 ty::TyInfer(ty::TyVar(_)) => {
1855 // Unbound type variable. Might or might not have
1856 // applicable impls and so forth, depending on what
1857 // those type variables wind up being bound to.
1861 ty::TyInfer(ty::FreshTy(_))
1862 | ty::TyInfer(ty::FreshIntTy(_))
1863 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1864 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1870 /// For default impls, we need to break apart a type into its
1871 /// "constituent types" -- meaning, the types that it contains.
1873 /// Here are some (simple) examples:
1876 /// (i32, u32) -> [i32, u32]
1877 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1878 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1879 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1881 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1891 ty::TyInfer(ty::IntVar(_)) |
1892 ty::TyInfer(ty::FloatVar(_)) |
1900 ty::TyProjection(..) |
1901 ty::TyInfer(ty::TyVar(_)) |
1902 ty::TyInfer(ty::FreshTy(_)) |
1903 ty::TyInfer(ty::FreshIntTy(_)) |
1904 ty::TyInfer(ty::FreshFloatTy(_)) => {
1905 bug!("asked to assemble constituent types of unexpected type: {:?}",
1909 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
1910 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
1914 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
1918 ty::TyTuple(ref tys, _) => {
1919 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1923 ty::TyClosure(def_id, ref substs) => {
1924 // FIXME(#27086). We are invariant w/r/t our
1925 // func_substs, but we don't see them as
1926 // constituent types; this seems RIGHT but also like
1927 // something that a normal type couldn't simulate. Is
1928 // this just a gap with the way that PhantomData and
1929 // OIBIT interact? That is, there is no way to say
1930 // "make me invariant with respect to this TYPE, but
1931 // do not act as though I can reach it"
1932 substs.upvar_tys(def_id, self.tcx()).collect()
1935 // for `PhantomData<T>`, we pass `T`
1936 ty::TyAdt(def, substs) if def.is_phantom_data() => {
1937 substs.types().collect()
1940 ty::TyAdt(def, substs) => {
1942 .map(|f| f.ty(self.tcx(), substs))
1946 ty::TyAnon(def_id, substs) => {
1947 // We can resolve the `impl Trait` to its concrete type,
1948 // which enforces a DAG between the functions requiring
1949 // the auto trait bounds in question.
1950 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
1955 fn collect_predicates_for_types(&mut self,
1956 cause: ObligationCause<'tcx>,
1957 recursion_depth: usize,
1958 trait_def_id: DefId,
1959 types: ty::Binder<Vec<Ty<'tcx>>>)
1960 -> Vec<PredicateObligation<'tcx>>
1962 // Because the types were potentially derived from
1963 // higher-ranked obligations they may reference late-bound
1964 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1965 // yield a type like `for<'a> &'a int`. In general, we
1966 // maintain the invariant that we never manipulate bound
1967 // regions, so we have to process these bound regions somehow.
1969 // The strategy is to:
1971 // 1. Instantiate those regions to skolemized regions (e.g.,
1972 // `for<'a> &'a int` becomes `&0 int`.
1973 // 2. Produce something like `&'0 int : Copy`
1974 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1976 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
1977 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
1979 self.in_snapshot(|this, snapshot| {
1980 let (skol_ty, skol_map) =
1981 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
1982 let Normalized { value: normalized_ty, mut obligations } =
1983 project::normalize_with_depth(this,
1987 let skol_obligation =
1988 this.tcx().predicate_for_trait_def(
1994 obligations.push(skol_obligation);
1995 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2000 ///////////////////////////////////////////////////////////////////////////
2003 // Confirmation unifies the output type parameters of the trait
2004 // with the values found in the obligation, possibly yielding a
2005 // type error. See `README.md` for more details.
2007 fn confirm_candidate(&mut self,
2008 obligation: &TraitObligation<'tcx>,
2009 candidate: SelectionCandidate<'tcx>)
2010 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2012 debug!("confirm_candidate({:?}, {:?})",
2017 BuiltinCandidate { has_nested } => {
2019 self.confirm_builtin_candidate(obligation, has_nested)))
2022 ParamCandidate(param) => {
2023 let obligations = self.confirm_param_candidate(obligation, param);
2024 Ok(VtableParam(obligations))
2027 DefaultImplCandidate(trait_def_id) => {
2028 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2029 Ok(VtableDefaultImpl(data))
2032 ImplCandidate(impl_def_id) => {
2033 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2036 ClosureCandidate(closure_def_id, substs, kind) => {
2037 let vtable_closure =
2038 self.confirm_closure_candidate(obligation, closure_def_id, substs, kind)?;
2039 Ok(VtableClosure(vtable_closure))
2042 BuiltinObjectCandidate => {
2043 // This indicates something like `(Trait+Send) :
2044 // Send`. In this case, we know that this holds
2045 // because that's what the object type is telling us,
2046 // and there's really no additional obligations to
2047 // prove and no types in particular to unify etc.
2048 Ok(VtableParam(Vec::new()))
2051 ObjectCandidate => {
2052 let data = self.confirm_object_candidate(obligation);
2053 Ok(VtableObject(data))
2056 FnPointerCandidate => {
2058 self.confirm_fn_pointer_candidate(obligation)?;
2059 Ok(VtableFnPointer(data))
2062 ProjectionCandidate => {
2063 self.confirm_projection_candidate(obligation);
2064 Ok(VtableParam(Vec::new()))
2067 BuiltinUnsizeCandidate => {
2068 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2069 Ok(VtableBuiltin(data))
2074 fn confirm_projection_candidate(&mut self,
2075 obligation: &TraitObligation<'tcx>)
2077 self.in_snapshot(|this, snapshot| {
2079 this.match_projection_obligation_against_definition_bounds(obligation,
2085 fn confirm_param_candidate(&mut self,
2086 obligation: &TraitObligation<'tcx>,
2087 param: ty::PolyTraitRef<'tcx>)
2088 -> Vec<PredicateObligation<'tcx>>
2090 debug!("confirm_param_candidate({:?},{:?})",
2094 // During evaluation, we already checked that this
2095 // where-clause trait-ref could be unified with the obligation
2096 // trait-ref. Repeat that unification now without any
2097 // transactional boundary; it should not fail.
2098 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2099 Ok(obligations) => obligations,
2101 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2108 fn confirm_builtin_candidate(&mut self,
2109 obligation: &TraitObligation<'tcx>,
2111 -> VtableBuiltinData<PredicateObligation<'tcx>>
2113 debug!("confirm_builtin_candidate({:?}, {:?})",
2114 obligation, has_nested);
2116 let obligations = if has_nested {
2117 let trait_def = obligation.predicate.def_id();
2118 let conditions = match trait_def {
2119 _ if Some(trait_def) == self.tcx().lang_items.sized_trait() => {
2120 self.sized_conditions(obligation)
2122 _ if Some(trait_def) == self.tcx().lang_items.copy_trait() => {
2123 self.copy_conditions(obligation)
2125 _ => bug!("unexpected builtin trait {:?}", trait_def)
2127 let nested = match conditions {
2128 BuiltinImplConditions::Where(nested) => nested,
2129 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2133 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2134 self.collect_predicates_for_types(cause,
2135 obligation.recursion_depth+1,
2142 debug!("confirm_builtin_candidate: obligations={:?}",
2144 VtableBuiltinData { nested: obligations }
2147 /// This handles the case where a `impl Foo for ..` impl is being used.
2148 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2150 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2151 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2152 fn confirm_default_impl_candidate(&mut self,
2153 obligation: &TraitObligation<'tcx>,
2154 trait_def_id: DefId)
2155 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2157 debug!("confirm_default_impl_candidate({:?}, {:?})",
2161 // binder is moved below
2162 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2163 let types = self.constituent_types_for_ty(self_ty);
2164 self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2167 /// See `confirm_default_impl_candidate`
2168 fn vtable_default_impl(&mut self,
2169 obligation: &TraitObligation<'tcx>,
2170 trait_def_id: DefId,
2171 nested: ty::Binder<Vec<Ty<'tcx>>>)
2172 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2174 debug!("vtable_default_impl: nested={:?}", nested);
2176 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2177 let mut obligations = self.collect_predicates_for_types(
2179 obligation.recursion_depth+1,
2183 let trait_obligations = self.in_snapshot(|this, snapshot| {
2184 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2185 let (trait_ref, skol_map) =
2186 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2187 let cause = obligation.derived_cause(ImplDerivedObligation);
2188 this.impl_or_trait_obligations(cause,
2189 obligation.recursion_depth + 1,
2196 obligations.extend(trait_obligations);
2198 debug!("vtable_default_impl: obligations={:?}", obligations);
2200 VtableDefaultImplData {
2201 trait_def_id: trait_def_id,
2206 fn confirm_impl_candidate(&mut self,
2207 obligation: &TraitObligation<'tcx>,
2209 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2211 debug!("confirm_impl_candidate({:?},{:?})",
2215 // First, create the substitutions by matching the impl again,
2216 // this time not in a probe.
2217 self.in_snapshot(|this, snapshot| {
2218 let (substs, skol_map) =
2219 this.rematch_impl(impl_def_id, obligation,
2221 debug!("confirm_impl_candidate substs={:?}", substs);
2222 let cause = obligation.derived_cause(ImplDerivedObligation);
2223 this.vtable_impl(impl_def_id, substs, cause,
2224 obligation.recursion_depth + 1,
2229 fn vtable_impl(&mut self,
2231 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2232 cause: ObligationCause<'tcx>,
2233 recursion_depth: usize,
2234 skol_map: infer::SkolemizationMap<'tcx>,
2235 snapshot: &infer::CombinedSnapshot)
2236 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2238 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2244 let mut impl_obligations =
2245 self.impl_or_trait_obligations(cause,
2252 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2256 // Because of RFC447, the impl-trait-ref and obligations
2257 // are sufficient to determine the impl substs, without
2258 // relying on projections in the impl-trait-ref.
2260 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2261 impl_obligations.append(&mut substs.obligations);
2263 VtableImplData { impl_def_id: impl_def_id,
2264 substs: substs.value,
2265 nested: impl_obligations }
2268 fn confirm_object_candidate(&mut self,
2269 obligation: &TraitObligation<'tcx>)
2270 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2272 debug!("confirm_object_candidate({:?})",
2275 // FIXME skipping binder here seems wrong -- we should
2276 // probably flatten the binder from the obligation and the
2277 // binder from the object. Have to try to make a broken test
2278 // case that results. -nmatsakis
2279 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2280 let poly_trait_ref = match self_ty.sty {
2281 ty::TyDynamic(ref data, ..) => {
2282 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2285 span_bug!(obligation.cause.span,
2286 "object candidate with non-object");
2290 let mut upcast_trait_ref = None;
2294 let tcx = self.tcx();
2296 // We want to find the first supertrait in the list of
2297 // supertraits that we can unify with, and do that
2298 // unification. We know that there is exactly one in the list
2299 // where we can unify because otherwise select would have
2300 // reported an ambiguity. (When we do find a match, also
2301 // record it for later.)
2303 util::supertraits(tcx, poly_trait_ref)
2307 |this, _| this.match_poly_trait_ref(obligation, t))
2309 Ok(_) => { upcast_trait_ref = Some(t); false }
2314 // Additionally, for each of the nonmatching predicates that
2315 // we pass over, we sum up the set of number of vtable
2316 // entries, so that we can compute the offset for the selected
2319 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2325 upcast_trait_ref: upcast_trait_ref.unwrap(),
2326 vtable_base: vtable_base,
2331 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2332 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2334 debug!("confirm_fn_pointer_candidate({:?})",
2337 // ok to skip binder; it is reintroduced below
2338 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2339 let sig = self_ty.fn_sig();
2341 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2344 util::TupleArgumentsFlag::Yes)
2345 .map_bound(|(trait_ref, _)| trait_ref);
2347 self.confirm_poly_trait_refs(obligation.cause.clone(),
2348 obligation.predicate.to_poly_trait_ref(),
2350 Ok(VtableFnPointerData { fn_ty: self_ty, nested: vec![] })
2353 fn confirm_closure_candidate(&mut self,
2354 obligation: &TraitObligation<'tcx>,
2355 closure_def_id: DefId,
2356 substs: ty::ClosureSubsts<'tcx>,
2357 kind: ty::ClosureKind)
2358 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2359 SelectionError<'tcx>>
2361 debug!("confirm_closure_candidate({:?},{:?},{:?})",
2369 } = self.closure_trait_ref(obligation, closure_def_id, substs);
2371 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2376 self.confirm_poly_trait_refs(obligation.cause.clone(),
2377 obligation.predicate.to_poly_trait_ref(),
2380 obligations.push(Obligation::new(
2381 obligation.cause.clone(),
2382 ty::Predicate::ClosureKind(closure_def_id, kind)));
2384 Ok(VtableClosureData {
2385 closure_def_id: closure_def_id,
2386 substs: substs.clone(),
2391 /// In the case of closure types and fn pointers,
2392 /// we currently treat the input type parameters on the trait as
2393 /// outputs. This means that when we have a match we have only
2394 /// considered the self type, so we have to go back and make sure
2395 /// to relate the argument types too. This is kind of wrong, but
2396 /// since we control the full set of impls, also not that wrong,
2397 /// and it DOES yield better error messages (since we don't report
2398 /// errors as if there is no applicable impl, but rather report
2399 /// errors are about mismatched argument types.
2401 /// Here is an example. Imagine we have a closure expression
2402 /// and we desugared it so that the type of the expression is
2403 /// `Closure`, and `Closure` expects an int as argument. Then it
2404 /// is "as if" the compiler generated this impl:
2406 /// impl Fn(int) for Closure { ... }
2408 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2409 /// we have matched the self-type `Closure`. At this point we'll
2410 /// compare the `int` to `usize` and generate an error.
2412 /// Note that this checking occurs *after* the impl has selected,
2413 /// because these output type parameters should not affect the
2414 /// selection of the impl. Therefore, if there is a mismatch, we
2415 /// report an error to the user.
2416 fn confirm_poly_trait_refs(&mut self,
2417 obligation_cause: ObligationCause<'tcx>,
2418 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2419 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2420 -> Result<(), SelectionError<'tcx>>
2422 let obligation_trait_ref = obligation_trait_ref.clone();
2423 self.infcx.sub_poly_trait_refs(false,
2424 obligation_cause.clone(),
2425 expected_trait_ref.clone(),
2426 obligation_trait_ref.clone())
2427 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2428 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2431 fn confirm_builtin_unsize_candidate(&mut self,
2432 obligation: &TraitObligation<'tcx>,)
2433 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2434 SelectionError<'tcx>> {
2435 let tcx = self.tcx();
2437 // assemble_candidates_for_unsizing should ensure there are no late bound
2438 // regions here. See the comment there for more details.
2439 let source = self.infcx.shallow_resolve(
2440 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2441 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2442 let target = self.infcx.shallow_resolve(target);
2444 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2447 let mut nested = vec![];
2448 match (&source.sty, &target.sty) {
2449 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2450 (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2451 // See assemble_candidates_for_unsizing for more info.
2452 // Binders reintroduced below in call to mk_existential_predicates.
2453 let principal = data_a.skip_binder().principal();
2454 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2455 .chain(data_a.skip_binder().projection_bounds()
2456 .map(|x| ty::ExistentialPredicate::Projection(x)))
2457 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2458 let new_trait = tcx.mk_dynamic(
2459 ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2460 let InferOk { obligations, .. } =
2461 self.infcx.eq_types(false, &obligation.cause, new_trait, target)
2462 .map_err(|_| Unimplemented)?;
2463 self.inferred_obligations.extend(obligations);
2465 // Register one obligation for 'a: 'b.
2466 let cause = ObligationCause::new(obligation.cause.span,
2467 obligation.cause.body_id,
2468 ObjectCastObligation(target));
2469 let outlives = ty::OutlivesPredicate(r_a, r_b);
2470 nested.push(Obligation::with_depth(cause,
2471 obligation.recursion_depth + 1,
2472 ty::Binder(outlives).to_predicate()));
2476 (_, &ty::TyDynamic(ref data, r)) => {
2477 let mut object_dids =
2478 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2479 if let Some(did) = object_dids.find(|did| {
2480 !tcx.is_object_safe(*did)
2482 return Err(TraitNotObjectSafe(did))
2485 let cause = ObligationCause::new(obligation.cause.span,
2486 obligation.cause.body_id,
2487 ObjectCastObligation(target));
2488 let mut push = |predicate| {
2489 nested.push(Obligation::with_depth(cause.clone(),
2490 obligation.recursion_depth + 1,
2494 // Create obligations:
2495 // - Casting T to Trait
2496 // - For all the various builtin bounds attached to the object cast. (In other
2497 // words, if the object type is Foo+Send, this would create an obligation for the
2499 // - Projection predicates
2500 for predicate in data.iter() {
2501 push(predicate.with_self_ty(tcx, source));
2504 // We can only make objects from sized types.
2505 let tr = ty::TraitRef {
2506 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2507 substs: tcx.mk_substs_trait(source, &[]),
2509 push(tr.to_predicate());
2511 // If the type is `Foo+'a`, ensures that the type
2512 // being cast to `Foo+'a` outlives `'a`:
2513 let outlives = ty::OutlivesPredicate(source, r);
2514 push(ty::Binder(outlives).to_predicate());
2518 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2519 let InferOk { obligations, .. } =
2520 self.infcx.eq_types(false, &obligation.cause, a, b)
2521 .map_err(|_| Unimplemented)?;
2522 self.inferred_obligations.extend(obligations);
2525 // Struct<T> -> Struct<U>.
2526 (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2529 .map(|f| tcx.type_of(f.did))
2530 .collect::<Vec<_>>();
2532 // The last field of the structure has to exist and contain type parameters.
2533 let field = if let Some(&field) = fields.last() {
2536 return Err(Unimplemented);
2538 let mut ty_params = BitVector::new(substs_a.types().count());
2539 let mut found = false;
2540 for ty in field.walk() {
2541 if let ty::TyParam(p) = ty.sty {
2542 ty_params.insert(p.idx as usize);
2547 return Err(Unimplemented);
2550 // Replace type parameters used in unsizing with
2551 // TyError and ensure they do not affect any other fields.
2552 // This could be checked after type collection for any struct
2553 // with a potentially unsized trailing field.
2554 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2555 if ty_params.contains(i) {
2556 Kind::from(tcx.types.err)
2561 let substs = tcx.mk_substs(params);
2562 for &ty in fields.split_last().unwrap().1 {
2563 if ty.subst(tcx, substs).references_error() {
2564 return Err(Unimplemented);
2568 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2569 let inner_source = field.subst(tcx, substs_a);
2570 let inner_target = field.subst(tcx, substs_b);
2572 // Check that the source structure with the target's
2573 // type parameters is a subtype of the target.
2574 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2575 if ty_params.contains(i) {
2576 Kind::from(substs_b.type_at(i))
2581 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
2582 let InferOk { obligations, .. } =
2583 self.infcx.eq_types(false, &obligation.cause, new_struct, target)
2584 .map_err(|_| Unimplemented)?;
2585 self.inferred_obligations.extend(obligations);
2587 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2588 nested.push(tcx.predicate_for_trait_def(
2589 obligation.cause.clone(),
2590 obligation.predicate.def_id(),
2591 obligation.recursion_depth + 1,
2599 Ok(VtableBuiltinData { nested: nested })
2602 ///////////////////////////////////////////////////////////////////////////
2605 // Matching is a common path used for both evaluation and
2606 // confirmation. It basically unifies types that appear in impls
2607 // and traits. This does affect the surrounding environment;
2608 // therefore, when used during evaluation, match routines must be
2609 // run inside of a `probe()` so that their side-effects are
2612 fn rematch_impl(&mut self,
2614 obligation: &TraitObligation<'tcx>,
2615 snapshot: &infer::CombinedSnapshot)
2616 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
2617 infer::SkolemizationMap<'tcx>)
2619 match self.match_impl(impl_def_id, obligation, snapshot) {
2620 Ok((substs, skol_map)) => (substs, skol_map),
2622 bug!("Impl {:?} was matchable against {:?} but now is not",
2629 fn match_impl(&mut self,
2631 obligation: &TraitObligation<'tcx>,
2632 snapshot: &infer::CombinedSnapshot)
2633 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
2634 infer::SkolemizationMap<'tcx>), ()>
2636 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2638 // Before we create the substitutions and everything, first
2639 // consider a "quick reject". This avoids creating more types
2640 // and so forth that we need to.
2641 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2645 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2646 &obligation.predicate,
2648 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2650 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
2653 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2656 let impl_trait_ref =
2657 project::normalize_with_depth(self,
2658 obligation.cause.clone(),
2659 obligation.recursion_depth + 1,
2662 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2663 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2667 skol_obligation_trait_ref);
2669 let InferOk { obligations, .. } =
2670 self.infcx.eq_trait_refs(false,
2672 impl_trait_ref.value.clone(),
2673 skol_obligation_trait_ref)
2675 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2678 self.inferred_obligations.extend(obligations);
2680 if let Err(e) = self.infcx.leak_check(false,
2681 obligation.cause.span,
2684 debug!("match_impl: failed leak check due to `{}`", e);
2688 debug!("match_impl: success impl_substs={:?}", impl_substs);
2691 obligations: impl_trait_ref.obligations
2695 fn fast_reject_trait_refs(&mut self,
2696 obligation: &TraitObligation,
2697 impl_trait_ref: &ty::TraitRef)
2700 // We can avoid creating type variables and doing the full
2701 // substitution if we find that any of the input types, when
2702 // simplified, do not match.
2704 obligation.predicate.skip_binder().input_types()
2705 .zip(impl_trait_ref.input_types())
2706 .any(|(obligation_ty, impl_ty)| {
2707 let simplified_obligation_ty =
2708 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2709 let simplified_impl_ty =
2710 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2712 simplified_obligation_ty.is_some() &&
2713 simplified_impl_ty.is_some() &&
2714 simplified_obligation_ty != simplified_impl_ty
2718 /// Normalize `where_clause_trait_ref` and try to match it against
2719 /// `obligation`. If successful, return any predicates that
2720 /// result from the normalization. Normalization is necessary
2721 /// because where-clauses are stored in the parameter environment
2723 fn match_where_clause_trait_ref(&mut self,
2724 obligation: &TraitObligation<'tcx>,
2725 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2726 -> Result<Vec<PredicateObligation<'tcx>>,()>
2728 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
2732 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2733 /// obligation is satisfied.
2734 fn match_poly_trait_ref(&mut self,
2735 obligation: &TraitObligation<'tcx>,
2736 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2739 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2743 self.infcx.sub_poly_trait_refs(false,
2744 obligation.cause.clone(),
2746 obligation.predicate.to_poly_trait_ref())
2747 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2751 ///////////////////////////////////////////////////////////////////////////
2754 fn match_fresh_trait_refs(&self,
2755 previous: &ty::PolyTraitRef<'tcx>,
2756 current: &ty::PolyTraitRef<'tcx>)
2759 let mut matcher = ty::_match::Match::new(self.tcx());
2760 matcher.relate(previous, current).is_ok()
2763 fn push_stack<'o,'s:'o>(&mut self,
2764 previous_stack: TraitObligationStackList<'s, 'tcx>,
2765 obligation: &'o TraitObligation<'tcx>)
2766 -> TraitObligationStack<'o, 'tcx>
2768 let fresh_trait_ref =
2769 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2771 TraitObligationStack {
2772 obligation: obligation,
2773 fresh_trait_ref: fresh_trait_ref,
2774 previous: previous_stack,
2778 fn closure_trait_ref_unnormalized(&mut self,
2779 obligation: &TraitObligation<'tcx>,
2780 closure_def_id: DefId,
2781 substs: ty::ClosureSubsts<'tcx>)
2782 -> ty::PolyTraitRef<'tcx>
2784 let closure_type = self.infcx.closure_type(closure_def_id)
2785 .subst(self.tcx(), substs.substs);
2786 let ty::Binder((trait_ref, _)) =
2787 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2788 obligation.predicate.0.self_ty(), // (1)
2790 util::TupleArgumentsFlag::No);
2791 // (1) Feels icky to skip the binder here, but OTOH we know
2792 // that the self-type is an unboxed closure type and hence is
2793 // in fact unparameterized (or at least does not reference any
2794 // regions bound in the obligation). Still probably some
2795 // refactoring could make this nicer.
2797 ty::Binder(trait_ref)
2800 fn closure_trait_ref(&mut self,
2801 obligation: &TraitObligation<'tcx>,
2802 closure_def_id: DefId,
2803 substs: ty::ClosureSubsts<'tcx>)
2804 -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
2806 let trait_ref = self.closure_trait_ref_unnormalized(
2807 obligation, closure_def_id, substs);
2809 // A closure signature can contain associated types which
2810 // must be normalized.
2811 normalize_with_depth(self,
2812 obligation.cause.clone(),
2813 obligation.recursion_depth+1,
2817 /// Returns the obligations that are implied by instantiating an
2818 /// impl or trait. The obligations are substituted and fully
2819 /// normalized. This is used when confirming an impl or default
2821 fn impl_or_trait_obligations(&mut self,
2822 cause: ObligationCause<'tcx>,
2823 recursion_depth: usize,
2824 def_id: DefId, // of impl or trait
2825 substs: &Substs<'tcx>, // for impl or trait
2826 skol_map: infer::SkolemizationMap<'tcx>,
2827 snapshot: &infer::CombinedSnapshot)
2828 -> Vec<PredicateObligation<'tcx>>
2830 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2831 let tcx = self.tcx();
2833 // To allow for one-pass evaluation of the nested obligation,
2834 // each predicate must be preceded by the obligations required
2836 // for example, if we have:
2837 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2838 // the impl will have the following predicates:
2839 // <V as Iterator>::Item = U,
2840 // U: Iterator, U: Sized,
2841 // V: Iterator, V: Sized,
2842 // <U as Iterator>::Item: Copy
2843 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2844 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2845 // `$1: Copy`, so we must ensure the obligations are emitted in
2847 let predicates = tcx.predicates_of(def_id);
2848 assert_eq!(predicates.parent, None);
2849 let predicates = predicates.predicates.iter().flat_map(|predicate| {
2850 let predicate = normalize_with_depth(self, cause.clone(), recursion_depth,
2851 &predicate.subst(tcx, substs));
2852 predicate.obligations.into_iter().chain(
2854 cause: cause.clone(),
2855 recursion_depth: recursion_depth,
2856 predicate: predicate.value
2859 self.infcx().plug_leaks(skol_map, snapshot, predicates)
2863 impl<'tcx> TraitObligation<'tcx> {
2864 #[allow(unused_comparisons)]
2865 pub fn derived_cause(&self,
2866 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2867 -> ObligationCause<'tcx>
2870 * Creates a cause for obligations that are derived from
2871 * `obligation` by a recursive search (e.g., for a builtin
2872 * bound, or eventually a `impl Foo for ..`). If `obligation`
2873 * is itself a derived obligation, this is just a clone, but
2874 * otherwise we create a "derived obligation" cause so as to
2875 * keep track of the original root obligation for error
2879 let obligation = self;
2881 // NOTE(flaper87): As of now, it keeps track of the whole error
2882 // chain. Ideally, we should have a way to configure this either
2883 // by using -Z verbose or just a CLI argument.
2884 if obligation.recursion_depth >= 0 {
2885 let derived_cause = DerivedObligationCause {
2886 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2887 parent_code: Rc::new(obligation.cause.code.clone())
2889 let derived_code = variant(derived_cause);
2890 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2892 obligation.cause.clone()
2897 impl<'tcx> SelectionCache<'tcx> {
2898 pub fn new() -> SelectionCache<'tcx> {
2900 hashmap: RefCell::new(FxHashMap())
2905 impl<'tcx> EvaluationCache<'tcx> {
2906 pub fn new() -> EvaluationCache<'tcx> {
2908 hashmap: RefCell::new(FxHashMap())
2913 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
2914 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
2915 TraitObligationStackList::with(self)
2918 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
2923 #[derive(Copy, Clone)]
2924 struct TraitObligationStackList<'o,'tcx:'o> {
2925 head: Option<&'o TraitObligationStack<'o,'tcx>>
2928 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
2929 fn empty() -> TraitObligationStackList<'o,'tcx> {
2930 TraitObligationStackList { head: None }
2933 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
2934 TraitObligationStackList { head: Some(r) }
2938 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
2939 type Item = &'o TraitObligationStack<'o,'tcx>;
2941 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
2952 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
2953 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2954 write!(f, "TraitObligationStack({:?})", self.obligation)
2958 impl EvaluationResult {
2959 fn may_apply(&self) -> bool {
2963 EvaluatedToUnknown => true,
2965 EvaluatedToErr => false