1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See `README.md` for high-level documentation
13 pub use self::MethodMatchResult::*;
14 pub use self::MethodMatchedData::*;
15 use self::SelectionCandidate::*;
16 use self::EvaluationResult::*;
19 use super::DerivedObligationCause;
21 use super::project::{normalize_with_depth, Normalized};
22 use super::{PredicateObligation, TraitObligation, ObligationCause};
23 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
24 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
25 use super::{ObjectCastObligation, Obligation};
27 use super::TraitNotObjectSafe;
29 use super::SelectionResult;
30 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure,
31 VtableFnPointer, VtableObject, VtableDefaultImpl};
32 use super::{VtableImplData, VtableObjectData, VtableBuiltinData,
33 VtableClosureData, VtableDefaultImplData, VtableFnPointerData};
36 use hir::def_id::DefId;
38 use infer::{InferCtxt, InferOk, TypeFreshener};
39 use ty::subst::{Kind, Subst, Substs};
40 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
43 use ty::relate::TypeRelation;
44 use middle::lang_items;
46 use rustc_data_structures::bitvec::BitVector;
47 use rustc_data_structures::snapshot_vec::{SnapshotVecDelegate, SnapshotVec};
48 use std::cell::RefCell;
50 use std::marker::PhantomData;
56 use util::nodemap::FxHashMap;
58 struct InferredObligationsSnapshotVecDelegate<'tcx> {
59 phantom: PhantomData<&'tcx i32>,
61 impl<'tcx> SnapshotVecDelegate for InferredObligationsSnapshotVecDelegate<'tcx> {
62 type Value = PredicateObligation<'tcx>;
64 fn reverse(_: &mut Vec<Self::Value>, _: Self::Undo) {}
67 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
68 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
70 /// Freshener used specifically for skolemizing entries on the
71 /// obligation stack. This ensures that all entries on the stack
72 /// at one time will have the same set of skolemized entries,
73 /// which is important for checking for trait bounds that
74 /// recursively require themselves.
75 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
77 /// If true, indicates that the evaluation should be conservative
78 /// and consider the possibility of types outside this crate.
79 /// This comes up primarily when resolving ambiguity. Imagine
80 /// there is some trait reference `$0 : Bar` where `$0` is an
81 /// inference variable. If `intercrate` is true, then we can never
82 /// say for sure that this reference is not implemented, even if
83 /// there are *no impls at all for `Bar`*, because `$0` could be
84 /// bound to some type that in a downstream crate that implements
85 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
86 /// though, we set this to false, because we are only interested
87 /// in types that the user could actually have written --- in
88 /// other words, we consider `$0 : Bar` to be unimplemented if
89 /// there is no type that the user could *actually name* that
90 /// would satisfy it. This avoids crippling inference, basically.
93 inferred_obligations: SnapshotVec<InferredObligationsSnapshotVecDelegate<'tcx>>,
96 // A stack that walks back up the stack frame.
97 struct TraitObligationStack<'prev, 'tcx: 'prev> {
98 obligation: &'prev TraitObligation<'tcx>,
100 /// Trait ref from `obligation` but skolemized with the
101 /// selection-context's freshener. Used to check for recursion.
102 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
104 previous: TraitObligationStackList<'prev, 'tcx>,
108 pub struct SelectionCache<'tcx> {
109 hashmap: RefCell<FxHashMap<ty::TraitRef<'tcx>,
110 SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
113 pub enum MethodMatchResult {
114 MethodMatched(MethodMatchedData),
115 MethodAmbiguous(/* list of impls that could apply */ Vec<DefId>),
119 #[derive(Copy, Clone, Debug)]
120 pub enum MethodMatchedData {
121 // In the case of a precise match, we don't really need to store
122 // how the match was found. So don't.
125 // In the case of a coercion, we need to know the precise impl so
126 // that we can determine the type to which things were coerced.
127 CoerciveMethodMatch(/* impl we matched */ DefId)
130 /// The selection process begins by considering all impls, where
131 /// clauses, and so forth that might resolve an obligation. Sometimes
132 /// we'll be able to say definitively that (e.g.) an impl does not
133 /// apply to the obligation: perhaps it is defined for `usize` but the
134 /// obligation is for `int`. In that case, we drop the impl out of the
135 /// list. But the other cases are considered *candidates*.
137 /// For selection to succeed, there must be exactly one matching
138 /// candidate. If the obligation is fully known, this is guaranteed
139 /// by coherence. However, if the obligation contains type parameters
140 /// or variables, there may be multiple such impls.
142 /// It is not a real problem if multiple matching impls exist because
143 /// of type variables - it just means the obligation isn't sufficiently
144 /// elaborated. In that case we report an ambiguity, and the caller can
145 /// try again after more type information has been gathered or report a
146 /// "type annotations required" error.
148 /// However, with type parameters, this can be a real problem - type
149 /// parameters don't unify with regular types, but they *can* unify
150 /// with variables from blanket impls, and (unless we know its bounds
151 /// will always be satisfied) picking the blanket impl will be wrong
152 /// for at least *some* substitutions. To make this concrete, if we have
154 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
155 /// impl<T: fmt::Debug> AsDebug for T {
157 /// fn debug(self) -> fmt::Debug { self }
159 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
161 /// we can't just use the impl to resolve the <T as AsDebug> obligation
162 /// - a type from another crate (that doesn't implement fmt::Debug) could
163 /// implement AsDebug.
165 /// Because where-clauses match the type exactly, multiple clauses can
166 /// only match if there are unresolved variables, and we can mostly just
167 /// report this ambiguity in that case. This is still a problem - we can't
168 /// *do anything* with ambiguities that involve only regions. This is issue
171 /// If a single where-clause matches and there are no inference
172 /// variables left, then it definitely matches and we can just select
175 /// In fact, we even select the where-clause when the obligation contains
176 /// inference variables. The can lead to inference making "leaps of logic",
177 /// for example in this situation:
179 /// pub trait Foo<T> { fn foo(&self) -> T; }
180 /// impl<T> Foo<()> for T { fn foo(&self) { } }
181 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
183 /// pub fn foo<T>(t: T) where T: Foo<bool> {
184 /// println!("{:?}", <T as Foo<_>>::foo(&t));
186 /// fn main() { foo(false); }
188 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
189 /// impl and the where-clause. We select the where-clause and unify $0=bool,
190 /// so the program prints "false". However, if the where-clause is omitted,
191 /// the blanket impl is selected, we unify $0=(), and the program prints
194 /// Exactly the same issues apply to projection and object candidates, except
195 /// that we can have both a projection candidate and a where-clause candidate
196 /// for the same obligation. In that case either would do (except that
197 /// different "leaps of logic" would occur if inference variables are
198 /// present), and we just pick the where-clause. This is, for example,
199 /// required for associated types to work in default impls, as the bounds
200 /// are visible both as projection bounds and as where-clauses from the
201 /// parameter environment.
202 #[derive(PartialEq,Eq,Debug,Clone)]
203 enum SelectionCandidate<'tcx> {
204 BuiltinCandidate { has_nested: bool },
205 ParamCandidate(ty::PolyTraitRef<'tcx>),
206 ImplCandidate(DefId),
207 DefaultImplCandidate(DefId),
209 /// This is a trait matching with a projected type as `Self`, and
210 /// we found an applicable bound in the trait definition.
213 /// Implementation of a `Fn`-family trait by one of the anonymous types
214 /// generated for a `||` expression. The ty::ClosureKind informs the
215 /// confirmation step what ClosureKind obligation to emit.
216 ClosureCandidate(/* closure */ DefId, ty::ClosureSubsts<'tcx>, ty::ClosureKind),
218 /// Implementation of a `Fn`-family trait by one of the anonymous
219 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
224 BuiltinObjectCandidate,
226 BuiltinUnsizeCandidate,
229 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
230 type Lifted = SelectionCandidate<'tcx>;
231 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
233 BuiltinCandidate { has_nested } => {
235 has_nested: has_nested
238 ImplCandidate(def_id) => ImplCandidate(def_id),
239 DefaultImplCandidate(def_id) => DefaultImplCandidate(def_id),
240 ProjectionCandidate => ProjectionCandidate,
241 FnPointerCandidate => FnPointerCandidate,
242 ObjectCandidate => ObjectCandidate,
243 BuiltinObjectCandidate => BuiltinObjectCandidate,
244 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
246 ParamCandidate(ref trait_ref) => {
247 return tcx.lift(trait_ref).map(ParamCandidate);
249 ClosureCandidate(def_id, ref substs, kind) => {
250 return tcx.lift(substs).map(|substs| {
251 ClosureCandidate(def_id, substs, kind)
258 struct SelectionCandidateSet<'tcx> {
259 // a list of candidates that definitely apply to the current
260 // obligation (meaning: types unify).
261 vec: Vec<SelectionCandidate<'tcx>>,
263 // if this is true, then there were candidates that might or might
264 // not have applied, but we couldn't tell. This occurs when some
265 // of the input types are type variables, in which case there are
266 // various "builtin" rules that might or might not trigger.
270 #[derive(PartialEq,Eq,Debug,Clone)]
271 struct EvaluatedCandidate<'tcx> {
272 candidate: SelectionCandidate<'tcx>,
273 evaluation: EvaluationResult,
276 /// When does the builtin impl for `T: Trait` apply?
277 enum BuiltinImplConditions<'tcx> {
278 /// The impl is conditional on T1,T2,.. : Trait
279 Where(ty::Binder<Vec<Ty<'tcx>>>),
280 /// There is no built-in impl. There may be some other
281 /// candidate (a where-clause or user-defined impl).
283 /// There is *no* impl for this, builtin or not. Ignore
284 /// all where-clauses.
286 /// It is unknown whether there is an impl.
290 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
291 /// The result of trait evaluation. The order is important
292 /// here as the evaluation of a list is the maximum of the
294 enum EvaluationResult {
295 /// Evaluation successful
297 /// Evaluation failed because of recursion - treated as ambiguous
299 /// Evaluation is known to be ambiguous
301 /// Evaluation failed
306 pub struct EvaluationCache<'tcx> {
307 hashmap: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, EvaluationResult>>
310 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
311 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
314 freshener: infcx.freshener(),
316 inferred_obligations: SnapshotVec::new(),
320 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
323 freshener: infcx.freshener(),
325 inferred_obligations: SnapshotVec::new(),
329 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
333 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
337 pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'gcx> {
338 self.infcx.param_env()
341 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
345 pub fn projection_mode(&self) -> Reveal {
346 self.infcx.projection_mode()
349 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
351 fn in_snapshot<R, F>(&mut self, f: F) -> R
352 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
354 // The irrefutable nature of the operation means we don't need to snapshot the
355 // inferred_obligations vector.
356 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
359 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
361 fn probe<R, F>(&mut self, f: F) -> R
362 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
364 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
365 let result = self.infcx.probe(|snapshot| f(self, snapshot));
366 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
370 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
371 /// the transaction fails and s.t. old obligations are retained.
372 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
373 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
375 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
376 match self.infcx.commit_if_ok(|snapshot| f(self, snapshot)) {
378 self.inferred_obligations.commit(inferred_obligations_snapshot);
382 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
389 ///////////////////////////////////////////////////////////////////////////
392 // The selection phase tries to identify *how* an obligation will
393 // be resolved. For example, it will identify which impl or
394 // parameter bound is to be used. The process can be inconclusive
395 // if the self type in the obligation is not fully inferred. Selection
396 // can result in an error in one of two ways:
398 // 1. If no applicable impl or parameter bound can be found.
399 // 2. If the output type parameters in the obligation do not match
400 // those specified by the impl/bound. For example, if the obligation
401 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
402 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
404 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
405 /// type environment by performing unification.
406 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
407 -> SelectionResult<'tcx, Selection<'tcx>> {
408 debug!("select({:?})", obligation);
409 assert!(!obligation.predicate.has_escaping_regions());
411 let tcx = self.tcx();
412 let dep_node = obligation.predicate.dep_node();
413 let _task = tcx.dep_graph.in_task(dep_node);
415 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
416 let ret = match self.candidate_from_obligation(&stack)? {
419 let mut candidate = self.confirm_candidate(obligation, candidate)?;
420 let inferred_obligations = (*self.inferred_obligations).into_iter().cloned();
421 candidate.nested_obligations_mut().extend(inferred_obligations);
426 // Test whether this is a `()` which was produced by defaulting a
427 // diverging type variable with `!` disabled. If so, we may need
428 // to raise a warning.
429 if obligation.predicate.skip_binder().self_ty().is_defaulted_unit() {
430 let mut raise_warning = true;
431 // Don't raise a warning if the trait is implemented for ! and only
432 // permits a trivial implementation for !. This stops us warning
433 // about (for example) `(): Clone` becoming `!: Clone` because such
434 // a switch can't cause code to stop compiling or execute
436 let mut never_obligation = obligation.clone();
437 let def_id = never_obligation.predicate.skip_binder().trait_ref.def_id;
438 never_obligation.predicate = never_obligation.predicate.map_bound(|mut trait_pred| {
439 // Swap out () with ! so we can check if the trait is impld for !
441 let mut trait_ref = &mut trait_pred.trait_ref;
442 let unit_substs = trait_ref.substs;
443 let mut never_substs = Vec::with_capacity(unit_substs.len());
444 never_substs.push(From::from(tcx.types.never));
445 never_substs.extend(&unit_substs[1..]);
446 trait_ref.substs = tcx.intern_substs(&never_substs);
450 if let Ok(Some(..)) = self.select(&never_obligation) {
451 if !tcx.trait_relevant_for_never(def_id) {
452 // The trait is also implemented for ! and the resulting
453 // implementation cannot actually be invoked in any way.
454 raise_warning = false;
459 tcx.sess.add_lint(lint::builtin::RESOLVE_TRAIT_ON_DEFAULTED_UNIT,
460 obligation.cause.body_id,
461 obligation.cause.span,
462 format!("code relies on type inference rules which are likely \
469 ///////////////////////////////////////////////////////////////////////////
472 // Tests whether an obligation can be selected or whether an impl
473 // can be applied to particular types. It skips the "confirmation"
474 // step and hence completely ignores output type parameters.
476 // The result is "true" if the obligation *may* hold and "false" if
477 // we can be sure it does not.
479 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
480 pub fn evaluate_obligation(&mut self,
481 obligation: &PredicateObligation<'tcx>)
484 debug!("evaluate_obligation({:?})",
487 self.probe(|this, _| {
488 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
493 /// Evaluates whether the obligation `obligation` can be satisfied,
494 /// and returns `false` if not certain. However, this is not entirely
495 /// accurate if inference variables are involved.
496 pub fn evaluate_obligation_conservatively(&mut self,
497 obligation: &PredicateObligation<'tcx>)
500 debug!("evaluate_obligation_conservatively({:?})",
503 self.probe(|this, _| {
504 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
509 /// Evaluates the predicates in `predicates` recursively. Note that
510 /// this applies projections in the predicates, and therefore
511 /// is run within an inference probe.
512 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
513 stack: TraitObligationStackList<'o, 'tcx>,
516 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
518 let mut result = EvaluatedToOk;
519 for obligation in predicates {
520 let eval = self.evaluate_predicate_recursively(stack, obligation);
521 debug!("evaluate_predicate_recursively({:?}) = {:?}",
524 EvaluatedToErr => { return EvaluatedToErr; }
525 EvaluatedToAmbig => { result = EvaluatedToAmbig; }
526 EvaluatedToUnknown => {
527 if result < EvaluatedToUnknown {
528 result = EvaluatedToUnknown;
537 fn evaluate_predicate_recursively<'o>(&mut self,
538 previous_stack: TraitObligationStackList<'o, 'tcx>,
539 obligation: &PredicateObligation<'tcx>)
542 debug!("evaluate_predicate_recursively({:?})",
545 // Check the cache from the tcx of predicates that we know
546 // have been proven elsewhere. This cache only contains
547 // predicates that are global in scope and hence unaffected by
548 // the current environment.
549 if self.tcx().fulfilled_predicates.borrow().check_duplicate(&obligation.predicate) {
550 return EvaluatedToOk;
553 match obligation.predicate {
554 ty::Predicate::Trait(ref t) => {
555 assert!(!t.has_escaping_regions());
556 let obligation = obligation.with(t.clone());
557 self.evaluate_obligation_recursively(previous_stack, &obligation)
560 ty::Predicate::Equate(ref p) => {
561 // does this code ever run?
562 match self.infcx.equality_predicate(&obligation.cause, p) {
563 Ok(InferOk { obligations, .. }) => {
564 self.inferred_obligations.extend(obligations);
567 Err(_) => EvaluatedToErr
571 ty::Predicate::Subtype(ref p) => {
572 // does this code ever run?
573 match self.infcx.subtype_predicate(&obligation.cause, p) {
574 Some(Ok(InferOk { obligations, .. })) => {
575 self.inferred_obligations.extend(obligations);
578 Some(Err(_)) => EvaluatedToErr,
579 None => EvaluatedToAmbig,
583 ty::Predicate::WellFormed(ty) => {
584 match ty::wf::obligations(self.infcx, obligation.cause.body_id,
585 ty, obligation.cause.span) {
587 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
593 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
594 // we do not consider region relationships when
595 // evaluating trait matches
599 ty::Predicate::ObjectSafe(trait_def_id) => {
600 if self.tcx().is_object_safe(trait_def_id) {
607 ty::Predicate::Projection(ref data) => {
608 let project_obligation = obligation.with(data.clone());
609 match project::poly_project_and_unify_type(self, &project_obligation) {
610 Ok(Some(subobligations)) => {
611 self.evaluate_predicates_recursively(previous_stack,
612 subobligations.iter())
623 ty::Predicate::ClosureKind(closure_def_id, kind) => {
624 match self.infcx.closure_kind(closure_def_id) {
625 Some(closure_kind) => {
626 if closure_kind.extends(kind) {
640 fn evaluate_obligation_recursively<'o>(&mut self,
641 previous_stack: TraitObligationStackList<'o, 'tcx>,
642 obligation: &TraitObligation<'tcx>)
645 debug!("evaluate_obligation_recursively({:?})",
648 let stack = self.push_stack(previous_stack, obligation);
649 let fresh_trait_ref = stack.fresh_trait_ref;
650 if let Some(result) = self.check_evaluation_cache(fresh_trait_ref) {
651 debug!("CACHE HIT: EVAL({:?})={:?}",
657 let result = self.evaluate_stack(&stack);
659 debug!("CACHE MISS: EVAL({:?})={:?}",
662 self.insert_evaluation_cache(fresh_trait_ref, result);
667 fn evaluate_stack<'o>(&mut self,
668 stack: &TraitObligationStack<'o, 'tcx>)
671 // In intercrate mode, whenever any of the types are unbound,
672 // there can always be an impl. Even if there are no impls in
673 // this crate, perhaps the type would be unified with
674 // something from another crate that does provide an impl.
676 // In intra mode, we must still be conservative. The reason is
677 // that we want to avoid cycles. Imagine an impl like:
679 // impl<T:Eq> Eq for Vec<T>
681 // and a trait reference like `$0 : Eq` where `$0` is an
682 // unbound variable. When we evaluate this trait-reference, we
683 // will unify `$0` with `Vec<$1>` (for some fresh variable
684 // `$1`), on the condition that `$1 : Eq`. We will then wind
685 // up with many candidates (since that are other `Eq` impls
686 // that apply) and try to winnow things down. This results in
687 // a recursive evaluation that `$1 : Eq` -- as you can
688 // imagine, this is just where we started. To avoid that, we
689 // check for unbound variables and return an ambiguous (hence possible)
690 // match if we've seen this trait before.
692 // This suffices to allow chains like `FnMut` implemented in
693 // terms of `Fn` etc, but we could probably make this more
695 let unbound_input_types = stack.fresh_trait_ref.input_types().any(|ty| ty.is_fresh());
696 if unbound_input_types && self.intercrate {
697 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
698 stack.fresh_trait_ref);
699 return EvaluatedToAmbig;
701 if unbound_input_types &&
702 stack.iter().skip(1).any(
703 |prev| self.match_fresh_trait_refs(&stack.fresh_trait_ref,
704 &prev.fresh_trait_ref))
706 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
707 stack.fresh_trait_ref);
708 return EvaluatedToUnknown;
711 // If there is any previous entry on the stack that precisely
712 // matches this obligation, then we can assume that the
713 // obligation is satisfied for now (still all other conditions
714 // must be met of course). One obvious case this comes up is
715 // marker traits like `Send`. Think of a linked list:
717 // struct List<T> { data: T, next: Option<Box<List<T>>> {
719 // `Box<List<T>>` will be `Send` if `T` is `Send` and
720 // `Option<Box<List<T>>>` is `Send`, and in turn
721 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
724 // Note that we do this comparison using the `fresh_trait_ref`
725 // fields. Because these have all been skolemized using
726 // `self.freshener`, we can be sure that (a) this will not
727 // affect the inferencer state and (b) that if we see two
728 // skolemized types with the same index, they refer to the
729 // same unbound type variable.
732 .skip(1) // skip top-most frame
733 .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref)
735 debug!("evaluate_stack({:?}) --> recursive",
736 stack.fresh_trait_ref);
737 return EvaluatedToOk;
740 match self.candidate_from_obligation(stack) {
741 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
742 Ok(None) => EvaluatedToAmbig,
743 Err(..) => EvaluatedToErr
747 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
748 /// obligations are met. Returns true if `candidate` remains viable after this further
750 fn evaluate_candidate<'o>(&mut self,
751 stack: &TraitObligationStack<'o, 'tcx>,
752 candidate: &SelectionCandidate<'tcx>)
755 debug!("evaluate_candidate: depth={} candidate={:?}",
756 stack.obligation.recursion_depth, candidate);
757 let result = self.probe(|this, _| {
758 let candidate = (*candidate).clone();
759 match this.confirm_candidate(stack.obligation, candidate) {
761 this.evaluate_predicates_recursively(
763 selection.nested_obligations().iter())
765 Err(..) => EvaluatedToErr
768 debug!("evaluate_candidate: depth={} result={:?}",
769 stack.obligation.recursion_depth, result);
773 fn check_evaluation_cache(&self, trait_ref: ty::PolyTraitRef<'tcx>)
774 -> Option<EvaluationResult>
776 if self.can_use_global_caches() {
777 let cache = self.tcx().evaluation_cache.hashmap.borrow();
778 if let Some(cached) = cache.get(&trait_ref) {
779 return Some(cached.clone());
782 self.infcx.evaluation_cache.hashmap.borrow().get(&trait_ref).cloned()
785 fn insert_evaluation_cache(&mut self,
786 trait_ref: ty::PolyTraitRef<'tcx>,
787 result: EvaluationResult)
789 // Avoid caching results that depend on more than just the trait-ref:
790 // The stack can create EvaluatedToUnknown, and closure signatures
791 // being yet uninferred can create "spurious" EvaluatedToAmbig
792 // and EvaluatedToOk.
793 if result == EvaluatedToUnknown ||
794 ((result == EvaluatedToAmbig || result == EvaluatedToOk)
795 && trait_ref.has_closure_types())
800 if self.can_use_global_caches() {
801 let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
802 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
803 cache.insert(trait_ref, result);
808 self.infcx.evaluation_cache.hashmap.borrow_mut().insert(trait_ref, result);
811 ///////////////////////////////////////////////////////////////////////////
812 // CANDIDATE ASSEMBLY
814 // The selection process begins by examining all in-scope impls,
815 // caller obligations, and so forth and assembling a list of
816 // candidates. See `README.md` and the `Candidate` type for more
819 fn candidate_from_obligation<'o>(&mut self,
820 stack: &TraitObligationStack<'o, 'tcx>)
821 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
823 // Watch out for overflow. This intentionally bypasses (and does
824 // not update) the cache.
825 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
826 if stack.obligation.recursion_depth >= recursion_limit {
827 self.infcx().report_overflow_error(&stack.obligation, true);
830 // Check the cache. Note that we skolemize the trait-ref
831 // separately rather than using `stack.fresh_trait_ref` -- this
832 // is because we want the unbound variables to be replaced
833 // with fresh skolemized types starting from index 0.
834 let cache_fresh_trait_pred =
835 self.infcx.freshen(stack.obligation.predicate.clone());
836 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
837 cache_fresh_trait_pred,
839 assert!(!stack.obligation.predicate.has_escaping_regions());
841 if let Some(c) = self.check_candidate_cache(&cache_fresh_trait_pred) {
842 debug!("CACHE HIT: SELECT({:?})={:?}",
843 cache_fresh_trait_pred,
848 // If no match, compute result and insert into cache.
849 let candidate = self.candidate_from_obligation_no_cache(stack);
851 if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
852 debug!("CACHE MISS: SELECT({:?})={:?}",
853 cache_fresh_trait_pred, candidate);
854 self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone());
860 // Treat negative impls as unimplemented
861 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
862 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
863 if let ImplCandidate(def_id) = candidate {
864 if self.tcx().trait_impl_polarity(def_id) == hir::ImplPolarity::Negative {
865 return Err(Unimplemented)
871 fn candidate_from_obligation_no_cache<'o>(&mut self,
872 stack: &TraitObligationStack<'o, 'tcx>)
873 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
875 if stack.obligation.predicate.references_error() {
876 // If we encounter a `TyError`, we generally prefer the
877 // most "optimistic" result in response -- that is, the
878 // one least likely to report downstream errors. But
879 // because this routine is shared by coherence and by
880 // trait selection, there isn't an obvious "right" choice
881 // here in that respect, so we opt to just return
882 // ambiguity and let the upstream clients sort it out.
886 if !self.is_knowable(stack) {
887 debug!("coherence stage: not knowable");
891 let candidate_set = self.assemble_candidates(stack)?;
893 if candidate_set.ambiguous {
894 debug!("candidate set contains ambig");
898 let mut candidates = candidate_set.vec;
900 debug!("assembled {} candidates for {:?}: {:?}",
905 // At this point, we know that each of the entries in the
906 // candidate set is *individually* applicable. Now we have to
907 // figure out if they contain mutual incompatibilities. This
908 // frequently arises if we have an unconstrained input type --
909 // for example, we are looking for $0:Eq where $0 is some
910 // unconstrained type variable. In that case, we'll get a
911 // candidate which assumes $0 == int, one that assumes $0 ==
912 // usize, etc. This spells an ambiguity.
914 // If there is more than one candidate, first winnow them down
915 // by considering extra conditions (nested obligations and so
916 // forth). We don't winnow if there is exactly one
917 // candidate. This is a relatively minor distinction but it
918 // can lead to better inference and error-reporting. An
919 // example would be if there was an impl:
921 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
923 // and we were to see some code `foo.push_clone()` where `boo`
924 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
925 // we were to winnow, we'd wind up with zero candidates.
926 // Instead, we select the right impl now but report `Bar does
927 // not implement Clone`.
928 if candidates.len() == 1 {
929 return self.filter_negative_impls(candidates.pop().unwrap());
932 // Winnow, but record the exact outcome of evaluation, which
933 // is needed for specialization.
934 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
935 let eval = self.evaluate_candidate(stack, &c);
936 if eval.may_apply() {
937 Some(EvaluatedCandidate {
946 // If there are STILL multiple candidate, we can further
947 // reduce the list by dropping duplicates -- including
948 // resolving specializations.
949 if candidates.len() > 1 {
951 while i < candidates.len() {
953 (0..candidates.len())
955 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
958 debug!("Dropping candidate #{}/{}: {:?}",
959 i, candidates.len(), candidates[i]);
960 candidates.swap_remove(i);
962 debug!("Retaining candidate #{}/{}: {:?}",
963 i, candidates.len(), candidates[i]);
969 // If there are *STILL* multiple candidates, give up and
971 if candidates.len() > 1 {
972 debug!("multiple matches, ambig");
976 // If there are *NO* candidates, then there are no impls --
977 // that we know of, anyway. Note that in the case where there
978 // are unbound type variables within the obligation, it might
979 // be the case that you could still satisfy the obligation
980 // from another crate by instantiating the type variables with
981 // a type from another crate that does have an impl. This case
982 // is checked for in `evaluate_stack` (and hence users
983 // who might care about this case, like coherence, should use
985 if candidates.is_empty() {
986 return Err(Unimplemented);
989 // Just one candidate left.
990 self.filter_negative_impls(candidates.pop().unwrap().candidate)
993 fn is_knowable<'o>(&mut self,
994 stack: &TraitObligationStack<'o, 'tcx>)
997 debug!("is_knowable(intercrate={})", self.intercrate);
999 if !self.intercrate {
1003 let obligation = &stack.obligation;
1004 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1006 // ok to skip binder because of the nature of the
1007 // trait-ref-is-knowable check, which does not care about
1009 let trait_ref = &predicate.skip_binder().trait_ref;
1011 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1014 /// Returns true if the global caches can be used.
1015 /// Do note that if the type itself is not in the
1016 /// global tcx, the local caches will be used.
1017 fn can_use_global_caches(&self) -> bool {
1018 // If there are any where-clauses in scope, then we always use
1019 // a cache local to this particular scope. Otherwise, we
1020 // switch to a global cache. We used to try and draw
1021 // finer-grained distinctions, but that led to a serious of
1022 // annoying and weird bugs like #22019 and #18290. This simple
1023 // rule seems to be pretty clearly safe and also still retains
1024 // a very high hit rate (~95% when compiling rustc).
1025 if !self.param_env().caller_bounds.is_empty() {
1029 // Avoid using the master cache during coherence and just rely
1030 // on the local cache. This effectively disables caching
1031 // during coherence. It is really just a simplification to
1032 // avoid us having to fear that coherence results "pollute"
1033 // the master cache. Since coherence executes pretty quickly,
1034 // it's not worth going to more trouble to increase the
1035 // hit-rate I don't think.
1036 if self.intercrate {
1040 // Otherwise, we can use the global cache.
1044 fn check_candidate_cache(&mut self,
1045 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1046 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1048 let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1049 if self.can_use_global_caches() {
1050 let cache = self.tcx().selection_cache.hashmap.borrow();
1051 if let Some(cached) = cache.get(&trait_ref) {
1052 return Some(cached.clone());
1055 self.infcx.selection_cache.hashmap.borrow().get(trait_ref).cloned()
1058 fn insert_candidate_cache(&mut self,
1059 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1060 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1062 let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1063 if self.can_use_global_caches() {
1064 let mut cache = self.tcx().selection_cache.hashmap.borrow_mut();
1065 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1066 if let Some(candidate) = self.tcx().lift_to_global(&candidate) {
1067 cache.insert(trait_ref, candidate);
1073 self.infcx.selection_cache.hashmap.borrow_mut().insert(trait_ref, candidate);
1076 fn should_update_candidate_cache(&mut self,
1077 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1078 candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1081 // In general, it's a good idea to cache results, even
1082 // ambiguous ones, to save us some trouble later. But we have
1083 // to be careful not to cache results that could be
1084 // invalidated later by advances in inference. Normally, this
1085 // is not an issue, because any inference variables whose
1086 // types are not yet bound are "freshened" in the cache key,
1087 // which means that if we later get the same request once that
1088 // type variable IS bound, we'll have a different cache key.
1089 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
1090 // not yet known, we may cache the result as `None`. But if
1091 // later `_#0t` is bound to `Bar`, then when we freshen we'll
1092 // have `Vec<Bar> : Foo` as the cache key.
1094 // HOWEVER, it CAN happen that we get an ambiguity result in
1095 // one particular case around closures where the cache key
1096 // would not change. That is when the precise types of the
1097 // upvars that a closure references have not yet been figured
1098 // out (i.e., because it is not yet known if they are captured
1099 // by ref, and if by ref, what kind of ref). In these cases,
1100 // when matching a builtin bound, we will yield back an
1101 // ambiguous result. But the *cache key* is just the closure type,
1102 // it doesn't capture the state of the upvar computation.
1104 // To avoid this trap, just don't cache ambiguous results if
1105 // the self-type contains no inference byproducts (that really
1106 // shouldn't happen in other circumstances anyway, given
1110 Ok(Some(_)) | Err(_) => true,
1111 Ok(None) => cache_fresh_trait_pred.has_infer_types()
1115 fn assemble_candidates<'o>(&mut self,
1116 stack: &TraitObligationStack<'o, 'tcx>)
1117 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1119 let TraitObligationStack { obligation, .. } = *stack;
1120 let ref obligation = Obligation {
1121 cause: obligation.cause.clone(),
1122 recursion_depth: obligation.recursion_depth,
1123 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1126 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1127 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1129 // This is somewhat problematic, as the current scheme can't really
1130 // handle it turning to be a projection. This does end up as truly
1131 // ambiguous in most cases anyway.
1133 // Until this is fixed, take the fast path out - this also improves
1134 // performance by preventing assemble_candidates_from_impls from
1135 // matching every impl for this trait.
1136 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1139 let mut candidates = SelectionCandidateSet {
1144 // Other bounds. Consider both in-scope bounds from fn decl
1145 // and applicable impls. There is a certain set of precedence rules here.
1147 let def_id = obligation.predicate.def_id();
1148 if self.tcx().lang_items.copy_trait() == Some(def_id) {
1149 debug!("obligation self ty is {:?}",
1150 obligation.predicate.0.self_ty());
1152 // User-defined copy impls are permitted, but only for
1153 // structs and enums.
1154 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1156 // For other types, we'll use the builtin rules.
1157 let copy_conditions = self.copy_conditions(obligation);
1158 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1159 } else if self.tcx().lang_items.sized_trait() == Some(def_id) {
1160 // Sized is never implementable by end-users, it is
1161 // always automatically computed.
1162 let sized_conditions = self.sized_conditions(obligation);
1163 self.assemble_builtin_bound_candidates(sized_conditions,
1165 } else if self.tcx().lang_items.unsize_trait() == Some(def_id) {
1166 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1168 self.assemble_closure_candidates(obligation, &mut candidates)?;
1169 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1170 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1171 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1174 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1175 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1176 // Default implementations have lower priority, so we only
1177 // consider triggering a default if there is no other impl that can apply.
1178 if candidates.vec.is_empty() {
1179 self.assemble_candidates_from_default_impls(obligation, &mut candidates)?;
1181 debug!("candidate list size: {}", candidates.vec.len());
1185 fn assemble_candidates_from_projected_tys(&mut self,
1186 obligation: &TraitObligation<'tcx>,
1187 candidates: &mut SelectionCandidateSet<'tcx>)
1189 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1191 // FIXME(#20297) -- just examining the self-type is very simplistic
1193 // before we go into the whole skolemization thing, just
1194 // quickly check if the self-type is a projection at all.
1195 match obligation.predicate.0.trait_ref.self_ty().sty {
1196 ty::TyProjection(_) | ty::TyAnon(..) => {}
1197 ty::TyInfer(ty::TyVar(_)) => {
1198 span_bug!(obligation.cause.span,
1199 "Self=_ should have been handled by assemble_candidates");
1204 let result = self.probe(|this, snapshot| {
1205 this.match_projection_obligation_against_definition_bounds(obligation,
1210 candidates.vec.push(ProjectionCandidate);
1214 fn match_projection_obligation_against_definition_bounds(
1216 obligation: &TraitObligation<'tcx>,
1217 snapshot: &infer::CombinedSnapshot)
1220 let poly_trait_predicate =
1221 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1222 let (skol_trait_predicate, skol_map) =
1223 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1224 debug!("match_projection_obligation_against_definition_bounds: \
1225 skol_trait_predicate={:?} skol_map={:?}",
1226 skol_trait_predicate,
1229 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1230 ty::TyProjection(ref data) => (data.trait_ref.def_id, data.trait_ref.substs),
1231 ty::TyAnon(def_id, substs) => (def_id, substs),
1234 obligation.cause.span,
1235 "match_projection_obligation_against_definition_bounds() called \
1236 but self-ty not a projection: {:?}",
1237 skol_trait_predicate.trait_ref.self_ty());
1240 debug!("match_projection_obligation_against_definition_bounds: \
1241 def_id={:?}, substs={:?}",
1244 let item_predicates = self.tcx().item_predicates(def_id);
1245 let bounds = item_predicates.instantiate(self.tcx(), substs);
1246 debug!("match_projection_obligation_against_definition_bounds: \
1250 let matching_bound =
1251 util::elaborate_predicates(self.tcx(), bounds.predicates)
1255 |this, _| this.match_projection(obligation,
1257 skol_trait_predicate.trait_ref.clone(),
1261 debug!("match_projection_obligation_against_definition_bounds: \
1262 matching_bound={:?}",
1264 match matching_bound {
1267 // Repeat the successful match, if any, this time outside of a probe.
1268 let result = self.match_projection(obligation,
1270 skol_trait_predicate.trait_ref.clone(),
1274 self.infcx.pop_skolemized(skol_map, snapshot);
1282 fn match_projection(&mut self,
1283 obligation: &TraitObligation<'tcx>,
1284 trait_bound: ty::PolyTraitRef<'tcx>,
1285 skol_trait_ref: ty::TraitRef<'tcx>,
1286 skol_map: &infer::SkolemizationMap<'tcx>,
1287 snapshot: &infer::CombinedSnapshot)
1290 assert!(!skol_trait_ref.has_escaping_regions());
1291 let cause = obligation.cause.clone();
1292 match self.infcx.sub_poly_trait_refs(false,
1294 trait_bound.clone(),
1295 ty::Binder(skol_trait_ref.clone())) {
1296 Ok(InferOk { obligations, .. }) => {
1297 self.inferred_obligations.extend(obligations);
1299 Err(_) => { return false; }
1302 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1305 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1306 /// supplied to find out whether it is listed among them.
1308 /// Never affects inference environment.
1309 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1310 stack: &TraitObligationStack<'o, 'tcx>,
1311 candidates: &mut SelectionCandidateSet<'tcx>)
1312 -> Result<(),SelectionError<'tcx>>
1314 debug!("assemble_candidates_from_caller_bounds({:?})",
1318 self.param_env().caller_bounds
1320 .filter_map(|o| o.to_opt_poly_trait_ref());
1322 let matching_bounds =
1324 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1326 let param_candidates =
1327 matching_bounds.map(|bound| ParamCandidate(bound));
1329 candidates.vec.extend(param_candidates);
1334 fn evaluate_where_clause<'o>(&mut self,
1335 stack: &TraitObligationStack<'o, 'tcx>,
1336 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1339 self.probe(move |this, _| {
1340 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1341 Ok(obligations) => {
1342 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1344 Err(()) => EvaluatedToErr
1349 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1350 /// FnMut<..>` where `X` is a closure type.
1352 /// Note: the type parameters on a closure candidate are modeled as *output* type
1353 /// parameters and hence do not affect whether this trait is a match or not. They will be
1354 /// unified during the confirmation step.
1355 fn assemble_closure_candidates(&mut self,
1356 obligation: &TraitObligation<'tcx>,
1357 candidates: &mut SelectionCandidateSet<'tcx>)
1358 -> Result<(),SelectionError<'tcx>>
1360 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1362 None => { return Ok(()); }
1365 // ok to skip binder because the substs on closure types never
1366 // touch bound regions, they just capture the in-scope
1367 // type/region parameters
1368 let self_ty = *obligation.self_ty().skip_binder();
1369 let (closure_def_id, substs) = match self_ty.sty {
1370 ty::TyClosure(id, substs) => (id, substs),
1371 ty::TyInfer(ty::TyVar(_)) => {
1372 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1373 candidates.ambiguous = true;
1376 _ => { return Ok(()); }
1379 debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1384 match self.infcx.closure_kind(closure_def_id) {
1385 Some(closure_kind) => {
1386 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1387 if closure_kind.extends(kind) {
1388 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1392 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1393 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1400 /// Implement one of the `Fn()` family for a fn pointer.
1401 fn assemble_fn_pointer_candidates(&mut self,
1402 obligation: &TraitObligation<'tcx>,
1403 candidates: &mut SelectionCandidateSet<'tcx>)
1404 -> Result<(),SelectionError<'tcx>>
1406 // We provide impl of all fn traits for fn pointers.
1407 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1411 // ok to skip binder because what we are inspecting doesn't involve bound regions
1412 let self_ty = *obligation.self_ty().skip_binder();
1414 ty::TyInfer(ty::TyVar(_)) => {
1415 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1416 candidates.ambiguous = true; // could wind up being a fn() type
1419 // provide an impl, but only for suitable `fn` pointers
1420 ty::TyFnDef(.., ty::Binder(ty::FnSig {
1421 unsafety: hir::Unsafety::Normal,
1426 ty::TyFnPtr(ty::Binder(ty::FnSig {
1427 unsafety: hir::Unsafety::Normal,
1432 candidates.vec.push(FnPointerCandidate);
1441 /// Search for impls that might apply to `obligation`.
1442 fn assemble_candidates_from_impls(&mut self,
1443 obligation: &TraitObligation<'tcx>,
1444 candidates: &mut SelectionCandidateSet<'tcx>)
1445 -> Result<(), SelectionError<'tcx>>
1447 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1449 let def = self.tcx().lookup_trait_def(obligation.predicate.def_id());
1451 def.for_each_relevant_impl(
1453 obligation.predicate.0.trait_ref.self_ty(),
1455 self.probe(|this, snapshot| { /* [1] */
1456 match this.match_impl(impl_def_id, obligation, snapshot) {
1458 candidates.vec.push(ImplCandidate(impl_def_id));
1460 // NB: we can safely drop the skol map
1461 // since we are in a probe [1]
1462 mem::drop(skol_map);
1473 fn assemble_candidates_from_default_impls(&mut self,
1474 obligation: &TraitObligation<'tcx>,
1475 candidates: &mut SelectionCandidateSet<'tcx>)
1476 -> Result<(), SelectionError<'tcx>>
1478 // OK to skip binder here because the tests we do below do not involve bound regions
1479 let self_ty = *obligation.self_ty().skip_binder();
1480 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1482 let def_id = obligation.predicate.def_id();
1484 if self.tcx().trait_has_default_impl(def_id) {
1486 ty::TyDynamic(..) => {
1487 // For object types, we don't know what the closed
1488 // over types are. This means we conservatively
1489 // say nothing; a candidate may be added by
1490 // `assemble_candidates_from_object_ty`.
1493 ty::TyProjection(..) => {
1494 // In these cases, we don't know what the actual
1495 // type is. Therefore, we cannot break it down
1496 // into its constituent types. So we don't
1497 // consider the `..` impl but instead just add no
1498 // candidates: this means that typeck will only
1499 // succeed if there is another reason to believe
1500 // that this obligation holds. That could be a
1501 // where-clause or, in the case of an object type,
1502 // it could be that the object type lists the
1503 // trait (e.g. `Foo+Send : Send`). See
1504 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1505 // for an example of a test case that exercises
1508 ty::TyInfer(ty::TyVar(_)) => {
1509 // the defaulted impl might apply, we don't know
1510 candidates.ambiguous = true;
1513 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1521 /// Search for impls that might apply to `obligation`.
1522 fn assemble_candidates_from_object_ty(&mut self,
1523 obligation: &TraitObligation<'tcx>,
1524 candidates: &mut SelectionCandidateSet<'tcx>)
1526 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1527 obligation.self_ty().skip_binder());
1529 // Object-safety candidates are only applicable to object-safe
1530 // traits. Including this check is useful because it helps
1531 // inference in cases of traits like `BorrowFrom`, which are
1532 // not object-safe, and which rely on being able to infer the
1533 // self-type from one of the other inputs. Without this check,
1534 // these cases wind up being considered ambiguous due to a
1535 // (spurious) ambiguity introduced here.
1536 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1537 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1541 self.probe(|this, _snapshot| {
1542 // the code below doesn't care about regions, and the
1543 // self-ty here doesn't escape this probe, so just erase
1545 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1546 let poly_trait_ref = match self_ty.sty {
1547 ty::TyDynamic(ref data, ..) => {
1548 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1549 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1550 pushing candidate");
1551 candidates.vec.push(BuiltinObjectCandidate);
1555 match data.principal() {
1556 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1560 ty::TyInfer(ty::TyVar(_)) => {
1561 debug!("assemble_candidates_from_object_ty: ambiguous");
1562 candidates.ambiguous = true; // could wind up being an object type
1570 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1573 // Count only those upcast versions that match the trait-ref
1574 // we are looking for. Specifically, do not only check for the
1575 // correct trait, but also the correct type parameters.
1576 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1577 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1578 let upcast_trait_refs =
1579 util::supertraits(this.tcx(), poly_trait_ref)
1580 .filter(|upcast_trait_ref| {
1581 this.probe(|this, _| {
1582 let upcast_trait_ref = upcast_trait_ref.clone();
1583 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1588 if upcast_trait_refs > 1 {
1589 // can be upcast in many ways; need more type information
1590 candidates.ambiguous = true;
1591 } else if upcast_trait_refs == 1 {
1592 candidates.vec.push(ObjectCandidate);
1597 /// Search for unsizing that might apply to `obligation`.
1598 fn assemble_candidates_for_unsizing(&mut self,
1599 obligation: &TraitObligation<'tcx>,
1600 candidates: &mut SelectionCandidateSet<'tcx>) {
1601 // We currently never consider higher-ranked obligations e.g.
1602 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1603 // because they are a priori invalid, and we could potentially add support
1604 // for them later, it's just that there isn't really a strong need for it.
1605 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1606 // impl, and those are generally applied to concrete types.
1608 // That said, one might try to write a fn with a where clause like
1609 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1610 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1611 // Still, you'd be more likely to write that where clause as
1613 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1614 // obligation above. Should be possible to extend this in the future.
1615 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1618 // Don't add any candidates if there are bound regions.
1622 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1624 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1627 let may_apply = match (&source.sty, &target.sty) {
1628 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1629 (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1630 // Upcasts permit two things:
1632 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1633 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1635 // Note that neither of these changes requires any
1636 // change at runtime. Eventually this will be
1639 // We always upcast when we can because of reason
1640 // #2 (region bounds).
1641 match (data_a.principal(), data_b.principal()) {
1642 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1643 data_b.auto_traits()
1644 // All of a's auto traits need to be in b's auto traits.
1645 .all(|b| data_a.auto_traits().any(|a| a == b)),
1651 (_, &ty::TyDynamic(..)) => true,
1653 // Ambiguous handling is below T -> Trait, because inference
1654 // variables can still implement Unsize<Trait> and nested
1655 // obligations will have the final say (likely deferred).
1656 (&ty::TyInfer(ty::TyVar(_)), _) |
1657 (_, &ty::TyInfer(ty::TyVar(_))) => {
1658 debug!("assemble_candidates_for_unsizing: ambiguous");
1659 candidates.ambiguous = true;
1664 (&ty::TyArray(..), &ty::TySlice(_)) => true,
1666 // Struct<T> -> Struct<U>.
1667 (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1668 def_id_a == def_id_b
1675 candidates.vec.push(BuiltinUnsizeCandidate);
1679 ///////////////////////////////////////////////////////////////////////////
1682 // Winnowing is the process of attempting to resolve ambiguity by
1683 // probing further. During the winnowing process, we unify all
1684 // type variables (ignoring skolemization) and then we also
1685 // attempt to evaluate recursive bounds to see if they are
1688 /// Returns true if `candidate_i` should be dropped in favor of
1689 /// `candidate_j`. Generally speaking we will drop duplicate
1690 /// candidates and prefer where-clause candidates.
1691 /// Returns true if `victim` should be dropped in favor of
1692 /// `other`. Generally speaking we will drop duplicate
1693 /// candidates and prefer where-clause candidates.
1695 /// See the comment for "SelectionCandidate" for more details.
1696 fn candidate_should_be_dropped_in_favor_of<'o>(
1698 victim: &EvaluatedCandidate<'tcx>,
1699 other: &EvaluatedCandidate<'tcx>)
1702 if victim.candidate == other.candidate {
1706 match other.candidate {
1708 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1709 DefaultImplCandidate(..) => {
1711 "default implementations shouldn't be recorded \
1712 when there are other valid candidates");
1715 ClosureCandidate(..) |
1716 FnPointerCandidate |
1717 BuiltinObjectCandidate |
1718 BuiltinUnsizeCandidate |
1719 BuiltinCandidate { .. } => {
1720 // We have a where-clause so don't go around looking
1725 ProjectionCandidate => {
1726 // Arbitrarily give param candidates priority
1727 // over projection and object candidates.
1730 ParamCandidate(..) => false,
1732 ImplCandidate(other_def) => {
1733 // See if we can toss out `victim` based on specialization.
1734 // This requires us to know *for sure* that the `other` impl applies
1735 // i.e. EvaluatedToOk:
1736 if other.evaluation == EvaluatedToOk {
1737 if let ImplCandidate(victim_def) = victim.candidate {
1738 let tcx = self.tcx().global_tcx();
1739 return traits::specializes(tcx, other_def, victim_def) ||
1740 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
1750 ///////////////////////////////////////////////////////////////////////////
1753 // These cover the traits that are built-in to the language
1754 // itself. This includes `Copy` and `Sized` for sure. For the
1755 // moment, it also includes `Send` / `Sync` and a few others, but
1756 // those will hopefully change to library-defined traits in the
1759 // HACK: if this returns an error, selection exits without considering
1761 fn assemble_builtin_bound_candidates<'o>(&mut self,
1762 conditions: BuiltinImplConditions<'tcx>,
1763 candidates: &mut SelectionCandidateSet<'tcx>)
1764 -> Result<(),SelectionError<'tcx>>
1767 BuiltinImplConditions::Where(nested) => {
1768 debug!("builtin_bound: nested={:?}", nested);
1769 candidates.vec.push(BuiltinCandidate {
1770 has_nested: nested.skip_binder().len() > 0
1774 BuiltinImplConditions::None => { Ok(()) }
1775 BuiltinImplConditions::Ambiguous => {
1776 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1777 Ok(candidates.ambiguous = true)
1779 BuiltinImplConditions::Never => { Err(Unimplemented) }
1783 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1784 -> BuiltinImplConditions<'tcx>
1786 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1788 // NOTE: binder moved to (*)
1789 let self_ty = self.infcx.shallow_resolve(
1790 obligation.predicate.skip_binder().self_ty());
1793 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1794 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1795 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
1796 ty::TyChar | ty::TyRef(..) |
1797 ty::TyArray(..) | ty::TyClosure(..) | ty::TyNever |
1799 // safe for everything
1800 Where(ty::Binder(Vec::new()))
1803 ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) => Never,
1805 ty::TyTuple(tys, _) => {
1806 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
1809 ty::TyAdt(def, substs) => {
1810 let sized_crit = def.sized_constraint(self.tcx());
1811 // (*) binder moved here
1812 Where(ty::Binder(match sized_crit.sty {
1813 ty::TyTuple(tys, _) => tys.to_vec().subst(self.tcx(), substs),
1814 ty::TyBool => vec![],
1815 _ => vec![sized_crit.subst(self.tcx(), substs)]
1819 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
1820 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
1822 ty::TyInfer(ty::FreshTy(_))
1823 | ty::TyInfer(ty::FreshIntTy(_))
1824 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1825 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1831 fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1832 -> BuiltinImplConditions<'tcx>
1834 // NOTE: binder moved to (*)
1835 let self_ty = self.infcx.shallow_resolve(
1836 obligation.predicate.skip_binder().self_ty());
1838 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1841 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1842 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1843 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1844 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
1845 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
1846 Where(ty::Binder(Vec::new()))
1849 ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
1851 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
1855 ty::TyArray(element_ty, _) => {
1856 // (*) binder moved here
1857 Where(ty::Binder(vec![element_ty]))
1860 ty::TyTuple(tys, _) => {
1861 // (*) binder moved here
1862 Where(ty::Binder(tys.to_vec()))
1865 ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
1866 // Fallback to whatever user-defined impls exist in this case.
1870 ty::TyInfer(ty::TyVar(_)) => {
1871 // Unbound type variable. Might or might not have
1872 // applicable impls and so forth, depending on what
1873 // those type variables wind up being bound to.
1877 ty::TyInfer(ty::FreshTy(_))
1878 | ty::TyInfer(ty::FreshIntTy(_))
1879 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1880 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1886 /// For default impls, we need to break apart a type into its
1887 /// "constituent types" -- meaning, the types that it contains.
1889 /// Here are some (simple) examples:
1892 /// (i32, u32) -> [i32, u32]
1893 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1894 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1895 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1897 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1907 ty::TyInfer(ty::IntVar(_)) |
1908 ty::TyInfer(ty::FloatVar(_)) |
1916 ty::TyProjection(..) |
1917 ty::TyInfer(ty::TyVar(_)) |
1918 ty::TyInfer(ty::FreshTy(_)) |
1919 ty::TyInfer(ty::FreshIntTy(_)) |
1920 ty::TyInfer(ty::FreshFloatTy(_)) => {
1921 bug!("asked to assemble constituent types of unexpected type: {:?}",
1925 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
1926 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
1930 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
1934 ty::TyTuple(ref tys, _) => {
1935 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1939 ty::TyClosure(def_id, ref substs) => {
1940 // FIXME(#27086). We are invariant w/r/t our
1941 // func_substs, but we don't see them as
1942 // constituent types; this seems RIGHT but also like
1943 // something that a normal type couldn't simulate. Is
1944 // this just a gap with the way that PhantomData and
1945 // OIBIT interact? That is, there is no way to say
1946 // "make me invariant with respect to this TYPE, but
1947 // do not act as though I can reach it"
1948 substs.upvar_tys(def_id, self.tcx()).collect()
1951 // for `PhantomData<T>`, we pass `T`
1952 ty::TyAdt(def, substs) if def.is_phantom_data() => {
1953 substs.types().collect()
1956 ty::TyAdt(def, substs) => {
1958 .map(|f| f.ty(self.tcx(), substs))
1962 ty::TyAnon(def_id, substs) => {
1963 // We can resolve the `impl Trait` to its concrete type,
1964 // which enforces a DAG between the functions requiring
1965 // the auto trait bounds in question.
1966 vec![self.tcx().item_type(def_id).subst(self.tcx(), substs)]
1971 fn collect_predicates_for_types(&mut self,
1972 cause: ObligationCause<'tcx>,
1973 recursion_depth: usize,
1974 trait_def_id: DefId,
1975 types: ty::Binder<Vec<Ty<'tcx>>>)
1976 -> Vec<PredicateObligation<'tcx>>
1978 // Because the types were potentially derived from
1979 // higher-ranked obligations they may reference late-bound
1980 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1981 // yield a type like `for<'a> &'a int`. In general, we
1982 // maintain the invariant that we never manipulate bound
1983 // regions, so we have to process these bound regions somehow.
1985 // The strategy is to:
1987 // 1. Instantiate those regions to skolemized regions (e.g.,
1988 // `for<'a> &'a int` becomes `&0 int`.
1989 // 2. Produce something like `&'0 int : Copy`
1990 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1992 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
1993 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
1995 self.in_snapshot(|this, snapshot| {
1996 let (skol_ty, skol_map) =
1997 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
1998 let Normalized { value: normalized_ty, mut obligations } =
1999 project::normalize_with_depth(this,
2003 let skol_obligation =
2004 this.tcx().predicate_for_trait_def(
2010 obligations.push(skol_obligation);
2011 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2016 ///////////////////////////////////////////////////////////////////////////
2019 // Confirmation unifies the output type parameters of the trait
2020 // with the values found in the obligation, possibly yielding a
2021 // type error. See `README.md` for more details.
2023 fn confirm_candidate(&mut self,
2024 obligation: &TraitObligation<'tcx>,
2025 candidate: SelectionCandidate<'tcx>)
2026 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2028 debug!("confirm_candidate({:?}, {:?})",
2033 BuiltinCandidate { has_nested } => {
2035 self.confirm_builtin_candidate(obligation, has_nested)))
2038 ParamCandidate(param) => {
2039 let obligations = self.confirm_param_candidate(obligation, param);
2040 Ok(VtableParam(obligations))
2043 DefaultImplCandidate(trait_def_id) => {
2044 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2045 Ok(VtableDefaultImpl(data))
2048 ImplCandidate(impl_def_id) => {
2049 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2052 ClosureCandidate(closure_def_id, substs, kind) => {
2053 let vtable_closure =
2054 self.confirm_closure_candidate(obligation, closure_def_id, substs, kind)?;
2055 Ok(VtableClosure(vtable_closure))
2058 BuiltinObjectCandidate => {
2059 // This indicates something like `(Trait+Send) :
2060 // Send`. In this case, we know that this holds
2061 // because that's what the object type is telling us,
2062 // and there's really no additional obligations to
2063 // prove and no types in particular to unify etc.
2064 Ok(VtableParam(Vec::new()))
2067 ObjectCandidate => {
2068 let data = self.confirm_object_candidate(obligation);
2069 Ok(VtableObject(data))
2072 FnPointerCandidate => {
2074 self.confirm_fn_pointer_candidate(obligation)?;
2075 Ok(VtableFnPointer(data))
2078 ProjectionCandidate => {
2079 self.confirm_projection_candidate(obligation);
2080 Ok(VtableParam(Vec::new()))
2083 BuiltinUnsizeCandidate => {
2084 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2085 Ok(VtableBuiltin(data))
2090 fn confirm_projection_candidate(&mut self,
2091 obligation: &TraitObligation<'tcx>)
2093 self.in_snapshot(|this, snapshot| {
2095 this.match_projection_obligation_against_definition_bounds(obligation,
2101 fn confirm_param_candidate(&mut self,
2102 obligation: &TraitObligation<'tcx>,
2103 param: ty::PolyTraitRef<'tcx>)
2104 -> Vec<PredicateObligation<'tcx>>
2106 debug!("confirm_param_candidate({:?},{:?})",
2110 // During evaluation, we already checked that this
2111 // where-clause trait-ref could be unified with the obligation
2112 // trait-ref. Repeat that unification now without any
2113 // transactional boundary; it should not fail.
2114 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2115 Ok(obligations) => obligations,
2117 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2124 fn confirm_builtin_candidate(&mut self,
2125 obligation: &TraitObligation<'tcx>,
2127 -> VtableBuiltinData<PredicateObligation<'tcx>>
2129 debug!("confirm_builtin_candidate({:?}, {:?})",
2130 obligation, has_nested);
2132 let obligations = if has_nested {
2133 let trait_def = obligation.predicate.def_id();
2134 let conditions = match trait_def {
2135 _ if Some(trait_def) == self.tcx().lang_items.sized_trait() => {
2136 self.sized_conditions(obligation)
2138 _ if Some(trait_def) == self.tcx().lang_items.copy_trait() => {
2139 self.copy_conditions(obligation)
2141 _ => bug!("unexpected builtin trait {:?}", trait_def)
2143 let nested = match conditions {
2144 BuiltinImplConditions::Where(nested) => nested,
2145 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2149 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2150 self.collect_predicates_for_types(cause,
2151 obligation.recursion_depth+1,
2158 debug!("confirm_builtin_candidate: obligations={:?}",
2160 VtableBuiltinData { nested: obligations }
2163 /// This handles the case where a `impl Foo for ..` impl is being used.
2164 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2166 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2167 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2168 fn confirm_default_impl_candidate(&mut self,
2169 obligation: &TraitObligation<'tcx>,
2170 trait_def_id: DefId)
2171 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2173 debug!("confirm_default_impl_candidate({:?}, {:?})",
2177 // binder is moved below
2178 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2179 let types = self.constituent_types_for_ty(self_ty);
2180 self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2183 /// See `confirm_default_impl_candidate`
2184 fn vtable_default_impl(&mut self,
2185 obligation: &TraitObligation<'tcx>,
2186 trait_def_id: DefId,
2187 nested: ty::Binder<Vec<Ty<'tcx>>>)
2188 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2190 debug!("vtable_default_impl: nested={:?}", nested);
2192 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2193 let mut obligations = self.collect_predicates_for_types(
2195 obligation.recursion_depth+1,
2199 let trait_obligations = self.in_snapshot(|this, snapshot| {
2200 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2201 let (trait_ref, skol_map) =
2202 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2203 let cause = obligation.derived_cause(ImplDerivedObligation);
2204 this.impl_or_trait_obligations(cause,
2205 obligation.recursion_depth + 1,
2212 obligations.extend(trait_obligations);
2214 debug!("vtable_default_impl: obligations={:?}", obligations);
2216 VtableDefaultImplData {
2217 trait_def_id: trait_def_id,
2222 fn confirm_impl_candidate(&mut self,
2223 obligation: &TraitObligation<'tcx>,
2225 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2227 debug!("confirm_impl_candidate({:?},{:?})",
2231 // First, create the substitutions by matching the impl again,
2232 // this time not in a probe.
2233 self.in_snapshot(|this, snapshot| {
2234 let (substs, skol_map) =
2235 this.rematch_impl(impl_def_id, obligation,
2237 debug!("confirm_impl_candidate substs={:?}", substs);
2238 let cause = obligation.derived_cause(ImplDerivedObligation);
2239 this.vtable_impl(impl_def_id, substs, cause,
2240 obligation.recursion_depth + 1,
2245 fn vtable_impl(&mut self,
2247 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2248 cause: ObligationCause<'tcx>,
2249 recursion_depth: usize,
2250 skol_map: infer::SkolemizationMap<'tcx>,
2251 snapshot: &infer::CombinedSnapshot)
2252 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2254 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2260 let mut impl_obligations =
2261 self.impl_or_trait_obligations(cause,
2268 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2272 // Because of RFC447, the impl-trait-ref and obligations
2273 // are sufficient to determine the impl substs, without
2274 // relying on projections in the impl-trait-ref.
2276 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2277 impl_obligations.append(&mut substs.obligations);
2279 VtableImplData { impl_def_id: impl_def_id,
2280 substs: substs.value,
2281 nested: impl_obligations }
2284 fn confirm_object_candidate(&mut self,
2285 obligation: &TraitObligation<'tcx>)
2286 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2288 debug!("confirm_object_candidate({:?})",
2291 // FIXME skipping binder here seems wrong -- we should
2292 // probably flatten the binder from the obligation and the
2293 // binder from the object. Have to try to make a broken test
2294 // case that results. -nmatsakis
2295 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2296 let poly_trait_ref = match self_ty.sty {
2297 ty::TyDynamic(ref data, ..) => {
2298 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2301 span_bug!(obligation.cause.span,
2302 "object candidate with non-object");
2306 let mut upcast_trait_ref = None;
2310 let tcx = self.tcx();
2312 // We want to find the first supertrait in the list of
2313 // supertraits that we can unify with, and do that
2314 // unification. We know that there is exactly one in the list
2315 // where we can unify because otherwise select would have
2316 // reported an ambiguity. (When we do find a match, also
2317 // record it for later.)
2319 util::supertraits(tcx, poly_trait_ref)
2323 |this, _| this.match_poly_trait_ref(obligation, t))
2325 Ok(_) => { upcast_trait_ref = Some(t); false }
2330 // Additionally, for each of the nonmatching predicates that
2331 // we pass over, we sum up the set of number of vtable
2332 // entries, so that we can compute the offset for the selected
2335 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2341 upcast_trait_ref: upcast_trait_ref.unwrap(),
2342 vtable_base: vtable_base,
2347 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2348 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2350 debug!("confirm_fn_pointer_candidate({:?})",
2353 // ok to skip binder; it is reintroduced below
2354 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2355 let sig = self_ty.fn_sig();
2357 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2360 util::TupleArgumentsFlag::Yes)
2361 .map_bound(|(trait_ref, _)| trait_ref);
2363 self.confirm_poly_trait_refs(obligation.cause.clone(),
2364 obligation.predicate.to_poly_trait_ref(),
2366 Ok(VtableFnPointerData { fn_ty: self_ty, nested: vec![] })
2369 fn confirm_closure_candidate(&mut self,
2370 obligation: &TraitObligation<'tcx>,
2371 closure_def_id: DefId,
2372 substs: ty::ClosureSubsts<'tcx>,
2373 kind: ty::ClosureKind)
2374 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2375 SelectionError<'tcx>>
2377 debug!("confirm_closure_candidate({:?},{:?},{:?})",
2385 } = self.closure_trait_ref(obligation, closure_def_id, substs);
2387 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2392 self.confirm_poly_trait_refs(obligation.cause.clone(),
2393 obligation.predicate.to_poly_trait_ref(),
2396 obligations.push(Obligation::new(
2397 obligation.cause.clone(),
2398 ty::Predicate::ClosureKind(closure_def_id, kind)));
2400 Ok(VtableClosureData {
2401 closure_def_id: closure_def_id,
2402 substs: substs.clone(),
2407 /// In the case of closure types and fn pointers,
2408 /// we currently treat the input type parameters on the trait as
2409 /// outputs. This means that when we have a match we have only
2410 /// considered the self type, so we have to go back and make sure
2411 /// to relate the argument types too. This is kind of wrong, but
2412 /// since we control the full set of impls, also not that wrong,
2413 /// and it DOES yield better error messages (since we don't report
2414 /// errors as if there is no applicable impl, but rather report
2415 /// errors are about mismatched argument types.
2417 /// Here is an example. Imagine we have a closure expression
2418 /// and we desugared it so that the type of the expression is
2419 /// `Closure`, and `Closure` expects an int as argument. Then it
2420 /// is "as if" the compiler generated this impl:
2422 /// impl Fn(int) for Closure { ... }
2424 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2425 /// we have matched the self-type `Closure`. At this point we'll
2426 /// compare the `int` to `usize` and generate an error.
2428 /// Note that this checking occurs *after* the impl has selected,
2429 /// because these output type parameters should not affect the
2430 /// selection of the impl. Therefore, if there is a mismatch, we
2431 /// report an error to the user.
2432 fn confirm_poly_trait_refs(&mut self,
2433 obligation_cause: ObligationCause<'tcx>,
2434 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2435 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2436 -> Result<(), SelectionError<'tcx>>
2438 let obligation_trait_ref = obligation_trait_ref.clone();
2439 self.infcx.sub_poly_trait_refs(false,
2440 obligation_cause.clone(),
2441 expected_trait_ref.clone(),
2442 obligation_trait_ref.clone())
2443 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2444 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2447 fn confirm_builtin_unsize_candidate(&mut self,
2448 obligation: &TraitObligation<'tcx>,)
2449 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2450 SelectionError<'tcx>> {
2451 let tcx = self.tcx();
2453 // assemble_candidates_for_unsizing should ensure there are no late bound
2454 // regions here. See the comment there for more details.
2455 let source = self.infcx.shallow_resolve(
2456 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2457 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2458 let target = self.infcx.shallow_resolve(target);
2460 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2463 let mut nested = vec![];
2464 match (&source.sty, &target.sty) {
2465 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2466 (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2467 // See assemble_candidates_for_unsizing for more info.
2468 // Binders reintroduced below in call to mk_existential_predicates.
2469 let principal = data_a.skip_binder().principal();
2470 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2471 .chain(data_a.skip_binder().projection_bounds()
2472 .map(|x| ty::ExistentialPredicate::Projection(x)))
2473 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2474 let new_trait = tcx.mk_dynamic(
2475 ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2476 let InferOk { obligations, .. } =
2477 self.infcx.eq_types(false, &obligation.cause, new_trait, target)
2478 .map_err(|_| Unimplemented)?;
2479 self.inferred_obligations.extend(obligations);
2481 // Register one obligation for 'a: 'b.
2482 let cause = ObligationCause::new(obligation.cause.span,
2483 obligation.cause.body_id,
2484 ObjectCastObligation(target));
2485 let outlives = ty::OutlivesPredicate(r_a, r_b);
2486 nested.push(Obligation::with_depth(cause,
2487 obligation.recursion_depth + 1,
2488 ty::Binder(outlives).to_predicate()));
2492 (_, &ty::TyDynamic(ref data, r)) => {
2493 let mut object_dids =
2494 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2495 if let Some(did) = object_dids.find(|did| {
2496 !tcx.is_object_safe(*did)
2498 return Err(TraitNotObjectSafe(did))
2501 let cause = ObligationCause::new(obligation.cause.span,
2502 obligation.cause.body_id,
2503 ObjectCastObligation(target));
2504 let mut push = |predicate| {
2505 nested.push(Obligation::with_depth(cause.clone(),
2506 obligation.recursion_depth + 1,
2510 // Create obligations:
2511 // - Casting T to Trait
2512 // - For all the various builtin bounds attached to the object cast. (In other
2513 // words, if the object type is Foo+Send, this would create an obligation for the
2515 // - Projection predicates
2516 for predicate in data.iter() {
2517 push(predicate.with_self_ty(tcx, source));
2520 // We can only make objects from sized types.
2521 let tr = ty::TraitRef {
2522 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2523 substs: tcx.mk_substs_trait(source, &[]),
2525 push(tr.to_predicate());
2527 // If the type is `Foo+'a`, ensures that the type
2528 // being cast to `Foo+'a` outlives `'a`:
2529 let outlives = ty::OutlivesPredicate(source, r);
2530 push(ty::Binder(outlives).to_predicate());
2534 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2535 let InferOk { obligations, .. } =
2536 self.infcx.eq_types(false, &obligation.cause, a, b)
2537 .map_err(|_| Unimplemented)?;
2538 self.inferred_obligations.extend(obligations);
2541 // Struct<T> -> Struct<U>.
2542 (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2545 .map(|f| tcx.item_type(f.did))
2546 .collect::<Vec<_>>();
2548 // The last field of the structure has to exist and contain type parameters.
2549 let field = if let Some(&field) = fields.last() {
2552 return Err(Unimplemented);
2554 let mut ty_params = BitVector::new(substs_a.types().count());
2555 let mut found = false;
2556 for ty in field.walk() {
2557 if let ty::TyParam(p) = ty.sty {
2558 ty_params.insert(p.idx as usize);
2563 return Err(Unimplemented);
2566 // Replace type parameters used in unsizing with
2567 // TyError and ensure they do not affect any other fields.
2568 // This could be checked after type collection for any struct
2569 // with a potentially unsized trailing field.
2570 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2571 if ty_params.contains(i) {
2572 Kind::from(tcx.types.err)
2577 let substs = tcx.mk_substs(params);
2578 for &ty in fields.split_last().unwrap().1 {
2579 if ty.subst(tcx, substs).references_error() {
2580 return Err(Unimplemented);
2584 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2585 let inner_source = field.subst(tcx, substs_a);
2586 let inner_target = field.subst(tcx, substs_b);
2588 // Check that the source structure with the target's
2589 // type parameters is a subtype of the target.
2590 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2591 if ty_params.contains(i) {
2592 Kind::from(substs_b.type_at(i))
2597 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
2598 let InferOk { obligations, .. } =
2599 self.infcx.eq_types(false, &obligation.cause, new_struct, target)
2600 .map_err(|_| Unimplemented)?;
2601 self.inferred_obligations.extend(obligations);
2603 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2604 nested.push(tcx.predicate_for_trait_def(
2605 obligation.cause.clone(),
2606 obligation.predicate.def_id(),
2607 obligation.recursion_depth + 1,
2615 Ok(VtableBuiltinData { nested: nested })
2618 ///////////////////////////////////////////////////////////////////////////
2621 // Matching is a common path used for both evaluation and
2622 // confirmation. It basically unifies types that appear in impls
2623 // and traits. This does affect the surrounding environment;
2624 // therefore, when used during evaluation, match routines must be
2625 // run inside of a `probe()` so that their side-effects are
2628 fn rematch_impl(&mut self,
2630 obligation: &TraitObligation<'tcx>,
2631 snapshot: &infer::CombinedSnapshot)
2632 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
2633 infer::SkolemizationMap<'tcx>)
2635 match self.match_impl(impl_def_id, obligation, snapshot) {
2636 Ok((substs, skol_map)) => (substs, skol_map),
2638 bug!("Impl {:?} was matchable against {:?} but now is not",
2645 fn match_impl(&mut self,
2647 obligation: &TraitObligation<'tcx>,
2648 snapshot: &infer::CombinedSnapshot)
2649 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
2650 infer::SkolemizationMap<'tcx>), ()>
2652 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2654 // Before we create the substitutions and everything, first
2655 // consider a "quick reject". This avoids creating more types
2656 // and so forth that we need to.
2657 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2661 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2662 &obligation.predicate,
2664 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2666 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
2669 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2672 let impl_trait_ref =
2673 project::normalize_with_depth(self,
2674 obligation.cause.clone(),
2675 obligation.recursion_depth + 1,
2678 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2679 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2683 skol_obligation_trait_ref);
2685 let InferOk { obligations, .. } =
2686 self.infcx.eq_trait_refs(false,
2688 impl_trait_ref.value.clone(),
2689 skol_obligation_trait_ref)
2691 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2694 self.inferred_obligations.extend(obligations);
2696 if let Err(e) = self.infcx.leak_check(false,
2697 obligation.cause.span,
2700 debug!("match_impl: failed leak check due to `{}`", e);
2704 debug!("match_impl: success impl_substs={:?}", impl_substs);
2707 obligations: impl_trait_ref.obligations
2711 fn fast_reject_trait_refs(&mut self,
2712 obligation: &TraitObligation,
2713 impl_trait_ref: &ty::TraitRef)
2716 // We can avoid creating type variables and doing the full
2717 // substitution if we find that any of the input types, when
2718 // simplified, do not match.
2720 obligation.predicate.skip_binder().input_types()
2721 .zip(impl_trait_ref.input_types())
2722 .any(|(obligation_ty, impl_ty)| {
2723 let simplified_obligation_ty =
2724 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2725 let simplified_impl_ty =
2726 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2728 simplified_obligation_ty.is_some() &&
2729 simplified_impl_ty.is_some() &&
2730 simplified_obligation_ty != simplified_impl_ty
2734 /// Normalize `where_clause_trait_ref` and try to match it against
2735 /// `obligation`. If successful, return any predicates that
2736 /// result from the normalization. Normalization is necessary
2737 /// because where-clauses are stored in the parameter environment
2739 fn match_where_clause_trait_ref(&mut self,
2740 obligation: &TraitObligation<'tcx>,
2741 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2742 -> Result<Vec<PredicateObligation<'tcx>>,()>
2744 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
2748 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2749 /// obligation is satisfied.
2750 fn match_poly_trait_ref(&mut self,
2751 obligation: &TraitObligation<'tcx>,
2752 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2755 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2759 self.infcx.sub_poly_trait_refs(false,
2760 obligation.cause.clone(),
2762 obligation.predicate.to_poly_trait_ref())
2763 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2767 ///////////////////////////////////////////////////////////////////////////
2770 fn match_fresh_trait_refs(&self,
2771 previous: &ty::PolyTraitRef<'tcx>,
2772 current: &ty::PolyTraitRef<'tcx>)
2775 let mut matcher = ty::_match::Match::new(self.tcx());
2776 matcher.relate(previous, current).is_ok()
2779 fn push_stack<'o,'s:'o>(&mut self,
2780 previous_stack: TraitObligationStackList<'s, 'tcx>,
2781 obligation: &'o TraitObligation<'tcx>)
2782 -> TraitObligationStack<'o, 'tcx>
2784 let fresh_trait_ref =
2785 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2787 TraitObligationStack {
2788 obligation: obligation,
2789 fresh_trait_ref: fresh_trait_ref,
2790 previous: previous_stack,
2794 fn closure_trait_ref_unnormalized(&mut self,
2795 obligation: &TraitObligation<'tcx>,
2796 closure_def_id: DefId,
2797 substs: ty::ClosureSubsts<'tcx>)
2798 -> ty::PolyTraitRef<'tcx>
2800 let closure_type = self.infcx.closure_type(closure_def_id)
2801 .subst(self.tcx(), substs.substs);
2802 let ty::Binder((trait_ref, _)) =
2803 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2804 obligation.predicate.0.self_ty(), // (1)
2806 util::TupleArgumentsFlag::No);
2807 // (1) Feels icky to skip the binder here, but OTOH we know
2808 // that the self-type is an unboxed closure type and hence is
2809 // in fact unparameterized (or at least does not reference any
2810 // regions bound in the obligation). Still probably some
2811 // refactoring could make this nicer.
2813 ty::Binder(trait_ref)
2816 fn closure_trait_ref(&mut self,
2817 obligation: &TraitObligation<'tcx>,
2818 closure_def_id: DefId,
2819 substs: ty::ClosureSubsts<'tcx>)
2820 -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
2822 let trait_ref = self.closure_trait_ref_unnormalized(
2823 obligation, closure_def_id, substs);
2825 // A closure signature can contain associated types which
2826 // must be normalized.
2827 normalize_with_depth(self,
2828 obligation.cause.clone(),
2829 obligation.recursion_depth+1,
2833 /// Returns the obligations that are implied by instantiating an
2834 /// impl or trait. The obligations are substituted and fully
2835 /// normalized. This is used when confirming an impl or default
2837 fn impl_or_trait_obligations(&mut self,
2838 cause: ObligationCause<'tcx>,
2839 recursion_depth: usize,
2840 def_id: DefId, // of impl or trait
2841 substs: &Substs<'tcx>, // for impl or trait
2842 skol_map: infer::SkolemizationMap<'tcx>,
2843 snapshot: &infer::CombinedSnapshot)
2844 -> Vec<PredicateObligation<'tcx>>
2846 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2847 let tcx = self.tcx();
2849 // To allow for one-pass evaluation of the nested obligation,
2850 // each predicate must be preceded by the obligations required
2852 // for example, if we have:
2853 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2854 // the impl will have the following predicates:
2855 // <V as Iterator>::Item = U,
2856 // U: Iterator, U: Sized,
2857 // V: Iterator, V: Sized,
2858 // <U as Iterator>::Item: Copy
2859 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2860 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2861 // `$1: Copy`, so we must ensure the obligations are emitted in
2863 let predicates = tcx.item_predicates(def_id);
2864 assert_eq!(predicates.parent, None);
2865 let predicates = predicates.predicates.iter().flat_map(|predicate| {
2866 let predicate = normalize_with_depth(self, cause.clone(), recursion_depth,
2867 &predicate.subst(tcx, substs));
2868 predicate.obligations.into_iter().chain(
2870 cause: cause.clone(),
2871 recursion_depth: recursion_depth,
2872 predicate: predicate.value
2875 self.infcx().plug_leaks(skol_map, snapshot, predicates)
2879 impl<'tcx> TraitObligation<'tcx> {
2880 #[allow(unused_comparisons)]
2881 pub fn derived_cause(&self,
2882 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2883 -> ObligationCause<'tcx>
2886 * Creates a cause for obligations that are derived from
2887 * `obligation` by a recursive search (e.g., for a builtin
2888 * bound, or eventually a `impl Foo for ..`). If `obligation`
2889 * is itself a derived obligation, this is just a clone, but
2890 * otherwise we create a "derived obligation" cause so as to
2891 * keep track of the original root obligation for error
2895 let obligation = self;
2897 // NOTE(flaper87): As of now, it keeps track of the whole error
2898 // chain. Ideally, we should have a way to configure this either
2899 // by using -Z verbose or just a CLI argument.
2900 if obligation.recursion_depth >= 0 {
2901 let derived_cause = DerivedObligationCause {
2902 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2903 parent_code: Rc::new(obligation.cause.code.clone())
2905 let derived_code = variant(derived_cause);
2906 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2908 obligation.cause.clone()
2913 impl<'tcx> SelectionCache<'tcx> {
2914 pub fn new() -> SelectionCache<'tcx> {
2916 hashmap: RefCell::new(FxHashMap())
2921 impl<'tcx> EvaluationCache<'tcx> {
2922 pub fn new() -> EvaluationCache<'tcx> {
2924 hashmap: RefCell::new(FxHashMap())
2929 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
2930 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
2931 TraitObligationStackList::with(self)
2934 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
2939 #[derive(Copy, Clone)]
2940 struct TraitObligationStackList<'o,'tcx:'o> {
2941 head: Option<&'o TraitObligationStack<'o,'tcx>>
2944 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
2945 fn empty() -> TraitObligationStackList<'o,'tcx> {
2946 TraitObligationStackList { head: None }
2949 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
2950 TraitObligationStackList { head: Some(r) }
2954 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
2955 type Item = &'o TraitObligationStack<'o,'tcx>;
2957 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
2968 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
2969 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2970 write!(f, "TraitObligationStack({:?})", self.obligation)
2974 impl EvaluationResult {
2975 fn may_apply(&self) -> bool {
2979 EvaluatedToUnknown => true,
2981 EvaluatedToErr => false
2986 impl MethodMatchResult {
2987 pub fn may_apply(&self) -> bool {
2989 MethodMatched(_) => true,
2990 MethodAmbiguous(_) => true,
2991 MethodDidNotMatch => false,