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, TypeOrigin};
39 use ty::subst::{Subst, Substs};
40 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
43 use ty::relate::TypeRelation;
45 use rustc_data_structures::bitvec::BitVector;
46 use rustc_data_structures::snapshot_vec::{SnapshotVecDelegate, SnapshotVec};
47 use std::cell::RefCell;
49 use std::marker::PhantomData;
54 use util::nodemap::FnvHashMap;
56 struct InferredObligationsSnapshotVecDelegate<'tcx> {
57 phantom: PhantomData<&'tcx i32>,
59 impl<'tcx> SnapshotVecDelegate for InferredObligationsSnapshotVecDelegate<'tcx> {
60 type Value = PredicateObligation<'tcx>;
62 fn reverse(_: &mut Vec<Self::Value>, _: Self::Undo) {}
65 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
66 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
68 /// Freshener used specifically for skolemizing entries on the
69 /// obligation stack. This ensures that all entries on the stack
70 /// at one time will have the same set of skolemized entries,
71 /// which is important for checking for trait bounds that
72 /// recursively require themselves.
73 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
75 /// If true, indicates that the evaluation should be conservative
76 /// and consider the possibility of types outside this crate.
77 /// This comes up primarily when resolving ambiguity. Imagine
78 /// there is some trait reference `$0 : Bar` where `$0` is an
79 /// inference variable. If `intercrate` is true, then we can never
80 /// say for sure that this reference is not implemented, even if
81 /// there are *no impls at all for `Bar`*, because `$0` could be
82 /// bound to some type that in a downstream crate that implements
83 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
84 /// though, we set this to false, because we are only interested
85 /// in types that the user could actually have written --- in
86 /// other words, we consider `$0 : Bar` to be unimplemented if
87 /// there is no type that the user could *actually name* that
88 /// would satisfy it. This avoids crippling inference, basically.
91 inferred_obligations: SnapshotVec<InferredObligationsSnapshotVecDelegate<'tcx>>,
94 // A stack that walks back up the stack frame.
95 struct TraitObligationStack<'prev, 'tcx: 'prev> {
96 obligation: &'prev TraitObligation<'tcx>,
98 /// Trait ref from `obligation` but skolemized with the
99 /// selection-context's freshener. Used to check for recursion.
100 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
102 previous: TraitObligationStackList<'prev, 'tcx>,
106 pub struct SelectionCache<'tcx> {
107 hashmap: RefCell<FnvHashMap<ty::TraitRef<'tcx>,
108 SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
111 pub enum MethodMatchResult {
112 MethodMatched(MethodMatchedData),
113 MethodAmbiguous(/* list of impls that could apply */ Vec<DefId>),
117 #[derive(Copy, Clone, Debug)]
118 pub enum MethodMatchedData {
119 // In the case of a precise match, we don't really need to store
120 // how the match was found. So don't.
123 // In the case of a coercion, we need to know the precise impl so
124 // that we can determine the type to which things were coerced.
125 CoerciveMethodMatch(/* impl we matched */ DefId)
128 /// The selection process begins by considering all impls, where
129 /// clauses, and so forth that might resolve an obligation. Sometimes
130 /// we'll be able to say definitively that (e.g.) an impl does not
131 /// apply to the obligation: perhaps it is defined for `usize` but the
132 /// obligation is for `int`. In that case, we drop the impl out of the
133 /// list. But the other cases are considered *candidates*.
135 /// For selection to succeed, there must be exactly one matching
136 /// candidate. If the obligation is fully known, this is guaranteed
137 /// by coherence. However, if the obligation contains type parameters
138 /// or variables, there may be multiple such impls.
140 /// It is not a real problem if multiple matching impls exist because
141 /// of type variables - it just means the obligation isn't sufficiently
142 /// elaborated. In that case we report an ambiguity, and the caller can
143 /// try again after more type information has been gathered or report a
144 /// "type annotations required" error.
146 /// However, with type parameters, this can be a real problem - type
147 /// parameters don't unify with regular types, but they *can* unify
148 /// with variables from blanket impls, and (unless we know its bounds
149 /// will always be satisfied) picking the blanket impl will be wrong
150 /// for at least *some* substitutions. To make this concrete, if we have
152 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
153 /// impl<T: fmt::Debug> AsDebug for T {
155 /// fn debug(self) -> fmt::Debug { self }
157 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
159 /// we can't just use the impl to resolve the <T as AsDebug> obligation
160 /// - a type from another crate (that doesn't implement fmt::Debug) could
161 /// implement AsDebug.
163 /// Because where-clauses match the type exactly, multiple clauses can
164 /// only match if there are unresolved variables, and we can mostly just
165 /// report this ambiguity in that case. This is still a problem - we can't
166 /// *do anything* with ambiguities that involve only regions. This is issue
169 /// If a single where-clause matches and there are no inference
170 /// variables left, then it definitely matches and we can just select
173 /// In fact, we even select the where-clause when the obligation contains
174 /// inference variables. The can lead to inference making "leaps of logic",
175 /// for example in this situation:
177 /// pub trait Foo<T> { fn foo(&self) -> T; }
178 /// impl<T> Foo<()> for T { fn foo(&self) { } }
179 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
181 /// pub fn foo<T>(t: T) where T: Foo<bool> {
182 /// println!("{:?}", <T as Foo<_>>::foo(&t));
184 /// fn main() { foo(false); }
186 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
187 /// impl and the where-clause. We select the where-clause and unify $0=bool,
188 /// so the program prints "false". However, if the where-clause is omitted,
189 /// the blanket impl is selected, we unify $0=(), and the program prints
192 /// Exactly the same issues apply to projection and object candidates, except
193 /// that we can have both a projection candidate and a where-clause candidate
194 /// for the same obligation. In that case either would do (except that
195 /// different "leaps of logic" would occur if inference variables are
196 /// present), and we just pick the where-clause. This is, for example,
197 /// required for associated types to work in default impls, as the bounds
198 /// are visible both as projection bounds and as where-clauses from the
199 /// parameter environment.
200 #[derive(PartialEq,Eq,Debug,Clone)]
201 enum SelectionCandidate<'tcx> {
202 BuiltinCandidate { has_nested: bool },
203 ParamCandidate(ty::PolyTraitRef<'tcx>),
204 ImplCandidate(DefId),
205 DefaultImplCandidate(DefId),
206 DefaultImplObjectCandidate(DefId),
208 /// This is a trait matching with a projected type as `Self`, and
209 /// we found an applicable bound in the trait definition.
212 /// Implementation of a `Fn`-family trait by one of the anonymous types
213 /// generated for a `||` expression. The ty::ClosureKind informs the
214 /// confirmation step what ClosureKind obligation to emit.
215 ClosureCandidate(/* closure */ DefId, ty::ClosureSubsts<'tcx>, ty::ClosureKind),
217 /// Implementation of a `Fn`-family trait by one of the anonymous
218 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
223 BuiltinObjectCandidate,
225 BuiltinUnsizeCandidate,
228 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
229 type Lifted = SelectionCandidate<'tcx>;
230 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
232 BuiltinCandidate { has_nested } => {
234 has_nested: has_nested
237 ImplCandidate(def_id) => ImplCandidate(def_id),
238 DefaultImplCandidate(def_id) => DefaultImplCandidate(def_id),
239 DefaultImplObjectCandidate(def_id) => {
240 DefaultImplObjectCandidate(def_id)
242 ProjectionCandidate => ProjectionCandidate,
243 FnPointerCandidate => FnPointerCandidate,
244 ObjectCandidate => ObjectCandidate,
245 BuiltinObjectCandidate => BuiltinObjectCandidate,
246 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
248 ParamCandidate(ref trait_ref) => {
249 return tcx.lift(trait_ref).map(ParamCandidate);
251 ClosureCandidate(def_id, ref substs, kind) => {
252 return tcx.lift(substs).map(|substs| {
253 ClosureCandidate(def_id, substs, kind)
260 struct SelectionCandidateSet<'tcx> {
261 // a list of candidates that definitely apply to the current
262 // obligation (meaning: types unify).
263 vec: Vec<SelectionCandidate<'tcx>>,
265 // if this is true, then there were candidates that might or might
266 // not have applied, but we couldn't tell. This occurs when some
267 // of the input types are type variables, in which case there are
268 // various "builtin" rules that might or might not trigger.
272 #[derive(PartialEq,Eq,Debug,Clone)]
273 struct EvaluatedCandidate<'tcx> {
274 candidate: SelectionCandidate<'tcx>,
275 evaluation: EvaluationResult,
278 /// When does the builtin impl for `T: Trait` apply?
279 enum BuiltinImplConditions<'tcx> {
280 /// The impl is conditional on T1,T2,.. : Trait
281 Where(ty::Binder<Vec<Ty<'tcx>>>),
282 /// There is no built-in impl. There may be some other
283 /// candidate (a where-clause or user-defined impl).
285 /// There is *no* impl for this, builtin or not. Ignore
286 /// all where-clauses.
288 /// It is unknown whether there is an impl.
292 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
293 /// The result of trait evaluation. The order is important
294 /// here as the evaluation of a list is the maximum of the
296 enum EvaluationResult {
297 /// Evaluation successful
299 /// Evaluation failed because of recursion - treated as ambiguous
301 /// Evaluation is known to be ambiguous
303 /// Evaluation failed
308 pub struct EvaluationCache<'tcx> {
309 hashmap: RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, EvaluationResult>>
312 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
313 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
316 freshener: infcx.freshener(),
318 inferred_obligations: SnapshotVec::new(),
322 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
325 freshener: infcx.freshener(),
327 inferred_obligations: SnapshotVec::new(),
331 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
335 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
339 pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'tcx> {
340 self.infcx.param_env()
343 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
347 pub fn projection_mode(&self) -> Reveal {
348 self.infcx.projection_mode()
351 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
353 fn in_snapshot<R, F>(&mut self, f: F) -> R
354 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
356 // The irrefutable nature of the operation means we don't need to snapshot the
357 // inferred_obligations vector.
358 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
361 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
363 fn probe<R, F>(&mut self, f: F) -> R
364 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
366 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
367 let result = self.infcx.probe(|snapshot| f(self, snapshot));
368 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
372 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
373 /// the transaction fails and s.t. old obligations are retained.
374 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
375 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
377 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
378 match self.infcx.commit_if_ok(|snapshot| f(self, snapshot)) {
380 self.inferred_obligations.commit(inferred_obligations_snapshot);
384 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
391 ///////////////////////////////////////////////////////////////////////////
394 // The selection phase tries to identify *how* an obligation will
395 // be resolved. For example, it will identify which impl or
396 // parameter bound is to be used. The process can be inconclusive
397 // if the self type in the obligation is not fully inferred. Selection
398 // can result in an error in one of two ways:
400 // 1. If no applicable impl or parameter bound can be found.
401 // 2. If the output type parameters in the obligation do not match
402 // those specified by the impl/bound. For example, if the obligation
403 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
404 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
406 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
407 /// type environment by performing unification.
408 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
409 -> SelectionResult<'tcx, Selection<'tcx>> {
410 debug!("select({:?})", obligation);
411 assert!(!obligation.predicate.has_escaping_regions());
413 let dep_node = obligation.predicate.dep_node();
414 let _task = self.tcx().dep_graph.in_task(dep_node);
416 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
417 match self.candidate_from_obligation(&stack)? {
420 let mut candidate = self.confirm_candidate(obligation, candidate)?;
421 // FIXME(#32730) remove this assertion once inferred obligations are propagated
423 assert!(self.inferred_obligations.len() == 0);
424 let inferred_obligations = (*self.inferred_obligations).into_iter().cloned();
425 candidate.nested_obligations_mut().extend(inferred_obligations);
431 ///////////////////////////////////////////////////////////////////////////
434 // Tests whether an obligation can be selected or whether an impl
435 // can be applied to particular types. It skips the "confirmation"
436 // step and hence completely ignores output type parameters.
438 // The result is "true" if the obligation *may* hold and "false" if
439 // we can be sure it does not.
441 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
442 pub fn evaluate_obligation(&mut self,
443 obligation: &PredicateObligation<'tcx>)
446 debug!("evaluate_obligation({:?})",
449 self.probe(|this, _| {
450 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
455 /// Evaluates whether the obligation `obligation` can be satisfied,
456 /// and returns `false` if not certain. However, this is not entirely
457 /// accurate if inference variables are involved.
458 pub fn evaluate_obligation_conservatively(&mut self,
459 obligation: &PredicateObligation<'tcx>)
462 debug!("evaluate_obligation_conservatively({:?})",
465 self.probe(|this, _| {
466 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
471 /// Evaluates the predicates in `predicates` recursively. Note that
472 /// this applies projections in the predicates, and therefore
473 /// is run within an inference probe.
474 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
475 stack: TraitObligationStackList<'o, 'tcx>,
478 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
480 let mut result = EvaluatedToOk;
481 for obligation in predicates {
482 let eval = self.evaluate_predicate_recursively(stack, obligation);
483 debug!("evaluate_predicate_recursively({:?}) = {:?}",
486 EvaluatedToErr => { return EvaluatedToErr; }
487 EvaluatedToAmbig => { result = EvaluatedToAmbig; }
488 EvaluatedToUnknown => {
489 if result < EvaluatedToUnknown {
490 result = EvaluatedToUnknown;
499 fn evaluate_predicate_recursively<'o>(&mut self,
500 previous_stack: TraitObligationStackList<'o, 'tcx>,
501 obligation: &PredicateObligation<'tcx>)
504 debug!("evaluate_predicate_recursively({:?})",
507 // Check the cache from the tcx of predicates that we know
508 // have been proven elsewhere. This cache only contains
509 // predicates that are global in scope and hence unaffected by
510 // the current environment.
511 if self.tcx().fulfilled_predicates.borrow().check_duplicate(&obligation.predicate) {
512 return EvaluatedToOk;
515 match obligation.predicate {
516 ty::Predicate::Rfc1592(..) => EvaluatedToOk,
518 ty::Predicate::Trait(ref t) => {
519 assert!(!t.has_escaping_regions());
520 let obligation = obligation.with(t.clone());
521 self.evaluate_obligation_recursively(previous_stack, &obligation)
524 ty::Predicate::Equate(ref p) => {
525 // does this code ever run?
526 match self.infcx.equality_predicate(obligation.cause.span, p) {
527 Ok(InferOk { obligations, .. }) => {
528 self.inferred_obligations.extend(obligations);
531 Err(_) => EvaluatedToErr
535 ty::Predicate::WellFormed(ty) => {
536 match ty::wf::obligations(self.infcx, obligation.cause.body_id,
537 ty, obligation.cause.span) {
539 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
545 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
546 // we do not consider region relationships when
547 // evaluating trait matches
551 ty::Predicate::ObjectSafe(trait_def_id) => {
552 if self.tcx().is_object_safe(trait_def_id) {
559 ty::Predicate::Projection(ref data) => {
560 let project_obligation = obligation.with(data.clone());
561 match project::poly_project_and_unify_type(self, &project_obligation) {
562 Ok(Some(subobligations)) => {
563 self.evaluate_predicates_recursively(previous_stack,
564 subobligations.iter())
575 ty::Predicate::ClosureKind(closure_def_id, kind) => {
576 match self.infcx.closure_kind(closure_def_id) {
577 Some(closure_kind) => {
578 if closure_kind.extends(kind) {
592 fn evaluate_obligation_recursively<'o>(&mut self,
593 previous_stack: TraitObligationStackList<'o, 'tcx>,
594 obligation: &TraitObligation<'tcx>)
597 debug!("evaluate_obligation_recursively({:?})",
600 let stack = self.push_stack(previous_stack, obligation);
601 let fresh_trait_ref = stack.fresh_trait_ref;
602 if let Some(result) = self.check_evaluation_cache(fresh_trait_ref) {
603 debug!("CACHE HIT: EVAL({:?})={:?}",
609 let result = self.evaluate_stack(&stack);
611 debug!("CACHE MISS: EVAL({:?})={:?}",
614 self.insert_evaluation_cache(fresh_trait_ref, result);
619 fn evaluate_stack<'o>(&mut self,
620 stack: &TraitObligationStack<'o, 'tcx>)
623 // In intercrate mode, whenever any of the types are unbound,
624 // there can always be an impl. Even if there are no impls in
625 // this crate, perhaps the type would be unified with
626 // something from another crate that does provide an impl.
628 // In intra mode, we must still be conservative. The reason is
629 // that we want to avoid cycles. Imagine an impl like:
631 // impl<T:Eq> Eq for Vec<T>
633 // and a trait reference like `$0 : Eq` where `$0` is an
634 // unbound variable. When we evaluate this trait-reference, we
635 // will unify `$0` with `Vec<$1>` (for some fresh variable
636 // `$1`), on the condition that `$1 : Eq`. We will then wind
637 // up with many candidates (since that are other `Eq` impls
638 // that apply) and try to winnow things down. This results in
639 // a recursive evaluation that `$1 : Eq` -- as you can
640 // imagine, this is just where we started. To avoid that, we
641 // check for unbound variables and return an ambiguous (hence possible)
642 // match if we've seen this trait before.
644 // This suffices to allow chains like `FnMut` implemented in
645 // terms of `Fn` etc, but we could probably make this more
647 let input_types = stack.fresh_trait_ref.0.input_types();
648 let unbound_input_types = input_types.iter().any(|ty| ty.is_fresh());
649 if unbound_input_types && self.intercrate {
650 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
651 stack.fresh_trait_ref);
652 return EvaluatedToAmbig;
654 if unbound_input_types &&
655 stack.iter().skip(1).any(
656 |prev| self.match_fresh_trait_refs(&stack.fresh_trait_ref,
657 &prev.fresh_trait_ref))
659 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
660 stack.fresh_trait_ref);
661 return EvaluatedToUnknown;
664 // If there is any previous entry on the stack that precisely
665 // matches this obligation, then we can assume that the
666 // obligation is satisfied for now (still all other conditions
667 // must be met of course). One obvious case this comes up is
668 // marker traits like `Send`. Think of a linked list:
670 // struct List<T> { data: T, next: Option<Box<List<T>>> {
672 // `Box<List<T>>` will be `Send` if `T` is `Send` and
673 // `Option<Box<List<T>>>` is `Send`, and in turn
674 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
677 // Note that we do this comparison using the `fresh_trait_ref`
678 // fields. Because these have all been skolemized using
679 // `self.freshener`, we can be sure that (a) this will not
680 // affect the inferencer state and (b) that if we see two
681 // skolemized types with the same index, they refer to the
682 // same unbound type variable.
685 .skip(1) // skip top-most frame
686 .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref)
688 debug!("evaluate_stack({:?}) --> recursive",
689 stack.fresh_trait_ref);
690 return EvaluatedToOk;
693 match self.candidate_from_obligation(stack) {
694 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
695 Ok(None) => EvaluatedToAmbig,
696 Err(..) => EvaluatedToErr
700 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
701 /// obligations are met. Returns true if `candidate` remains viable after this further
703 fn evaluate_candidate<'o>(&mut self,
704 stack: &TraitObligationStack<'o, 'tcx>,
705 candidate: &SelectionCandidate<'tcx>)
708 debug!("evaluate_candidate: depth={} candidate={:?}",
709 stack.obligation.recursion_depth, candidate);
710 let result = self.probe(|this, _| {
711 let candidate = (*candidate).clone();
712 match this.confirm_candidate(stack.obligation, candidate) {
714 this.evaluate_predicates_recursively(
716 selection.nested_obligations().iter())
718 Err(..) => EvaluatedToErr
721 debug!("evaluate_candidate: depth={} result={:?}",
722 stack.obligation.recursion_depth, result);
726 fn check_evaluation_cache(&self, trait_ref: ty::PolyTraitRef<'tcx>)
727 -> Option<EvaluationResult>
729 if self.can_use_global_caches() {
730 let cache = self.tcx().evaluation_cache.hashmap.borrow();
731 if let Some(cached) = cache.get(&trait_ref) {
732 return Some(cached.clone());
735 self.infcx.evaluation_cache.hashmap.borrow().get(&trait_ref).cloned()
738 fn insert_evaluation_cache(&mut self,
739 trait_ref: ty::PolyTraitRef<'tcx>,
740 result: EvaluationResult)
742 // Avoid caching results that depend on more than just the trait-ref:
743 // The stack can create EvaluatedToUnknown, and closure signatures
744 // being yet uninferred can create "spurious" EvaluatedToAmbig
745 // and EvaluatedToOk.
746 if result == EvaluatedToUnknown ||
747 ((result == EvaluatedToAmbig || result == EvaluatedToOk)
748 && trait_ref.has_closure_types())
753 if self.can_use_global_caches() {
754 let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
755 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
756 cache.insert(trait_ref, result);
761 self.infcx.evaluation_cache.hashmap.borrow_mut().insert(trait_ref, result);
764 ///////////////////////////////////////////////////////////////////////////
765 // CANDIDATE ASSEMBLY
767 // The selection process begins by examining all in-scope impls,
768 // caller obligations, and so forth and assembling a list of
769 // candidates. See `README.md` and the `Candidate` type for more
772 fn candidate_from_obligation<'o>(&mut self,
773 stack: &TraitObligationStack<'o, 'tcx>)
774 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
776 // Watch out for overflow. This intentionally bypasses (and does
777 // not update) the cache.
778 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
779 if stack.obligation.recursion_depth >= recursion_limit {
780 self.infcx().report_overflow_error(&stack.obligation, true);
783 // Check the cache. Note that we skolemize the trait-ref
784 // separately rather than using `stack.fresh_trait_ref` -- this
785 // is because we want the unbound variables to be replaced
786 // with fresh skolemized types starting from index 0.
787 let cache_fresh_trait_pred =
788 self.infcx.freshen(stack.obligation.predicate.clone());
789 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
790 cache_fresh_trait_pred,
792 assert!(!stack.obligation.predicate.has_escaping_regions());
794 match self.check_candidate_cache(&cache_fresh_trait_pred) {
796 debug!("CACHE HIT: SELECT({:?})={:?}",
797 cache_fresh_trait_pred,
804 // If no match, compute result and insert into cache.
805 let candidate = self.candidate_from_obligation_no_cache(stack);
807 if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
808 debug!("CACHE MISS: SELECT({:?})={:?}",
809 cache_fresh_trait_pred, candidate);
810 self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone());
816 // Treat negative impls as unimplemented
817 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
818 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
819 if let ImplCandidate(def_id) = candidate {
820 if self.tcx().trait_impl_polarity(def_id) == Some(hir::ImplPolarity::Negative) {
821 return Err(Unimplemented)
827 fn candidate_from_obligation_no_cache<'o>(&mut self,
828 stack: &TraitObligationStack<'o, 'tcx>)
829 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
831 if stack.obligation.predicate.references_error() {
832 // If we encounter a `TyError`, we generally prefer the
833 // most "optimistic" result in response -- that is, the
834 // one least likely to report downstream errors. But
835 // because this routine is shared by coherence and by
836 // trait selection, there isn't an obvious "right" choice
837 // here in that respect, so we opt to just return
838 // ambiguity and let the upstream clients sort it out.
842 if !self.is_knowable(stack) {
843 debug!("coherence stage: not knowable");
847 let candidate_set = self.assemble_candidates(stack)?;
849 if candidate_set.ambiguous {
850 debug!("candidate set contains ambig");
854 let mut candidates = candidate_set.vec;
856 debug!("assembled {} candidates for {:?}: {:?}",
861 // At this point, we know that each of the entries in the
862 // candidate set is *individually* applicable. Now we have to
863 // figure out if they contain mutual incompatibilities. This
864 // frequently arises if we have an unconstrained input type --
865 // for example, we are looking for $0:Eq where $0 is some
866 // unconstrained type variable. In that case, we'll get a
867 // candidate which assumes $0 == int, one that assumes $0 ==
868 // usize, etc. This spells an ambiguity.
870 // If there is more than one candidate, first winnow them down
871 // by considering extra conditions (nested obligations and so
872 // forth). We don't winnow if there is exactly one
873 // candidate. This is a relatively minor distinction but it
874 // can lead to better inference and error-reporting. An
875 // example would be if there was an impl:
877 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
879 // and we were to see some code `foo.push_clone()` where `boo`
880 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
881 // we were to winnow, we'd wind up with zero candidates.
882 // Instead, we select the right impl now but report `Bar does
883 // not implement Clone`.
884 if candidates.len() == 1 {
885 return self.filter_negative_impls(candidates.pop().unwrap());
888 // Winnow, but record the exact outcome of evaluation, which
889 // is needed for specialization.
890 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
891 let eval = self.evaluate_candidate(stack, &c);
892 if eval.may_apply() {
893 Some(EvaluatedCandidate {
902 // If there are STILL multiple candidate, we can further
903 // reduce the list by dropping duplicates -- including
904 // resolving specializations.
905 if candidates.len() > 1 {
907 while i < candidates.len() {
909 (0..candidates.len())
911 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
914 debug!("Dropping candidate #{}/{}: {:?}",
915 i, candidates.len(), candidates[i]);
916 candidates.swap_remove(i);
918 debug!("Retaining candidate #{}/{}: {:?}",
919 i, candidates.len(), candidates[i]);
925 // If there are *STILL* multiple candidates, give up and
927 if candidates.len() > 1 {
928 debug!("multiple matches, ambig");
932 // If there are *NO* candidates, then there are no impls --
933 // that we know of, anyway. Note that in the case where there
934 // are unbound type variables within the obligation, it might
935 // be the case that you could still satisfy the obligation
936 // from another crate by instantiating the type variables with
937 // a type from another crate that does have an impl. This case
938 // is checked for in `evaluate_stack` (and hence users
939 // who might care about this case, like coherence, should use
941 if candidates.is_empty() {
942 return Err(Unimplemented);
945 // Just one candidate left.
946 self.filter_negative_impls(candidates.pop().unwrap().candidate)
949 fn is_knowable<'o>(&mut self,
950 stack: &TraitObligationStack<'o, 'tcx>)
953 debug!("is_knowable(intercrate={})", self.intercrate);
955 if !self.intercrate {
959 let obligation = &stack.obligation;
960 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
962 // ok to skip binder because of the nature of the
963 // trait-ref-is-knowable check, which does not care about
965 let trait_ref = &predicate.skip_binder().trait_ref;
967 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
970 /// Returns true if the global caches can be used.
971 /// Do note that if the type itself is not in the
972 /// global tcx, the local caches will be used.
973 fn can_use_global_caches(&self) -> bool {
974 // If there are any where-clauses in scope, then we always use
975 // a cache local to this particular scope. Otherwise, we
976 // switch to a global cache. We used to try and draw
977 // finer-grained distinctions, but that led to a serious of
978 // annoying and weird bugs like #22019 and #18290. This simple
979 // rule seems to be pretty clearly safe and also still retains
980 // a very high hit rate (~95% when compiling rustc).
981 if !self.param_env().caller_bounds.is_empty() {
985 // Avoid using the master cache during coherence and just rely
986 // on the local cache. This effectively disables caching
987 // during coherence. It is really just a simplification to
988 // avoid us having to fear that coherence results "pollute"
989 // the master cache. Since coherence executes pretty quickly,
990 // it's not worth going to more trouble to increase the
991 // hit-rate I don't think.
996 // Otherwise, we can use the global cache.
1000 fn check_candidate_cache(&mut self,
1001 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1002 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1004 let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1005 if self.can_use_global_caches() {
1006 let cache = self.tcx().selection_cache.hashmap.borrow();
1007 if let Some(cached) = cache.get(&trait_ref) {
1008 return Some(cached.clone());
1011 self.infcx.selection_cache.hashmap.borrow().get(trait_ref).cloned()
1014 fn insert_candidate_cache(&mut self,
1015 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1016 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1018 let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1019 if self.can_use_global_caches() {
1020 let mut cache = self.tcx().selection_cache.hashmap.borrow_mut();
1021 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1022 if let Some(candidate) = self.tcx().lift_to_global(&candidate) {
1023 cache.insert(trait_ref, candidate);
1029 self.infcx.selection_cache.hashmap.borrow_mut().insert(trait_ref, candidate);
1032 fn should_update_candidate_cache(&mut self,
1033 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1034 candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1037 // In general, it's a good idea to cache results, even
1038 // ambiguous ones, to save us some trouble later. But we have
1039 // to be careful not to cache results that could be
1040 // invalidated later by advances in inference. Normally, this
1041 // is not an issue, because any inference variables whose
1042 // types are not yet bound are "freshened" in the cache key,
1043 // which means that if we later get the same request once that
1044 // type variable IS bound, we'll have a different cache key.
1045 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
1046 // not yet known, we may cache the result as `None`. But if
1047 // later `_#0t` is bound to `Bar`, then when we freshen we'll
1048 // have `Vec<Bar> : Foo` as the cache key.
1050 // HOWEVER, it CAN happen that we get an ambiguity result in
1051 // one particular case around closures where the cache key
1052 // would not change. That is when the precise types of the
1053 // upvars that a closure references have not yet been figured
1054 // out (i.e., because it is not yet known if they are captured
1055 // by ref, and if by ref, what kind of ref). In these cases,
1056 // when matching a builtin bound, we will yield back an
1057 // ambiguous result. But the *cache key* is just the closure type,
1058 // it doesn't capture the state of the upvar computation.
1060 // To avoid this trap, just don't cache ambiguous results if
1061 // the self-type contains no inference byproducts (that really
1062 // shouldn't happen in other circumstances anyway, given
1066 Ok(Some(_)) | Err(_) => true,
1068 cache_fresh_trait_pred.0.trait_ref.substs.types.has_infer_types()
1073 fn assemble_candidates<'o>(&mut self,
1074 stack: &TraitObligationStack<'o, 'tcx>)
1075 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1077 let TraitObligationStack { obligation, .. } = *stack;
1078 let ref obligation = Obligation {
1079 cause: obligation.cause.clone(),
1080 recursion_depth: obligation.recursion_depth,
1081 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1084 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1085 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1087 // This is somewhat problematic, as the current scheme can't really
1088 // handle it turning to be a projection. This does end up as truly
1089 // ambiguous in most cases anyway.
1091 // Until this is fixed, take the fast path out - this also improves
1092 // performance by preventing assemble_candidates_from_impls from
1093 // matching every impl for this trait.
1094 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1097 let mut candidates = SelectionCandidateSet {
1102 // Other bounds. Consider both in-scope bounds from fn decl
1103 // and applicable impls. There is a certain set of precedence rules here.
1105 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
1106 Some(ty::BoundCopy) => {
1107 debug!("obligation self ty is {:?}",
1108 obligation.predicate.0.self_ty());
1110 // User-defined copy impls are permitted, but only for
1111 // structs and enums.
1112 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1114 // For other types, we'll use the builtin rules.
1115 let copy_conditions = self.copy_conditions(obligation);
1116 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1118 Some(ty::BoundSized) => {
1119 // Sized is never implementable by end-users, it is
1120 // always automatically computed.
1121 let sized_conditions = self.sized_conditions(obligation);
1122 self.assemble_builtin_bound_candidates(sized_conditions,
1126 None if self.tcx().lang_items.unsize_trait() ==
1127 Some(obligation.predicate.def_id()) => {
1128 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1131 Some(ty::BoundSend) |
1132 Some(ty::BoundSync) |
1134 self.assemble_closure_candidates(obligation, &mut candidates)?;
1135 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1136 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1137 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1141 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1142 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1143 // Default implementations have lower priority, so we only
1144 // consider triggering a default if there is no other impl that can apply.
1145 if candidates.vec.is_empty() {
1146 self.assemble_candidates_from_default_impls(obligation, &mut candidates)?;
1148 debug!("candidate list size: {}", candidates.vec.len());
1152 fn assemble_candidates_from_projected_tys(&mut self,
1153 obligation: &TraitObligation<'tcx>,
1154 candidates: &mut SelectionCandidateSet<'tcx>)
1156 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1158 // FIXME(#20297) -- just examining the self-type is very simplistic
1160 // before we go into the whole skolemization thing, just
1161 // quickly check if the self-type is a projection at all.
1162 match obligation.predicate.0.trait_ref.self_ty().sty {
1163 ty::TyProjection(_) | ty::TyAnon(..) => {}
1164 ty::TyInfer(ty::TyVar(_)) => {
1165 span_bug!(obligation.cause.span,
1166 "Self=_ should have been handled by assemble_candidates");
1171 let result = self.probe(|this, snapshot| {
1172 this.match_projection_obligation_against_definition_bounds(obligation,
1177 candidates.vec.push(ProjectionCandidate);
1181 fn match_projection_obligation_against_definition_bounds(
1183 obligation: &TraitObligation<'tcx>,
1184 snapshot: &infer::CombinedSnapshot)
1187 let poly_trait_predicate =
1188 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1189 let (skol_trait_predicate, skol_map) =
1190 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1191 debug!("match_projection_obligation_against_definition_bounds: \
1192 skol_trait_predicate={:?} skol_map={:?}",
1193 skol_trait_predicate,
1196 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1197 ty::TyProjection(ref data) => (data.trait_ref.def_id, data.trait_ref.substs),
1198 ty::TyAnon(def_id, substs) => (def_id, substs),
1201 obligation.cause.span,
1202 "match_projection_obligation_against_definition_bounds() called \
1203 but self-ty not a projection: {:?}",
1204 skol_trait_predicate.trait_ref.self_ty());
1207 debug!("match_projection_obligation_against_definition_bounds: \
1208 def_id={:?}, substs={:?}",
1211 let item_predicates = self.tcx().lookup_predicates(def_id);
1212 let bounds = item_predicates.instantiate(self.tcx(), substs);
1213 debug!("match_projection_obligation_against_definition_bounds: \
1217 let matching_bound =
1218 util::elaborate_predicates(self.tcx(), bounds.predicates)
1222 |this, _| this.match_projection(obligation,
1224 skol_trait_predicate.trait_ref.clone(),
1228 debug!("match_projection_obligation_against_definition_bounds: \
1229 matching_bound={:?}",
1231 match matching_bound {
1234 // Repeat the successful match, if any, this time outside of a probe.
1235 let result = self.match_projection(obligation,
1237 skol_trait_predicate.trait_ref.clone(),
1241 self.infcx.pop_skolemized(skol_map, snapshot);
1249 fn match_projection(&mut self,
1250 obligation: &TraitObligation<'tcx>,
1251 trait_bound: ty::PolyTraitRef<'tcx>,
1252 skol_trait_ref: ty::TraitRef<'tcx>,
1253 skol_map: &infer::SkolemizationMap,
1254 snapshot: &infer::CombinedSnapshot)
1257 assert!(!skol_trait_ref.has_escaping_regions());
1258 let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
1259 match self.infcx.sub_poly_trait_refs(false,
1261 trait_bound.clone(),
1262 ty::Binder(skol_trait_ref.clone())) {
1263 Ok(InferOk { obligations, .. }) => {
1264 self.inferred_obligations.extend(obligations);
1266 Err(_) => { return false; }
1269 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1272 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1273 /// supplied to find out whether it is listed among them.
1275 /// Never affects inference environment.
1276 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1277 stack: &TraitObligationStack<'o, 'tcx>,
1278 candidates: &mut SelectionCandidateSet<'tcx>)
1279 -> Result<(),SelectionError<'tcx>>
1281 debug!("assemble_candidates_from_caller_bounds({:?})",
1285 self.param_env().caller_bounds
1287 .filter_map(|o| o.to_opt_poly_trait_ref());
1289 let matching_bounds =
1291 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1293 let param_candidates =
1294 matching_bounds.map(|bound| ParamCandidate(bound));
1296 candidates.vec.extend(param_candidates);
1301 fn evaluate_where_clause<'o>(&mut self,
1302 stack: &TraitObligationStack<'o, 'tcx>,
1303 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1306 self.probe(move |this, _| {
1307 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1308 Ok(obligations) => {
1309 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1311 Err(()) => EvaluatedToErr
1316 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1317 /// FnMut<..>` where `X` is a closure type.
1319 /// Note: the type parameters on a closure candidate are modeled as *output* type
1320 /// parameters and hence do not affect whether this trait is a match or not. They will be
1321 /// unified during the confirmation step.
1322 fn assemble_closure_candidates(&mut self,
1323 obligation: &TraitObligation<'tcx>,
1324 candidates: &mut SelectionCandidateSet<'tcx>)
1325 -> Result<(),SelectionError<'tcx>>
1327 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1329 None => { return Ok(()); }
1332 // ok to skip binder because the substs on closure types never
1333 // touch bound regions, they just capture the in-scope
1334 // type/region parameters
1335 let self_ty = *obligation.self_ty().skip_binder();
1336 let (closure_def_id, substs) = match self_ty.sty {
1337 ty::TyClosure(id, substs) => (id, substs),
1338 ty::TyInfer(ty::TyVar(_)) => {
1339 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1340 candidates.ambiguous = true;
1343 _ => { return Ok(()); }
1346 debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1351 match self.infcx.closure_kind(closure_def_id) {
1352 Some(closure_kind) => {
1353 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1354 if closure_kind.extends(kind) {
1355 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1359 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1360 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1367 /// Implement one of the `Fn()` family for a fn pointer.
1368 fn assemble_fn_pointer_candidates(&mut self,
1369 obligation: &TraitObligation<'tcx>,
1370 candidates: &mut SelectionCandidateSet<'tcx>)
1371 -> Result<(),SelectionError<'tcx>>
1373 // We provide impl of all fn traits for fn pointers.
1374 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1378 // ok to skip binder because what we are inspecting doesn't involve bound regions
1379 let self_ty = *obligation.self_ty().skip_binder();
1381 ty::TyInfer(ty::TyVar(_)) => {
1382 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1383 candidates.ambiguous = true; // could wind up being a fn() type
1386 // provide an impl, but only for suitable `fn` pointers
1387 ty::TyFnDef(_, _, &ty::BareFnTy {
1388 unsafety: hir::Unsafety::Normal,
1390 sig: ty::Binder(ty::FnSig {
1396 ty::TyFnPtr(&ty::BareFnTy {
1397 unsafety: hir::Unsafety::Normal,
1399 sig: ty::Binder(ty::FnSig {
1405 candidates.vec.push(FnPointerCandidate);
1414 /// Search for impls that might apply to `obligation`.
1415 fn assemble_candidates_from_impls(&mut self,
1416 obligation: &TraitObligation<'tcx>,
1417 candidates: &mut SelectionCandidateSet<'tcx>)
1418 -> Result<(), SelectionError<'tcx>>
1420 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1422 let def = self.tcx().lookup_trait_def(obligation.predicate.def_id());
1424 def.for_each_relevant_impl(
1426 obligation.predicate.0.trait_ref.self_ty(),
1428 self.probe(|this, snapshot| { /* [1] */
1429 match this.match_impl(impl_def_id, obligation, snapshot) {
1431 candidates.vec.push(ImplCandidate(impl_def_id));
1433 // NB: we can safely drop the skol map
1434 // since we are in a probe [1]
1435 mem::drop(skol_map);
1446 fn assemble_candidates_from_default_impls(&mut self,
1447 obligation: &TraitObligation<'tcx>,
1448 candidates: &mut SelectionCandidateSet<'tcx>)
1449 -> Result<(), SelectionError<'tcx>>
1451 // OK to skip binder here because the tests we do below do not involve bound regions
1452 let self_ty = *obligation.self_ty().skip_binder();
1453 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1455 let def_id = obligation.predicate.def_id();
1457 if self.tcx().trait_has_default_impl(def_id) {
1459 ty::TyTrait(..) => {
1460 // For object types, we don't know what the closed
1461 // over types are. For most traits, this means we
1462 // conservatively say nothing; a candidate may be
1463 // added by `assemble_candidates_from_object_ty`.
1464 // However, for the kind of magic reflect trait,
1465 // we consider it to be implemented even for
1466 // object types, because it just lets you reflect
1467 // onto the object type, not into the object's
1469 if self.tcx().has_attr(def_id, "rustc_reflect_like") {
1470 candidates.vec.push(DefaultImplObjectCandidate(def_id));
1474 ty::TyProjection(..) |
1476 // In these cases, we don't know what the actual
1477 // type is. Therefore, we cannot break it down
1478 // into its constituent types. So we don't
1479 // consider the `..` impl but instead just add no
1480 // candidates: this means that typeck will only
1481 // succeed if there is another reason to believe
1482 // that this obligation holds. That could be a
1483 // where-clause or, in the case of an object type,
1484 // it could be that the object type lists the
1485 // trait (e.g. `Foo+Send : Send`). See
1486 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1487 // for an example of a test case that exercises
1490 ty::TyInfer(ty::TyVar(_)) => {
1491 // the defaulted impl might apply, we don't know
1492 candidates.ambiguous = true;
1495 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1503 /// Search for impls that might apply to `obligation`.
1504 fn assemble_candidates_from_object_ty(&mut self,
1505 obligation: &TraitObligation<'tcx>,
1506 candidates: &mut SelectionCandidateSet<'tcx>)
1508 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1509 obligation.self_ty().skip_binder());
1511 // Object-safety candidates are only applicable to object-safe
1512 // traits. Including this check is useful because it helps
1513 // inference in cases of traits like `BorrowFrom`, which are
1514 // not object-safe, and which rely on being able to infer the
1515 // self-type from one of the other inputs. Without this check,
1516 // these cases wind up being considered ambiguous due to a
1517 // (spurious) ambiguity introduced here.
1518 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1519 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1523 self.probe(|this, _snapshot| {
1524 // the code below doesn't care about regions, and the
1525 // self-ty here doesn't escape this probe, so just erase
1527 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1528 let poly_trait_ref = match self_ty.sty {
1529 ty::TyTrait(ref data) => {
1530 match this.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
1531 Some(bound @ ty::BoundSend) | Some(bound @ ty::BoundSync) => {
1532 if data.builtin_bounds.contains(&bound) {
1533 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1534 pushing candidate");
1535 candidates.vec.push(BuiltinObjectCandidate);
1542 data.principal.with_self_ty(this.tcx(), self_ty)
1544 ty::TyInfer(ty::TyVar(_)) => {
1545 debug!("assemble_candidates_from_object_ty: ambiguous");
1546 candidates.ambiguous = true; // could wind up being an object type
1554 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1557 // Count only those upcast versions that match the trait-ref
1558 // we are looking for. Specifically, do not only check for the
1559 // correct trait, but also the correct type parameters.
1560 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1561 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1562 let upcast_trait_refs =
1563 util::supertraits(this.tcx(), poly_trait_ref)
1564 .filter(|upcast_trait_ref| {
1565 this.probe(|this, _| {
1566 let upcast_trait_ref = upcast_trait_ref.clone();
1567 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1572 if upcast_trait_refs > 1 {
1573 // can be upcast in many ways; need more type information
1574 candidates.ambiguous = true;
1575 } else if upcast_trait_refs == 1 {
1576 candidates.vec.push(ObjectCandidate);
1581 /// Search for unsizing that might apply to `obligation`.
1582 fn assemble_candidates_for_unsizing(&mut self,
1583 obligation: &TraitObligation<'tcx>,
1584 candidates: &mut SelectionCandidateSet<'tcx>) {
1585 // We currently never consider higher-ranked obligations e.g.
1586 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1587 // because they are a priori invalid, and we could potentially add support
1588 // for them later, it's just that there isn't really a strong need for it.
1589 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1590 // impl, and those are generally applied to concrete types.
1592 // That said, one might try to write a fn with a where clause like
1593 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1594 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1595 // Still, you'd be more likely to write that where clause as
1597 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1598 // obligation above. Should be possible to extend this in the future.
1599 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1602 // Don't add any candidates if there are bound regions.
1606 let target = obligation.predicate.skip_binder().input_types()[1];
1608 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1611 let may_apply = match (&source.sty, &target.sty) {
1612 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1613 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
1614 // Upcasts permit two things:
1616 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1617 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1619 // Note that neither of these changes requires any
1620 // change at runtime. Eventually this will be
1623 // We always upcast when we can because of reason
1624 // #2 (region bounds).
1625 data_a.principal.def_id() == data_a.principal.def_id() &&
1626 data_a.builtin_bounds.is_superset(&data_b.builtin_bounds)
1630 (_, &ty::TyTrait(_)) => true,
1632 // Ambiguous handling is below T -> Trait, because inference
1633 // variables can still implement Unsize<Trait> and nested
1634 // obligations will have the final say (likely deferred).
1635 (&ty::TyInfer(ty::TyVar(_)), _) |
1636 (_, &ty::TyInfer(ty::TyVar(_))) => {
1637 debug!("assemble_candidates_for_unsizing: ambiguous");
1638 candidates.ambiguous = true;
1643 (&ty::TyArray(_, _), &ty::TySlice(_)) => true,
1645 // Struct<T> -> Struct<U>.
1646 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
1647 def_id_a == def_id_b
1654 candidates.vec.push(BuiltinUnsizeCandidate);
1658 ///////////////////////////////////////////////////////////////////////////
1661 // Winnowing is the process of attempting to resolve ambiguity by
1662 // probing further. During the winnowing process, we unify all
1663 // type variables (ignoring skolemization) and then we also
1664 // attempt to evaluate recursive bounds to see if they are
1667 /// Returns true if `candidate_i` should be dropped in favor of
1668 /// `candidate_j`. Generally speaking we will drop duplicate
1669 /// candidates and prefer where-clause candidates.
1670 /// Returns true if `victim` should be dropped in favor of
1671 /// `other`. Generally speaking we will drop duplicate
1672 /// candidates and prefer where-clause candidates.
1674 /// See the comment for "SelectionCandidate" for more details.
1675 fn candidate_should_be_dropped_in_favor_of<'o>(
1677 victim: &EvaluatedCandidate<'tcx>,
1678 other: &EvaluatedCandidate<'tcx>)
1681 if victim.candidate == other.candidate {
1685 match other.candidate {
1687 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1688 DefaultImplCandidate(..) => {
1690 "default implementations shouldn't be recorded \
1691 when there are other valid candidates");
1694 ClosureCandidate(..) |
1695 FnPointerCandidate |
1696 BuiltinObjectCandidate |
1697 BuiltinUnsizeCandidate |
1698 DefaultImplObjectCandidate(..) |
1699 BuiltinCandidate { .. } => {
1700 // We have a where-clause so don't go around looking
1705 ProjectionCandidate => {
1706 // Arbitrarily give param candidates priority
1707 // over projection and object candidates.
1710 ParamCandidate(..) => false,
1712 ImplCandidate(other_def) => {
1713 // See if we can toss out `victim` based on specialization.
1714 // This requires us to know *for sure* that the `other` impl applies
1715 // i.e. EvaluatedToOk:
1716 if other.evaluation == EvaluatedToOk {
1717 if let ImplCandidate(victim_def) = victim.candidate {
1718 let tcx = self.tcx().global_tcx();
1719 return traits::specializes(tcx, other_def, victim_def);
1729 ///////////////////////////////////////////////////////////////////////////
1732 // These cover the traits that are built-in to the language
1733 // itself. This includes `Copy` and `Sized` for sure. For the
1734 // moment, it also includes `Send` / `Sync` and a few others, but
1735 // those will hopefully change to library-defined traits in the
1738 // HACK: if this returns an error, selection exits without considering
1740 fn assemble_builtin_bound_candidates<'o>(&mut self,
1741 conditions: BuiltinImplConditions<'tcx>,
1742 candidates: &mut SelectionCandidateSet<'tcx>)
1743 -> Result<(),SelectionError<'tcx>>
1746 BuiltinImplConditions::Where(nested) => {
1747 debug!("builtin_bound: nested={:?}", nested);
1748 candidates.vec.push(BuiltinCandidate {
1749 has_nested: nested.skip_binder().len() > 0
1753 BuiltinImplConditions::None => { Ok(()) }
1754 BuiltinImplConditions::Ambiguous => {
1755 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1756 Ok(candidates.ambiguous = true)
1758 BuiltinImplConditions::Never => { Err(Unimplemented) }
1762 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1763 -> BuiltinImplConditions<'tcx>
1765 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1767 // NOTE: binder moved to (*)
1768 let self_ty = self.infcx.shallow_resolve(
1769 obligation.predicate.skip_binder().self_ty());
1772 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1773 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1774 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
1775 ty::TyChar | ty::TyBox(_) | ty::TyRef(..) |
1776 ty::TyArray(..) | ty::TyClosure(..) | ty::TyNever |
1778 // safe for everything
1779 Where(ty::Binder(Vec::new()))
1782 ty::TyStr | ty::TySlice(_) | ty::TyTrait(..) => Never,
1784 ty::TyTuple(tys) => {
1785 // FIXME(#33242) we only need to constrain the last field
1786 Where(ty::Binder(tys.to_vec()))
1789 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1790 let sized_crit = def.sized_constraint(self.tcx());
1791 // (*) binder moved here
1792 Where(ty::Binder(match sized_crit.sty {
1793 ty::TyTuple(tys) => tys.to_vec().subst(self.tcx(), substs),
1794 ty::TyBool => vec![],
1795 _ => vec![sized_crit.subst(self.tcx(), substs)]
1799 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
1800 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
1802 ty::TyInfer(ty::FreshTy(_))
1803 | ty::TyInfer(ty::FreshIntTy(_))
1804 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1805 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1811 fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1812 -> BuiltinImplConditions<'tcx>
1814 // NOTE: binder moved to (*)
1815 let self_ty = self.infcx.shallow_resolve(
1816 obligation.predicate.skip_binder().self_ty());
1818 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1821 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1822 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1823 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1824 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
1825 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
1826 Where(ty::Binder(Vec::new()))
1829 ty::TyBox(_) | ty::TyTrait(..) | ty::TyStr | ty::TySlice(..) |
1831 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
1835 ty::TyArray(element_ty, _) => {
1836 // (*) binder moved here
1837 Where(ty::Binder(vec![element_ty]))
1840 ty::TyTuple(tys) => {
1841 // (*) binder moved here
1842 Where(ty::Binder(tys.to_vec()))
1845 ty::TyStruct(..) | ty::TyEnum(..) |
1846 ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
1847 // Fallback to whatever user-defined impls exist in this case.
1851 ty::TyInfer(ty::TyVar(_)) => {
1852 // Unbound type variable. Might or might not have
1853 // applicable impls and so forth, depending on what
1854 // those type variables wind up being bound to.
1858 ty::TyInfer(ty::FreshTy(_))
1859 | ty::TyInfer(ty::FreshIntTy(_))
1860 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1861 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1867 /// For default impls, we need to break apart a type into its
1868 /// "constituent types" -- meaning, the types that it contains.
1870 /// Here are some (simple) examples:
1873 /// (i32, u32) -> [i32, u32]
1874 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1875 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1876 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1878 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1888 ty::TyInfer(ty::IntVar(_)) |
1889 ty::TyInfer(ty::FloatVar(_)) |
1897 ty::TyProjection(..) |
1899 ty::TyInfer(ty::TyVar(_)) |
1900 ty::TyInfer(ty::FreshTy(_)) |
1901 ty::TyInfer(ty::FreshIntTy(_)) |
1902 ty::TyInfer(ty::FreshFloatTy(_)) => {
1903 bug!("asked to assemble constituent types of unexpected type: {:?}",
1907 ty::TyBox(referent_ty) => { // Box<T>
1911 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
1912 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
1916 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
1920 ty::TyTuple(ref tys) => {
1921 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1925 ty::TyClosure(_, ref substs) => {
1926 // FIXME(#27086). We are invariant w/r/t our
1927 // substs.func_substs, but we don't see them as
1928 // constituent types; this seems RIGHT but also like
1929 // something that a normal type couldn't simulate. Is
1930 // this just a gap with the way that PhantomData and
1931 // OIBIT interact? That is, there is no way to say
1932 // "make me invariant with respect to this TYPE, but
1933 // do not act as though I can reach it"
1934 substs.upvar_tys.to_vec()
1937 // for `PhantomData<T>`, we pass `T`
1938 ty::TyStruct(def, substs) if def.is_phantom_data() => {
1939 substs.types.to_vec()
1942 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1944 .map(|f| f.ty(self.tcx(), substs))
1950 fn collect_predicates_for_types(&mut self,
1951 cause: ObligationCause<'tcx>,
1952 recursion_depth: usize,
1953 trait_def_id: DefId,
1954 types: ty::Binder<Vec<Ty<'tcx>>>)
1955 -> Vec<PredicateObligation<'tcx>>
1957 // Because the types were potentially derived from
1958 // higher-ranked obligations they may reference late-bound
1959 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1960 // yield a type like `for<'a> &'a int`. In general, we
1961 // maintain the invariant that we never manipulate bound
1962 // regions, so we have to process these bound regions somehow.
1964 // The strategy is to:
1966 // 1. Instantiate those regions to skolemized regions (e.g.,
1967 // `for<'a> &'a int` becomes `&0 int`.
1968 // 2. Produce something like `&'0 int : Copy`
1969 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1971 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
1972 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
1974 self.in_snapshot(|this, snapshot| {
1975 let (skol_ty, skol_map) =
1976 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
1977 let Normalized { value: normalized_ty, mut obligations } =
1978 project::normalize_with_depth(this,
1982 let skol_obligation =
1983 this.tcx().predicate_for_trait_def(
1989 obligations.push(skol_obligation);
1990 this.infcx().plug_leaks(skol_map, snapshot, &obligations)
1995 ///////////////////////////////////////////////////////////////////////////
1998 // Confirmation unifies the output type parameters of the trait
1999 // with the values found in the obligation, possibly yielding a
2000 // type error. See `README.md` for more details.
2002 fn confirm_candidate(&mut self,
2003 obligation: &TraitObligation<'tcx>,
2004 candidate: SelectionCandidate<'tcx>)
2005 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2007 debug!("confirm_candidate({:?}, {:?})",
2012 BuiltinCandidate { has_nested } => {
2014 self.confirm_builtin_candidate(obligation, has_nested)))
2017 ParamCandidate(param) => {
2018 let obligations = self.confirm_param_candidate(obligation, param);
2019 Ok(VtableParam(obligations))
2022 DefaultImplCandidate(trait_def_id) => {
2023 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2024 Ok(VtableDefaultImpl(data))
2027 DefaultImplObjectCandidate(trait_def_id) => {
2028 let data = self.confirm_default_impl_object_candidate(obligation, trait_def_id);
2029 Ok(VtableDefaultImpl(data))
2032 ImplCandidate(impl_def_id) => {
2033 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2036 ClosureCandidate(closure_def_id, substs, kind) => {
2037 let vtable_closure =
2038 self.confirm_closure_candidate(obligation, closure_def_id, substs, kind)?;
2039 Ok(VtableClosure(vtable_closure))
2042 BuiltinObjectCandidate => {
2043 // This indicates something like `(Trait+Send) :
2044 // Send`. In this case, we know that this holds
2045 // because that's what the object type is telling us,
2046 // and there's really no additional obligations to
2047 // prove and no types in particular to unify etc.
2048 Ok(VtableParam(Vec::new()))
2051 ObjectCandidate => {
2052 let data = self.confirm_object_candidate(obligation);
2053 Ok(VtableObject(data))
2056 FnPointerCandidate => {
2058 self.confirm_fn_pointer_candidate(obligation)?;
2059 Ok(VtableFnPointer(data))
2062 ProjectionCandidate => {
2063 self.confirm_projection_candidate(obligation);
2064 Ok(VtableParam(Vec::new()))
2067 BuiltinUnsizeCandidate => {
2068 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2069 Ok(VtableBuiltin(data))
2074 fn confirm_projection_candidate(&mut self,
2075 obligation: &TraitObligation<'tcx>)
2077 self.in_snapshot(|this, snapshot| {
2079 this.match_projection_obligation_against_definition_bounds(obligation,
2085 fn confirm_param_candidate(&mut self,
2086 obligation: &TraitObligation<'tcx>,
2087 param: ty::PolyTraitRef<'tcx>)
2088 -> Vec<PredicateObligation<'tcx>>
2090 debug!("confirm_param_candidate({:?},{:?})",
2094 // During evaluation, we already checked that this
2095 // where-clause trait-ref could be unified with the obligation
2096 // trait-ref. Repeat that unification now without any
2097 // transactional boundary; it should not fail.
2098 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2099 Ok(obligations) => obligations,
2101 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2108 fn confirm_builtin_candidate(&mut self,
2109 obligation: &TraitObligation<'tcx>,
2111 -> VtableBuiltinData<PredicateObligation<'tcx>>
2113 debug!("confirm_builtin_candidate({:?}, {:?})",
2114 obligation, has_nested);
2116 let obligations = if has_nested {
2117 let trait_def = obligation.predicate.def_id();
2118 let conditions = match trait_def {
2119 _ if Some(trait_def) == self.tcx().lang_items.sized_trait() => {
2120 self.sized_conditions(obligation)
2122 _ if Some(trait_def) == self.tcx().lang_items.copy_trait() => {
2123 self.copy_conditions(obligation)
2125 _ => bug!("unexpected builtin trait {:?}", trait_def)
2127 let nested = match conditions {
2128 BuiltinImplConditions::Where(nested) => nested,
2129 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2133 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2134 self.collect_predicates_for_types(cause,
2135 obligation.recursion_depth+1,
2142 debug!("confirm_builtin_candidate: obligations={:?}",
2144 VtableBuiltinData { nested: obligations }
2147 /// This handles the case where a `impl Foo for ..` impl is being used.
2148 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2150 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2151 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2152 fn confirm_default_impl_candidate(&mut self,
2153 obligation: &TraitObligation<'tcx>,
2154 trait_def_id: DefId)
2155 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2157 debug!("confirm_default_impl_candidate({:?}, {:?})",
2161 // binder is moved below
2162 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2163 let types = self.constituent_types_for_ty(self_ty);
2164 self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2167 fn confirm_default_impl_object_candidate(&mut self,
2168 obligation: &TraitObligation<'tcx>,
2169 trait_def_id: DefId)
2170 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2172 debug!("confirm_default_impl_object_candidate({:?}, {:?})",
2176 assert!(self.tcx().has_attr(trait_def_id, "rustc_reflect_like"));
2178 // OK to skip binder, it is reintroduced below
2179 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2181 ty::TyTrait(ref data) => {
2182 // OK to skip the binder, it is reintroduced below
2183 let input_types = data.principal.skip_binder().input_types();
2184 let assoc_types = data.projection_bounds.iter()
2185 .map(|pb| pb.skip_binder().ty);
2186 let all_types: Vec<_> = input_types.iter().cloned()
2190 // reintroduce the two binding levels we skipped, then flatten into one
2191 let all_types = ty::Binder(ty::Binder(all_types));
2192 let all_types = self.tcx().flatten_late_bound_regions(&all_types);
2194 self.vtable_default_impl(obligation, trait_def_id, all_types)
2197 bug!("asked to confirm default object implementation for non-object type: {:?}",
2203 /// See `confirm_default_impl_candidate`
2204 fn vtable_default_impl(&mut self,
2205 obligation: &TraitObligation<'tcx>,
2206 trait_def_id: DefId,
2207 nested: ty::Binder<Vec<Ty<'tcx>>>)
2208 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2210 debug!("vtable_default_impl: nested={:?}", nested);
2212 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2213 let mut obligations = self.collect_predicates_for_types(
2215 obligation.recursion_depth+1,
2219 let trait_obligations = self.in_snapshot(|this, snapshot| {
2220 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2221 let (trait_ref, skol_map) =
2222 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2223 let cause = obligation.derived_cause(ImplDerivedObligation);
2224 this.impl_or_trait_obligations(cause,
2225 obligation.recursion_depth + 1,
2232 obligations.extend(trait_obligations);
2234 debug!("vtable_default_impl: obligations={:?}", obligations);
2236 VtableDefaultImplData {
2237 trait_def_id: trait_def_id,
2242 fn confirm_impl_candidate(&mut self,
2243 obligation: &TraitObligation<'tcx>,
2245 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2247 debug!("confirm_impl_candidate({:?},{:?})",
2251 // First, create the substitutions by matching the impl again,
2252 // this time not in a probe.
2253 self.in_snapshot(|this, snapshot| {
2254 let (substs, skol_map) =
2255 this.rematch_impl(impl_def_id, obligation,
2257 debug!("confirm_impl_candidate substs={:?}", substs);
2258 let cause = obligation.derived_cause(ImplDerivedObligation);
2259 this.vtable_impl(impl_def_id, substs, cause,
2260 obligation.recursion_depth + 1,
2265 fn vtable_impl(&mut self,
2267 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2268 cause: ObligationCause<'tcx>,
2269 recursion_depth: usize,
2270 skol_map: infer::SkolemizationMap,
2271 snapshot: &infer::CombinedSnapshot)
2272 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2274 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2280 let mut impl_obligations =
2281 self.impl_or_trait_obligations(cause,
2288 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2292 // Because of RFC447, the impl-trait-ref and obligations
2293 // are sufficient to determine the impl substs, without
2294 // relying on projections in the impl-trait-ref.
2296 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2297 impl_obligations.append(&mut substs.obligations);
2299 VtableImplData { impl_def_id: impl_def_id,
2300 substs: substs.value,
2301 nested: impl_obligations }
2304 fn confirm_object_candidate(&mut self,
2305 obligation: &TraitObligation<'tcx>)
2306 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2308 debug!("confirm_object_candidate({:?})",
2311 // FIXME skipping binder here seems wrong -- we should
2312 // probably flatten the binder from the obligation and the
2313 // binder from the object. Have to try to make a broken test
2314 // case that results. -nmatsakis
2315 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2316 let poly_trait_ref = match self_ty.sty {
2317 ty::TyTrait(ref data) => {
2318 data.principal.with_self_ty(self.tcx(), self_ty)
2321 span_bug!(obligation.cause.span,
2322 "object candidate with non-object");
2326 let mut upcast_trait_ref = None;
2330 let tcx = self.tcx();
2332 // We want to find the first supertrait in the list of
2333 // supertraits that we can unify with, and do that
2334 // unification. We know that there is exactly one in the list
2335 // where we can unify because otherwise select would have
2336 // reported an ambiguity. (When we do find a match, also
2337 // record it for later.)
2339 util::supertraits(tcx, poly_trait_ref)
2343 |this, _| this.match_poly_trait_ref(obligation, t))
2345 Ok(_) => { upcast_trait_ref = Some(t); false }
2350 // Additionally, for each of the nonmatching predicates that
2351 // we pass over, we sum up the set of number of vtable
2352 // entries, so that we can compute the offset for the selected
2355 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2361 upcast_trait_ref: upcast_trait_ref.unwrap(),
2362 vtable_base: vtable_base,
2367 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2368 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2370 debug!("confirm_fn_pointer_candidate({:?})",
2373 // ok to skip binder; it is reintroduced below
2374 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2375 let sig = self_ty.fn_sig();
2377 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2380 util::TupleArgumentsFlag::Yes)
2381 .map_bound(|(trait_ref, _)| trait_ref);
2383 self.confirm_poly_trait_refs(obligation.cause.clone(),
2384 obligation.predicate.to_poly_trait_ref(),
2386 Ok(VtableFnPointerData { fn_ty: self_ty, nested: vec![] })
2389 fn confirm_closure_candidate(&mut self,
2390 obligation: &TraitObligation<'tcx>,
2391 closure_def_id: DefId,
2392 substs: ty::ClosureSubsts<'tcx>,
2393 kind: ty::ClosureKind)
2394 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2395 SelectionError<'tcx>>
2397 debug!("confirm_closure_candidate({:?},{:?},{:?})",
2405 } = self.closure_trait_ref(obligation, closure_def_id, substs);
2407 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2412 self.confirm_poly_trait_refs(obligation.cause.clone(),
2413 obligation.predicate.to_poly_trait_ref(),
2416 obligations.push(Obligation::new(
2417 obligation.cause.clone(),
2418 ty::Predicate::ClosureKind(closure_def_id, kind)));
2420 Ok(VtableClosureData {
2421 closure_def_id: closure_def_id,
2422 substs: substs.clone(),
2427 /// In the case of closure types and fn pointers,
2428 /// we currently treat the input type parameters on the trait as
2429 /// outputs. This means that when we have a match we have only
2430 /// considered the self type, so we have to go back and make sure
2431 /// to relate the argument types too. This is kind of wrong, but
2432 /// since we control the full set of impls, also not that wrong,
2433 /// and it DOES yield better error messages (since we don't report
2434 /// errors as if there is no applicable impl, but rather report
2435 /// errors are about mismatched argument types.
2437 /// Here is an example. Imagine we have a closure expression
2438 /// and we desugared it so that the type of the expression is
2439 /// `Closure`, and `Closure` expects an int as argument. Then it
2440 /// is "as if" the compiler generated this impl:
2442 /// impl Fn(int) for Closure { ... }
2444 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2445 /// we have matched the self-type `Closure`. At this point we'll
2446 /// compare the `int` to `usize` and generate an error.
2448 /// Note that this checking occurs *after* the impl has selected,
2449 /// because these output type parameters should not affect the
2450 /// selection of the impl. Therefore, if there is a mismatch, we
2451 /// report an error to the user.
2452 fn confirm_poly_trait_refs(&mut self,
2453 obligation_cause: ObligationCause,
2454 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2455 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2456 -> Result<(), SelectionError<'tcx>>
2458 let origin = TypeOrigin::RelateOutputImplTypes(obligation_cause.span);
2460 let obligation_trait_ref = obligation_trait_ref.clone();
2461 self.infcx.sub_poly_trait_refs(false,
2463 expected_trait_ref.clone(),
2464 obligation_trait_ref.clone())
2465 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2466 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2469 fn confirm_builtin_unsize_candidate(&mut self,
2470 obligation: &TraitObligation<'tcx>,)
2471 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2472 SelectionError<'tcx>> {
2473 let tcx = self.tcx();
2475 // assemble_candidates_for_unsizing should ensure there are no late bound
2476 // regions here. See the comment there for more details.
2477 let source = self.infcx.shallow_resolve(
2478 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2479 let target = obligation.predicate.skip_binder().input_types()[1];
2480 let target = self.infcx.shallow_resolve(target);
2482 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2485 let mut nested = vec![];
2486 match (&source.sty, &target.sty) {
2487 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2488 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
2489 // See assemble_candidates_for_unsizing for more info.
2490 let new_trait = tcx.mk_trait(ty::TraitObject {
2491 principal: data_a.principal,
2492 region_bound: data_b.region_bound,
2493 builtin_bounds: data_b.builtin_bounds,
2494 projection_bounds: data_a.projection_bounds.clone(),
2496 let origin = TypeOrigin::Misc(obligation.cause.span);
2497 let InferOk { obligations, .. } =
2498 self.infcx.sub_types(false, origin, new_trait, target)
2499 .map_err(|_| Unimplemented)?;
2500 self.inferred_obligations.extend(obligations);
2502 // Register one obligation for 'a: 'b.
2503 let cause = ObligationCause::new(obligation.cause.span,
2504 obligation.cause.body_id,
2505 ObjectCastObligation(target));
2506 let outlives = ty::OutlivesPredicate(data_a.region_bound,
2507 data_b.region_bound);
2508 nested.push(Obligation::with_depth(cause,
2509 obligation.recursion_depth + 1,
2510 ty::Binder(outlives).to_predicate()));
2514 (_, &ty::TyTrait(ref data)) => {
2515 let mut object_dids = Some(data.principal.def_id()).into_iter();
2517 // data.builtin_bounds.iter().flat_map(|bound| {
2518 // tcx.lang_items.from_builtin_kind(bound).ok()
2520 // .chain(Some(data.principal.def_id()));
2521 if let Some(did) = object_dids.find(|did| {
2522 !tcx.is_object_safe(*did)
2524 return Err(TraitNotObjectSafe(did))
2527 let cause = ObligationCause::new(obligation.cause.span,
2528 obligation.cause.body_id,
2529 ObjectCastObligation(target));
2530 let mut push = |predicate| {
2531 nested.push(Obligation::with_depth(cause.clone(),
2532 obligation.recursion_depth + 1,
2536 // Create the obligation for casting from T to Trait.
2537 push(data.principal.with_self_ty(tcx, source).to_predicate());
2539 // We can only make objects from sized types.
2540 let mut builtin_bounds = data.builtin_bounds;
2541 builtin_bounds.insert(ty::BoundSized);
2543 // Create additional obligations for all the various builtin
2544 // bounds attached to the object cast. (In other words, if the
2545 // object type is Foo+Send, this would create an obligation
2546 // for the Send check.)
2547 for bound in &builtin_bounds {
2548 if let Ok(tr) = tcx.trait_ref_for_builtin_bound(bound, source) {
2549 push(tr.to_predicate());
2551 return Err(Unimplemented);
2555 // Create obligations for the projection predicates.
2556 for bound in &data.projection_bounds {
2557 push(bound.with_self_ty(tcx, source).to_predicate());
2560 // If the type is `Foo+'a`, ensures that the type
2561 // being cast to `Foo+'a` outlives `'a`:
2562 let outlives = ty::OutlivesPredicate(source, data.region_bound);
2563 push(ty::Binder(outlives).to_predicate());
2567 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2568 let origin = TypeOrigin::Misc(obligation.cause.span);
2569 let InferOk { obligations, .. } =
2570 self.infcx.sub_types(false, origin, a, b)
2571 .map_err(|_| Unimplemented)?;
2572 self.inferred_obligations.extend(obligations);
2575 // Struct<T> -> Struct<U>.
2576 (&ty::TyStruct(def, substs_a), &ty::TyStruct(_, substs_b)) => {
2579 .map(|f| f.unsubst_ty())
2580 .collect::<Vec<_>>();
2582 // The last field of the structure has to exist and contain type parameters.
2583 let field = if let Some(&field) = fields.last() {
2586 return Err(Unimplemented);
2588 let mut ty_params = BitVector::new(substs_a.types.len());
2589 let mut found = false;
2590 for ty in field.walk() {
2591 if let ty::TyParam(p) = ty.sty {
2592 ty_params.insert(p.idx as usize);
2597 return Err(Unimplemented);
2600 // Replace type parameters used in unsizing with
2601 // TyError and ensure they do not affect any other fields.
2602 // This could be checked after type collection for any struct
2603 // with a potentially unsized trailing field.
2604 let types = substs_a.types.iter().enumerate().map(|(i, ty)| {
2605 if ty_params.contains(i) {
2611 let substs = Substs::new(tcx, types, substs_a.regions.clone());
2612 for &ty in fields.split_last().unwrap().1 {
2613 if ty.subst(tcx, substs).references_error() {
2614 return Err(Unimplemented);
2618 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2619 let inner_source = field.subst(tcx, substs_a);
2620 let inner_target = field.subst(tcx, substs_b);
2622 // Check that the source structure with the target's
2623 // type parameters is a subtype of the target.
2624 let types = substs_a.types.iter().enumerate().map(|(i, ty)| {
2625 if ty_params.contains(i) {
2631 let substs = Substs::new(tcx, types, substs_a.regions.clone());
2632 let new_struct = tcx.mk_struct(def, substs);
2633 let origin = TypeOrigin::Misc(obligation.cause.span);
2634 let InferOk { obligations, .. } =
2635 self.infcx.sub_types(false, origin, new_struct, target)
2636 .map_err(|_| Unimplemented)?;
2637 self.inferred_obligations.extend(obligations);
2639 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2640 nested.push(tcx.predicate_for_trait_def(
2641 obligation.cause.clone(),
2642 obligation.predicate.def_id(),
2643 obligation.recursion_depth + 1,
2645 vec![inner_target]));
2651 Ok(VtableBuiltinData { nested: nested })
2654 ///////////////////////////////////////////////////////////////////////////
2657 // Matching is a common path used for both evaluation and
2658 // confirmation. It basically unifies types that appear in impls
2659 // and traits. This does affect the surrounding environment;
2660 // therefore, when used during evaluation, match routines must be
2661 // run inside of a `probe()` so that their side-effects are
2664 fn rematch_impl(&mut self,
2666 obligation: &TraitObligation<'tcx>,
2667 snapshot: &infer::CombinedSnapshot)
2668 -> (Normalized<'tcx, &'tcx Substs<'tcx>>, infer::SkolemizationMap)
2670 match self.match_impl(impl_def_id, obligation, snapshot) {
2671 Ok((substs, skol_map)) => (substs, skol_map),
2673 bug!("Impl {:?} was matchable against {:?} but now is not",
2680 fn match_impl(&mut self,
2682 obligation: &TraitObligation<'tcx>,
2683 snapshot: &infer::CombinedSnapshot)
2684 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
2685 infer::SkolemizationMap), ()>
2687 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2689 // Before we create the substitutions and everything, first
2690 // consider a "quick reject". This avoids creating more types
2691 // and so forth that we need to.
2692 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2696 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2697 &obligation.predicate,
2699 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2701 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
2704 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2707 let impl_trait_ref =
2708 project::normalize_with_depth(self,
2709 obligation.cause.clone(),
2710 obligation.recursion_depth + 1,
2713 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2714 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2718 skol_obligation_trait_ref);
2720 let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
2721 let InferOk { obligations, .. } =
2722 self.infcx.eq_trait_refs(false,
2724 impl_trait_ref.value.clone(),
2725 skol_obligation_trait_ref)
2727 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2730 self.inferred_obligations.extend(obligations);
2732 if let Err(e) = self.infcx.leak_check(false,
2733 obligation.cause.span,
2736 debug!("match_impl: failed leak check due to `{}`", e);
2740 debug!("match_impl: success impl_substs={:?}", impl_substs);
2743 obligations: impl_trait_ref.obligations
2747 fn fast_reject_trait_refs(&mut self,
2748 obligation: &TraitObligation,
2749 impl_trait_ref: &ty::TraitRef)
2752 // We can avoid creating type variables and doing the full
2753 // substitution if we find that any of the input types, when
2754 // simplified, do not match.
2756 obligation.predicate.0.input_types().iter()
2757 .zip(impl_trait_ref.input_types())
2758 .any(|(&obligation_ty, &impl_ty)| {
2759 let simplified_obligation_ty =
2760 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2761 let simplified_impl_ty =
2762 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2764 simplified_obligation_ty.is_some() &&
2765 simplified_impl_ty.is_some() &&
2766 simplified_obligation_ty != simplified_impl_ty
2770 /// Normalize `where_clause_trait_ref` and try to match it against
2771 /// `obligation`. If successful, return any predicates that
2772 /// result from the normalization. Normalization is necessary
2773 /// because where-clauses are stored in the parameter environment
2775 fn match_where_clause_trait_ref(&mut self,
2776 obligation: &TraitObligation<'tcx>,
2777 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2778 -> Result<Vec<PredicateObligation<'tcx>>,()>
2780 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
2784 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2785 /// obligation is satisfied.
2786 fn match_poly_trait_ref(&mut self,
2787 obligation: &TraitObligation<'tcx>,
2788 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2791 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2795 let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
2796 self.infcx.sub_poly_trait_refs(false,
2799 obligation.predicate.to_poly_trait_ref())
2800 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2804 ///////////////////////////////////////////////////////////////////////////
2807 fn match_fresh_trait_refs(&self,
2808 previous: &ty::PolyTraitRef<'tcx>,
2809 current: &ty::PolyTraitRef<'tcx>)
2812 let mut matcher = ty::_match::Match::new(self.tcx());
2813 matcher.relate(previous, current).is_ok()
2816 fn push_stack<'o,'s:'o>(&mut self,
2817 previous_stack: TraitObligationStackList<'s, 'tcx>,
2818 obligation: &'o TraitObligation<'tcx>)
2819 -> TraitObligationStack<'o, 'tcx>
2821 let fresh_trait_ref =
2822 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2824 TraitObligationStack {
2825 obligation: obligation,
2826 fresh_trait_ref: fresh_trait_ref,
2827 previous: previous_stack,
2831 fn closure_trait_ref_unnormalized(&mut self,
2832 obligation: &TraitObligation<'tcx>,
2833 closure_def_id: DefId,
2834 substs: ty::ClosureSubsts<'tcx>)
2835 -> ty::PolyTraitRef<'tcx>
2837 let closure_type = self.infcx.closure_type(closure_def_id, substs);
2838 let ty::Binder((trait_ref, _)) =
2839 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2840 obligation.predicate.0.self_ty(), // (1)
2842 util::TupleArgumentsFlag::No);
2843 // (1) Feels icky to skip the binder here, but OTOH we know
2844 // that the self-type is an unboxed closure type and hence is
2845 // in fact unparameterized (or at least does not reference any
2846 // regions bound in the obligation). Still probably some
2847 // refactoring could make this nicer.
2849 ty::Binder(trait_ref)
2852 fn closure_trait_ref(&mut self,
2853 obligation: &TraitObligation<'tcx>,
2854 closure_def_id: DefId,
2855 substs: ty::ClosureSubsts<'tcx>)
2856 -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
2858 let trait_ref = self.closure_trait_ref_unnormalized(
2859 obligation, closure_def_id, substs);
2861 // A closure signature can contain associated types which
2862 // must be normalized.
2863 normalize_with_depth(self,
2864 obligation.cause.clone(),
2865 obligation.recursion_depth+1,
2869 /// Returns the obligations that are implied by instantiating an
2870 /// impl or trait. The obligations are substituted and fully
2871 /// normalized. This is used when confirming an impl or default
2873 fn impl_or_trait_obligations(&mut self,
2874 cause: ObligationCause<'tcx>,
2875 recursion_depth: usize,
2876 def_id: DefId, // of impl or trait
2877 substs: &Substs<'tcx>, // for impl or trait
2878 skol_map: infer::SkolemizationMap,
2879 snapshot: &infer::CombinedSnapshot)
2880 -> Vec<PredicateObligation<'tcx>>
2882 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2883 let tcx = self.tcx();
2885 // To allow for one-pass evaluation of the nested obligation,
2886 // each predicate must be preceded by the obligations required
2888 // for example, if we have:
2889 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2890 // the impl will have the following predicates:
2891 // <V as Iterator>::Item = U,
2892 // U: Iterator, U: Sized,
2893 // V: Iterator, V: Sized,
2894 // <U as Iterator>::Item: Copy
2895 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2896 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2897 // `$1: Copy`, so we must ensure the obligations are emitted in
2899 let predicates = tcx.lookup_predicates(def_id);
2900 assert_eq!(predicates.parent, None);
2901 let predicates = predicates.predicates.iter().flat_map(|predicate| {
2902 let predicate = normalize_with_depth(self, cause.clone(), recursion_depth,
2903 &predicate.subst(tcx, substs));
2904 predicate.obligations.into_iter().chain(
2906 cause: cause.clone(),
2907 recursion_depth: recursion_depth,
2908 predicate: predicate.value
2911 self.infcx().plug_leaks(skol_map, snapshot, &predicates)
2915 impl<'tcx> TraitObligation<'tcx> {
2916 #[allow(unused_comparisons)]
2917 pub fn derived_cause(&self,
2918 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2919 -> ObligationCause<'tcx>
2922 * Creates a cause for obligations that are derived from
2923 * `obligation` by a recursive search (e.g., for a builtin
2924 * bound, or eventually a `impl Foo for ..`). If `obligation`
2925 * is itself a derived obligation, this is just a clone, but
2926 * otherwise we create a "derived obligation" cause so as to
2927 * keep track of the original root obligation for error
2931 let obligation = self;
2933 // NOTE(flaper87): As of now, it keeps track of the whole error
2934 // chain. Ideally, we should have a way to configure this either
2935 // by using -Z verbose or just a CLI argument.
2936 if obligation.recursion_depth >= 0 {
2937 let derived_cause = DerivedObligationCause {
2938 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2939 parent_code: Rc::new(obligation.cause.code.clone())
2941 let derived_code = variant(derived_cause);
2942 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2944 obligation.cause.clone()
2949 impl<'tcx> SelectionCache<'tcx> {
2950 pub fn new() -> SelectionCache<'tcx> {
2952 hashmap: RefCell::new(FnvHashMap())
2957 impl<'tcx> EvaluationCache<'tcx> {
2958 pub fn new() -> EvaluationCache<'tcx> {
2960 hashmap: RefCell::new(FnvHashMap())
2965 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
2966 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
2967 TraitObligationStackList::with(self)
2970 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
2975 #[derive(Copy, Clone)]
2976 struct TraitObligationStackList<'o,'tcx:'o> {
2977 head: Option<&'o TraitObligationStack<'o,'tcx>>
2980 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
2981 fn empty() -> TraitObligationStackList<'o,'tcx> {
2982 TraitObligationStackList { head: None }
2985 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
2986 TraitObligationStackList { head: Some(r) }
2990 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
2991 type Item = &'o TraitObligationStack<'o,'tcx>;
2993 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3004 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3005 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3006 write!(f, "TraitObligationStack({:?})", self.obligation)
3010 impl EvaluationResult {
3011 fn may_apply(&self) -> bool {
3015 EvaluatedToUnknown => true,
3017 EvaluatedToErr => false
3022 impl MethodMatchResult {
3023 pub fn may_apply(&self) -> bool {
3025 MethodMatched(_) => true,
3026 MethodAmbiguous(_) => true,
3027 MethodDidNotMatch => false,