1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See `README.md` for high-level documentation
13 use self::SelectionCandidate::*;
14 use self::EvaluationResult::*;
17 use super::DerivedObligationCause;
19 use super::project::{normalize_with_depth, Normalized};
20 use super::{PredicateObligation, TraitObligation, ObligationCause};
21 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
22 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
23 use super::{ObjectCastObligation, Obligation};
24 use super::TraitNotObjectSafe;
26 use super::SelectionResult;
27 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure,
28 VtableFnPointer, VtableObject, VtableDefaultImpl};
29 use super::{VtableImplData, VtableObjectData, VtableBuiltinData,
30 VtableClosureData, VtableDefaultImplData, VtableFnPointerData};
33 use dep_graph::{DepNodeIndex, DepKind};
34 use hir::def_id::DefId;
36 use infer::{InferCtxt, InferOk, TypeFreshener};
37 use ty::subst::{Kind, Subst, Substs};
38 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
41 use ty::relate::TypeRelation;
42 use middle::lang_items;
44 use rustc_data_structures::bitvec::BitVector;
45 use rustc_data_structures::snapshot_vec::{SnapshotVecDelegate, SnapshotVec};
46 use std::cell::RefCell;
49 use std::marker::PhantomData;
55 use util::nodemap::FxHashMap;
57 struct InferredObligationsSnapshotVecDelegate<'tcx> {
58 phantom: PhantomData<&'tcx i32>,
60 impl<'tcx> SnapshotVecDelegate for InferredObligationsSnapshotVecDelegate<'tcx> {
61 type Value = PredicateObligation<'tcx>;
63 fn reverse(_: &mut Vec<Self::Value>, _: Self::Undo) {}
66 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
67 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
69 /// Freshener used specifically for skolemizing entries on the
70 /// obligation stack. This ensures that all entries on the stack
71 /// at one time will have the same set of skolemized entries,
72 /// which is important for checking for trait bounds that
73 /// recursively require themselves.
74 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
76 /// If true, indicates that the evaluation should be conservative
77 /// and consider the possibility of types outside this crate.
78 /// This comes up primarily when resolving ambiguity. Imagine
79 /// there is some trait reference `$0 : Bar` where `$0` is an
80 /// inference variable. If `intercrate` is true, then we can never
81 /// say for sure that this reference is not implemented, even if
82 /// there are *no impls at all for `Bar`*, because `$0` could be
83 /// bound to some type that in a downstream crate that implements
84 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
85 /// though, we set this to false, because we are only interested
86 /// in types that the user could actually have written --- in
87 /// other words, we consider `$0 : Bar` to be unimplemented if
88 /// there is no type that the user could *actually name* that
89 /// would satisfy it. This avoids crippling inference, basically.
92 inferred_obligations: SnapshotVec<InferredObligationsSnapshotVecDelegate<'tcx>>,
95 // A stack that walks back up the stack frame.
96 struct TraitObligationStack<'prev, 'tcx: 'prev> {
97 obligation: &'prev TraitObligation<'tcx>,
99 /// Trait ref from `obligation` but skolemized with the
100 /// selection-context's freshener. Used to check for recursion.
101 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
103 previous: TraitObligationStackList<'prev, 'tcx>,
107 pub struct SelectionCache<'tcx> {
108 hashmap: RefCell<FxHashMap<ty::TraitRef<'tcx>,
109 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>>,
112 /// The selection process begins by considering all impls, where
113 /// clauses, and so forth that might resolve an obligation. Sometimes
114 /// we'll be able to say definitively that (e.g.) an impl does not
115 /// apply to the obligation: perhaps it is defined for `usize` but the
116 /// obligation is for `int`. In that case, we drop the impl out of the
117 /// list. But the other cases are considered *candidates*.
119 /// For selection to succeed, there must be exactly one matching
120 /// candidate. If the obligation is fully known, this is guaranteed
121 /// by coherence. However, if the obligation contains type parameters
122 /// or variables, there may be multiple such impls.
124 /// It is not a real problem if multiple matching impls exist because
125 /// of type variables - it just means the obligation isn't sufficiently
126 /// elaborated. In that case we report an ambiguity, and the caller can
127 /// try again after more type information has been gathered or report a
128 /// "type annotations required" error.
130 /// However, with type parameters, this can be a real problem - type
131 /// parameters don't unify with regular types, but they *can* unify
132 /// with variables from blanket impls, and (unless we know its bounds
133 /// will always be satisfied) picking the blanket impl will be wrong
134 /// for at least *some* substitutions. To make this concrete, if we have
136 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
137 /// impl<T: fmt::Debug> AsDebug for T {
139 /// fn debug(self) -> fmt::Debug { self }
141 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
143 /// we can't just use the impl to resolve the <T as AsDebug> obligation
144 /// - a type from another crate (that doesn't implement fmt::Debug) could
145 /// implement AsDebug.
147 /// Because where-clauses match the type exactly, multiple clauses can
148 /// only match if there are unresolved variables, and we can mostly just
149 /// report this ambiguity in that case. This is still a problem - we can't
150 /// *do anything* with ambiguities that involve only regions. This is issue
153 /// If a single where-clause matches and there are no inference
154 /// variables left, then it definitely matches and we can just select
157 /// In fact, we even select the where-clause when the obligation contains
158 /// inference variables. The can lead to inference making "leaps of logic",
159 /// for example in this situation:
161 /// pub trait Foo<T> { fn foo(&self) -> T; }
162 /// impl<T> Foo<()> for T { fn foo(&self) { } }
163 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
165 /// pub fn foo<T>(t: T) where T: Foo<bool> {
166 /// println!("{:?}", <T as Foo<_>>::foo(&t));
168 /// fn main() { foo(false); }
170 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
171 /// impl and the where-clause. We select the where-clause and unify $0=bool,
172 /// so the program prints "false". However, if the where-clause is omitted,
173 /// the blanket impl is selected, we unify $0=(), and the program prints
176 /// Exactly the same issues apply to projection and object candidates, except
177 /// that we can have both a projection candidate and a where-clause candidate
178 /// for the same obligation. In that case either would do (except that
179 /// different "leaps of logic" would occur if inference variables are
180 /// present), and we just pick the where-clause. This is, for example,
181 /// required for associated types to work in default impls, as the bounds
182 /// are visible both as projection bounds and as where-clauses from the
183 /// parameter environment.
184 #[derive(PartialEq,Eq,Debug,Clone)]
185 enum SelectionCandidate<'tcx> {
186 BuiltinCandidate { has_nested: bool },
187 ParamCandidate(ty::PolyTraitRef<'tcx>),
188 ImplCandidate(DefId),
189 DefaultImplCandidate(DefId),
191 /// This is a trait matching with a projected type as `Self`, and
192 /// we found an applicable bound in the trait definition.
195 /// Implementation of a `Fn`-family trait by one of the anonymous types
196 /// generated for a `||` expression. The ty::ClosureKind informs the
197 /// confirmation step what ClosureKind obligation to emit.
198 ClosureCandidate(/* closure */ DefId, ty::ClosureSubsts<'tcx>, ty::ClosureKind),
200 /// Implementation of a `Fn`-family trait by one of the anonymous
201 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
206 BuiltinObjectCandidate,
208 BuiltinUnsizeCandidate,
211 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
212 type Lifted = SelectionCandidate<'tcx>;
213 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
215 BuiltinCandidate { has_nested } => {
220 ImplCandidate(def_id) => ImplCandidate(def_id),
221 DefaultImplCandidate(def_id) => DefaultImplCandidate(def_id),
222 ProjectionCandidate => ProjectionCandidate,
223 FnPointerCandidate => FnPointerCandidate,
224 ObjectCandidate => ObjectCandidate,
225 BuiltinObjectCandidate => BuiltinObjectCandidate,
226 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
228 ParamCandidate(ref trait_ref) => {
229 return tcx.lift(trait_ref).map(ParamCandidate);
231 ClosureCandidate(def_id, ref substs, kind) => {
232 return tcx.lift(substs).map(|substs| {
233 ClosureCandidate(def_id, substs, kind)
240 struct SelectionCandidateSet<'tcx> {
241 // a list of candidates that definitely apply to the current
242 // obligation (meaning: types unify).
243 vec: Vec<SelectionCandidate<'tcx>>,
245 // if this is true, then there were candidates that might or might
246 // not have applied, but we couldn't tell. This occurs when some
247 // of the input types are type variables, in which case there are
248 // various "builtin" rules that might or might not trigger.
252 #[derive(PartialEq,Eq,Debug,Clone)]
253 struct EvaluatedCandidate<'tcx> {
254 candidate: SelectionCandidate<'tcx>,
255 evaluation: EvaluationResult,
258 /// When does the builtin impl for `T: Trait` apply?
259 enum BuiltinImplConditions<'tcx> {
260 /// The impl is conditional on T1,T2,.. : Trait
261 Where(ty::Binder<Vec<Ty<'tcx>>>),
262 /// There is no built-in impl. There may be some other
263 /// candidate (a where-clause or user-defined impl).
265 /// There is *no* impl for this, builtin or not. Ignore
266 /// all where-clauses.
268 /// It is unknown whether there is an impl.
272 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
273 /// The result of trait evaluation. The order is important
274 /// here as the evaluation of a list is the maximum of the
277 /// The evaluation results are ordered:
278 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
279 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
280 /// - the "union" of evaluation results is equal to their maximum -
281 /// all the "potential success" candidates can potentially succeed,
282 /// so they are no-ops when unioned with a definite error, and within
283 /// the categories it's easy to see that the unions are correct.
284 enum EvaluationResult {
285 /// Evaluation successful
287 /// Evaluation is known to be ambiguous - it *might* hold for some
288 /// assignment of inference variables, but it might not.
290 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
291 /// know whether this obligation holds or not - it is the result we
292 /// would get with an empty stack, and therefore is cacheable.
294 /// Evaluation failed because of recursion involving inference
295 /// variables. We are somewhat imprecise there, so we don't actually
296 /// know the real result.
298 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
300 /// Evaluation failed because we encountered an obligation we are already
301 /// trying to prove on this branch.
303 /// We know this branch can't be a part of a minimal proof-tree for
304 /// the "root" of our cycle, because then we could cut out the recursion
305 /// and maintain a valid proof tree. However, this does not mean
306 /// that all the obligations on this branch do not hold - it's possible
307 /// that we entered this branch "speculatively", and that there
308 /// might be some other way to prove this obligation that does not
309 /// go through this cycle - so we can't cache this as a failure.
311 /// For example, suppose we have this:
313 /// ```rust,ignore (pseudo-Rust)
314 /// pub trait Trait { fn xyz(); }
315 /// // This impl is "useless", but we can still have
316 /// // an `impl Trait for SomeUnsizedType` somewhere.
317 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
319 /// pub fn foo<T: Trait + ?Sized>() {
320 /// <T as Trait>::xyz();
324 /// When checking `foo`, we have to prove `T: Trait`. This basically
325 /// translates into this:
327 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
329 /// When we try to prove it, we first go the first option, which
330 /// recurses. This shows us that the impl is "useless" - it won't
331 /// tell us that `T: Trait` unless it already implemented `Trait`
332 /// by some other means. However, that does not prevent `T: Trait`
333 /// does not hold, because of the bound (which can indeed be satisfied
334 /// by `SomeUnsizedType` from another crate).
336 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
337 /// ought to convert it to an `EvaluatedToErr`, because we know
338 /// there definitely isn't a proof tree for that obligation. Not
339 /// doing so is still sound - there isn't any proof tree, so the
340 /// branch still can't be a part of a minimal one - but does not
341 /// re-enable caching.
343 /// Evaluation failed
347 impl EvaluationResult {
348 fn may_apply(self) -> bool {
352 EvaluatedToUnknown => true,
355 EvaluatedToRecur => false
359 fn is_stack_dependent(self) -> bool {
362 EvaluatedToRecur => true,
366 EvaluatedToErr => false,
372 pub struct EvaluationCache<'tcx> {
373 hashmap: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>
376 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
377 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
380 freshener: infcx.freshener(),
382 inferred_obligations: SnapshotVec::new(),
386 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
389 freshener: infcx.freshener(),
391 inferred_obligations: SnapshotVec::new(),
395 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
399 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
403 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
407 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
409 fn in_snapshot<R, F>(&mut self, f: F) -> R
410 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
412 // The irrefutable nature of the operation means we don't need to snapshot the
413 // inferred_obligations vector.
414 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
417 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
419 fn probe<R, F>(&mut self, f: F) -> R
420 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
422 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
423 let result = self.infcx.probe(|snapshot| f(self, snapshot));
424 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
428 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
429 /// the transaction fails and s.t. old obligations are retained.
430 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
431 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
433 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
434 match self.infcx.commit_if_ok(|snapshot| f(self, snapshot)) {
436 self.inferred_obligations.commit(inferred_obligations_snapshot);
440 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
447 ///////////////////////////////////////////////////////////////////////////
450 // The selection phase tries to identify *how* an obligation will
451 // be resolved. For example, it will identify which impl or
452 // parameter bound is to be used. The process can be inconclusive
453 // if the self type in the obligation is not fully inferred. Selection
454 // can result in an error in one of two ways:
456 // 1. If no applicable impl or parameter bound can be found.
457 // 2. If the output type parameters in the obligation do not match
458 // those specified by the impl/bound. For example, if the obligation
459 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
460 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
462 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
463 /// type environment by performing unification.
464 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
465 -> SelectionResult<'tcx, Selection<'tcx>> {
466 debug!("select({:?})", obligation);
467 assert!(!obligation.predicate.has_escaping_regions());
469 let tcx = self.tcx();
471 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
472 let ret = match self.candidate_from_obligation(&stack)? {
475 let mut candidate = self.confirm_candidate(obligation, candidate)?;
476 let inferred_obligations = (*self.inferred_obligations).into_iter().cloned();
477 candidate.nested_obligations_mut().extend(inferred_obligations);
482 // Test whether this is a `()` which was produced by defaulting a
483 // diverging type variable with `!` disabled. If so, we may need
484 // to raise a warning.
485 if obligation.predicate.skip_binder().self_ty().is_defaulted_unit() {
486 let mut raise_warning = true;
487 // Don't raise a warning if the trait is implemented for ! and only
488 // permits a trivial implementation for !. This stops us warning
489 // about (for example) `(): Clone` becoming `!: Clone` because such
490 // a switch can't cause code to stop compiling or execute
492 let mut never_obligation = obligation.clone();
493 let def_id = never_obligation.predicate.skip_binder().trait_ref.def_id;
494 never_obligation.predicate = never_obligation.predicate.map_bound(|mut trait_pred| {
495 // Swap out () with ! so we can check if the trait is impld for !
497 let mut trait_ref = &mut trait_pred.trait_ref;
498 let unit_substs = trait_ref.substs;
499 let mut never_substs = Vec::with_capacity(unit_substs.len());
500 never_substs.push(From::from(tcx.types.never));
501 never_substs.extend(&unit_substs[1..]);
502 trait_ref.substs = tcx.intern_substs(&never_substs);
506 if let Ok(Some(..)) = self.select(&never_obligation) {
507 if !tcx.trait_relevant_for_never(def_id) {
508 // The trait is also implemented for ! and the resulting
509 // implementation cannot actually be invoked in any way.
510 raise_warning = false;
515 tcx.sess.add_lint(lint::builtin::RESOLVE_TRAIT_ON_DEFAULTED_UNIT,
516 obligation.cause.body_id,
517 obligation.cause.span,
518 format!("code relies on type inference rules which are likely \
525 ///////////////////////////////////////////////////////////////////////////
528 // Tests whether an obligation can be selected or whether an impl
529 // can be applied to particular types. It skips the "confirmation"
530 // step and hence completely ignores output type parameters.
532 // The result is "true" if the obligation *may* hold and "false" if
533 // we can be sure it does not.
535 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
536 pub fn evaluate_obligation(&mut self,
537 obligation: &PredicateObligation<'tcx>)
540 debug!("evaluate_obligation({:?})",
543 self.probe(|this, _| {
544 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
549 /// Evaluates whether the obligation `obligation` can be satisfied,
550 /// and returns `false` if not certain. However, this is not entirely
551 /// accurate if inference variables are involved.
552 pub fn evaluate_obligation_conservatively(&mut self,
553 obligation: &PredicateObligation<'tcx>)
556 debug!("evaluate_obligation_conservatively({:?})",
559 self.probe(|this, _| {
560 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
565 /// Evaluates the predicates in `predicates` recursively. Note that
566 /// this applies projections in the predicates, and therefore
567 /// is run within an inference probe.
568 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
569 stack: TraitObligationStackList<'o, 'tcx>,
572 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
574 let mut result = EvaluatedToOk;
575 for obligation in predicates {
576 let eval = self.evaluate_predicate_recursively(stack, obligation);
577 debug!("evaluate_predicate_recursively({:?}) = {:?}",
579 if let EvaluatedToErr = eval {
580 // fast-path - EvaluatedToErr is the top of the lattice,
581 // so we don't need to look on the other predicates.
582 return EvaluatedToErr;
584 result = cmp::max(result, eval);
590 fn evaluate_predicate_recursively<'o>(&mut self,
591 previous_stack: TraitObligationStackList<'o, 'tcx>,
592 obligation: &PredicateObligation<'tcx>)
595 debug!("evaluate_predicate_recursively({:?})",
598 match obligation.predicate {
599 ty::Predicate::Trait(ref t) => {
600 assert!(!t.has_escaping_regions());
601 let obligation = obligation.with(t.clone());
602 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
605 ty::Predicate::Equate(ref p) => {
606 // does this code ever run?
607 match self.infcx.equality_predicate(&obligation.cause, obligation.param_env, p) {
608 Ok(InferOk { obligations, .. }) => {
609 self.inferred_obligations.extend(obligations);
612 Err(_) => EvaluatedToErr
616 ty::Predicate::Subtype(ref p) => {
617 // does this code ever run?
618 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
619 Some(Ok(InferOk { obligations, .. })) => {
620 self.inferred_obligations.extend(obligations);
623 Some(Err(_)) => EvaluatedToErr,
624 None => EvaluatedToAmbig,
628 ty::Predicate::WellFormed(ty) => {
629 match ty::wf::obligations(self.infcx,
630 obligation.param_env,
631 obligation.cause.body_id,
632 ty, obligation.cause.span) {
634 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
640 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
641 // we do not consider region relationships when
642 // evaluating trait matches
646 ty::Predicate::ObjectSafe(trait_def_id) => {
647 if self.tcx().is_object_safe(trait_def_id) {
654 ty::Predicate::Projection(ref data) => {
655 let project_obligation = obligation.with(data.clone());
656 match project::poly_project_and_unify_type(self, &project_obligation) {
657 Ok(Some(subobligations)) => {
658 self.evaluate_predicates_recursively(previous_stack,
659 subobligations.iter())
670 ty::Predicate::ClosureKind(closure_def_id, kind) => {
671 match self.infcx.closure_kind(closure_def_id) {
672 Some(closure_kind) => {
673 if closure_kind.extends(kind) {
687 fn evaluate_trait_predicate_recursively<'o>(&mut self,
688 previous_stack: TraitObligationStackList<'o, 'tcx>,
689 mut obligation: TraitObligation<'tcx>)
692 debug!("evaluate_trait_predicate_recursively({:?})",
695 if !self.intercrate && obligation.is_global() {
696 // If a param env is consistent, global obligations do not depend on its particular
697 // value in order to work, so we can clear out the param env and get better
698 // caching. (If the current param env is inconsistent, we don't care what happens).
699 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
700 obligation.param_env = ty::ParamEnv::empty(obligation.param_env.reveal);
703 let stack = self.push_stack(previous_stack, &obligation);
704 let fresh_trait_ref = stack.fresh_trait_ref;
705 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
706 debug!("CACHE HIT: EVAL({:?})={:?}",
712 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
714 debug!("CACHE MISS: EVAL({:?})={:?}",
717 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
722 fn evaluate_stack<'o>(&mut self,
723 stack: &TraitObligationStack<'o, 'tcx>)
726 // In intercrate mode, whenever any of the types are unbound,
727 // there can always be an impl. Even if there are no impls in
728 // this crate, perhaps the type would be unified with
729 // something from another crate that does provide an impl.
731 // In intra mode, we must still be conservative. The reason is
732 // that we want to avoid cycles. Imagine an impl like:
734 // impl<T:Eq> Eq for Vec<T>
736 // and a trait reference like `$0 : Eq` where `$0` is an
737 // unbound variable. When we evaluate this trait-reference, we
738 // will unify `$0` with `Vec<$1>` (for some fresh variable
739 // `$1`), on the condition that `$1 : Eq`. We will then wind
740 // up with many candidates (since that are other `Eq` impls
741 // that apply) and try to winnow things down. This results in
742 // a recursive evaluation that `$1 : Eq` -- as you can
743 // imagine, this is just where we started. To avoid that, we
744 // check for unbound variables and return an ambiguous (hence possible)
745 // match if we've seen this trait before.
747 // This suffices to allow chains like `FnMut` implemented in
748 // terms of `Fn` etc, but we could probably make this more
750 let unbound_input_types = stack.fresh_trait_ref.input_types().any(|ty| ty.is_fresh());
751 if unbound_input_types && self.intercrate {
752 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
753 stack.fresh_trait_ref);
754 return EvaluatedToAmbig;
756 if unbound_input_types &&
757 stack.iter().skip(1).any(
758 |prev| stack.obligation.param_env == prev.obligation.param_env &&
759 self.match_fresh_trait_refs(&stack.fresh_trait_ref,
760 &prev.fresh_trait_ref))
762 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
763 stack.fresh_trait_ref);
764 return EvaluatedToUnknown;
767 // If there is any previous entry on the stack that precisely
768 // matches this obligation, then we can assume that the
769 // obligation is satisfied for now (still all other conditions
770 // must be met of course). One obvious case this comes up is
771 // marker traits like `Send`. Think of a linked list:
773 // struct List<T> { data: T, next: Option<Box<List<T>>> {
775 // `Box<List<T>>` will be `Send` if `T` is `Send` and
776 // `Option<Box<List<T>>>` is `Send`, and in turn
777 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
780 // Note that we do this comparison using the `fresh_trait_ref`
781 // fields. Because these have all been skolemized using
782 // `self.freshener`, we can be sure that (a) this will not
783 // affect the inferencer state and (b) that if we see two
784 // skolemized types with the same index, they refer to the
785 // same unbound type variable.
786 if let Some(rec_index) =
788 .skip(1) // skip top-most frame
789 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
790 stack.fresh_trait_ref == prev.fresh_trait_ref)
792 debug!("evaluate_stack({:?}) --> recursive",
793 stack.fresh_trait_ref);
794 let cycle = stack.iter().skip(1).take(rec_index+1);
795 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
796 if self.coinductive_match(cycle) {
797 debug!("evaluate_stack({:?}) --> recursive, coinductive",
798 stack.fresh_trait_ref);
799 return EvaluatedToOk;
801 debug!("evaluate_stack({:?}) --> recursive, inductive",
802 stack.fresh_trait_ref);
803 return EvaluatedToRecur;
807 match self.candidate_from_obligation(stack) {
808 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
809 Ok(None) => EvaluatedToAmbig,
810 Err(..) => EvaluatedToErr
814 /// For defaulted traits, we use a co-inductive strategy to solve, so
815 /// that recursion is ok. This routine returns true if the top of the
816 /// stack (`cycle[0]`):
817 /// - is a defaulted trait, and
818 /// - it also appears in the backtrace at some position `X`; and,
819 /// - all the predicates at positions `X..` between `X` an the top are
820 /// also defaulted traits.
821 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
822 where I: Iterator<Item=ty::Predicate<'tcx>>
824 let mut cycle = cycle;
825 cycle.all(|predicate| self.coinductive_predicate(predicate))
828 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
829 let result = match predicate {
830 ty::Predicate::Trait(ref data) => {
831 self.tcx().trait_has_default_impl(data.def_id())
837 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
841 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
842 /// obligations are met. Returns true if `candidate` remains viable after this further
844 fn evaluate_candidate<'o>(&mut self,
845 stack: &TraitObligationStack<'o, 'tcx>,
846 candidate: &SelectionCandidate<'tcx>)
849 debug!("evaluate_candidate: depth={} candidate={:?}",
850 stack.obligation.recursion_depth, candidate);
851 let result = self.probe(|this, _| {
852 let candidate = (*candidate).clone();
853 match this.confirm_candidate(stack.obligation, candidate) {
855 this.evaluate_predicates_recursively(
857 selection.nested_obligations().iter())
859 Err(..) => EvaluatedToErr
862 debug!("evaluate_candidate: depth={} result={:?}",
863 stack.obligation.recursion_depth, result);
867 fn check_evaluation_cache(&self,
868 param_env: ty::ParamEnv<'tcx>,
869 trait_ref: ty::PolyTraitRef<'tcx>)
870 -> Option<EvaluationResult>
872 let tcx = self.tcx();
873 if self.can_use_global_caches(param_env) {
874 let cache = tcx.evaluation_cache.hashmap.borrow();
875 if let Some(cached) = cache.get(&trait_ref) {
876 return Some(cached.get(tcx));
879 self.infcx.evaluation_cache.hashmap
885 fn insert_evaluation_cache(&mut self,
886 param_env: ty::ParamEnv<'tcx>,
887 trait_ref: ty::PolyTraitRef<'tcx>,
888 dep_node: DepNodeIndex,
889 result: EvaluationResult)
891 // Avoid caching results that depend on more than just the trait-ref:
892 // The stack can create recursion, and closure signatures
893 // being yet uninferred can create "spurious" EvaluatedToAmbig
894 // and EvaluatedToOk.
895 if result.is_stack_dependent() ||
896 ((result == EvaluatedToAmbig || result == EvaluatedToOk)
897 && trait_ref.has_closure_types())
902 if self.can_use_global_caches(param_env) {
903 let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
904 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
905 cache.insert(trait_ref, WithDepNode::new(dep_node, result));
910 self.infcx.evaluation_cache.hashmap
912 .insert(trait_ref, WithDepNode::new(dep_node, result));
915 ///////////////////////////////////////////////////////////////////////////
916 // CANDIDATE ASSEMBLY
918 // The selection process begins by examining all in-scope impls,
919 // caller obligations, and so forth and assembling a list of
920 // candidates. See `README.md` and the `Candidate` type for more
923 fn candidate_from_obligation<'o>(&mut self,
924 stack: &TraitObligationStack<'o, 'tcx>)
925 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
927 // Watch out for overflow. This intentionally bypasses (and does
928 // not update) the cache.
929 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
930 if stack.obligation.recursion_depth >= recursion_limit {
931 self.infcx().report_overflow_error(&stack.obligation, true);
934 // Check the cache. Note that we skolemize the trait-ref
935 // separately rather than using `stack.fresh_trait_ref` -- this
936 // is because we want the unbound variables to be replaced
937 // with fresh skolemized types starting from index 0.
938 let cache_fresh_trait_pred =
939 self.infcx.freshen(stack.obligation.predicate.clone());
940 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
941 cache_fresh_trait_pred,
943 assert!(!stack.obligation.predicate.has_escaping_regions());
945 if let Some(c) = self.check_candidate_cache(stack.obligation.param_env,
946 &cache_fresh_trait_pred) {
947 debug!("CACHE HIT: SELECT({:?})={:?}",
948 cache_fresh_trait_pred,
953 // If no match, compute result and insert into cache.
954 let (candidate, dep_node) = self.in_task(|this| {
955 this.candidate_from_obligation_no_cache(stack)
958 if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
959 debug!("CACHE MISS: SELECT({:?})={:?}",
960 cache_fresh_trait_pred, candidate);
961 self.insert_candidate_cache(stack.obligation.param_env,
962 cache_fresh_trait_pred,
970 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
971 where OP: FnOnce(&mut Self) -> R
973 let (result, dep_node) = self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || {
976 self.tcx().dep_graph.read_index(dep_node);
980 // Treat negative impls as unimplemented
981 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
982 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
983 if let ImplCandidate(def_id) = candidate {
984 if self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative {
985 return Err(Unimplemented)
991 fn candidate_from_obligation_no_cache<'o>(&mut self,
992 stack: &TraitObligationStack<'o, 'tcx>)
993 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
995 if stack.obligation.predicate.references_error() {
996 // If we encounter a `TyError`, we generally prefer the
997 // most "optimistic" result in response -- that is, the
998 // one least likely to report downstream errors. But
999 // because this routine is shared by coherence and by
1000 // trait selection, there isn't an obvious "right" choice
1001 // here in that respect, so we opt to just return
1002 // ambiguity and let the upstream clients sort it out.
1006 if !self.is_knowable(stack) {
1007 debug!("coherence stage: not knowable");
1011 let candidate_set = self.assemble_candidates(stack)?;
1013 if candidate_set.ambiguous {
1014 debug!("candidate set contains ambig");
1018 let mut candidates = candidate_set.vec;
1020 debug!("assembled {} candidates for {:?}: {:?}",
1025 // At this point, we know that each of the entries in the
1026 // candidate set is *individually* applicable. Now we have to
1027 // figure out if they contain mutual incompatibilities. This
1028 // frequently arises if we have an unconstrained input type --
1029 // for example, we are looking for $0:Eq where $0 is some
1030 // unconstrained type variable. In that case, we'll get a
1031 // candidate which assumes $0 == int, one that assumes $0 ==
1032 // usize, etc. This spells an ambiguity.
1034 // If there is more than one candidate, first winnow them down
1035 // by considering extra conditions (nested obligations and so
1036 // forth). We don't winnow if there is exactly one
1037 // candidate. This is a relatively minor distinction but it
1038 // can lead to better inference and error-reporting. An
1039 // example would be if there was an impl:
1041 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1043 // and we were to see some code `foo.push_clone()` where `boo`
1044 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1045 // we were to winnow, we'd wind up with zero candidates.
1046 // Instead, we select the right impl now but report `Bar does
1047 // not implement Clone`.
1048 if candidates.len() == 1 {
1049 return self.filter_negative_impls(candidates.pop().unwrap());
1052 // Winnow, but record the exact outcome of evaluation, which
1053 // is needed for specialization.
1054 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
1055 let eval = self.evaluate_candidate(stack, &c);
1056 if eval.may_apply() {
1057 Some(EvaluatedCandidate {
1066 // If there are STILL multiple candidate, we can further
1067 // reduce the list by dropping duplicates -- including
1068 // resolving specializations.
1069 if candidates.len() > 1 {
1071 while i < candidates.len() {
1073 (0..candidates.len())
1074 .filter(|&j| i != j)
1075 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
1078 debug!("Dropping candidate #{}/{}: {:?}",
1079 i, candidates.len(), candidates[i]);
1080 candidates.swap_remove(i);
1082 debug!("Retaining candidate #{}/{}: {:?}",
1083 i, candidates.len(), candidates[i]);
1086 // If there are *STILL* multiple candidates, give up
1087 // and report ambiguity.
1089 debug!("multiple matches, ambig");
1096 // If there are *NO* candidates, then there are no impls --
1097 // that we know of, anyway. Note that in the case where there
1098 // are unbound type variables within the obligation, it might
1099 // be the case that you could still satisfy the obligation
1100 // from another crate by instantiating the type variables with
1101 // a type from another crate that does have an impl. This case
1102 // is checked for in `evaluate_stack` (and hence users
1103 // who might care about this case, like coherence, should use
1105 if candidates.is_empty() {
1106 return Err(Unimplemented);
1109 // Just one candidate left.
1110 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1113 fn is_knowable<'o>(&mut self,
1114 stack: &TraitObligationStack<'o, 'tcx>)
1117 debug!("is_knowable(intercrate={})", self.intercrate);
1119 if !self.intercrate {
1123 let obligation = &stack.obligation;
1124 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1126 // ok to skip binder because of the nature of the
1127 // trait-ref-is-knowable check, which does not care about
1129 let trait_ref = &predicate.skip_binder().trait_ref;
1131 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1134 /// Returns true if the global caches can be used.
1135 /// Do note that if the type itself is not in the
1136 /// global tcx, the local caches will be used.
1137 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1138 // If there are any where-clauses in scope, then we always use
1139 // a cache local to this particular scope. Otherwise, we
1140 // switch to a global cache. We used to try and draw
1141 // finer-grained distinctions, but that led to a serious of
1142 // annoying and weird bugs like #22019 and #18290. This simple
1143 // rule seems to be pretty clearly safe and also still retains
1144 // a very high hit rate (~95% when compiling rustc).
1145 if !param_env.caller_bounds.is_empty() {
1149 // Avoid using the master cache during coherence and just rely
1150 // on the local cache. This effectively disables caching
1151 // during coherence. It is really just a simplification to
1152 // avoid us having to fear that coherence results "pollute"
1153 // the master cache. Since coherence executes pretty quickly,
1154 // it's not worth going to more trouble to increase the
1155 // hit-rate I don't think.
1156 if self.intercrate {
1160 // Otherwise, we can use the global cache.
1164 fn check_candidate_cache(&mut self,
1165 param_env: ty::ParamEnv<'tcx>,
1166 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1167 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1169 let tcx = self.tcx();
1170 let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1171 if self.can_use_global_caches(param_env) {
1172 let cache = tcx.selection_cache.hashmap.borrow();
1173 if let Some(cached) = cache.get(&trait_ref) {
1174 return Some(cached.get(tcx));
1177 self.infcx.selection_cache.hashmap
1180 .map(|v| v.get(tcx))
1183 fn insert_candidate_cache(&mut self,
1184 param_env: ty::ParamEnv<'tcx>,
1185 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1186 dep_node: DepNodeIndex,
1187 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1189 let tcx = self.tcx();
1190 let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1191 if self.can_use_global_caches(param_env) {
1192 let mut cache = tcx.selection_cache.hashmap.borrow_mut();
1193 if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1194 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1195 cache.insert(trait_ref, WithDepNode::new(dep_node, candidate));
1201 self.infcx.selection_cache.hashmap
1203 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1206 fn should_update_candidate_cache(&mut self,
1207 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1208 candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1211 // In general, it's a good idea to cache results, even
1212 // ambiguous ones, to save us some trouble later. But we have
1213 // to be careful not to cache results that could be
1214 // invalidated later by advances in inference. Normally, this
1215 // is not an issue, because any inference variables whose
1216 // types are not yet bound are "freshened" in the cache key,
1217 // which means that if we later get the same request once that
1218 // type variable IS bound, we'll have a different cache key.
1219 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
1220 // not yet known, we may cache the result as `None`. But if
1221 // later `_#0t` is bound to `Bar`, then when we freshen we'll
1222 // have `Vec<Bar> : Foo` as the cache key.
1224 // HOWEVER, it CAN happen that we get an ambiguity result in
1225 // one particular case around closures where the cache key
1226 // would not change. That is when the precise types of the
1227 // upvars that a closure references have not yet been figured
1228 // out (i.e., because it is not yet known if they are captured
1229 // by ref, and if by ref, what kind of ref). In these cases,
1230 // when matching a builtin bound, we will yield back an
1231 // ambiguous result. But the *cache key* is just the closure type,
1232 // it doesn't capture the state of the upvar computation.
1234 // To avoid this trap, just don't cache ambiguous results if
1235 // the self-type contains no inference byproducts (that really
1236 // shouldn't happen in other circumstances anyway, given
1240 Ok(Some(_)) | Err(_) => true,
1241 Ok(None) => cache_fresh_trait_pred.has_infer_types()
1245 fn assemble_candidates<'o>(&mut self,
1246 stack: &TraitObligationStack<'o, 'tcx>)
1247 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1249 let TraitObligationStack { obligation, .. } = *stack;
1250 let ref obligation = Obligation {
1251 param_env: obligation.param_env,
1252 cause: obligation.cause.clone(),
1253 recursion_depth: obligation.recursion_depth,
1254 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1257 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1258 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1260 // This is somewhat problematic, as the current scheme can't really
1261 // handle it turning to be a projection. This does end up as truly
1262 // ambiguous in most cases anyway.
1264 // Until this is fixed, take the fast path out - this also improves
1265 // performance by preventing assemble_candidates_from_impls from
1266 // matching every impl for this trait.
1267 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1270 let mut candidates = SelectionCandidateSet {
1275 // Other bounds. Consider both in-scope bounds from fn decl
1276 // and applicable impls. There is a certain set of precedence rules here.
1278 let def_id = obligation.predicate.def_id();
1279 if self.tcx().lang_items.copy_trait() == Some(def_id) {
1280 debug!("obligation self ty is {:?}",
1281 obligation.predicate.0.self_ty());
1283 // User-defined copy impls are permitted, but only for
1284 // structs and enums.
1285 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1287 // For other types, we'll use the builtin rules.
1288 let copy_conditions = self.copy_conditions(obligation);
1289 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1290 } else if self.tcx().lang_items.sized_trait() == Some(def_id) {
1291 // Sized is never implementable by end-users, it is
1292 // always automatically computed.
1293 let sized_conditions = self.sized_conditions(obligation);
1294 self.assemble_builtin_bound_candidates(sized_conditions,
1296 } else if self.tcx().lang_items.unsize_trait() == Some(def_id) {
1297 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1299 self.assemble_closure_candidates(obligation, &mut candidates)?;
1300 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1301 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1302 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1305 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1306 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1307 // Default implementations have lower priority, so we only
1308 // consider triggering a default if there is no other impl that can apply.
1309 if candidates.vec.is_empty() {
1310 self.assemble_candidates_from_default_impls(obligation, &mut candidates)?;
1312 debug!("candidate list size: {}", candidates.vec.len());
1316 fn assemble_candidates_from_projected_tys(&mut self,
1317 obligation: &TraitObligation<'tcx>,
1318 candidates: &mut SelectionCandidateSet<'tcx>)
1320 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1322 // FIXME(#20297) -- just examining the self-type is very simplistic
1324 // before we go into the whole skolemization thing, just
1325 // quickly check if the self-type is a projection at all.
1326 match obligation.predicate.0.trait_ref.self_ty().sty {
1327 ty::TyProjection(_) | ty::TyAnon(..) => {}
1328 ty::TyInfer(ty::TyVar(_)) => {
1329 span_bug!(obligation.cause.span,
1330 "Self=_ should have been handled by assemble_candidates");
1335 let result = self.probe(|this, snapshot| {
1336 this.match_projection_obligation_against_definition_bounds(obligation,
1341 candidates.vec.push(ProjectionCandidate);
1345 fn match_projection_obligation_against_definition_bounds(
1347 obligation: &TraitObligation<'tcx>,
1348 snapshot: &infer::CombinedSnapshot)
1351 let poly_trait_predicate =
1352 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1353 let (skol_trait_predicate, skol_map) =
1354 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1355 debug!("match_projection_obligation_against_definition_bounds: \
1356 skol_trait_predicate={:?} skol_map={:?}",
1357 skol_trait_predicate,
1360 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1361 ty::TyProjection(ref data) =>
1362 (data.trait_ref(self.tcx()).def_id, data.substs),
1363 ty::TyAnon(def_id, substs) => (def_id, substs),
1366 obligation.cause.span,
1367 "match_projection_obligation_against_definition_bounds() called \
1368 but self-ty not a projection: {:?}",
1369 skol_trait_predicate.trait_ref.self_ty());
1372 debug!("match_projection_obligation_against_definition_bounds: \
1373 def_id={:?}, substs={:?}",
1376 let predicates_of = self.tcx().predicates_of(def_id);
1377 let bounds = predicates_of.instantiate(self.tcx(), substs);
1378 debug!("match_projection_obligation_against_definition_bounds: \
1382 let matching_bound =
1383 util::elaborate_predicates(self.tcx(), bounds.predicates)
1387 |this, _| this.match_projection(obligation,
1389 skol_trait_predicate.trait_ref.clone(),
1393 debug!("match_projection_obligation_against_definition_bounds: \
1394 matching_bound={:?}",
1396 match matching_bound {
1399 // Repeat the successful match, if any, this time outside of a probe.
1400 let result = self.match_projection(obligation,
1402 skol_trait_predicate.trait_ref.clone(),
1406 self.infcx.pop_skolemized(skol_map, snapshot);
1414 fn match_projection(&mut self,
1415 obligation: &TraitObligation<'tcx>,
1416 trait_bound: ty::PolyTraitRef<'tcx>,
1417 skol_trait_ref: ty::TraitRef<'tcx>,
1418 skol_map: &infer::SkolemizationMap<'tcx>,
1419 snapshot: &infer::CombinedSnapshot)
1422 assert!(!skol_trait_ref.has_escaping_regions());
1423 match self.infcx.at(&obligation.cause, obligation.param_env)
1424 .sup(ty::Binder(skol_trait_ref), trait_bound) {
1425 Ok(InferOk { obligations, .. }) => {
1426 self.inferred_obligations.extend(obligations);
1428 Err(_) => { return false; }
1431 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1434 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1435 /// supplied to find out whether it is listed among them.
1437 /// Never affects inference environment.
1438 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1439 stack: &TraitObligationStack<'o, 'tcx>,
1440 candidates: &mut SelectionCandidateSet<'tcx>)
1441 -> Result<(),SelectionError<'tcx>>
1443 debug!("assemble_candidates_from_caller_bounds({:?})",
1447 stack.obligation.param_env.caller_bounds
1449 .filter_map(|o| o.to_opt_poly_trait_ref());
1451 // micro-optimization: filter out predicates relating to different
1453 let matching_bounds =
1454 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1456 let matching_bounds =
1457 matching_bounds.filter(
1458 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1460 let param_candidates =
1461 matching_bounds.map(|bound| ParamCandidate(bound));
1463 candidates.vec.extend(param_candidates);
1468 fn evaluate_where_clause<'o>(&mut self,
1469 stack: &TraitObligationStack<'o, 'tcx>,
1470 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1473 self.probe(move |this, _| {
1474 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1475 Ok(obligations) => {
1476 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1478 Err(()) => EvaluatedToErr
1483 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1484 /// FnMut<..>` where `X` is a closure type.
1486 /// Note: the type parameters on a closure candidate are modeled as *output* type
1487 /// parameters and hence do not affect whether this trait is a match or not. They will be
1488 /// unified during the confirmation step.
1489 fn assemble_closure_candidates(&mut self,
1490 obligation: &TraitObligation<'tcx>,
1491 candidates: &mut SelectionCandidateSet<'tcx>)
1492 -> Result<(),SelectionError<'tcx>>
1494 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1496 None => { return Ok(()); }
1499 // ok to skip binder because the substs on closure types never
1500 // touch bound regions, they just capture the in-scope
1501 // type/region parameters
1502 let self_ty = *obligation.self_ty().skip_binder();
1503 let (closure_def_id, substs) = match self_ty.sty {
1504 ty::TyClosure(id, substs) => (id, substs),
1505 ty::TyInfer(ty::TyVar(_)) => {
1506 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1507 candidates.ambiguous = true;
1510 _ => { return Ok(()); }
1513 debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1518 match self.infcx.closure_kind(closure_def_id) {
1519 Some(closure_kind) => {
1520 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1521 if closure_kind.extends(kind) {
1522 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1526 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1527 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1534 /// Implement one of the `Fn()` family for a fn pointer.
1535 fn assemble_fn_pointer_candidates(&mut self,
1536 obligation: &TraitObligation<'tcx>,
1537 candidates: &mut SelectionCandidateSet<'tcx>)
1538 -> Result<(),SelectionError<'tcx>>
1540 // We provide impl of all fn traits for fn pointers.
1541 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1545 // ok to skip binder because what we are inspecting doesn't involve bound regions
1546 let self_ty = *obligation.self_ty().skip_binder();
1548 ty::TyInfer(ty::TyVar(_)) => {
1549 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1550 candidates.ambiguous = true; // could wind up being a fn() type
1553 // provide an impl, but only for suitable `fn` pointers
1554 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
1555 if let ty::Binder(ty::FnSig {
1556 unsafety: hir::Unsafety::Normal,
1560 }) = self_ty.fn_sig(self.tcx()) {
1561 candidates.vec.push(FnPointerCandidate);
1571 /// Search for impls that might apply to `obligation`.
1572 fn assemble_candidates_from_impls(&mut self,
1573 obligation: &TraitObligation<'tcx>,
1574 candidates: &mut SelectionCandidateSet<'tcx>)
1575 -> Result<(), SelectionError<'tcx>>
1577 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1579 let def = self.tcx().trait_def(obligation.predicate.def_id());
1581 def.for_each_relevant_impl(
1583 obligation.predicate.0.trait_ref.self_ty(),
1585 self.probe(|this, snapshot| { /* [1] */
1586 match this.match_impl(impl_def_id, obligation, snapshot) {
1588 candidates.vec.push(ImplCandidate(impl_def_id));
1590 // NB: we can safely drop the skol map
1591 // since we are in a probe [1]
1592 mem::drop(skol_map);
1603 fn assemble_candidates_from_default_impls(&mut self,
1604 obligation: &TraitObligation<'tcx>,
1605 candidates: &mut SelectionCandidateSet<'tcx>)
1606 -> Result<(), SelectionError<'tcx>>
1608 // OK to skip binder here because the tests we do below do not involve bound regions
1609 let self_ty = *obligation.self_ty().skip_binder();
1610 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1612 let def_id = obligation.predicate.def_id();
1614 if self.tcx().trait_has_default_impl(def_id) {
1616 ty::TyDynamic(..) => {
1617 // For object types, we don't know what the closed
1618 // over types are. This means we conservatively
1619 // say nothing; a candidate may be added by
1620 // `assemble_candidates_from_object_ty`.
1623 ty::TyProjection(..) => {
1624 // In these cases, we don't know what the actual
1625 // type is. Therefore, we cannot break it down
1626 // into its constituent types. So we don't
1627 // consider the `..` impl but instead just add no
1628 // candidates: this means that typeck will only
1629 // succeed if there is another reason to believe
1630 // that this obligation holds. That could be a
1631 // where-clause or, in the case of an object type,
1632 // it could be that the object type lists the
1633 // trait (e.g. `Foo+Send : Send`). See
1634 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1635 // for an example of a test case that exercises
1638 ty::TyInfer(ty::TyVar(_)) => {
1639 // the defaulted impl might apply, we don't know
1640 candidates.ambiguous = true;
1643 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1651 /// Search for impls that might apply to `obligation`.
1652 fn assemble_candidates_from_object_ty(&mut self,
1653 obligation: &TraitObligation<'tcx>,
1654 candidates: &mut SelectionCandidateSet<'tcx>)
1656 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1657 obligation.self_ty().skip_binder());
1659 // Object-safety candidates are only applicable to object-safe
1660 // traits. Including this check is useful because it helps
1661 // inference in cases of traits like `BorrowFrom`, which are
1662 // not object-safe, and which rely on being able to infer the
1663 // self-type from one of the other inputs. Without this check,
1664 // these cases wind up being considered ambiguous due to a
1665 // (spurious) ambiguity introduced here.
1666 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1667 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1671 self.probe(|this, _snapshot| {
1672 // the code below doesn't care about regions, and the
1673 // self-ty here doesn't escape this probe, so just erase
1675 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1676 let poly_trait_ref = match self_ty.sty {
1677 ty::TyDynamic(ref data, ..) => {
1678 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1679 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1680 pushing candidate");
1681 candidates.vec.push(BuiltinObjectCandidate);
1685 match data.principal() {
1686 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1690 ty::TyInfer(ty::TyVar(_)) => {
1691 debug!("assemble_candidates_from_object_ty: ambiguous");
1692 candidates.ambiguous = true; // could wind up being an object type
1700 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1703 // Count only those upcast versions that match the trait-ref
1704 // we are looking for. Specifically, do not only check for the
1705 // correct trait, but also the correct type parameters.
1706 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1707 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1708 let upcast_trait_refs =
1709 util::supertraits(this.tcx(), poly_trait_ref)
1710 .filter(|upcast_trait_ref| {
1711 this.probe(|this, _| {
1712 let upcast_trait_ref = upcast_trait_ref.clone();
1713 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1718 if upcast_trait_refs > 1 {
1719 // can be upcast in many ways; need more type information
1720 candidates.ambiguous = true;
1721 } else if upcast_trait_refs == 1 {
1722 candidates.vec.push(ObjectCandidate);
1727 /// Search for unsizing that might apply to `obligation`.
1728 fn assemble_candidates_for_unsizing(&mut self,
1729 obligation: &TraitObligation<'tcx>,
1730 candidates: &mut SelectionCandidateSet<'tcx>) {
1731 // We currently never consider higher-ranked obligations e.g.
1732 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1733 // because they are a priori invalid, and we could potentially add support
1734 // for them later, it's just that there isn't really a strong need for it.
1735 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1736 // impl, and those are generally applied to concrete types.
1738 // That said, one might try to write a fn with a where clause like
1739 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1740 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1741 // Still, you'd be more likely to write that where clause as
1743 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1744 // obligation above. Should be possible to extend this in the future.
1745 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1748 // Don't add any candidates if there are bound regions.
1752 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1754 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1757 let may_apply = match (&source.sty, &target.sty) {
1758 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1759 (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1760 // Upcasts permit two things:
1762 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1763 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1765 // Note that neither of these changes requires any
1766 // change at runtime. Eventually this will be
1769 // We always upcast when we can because of reason
1770 // #2 (region bounds).
1771 match (data_a.principal(), data_b.principal()) {
1772 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1773 data_b.auto_traits()
1774 // All of a's auto traits need to be in b's auto traits.
1775 .all(|b| data_a.auto_traits().any(|a| a == b)),
1781 (_, &ty::TyDynamic(..)) => true,
1783 // Ambiguous handling is below T -> Trait, because inference
1784 // variables can still implement Unsize<Trait> and nested
1785 // obligations will have the final say (likely deferred).
1786 (&ty::TyInfer(ty::TyVar(_)), _) |
1787 (_, &ty::TyInfer(ty::TyVar(_))) => {
1788 debug!("assemble_candidates_for_unsizing: ambiguous");
1789 candidates.ambiguous = true;
1794 (&ty::TyArray(..), &ty::TySlice(_)) => true,
1796 // Struct<T> -> Struct<U>.
1797 (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1798 def_id_a == def_id_b
1801 // (.., T) -> (.., U).
1802 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
1803 tys_a.len() == tys_b.len()
1810 candidates.vec.push(BuiltinUnsizeCandidate);
1814 ///////////////////////////////////////////////////////////////////////////
1817 // Winnowing is the process of attempting to resolve ambiguity by
1818 // probing further. During the winnowing process, we unify all
1819 // type variables (ignoring skolemization) and then we also
1820 // attempt to evaluate recursive bounds to see if they are
1823 /// Returns true if `candidate_i` should be dropped in favor of
1824 /// `candidate_j`. Generally speaking we will drop duplicate
1825 /// candidates and prefer where-clause candidates.
1826 /// Returns true if `victim` should be dropped in favor of
1827 /// `other`. Generally speaking we will drop duplicate
1828 /// candidates and prefer where-clause candidates.
1830 /// See the comment for "SelectionCandidate" for more details.
1831 fn candidate_should_be_dropped_in_favor_of<'o>(
1833 victim: &EvaluatedCandidate<'tcx>,
1834 other: &EvaluatedCandidate<'tcx>)
1837 if victim.candidate == other.candidate {
1841 match other.candidate {
1843 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1844 DefaultImplCandidate(..) => {
1846 "default implementations shouldn't be recorded \
1847 when there are other valid candidates");
1850 ClosureCandidate(..) |
1851 FnPointerCandidate |
1852 BuiltinObjectCandidate |
1853 BuiltinUnsizeCandidate |
1854 BuiltinCandidate { .. } => {
1855 // We have a where-clause so don't go around looking
1860 ProjectionCandidate => {
1861 // Arbitrarily give param candidates priority
1862 // over projection and object candidates.
1865 ParamCandidate(..) => false,
1867 ImplCandidate(other_def) => {
1868 // See if we can toss out `victim` based on specialization.
1869 // This requires us to know *for sure* that the `other` impl applies
1870 // i.e. EvaluatedToOk:
1871 if other.evaluation == EvaluatedToOk {
1872 if let ImplCandidate(victim_def) = victim.candidate {
1873 let tcx = self.tcx().global_tcx();
1874 return traits::specializes(tcx, other_def, victim_def) ||
1875 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
1885 ///////////////////////////////////////////////////////////////////////////
1888 // These cover the traits that are built-in to the language
1889 // itself. This includes `Copy` and `Sized` for sure. For the
1890 // moment, it also includes `Send` / `Sync` and a few others, but
1891 // those will hopefully change to library-defined traits in the
1894 // HACK: if this returns an error, selection exits without considering
1896 fn assemble_builtin_bound_candidates<'o>(&mut self,
1897 conditions: BuiltinImplConditions<'tcx>,
1898 candidates: &mut SelectionCandidateSet<'tcx>)
1899 -> Result<(),SelectionError<'tcx>>
1902 BuiltinImplConditions::Where(nested) => {
1903 debug!("builtin_bound: nested={:?}", nested);
1904 candidates.vec.push(BuiltinCandidate {
1905 has_nested: nested.skip_binder().len() > 0
1909 BuiltinImplConditions::None => { Ok(()) }
1910 BuiltinImplConditions::Ambiguous => {
1911 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1912 Ok(candidates.ambiguous = true)
1914 BuiltinImplConditions::Never => { Err(Unimplemented) }
1918 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1919 -> BuiltinImplConditions<'tcx>
1921 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1923 // NOTE: binder moved to (*)
1924 let self_ty = self.infcx.shallow_resolve(
1925 obligation.predicate.skip_binder().self_ty());
1928 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1929 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1930 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
1931 ty::TyChar | ty::TyRef(..) |
1932 ty::TyArray(..) | ty::TyClosure(..) | ty::TyNever |
1934 // safe for everything
1935 Where(ty::Binder(Vec::new()))
1938 ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) => Never,
1940 ty::TyTuple(tys, _) => {
1941 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
1944 ty::TyAdt(def, substs) => {
1945 let sized_crit = def.sized_constraint(self.tcx());
1946 // (*) binder moved here
1948 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1952 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
1953 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
1955 ty::TyInfer(ty::FreshTy(_))
1956 | ty::TyInfer(ty::FreshIntTy(_))
1957 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1958 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1964 fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1965 -> BuiltinImplConditions<'tcx>
1967 // NOTE: binder moved to (*)
1968 let self_ty = self.infcx.shallow_resolve(
1969 obligation.predicate.skip_binder().self_ty());
1971 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1974 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1975 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1976 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1977 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
1978 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
1979 Where(ty::Binder(Vec::new()))
1982 ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
1984 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
1988 ty::TyArray(element_ty, _) => {
1989 // (*) binder moved here
1990 Where(ty::Binder(vec![element_ty]))
1993 ty::TyTuple(tys, _) => {
1994 // (*) binder moved here
1995 Where(ty::Binder(tys.to_vec()))
1998 ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
1999 // Fallback to whatever user-defined impls exist in this case.
2003 ty::TyInfer(ty::TyVar(_)) => {
2004 // Unbound type variable. Might or might not have
2005 // applicable impls and so forth, depending on what
2006 // those type variables wind up being bound to.
2010 ty::TyInfer(ty::FreshTy(_))
2011 | ty::TyInfer(ty::FreshIntTy(_))
2012 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2013 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2019 /// For default impls, we need to break apart a type into its
2020 /// "constituent types" -- meaning, the types that it contains.
2022 /// Here are some (simple) examples:
2025 /// (i32, u32) -> [i32, u32]
2026 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2027 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2028 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2030 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2040 ty::TyInfer(ty::IntVar(_)) |
2041 ty::TyInfer(ty::FloatVar(_)) |
2049 ty::TyProjection(..) |
2050 ty::TyInfer(ty::TyVar(_)) |
2051 ty::TyInfer(ty::FreshTy(_)) |
2052 ty::TyInfer(ty::FreshIntTy(_)) |
2053 ty::TyInfer(ty::FreshFloatTy(_)) => {
2054 bug!("asked to assemble constituent types of unexpected type: {:?}",
2058 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
2059 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
2063 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
2067 ty::TyTuple(ref tys, _) => {
2068 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2072 ty::TyClosure(def_id, ref substs) => {
2073 // FIXME(#27086). We are invariant w/r/t our
2074 // func_substs, but we don't see them as
2075 // constituent types; this seems RIGHT but also like
2076 // something that a normal type couldn't simulate. Is
2077 // this just a gap with the way that PhantomData and
2078 // OIBIT interact? That is, there is no way to say
2079 // "make me invariant with respect to this TYPE, but
2080 // do not act as though I can reach it"
2081 substs.upvar_tys(def_id, self.tcx()).collect()
2084 // for `PhantomData<T>`, we pass `T`
2085 ty::TyAdt(def, substs) if def.is_phantom_data() => {
2086 substs.types().collect()
2089 ty::TyAdt(def, substs) => {
2091 .map(|f| f.ty(self.tcx(), substs))
2095 ty::TyAnon(def_id, substs) => {
2096 // We can resolve the `impl Trait` to its concrete type,
2097 // which enforces a DAG between the functions requiring
2098 // the auto trait bounds in question.
2099 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2104 fn collect_predicates_for_types(&mut self,
2105 param_env: ty::ParamEnv<'tcx>,
2106 cause: ObligationCause<'tcx>,
2107 recursion_depth: usize,
2108 trait_def_id: DefId,
2109 types: ty::Binder<Vec<Ty<'tcx>>>)
2110 -> Vec<PredicateObligation<'tcx>>
2112 // Because the types were potentially derived from
2113 // higher-ranked obligations they may reference late-bound
2114 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2115 // yield a type like `for<'a> &'a int`. In general, we
2116 // maintain the invariant that we never manipulate bound
2117 // regions, so we have to process these bound regions somehow.
2119 // The strategy is to:
2121 // 1. Instantiate those regions to skolemized regions (e.g.,
2122 // `for<'a> &'a int` becomes `&0 int`.
2123 // 2. Produce something like `&'0 int : Copy`
2124 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2126 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
2127 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
2129 self.in_snapshot(|this, snapshot| {
2130 let (skol_ty, skol_map) =
2131 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
2132 let Normalized { value: normalized_ty, mut obligations } =
2133 project::normalize_with_depth(this,
2138 let skol_obligation =
2139 this.tcx().predicate_for_trait_def(param_env,
2145 obligations.push(skol_obligation);
2146 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2151 ///////////////////////////////////////////////////////////////////////////
2154 // Confirmation unifies the output type parameters of the trait
2155 // with the values found in the obligation, possibly yielding a
2156 // type error. See `README.md` for more details.
2158 fn confirm_candidate(&mut self,
2159 obligation: &TraitObligation<'tcx>,
2160 candidate: SelectionCandidate<'tcx>)
2161 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2163 debug!("confirm_candidate({:?}, {:?})",
2168 BuiltinCandidate { has_nested } => {
2170 self.confirm_builtin_candidate(obligation, has_nested)))
2173 ParamCandidate(param) => {
2174 let obligations = self.confirm_param_candidate(obligation, param);
2175 Ok(VtableParam(obligations))
2178 DefaultImplCandidate(trait_def_id) => {
2179 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2180 Ok(VtableDefaultImpl(data))
2183 ImplCandidate(impl_def_id) => {
2184 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2187 ClosureCandidate(closure_def_id, substs, kind) => {
2188 let vtable_closure =
2189 self.confirm_closure_candidate(obligation, closure_def_id, substs, kind)?;
2190 Ok(VtableClosure(vtable_closure))
2193 BuiltinObjectCandidate => {
2194 // This indicates something like `(Trait+Send) :
2195 // Send`. In this case, we know that this holds
2196 // because that's what the object type is telling us,
2197 // and there's really no additional obligations to
2198 // prove and no types in particular to unify etc.
2199 Ok(VtableParam(Vec::new()))
2202 ObjectCandidate => {
2203 let data = self.confirm_object_candidate(obligation);
2204 Ok(VtableObject(data))
2207 FnPointerCandidate => {
2209 self.confirm_fn_pointer_candidate(obligation)?;
2210 Ok(VtableFnPointer(data))
2213 ProjectionCandidate => {
2214 self.confirm_projection_candidate(obligation);
2215 Ok(VtableParam(Vec::new()))
2218 BuiltinUnsizeCandidate => {
2219 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2220 Ok(VtableBuiltin(data))
2225 fn confirm_projection_candidate(&mut self,
2226 obligation: &TraitObligation<'tcx>)
2228 self.in_snapshot(|this, snapshot| {
2230 this.match_projection_obligation_against_definition_bounds(obligation,
2236 fn confirm_param_candidate(&mut self,
2237 obligation: &TraitObligation<'tcx>,
2238 param: ty::PolyTraitRef<'tcx>)
2239 -> Vec<PredicateObligation<'tcx>>
2241 debug!("confirm_param_candidate({:?},{:?})",
2245 // During evaluation, we already checked that this
2246 // where-clause trait-ref could be unified with the obligation
2247 // trait-ref. Repeat that unification now without any
2248 // transactional boundary; it should not fail.
2249 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2250 Ok(obligations) => obligations,
2252 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2259 fn confirm_builtin_candidate(&mut self,
2260 obligation: &TraitObligation<'tcx>,
2262 -> VtableBuiltinData<PredicateObligation<'tcx>>
2264 debug!("confirm_builtin_candidate({:?}, {:?})",
2265 obligation, has_nested);
2267 let obligations = if has_nested {
2268 let trait_def = obligation.predicate.def_id();
2269 let conditions = match trait_def {
2270 _ if Some(trait_def) == self.tcx().lang_items.sized_trait() => {
2271 self.sized_conditions(obligation)
2273 _ if Some(trait_def) == self.tcx().lang_items.copy_trait() => {
2274 self.copy_conditions(obligation)
2276 _ => bug!("unexpected builtin trait {:?}", trait_def)
2278 let nested = match conditions {
2279 BuiltinImplConditions::Where(nested) => nested,
2280 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2284 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2285 self.collect_predicates_for_types(obligation.param_env,
2287 obligation.recursion_depth+1,
2294 debug!("confirm_builtin_candidate: obligations={:?}",
2296 VtableBuiltinData { nested: obligations }
2299 /// This handles the case where a `impl Foo for ..` impl is being used.
2300 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2302 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2303 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2304 fn confirm_default_impl_candidate(&mut self,
2305 obligation: &TraitObligation<'tcx>,
2306 trait_def_id: DefId)
2307 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2309 debug!("confirm_default_impl_candidate({:?}, {:?})",
2313 // binder is moved below
2314 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2315 let types = self.constituent_types_for_ty(self_ty);
2316 self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2319 /// See `confirm_default_impl_candidate`
2320 fn vtable_default_impl(&mut self,
2321 obligation: &TraitObligation<'tcx>,
2322 trait_def_id: DefId,
2323 nested: ty::Binder<Vec<Ty<'tcx>>>)
2324 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2326 debug!("vtable_default_impl: nested={:?}", nested);
2328 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2329 let mut obligations = self.collect_predicates_for_types(
2330 obligation.param_env,
2332 obligation.recursion_depth+1,
2336 let trait_obligations = self.in_snapshot(|this, snapshot| {
2337 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2338 let (trait_ref, skol_map) =
2339 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2340 let cause = obligation.derived_cause(ImplDerivedObligation);
2341 this.impl_or_trait_obligations(cause,
2342 obligation.recursion_depth + 1,
2343 obligation.param_env,
2350 obligations.extend(trait_obligations);
2352 debug!("vtable_default_impl: obligations={:?}", obligations);
2354 VtableDefaultImplData {
2360 fn confirm_impl_candidate(&mut self,
2361 obligation: &TraitObligation<'tcx>,
2363 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2365 debug!("confirm_impl_candidate({:?},{:?})",
2369 // First, create the substitutions by matching the impl again,
2370 // this time not in a probe.
2371 self.in_snapshot(|this, snapshot| {
2372 let (substs, skol_map) =
2373 this.rematch_impl(impl_def_id, obligation,
2375 debug!("confirm_impl_candidate substs={:?}", substs);
2376 let cause = obligation.derived_cause(ImplDerivedObligation);
2377 this.vtable_impl(impl_def_id,
2380 obligation.recursion_depth + 1,
2381 obligation.param_env,
2387 fn vtable_impl(&mut self,
2389 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2390 cause: ObligationCause<'tcx>,
2391 recursion_depth: usize,
2392 param_env: ty::ParamEnv<'tcx>,
2393 skol_map: infer::SkolemizationMap<'tcx>,
2394 snapshot: &infer::CombinedSnapshot)
2395 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2397 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2403 let mut impl_obligations =
2404 self.impl_or_trait_obligations(cause,
2412 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2416 // Because of RFC447, the impl-trait-ref and obligations
2417 // are sufficient to determine the impl substs, without
2418 // relying on projections in the impl-trait-ref.
2420 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2421 impl_obligations.append(&mut substs.obligations);
2423 VtableImplData { impl_def_id,
2424 substs: substs.value,
2425 nested: impl_obligations }
2428 fn confirm_object_candidate(&mut self,
2429 obligation: &TraitObligation<'tcx>)
2430 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2432 debug!("confirm_object_candidate({:?})",
2435 // FIXME skipping binder here seems wrong -- we should
2436 // probably flatten the binder from the obligation and the
2437 // binder from the object. Have to try to make a broken test
2438 // case that results. -nmatsakis
2439 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2440 let poly_trait_ref = match self_ty.sty {
2441 ty::TyDynamic(ref data, ..) => {
2442 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2445 span_bug!(obligation.cause.span,
2446 "object candidate with non-object");
2450 let mut upcast_trait_ref = None;
2454 let tcx = self.tcx();
2456 // We want to find the first supertrait in the list of
2457 // supertraits that we can unify with, and do that
2458 // unification. We know that there is exactly one in the list
2459 // where we can unify because otherwise select would have
2460 // reported an ambiguity. (When we do find a match, also
2461 // record it for later.)
2463 util::supertraits(tcx, poly_trait_ref)
2467 |this, _| this.match_poly_trait_ref(obligation, t))
2469 Ok(_) => { upcast_trait_ref = Some(t); false }
2474 // Additionally, for each of the nonmatching predicates that
2475 // we pass over, we sum up the set of number of vtable
2476 // entries, so that we can compute the offset for the selected
2479 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2485 upcast_trait_ref: upcast_trait_ref.unwrap(),
2491 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2492 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2494 debug!("confirm_fn_pointer_candidate({:?})",
2497 // ok to skip binder; it is reintroduced below
2498 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2499 let sig = self_ty.fn_sig(self.tcx());
2501 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2504 util::TupleArgumentsFlag::Yes)
2505 .map_bound(|(trait_ref, _)| trait_ref);
2507 let Normalized { value: trait_ref, obligations } =
2508 project::normalize_with_depth(self,
2509 obligation.param_env,
2510 obligation.cause.clone(),
2511 obligation.recursion_depth + 1,
2514 self.confirm_poly_trait_refs(obligation.cause.clone(),
2515 obligation.param_env,
2516 obligation.predicate.to_poly_trait_ref(),
2518 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2521 fn confirm_closure_candidate(&mut self,
2522 obligation: &TraitObligation<'tcx>,
2523 closure_def_id: DefId,
2524 substs: ty::ClosureSubsts<'tcx>,
2525 kind: ty::ClosureKind)
2526 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2527 SelectionError<'tcx>>
2529 debug!("confirm_closure_candidate({:?},{:?},{:?})",
2537 } = self.closure_trait_ref(obligation, closure_def_id, substs);
2539 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2544 self.confirm_poly_trait_refs(obligation.cause.clone(),
2545 obligation.param_env,
2546 obligation.predicate.to_poly_trait_ref(),
2549 obligations.push(Obligation::new(
2550 obligation.cause.clone(),
2551 obligation.param_env,
2552 ty::Predicate::ClosureKind(closure_def_id, kind)));
2554 Ok(VtableClosureData {
2556 substs: substs.clone(),
2561 /// In the case of closure types and fn pointers,
2562 /// we currently treat the input type parameters on the trait as
2563 /// outputs. This means that when we have a match we have only
2564 /// considered the self type, so we have to go back and make sure
2565 /// to relate the argument types too. This is kind of wrong, but
2566 /// since we control the full set of impls, also not that wrong,
2567 /// and it DOES yield better error messages (since we don't report
2568 /// errors as if there is no applicable impl, but rather report
2569 /// errors are about mismatched argument types.
2571 /// Here is an example. Imagine we have a closure expression
2572 /// and we desugared it so that the type of the expression is
2573 /// `Closure`, and `Closure` expects an int as argument. Then it
2574 /// is "as if" the compiler generated this impl:
2576 /// impl Fn(int) for Closure { ... }
2578 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2579 /// we have matched the self-type `Closure`. At this point we'll
2580 /// compare the `int` to `usize` and generate an error.
2582 /// Note that this checking occurs *after* the impl has selected,
2583 /// because these output type parameters should not affect the
2584 /// selection of the impl. Therefore, if there is a mismatch, we
2585 /// report an error to the user.
2586 fn confirm_poly_trait_refs(&mut self,
2587 obligation_cause: ObligationCause<'tcx>,
2588 obligation_param_env: ty::ParamEnv<'tcx>,
2589 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2590 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2591 -> Result<(), SelectionError<'tcx>>
2593 let obligation_trait_ref = obligation_trait_ref.clone();
2595 .at(&obligation_cause, obligation_param_env)
2596 .sup(obligation_trait_ref, expected_trait_ref)
2597 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2598 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2601 fn confirm_builtin_unsize_candidate(&mut self,
2602 obligation: &TraitObligation<'tcx>,)
2603 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2604 SelectionError<'tcx>> {
2605 let tcx = self.tcx();
2607 // assemble_candidates_for_unsizing should ensure there are no late bound
2608 // regions here. See the comment there for more details.
2609 let source = self.infcx.shallow_resolve(
2610 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2611 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2612 let target = self.infcx.shallow_resolve(target);
2614 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2617 let mut nested = vec![];
2618 match (&source.sty, &target.sty) {
2619 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2620 (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2621 // See assemble_candidates_for_unsizing for more info.
2622 // Binders reintroduced below in call to mk_existential_predicates.
2623 let principal = data_a.skip_binder().principal();
2624 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2625 .chain(data_a.skip_binder().projection_bounds()
2626 .map(|x| ty::ExistentialPredicate::Projection(x)))
2627 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2628 let new_trait = tcx.mk_dynamic(
2629 ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2630 let InferOk { obligations, .. } =
2631 self.infcx.at(&obligation.cause, obligation.param_env)
2632 .eq(target, new_trait)
2633 .map_err(|_| Unimplemented)?;
2634 self.inferred_obligations.extend(obligations);
2636 // Register one obligation for 'a: 'b.
2637 let cause = ObligationCause::new(obligation.cause.span,
2638 obligation.cause.body_id,
2639 ObjectCastObligation(target));
2640 let outlives = ty::OutlivesPredicate(r_a, r_b);
2641 nested.push(Obligation::with_depth(cause,
2642 obligation.recursion_depth + 1,
2643 obligation.param_env,
2644 ty::Binder(outlives).to_predicate()));
2648 (_, &ty::TyDynamic(ref data, r)) => {
2649 let mut object_dids =
2650 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2651 if let Some(did) = object_dids.find(|did| {
2652 !tcx.is_object_safe(*did)
2654 return Err(TraitNotObjectSafe(did))
2657 let cause = ObligationCause::new(obligation.cause.span,
2658 obligation.cause.body_id,
2659 ObjectCastObligation(target));
2660 let mut push = |predicate| {
2661 nested.push(Obligation::with_depth(cause.clone(),
2662 obligation.recursion_depth + 1,
2663 obligation.param_env,
2667 // Create obligations:
2668 // - Casting T to Trait
2669 // - For all the various builtin bounds attached to the object cast. (In other
2670 // words, if the object type is Foo+Send, this would create an obligation for the
2672 // - Projection predicates
2673 for predicate in data.iter() {
2674 push(predicate.with_self_ty(tcx, source));
2677 // We can only make objects from sized types.
2678 let tr = ty::TraitRef {
2679 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2680 substs: tcx.mk_substs_trait(source, &[]),
2682 push(tr.to_predicate());
2684 // If the type is `Foo+'a`, ensures that the type
2685 // being cast to `Foo+'a` outlives `'a`:
2686 let outlives = ty::OutlivesPredicate(source, r);
2687 push(ty::Binder(outlives).to_predicate());
2691 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2692 let InferOk { obligations, .. } =
2693 self.infcx.at(&obligation.cause, obligation.param_env)
2695 .map_err(|_| Unimplemented)?;
2696 self.inferred_obligations.extend(obligations);
2699 // Struct<T> -> Struct<U>.
2700 (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2703 .map(|f| tcx.type_of(f.did))
2704 .collect::<Vec<_>>();
2706 // The last field of the structure has to exist and contain type parameters.
2707 let field = if let Some(&field) = fields.last() {
2710 return Err(Unimplemented);
2712 let mut ty_params = BitVector::new(substs_a.types().count());
2713 let mut found = false;
2714 for ty in field.walk() {
2715 if let ty::TyParam(p) = ty.sty {
2716 ty_params.insert(p.idx as usize);
2721 return Err(Unimplemented);
2724 // Replace type parameters used in unsizing with
2725 // TyError and ensure they do not affect any other fields.
2726 // This could be checked after type collection for any struct
2727 // with a potentially unsized trailing field.
2728 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2729 if ty_params.contains(i) {
2730 Kind::from(tcx.types.err)
2735 let substs = tcx.mk_substs(params);
2736 for &ty in fields.split_last().unwrap().1 {
2737 if ty.subst(tcx, substs).references_error() {
2738 return Err(Unimplemented);
2742 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2743 let inner_source = field.subst(tcx, substs_a);
2744 let inner_target = field.subst(tcx, substs_b);
2746 // Check that the source struct with the target's
2747 // unsized parameters is equal to the target.
2748 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2749 if ty_params.contains(i) {
2750 Kind::from(substs_b.type_at(i))
2755 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
2756 let InferOk { obligations, .. } =
2757 self.infcx.at(&obligation.cause, obligation.param_env)
2758 .eq(target, new_struct)
2759 .map_err(|_| Unimplemented)?;
2760 self.inferred_obligations.extend(obligations);
2762 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2763 nested.push(tcx.predicate_for_trait_def(
2764 obligation.param_env,
2765 obligation.cause.clone(),
2766 obligation.predicate.def_id(),
2767 obligation.recursion_depth + 1,
2772 // (.., T) -> (.., U).
2773 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
2774 assert_eq!(tys_a.len(), tys_b.len());
2776 // The last field of the tuple has to exist.
2777 let (a_last, a_mid) = if let Some(x) = tys_a.split_last() {
2780 return Err(Unimplemented);
2782 let b_last = tys_b.last().unwrap();
2784 // Check that the source tuple with the target's
2785 // last element is equal to the target.
2786 let new_tuple = tcx.mk_tup(a_mid.iter().chain(Some(b_last)), false);
2787 let InferOk { obligations, .. } =
2788 self.infcx.at(&obligation.cause, obligation.param_env)
2789 .eq(target, new_tuple)
2790 .map_err(|_| Unimplemented)?;
2791 self.inferred_obligations.extend(obligations);
2793 // Construct the nested T: Unsize<U> predicate.
2794 nested.push(tcx.predicate_for_trait_def(
2795 obligation.param_env,
2796 obligation.cause.clone(),
2797 obligation.predicate.def_id(),
2798 obligation.recursion_depth + 1,
2806 Ok(VtableBuiltinData { nested: nested })
2809 ///////////////////////////////////////////////////////////////////////////
2812 // Matching is a common path used for both evaluation and
2813 // confirmation. It basically unifies types that appear in impls
2814 // and traits. This does affect the surrounding environment;
2815 // therefore, when used during evaluation, match routines must be
2816 // run inside of a `probe()` so that their side-effects are
2819 fn rematch_impl(&mut self,
2821 obligation: &TraitObligation<'tcx>,
2822 snapshot: &infer::CombinedSnapshot)
2823 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
2824 infer::SkolemizationMap<'tcx>)
2826 match self.match_impl(impl_def_id, obligation, snapshot) {
2827 Ok((substs, skol_map)) => (substs, skol_map),
2829 bug!("Impl {:?} was matchable against {:?} but now is not",
2836 fn match_impl(&mut self,
2838 obligation: &TraitObligation<'tcx>,
2839 snapshot: &infer::CombinedSnapshot)
2840 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
2841 infer::SkolemizationMap<'tcx>), ()>
2843 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2845 // Before we create the substitutions and everything, first
2846 // consider a "quick reject". This avoids creating more types
2847 // and so forth that we need to.
2848 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2852 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2853 &obligation.predicate,
2855 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2857 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
2860 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2863 let impl_trait_ref =
2864 project::normalize_with_depth(self,
2865 obligation.param_env,
2866 obligation.cause.clone(),
2867 obligation.recursion_depth + 1,
2870 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2871 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2875 skol_obligation_trait_ref);
2877 let InferOk { obligations, .. } =
2878 self.infcx.at(&obligation.cause, obligation.param_env)
2879 .eq(skol_obligation_trait_ref, impl_trait_ref.value)
2881 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2884 self.inferred_obligations.extend(obligations);
2886 if let Err(e) = self.infcx.leak_check(false,
2887 obligation.cause.span,
2890 debug!("match_impl: failed leak check due to `{}`", e);
2894 debug!("match_impl: success impl_substs={:?}", impl_substs);
2897 obligations: impl_trait_ref.obligations
2901 fn fast_reject_trait_refs(&mut self,
2902 obligation: &TraitObligation,
2903 impl_trait_ref: &ty::TraitRef)
2906 // We can avoid creating type variables and doing the full
2907 // substitution if we find that any of the input types, when
2908 // simplified, do not match.
2910 obligation.predicate.skip_binder().input_types()
2911 .zip(impl_trait_ref.input_types())
2912 .any(|(obligation_ty, impl_ty)| {
2913 let simplified_obligation_ty =
2914 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2915 let simplified_impl_ty =
2916 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2918 simplified_obligation_ty.is_some() &&
2919 simplified_impl_ty.is_some() &&
2920 simplified_obligation_ty != simplified_impl_ty
2924 /// Normalize `where_clause_trait_ref` and try to match it against
2925 /// `obligation`. If successful, return any predicates that
2926 /// result from the normalization. Normalization is necessary
2927 /// because where-clauses are stored in the parameter environment
2929 fn match_where_clause_trait_ref(&mut self,
2930 obligation: &TraitObligation<'tcx>,
2931 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2932 -> Result<Vec<PredicateObligation<'tcx>>,()>
2934 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
2938 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2939 /// obligation is satisfied.
2940 fn match_poly_trait_ref(&mut self,
2941 obligation: &TraitObligation<'tcx>,
2942 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2945 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2949 self.infcx.at(&obligation.cause, obligation.param_env)
2950 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2951 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2955 ///////////////////////////////////////////////////////////////////////////
2958 fn match_fresh_trait_refs(&self,
2959 previous: &ty::PolyTraitRef<'tcx>,
2960 current: &ty::PolyTraitRef<'tcx>)
2963 let mut matcher = ty::_match::Match::new(self.tcx());
2964 matcher.relate(previous, current).is_ok()
2967 fn push_stack<'o,'s:'o>(&mut self,
2968 previous_stack: TraitObligationStackList<'s, 'tcx>,
2969 obligation: &'o TraitObligation<'tcx>)
2970 -> TraitObligationStack<'o, 'tcx>
2972 let fresh_trait_ref =
2973 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2975 TraitObligationStack {
2978 previous: previous_stack,
2982 fn closure_trait_ref_unnormalized(&mut self,
2983 obligation: &TraitObligation<'tcx>,
2984 closure_def_id: DefId,
2985 substs: ty::ClosureSubsts<'tcx>)
2986 -> ty::PolyTraitRef<'tcx>
2988 let closure_type = self.infcx.fn_sig(closure_def_id)
2989 .subst(self.tcx(), substs.substs);
2990 let ty::Binder((trait_ref, _)) =
2991 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2992 obligation.predicate.0.self_ty(), // (1)
2994 util::TupleArgumentsFlag::No);
2995 // (1) Feels icky to skip the binder here, but OTOH we know
2996 // that the self-type is an unboxed closure type and hence is
2997 // in fact unparameterized (or at least does not reference any
2998 // regions bound in the obligation). Still probably some
2999 // refactoring could make this nicer.
3001 ty::Binder(trait_ref)
3004 fn closure_trait_ref(&mut self,
3005 obligation: &TraitObligation<'tcx>,
3006 closure_def_id: DefId,
3007 substs: ty::ClosureSubsts<'tcx>)
3008 -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
3010 let trait_ref = self.closure_trait_ref_unnormalized(
3011 obligation, closure_def_id, substs);
3013 // A closure signature can contain associated types which
3014 // must be normalized.
3015 normalize_with_depth(self,
3016 obligation.param_env,
3017 obligation.cause.clone(),
3018 obligation.recursion_depth+1,
3022 /// Returns the obligations that are implied by instantiating an
3023 /// impl or trait. The obligations are substituted and fully
3024 /// normalized. This is used when confirming an impl or default
3026 fn impl_or_trait_obligations(&mut self,
3027 cause: ObligationCause<'tcx>,
3028 recursion_depth: usize,
3029 param_env: ty::ParamEnv<'tcx>,
3030 def_id: DefId, // of impl or trait
3031 substs: &Substs<'tcx>, // for impl or trait
3032 skol_map: infer::SkolemizationMap<'tcx>,
3033 snapshot: &infer::CombinedSnapshot)
3034 -> Vec<PredicateObligation<'tcx>>
3036 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3037 let tcx = self.tcx();
3039 // To allow for one-pass evaluation of the nested obligation,
3040 // each predicate must be preceded by the obligations required
3042 // for example, if we have:
3043 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3044 // the impl will have the following predicates:
3045 // <V as Iterator>::Item = U,
3046 // U: Iterator, U: Sized,
3047 // V: Iterator, V: Sized,
3048 // <U as Iterator>::Item: Copy
3049 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3050 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3051 // `$1: Copy`, so we must ensure the obligations are emitted in
3053 let predicates = tcx.predicates_of(def_id);
3054 assert_eq!(predicates.parent, None);
3055 let predicates = predicates.predicates.iter().flat_map(|predicate| {
3056 let predicate = normalize_with_depth(self, param_env, cause.clone(), recursion_depth,
3057 &predicate.subst(tcx, substs));
3058 predicate.obligations.into_iter().chain(
3060 cause: cause.clone(),
3063 predicate: predicate.value
3066 self.infcx().plug_leaks(skol_map, snapshot, predicates)
3070 impl<'tcx> TraitObligation<'tcx> {
3071 #[allow(unused_comparisons)]
3072 pub fn derived_cause(&self,
3073 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
3074 -> ObligationCause<'tcx>
3077 * Creates a cause for obligations that are derived from
3078 * `obligation` by a recursive search (e.g., for a builtin
3079 * bound, or eventually a `impl Foo for ..`). If `obligation`
3080 * is itself a derived obligation, this is just a clone, but
3081 * otherwise we create a "derived obligation" cause so as to
3082 * keep track of the original root obligation for error
3086 let obligation = self;
3088 // NOTE(flaper87): As of now, it keeps track of the whole error
3089 // chain. Ideally, we should have a way to configure this either
3090 // by using -Z verbose or just a CLI argument.
3091 if obligation.recursion_depth >= 0 {
3092 let derived_cause = DerivedObligationCause {
3093 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3094 parent_code: Rc::new(obligation.cause.code.clone())
3096 let derived_code = variant(derived_cause);
3097 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3099 obligation.cause.clone()
3104 impl<'tcx> SelectionCache<'tcx> {
3105 pub fn new() -> SelectionCache<'tcx> {
3107 hashmap: RefCell::new(FxHashMap())
3112 impl<'tcx> EvaluationCache<'tcx> {
3113 pub fn new() -> EvaluationCache<'tcx> {
3115 hashmap: RefCell::new(FxHashMap())
3120 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
3121 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
3122 TraitObligationStackList::with(self)
3125 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
3130 #[derive(Copy, Clone)]
3131 struct TraitObligationStackList<'o,'tcx:'o> {
3132 head: Option<&'o TraitObligationStack<'o,'tcx>>
3135 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
3136 fn empty() -> TraitObligationStackList<'o,'tcx> {
3137 TraitObligationStackList { head: None }
3140 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
3141 TraitObligationStackList { head: Some(r) }
3145 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
3146 type Item = &'o TraitObligationStack<'o,'tcx>;
3148 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3159 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3160 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3161 write!(f, "TraitObligationStack({:?})", self.obligation)
3166 pub struct WithDepNode<T> {
3167 dep_node: DepNodeIndex,
3171 impl<T: Clone> WithDepNode<T> {
3172 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3173 WithDepNode { dep_node, cached_value }
3176 pub fn get(&self, tcx: TyCtxt) -> T {
3177 tcx.dep_graph.read_index(self.dep_node);
3178 self.cached_value.clone()