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, ProjectionCacheKey};
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, VtableGenerator,
28 VtableFnPointer, VtableObject, VtableAutoImpl};
29 use super::{VtableImplData, VtableObjectData, VtableBuiltinData, VtableGeneratorData,
30 VtableClosureData, VtableAutoImplData, 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};
40 use ty::relate::TypeRelation;
41 use middle::lang_items;
43 use rustc_data_structures::bitvec::BitVector;
44 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>>,
94 intercrate_ambiguity_causes: Vec<IntercrateAmbiguityCause>,
98 pub enum IntercrateAmbiguityCause {
101 self_desc: Option<String>,
103 UpstreamCrateUpdate {
105 self_desc: Option<String>,
109 impl IntercrateAmbiguityCause {
110 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
111 /// See #23980 for details.
112 pub fn add_intercrate_ambiguity_hint<'a, 'tcx>(&self,
113 err: &mut ::errors::DiagnosticBuilder) {
115 &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
116 let self_desc = if let &Some(ref ty) = self_desc {
117 format!(" for type `{}`", ty)
118 } else { "".to_string() };
119 err.note(&format!("downstream crates may implement trait `{}`{}",
120 trait_desc, self_desc));
122 &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
123 let self_desc = if let &Some(ref ty) = self_desc {
124 format!(" for type `{}`", ty)
125 } else { "".to_string() };
126 err.note(&format!("upstream crates may add new impl of trait `{}`{} \
128 trait_desc, self_desc));
134 // A stack that walks back up the stack frame.
135 struct TraitObligationStack<'prev, 'tcx: 'prev> {
136 obligation: &'prev TraitObligation<'tcx>,
138 /// Trait ref from `obligation` but skolemized with the
139 /// selection-context's freshener. Used to check for recursion.
140 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
142 previous: TraitObligationStackList<'prev, 'tcx>,
146 pub struct SelectionCache<'tcx> {
147 hashmap: RefCell<FxHashMap<ty::TraitRef<'tcx>,
148 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>>,
151 /// The selection process begins by considering all impls, where
152 /// clauses, and so forth that might resolve an obligation. Sometimes
153 /// we'll be able to say definitively that (e.g.) an impl does not
154 /// apply to the obligation: perhaps it is defined for `usize` but the
155 /// obligation is for `int`. In that case, we drop the impl out of the
156 /// list. But the other cases are considered *candidates*.
158 /// For selection to succeed, there must be exactly one matching
159 /// candidate. If the obligation is fully known, this is guaranteed
160 /// by coherence. However, if the obligation contains type parameters
161 /// or variables, there may be multiple such impls.
163 /// It is not a real problem if multiple matching impls exist because
164 /// of type variables - it just means the obligation isn't sufficiently
165 /// elaborated. In that case we report an ambiguity, and the caller can
166 /// try again after more type information has been gathered or report a
167 /// "type annotations required" error.
169 /// However, with type parameters, this can be a real problem - type
170 /// parameters don't unify with regular types, but they *can* unify
171 /// with variables from blanket impls, and (unless we know its bounds
172 /// will always be satisfied) picking the blanket impl will be wrong
173 /// for at least *some* substitutions. To make this concrete, if we have
175 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
176 /// impl<T: fmt::Debug> AsDebug for T {
178 /// fn debug(self) -> fmt::Debug { self }
180 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
182 /// we can't just use the impl to resolve the <T as AsDebug> obligation
183 /// - a type from another crate (that doesn't implement fmt::Debug) could
184 /// implement AsDebug.
186 /// Because where-clauses match the type exactly, multiple clauses can
187 /// only match if there are unresolved variables, and we can mostly just
188 /// report this ambiguity in that case. This is still a problem - we can't
189 /// *do anything* with ambiguities that involve only regions. This is issue
192 /// If a single where-clause matches and there are no inference
193 /// variables left, then it definitely matches and we can just select
196 /// In fact, we even select the where-clause when the obligation contains
197 /// inference variables. The can lead to inference making "leaps of logic",
198 /// for example in this situation:
200 /// pub trait Foo<T> { fn foo(&self) -> T; }
201 /// impl<T> Foo<()> for T { fn foo(&self) { } }
202 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
204 /// pub fn foo<T>(t: T) where T: Foo<bool> {
205 /// println!("{:?}", <T as Foo<_>>::foo(&t));
207 /// fn main() { foo(false); }
209 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
210 /// impl and the where-clause. We select the where-clause and unify $0=bool,
211 /// so the program prints "false". However, if the where-clause is omitted,
212 /// the blanket impl is selected, we unify $0=(), and the program prints
215 /// Exactly the same issues apply to projection and object candidates, except
216 /// that we can have both a projection candidate and a where-clause candidate
217 /// for the same obligation. In that case either would do (except that
218 /// different "leaps of logic" would occur if inference variables are
219 /// present), and we just pick the where-clause. This is, for example,
220 /// required for associated types to work in default impls, as the bounds
221 /// are visible both as projection bounds and as where-clauses from the
222 /// parameter environment.
223 #[derive(PartialEq,Eq,Debug,Clone)]
224 enum SelectionCandidate<'tcx> {
225 BuiltinCandidate { has_nested: bool },
226 ParamCandidate(ty::PolyTraitRef<'tcx>),
227 ImplCandidate(DefId),
228 AutoImplCandidate(DefId),
230 /// This is a trait matching with a projected type as `Self`, and
231 /// we found an applicable bound in the trait definition.
234 /// Implementation of a `Fn`-family trait by one of the anonymous types
235 /// generated for a `||` expression.
238 /// Implementation of a `Generator` trait by one of the anonymous types
239 /// generated for a generator.
242 /// Implementation of a `Fn`-family trait by one of the anonymous
243 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
248 BuiltinObjectCandidate,
250 BuiltinUnsizeCandidate,
253 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
254 type Lifted = SelectionCandidate<'tcx>;
255 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
257 BuiltinCandidate { has_nested } => {
262 ImplCandidate(def_id) => ImplCandidate(def_id),
263 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
264 ProjectionCandidate => ProjectionCandidate,
265 FnPointerCandidate => FnPointerCandidate,
266 ObjectCandidate => ObjectCandidate,
267 BuiltinObjectCandidate => BuiltinObjectCandidate,
268 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
269 ClosureCandidate => ClosureCandidate,
270 GeneratorCandidate => GeneratorCandidate,
272 ParamCandidate(ref trait_ref) => {
273 return tcx.lift(trait_ref).map(ParamCandidate);
279 struct SelectionCandidateSet<'tcx> {
280 // a list of candidates that definitely apply to the current
281 // obligation (meaning: types unify).
282 vec: Vec<SelectionCandidate<'tcx>>,
284 // if this is true, then there were candidates that might or might
285 // not have applied, but we couldn't tell. This occurs when some
286 // of the input types are type variables, in which case there are
287 // various "builtin" rules that might or might not trigger.
291 #[derive(PartialEq,Eq,Debug,Clone)]
292 struct EvaluatedCandidate<'tcx> {
293 candidate: SelectionCandidate<'tcx>,
294 evaluation: EvaluationResult,
297 /// When does the builtin impl for `T: Trait` apply?
298 enum BuiltinImplConditions<'tcx> {
299 /// The impl is conditional on T1,T2,.. : Trait
300 Where(ty::Binder<Vec<Ty<'tcx>>>),
301 /// There is no built-in impl. There may be some other
302 /// candidate (a where-clause or user-defined impl).
304 /// There is *no* impl for this, builtin or not. Ignore
305 /// all where-clauses.
307 /// It is unknown whether there is an impl.
311 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
312 /// The result of trait evaluation. The order is important
313 /// here as the evaluation of a list is the maximum of the
316 /// The evaluation results are ordered:
317 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
318 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
319 /// - the "union" of evaluation results is equal to their maximum -
320 /// all the "potential success" candidates can potentially succeed,
321 /// so they are no-ops when unioned with a definite error, and within
322 /// the categories it's easy to see that the unions are correct.
323 enum EvaluationResult {
324 /// Evaluation successful
326 /// Evaluation is known to be ambiguous - it *might* hold for some
327 /// assignment of inference variables, but it might not.
329 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
330 /// know whether this obligation holds or not - it is the result we
331 /// would get with an empty stack, and therefore is cacheable.
333 /// Evaluation failed because of recursion involving inference
334 /// variables. We are somewhat imprecise there, so we don't actually
335 /// know the real result.
337 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
339 /// Evaluation failed because we encountered an obligation we are already
340 /// trying to prove on this branch.
342 /// We know this branch can't be a part of a minimal proof-tree for
343 /// the "root" of our cycle, because then we could cut out the recursion
344 /// and maintain a valid proof tree. However, this does not mean
345 /// that all the obligations on this branch do not hold - it's possible
346 /// that we entered this branch "speculatively", and that there
347 /// might be some other way to prove this obligation that does not
348 /// go through this cycle - so we can't cache this as a failure.
350 /// For example, suppose we have this:
352 /// ```rust,ignore (pseudo-Rust)
353 /// pub trait Trait { fn xyz(); }
354 /// // This impl is "useless", but we can still have
355 /// // an `impl Trait for SomeUnsizedType` somewhere.
356 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
358 /// pub fn foo<T: Trait + ?Sized>() {
359 /// <T as Trait>::xyz();
363 /// When checking `foo`, we have to prove `T: Trait`. This basically
364 /// translates into this:
366 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
368 /// When we try to prove it, we first go the first option, which
369 /// recurses. This shows us that the impl is "useless" - it won't
370 /// tell us that `T: Trait` unless it already implemented `Trait`
371 /// by some other means. However, that does not prevent `T: Trait`
372 /// does not hold, because of the bound (which can indeed be satisfied
373 /// by `SomeUnsizedType` from another crate).
375 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
376 /// ought to convert it to an `EvaluatedToErr`, because we know
377 /// there definitely isn't a proof tree for that obligation. Not
378 /// doing so is still sound - there isn't any proof tree, so the
379 /// branch still can't be a part of a minimal one - but does not
380 /// re-enable caching.
382 /// Evaluation failed
386 impl EvaluationResult {
387 fn may_apply(self) -> bool {
391 EvaluatedToUnknown => true,
394 EvaluatedToRecur => false
398 fn is_stack_dependent(self) -> bool {
401 EvaluatedToRecur => true,
405 EvaluatedToErr => false,
411 pub struct EvaluationCache<'tcx> {
412 hashmap: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>
415 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
416 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
419 freshener: infcx.freshener(),
421 inferred_obligations: SnapshotVec::new(),
422 intercrate_ambiguity_causes: Vec::new(),
426 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
429 freshener: infcx.freshener(),
431 inferred_obligations: SnapshotVec::new(),
432 intercrate_ambiguity_causes: Vec::new(),
436 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
440 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
444 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
448 pub fn intercrate_ambiguity_causes(&self) -> &[IntercrateAmbiguityCause] {
449 &self.intercrate_ambiguity_causes
452 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
454 fn in_snapshot<R, F>(&mut self, f: F) -> R
455 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
457 // The irrefutable nature of the operation means we don't need to snapshot the
458 // inferred_obligations vector.
459 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
462 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
464 fn probe<R, F>(&mut self, f: F) -> R
465 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
467 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
468 let result = self.infcx.probe(|snapshot| f(self, snapshot));
469 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
473 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
474 /// the transaction fails and s.t. old obligations are retained.
475 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
476 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
478 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
479 match self.infcx.commit_if_ok(|snapshot| f(self, snapshot)) {
481 self.inferred_obligations.commit(inferred_obligations_snapshot);
485 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
492 ///////////////////////////////////////////////////////////////////////////
495 // The selection phase tries to identify *how* an obligation will
496 // be resolved. For example, it will identify which impl or
497 // parameter bound is to be used. The process can be inconclusive
498 // if the self type in the obligation is not fully inferred. Selection
499 // can result in an error in one of two ways:
501 // 1. If no applicable impl or parameter bound can be found.
502 // 2. If the output type parameters in the obligation do not match
503 // those specified by the impl/bound. For example, if the obligation
504 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
505 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
507 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
508 /// type environment by performing unification.
509 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
510 -> SelectionResult<'tcx, Selection<'tcx>> {
511 debug!("select({:?})", obligation);
512 assert!(!obligation.predicate.has_escaping_regions());
514 let tcx = self.tcx();
516 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
517 let ret = match self.candidate_from_obligation(&stack)? {
520 let mut candidate = self.confirm_candidate(obligation, candidate)?;
521 let inferred_obligations = (*self.inferred_obligations).into_iter().cloned();
522 candidate.nested_obligations_mut().extend(inferred_obligations);
527 // Test whether this is a `()` which was produced by defaulting a
528 // diverging type variable with `!` disabled. If so, we may need
529 // to raise a warning.
530 if obligation.predicate.skip_binder().self_ty().is_defaulted_unit() {
531 let mut raise_warning = true;
532 // Don't raise a warning if the trait is implemented for ! and only
533 // permits a trivial implementation for !. This stops us warning
534 // about (for example) `(): Clone` becoming `!: Clone` because such
535 // a switch can't cause code to stop compiling or execute
537 let mut never_obligation = obligation.clone();
538 let def_id = never_obligation.predicate.skip_binder().trait_ref.def_id;
539 never_obligation.predicate = never_obligation.predicate.map_bound(|mut trait_pred| {
540 // Swap out () with ! so we can check if the trait is impld for !
542 let trait_ref = &mut trait_pred.trait_ref;
543 let unit_substs = trait_ref.substs;
544 let mut never_substs = Vec::with_capacity(unit_substs.len());
545 never_substs.push(From::from(tcx.types.never));
546 never_substs.extend(&unit_substs[1..]);
547 trait_ref.substs = tcx.intern_substs(&never_substs);
551 if let Ok(Some(..)) = self.select(&never_obligation) {
552 if !tcx.trait_relevant_for_never(def_id) {
553 // The trait is also implemented for ! and the resulting
554 // implementation cannot actually be invoked in any way.
555 raise_warning = false;
560 tcx.lint_node(lint::builtin::RESOLVE_TRAIT_ON_DEFAULTED_UNIT,
561 obligation.cause.body_id,
562 obligation.cause.span,
563 &format!("code relies on type inference rules which are likely \
570 ///////////////////////////////////////////////////////////////////////////
573 // Tests whether an obligation can be selected or whether an impl
574 // can be applied to particular types. It skips the "confirmation"
575 // step and hence completely ignores output type parameters.
577 // The result is "true" if the obligation *may* hold and "false" if
578 // we can be sure it does not.
580 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
581 pub fn evaluate_obligation(&mut self,
582 obligation: &PredicateObligation<'tcx>)
585 debug!("evaluate_obligation({:?})",
588 self.probe(|this, _| {
589 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
594 /// Evaluates whether the obligation `obligation` can be satisfied,
595 /// and returns `false` if not certain. However, this is not entirely
596 /// accurate if inference variables are involved.
597 pub fn evaluate_obligation_conservatively(&mut self,
598 obligation: &PredicateObligation<'tcx>)
601 debug!("evaluate_obligation_conservatively({:?})",
604 self.probe(|this, _| {
605 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
610 /// Evaluates the predicates in `predicates` recursively. Note that
611 /// this applies projections in the predicates, and therefore
612 /// is run within an inference probe.
613 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
614 stack: TraitObligationStackList<'o, 'tcx>,
617 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
619 let mut result = EvaluatedToOk;
620 for obligation in predicates {
621 let eval = self.evaluate_predicate_recursively(stack, obligation);
622 debug!("evaluate_predicate_recursively({:?}) = {:?}",
624 if let EvaluatedToErr = eval {
625 // fast-path - EvaluatedToErr is the top of the lattice,
626 // so we don't need to look on the other predicates.
627 return EvaluatedToErr;
629 result = cmp::max(result, eval);
635 fn evaluate_predicate_recursively<'o>(&mut self,
636 previous_stack: TraitObligationStackList<'o, 'tcx>,
637 obligation: &PredicateObligation<'tcx>)
640 debug!("evaluate_predicate_recursively({:?})",
643 match obligation.predicate {
644 ty::Predicate::Trait(ref t) => {
645 assert!(!t.has_escaping_regions());
646 let obligation = obligation.with(t.clone());
647 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
650 ty::Predicate::Equate(ref p) => {
651 // does this code ever run?
652 match self.infcx.equality_predicate(&obligation.cause, obligation.param_env, p) {
653 Ok(InferOk { obligations, .. }) => {
654 self.inferred_obligations.extend(obligations);
657 Err(_) => EvaluatedToErr
661 ty::Predicate::Subtype(ref p) => {
662 // does this code ever run?
663 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
664 Some(Ok(InferOk { obligations, .. })) => {
665 self.inferred_obligations.extend(obligations);
668 Some(Err(_)) => EvaluatedToErr,
669 None => EvaluatedToAmbig,
673 ty::Predicate::WellFormed(ty) => {
674 match ty::wf::obligations(self.infcx,
675 obligation.param_env,
676 obligation.cause.body_id,
677 ty, obligation.cause.span) {
679 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
685 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
686 // we do not consider region relationships when
687 // evaluating trait matches
691 ty::Predicate::ObjectSafe(trait_def_id) => {
692 if self.tcx().is_object_safe(trait_def_id) {
699 ty::Predicate::Projection(ref data) => {
700 let project_obligation = obligation.with(data.clone());
701 match project::poly_project_and_unify_type(self, &project_obligation) {
702 Ok(Some(subobligations)) => {
703 let result = self.evaluate_predicates_recursively(previous_stack,
704 subobligations.iter());
706 ProjectionCacheKey::from_poly_projection_predicate(self, data)
708 self.infcx.projection_cache.borrow_mut().complete(key);
721 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
722 match self.infcx.closure_kind(closure_def_id, closure_substs) {
723 Some(closure_kind) => {
724 if closure_kind.extends(kind) {
736 ty::Predicate::ConstEvaluatable(def_id, substs) => {
737 match self.tcx().lift_to_global(&(obligation.param_env, substs)) {
738 Some((param_env, substs)) => {
739 match self.tcx().const_eval(param_env.and((def_id, substs))) {
740 Ok(_) => EvaluatedToOk,
741 Err(_) => EvaluatedToErr
745 // Inference variables still left in param_env or substs.
753 fn evaluate_trait_predicate_recursively<'o>(&mut self,
754 previous_stack: TraitObligationStackList<'o, 'tcx>,
755 mut obligation: TraitObligation<'tcx>)
758 debug!("evaluate_trait_predicate_recursively({:?})",
761 if !self.intercrate && obligation.is_global() {
762 // If a param env is consistent, global obligations do not depend on its particular
763 // value in order to work, so we can clear out the param env and get better
764 // caching. (If the current param env is inconsistent, we don't care what happens).
765 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
766 obligation.param_env = ty::ParamEnv::empty(obligation.param_env.reveal);
769 let stack = self.push_stack(previous_stack, &obligation);
770 let fresh_trait_ref = stack.fresh_trait_ref;
771 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
772 debug!("CACHE HIT: EVAL({:?})={:?}",
778 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
780 debug!("CACHE MISS: EVAL({:?})={:?}",
783 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
788 fn evaluate_stack<'o>(&mut self,
789 stack: &TraitObligationStack<'o, 'tcx>)
792 // In intercrate mode, whenever any of the types are unbound,
793 // there can always be an impl. Even if there are no impls in
794 // this crate, perhaps the type would be unified with
795 // something from another crate that does provide an impl.
797 // In intra mode, we must still be conservative. The reason is
798 // that we want to avoid cycles. Imagine an impl like:
800 // impl<T:Eq> Eq for Vec<T>
802 // and a trait reference like `$0 : Eq` where `$0` is an
803 // unbound variable. When we evaluate this trait-reference, we
804 // will unify `$0` with `Vec<$1>` (for some fresh variable
805 // `$1`), on the condition that `$1 : Eq`. We will then wind
806 // up with many candidates (since that are other `Eq` impls
807 // that apply) and try to winnow things down. This results in
808 // a recursive evaluation that `$1 : Eq` -- as you can
809 // imagine, this is just where we started. To avoid that, we
810 // check for unbound variables and return an ambiguous (hence possible)
811 // match if we've seen this trait before.
813 // This suffices to allow chains like `FnMut` implemented in
814 // terms of `Fn` etc, but we could probably make this more
816 let unbound_input_types = stack.fresh_trait_ref.input_types().any(|ty| ty.is_fresh());
817 if unbound_input_types && self.intercrate {
818 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
819 stack.fresh_trait_ref);
820 // Heuristics: show the diagnostics when there are no candidates in crate.
821 if let Ok(candidate_set) = self.assemble_candidates(stack) {
822 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
823 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
824 let self_ty = trait_ref.self_ty();
825 let cause = IntercrateAmbiguityCause::DownstreamCrate {
826 trait_desc: trait_ref.to_string(),
827 self_desc: if self_ty.has_concrete_skeleton() {
828 Some(self_ty.to_string())
833 self.intercrate_ambiguity_causes.push(cause);
836 return EvaluatedToAmbig;
838 if unbound_input_types &&
839 stack.iter().skip(1).any(
840 |prev| stack.obligation.param_env == prev.obligation.param_env &&
841 self.match_fresh_trait_refs(&stack.fresh_trait_ref,
842 &prev.fresh_trait_ref))
844 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
845 stack.fresh_trait_ref);
846 return EvaluatedToUnknown;
849 // If there is any previous entry on the stack that precisely
850 // matches this obligation, then we can assume that the
851 // obligation is satisfied for now (still all other conditions
852 // must be met of course). One obvious case this comes up is
853 // marker traits like `Send`. Think of a linked list:
855 // struct List<T> { data: T, next: Option<Box<List<T>>> {
857 // `Box<List<T>>` will be `Send` if `T` is `Send` and
858 // `Option<Box<List<T>>>` is `Send`, and in turn
859 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
862 // Note that we do this comparison using the `fresh_trait_ref`
863 // fields. Because these have all been skolemized using
864 // `self.freshener`, we can be sure that (a) this will not
865 // affect the inferencer state and (b) that if we see two
866 // skolemized types with the same index, they refer to the
867 // same unbound type variable.
868 if let Some(rec_index) =
870 .skip(1) // skip top-most frame
871 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
872 stack.fresh_trait_ref == prev.fresh_trait_ref)
874 debug!("evaluate_stack({:?}) --> recursive",
875 stack.fresh_trait_ref);
876 let cycle = stack.iter().skip(1).take(rec_index+1);
877 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
878 if self.coinductive_match(cycle) {
879 debug!("evaluate_stack({:?}) --> recursive, coinductive",
880 stack.fresh_trait_ref);
881 return EvaluatedToOk;
883 debug!("evaluate_stack({:?}) --> recursive, inductive",
884 stack.fresh_trait_ref);
885 return EvaluatedToRecur;
889 match self.candidate_from_obligation(stack) {
890 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
891 Ok(None) => EvaluatedToAmbig,
892 Err(..) => EvaluatedToErr
896 /// For defaulted traits, we use a co-inductive strategy to solve, so
897 /// that recursion is ok. This routine returns true if the top of the
898 /// stack (`cycle[0]`):
899 /// - is a defaulted trait, and
900 /// - it also appears in the backtrace at some position `X`; and,
901 /// - all the predicates at positions `X..` between `X` an the top are
902 /// also defaulted traits.
903 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
904 where I: Iterator<Item=ty::Predicate<'tcx>>
906 let mut cycle = cycle;
907 cycle.all(|predicate| self.coinductive_predicate(predicate))
910 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
911 let result = match predicate {
912 ty::Predicate::Trait(ref data) => {
913 self.tcx().trait_is_auto(data.def_id())
919 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
923 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
924 /// obligations are met. Returns true if `candidate` remains viable after this further
926 fn evaluate_candidate<'o>(&mut self,
927 stack: &TraitObligationStack<'o, 'tcx>,
928 candidate: &SelectionCandidate<'tcx>)
931 debug!("evaluate_candidate: depth={} candidate={:?}",
932 stack.obligation.recursion_depth, candidate);
933 let result = self.probe(|this, _| {
934 let candidate = (*candidate).clone();
935 match this.confirm_candidate(stack.obligation, candidate) {
937 this.evaluate_predicates_recursively(
939 selection.nested_obligations().iter())
941 Err(..) => EvaluatedToErr
944 debug!("evaluate_candidate: depth={} result={:?}",
945 stack.obligation.recursion_depth, result);
949 fn check_evaluation_cache(&self,
950 param_env: ty::ParamEnv<'tcx>,
951 trait_ref: ty::PolyTraitRef<'tcx>)
952 -> Option<EvaluationResult>
954 let tcx = self.tcx();
955 if self.can_use_global_caches(param_env) {
956 let cache = tcx.evaluation_cache.hashmap.borrow();
957 if let Some(cached) = cache.get(&trait_ref) {
958 return Some(cached.get(tcx));
961 self.infcx.evaluation_cache.hashmap
967 fn insert_evaluation_cache(&mut self,
968 param_env: ty::ParamEnv<'tcx>,
969 trait_ref: ty::PolyTraitRef<'tcx>,
970 dep_node: DepNodeIndex,
971 result: EvaluationResult)
973 // Avoid caching results that depend on more than just the trait-ref
974 // - the stack can create recursion.
975 if result.is_stack_dependent() {
979 if self.can_use_global_caches(param_env) {
980 let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
981 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
982 cache.insert(trait_ref, WithDepNode::new(dep_node, result));
987 self.infcx.evaluation_cache.hashmap
989 .insert(trait_ref, WithDepNode::new(dep_node, result));
992 ///////////////////////////////////////////////////////////////////////////
993 // CANDIDATE ASSEMBLY
995 // The selection process begins by examining all in-scope impls,
996 // caller obligations, and so forth and assembling a list of
997 // candidates. See `README.md` and the `Candidate` type for more
1000 fn candidate_from_obligation<'o>(&mut self,
1001 stack: &TraitObligationStack<'o, 'tcx>)
1002 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1004 // Watch out for overflow. This intentionally bypasses (and does
1005 // not update) the cache.
1006 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
1007 if stack.obligation.recursion_depth >= recursion_limit {
1008 self.infcx().report_overflow_error(&stack.obligation, true);
1011 // Check the cache. Note that we skolemize the trait-ref
1012 // separately rather than using `stack.fresh_trait_ref` -- this
1013 // is because we want the unbound variables to be replaced
1014 // with fresh skolemized types starting from index 0.
1015 let cache_fresh_trait_pred =
1016 self.infcx.freshen(stack.obligation.predicate.clone());
1017 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1018 cache_fresh_trait_pred,
1020 assert!(!stack.obligation.predicate.has_escaping_regions());
1022 if let Some(c) = self.check_candidate_cache(stack.obligation.param_env,
1023 &cache_fresh_trait_pred) {
1024 debug!("CACHE HIT: SELECT({:?})={:?}",
1025 cache_fresh_trait_pred,
1030 // If no match, compute result and insert into cache.
1031 let (candidate, dep_node) = self.in_task(|this| {
1032 this.candidate_from_obligation_no_cache(stack)
1035 debug!("CACHE MISS: SELECT({:?})={:?}",
1036 cache_fresh_trait_pred, candidate);
1037 self.insert_candidate_cache(stack.obligation.param_env,
1038 cache_fresh_trait_pred,
1044 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1045 where OP: FnOnce(&mut Self) -> R
1047 let (result, dep_node) = self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || {
1050 self.tcx().dep_graph.read_index(dep_node);
1054 // Treat negative impls as unimplemented
1055 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
1056 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1057 if let ImplCandidate(def_id) = candidate {
1058 if self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative {
1059 return Err(Unimplemented)
1065 fn candidate_from_obligation_no_cache<'o>(&mut self,
1066 stack: &TraitObligationStack<'o, 'tcx>)
1067 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1069 if stack.obligation.predicate.references_error() {
1070 // If we encounter a `TyError`, we generally prefer the
1071 // most "optimistic" result in response -- that is, the
1072 // one least likely to report downstream errors. But
1073 // because this routine is shared by coherence and by
1074 // trait selection, there isn't an obvious "right" choice
1075 // here in that respect, so we opt to just return
1076 // ambiguity and let the upstream clients sort it out.
1080 if !self.is_knowable(stack) {
1081 debug!("coherence stage: not knowable");
1082 // Heuristics: show the diagnostics when there are no candidates in crate.
1083 let candidate_set = self.assemble_candidates(stack)?;
1084 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
1085 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1086 let self_ty = trait_ref.self_ty();
1087 let trait_desc = trait_ref.to_string();
1088 let self_desc = if self_ty.has_concrete_skeleton() {
1089 Some(self_ty.to_string())
1093 let cause = if !coherence::trait_ref_is_local_or_fundamental(self.tcx(),
1095 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1097 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1099 self.intercrate_ambiguity_causes.push(cause);
1104 let candidate_set = self.assemble_candidates(stack)?;
1106 if candidate_set.ambiguous {
1107 debug!("candidate set contains ambig");
1111 let mut candidates = candidate_set.vec;
1113 debug!("assembled {} candidates for {:?}: {:?}",
1118 // At this point, we know that each of the entries in the
1119 // candidate set is *individually* applicable. Now we have to
1120 // figure out if they contain mutual incompatibilities. This
1121 // frequently arises if we have an unconstrained input type --
1122 // for example, we are looking for $0:Eq where $0 is some
1123 // unconstrained type variable. In that case, we'll get a
1124 // candidate which assumes $0 == int, one that assumes $0 ==
1125 // usize, etc. This spells an ambiguity.
1127 // If there is more than one candidate, first winnow them down
1128 // by considering extra conditions (nested obligations and so
1129 // forth). We don't winnow if there is exactly one
1130 // candidate. This is a relatively minor distinction but it
1131 // can lead to better inference and error-reporting. An
1132 // example would be if there was an impl:
1134 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1136 // and we were to see some code `foo.push_clone()` where `boo`
1137 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1138 // we were to winnow, we'd wind up with zero candidates.
1139 // Instead, we select the right impl now but report `Bar does
1140 // not implement Clone`.
1141 if candidates.len() == 1 {
1142 return self.filter_negative_impls(candidates.pop().unwrap());
1145 // Winnow, but record the exact outcome of evaluation, which
1146 // is needed for specialization.
1147 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
1148 let eval = self.evaluate_candidate(stack, &c);
1149 if eval.may_apply() {
1150 Some(EvaluatedCandidate {
1159 // If there are STILL multiple candidate, we can further
1160 // reduce the list by dropping duplicates -- including
1161 // resolving specializations.
1162 if candidates.len() > 1 {
1164 while i < candidates.len() {
1166 (0..candidates.len())
1167 .filter(|&j| i != j)
1168 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
1171 debug!("Dropping candidate #{}/{}: {:?}",
1172 i, candidates.len(), candidates[i]);
1173 candidates.swap_remove(i);
1175 debug!("Retaining candidate #{}/{}: {:?}",
1176 i, candidates.len(), candidates[i]);
1179 // If there are *STILL* multiple candidates, give up
1180 // and report ambiguity.
1182 debug!("multiple matches, ambig");
1189 // If there are *NO* candidates, then there are no impls --
1190 // that we know of, anyway. Note that in the case where there
1191 // are unbound type variables within the obligation, it might
1192 // be the case that you could still satisfy the obligation
1193 // from another crate by instantiating the type variables with
1194 // a type from another crate that does have an impl. This case
1195 // is checked for in `evaluate_stack` (and hence users
1196 // who might care about this case, like coherence, should use
1198 if candidates.is_empty() {
1199 return Err(Unimplemented);
1202 // Just one candidate left.
1203 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1206 fn is_knowable<'o>(&mut self,
1207 stack: &TraitObligationStack<'o, 'tcx>)
1210 debug!("is_knowable(intercrate={})", self.intercrate);
1212 if !self.intercrate {
1216 let obligation = &stack.obligation;
1217 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1219 // ok to skip binder because of the nature of the
1220 // trait-ref-is-knowable check, which does not care about
1222 let trait_ref = predicate.skip_binder().trait_ref;
1224 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1227 /// Returns true if the global caches can be used.
1228 /// Do note that if the type itself is not in the
1229 /// global tcx, the local caches will be used.
1230 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1231 // If there are any where-clauses in scope, then we always use
1232 // a cache local to this particular scope. Otherwise, we
1233 // switch to a global cache. We used to try and draw
1234 // finer-grained distinctions, but that led to a serious of
1235 // annoying and weird bugs like #22019 and #18290. This simple
1236 // rule seems to be pretty clearly safe and also still retains
1237 // a very high hit rate (~95% when compiling rustc).
1238 if !param_env.caller_bounds.is_empty() {
1242 // Avoid using the master cache during coherence and just rely
1243 // on the local cache. This effectively disables caching
1244 // during coherence. It is really just a simplification to
1245 // avoid us having to fear that coherence results "pollute"
1246 // the master cache. Since coherence executes pretty quickly,
1247 // it's not worth going to more trouble to increase the
1248 // hit-rate I don't think.
1249 if self.intercrate {
1253 // Otherwise, we can use the global cache.
1257 fn check_candidate_cache(&mut self,
1258 param_env: ty::ParamEnv<'tcx>,
1259 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1260 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1262 let tcx = self.tcx();
1263 let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1264 if self.can_use_global_caches(param_env) {
1265 let cache = tcx.selection_cache.hashmap.borrow();
1266 if let Some(cached) = cache.get(&trait_ref) {
1267 return Some(cached.get(tcx));
1270 self.infcx.selection_cache.hashmap
1273 .map(|v| v.get(tcx))
1276 fn insert_candidate_cache(&mut self,
1277 param_env: ty::ParamEnv<'tcx>,
1278 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1279 dep_node: DepNodeIndex,
1280 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1282 let tcx = self.tcx();
1283 let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1284 if self.can_use_global_caches(param_env) {
1285 let mut cache = tcx.selection_cache.hashmap.borrow_mut();
1286 if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1287 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1288 cache.insert(trait_ref, WithDepNode::new(dep_node, candidate));
1294 self.infcx.selection_cache.hashmap
1296 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1299 fn assemble_candidates<'o>(&mut self,
1300 stack: &TraitObligationStack<'o, 'tcx>)
1301 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1303 let TraitObligationStack { obligation, .. } = *stack;
1304 let ref obligation = Obligation {
1305 param_env: obligation.param_env,
1306 cause: obligation.cause.clone(),
1307 recursion_depth: obligation.recursion_depth,
1308 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1311 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1312 // Self is a type variable (e.g. `_: AsRef<str>`).
1314 // This is somewhat problematic, as the current scheme can't really
1315 // handle it turning to be a projection. This does end up as truly
1316 // ambiguous in most cases anyway.
1318 // Take the fast path out - this also improves
1319 // performance by preventing assemble_candidates_from_impls from
1320 // matching every impl for this trait.
1321 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1324 let mut candidates = SelectionCandidateSet {
1329 // Other bounds. Consider both in-scope bounds from fn decl
1330 // and applicable impls. There is a certain set of precedence rules here.
1332 let def_id = obligation.predicate.def_id();
1333 let lang_items = self.tcx().lang_items();
1334 if lang_items.copy_trait() == Some(def_id) {
1335 debug!("obligation self ty is {:?}",
1336 obligation.predicate.0.self_ty());
1338 // User-defined copy impls are permitted, but only for
1339 // structs and enums.
1340 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1342 // For other types, we'll use the builtin rules.
1343 let copy_conditions = self.copy_clone_conditions(obligation);
1344 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1345 } else if lang_items.sized_trait() == Some(def_id) {
1346 // Sized is never implementable by end-users, it is
1347 // always automatically computed.
1348 let sized_conditions = self.sized_conditions(obligation);
1349 self.assemble_builtin_bound_candidates(sized_conditions,
1351 } else if lang_items.unsize_trait() == Some(def_id) {
1352 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1354 if lang_items.clone_trait() == Some(def_id) {
1355 // Same builtin conditions as `Copy`, i.e. every type which has builtin support
1356 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1357 // types have builtin support for `Clone`.
1358 let clone_conditions = self.copy_clone_conditions(obligation);
1359 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1362 self.assemble_generator_candidates(obligation, &mut candidates)?;
1363 self.assemble_closure_candidates(obligation, &mut candidates)?;
1364 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1365 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1366 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1369 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1370 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1371 // Auto implementations have lower priority, so we only
1372 // consider triggering a default if there is no other impl that can apply.
1373 if candidates.vec.is_empty() {
1374 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1376 debug!("candidate list size: {}", candidates.vec.len());
1380 fn assemble_candidates_from_projected_tys(&mut self,
1381 obligation: &TraitObligation<'tcx>,
1382 candidates: &mut SelectionCandidateSet<'tcx>)
1384 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1386 // before we go into the whole skolemization thing, just
1387 // quickly check if the self-type is a projection at all.
1388 match obligation.predicate.0.trait_ref.self_ty().sty {
1389 ty::TyProjection(_) | ty::TyAnon(..) => {}
1390 ty::TyInfer(ty::TyVar(_)) => {
1391 span_bug!(obligation.cause.span,
1392 "Self=_ should have been handled by assemble_candidates");
1397 let result = self.probe(|this, snapshot| {
1398 this.match_projection_obligation_against_definition_bounds(obligation,
1403 candidates.vec.push(ProjectionCandidate);
1407 fn match_projection_obligation_against_definition_bounds(
1409 obligation: &TraitObligation<'tcx>,
1410 snapshot: &infer::CombinedSnapshot)
1413 let poly_trait_predicate =
1414 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1415 let (skol_trait_predicate, skol_map) =
1416 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1417 debug!("match_projection_obligation_against_definition_bounds: \
1418 skol_trait_predicate={:?} skol_map={:?}",
1419 skol_trait_predicate,
1422 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1423 ty::TyProjection(ref data) =>
1424 (data.trait_ref(self.tcx()).def_id, data.substs),
1425 ty::TyAnon(def_id, substs) => (def_id, substs),
1428 obligation.cause.span,
1429 "match_projection_obligation_against_definition_bounds() called \
1430 but self-ty not a projection: {:?}",
1431 skol_trait_predicate.trait_ref.self_ty());
1434 debug!("match_projection_obligation_against_definition_bounds: \
1435 def_id={:?}, substs={:?}",
1438 let predicates_of = self.tcx().predicates_of(def_id);
1439 let bounds = predicates_of.instantiate(self.tcx(), substs);
1440 debug!("match_projection_obligation_against_definition_bounds: \
1444 let matching_bound =
1445 util::elaborate_predicates(self.tcx(), bounds.predicates)
1449 |this, _| this.match_projection(obligation,
1451 skol_trait_predicate.trait_ref.clone(),
1455 debug!("match_projection_obligation_against_definition_bounds: \
1456 matching_bound={:?}",
1458 match matching_bound {
1461 // Repeat the successful match, if any, this time outside of a probe.
1462 let result = self.match_projection(obligation,
1464 skol_trait_predicate.trait_ref.clone(),
1468 self.infcx.pop_skolemized(skol_map, snapshot);
1476 fn match_projection(&mut self,
1477 obligation: &TraitObligation<'tcx>,
1478 trait_bound: ty::PolyTraitRef<'tcx>,
1479 skol_trait_ref: ty::TraitRef<'tcx>,
1480 skol_map: &infer::SkolemizationMap<'tcx>,
1481 snapshot: &infer::CombinedSnapshot)
1484 assert!(!skol_trait_ref.has_escaping_regions());
1485 match self.infcx.at(&obligation.cause, obligation.param_env)
1486 .sup(ty::Binder(skol_trait_ref), trait_bound) {
1487 Ok(InferOk { obligations, .. }) => {
1488 self.inferred_obligations.extend(obligations);
1490 Err(_) => { return false; }
1493 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1496 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1497 /// supplied to find out whether it is listed among them.
1499 /// Never affects inference environment.
1500 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1501 stack: &TraitObligationStack<'o, 'tcx>,
1502 candidates: &mut SelectionCandidateSet<'tcx>)
1503 -> Result<(),SelectionError<'tcx>>
1505 debug!("assemble_candidates_from_caller_bounds({:?})",
1509 stack.obligation.param_env.caller_bounds
1511 .filter_map(|o| o.to_opt_poly_trait_ref());
1513 // micro-optimization: filter out predicates relating to different
1515 let matching_bounds =
1516 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1518 let matching_bounds =
1519 matching_bounds.filter(
1520 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1522 let param_candidates =
1523 matching_bounds.map(|bound| ParamCandidate(bound));
1525 candidates.vec.extend(param_candidates);
1530 fn evaluate_where_clause<'o>(&mut self,
1531 stack: &TraitObligationStack<'o, 'tcx>,
1532 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1535 self.probe(move |this, _| {
1536 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1537 Ok(obligations) => {
1538 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1540 Err(()) => EvaluatedToErr
1545 fn assemble_generator_candidates(&mut self,
1546 obligation: &TraitObligation<'tcx>,
1547 candidates: &mut SelectionCandidateSet<'tcx>)
1548 -> Result<(),SelectionError<'tcx>>
1550 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1554 // ok to skip binder because the substs on generator types never
1555 // touch bound regions, they just capture the in-scope
1556 // type/region parameters
1557 let self_ty = *obligation.self_ty().skip_binder();
1559 ty::TyGenerator(..) => {
1560 debug!("assemble_generator_candidates: self_ty={:?} obligation={:?}",
1564 candidates.vec.push(GeneratorCandidate);
1567 ty::TyInfer(ty::TyVar(_)) => {
1568 debug!("assemble_generator_candidates: ambiguous self-type");
1569 candidates.ambiguous = true;
1572 _ => { return Ok(()); }
1576 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1577 /// FnMut<..>` where `X` is a closure type.
1579 /// Note: the type parameters on a closure candidate are modeled as *output* type
1580 /// parameters and hence do not affect whether this trait is a match or not. They will be
1581 /// unified during the confirmation step.
1582 fn assemble_closure_candidates(&mut self,
1583 obligation: &TraitObligation<'tcx>,
1584 candidates: &mut SelectionCandidateSet<'tcx>)
1585 -> Result<(),SelectionError<'tcx>>
1587 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.0.def_id()) {
1589 None => { return Ok(()); }
1592 // ok to skip binder because the substs on closure types never
1593 // touch bound regions, they just capture the in-scope
1594 // type/region parameters
1595 match obligation.self_ty().skip_binder().sty {
1596 ty::TyClosure(closure_def_id, closure_substs) => {
1597 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}",
1599 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1600 Some(closure_kind) => {
1601 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1602 if closure_kind.extends(kind) {
1603 candidates.vec.push(ClosureCandidate);
1607 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1608 candidates.vec.push(ClosureCandidate);
1613 ty::TyInfer(ty::TyVar(_)) => {
1614 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1615 candidates.ambiguous = true;
1618 _ => { return Ok(()); }
1622 /// Implement one of the `Fn()` family for a fn pointer.
1623 fn assemble_fn_pointer_candidates(&mut self,
1624 obligation: &TraitObligation<'tcx>,
1625 candidates: &mut SelectionCandidateSet<'tcx>)
1626 -> Result<(),SelectionError<'tcx>>
1628 // We provide impl of all fn traits for fn pointers.
1629 if self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()).is_none() {
1633 // ok to skip binder because what we are inspecting doesn't involve bound regions
1634 let self_ty = *obligation.self_ty().skip_binder();
1636 ty::TyInfer(ty::TyVar(_)) => {
1637 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1638 candidates.ambiguous = true; // could wind up being a fn() type
1641 // provide an impl, but only for suitable `fn` pointers
1642 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
1643 if let ty::Binder(ty::FnSig {
1644 unsafety: hir::Unsafety::Normal,
1648 }) = self_ty.fn_sig(self.tcx()) {
1649 candidates.vec.push(FnPointerCandidate);
1659 /// Search for impls that might apply to `obligation`.
1660 fn assemble_candidates_from_impls(&mut self,
1661 obligation: &TraitObligation<'tcx>,
1662 candidates: &mut SelectionCandidateSet<'tcx>)
1663 -> Result<(), SelectionError<'tcx>>
1665 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1667 self.tcx().for_each_relevant_impl(
1668 obligation.predicate.def_id(),
1669 obligation.predicate.0.trait_ref.self_ty(),
1671 self.probe(|this, snapshot| { /* [1] */
1672 match this.match_impl(impl_def_id, obligation, snapshot) {
1674 candidates.vec.push(ImplCandidate(impl_def_id));
1676 // NB: we can safely drop the skol map
1677 // since we are in a probe [1]
1678 mem::drop(skol_map);
1689 fn assemble_candidates_from_auto_impls(&mut self,
1690 obligation: &TraitObligation<'tcx>,
1691 candidates: &mut SelectionCandidateSet<'tcx>)
1692 -> Result<(), SelectionError<'tcx>>
1694 // OK to skip binder here because the tests we do below do not involve bound regions
1695 let self_ty = *obligation.self_ty().skip_binder();
1696 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
1698 let def_id = obligation.predicate.def_id();
1700 if self.tcx().trait_is_auto(def_id) {
1702 ty::TyDynamic(..) => {
1703 // For object types, we don't know what the closed
1704 // over types are. This means we conservatively
1705 // say nothing; a candidate may be added by
1706 // `assemble_candidates_from_object_ty`.
1708 ty::TyForeign(..) => {
1709 // Since the contents of foreign types is unknown,
1710 // we don't add any `..` impl. Default traits could
1711 // still be provided by a manual implementation for
1712 // this trait and type.
1715 ty::TyProjection(..) => {
1716 // In these cases, we don't know what the actual
1717 // type is. Therefore, we cannot break it down
1718 // into its constituent types. So we don't
1719 // consider the `..` impl but instead just add no
1720 // candidates: this means that typeck will only
1721 // succeed if there is another reason to believe
1722 // that this obligation holds. That could be a
1723 // where-clause or, in the case of an object type,
1724 // it could be that the object type lists the
1725 // trait (e.g. `Foo+Send : Send`). See
1726 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1727 // for an example of a test case that exercises
1730 ty::TyInfer(ty::TyVar(_)) => {
1731 // the auto impl might apply, we don't know
1732 candidates.ambiguous = true;
1735 candidates.vec.push(AutoImplCandidate(def_id.clone()))
1743 /// Search for impls that might apply to `obligation`.
1744 fn assemble_candidates_from_object_ty(&mut self,
1745 obligation: &TraitObligation<'tcx>,
1746 candidates: &mut SelectionCandidateSet<'tcx>)
1748 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1749 obligation.self_ty().skip_binder());
1751 // Object-safety candidates are only applicable to object-safe
1752 // traits. Including this check is useful because it helps
1753 // inference in cases of traits like `BorrowFrom`, which are
1754 // not object-safe, and which rely on being able to infer the
1755 // self-type from one of the other inputs. Without this check,
1756 // these cases wind up being considered ambiguous due to a
1757 // (spurious) ambiguity introduced here.
1758 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1759 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1763 self.probe(|this, _snapshot| {
1764 // the code below doesn't care about regions, and the
1765 // self-ty here doesn't escape this probe, so just erase
1767 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1768 let poly_trait_ref = match self_ty.sty {
1769 ty::TyDynamic(ref data, ..) => {
1770 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1771 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1772 pushing candidate");
1773 candidates.vec.push(BuiltinObjectCandidate);
1777 match data.principal() {
1778 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1782 ty::TyInfer(ty::TyVar(_)) => {
1783 debug!("assemble_candidates_from_object_ty: ambiguous");
1784 candidates.ambiguous = true; // could wind up being an object type
1792 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1795 // Count only those upcast versions that match the trait-ref
1796 // we are looking for. Specifically, do not only check for the
1797 // correct trait, but also the correct type parameters.
1798 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1799 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1800 let upcast_trait_refs =
1801 util::supertraits(this.tcx(), poly_trait_ref)
1802 .filter(|upcast_trait_ref| {
1803 this.probe(|this, _| {
1804 let upcast_trait_ref = upcast_trait_ref.clone();
1805 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1810 if upcast_trait_refs > 1 {
1811 // can be upcast in many ways; need more type information
1812 candidates.ambiguous = true;
1813 } else if upcast_trait_refs == 1 {
1814 candidates.vec.push(ObjectCandidate);
1819 /// Search for unsizing that might apply to `obligation`.
1820 fn assemble_candidates_for_unsizing(&mut self,
1821 obligation: &TraitObligation<'tcx>,
1822 candidates: &mut SelectionCandidateSet<'tcx>) {
1823 // We currently never consider higher-ranked obligations e.g.
1824 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1825 // because they are a priori invalid, and we could potentially add support
1826 // for them later, it's just that there isn't really a strong need for it.
1827 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1828 // impl, and those are generally applied to concrete types.
1830 // That said, one might try to write a fn with a where clause like
1831 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1832 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1833 // Still, you'd be more likely to write that where clause as
1835 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1836 // obligation above. Should be possible to extend this in the future.
1837 let source = match obligation.self_ty().no_late_bound_regions() {
1840 // Don't add any candidates if there are bound regions.
1844 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1846 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1849 let may_apply = match (&source.sty, &target.sty) {
1850 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1851 (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1852 // Upcasts permit two things:
1854 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1855 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1857 // Note that neither of these changes requires any
1858 // change at runtime. Eventually this will be
1861 // We always upcast when we can because of reason
1862 // #2 (region bounds).
1863 match (data_a.principal(), data_b.principal()) {
1864 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1865 data_b.auto_traits()
1866 // All of a's auto traits need to be in b's auto traits.
1867 .all(|b| data_a.auto_traits().any(|a| a == b)),
1873 (_, &ty::TyDynamic(..)) => true,
1875 // Ambiguous handling is below T -> Trait, because inference
1876 // variables can still implement Unsize<Trait> and nested
1877 // obligations will have the final say (likely deferred).
1878 (&ty::TyInfer(ty::TyVar(_)), _) |
1879 (_, &ty::TyInfer(ty::TyVar(_))) => {
1880 debug!("assemble_candidates_for_unsizing: ambiguous");
1881 candidates.ambiguous = true;
1886 (&ty::TyArray(..), &ty::TySlice(_)) => true,
1888 // Struct<T> -> Struct<U>.
1889 (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1890 def_id_a == def_id_b
1893 // (.., T) -> (.., U).
1894 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
1895 tys_a.len() == tys_b.len()
1902 candidates.vec.push(BuiltinUnsizeCandidate);
1906 ///////////////////////////////////////////////////////////////////////////
1909 // Winnowing is the process of attempting to resolve ambiguity by
1910 // probing further. During the winnowing process, we unify all
1911 // type variables (ignoring skolemization) and then we also
1912 // attempt to evaluate recursive bounds to see if they are
1915 /// Returns true if `candidate_i` should be dropped in favor of
1916 /// `candidate_j`. Generally speaking we will drop duplicate
1917 /// candidates and prefer where-clause candidates.
1918 /// Returns true if `victim` should be dropped in favor of
1919 /// `other`. Generally speaking we will drop duplicate
1920 /// candidates and prefer where-clause candidates.
1922 /// See the comment for "SelectionCandidate" for more details.
1923 fn candidate_should_be_dropped_in_favor_of<'o>(
1925 victim: &EvaluatedCandidate<'tcx>,
1926 other: &EvaluatedCandidate<'tcx>)
1929 if victim.candidate == other.candidate {
1933 match other.candidate {
1935 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1936 AutoImplCandidate(..) => {
1938 "default implementations shouldn't be recorded \
1939 when there are other valid candidates");
1943 GeneratorCandidate |
1944 FnPointerCandidate |
1945 BuiltinObjectCandidate |
1946 BuiltinUnsizeCandidate |
1947 BuiltinCandidate { .. } => {
1948 // We have a where-clause so don't go around looking
1953 ProjectionCandidate => {
1954 // Arbitrarily give param candidates priority
1955 // over projection and object candidates.
1958 ParamCandidate(..) => false,
1960 ImplCandidate(other_def) => {
1961 // See if we can toss out `victim` based on specialization.
1962 // This requires us to know *for sure* that the `other` impl applies
1963 // i.e. EvaluatedToOk:
1964 if other.evaluation == EvaluatedToOk {
1965 if let ImplCandidate(victim_def) = victim.candidate {
1966 let tcx = self.tcx().global_tcx();
1967 return tcx.specializes((other_def, victim_def)) ||
1968 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
1978 ///////////////////////////////////////////////////////////////////////////
1981 // These cover the traits that are built-in to the language
1982 // itself. This includes `Copy` and `Sized` for sure. For the
1983 // moment, it also includes `Send` / `Sync` and a few others, but
1984 // those will hopefully change to library-defined traits in the
1987 // HACK: if this returns an error, selection exits without considering
1989 fn assemble_builtin_bound_candidates<'o>(&mut self,
1990 conditions: BuiltinImplConditions<'tcx>,
1991 candidates: &mut SelectionCandidateSet<'tcx>)
1992 -> Result<(),SelectionError<'tcx>>
1995 BuiltinImplConditions::Where(nested) => {
1996 debug!("builtin_bound: nested={:?}", nested);
1997 candidates.vec.push(BuiltinCandidate {
1998 has_nested: nested.skip_binder().len() > 0
2002 BuiltinImplConditions::None => { Ok(()) }
2003 BuiltinImplConditions::Ambiguous => {
2004 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2005 Ok(candidates.ambiguous = true)
2007 BuiltinImplConditions::Never => { Err(Unimplemented) }
2011 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2012 -> BuiltinImplConditions<'tcx>
2014 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
2016 // NOTE: binder moved to (*)
2017 let self_ty = self.infcx.shallow_resolve(
2018 obligation.predicate.skip_binder().self_ty());
2021 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
2022 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
2023 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
2024 ty::TyChar | ty::TyRef(..) | ty::TyGenerator(..) |
2025 ty::TyArray(..) | ty::TyClosure(..) | ty::TyNever |
2027 // safe for everything
2028 Where(ty::Binder(Vec::new()))
2031 ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) | ty::TyForeign(..) => Never,
2033 ty::TyTuple(tys, _) => {
2034 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
2037 ty::TyAdt(def, substs) => {
2038 let sized_crit = def.sized_constraint(self.tcx());
2039 // (*) binder moved here
2041 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
2045 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
2046 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
2048 ty::TyInfer(ty::FreshTy(_))
2049 | ty::TyInfer(ty::FreshIntTy(_))
2050 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2051 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2057 fn copy_clone_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2058 -> BuiltinImplConditions<'tcx>
2060 // NOTE: binder moved to (*)
2061 let self_ty = self.infcx.shallow_resolve(
2062 obligation.predicate.skip_binder().self_ty());
2064 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
2067 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
2068 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
2069 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
2070 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
2071 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
2072 Where(ty::Binder(Vec::new()))
2075 ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
2076 ty::TyGenerator(..) | ty::TyForeign(..) |
2077 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
2081 ty::TyArray(element_ty, _) => {
2082 // (*) binder moved here
2083 Where(ty::Binder(vec![element_ty]))
2086 ty::TyTuple(tys, _) => {
2087 // (*) binder moved here
2088 Where(ty::Binder(tys.to_vec()))
2091 ty::TyClosure(def_id, substs) => {
2092 let trait_id = obligation.predicate.def_id();
2094 Some(trait_id) == self.tcx().lang_items().copy_trait() &&
2095 self.tcx().has_copy_closures(def_id.krate);
2096 let clone_closures =
2097 Some(trait_id) == self.tcx().lang_items().clone_trait() &&
2098 self.tcx().has_clone_closures(def_id.krate);
2100 if copy_closures || clone_closures {
2101 Where(ty::Binder(substs.upvar_tys(def_id, self.tcx()).collect()))
2107 ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
2108 // Fallback to whatever user-defined impls exist in this case.
2112 ty::TyInfer(ty::TyVar(_)) => {
2113 // Unbound type variable. Might or might not have
2114 // applicable impls and so forth, depending on what
2115 // those type variables wind up being bound to.
2119 ty::TyInfer(ty::FreshTy(_))
2120 | ty::TyInfer(ty::FreshIntTy(_))
2121 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2122 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2128 /// For default impls, we need to break apart a type into its
2129 /// "constituent types" -- meaning, the types that it contains.
2131 /// Here are some (simple) examples:
2134 /// (i32, u32) -> [i32, u32]
2135 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2136 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2137 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2139 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2149 ty::TyInfer(ty::IntVar(_)) |
2150 ty::TyInfer(ty::FloatVar(_)) |
2159 ty::TyProjection(..) |
2160 ty::TyInfer(ty::TyVar(_)) |
2161 ty::TyInfer(ty::FreshTy(_)) |
2162 ty::TyInfer(ty::FreshIntTy(_)) |
2163 ty::TyInfer(ty::FreshFloatTy(_)) => {
2164 bug!("asked to assemble constituent types of unexpected type: {:?}",
2168 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
2169 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
2173 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
2177 ty::TyTuple(ref tys, _) => {
2178 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2182 ty::TyClosure(def_id, ref substs) => {
2183 substs.upvar_tys(def_id, self.tcx()).collect()
2186 ty::TyGenerator(def_id, ref substs, interior) => {
2187 let witness = iter::once(interior.witness);
2188 substs.upvar_tys(def_id, self.tcx()).chain(witness).collect()
2191 // for `PhantomData<T>`, we pass `T`
2192 ty::TyAdt(def, substs) if def.is_phantom_data() => {
2193 substs.types().collect()
2196 ty::TyAdt(def, substs) => {
2198 .map(|f| f.ty(self.tcx(), substs))
2202 ty::TyAnon(def_id, substs) => {
2203 // We can resolve the `impl Trait` to its concrete type,
2204 // which enforces a DAG between the functions requiring
2205 // the auto trait bounds in question.
2206 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2211 fn collect_predicates_for_types(&mut self,
2212 param_env: ty::ParamEnv<'tcx>,
2213 cause: ObligationCause<'tcx>,
2214 recursion_depth: usize,
2215 trait_def_id: DefId,
2216 types: ty::Binder<Vec<Ty<'tcx>>>)
2217 -> Vec<PredicateObligation<'tcx>>
2219 // Because the types were potentially derived from
2220 // higher-ranked obligations they may reference late-bound
2221 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2222 // yield a type like `for<'a> &'a int`. In general, we
2223 // maintain the invariant that we never manipulate bound
2224 // regions, so we have to process these bound regions somehow.
2226 // The strategy is to:
2228 // 1. Instantiate those regions to skolemized regions (e.g.,
2229 // `for<'a> &'a int` becomes `&0 int`.
2230 // 2. Produce something like `&'0 int : Copy`
2231 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2233 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
2234 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
2236 self.in_snapshot(|this, snapshot| {
2237 let (skol_ty, skol_map) =
2238 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
2239 let Normalized { value: normalized_ty, mut obligations } =
2240 project::normalize_with_depth(this,
2245 let skol_obligation =
2246 this.tcx().predicate_for_trait_def(param_env,
2252 obligations.push(skol_obligation);
2253 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2258 ///////////////////////////////////////////////////////////////////////////
2261 // Confirmation unifies the output type parameters of the trait
2262 // with the values found in the obligation, possibly yielding a
2263 // type error. See `README.md` for more details.
2265 fn confirm_candidate(&mut self,
2266 obligation: &TraitObligation<'tcx>,
2267 candidate: SelectionCandidate<'tcx>)
2268 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2270 debug!("confirm_candidate({:?}, {:?})",
2275 BuiltinCandidate { has_nested } => {
2276 let data = self.confirm_builtin_candidate(obligation, has_nested);
2277 Ok(VtableBuiltin(data))
2280 ParamCandidate(param) => {
2281 let obligations = self.confirm_param_candidate(obligation, param);
2282 Ok(VtableParam(obligations))
2285 AutoImplCandidate(trait_def_id) => {
2286 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2287 Ok(VtableAutoImpl(data))
2290 ImplCandidate(impl_def_id) => {
2291 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2294 ClosureCandidate => {
2295 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2296 Ok(VtableClosure(vtable_closure))
2299 GeneratorCandidate => {
2300 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2301 Ok(VtableGenerator(vtable_generator))
2304 BuiltinObjectCandidate => {
2305 // This indicates something like `(Trait+Send) :
2306 // Send`. In this case, we know that this holds
2307 // because that's what the object type is telling us,
2308 // and there's really no additional obligations to
2309 // prove and no types in particular to unify etc.
2310 Ok(VtableParam(Vec::new()))
2313 ObjectCandidate => {
2314 let data = self.confirm_object_candidate(obligation);
2315 Ok(VtableObject(data))
2318 FnPointerCandidate => {
2320 self.confirm_fn_pointer_candidate(obligation)?;
2321 Ok(VtableFnPointer(data))
2324 ProjectionCandidate => {
2325 self.confirm_projection_candidate(obligation);
2326 Ok(VtableParam(Vec::new()))
2329 BuiltinUnsizeCandidate => {
2330 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2331 Ok(VtableBuiltin(data))
2336 fn confirm_projection_candidate(&mut self,
2337 obligation: &TraitObligation<'tcx>)
2339 self.in_snapshot(|this, snapshot| {
2341 this.match_projection_obligation_against_definition_bounds(obligation,
2347 fn confirm_param_candidate(&mut self,
2348 obligation: &TraitObligation<'tcx>,
2349 param: ty::PolyTraitRef<'tcx>)
2350 -> Vec<PredicateObligation<'tcx>>
2352 debug!("confirm_param_candidate({:?},{:?})",
2356 // During evaluation, we already checked that this
2357 // where-clause trait-ref could be unified with the obligation
2358 // trait-ref. Repeat that unification now without any
2359 // transactional boundary; it should not fail.
2360 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2361 Ok(obligations) => obligations,
2363 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2370 fn confirm_builtin_candidate(&mut self,
2371 obligation: &TraitObligation<'tcx>,
2373 -> VtableBuiltinData<PredicateObligation<'tcx>>
2375 debug!("confirm_builtin_candidate({:?}, {:?})",
2376 obligation, has_nested);
2378 let lang_items = self.tcx().lang_items();
2379 let obligations = if has_nested {
2380 let trait_def = obligation.predicate.def_id();
2381 let conditions = match trait_def {
2382 _ if Some(trait_def) == lang_items.sized_trait() => {
2383 self.sized_conditions(obligation)
2385 _ if Some(trait_def) == lang_items.copy_trait() => {
2386 self.copy_clone_conditions(obligation)
2388 _ if Some(trait_def) == lang_items.clone_trait() => {
2389 self.copy_clone_conditions(obligation)
2391 _ => bug!("unexpected builtin trait {:?}", trait_def)
2393 let nested = match conditions {
2394 BuiltinImplConditions::Where(nested) => nested,
2395 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2399 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2400 self.collect_predicates_for_types(obligation.param_env,
2402 obligation.recursion_depth+1,
2409 debug!("confirm_builtin_candidate: obligations={:?}",
2412 VtableBuiltinData { nested: obligations }
2415 /// This handles the case where a `impl Foo for ..` impl is being used.
2416 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2418 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2419 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2420 fn confirm_auto_impl_candidate(&mut self,
2421 obligation: &TraitObligation<'tcx>,
2422 trait_def_id: DefId)
2423 -> VtableAutoImplData<PredicateObligation<'tcx>>
2425 debug!("confirm_auto_impl_candidate({:?}, {:?})",
2429 // binder is moved below
2430 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2431 let types = self.constituent_types_for_ty(self_ty);
2432 self.vtable_auto_impl(obligation, trait_def_id, ty::Binder(types))
2435 /// See `confirm_auto_impl_candidate`
2436 fn vtable_auto_impl(&mut self,
2437 obligation: &TraitObligation<'tcx>,
2438 trait_def_id: DefId,
2439 nested: ty::Binder<Vec<Ty<'tcx>>>)
2440 -> VtableAutoImplData<PredicateObligation<'tcx>>
2442 debug!("vtable_auto_impl: nested={:?}", nested);
2444 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2445 let mut obligations = self.collect_predicates_for_types(
2446 obligation.param_env,
2448 obligation.recursion_depth+1,
2452 let trait_obligations = self.in_snapshot(|this, snapshot| {
2453 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2454 let (trait_ref, skol_map) =
2455 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2456 let cause = obligation.derived_cause(ImplDerivedObligation);
2457 this.impl_or_trait_obligations(cause,
2458 obligation.recursion_depth + 1,
2459 obligation.param_env,
2466 obligations.extend(trait_obligations);
2468 debug!("vtable_auto_impl: obligations={:?}", obligations);
2470 VtableAutoImplData {
2476 fn confirm_impl_candidate(&mut self,
2477 obligation: &TraitObligation<'tcx>,
2479 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2481 debug!("confirm_impl_candidate({:?},{:?})",
2485 // First, create the substitutions by matching the impl again,
2486 // this time not in a probe.
2487 self.in_snapshot(|this, snapshot| {
2488 let (substs, skol_map) =
2489 this.rematch_impl(impl_def_id, obligation,
2491 debug!("confirm_impl_candidate substs={:?}", substs);
2492 let cause = obligation.derived_cause(ImplDerivedObligation);
2493 this.vtable_impl(impl_def_id,
2496 obligation.recursion_depth + 1,
2497 obligation.param_env,
2503 fn vtable_impl(&mut self,
2505 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2506 cause: ObligationCause<'tcx>,
2507 recursion_depth: usize,
2508 param_env: ty::ParamEnv<'tcx>,
2509 skol_map: infer::SkolemizationMap<'tcx>,
2510 snapshot: &infer::CombinedSnapshot)
2511 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2513 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2519 let mut impl_obligations =
2520 self.impl_or_trait_obligations(cause,
2528 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2532 // Because of RFC447, the impl-trait-ref and obligations
2533 // are sufficient to determine the impl substs, without
2534 // relying on projections in the impl-trait-ref.
2536 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2537 impl_obligations.append(&mut substs.obligations);
2539 VtableImplData { impl_def_id,
2540 substs: substs.value,
2541 nested: impl_obligations }
2544 fn confirm_object_candidate(&mut self,
2545 obligation: &TraitObligation<'tcx>)
2546 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2548 debug!("confirm_object_candidate({:?})",
2551 // FIXME skipping binder here seems wrong -- we should
2552 // probably flatten the binder from the obligation and the
2553 // binder from the object. Have to try to make a broken test
2554 // case that results. -nmatsakis
2555 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2556 let poly_trait_ref = match self_ty.sty {
2557 ty::TyDynamic(ref data, ..) => {
2558 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2561 span_bug!(obligation.cause.span,
2562 "object candidate with non-object");
2566 let mut upcast_trait_ref = None;
2570 let tcx = self.tcx();
2572 // We want to find the first supertrait in the list of
2573 // supertraits that we can unify with, and do that
2574 // unification. We know that there is exactly one in the list
2575 // where we can unify because otherwise select would have
2576 // reported an ambiguity. (When we do find a match, also
2577 // record it for later.)
2579 util::supertraits(tcx, poly_trait_ref)
2583 |this, _| this.match_poly_trait_ref(obligation, t))
2585 Ok(_) => { upcast_trait_ref = Some(t); false }
2590 // Additionally, for each of the nonmatching predicates that
2591 // we pass over, we sum up the set of number of vtable
2592 // entries, so that we can compute the offset for the selected
2595 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2601 upcast_trait_ref: upcast_trait_ref.unwrap(),
2607 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2608 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2610 debug!("confirm_fn_pointer_candidate({:?})",
2613 // ok to skip binder; it is reintroduced below
2614 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2615 let sig = self_ty.fn_sig(self.tcx());
2617 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2620 util::TupleArgumentsFlag::Yes)
2621 .map_bound(|(trait_ref, _)| trait_ref);
2623 let Normalized { value: trait_ref, obligations } =
2624 project::normalize_with_depth(self,
2625 obligation.param_env,
2626 obligation.cause.clone(),
2627 obligation.recursion_depth + 1,
2630 self.confirm_poly_trait_refs(obligation.cause.clone(),
2631 obligation.param_env,
2632 obligation.predicate.to_poly_trait_ref(),
2634 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2637 fn confirm_generator_candidate(&mut self,
2638 obligation: &TraitObligation<'tcx>)
2639 -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
2640 SelectionError<'tcx>>
2642 // ok to skip binder because the substs on generator types never
2643 // touch bound regions, they just capture the in-scope
2644 // type/region parameters
2645 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2646 let (closure_def_id, substs) = match self_ty.sty {
2647 ty::TyGenerator(id, substs, _) => (id, substs),
2648 _ => bug!("closure candidate for non-closure {:?}", obligation)
2651 debug!("confirm_generator_candidate({:?},{:?},{:?})",
2657 self.generator_trait_ref_unnormalized(obligation, closure_def_id, substs);
2661 } = normalize_with_depth(self,
2662 obligation.param_env,
2663 obligation.cause.clone(),
2664 obligation.recursion_depth+1,
2667 debug!("confirm_generator_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2672 self.confirm_poly_trait_refs(obligation.cause.clone(),
2673 obligation.param_env,
2674 obligation.predicate.to_poly_trait_ref(),
2677 Ok(VtableGeneratorData {
2678 closure_def_id: closure_def_id,
2679 substs: substs.clone(),
2684 fn confirm_closure_candidate(&mut self,
2685 obligation: &TraitObligation<'tcx>)
2686 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2687 SelectionError<'tcx>>
2689 debug!("confirm_closure_candidate({:?})", obligation);
2691 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.0.def_id()) {
2693 None => bug!("closure candidate for non-fn trait {:?}", obligation)
2696 // ok to skip binder because the substs on closure types never
2697 // touch bound regions, they just capture the in-scope
2698 // type/region parameters
2699 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2700 let (closure_def_id, substs) = match self_ty.sty {
2701 ty::TyClosure(id, substs) => (id, substs),
2702 _ => bug!("closure candidate for non-closure {:?}", obligation)
2706 self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
2710 } = normalize_with_depth(self,
2711 obligation.param_env,
2712 obligation.cause.clone(),
2713 obligation.recursion_depth+1,
2716 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2721 self.confirm_poly_trait_refs(obligation.cause.clone(),
2722 obligation.param_env,
2723 obligation.predicate.to_poly_trait_ref(),
2726 obligations.push(Obligation::new(
2727 obligation.cause.clone(),
2728 obligation.param_env,
2729 ty::Predicate::ClosureKind(closure_def_id, substs, kind)));
2731 Ok(VtableClosureData {
2733 substs: substs.clone(),
2738 /// In the case of closure types and fn pointers,
2739 /// we currently treat the input type parameters on the trait as
2740 /// outputs. This means that when we have a match we have only
2741 /// considered the self type, so we have to go back and make sure
2742 /// to relate the argument types too. This is kind of wrong, but
2743 /// since we control the full set of impls, also not that wrong,
2744 /// and it DOES yield better error messages (since we don't report
2745 /// errors as if there is no applicable impl, but rather report
2746 /// errors are about mismatched argument types.
2748 /// Here is an example. Imagine we have a closure expression
2749 /// and we desugared it so that the type of the expression is
2750 /// `Closure`, and `Closure` expects an int as argument. Then it
2751 /// is "as if" the compiler generated this impl:
2753 /// impl Fn(int) for Closure { ... }
2755 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2756 /// we have matched the self-type `Closure`. At this point we'll
2757 /// compare the `int` to `usize` and generate an error.
2759 /// Note that this checking occurs *after* the impl has selected,
2760 /// because these output type parameters should not affect the
2761 /// selection of the impl. Therefore, if there is a mismatch, we
2762 /// report an error to the user.
2763 fn confirm_poly_trait_refs(&mut self,
2764 obligation_cause: ObligationCause<'tcx>,
2765 obligation_param_env: ty::ParamEnv<'tcx>,
2766 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2767 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2768 -> Result<(), SelectionError<'tcx>>
2770 let obligation_trait_ref = obligation_trait_ref.clone();
2772 .at(&obligation_cause, obligation_param_env)
2773 .sup(obligation_trait_ref, expected_trait_ref)
2774 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2775 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2778 fn confirm_builtin_unsize_candidate(&mut self,
2779 obligation: &TraitObligation<'tcx>,)
2780 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>>
2782 let tcx = self.tcx();
2784 // assemble_candidates_for_unsizing should ensure there are no late bound
2785 // regions here. See the comment there for more details.
2786 let source = self.infcx.shallow_resolve(
2787 obligation.self_ty().no_late_bound_regions().unwrap());
2788 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2789 let target = self.infcx.shallow_resolve(target);
2791 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2794 let mut nested = vec![];
2795 match (&source.sty, &target.sty) {
2796 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2797 (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2798 // See assemble_candidates_for_unsizing for more info.
2799 // Binders reintroduced below in call to mk_existential_predicates.
2800 let principal = data_a.skip_binder().principal();
2801 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2802 .chain(data_a.skip_binder().projection_bounds()
2803 .map(|x| ty::ExistentialPredicate::Projection(x)))
2804 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2805 let new_trait = tcx.mk_dynamic(
2806 ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2807 let InferOk { obligations, .. } =
2808 self.infcx.at(&obligation.cause, obligation.param_env)
2809 .eq(target, new_trait)
2810 .map_err(|_| Unimplemented)?;
2811 self.inferred_obligations.extend(obligations);
2813 // Register one obligation for 'a: 'b.
2814 let cause = ObligationCause::new(obligation.cause.span,
2815 obligation.cause.body_id,
2816 ObjectCastObligation(target));
2817 let outlives = ty::OutlivesPredicate(r_a, r_b);
2818 nested.push(Obligation::with_depth(cause,
2819 obligation.recursion_depth + 1,
2820 obligation.param_env,
2821 ty::Binder(outlives).to_predicate()));
2825 (_, &ty::TyDynamic(ref data, r)) => {
2826 let mut object_dids =
2827 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2828 if let Some(did) = object_dids.find(|did| {
2829 !tcx.is_object_safe(*did)
2831 return Err(TraitNotObjectSafe(did))
2834 let cause = ObligationCause::new(obligation.cause.span,
2835 obligation.cause.body_id,
2836 ObjectCastObligation(target));
2837 let mut push = |predicate| {
2838 nested.push(Obligation::with_depth(cause.clone(),
2839 obligation.recursion_depth + 1,
2840 obligation.param_env,
2844 // Create obligations:
2845 // - Casting T to Trait
2846 // - For all the various builtin bounds attached to the object cast. (In other
2847 // words, if the object type is Foo+Send, this would create an obligation for the
2849 // - Projection predicates
2850 for predicate in data.iter() {
2851 push(predicate.with_self_ty(tcx, source));
2854 // We can only make objects from sized types.
2855 let tr = ty::TraitRef {
2856 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2857 substs: tcx.mk_substs_trait(source, &[]),
2859 push(tr.to_predicate());
2861 // If the type is `Foo+'a`, ensures that the type
2862 // being cast to `Foo+'a` outlives `'a`:
2863 let outlives = ty::OutlivesPredicate(source, r);
2864 push(ty::Binder(outlives).to_predicate());
2868 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2869 let InferOk { obligations, .. } =
2870 self.infcx.at(&obligation.cause, obligation.param_env)
2872 .map_err(|_| Unimplemented)?;
2873 self.inferred_obligations.extend(obligations);
2876 // Struct<T> -> Struct<U>.
2877 (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2880 .map(|f| tcx.type_of(f.did))
2881 .collect::<Vec<_>>();
2883 // The last field of the structure has to exist and contain type parameters.
2884 let field = if let Some(&field) = fields.last() {
2887 return Err(Unimplemented);
2889 let mut ty_params = BitVector::new(substs_a.types().count());
2890 let mut found = false;
2891 for ty in field.walk() {
2892 if let ty::TyParam(p) = ty.sty {
2893 ty_params.insert(p.idx as usize);
2898 return Err(Unimplemented);
2901 // Replace type parameters used in unsizing with
2902 // TyError and ensure they do not affect any other fields.
2903 // This could be checked after type collection for any struct
2904 // with a potentially unsized trailing field.
2905 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2906 if ty_params.contains(i) {
2907 Kind::from(tcx.types.err)
2912 let substs = tcx.mk_substs(params);
2913 for &ty in fields.split_last().unwrap().1 {
2914 if ty.subst(tcx, substs).references_error() {
2915 return Err(Unimplemented);
2919 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2920 let inner_source = field.subst(tcx, substs_a);
2921 let inner_target = field.subst(tcx, substs_b);
2923 // Check that the source struct with the target's
2924 // unsized parameters is equal to the target.
2925 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2926 if ty_params.contains(i) {
2927 Kind::from(substs_b.type_at(i))
2932 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
2933 let InferOk { obligations, .. } =
2934 self.infcx.at(&obligation.cause, obligation.param_env)
2935 .eq(target, new_struct)
2936 .map_err(|_| Unimplemented)?;
2937 self.inferred_obligations.extend(obligations);
2939 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2940 nested.push(tcx.predicate_for_trait_def(
2941 obligation.param_env,
2942 obligation.cause.clone(),
2943 obligation.predicate.def_id(),
2944 obligation.recursion_depth + 1,
2949 // (.., T) -> (.., U).
2950 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
2951 assert_eq!(tys_a.len(), tys_b.len());
2953 // The last field of the tuple has to exist.
2954 let (a_last, a_mid) = if let Some(x) = tys_a.split_last() {
2957 return Err(Unimplemented);
2959 let b_last = tys_b.last().unwrap();
2961 // Check that the source tuple with the target's
2962 // last element is equal to the target.
2963 let new_tuple = tcx.mk_tup(a_mid.iter().chain(Some(b_last)), false);
2964 let InferOk { obligations, .. } =
2965 self.infcx.at(&obligation.cause, obligation.param_env)
2966 .eq(target, new_tuple)
2967 .map_err(|_| Unimplemented)?;
2968 self.inferred_obligations.extend(obligations);
2970 // Construct the nested T: Unsize<U> predicate.
2971 nested.push(tcx.predicate_for_trait_def(
2972 obligation.param_env,
2973 obligation.cause.clone(),
2974 obligation.predicate.def_id(),
2975 obligation.recursion_depth + 1,
2983 Ok(VtableBuiltinData { nested: nested })
2986 ///////////////////////////////////////////////////////////////////////////
2989 // Matching is a common path used for both evaluation and
2990 // confirmation. It basically unifies types that appear in impls
2991 // and traits. This does affect the surrounding environment;
2992 // therefore, when used during evaluation, match routines must be
2993 // run inside of a `probe()` so that their side-effects are
2996 fn rematch_impl(&mut self,
2998 obligation: &TraitObligation<'tcx>,
2999 snapshot: &infer::CombinedSnapshot)
3000 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
3001 infer::SkolemizationMap<'tcx>)
3003 match self.match_impl(impl_def_id, obligation, snapshot) {
3004 Ok((substs, skol_map)) => (substs, skol_map),
3006 bug!("Impl {:?} was matchable against {:?} but now is not",
3013 fn match_impl(&mut self,
3015 obligation: &TraitObligation<'tcx>,
3016 snapshot: &infer::CombinedSnapshot)
3017 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
3018 infer::SkolemizationMap<'tcx>), ()>
3020 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3022 // Before we create the substitutions and everything, first
3023 // consider a "quick reject". This avoids creating more types
3024 // and so forth that we need to.
3025 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3029 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
3030 &obligation.predicate,
3032 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3034 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
3037 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
3040 let impl_trait_ref =
3041 project::normalize_with_depth(self,
3042 obligation.param_env,
3043 obligation.cause.clone(),
3044 obligation.recursion_depth + 1,
3047 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
3048 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3052 skol_obligation_trait_ref);
3054 let InferOk { obligations, .. } =
3055 self.infcx.at(&obligation.cause, obligation.param_env)
3056 .eq(skol_obligation_trait_ref, impl_trait_ref.value)
3058 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
3061 self.inferred_obligations.extend(obligations);
3063 if let Err(e) = self.infcx.leak_check(false,
3064 obligation.cause.span,
3067 debug!("match_impl: failed leak check due to `{}`", e);
3071 debug!("match_impl: success impl_substs={:?}", impl_substs);
3074 obligations: impl_trait_ref.obligations
3078 fn fast_reject_trait_refs(&mut self,
3079 obligation: &TraitObligation,
3080 impl_trait_ref: &ty::TraitRef)
3083 // We can avoid creating type variables and doing the full
3084 // substitution if we find that any of the input types, when
3085 // simplified, do not match.
3087 obligation.predicate.skip_binder().input_types()
3088 .zip(impl_trait_ref.input_types())
3089 .any(|(obligation_ty, impl_ty)| {
3090 let simplified_obligation_ty =
3091 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3092 let simplified_impl_ty =
3093 fast_reject::simplify_type(self.tcx(), impl_ty, false);
3095 simplified_obligation_ty.is_some() &&
3096 simplified_impl_ty.is_some() &&
3097 simplified_obligation_ty != simplified_impl_ty
3101 /// Normalize `where_clause_trait_ref` and try to match it against
3102 /// `obligation`. If successful, return any predicates that
3103 /// result from the normalization. Normalization is necessary
3104 /// because where-clauses are stored in the parameter environment
3106 fn match_where_clause_trait_ref(&mut self,
3107 obligation: &TraitObligation<'tcx>,
3108 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
3109 -> Result<Vec<PredicateObligation<'tcx>>,()>
3111 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
3115 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3116 /// obligation is satisfied.
3117 fn match_poly_trait_ref(&mut self,
3118 obligation: &TraitObligation<'tcx>,
3119 poly_trait_ref: ty::PolyTraitRef<'tcx>)
3122 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3126 self.infcx.at(&obligation.cause, obligation.param_env)
3127 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3128 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
3132 ///////////////////////////////////////////////////////////////////////////
3135 fn match_fresh_trait_refs(&self,
3136 previous: &ty::PolyTraitRef<'tcx>,
3137 current: &ty::PolyTraitRef<'tcx>)
3140 let mut matcher = ty::_match::Match::new(self.tcx());
3141 matcher.relate(previous, current).is_ok()
3144 fn push_stack<'o,'s:'o>(&mut self,
3145 previous_stack: TraitObligationStackList<'s, 'tcx>,
3146 obligation: &'o TraitObligation<'tcx>)
3147 -> TraitObligationStack<'o, 'tcx>
3149 let fresh_trait_ref =
3150 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3152 TraitObligationStack {
3155 previous: previous_stack,
3159 fn closure_trait_ref_unnormalized(&mut self,
3160 obligation: &TraitObligation<'tcx>,
3161 closure_def_id: DefId,
3162 substs: ty::ClosureSubsts<'tcx>)
3163 -> ty::PolyTraitRef<'tcx>
3165 let closure_type = self.infcx.fn_sig(closure_def_id)
3166 .subst(self.tcx(), substs.substs);
3167 let ty::Binder((trait_ref, _)) =
3168 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
3169 obligation.predicate.0.self_ty(), // (1)
3171 util::TupleArgumentsFlag::No);
3172 // (1) Feels icky to skip the binder here, but OTOH we know
3173 // that the self-type is an unboxed closure type and hence is
3174 // in fact unparameterized (or at least does not reference any
3175 // regions bound in the obligation). Still probably some
3176 // refactoring could make this nicer.
3178 ty::Binder(trait_ref)
3181 fn generator_trait_ref_unnormalized(&mut self,
3182 obligation: &TraitObligation<'tcx>,
3183 closure_def_id: DefId,
3184 substs: ty::ClosureSubsts<'tcx>)
3185 -> ty::PolyTraitRef<'tcx>
3187 let gen_sig = substs.generator_poly_sig(closure_def_id, self.tcx());
3188 let ty::Binder((trait_ref, ..)) =
3189 self.tcx().generator_trait_ref_and_outputs(obligation.predicate.def_id(),
3190 obligation.predicate.0.self_ty(), // (1)
3192 // (1) Feels icky to skip the binder here, but OTOH we know
3193 // that the self-type is an generator type and hence is
3194 // in fact unparameterized (or at least does not reference any
3195 // regions bound in the obligation). Still probably some
3196 // refactoring could make this nicer.
3198 ty::Binder(trait_ref)
3201 /// Returns the obligations that are implied by instantiating an
3202 /// impl or trait. The obligations are substituted and fully
3203 /// normalized. This is used when confirming an impl or default
3205 fn impl_or_trait_obligations(&mut self,
3206 cause: ObligationCause<'tcx>,
3207 recursion_depth: usize,
3208 param_env: ty::ParamEnv<'tcx>,
3209 def_id: DefId, // of impl or trait
3210 substs: &Substs<'tcx>, // for impl or trait
3211 skol_map: infer::SkolemizationMap<'tcx>,
3212 snapshot: &infer::CombinedSnapshot)
3213 -> Vec<PredicateObligation<'tcx>>
3215 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3216 let tcx = self.tcx();
3218 // To allow for one-pass evaluation of the nested obligation,
3219 // each predicate must be preceded by the obligations required
3221 // for example, if we have:
3222 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3223 // the impl will have the following predicates:
3224 // <V as Iterator>::Item = U,
3225 // U: Iterator, U: Sized,
3226 // V: Iterator, V: Sized,
3227 // <U as Iterator>::Item: Copy
3228 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3229 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3230 // `$1: Copy`, so we must ensure the obligations are emitted in
3232 let predicates = tcx.predicates_of(def_id);
3233 assert_eq!(predicates.parent, None);
3234 let predicates = predicates.predicates.iter().flat_map(|predicate| {
3235 let predicate = normalize_with_depth(self, param_env, cause.clone(), recursion_depth,
3236 &predicate.subst(tcx, substs));
3237 predicate.obligations.into_iter().chain(
3239 cause: cause.clone(),
3242 predicate: predicate.value
3245 self.infcx().plug_leaks(skol_map, snapshot, predicates)
3249 impl<'tcx> TraitObligation<'tcx> {
3250 #[allow(unused_comparisons)]
3251 pub fn derived_cause(&self,
3252 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
3253 -> ObligationCause<'tcx>
3256 * Creates a cause for obligations that are derived from
3257 * `obligation` by a recursive search (e.g., for a builtin
3258 * bound, or eventually a `impl Foo for ..`). If `obligation`
3259 * is itself a derived obligation, this is just a clone, but
3260 * otherwise we create a "derived obligation" cause so as to
3261 * keep track of the original root obligation for error
3265 let obligation = self;
3267 // NOTE(flaper87): As of now, it keeps track of the whole error
3268 // chain. Ideally, we should have a way to configure this either
3269 // by using -Z verbose or just a CLI argument.
3270 if obligation.recursion_depth >= 0 {
3271 let derived_cause = DerivedObligationCause {
3272 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3273 parent_code: Rc::new(obligation.cause.code.clone())
3275 let derived_code = variant(derived_cause);
3276 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3278 obligation.cause.clone()
3283 impl<'tcx> SelectionCache<'tcx> {
3284 pub fn new() -> SelectionCache<'tcx> {
3286 hashmap: RefCell::new(FxHashMap())
3291 impl<'tcx> EvaluationCache<'tcx> {
3292 pub fn new() -> EvaluationCache<'tcx> {
3294 hashmap: RefCell::new(FxHashMap())
3299 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
3300 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
3301 TraitObligationStackList::with(self)
3304 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
3309 #[derive(Copy, Clone)]
3310 struct TraitObligationStackList<'o,'tcx:'o> {
3311 head: Option<&'o TraitObligationStack<'o,'tcx>>
3314 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
3315 fn empty() -> TraitObligationStackList<'o,'tcx> {
3316 TraitObligationStackList { head: None }
3319 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
3320 TraitObligationStackList { head: Some(r) }
3324 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
3325 type Item = &'o TraitObligationStack<'o,'tcx>;
3327 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3338 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3339 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3340 write!(f, "TraitObligationStack({:?})", self.obligation)
3345 pub struct WithDepNode<T> {
3346 dep_node: DepNodeIndex,
3350 impl<T: Clone> WithDepNode<T> {
3351 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3352 WithDepNode { dep_node, cached_value }
3355 pub fn get(&self, tcx: TyCtxt) -> T {
3356 tcx.dep_graph.read_index(self.dep_node);
3357 self.cached_value.clone()