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::*;
16 use super::coherence::{self, Conflict};
17 use super::DerivedObligationCause;
18 use super::IntercrateMode;
20 use super::project::{normalize_with_depth, Normalized, ProjectionCacheKey};
21 use super::{PredicateObligation, TraitObligation, ObligationCause};
22 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
23 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
24 use super::{ObjectCastObligation, Obligation};
25 use super::TraitNotObjectSafe;
27 use super::SelectionResult;
28 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure, VtableGenerator,
29 VtableFnPointer, VtableObject, VtableAutoImpl};
30 use super::{VtableImplData, VtableObjectData, VtableBuiltinData, VtableGeneratorData,
31 VtableClosureData, VtableAutoImplData, VtableFnPointerData};
34 use dep_graph::{DepNodeIndex, DepKind};
35 use hir::def_id::DefId;
37 use infer::{InferCtxt, InferOk, TypeFreshener};
38 use ty::subst::{Kind, Subst, Substs};
39 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
41 use ty::relate::TypeRelation;
42 use middle::lang_items;
44 use rustc_data_structures::bitvec::BitVector;
45 use rustc_data_structures::snapshot_vec::{SnapshotVecDelegate, SnapshotVec};
47 use std::cell::RefCell;
50 use std::marker::PhantomData;
56 use util::nodemap::{FxHashMap, FxHashSet};
58 struct InferredObligationsSnapshotVecDelegate<'tcx> {
59 phantom: PhantomData<&'tcx i32>,
61 impl<'tcx> SnapshotVecDelegate for InferredObligationsSnapshotVecDelegate<'tcx> {
62 type Value = PredicateObligation<'tcx>;
64 fn reverse(_: &mut Vec<Self::Value>, _: Self::Undo) {}
67 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
68 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
70 /// Freshener used specifically for skolemizing entries on the
71 /// obligation stack. This ensures that all entries on the stack
72 /// at one time will have the same set of skolemized entries,
73 /// which is important for checking for trait bounds that
74 /// recursively require themselves.
75 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
77 /// If true, indicates that the evaluation should be conservative
78 /// and consider the possibility of types outside this crate.
79 /// This comes up primarily when resolving ambiguity. Imagine
80 /// there is some trait reference `$0 : Bar` where `$0` is an
81 /// inference variable. If `intercrate` is true, then we can never
82 /// say for sure that this reference is not implemented, even if
83 /// there are *no impls at all for `Bar`*, because `$0` could be
84 /// bound to some type that in a downstream crate that implements
85 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
86 /// though, we set this to false, because we are only interested
87 /// in types that the user could actually have written --- in
88 /// other words, we consider `$0 : Bar` to be unimplemented if
89 /// there is no type that the user could *actually name* that
90 /// would satisfy it. This avoids crippling inference, basically.
91 intercrate: Option<IntercrateMode>,
93 inferred_obligations: SnapshotVec<InferredObligationsSnapshotVecDelegate<'tcx>>,
95 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
97 /// Controls whether or not to filter out negative impls when selecting.
98 /// This is used in librustdoc to distinguish between the lack of an impl
99 /// and a negative impl
100 allow_negative_impls: bool
103 #[derive(Clone, Debug)]
104 pub enum IntercrateAmbiguityCause {
107 self_desc: Option<String>,
109 UpstreamCrateUpdate {
111 self_desc: Option<String>,
115 impl IntercrateAmbiguityCause {
116 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
117 /// See #23980 for details.
118 pub fn add_intercrate_ambiguity_hint<'a, 'tcx>(&self,
119 err: &mut ::errors::DiagnosticBuilder) {
120 err.note(&self.intercrate_ambiguity_hint());
123 pub fn intercrate_ambiguity_hint(&self) -> String {
125 &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
126 let self_desc = if let &Some(ref ty) = self_desc {
127 format!(" for type `{}`", ty)
128 } else { "".to_string() };
129 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
131 &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
132 let self_desc = if let &Some(ref ty) = self_desc {
133 format!(" for type `{}`", ty)
134 } else { "".to_string() };
135 format!("upstream crates may add new impl of trait `{}`{} \
137 trait_desc, self_desc)
143 // A stack that walks back up the stack frame.
144 struct TraitObligationStack<'prev, 'tcx: 'prev> {
145 obligation: &'prev TraitObligation<'tcx>,
147 /// Trait ref from `obligation` but skolemized with the
148 /// selection-context's freshener. Used to check for recursion.
149 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
151 previous: TraitObligationStackList<'prev, 'tcx>,
155 pub struct SelectionCache<'tcx> {
156 hashmap: RefCell<FxHashMap<ty::TraitRef<'tcx>,
157 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>>,
160 /// The selection process begins by considering all impls, where
161 /// clauses, and so forth that might resolve an obligation. Sometimes
162 /// we'll be able to say definitively that (e.g.) an impl does not
163 /// apply to the obligation: perhaps it is defined for `usize` but the
164 /// obligation is for `int`. In that case, we drop the impl out of the
165 /// list. But the other cases are considered *candidates*.
167 /// For selection to succeed, there must be exactly one matching
168 /// candidate. If the obligation is fully known, this is guaranteed
169 /// by coherence. However, if the obligation contains type parameters
170 /// or variables, there may be multiple such impls.
172 /// It is not a real problem if multiple matching impls exist because
173 /// of type variables - it just means the obligation isn't sufficiently
174 /// elaborated. In that case we report an ambiguity, and the caller can
175 /// try again after more type information has been gathered or report a
176 /// "type annotations required" error.
178 /// However, with type parameters, this can be a real problem - type
179 /// parameters don't unify with regular types, but they *can* unify
180 /// with variables from blanket impls, and (unless we know its bounds
181 /// will always be satisfied) picking the blanket impl will be wrong
182 /// for at least *some* substitutions. To make this concrete, if we have
184 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
185 /// impl<T: fmt::Debug> AsDebug for T {
187 /// fn debug(self) -> fmt::Debug { self }
189 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
191 /// we can't just use the impl to resolve the <T as AsDebug> obligation
192 /// - a type from another crate (that doesn't implement fmt::Debug) could
193 /// implement AsDebug.
195 /// Because where-clauses match the type exactly, multiple clauses can
196 /// only match if there are unresolved variables, and we can mostly just
197 /// report this ambiguity in that case. This is still a problem - we can't
198 /// *do anything* with ambiguities that involve only regions. This is issue
201 /// If a single where-clause matches and there are no inference
202 /// variables left, then it definitely matches and we can just select
205 /// In fact, we even select the where-clause when the obligation contains
206 /// inference variables. The can lead to inference making "leaps of logic",
207 /// for example in this situation:
209 /// pub trait Foo<T> { fn foo(&self) -> T; }
210 /// impl<T> Foo<()> for T { fn foo(&self) { } }
211 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
213 /// pub fn foo<T>(t: T) where T: Foo<bool> {
214 /// println!("{:?}", <T as Foo<_>>::foo(&t));
216 /// fn main() { foo(false); }
218 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
219 /// impl and the where-clause. We select the where-clause and unify $0=bool,
220 /// so the program prints "false". However, if the where-clause is omitted,
221 /// the blanket impl is selected, we unify $0=(), and the program prints
224 /// Exactly the same issues apply to projection and object candidates, except
225 /// that we can have both a projection candidate and a where-clause candidate
226 /// for the same obligation. In that case either would do (except that
227 /// different "leaps of logic" would occur if inference variables are
228 /// present), and we just pick the where-clause. This is, for example,
229 /// required for associated types to work in default impls, as the bounds
230 /// are visible both as projection bounds and as where-clauses from the
231 /// parameter environment.
232 #[derive(PartialEq,Eq,Debug,Clone)]
233 enum SelectionCandidate<'tcx> {
234 BuiltinCandidate { has_nested: bool },
235 ParamCandidate(ty::PolyTraitRef<'tcx>),
236 ImplCandidate(DefId),
237 AutoImplCandidate(DefId),
239 /// This is a trait matching with a projected type as `Self`, and
240 /// we found an applicable bound in the trait definition.
243 /// Implementation of a `Fn`-family trait by one of the anonymous types
244 /// generated for a `||` expression.
247 /// Implementation of a `Generator` trait by one of the anonymous types
248 /// generated for a generator.
251 /// Implementation of a `Fn`-family trait by one of the anonymous
252 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
257 BuiltinObjectCandidate,
259 BuiltinUnsizeCandidate,
262 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
263 type Lifted = SelectionCandidate<'tcx>;
264 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
266 BuiltinCandidate { has_nested } => {
271 ImplCandidate(def_id) => ImplCandidate(def_id),
272 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
273 ProjectionCandidate => ProjectionCandidate,
274 FnPointerCandidate => FnPointerCandidate,
275 ObjectCandidate => ObjectCandidate,
276 BuiltinObjectCandidate => BuiltinObjectCandidate,
277 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
278 ClosureCandidate => ClosureCandidate,
279 GeneratorCandidate => GeneratorCandidate,
281 ParamCandidate(ref trait_ref) => {
282 return tcx.lift(trait_ref).map(ParamCandidate);
288 struct SelectionCandidateSet<'tcx> {
289 // a list of candidates that definitely apply to the current
290 // obligation (meaning: types unify).
291 vec: Vec<SelectionCandidate<'tcx>>,
293 // if this is true, then there were candidates that might or might
294 // not have applied, but we couldn't tell. This occurs when some
295 // of the input types are type variables, in which case there are
296 // various "builtin" rules that might or might not trigger.
300 #[derive(PartialEq,Eq,Debug,Clone)]
301 struct EvaluatedCandidate<'tcx> {
302 candidate: SelectionCandidate<'tcx>,
303 evaluation: EvaluationResult,
306 /// When does the builtin impl for `T: Trait` apply?
307 enum BuiltinImplConditions<'tcx> {
308 /// The impl is conditional on T1,T2,.. : Trait
309 Where(ty::Binder<Vec<Ty<'tcx>>>),
310 /// There is no built-in impl. There may be some other
311 /// candidate (a where-clause or user-defined impl).
313 /// There is *no* impl for this, builtin or not. Ignore
314 /// all where-clauses.
316 /// It is unknown whether there is an impl.
320 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
321 /// The result of trait evaluation. The order is important
322 /// here as the evaluation of a list is the maximum of the
325 /// The evaluation results are ordered:
326 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
327 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
328 /// - the "union" of evaluation results is equal to their maximum -
329 /// all the "potential success" candidates can potentially succeed,
330 /// so they are no-ops when unioned with a definite error, and within
331 /// the categories it's easy to see that the unions are correct.
332 enum EvaluationResult {
333 /// Evaluation successful
335 /// Evaluation is known to be ambiguous - it *might* hold for some
336 /// assignment of inference variables, but it might not.
338 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
339 /// know whether this obligation holds or not - it is the result we
340 /// would get with an empty stack, and therefore is cacheable.
342 /// Evaluation failed because of recursion involving inference
343 /// variables. We are somewhat imprecise there, so we don't actually
344 /// know the real result.
346 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
348 /// Evaluation failed because we encountered an obligation we are already
349 /// trying to prove on this branch.
351 /// We know this branch can't be a part of a minimal proof-tree for
352 /// the "root" of our cycle, because then we could cut out the recursion
353 /// and maintain a valid proof tree. However, this does not mean
354 /// that all the obligations on this branch do not hold - it's possible
355 /// that we entered this branch "speculatively", and that there
356 /// might be some other way to prove this obligation that does not
357 /// go through this cycle - so we can't cache this as a failure.
359 /// For example, suppose we have this:
361 /// ```rust,ignore (pseudo-Rust)
362 /// pub trait Trait { fn xyz(); }
363 /// // This impl is "useless", but we can still have
364 /// // an `impl Trait for SomeUnsizedType` somewhere.
365 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
367 /// pub fn foo<T: Trait + ?Sized>() {
368 /// <T as Trait>::xyz();
372 /// When checking `foo`, we have to prove `T: Trait`. This basically
373 /// translates into this:
375 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
377 /// When we try to prove it, we first go the first option, which
378 /// recurses. This shows us that the impl is "useless" - it won't
379 /// tell us that `T: Trait` unless it already implemented `Trait`
380 /// by some other means. However, that does not prevent `T: Trait`
381 /// does not hold, because of the bound (which can indeed be satisfied
382 /// by `SomeUnsizedType` from another crate).
384 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
385 /// ought to convert it to an `EvaluatedToErr`, because we know
386 /// there definitely isn't a proof tree for that obligation. Not
387 /// doing so is still sound - there isn't any proof tree, so the
388 /// branch still can't be a part of a minimal one - but does not
389 /// re-enable caching.
391 /// Evaluation failed
395 impl EvaluationResult {
396 fn may_apply(self) -> bool {
400 EvaluatedToUnknown => true,
403 EvaluatedToRecur => false
407 fn is_stack_dependent(self) -> bool {
410 EvaluatedToRecur => true,
414 EvaluatedToErr => false,
420 pub struct EvaluationCache<'tcx> {
421 hashmap: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>
424 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
425 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
428 freshener: infcx.freshener(),
430 inferred_obligations: SnapshotVec::new(),
431 intercrate_ambiguity_causes: None,
432 allow_negative_impls: false,
436 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
437 mode: IntercrateMode) -> SelectionContext<'cx, 'gcx, 'tcx> {
438 debug!("intercrate({:?})", mode);
441 freshener: infcx.freshener(),
442 intercrate: Some(mode),
443 inferred_obligations: SnapshotVec::new(),
444 intercrate_ambiguity_causes: None,
445 allow_negative_impls: false,
449 pub fn with_negative(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
450 allow_negative_impls: bool) -> SelectionContext<'cx, 'gcx, 'tcx> {
451 debug!("with_negative({:?})", allow_negative_impls);
454 freshener: infcx.freshener(),
456 inferred_obligations: SnapshotVec::new(),
457 intercrate_ambiguity_causes: None,
458 allow_negative_impls,
462 /// Enables tracking of intercrate ambiguity causes. These are
463 /// used in coherence to give improved diagnostics. We don't do
464 /// this until we detect a coherence error because it can lead to
465 /// false overflow results (#47139) and because it costs
466 /// computation time.
467 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
468 assert!(self.intercrate.is_some());
469 assert!(self.intercrate_ambiguity_causes.is_none());
470 self.intercrate_ambiguity_causes = Some(vec![]);
471 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
474 /// Gets the intercrate ambiguity causes collected since tracking
475 /// was enabled and disables tracking at the same time. If
476 /// tracking is not enabled, just returns an empty vector.
477 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
478 assert!(self.intercrate.is_some());
479 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
482 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
486 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
490 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
494 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
496 fn in_snapshot<R, F>(&mut self, f: F) -> R
497 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
499 // The irrefutable nature of the operation means we don't need to snapshot the
500 // inferred_obligations vector.
501 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
504 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
506 fn probe<R, F>(&mut self, f: F) -> R
507 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
509 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
510 let result = self.infcx.probe(|snapshot| f(self, snapshot));
511 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
515 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
516 /// the transaction fails and s.t. old obligations are retained.
517 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
518 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
520 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
521 match self.infcx.commit_if_ok(|snapshot| f(self, snapshot)) {
523 self.inferred_obligations.commit(inferred_obligations_snapshot);
527 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
534 ///////////////////////////////////////////////////////////////////////////
537 // The selection phase tries to identify *how* an obligation will
538 // be resolved. For example, it will identify which impl or
539 // parameter bound is to be used. The process can be inconclusive
540 // if the self type in the obligation is not fully inferred. Selection
541 // can result in an error in one of two ways:
543 // 1. If no applicable impl or parameter bound can be found.
544 // 2. If the output type parameters in the obligation do not match
545 // those specified by the impl/bound. For example, if the obligation
546 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
547 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
549 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
550 /// type environment by performing unification.
551 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
552 -> SelectionResult<'tcx, Selection<'tcx>> {
553 debug!("select({:?})", obligation);
554 assert!(!obligation.predicate.has_escaping_regions());
556 let tcx = self.tcx();
558 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
559 let ret = match self.candidate_from_obligation(&stack)? {
562 let mut candidate = self.confirm_candidate(obligation, candidate)?;
563 let inferred_obligations = (*self.inferred_obligations).into_iter().cloned();
564 candidate.nested_obligations_mut().extend(inferred_obligations);
569 // Test whether this is a `()` which was produced by defaulting a
570 // diverging type variable with `!` disabled. If so, we may need
571 // to raise a warning.
572 if obligation.predicate.skip_binder().self_ty().is_defaulted_unit() {
573 let mut raise_warning = true;
574 // Don't raise a warning if the trait is implemented for ! and only
575 // permits a trivial implementation for !. This stops us warning
576 // about (for example) `(): Clone` becoming `!: Clone` because such
577 // a switch can't cause code to stop compiling or execute
579 let mut never_obligation = obligation.clone();
580 let def_id = never_obligation.predicate.skip_binder().trait_ref.def_id;
581 never_obligation.predicate = never_obligation.predicate.map_bound(|mut trait_pred| {
582 // Swap out () with ! so we can check if the trait is impld for !
584 let trait_ref = &mut trait_pred.trait_ref;
585 let unit_substs = trait_ref.substs;
586 let mut never_substs = Vec::with_capacity(unit_substs.len());
587 never_substs.push(tcx.types.never.into());
588 never_substs.extend(&unit_substs[1..]);
589 trait_ref.substs = tcx.intern_substs(&never_substs);
593 if let Ok(Some(..)) = self.select(&never_obligation) {
594 if !tcx.trait_relevant_for_never(def_id) {
595 // The trait is also implemented for ! and the resulting
596 // implementation cannot actually be invoked in any way.
597 raise_warning = false;
602 tcx.lint_node(lint::builtin::RESOLVE_TRAIT_ON_DEFAULTED_UNIT,
603 obligation.cause.body_id,
604 obligation.cause.span,
605 &format!("code relies on type inference rules which are likely \
612 ///////////////////////////////////////////////////////////////////////////
615 // Tests whether an obligation can be selected or whether an impl
616 // can be applied to particular types. It skips the "confirmation"
617 // step and hence completely ignores output type parameters.
619 // The result is "true" if the obligation *may* hold and "false" if
620 // we can be sure it does not.
622 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
623 pub fn evaluate_obligation(&mut self,
624 obligation: &PredicateObligation<'tcx>)
627 debug!("evaluate_obligation({:?})",
630 self.probe(|this, _| {
631 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
636 /// Evaluates whether the obligation `obligation` can be satisfied,
637 /// and returns `false` if not certain. However, this is not entirely
638 /// accurate if inference variables are involved.
639 pub fn evaluate_obligation_conservatively(&mut self,
640 obligation: &PredicateObligation<'tcx>)
643 debug!("evaluate_obligation_conservatively({:?})",
646 self.probe(|this, _| {
647 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
652 /// Evaluates the predicates in `predicates` recursively. Note that
653 /// this applies projections in the predicates, and therefore
654 /// is run within an inference probe.
655 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
656 stack: TraitObligationStackList<'o, 'tcx>,
659 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
661 let mut result = EvaluatedToOk;
662 for obligation in predicates {
663 let eval = self.evaluate_predicate_recursively(stack, obligation);
664 debug!("evaluate_predicate_recursively({:?}) = {:?}",
666 if let EvaluatedToErr = eval {
667 // fast-path - EvaluatedToErr is the top of the lattice,
668 // so we don't need to look on the other predicates.
669 return EvaluatedToErr;
671 result = cmp::max(result, eval);
677 fn evaluate_predicate_recursively<'o>(&mut self,
678 previous_stack: TraitObligationStackList<'o, 'tcx>,
679 obligation: &PredicateObligation<'tcx>)
682 debug!("evaluate_predicate_recursively({:?})",
685 match obligation.predicate {
686 ty::Predicate::Trait(ref t) => {
687 assert!(!t.has_escaping_regions());
688 let obligation = obligation.with(t.clone());
689 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
692 ty::Predicate::Equate(ref p) => {
693 // does this code ever run?
694 match self.infcx.equality_predicate(&obligation.cause, obligation.param_env, p) {
695 Ok(InferOk { obligations, .. }) => {
696 self.inferred_obligations.extend(obligations);
699 Err(_) => EvaluatedToErr
703 ty::Predicate::Subtype(ref p) => {
704 // does this code ever run?
705 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
706 Some(Ok(InferOk { obligations, .. })) => {
707 self.inferred_obligations.extend(obligations);
710 Some(Err(_)) => EvaluatedToErr,
711 None => EvaluatedToAmbig,
715 ty::Predicate::WellFormed(ty) => {
716 match ty::wf::obligations(self.infcx,
717 obligation.param_env,
718 obligation.cause.body_id,
719 ty, obligation.cause.span) {
721 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
727 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
728 // we do not consider region relationships when
729 // evaluating trait matches
733 ty::Predicate::ObjectSafe(trait_def_id) => {
734 if self.tcx().is_object_safe(trait_def_id) {
741 ty::Predicate::Projection(ref data) => {
742 let project_obligation = obligation.with(data.clone());
743 match project::poly_project_and_unify_type(self, &project_obligation) {
744 Ok(Some(subobligations)) => {
745 let result = self.evaluate_predicates_recursively(previous_stack,
746 subobligations.iter());
748 ProjectionCacheKey::from_poly_projection_predicate(self, data)
750 self.infcx.projection_cache.borrow_mut().complete(key);
763 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
764 match self.infcx.closure_kind(closure_def_id, closure_substs) {
765 Some(closure_kind) => {
766 if closure_kind.extends(kind) {
778 ty::Predicate::ConstEvaluatable(def_id, substs) => {
779 match self.tcx().lift_to_global(&(obligation.param_env, substs)) {
780 Some((param_env, substs)) => {
781 match self.tcx().const_eval(param_env.and((def_id, substs))) {
782 Ok(_) => EvaluatedToOk,
783 Err(_) => EvaluatedToErr
787 // Inference variables still left in param_env or substs.
795 fn evaluate_trait_predicate_recursively<'o>(&mut self,
796 previous_stack: TraitObligationStackList<'o, 'tcx>,
797 mut obligation: TraitObligation<'tcx>)
800 debug!("evaluate_trait_predicate_recursively({:?})",
803 if !self.intercrate.is_some() && obligation.is_global() {
804 // If a param env is consistent, global obligations do not depend on its particular
805 // value in order to work, so we can clear out the param env and get better
806 // caching. (If the current param env is inconsistent, we don't care what happens).
807 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
808 obligation.param_env = ty::ParamEnv::empty(obligation.param_env.reveal);
811 let stack = self.push_stack(previous_stack, &obligation);
812 let fresh_trait_ref = stack.fresh_trait_ref;
813 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
814 debug!("CACHE HIT: EVAL({:?})={:?}",
820 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
822 debug!("CACHE MISS: EVAL({:?})={:?}",
825 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
830 fn evaluate_stack<'o>(&mut self,
831 stack: &TraitObligationStack<'o, 'tcx>)
834 // In intercrate mode, whenever any of the types are unbound,
835 // there can always be an impl. Even if there are no impls in
836 // this crate, perhaps the type would be unified with
837 // something from another crate that does provide an impl.
839 // In intra mode, we must still be conservative. The reason is
840 // that we want to avoid cycles. Imagine an impl like:
842 // impl<T:Eq> Eq for Vec<T>
844 // and a trait reference like `$0 : Eq` where `$0` is an
845 // unbound variable. When we evaluate this trait-reference, we
846 // will unify `$0` with `Vec<$1>` (for some fresh variable
847 // `$1`), on the condition that `$1 : Eq`. We will then wind
848 // up with many candidates (since that are other `Eq` impls
849 // that apply) and try to winnow things down. This results in
850 // a recursive evaluation that `$1 : Eq` -- as you can
851 // imagine, this is just where we started. To avoid that, we
852 // check for unbound variables and return an ambiguous (hence possible)
853 // match if we've seen this trait before.
855 // This suffices to allow chains like `FnMut` implemented in
856 // terms of `Fn` etc, but we could probably make this more
858 let unbound_input_types = stack.fresh_trait_ref.input_types().any(|ty| ty.is_fresh());
859 // this check was an imperfect workaround for a bug n the old
860 // intercrate mode, it should be removed when that goes away.
861 if unbound_input_types &&
862 self.intercrate == Some(IntercrateMode::Issue43355)
864 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
865 stack.fresh_trait_ref);
866 // Heuristics: show the diagnostics when there are no candidates in crate.
867 if self.intercrate_ambiguity_causes.is_some() {
868 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
869 if let Ok(candidate_set) = self.assemble_candidates(stack) {
870 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
871 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
872 let self_ty = trait_ref.self_ty();
873 let cause = IntercrateAmbiguityCause::DownstreamCrate {
874 trait_desc: trait_ref.to_string(),
875 self_desc: if self_ty.has_concrete_skeleton() {
876 Some(self_ty.to_string())
881 debug!("evaluate_stack: pushing cause = {:?}", cause);
882 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
886 return EvaluatedToAmbig;
888 if unbound_input_types &&
889 stack.iter().skip(1).any(
890 |prev| stack.obligation.param_env == prev.obligation.param_env &&
891 self.match_fresh_trait_refs(&stack.fresh_trait_ref,
892 &prev.fresh_trait_ref))
894 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
895 stack.fresh_trait_ref);
896 return EvaluatedToUnknown;
899 // If there is any previous entry on the stack that precisely
900 // matches this obligation, then we can assume that the
901 // obligation is satisfied for now (still all other conditions
902 // must be met of course). One obvious case this comes up is
903 // marker traits like `Send`. Think of a linked list:
905 // struct List<T> { data: T, next: Option<Box<List<T>>> {
907 // `Box<List<T>>` will be `Send` if `T` is `Send` and
908 // `Option<Box<List<T>>>` is `Send`, and in turn
909 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
912 // Note that we do this comparison using the `fresh_trait_ref`
913 // fields. Because these have all been skolemized using
914 // `self.freshener`, we can be sure that (a) this will not
915 // affect the inferencer state and (b) that if we see two
916 // skolemized types with the same index, they refer to the
917 // same unbound type variable.
918 if let Some(rec_index) =
920 .skip(1) // skip top-most frame
921 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
922 stack.fresh_trait_ref == prev.fresh_trait_ref)
924 debug!("evaluate_stack({:?}) --> recursive",
925 stack.fresh_trait_ref);
926 let cycle = stack.iter().skip(1).take(rec_index+1);
927 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
928 if self.coinductive_match(cycle) {
929 debug!("evaluate_stack({:?}) --> recursive, coinductive",
930 stack.fresh_trait_ref);
931 return EvaluatedToOk;
933 debug!("evaluate_stack({:?}) --> recursive, inductive",
934 stack.fresh_trait_ref);
935 return EvaluatedToRecur;
939 match self.candidate_from_obligation(stack) {
940 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
941 Ok(None) => EvaluatedToAmbig,
942 Err(..) => EvaluatedToErr
946 /// For defaulted traits, we use a co-inductive strategy to solve, so
947 /// that recursion is ok. This routine returns true if the top of the
948 /// stack (`cycle[0]`):
950 /// - is a defaulted trait, and
951 /// - it also appears in the backtrace at some position `X`; and,
952 /// - all the predicates at positions `X..` between `X` an the top are
953 /// also defaulted traits.
954 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
955 where I: Iterator<Item=ty::Predicate<'tcx>>
957 let mut cycle = cycle;
958 cycle.all(|predicate| self.coinductive_predicate(predicate))
961 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
962 let result = match predicate {
963 ty::Predicate::Trait(ref data) => {
964 self.tcx().trait_is_auto(data.def_id())
970 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
974 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
975 /// obligations are met. Returns true if `candidate` remains viable after this further
977 fn evaluate_candidate<'o>(&mut self,
978 stack: &TraitObligationStack<'o, 'tcx>,
979 candidate: &SelectionCandidate<'tcx>)
982 debug!("evaluate_candidate: depth={} candidate={:?}",
983 stack.obligation.recursion_depth, candidate);
984 let result = self.probe(|this, _| {
985 let candidate = (*candidate).clone();
986 match this.confirm_candidate(stack.obligation, candidate) {
988 this.evaluate_predicates_recursively(
990 selection.nested_obligations().iter())
992 Err(..) => EvaluatedToErr
995 debug!("evaluate_candidate: depth={} result={:?}",
996 stack.obligation.recursion_depth, result);
1000 fn check_evaluation_cache(&self,
1001 param_env: ty::ParamEnv<'tcx>,
1002 trait_ref: ty::PolyTraitRef<'tcx>)
1003 -> Option<EvaluationResult>
1005 let tcx = self.tcx();
1006 if self.can_use_global_caches(param_env) {
1007 let cache = tcx.evaluation_cache.hashmap.borrow();
1008 if let Some(cached) = cache.get(&trait_ref) {
1009 return Some(cached.get(tcx));
1012 self.infcx.evaluation_cache.hashmap
1015 .map(|v| v.get(tcx))
1018 fn insert_evaluation_cache(&mut self,
1019 param_env: ty::ParamEnv<'tcx>,
1020 trait_ref: ty::PolyTraitRef<'tcx>,
1021 dep_node: DepNodeIndex,
1022 result: EvaluationResult)
1024 // Avoid caching results that depend on more than just the trait-ref
1025 // - the stack can create recursion.
1026 if result.is_stack_dependent() {
1030 if self.can_use_global_caches(param_env) {
1031 let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
1032 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1033 cache.insert(trait_ref, WithDepNode::new(dep_node, result));
1038 self.infcx.evaluation_cache.hashmap
1040 .insert(trait_ref, WithDepNode::new(dep_node, result));
1043 ///////////////////////////////////////////////////////////////////////////
1044 // CANDIDATE ASSEMBLY
1046 // The selection process begins by examining all in-scope impls,
1047 // caller obligations, and so forth and assembling a list of
1048 // candidates. See `README.md` and the `Candidate` type for more
1051 fn candidate_from_obligation<'o>(&mut self,
1052 stack: &TraitObligationStack<'o, 'tcx>)
1053 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1055 // Watch out for overflow. This intentionally bypasses (and does
1056 // not update) the cache.
1057 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
1058 if stack.obligation.recursion_depth >= recursion_limit {
1059 self.infcx().report_overflow_error(&stack.obligation, true);
1062 // Check the cache. Note that we skolemize the trait-ref
1063 // separately rather than using `stack.fresh_trait_ref` -- this
1064 // is because we want the unbound variables to be replaced
1065 // with fresh skolemized types starting from index 0.
1066 let cache_fresh_trait_pred =
1067 self.infcx.freshen(stack.obligation.predicate.clone());
1068 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1069 cache_fresh_trait_pred,
1071 assert!(!stack.obligation.predicate.has_escaping_regions());
1073 if let Some(c) = self.check_candidate_cache(stack.obligation.param_env,
1074 &cache_fresh_trait_pred) {
1075 debug!("CACHE HIT: SELECT({:?})={:?}",
1076 cache_fresh_trait_pred,
1081 // If no match, compute result and insert into cache.
1082 let (candidate, dep_node) = self.in_task(|this| {
1083 this.candidate_from_obligation_no_cache(stack)
1086 debug!("CACHE MISS: SELECT({:?})={:?}",
1087 cache_fresh_trait_pred, candidate);
1088 self.insert_candidate_cache(stack.obligation.param_env,
1089 cache_fresh_trait_pred,
1095 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1096 where OP: FnOnce(&mut Self) -> R
1098 let (result, dep_node) = self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || {
1101 self.tcx().dep_graph.read_index(dep_node);
1105 // Treat negative impls as unimplemented
1106 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
1107 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1108 if let ImplCandidate(def_id) = candidate {
1109 if !self.allow_negative_impls &&
1110 self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative {
1111 return Err(Unimplemented)
1117 fn candidate_from_obligation_no_cache<'o>(&mut self,
1118 stack: &TraitObligationStack<'o, 'tcx>)
1119 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1121 if stack.obligation.predicate.references_error() {
1122 // If we encounter a `TyError`, we generally prefer the
1123 // most "optimistic" result in response -- that is, the
1124 // one least likely to report downstream errors. But
1125 // because this routine is shared by coherence and by
1126 // trait selection, there isn't an obvious "right" choice
1127 // here in that respect, so we opt to just return
1128 // ambiguity and let the upstream clients sort it out.
1132 match self.is_knowable(stack) {
1135 debug!("coherence stage: not knowable");
1136 if self.intercrate_ambiguity_causes.is_some() {
1137 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1138 // Heuristics: show the diagnostics when there are no candidates in crate.
1139 let candidate_set = self.assemble_candidates(stack)?;
1140 if !candidate_set.ambiguous && candidate_set.vec.iter().all(|c| {
1141 !self.evaluate_candidate(stack, &c).may_apply()
1143 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1144 let self_ty = trait_ref.self_ty();
1145 let trait_desc = trait_ref.to_string();
1146 let self_desc = if self_ty.has_concrete_skeleton() {
1147 Some(self_ty.to_string())
1151 let cause = if let Conflict::Upstream = conflict {
1152 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1154 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1156 debug!("evaluate_stack: pushing cause = {:?}", cause);
1157 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1164 let candidate_set = self.assemble_candidates(stack)?;
1166 if candidate_set.ambiguous {
1167 debug!("candidate set contains ambig");
1171 let mut candidates = candidate_set.vec;
1173 debug!("assembled {} candidates for {:?}: {:?}",
1178 // At this point, we know that each of the entries in the
1179 // candidate set is *individually* applicable. Now we have to
1180 // figure out if they contain mutual incompatibilities. This
1181 // frequently arises if we have an unconstrained input type --
1182 // for example, we are looking for $0:Eq where $0 is some
1183 // unconstrained type variable. In that case, we'll get a
1184 // candidate which assumes $0 == int, one that assumes $0 ==
1185 // usize, etc. This spells an ambiguity.
1187 // If there is more than one candidate, first winnow them down
1188 // by considering extra conditions (nested obligations and so
1189 // forth). We don't winnow if there is exactly one
1190 // candidate. This is a relatively minor distinction but it
1191 // can lead to better inference and error-reporting. An
1192 // example would be if there was an impl:
1194 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1196 // and we were to see some code `foo.push_clone()` where `boo`
1197 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1198 // we were to winnow, we'd wind up with zero candidates.
1199 // Instead, we select the right impl now but report `Bar does
1200 // not implement Clone`.
1201 if candidates.len() == 1 {
1202 return self.filter_negative_impls(candidates.pop().unwrap());
1205 // Winnow, but record the exact outcome of evaluation, which
1206 // is needed for specialization.
1207 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
1208 let eval = self.evaluate_candidate(stack, &c);
1209 if eval.may_apply() {
1210 Some(EvaluatedCandidate {
1219 // If there are STILL multiple candidate, we can further
1220 // reduce the list by dropping duplicates -- including
1221 // resolving specializations.
1222 if candidates.len() > 1 {
1224 while i < candidates.len() {
1226 (0..candidates.len())
1227 .filter(|&j| i != j)
1228 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
1231 debug!("Dropping candidate #{}/{}: {:?}",
1232 i, candidates.len(), candidates[i]);
1233 candidates.swap_remove(i);
1235 debug!("Retaining candidate #{}/{}: {:?}",
1236 i, candidates.len(), candidates[i]);
1239 // If there are *STILL* multiple candidates, give up
1240 // and report ambiguity.
1242 debug!("multiple matches, ambig");
1249 // If there are *NO* candidates, then there are no impls --
1250 // that we know of, anyway. Note that in the case where there
1251 // are unbound type variables within the obligation, it might
1252 // be the case that you could still satisfy the obligation
1253 // from another crate by instantiating the type variables with
1254 // a type from another crate that does have an impl. This case
1255 // is checked for in `evaluate_stack` (and hence users
1256 // who might care about this case, like coherence, should use
1258 if candidates.is_empty() {
1259 return Err(Unimplemented);
1262 // Just one candidate left.
1263 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1266 fn is_knowable<'o>(&mut self,
1267 stack: &TraitObligationStack<'o, 'tcx>)
1270 debug!("is_knowable(intercrate={:?})", self.intercrate);
1272 if !self.intercrate.is_some() {
1276 let obligation = &stack.obligation;
1277 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1279 // ok to skip binder because of the nature of the
1280 // trait-ref-is-knowable check, which does not care about
1282 let trait_ref = predicate.skip_binder().trait_ref;
1284 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1285 if let (Some(Conflict::Downstream { used_to_be_broken: true }),
1286 Some(IntercrateMode::Issue43355)) = (result, self.intercrate) {
1287 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1294 /// Returns true if the global caches can be used.
1295 /// Do note that if the type itself is not in the
1296 /// global tcx, the local caches will be used.
1297 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1298 // If there are any where-clauses in scope, then we always use
1299 // a cache local to this particular scope. Otherwise, we
1300 // switch to a global cache. We used to try and draw
1301 // finer-grained distinctions, but that led to a serious of
1302 // annoying and weird bugs like #22019 and #18290. This simple
1303 // rule seems to be pretty clearly safe and also still retains
1304 // a very high hit rate (~95% when compiling rustc).
1305 if !param_env.caller_bounds.is_empty() {
1309 // Avoid using the master cache during coherence and just rely
1310 // on the local cache. This effectively disables caching
1311 // during coherence. It is really just a simplification to
1312 // avoid us having to fear that coherence results "pollute"
1313 // the master cache. Since coherence executes pretty quickly,
1314 // it's not worth going to more trouble to increase the
1315 // hit-rate I don't think.
1316 if self.intercrate.is_some() {
1320 // Otherwise, we can use the global cache.
1324 fn check_candidate_cache(&mut self,
1325 param_env: ty::ParamEnv<'tcx>,
1326 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1327 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1329 let tcx = self.tcx();
1330 let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1331 if self.can_use_global_caches(param_env) {
1332 let cache = tcx.selection_cache.hashmap.borrow();
1333 if let Some(cached) = cache.get(&trait_ref) {
1334 return Some(cached.get(tcx));
1337 self.infcx.selection_cache.hashmap
1340 .map(|v| v.get(tcx))
1343 fn insert_candidate_cache(&mut self,
1344 param_env: ty::ParamEnv<'tcx>,
1345 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1346 dep_node: DepNodeIndex,
1347 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1349 let tcx = self.tcx();
1350 let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1351 if self.can_use_global_caches(param_env) {
1352 let mut cache = tcx.selection_cache.hashmap.borrow_mut();
1353 if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1354 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1355 cache.insert(trait_ref, WithDepNode::new(dep_node, candidate));
1361 self.infcx.selection_cache.hashmap
1363 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1366 fn assemble_candidates<'o>(&mut self,
1367 stack: &TraitObligationStack<'o, 'tcx>)
1368 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1370 let TraitObligationStack { obligation, .. } = *stack;
1371 let ref obligation = Obligation {
1372 param_env: obligation.param_env,
1373 cause: obligation.cause.clone(),
1374 recursion_depth: obligation.recursion_depth,
1375 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1378 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1379 // Self is a type variable (e.g. `_: AsRef<str>`).
1381 // This is somewhat problematic, as the current scheme can't really
1382 // handle it turning to be a projection. This does end up as truly
1383 // ambiguous in most cases anyway.
1385 // Take the fast path out - this also improves
1386 // performance by preventing assemble_candidates_from_impls from
1387 // matching every impl for this trait.
1388 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1391 let mut candidates = SelectionCandidateSet {
1396 // Other bounds. Consider both in-scope bounds from fn decl
1397 // and applicable impls. There is a certain set of precedence rules here.
1399 let def_id = obligation.predicate.def_id();
1400 let lang_items = self.tcx().lang_items();
1401 if lang_items.copy_trait() == Some(def_id) {
1402 debug!("obligation self ty is {:?}",
1403 obligation.predicate.0.self_ty());
1405 // User-defined copy impls are permitted, but only for
1406 // structs and enums.
1407 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1409 // For other types, we'll use the builtin rules.
1410 let copy_conditions = self.copy_clone_conditions(obligation);
1411 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1412 } else if lang_items.sized_trait() == Some(def_id) {
1413 // Sized is never implementable by end-users, it is
1414 // always automatically computed.
1415 let sized_conditions = self.sized_conditions(obligation);
1416 self.assemble_builtin_bound_candidates(sized_conditions,
1418 } else if lang_items.unsize_trait() == Some(def_id) {
1419 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1421 if lang_items.clone_trait() == Some(def_id) {
1422 // Same builtin conditions as `Copy`, i.e. every type which has builtin support
1423 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1424 // types have builtin support for `Clone`.
1425 let clone_conditions = self.copy_clone_conditions(obligation);
1426 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1429 self.assemble_generator_candidates(obligation, &mut candidates)?;
1430 self.assemble_closure_candidates(obligation, &mut candidates)?;
1431 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1432 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1433 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1436 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1437 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1438 // Auto implementations have lower priority, so we only
1439 // consider triggering a default if there is no other impl that can apply.
1440 if candidates.vec.is_empty() {
1441 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1443 debug!("candidate list size: {}", candidates.vec.len());
1447 fn assemble_candidates_from_projected_tys(&mut self,
1448 obligation: &TraitObligation<'tcx>,
1449 candidates: &mut SelectionCandidateSet<'tcx>)
1451 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1453 // before we go into the whole skolemization thing, just
1454 // quickly check if the self-type is a projection at all.
1455 match obligation.predicate.0.trait_ref.self_ty().sty {
1456 ty::TyProjection(_) | ty::TyAnon(..) => {}
1457 ty::TyInfer(ty::TyVar(_)) => {
1458 span_bug!(obligation.cause.span,
1459 "Self=_ should have been handled by assemble_candidates");
1464 let result = self.probe(|this, snapshot| {
1465 this.match_projection_obligation_against_definition_bounds(obligation,
1470 candidates.vec.push(ProjectionCandidate);
1474 fn match_projection_obligation_against_definition_bounds(
1476 obligation: &TraitObligation<'tcx>,
1477 snapshot: &infer::CombinedSnapshot)
1480 let poly_trait_predicate =
1481 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1482 let (skol_trait_predicate, skol_map) =
1483 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1484 debug!("match_projection_obligation_against_definition_bounds: \
1485 skol_trait_predicate={:?} skol_map={:?}",
1486 skol_trait_predicate,
1489 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1490 ty::TyProjection(ref data) =>
1491 (data.trait_ref(self.tcx()).def_id, data.substs),
1492 ty::TyAnon(def_id, substs) => (def_id, substs),
1495 obligation.cause.span,
1496 "match_projection_obligation_against_definition_bounds() called \
1497 but self-ty not a projection: {:?}",
1498 skol_trait_predicate.trait_ref.self_ty());
1501 debug!("match_projection_obligation_against_definition_bounds: \
1502 def_id={:?}, substs={:?}",
1505 let predicates_of = self.tcx().predicates_of(def_id);
1506 let bounds = predicates_of.instantiate(self.tcx(), substs);
1507 debug!("match_projection_obligation_against_definition_bounds: \
1511 let matching_bound =
1512 util::elaborate_predicates(self.tcx(), bounds.predicates)
1516 |this, _| this.match_projection(obligation,
1518 skol_trait_predicate.trait_ref.clone(),
1522 debug!("match_projection_obligation_against_definition_bounds: \
1523 matching_bound={:?}",
1525 match matching_bound {
1528 // Repeat the successful match, if any, this time outside of a probe.
1529 let result = self.match_projection(obligation,
1531 skol_trait_predicate.trait_ref.clone(),
1535 self.infcx.pop_skolemized(skol_map, snapshot);
1543 fn match_projection(&mut self,
1544 obligation: &TraitObligation<'tcx>,
1545 trait_bound: ty::PolyTraitRef<'tcx>,
1546 skol_trait_ref: ty::TraitRef<'tcx>,
1547 skol_map: &infer::SkolemizationMap<'tcx>,
1548 snapshot: &infer::CombinedSnapshot)
1551 assert!(!skol_trait_ref.has_escaping_regions());
1552 match self.infcx.at(&obligation.cause, obligation.param_env)
1553 .sup(ty::Binder(skol_trait_ref), trait_bound) {
1554 Ok(InferOk { obligations, .. }) => {
1555 self.inferred_obligations.extend(obligations);
1557 Err(_) => { return false; }
1560 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1563 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1564 /// supplied to find out whether it is listed among them.
1566 /// Never affects inference environment.
1567 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1568 stack: &TraitObligationStack<'o, 'tcx>,
1569 candidates: &mut SelectionCandidateSet<'tcx>)
1570 -> Result<(),SelectionError<'tcx>>
1572 debug!("assemble_candidates_from_caller_bounds({:?})",
1576 stack.obligation.param_env.caller_bounds
1578 .filter_map(|o| o.to_opt_poly_trait_ref());
1580 // micro-optimization: filter out predicates relating to different
1582 let matching_bounds =
1583 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1585 let matching_bounds =
1586 matching_bounds.filter(
1587 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1589 let param_candidates =
1590 matching_bounds.map(|bound| ParamCandidate(bound));
1592 candidates.vec.extend(param_candidates);
1597 fn evaluate_where_clause<'o>(&mut self,
1598 stack: &TraitObligationStack<'o, 'tcx>,
1599 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1602 self.probe(move |this, _| {
1603 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1604 Ok(obligations) => {
1605 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1607 Err(()) => EvaluatedToErr
1612 fn assemble_generator_candidates(&mut self,
1613 obligation: &TraitObligation<'tcx>,
1614 candidates: &mut SelectionCandidateSet<'tcx>)
1615 -> Result<(),SelectionError<'tcx>>
1617 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1621 // ok to skip binder because the substs on generator types never
1622 // touch bound regions, they just capture the in-scope
1623 // type/region parameters
1624 let self_ty = *obligation.self_ty().skip_binder();
1626 ty::TyGenerator(..) => {
1627 debug!("assemble_generator_candidates: self_ty={:?} obligation={:?}",
1631 candidates.vec.push(GeneratorCandidate);
1634 ty::TyInfer(ty::TyVar(_)) => {
1635 debug!("assemble_generator_candidates: ambiguous self-type");
1636 candidates.ambiguous = true;
1639 _ => { return Ok(()); }
1643 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1644 /// FnMut<..>` where `X` is a closure type.
1646 /// Note: the type parameters on a closure candidate are modeled as *output* type
1647 /// parameters and hence do not affect whether this trait is a match or not. They will be
1648 /// unified during the confirmation step.
1649 fn assemble_closure_candidates(&mut self,
1650 obligation: &TraitObligation<'tcx>,
1651 candidates: &mut SelectionCandidateSet<'tcx>)
1652 -> Result<(),SelectionError<'tcx>>
1654 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.0.def_id()) {
1656 None => { return Ok(()); }
1659 // ok to skip binder because the substs on closure types never
1660 // touch bound regions, they just capture the in-scope
1661 // type/region parameters
1662 match obligation.self_ty().skip_binder().sty {
1663 ty::TyClosure(closure_def_id, closure_substs) => {
1664 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}",
1666 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1667 Some(closure_kind) => {
1668 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1669 if closure_kind.extends(kind) {
1670 candidates.vec.push(ClosureCandidate);
1674 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1675 candidates.vec.push(ClosureCandidate);
1680 ty::TyInfer(ty::TyVar(_)) => {
1681 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1682 candidates.ambiguous = true;
1685 _ => { return Ok(()); }
1689 /// Implement one of the `Fn()` family for a fn pointer.
1690 fn assemble_fn_pointer_candidates(&mut self,
1691 obligation: &TraitObligation<'tcx>,
1692 candidates: &mut SelectionCandidateSet<'tcx>)
1693 -> Result<(),SelectionError<'tcx>>
1695 // We provide impl of all fn traits for fn pointers.
1696 if self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()).is_none() {
1700 // ok to skip binder because what we are inspecting doesn't involve bound regions
1701 let self_ty = *obligation.self_ty().skip_binder();
1703 ty::TyInfer(ty::TyVar(_)) => {
1704 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1705 candidates.ambiguous = true; // could wind up being a fn() type
1708 // provide an impl, but only for suitable `fn` pointers
1709 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
1710 if let ty::Binder(ty::FnSig {
1711 unsafety: hir::Unsafety::Normal,
1715 }) = self_ty.fn_sig(self.tcx()) {
1716 candidates.vec.push(FnPointerCandidate);
1726 /// Search for impls that might apply to `obligation`.
1727 fn assemble_candidates_from_impls(&mut self,
1728 obligation: &TraitObligation<'tcx>,
1729 candidates: &mut SelectionCandidateSet<'tcx>)
1730 -> Result<(), SelectionError<'tcx>>
1732 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1734 self.tcx().for_each_relevant_impl(
1735 obligation.predicate.def_id(),
1736 obligation.predicate.0.trait_ref.self_ty(),
1738 self.probe(|this, snapshot| { /* [1] */
1739 match this.match_impl(impl_def_id, obligation, snapshot) {
1741 candidates.vec.push(ImplCandidate(impl_def_id));
1743 // NB: we can safely drop the skol map
1744 // since we are in a probe [1]
1745 mem::drop(skol_map);
1756 fn assemble_candidates_from_auto_impls(&mut self,
1757 obligation: &TraitObligation<'tcx>,
1758 candidates: &mut SelectionCandidateSet<'tcx>)
1759 -> Result<(), SelectionError<'tcx>>
1761 // OK to skip binder here because the tests we do below do not involve bound regions
1762 let self_ty = *obligation.self_ty().skip_binder();
1763 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
1765 let def_id = obligation.predicate.def_id();
1767 if self.tcx().trait_is_auto(def_id) {
1769 ty::TyDynamic(..) => {
1770 // For object types, we don't know what the closed
1771 // over types are. This means we conservatively
1772 // say nothing; a candidate may be added by
1773 // `assemble_candidates_from_object_ty`.
1775 ty::TyForeign(..) => {
1776 // Since the contents of foreign types is unknown,
1777 // we don't add any `..` impl. Default traits could
1778 // still be provided by a manual implementation for
1779 // this trait and type.
1782 ty::TyProjection(..) => {
1783 // In these cases, we don't know what the actual
1784 // type is. Therefore, we cannot break it down
1785 // into its constituent types. So we don't
1786 // consider the `..` impl but instead just add no
1787 // candidates: this means that typeck will only
1788 // succeed if there is another reason to believe
1789 // that this obligation holds. That could be a
1790 // where-clause or, in the case of an object type,
1791 // it could be that the object type lists the
1792 // trait (e.g. `Foo+Send : Send`). See
1793 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1794 // for an example of a test case that exercises
1797 ty::TyInfer(ty::TyVar(_)) => {
1798 // the auto impl might apply, we don't know
1799 candidates.ambiguous = true;
1802 candidates.vec.push(AutoImplCandidate(def_id.clone()))
1810 /// Search for impls that might apply to `obligation`.
1811 fn assemble_candidates_from_object_ty(&mut self,
1812 obligation: &TraitObligation<'tcx>,
1813 candidates: &mut SelectionCandidateSet<'tcx>)
1815 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1816 obligation.self_ty().skip_binder());
1818 // Object-safety candidates are only applicable to object-safe
1819 // traits. Including this check is useful because it helps
1820 // inference in cases of traits like `BorrowFrom`, which are
1821 // not object-safe, and which rely on being able to infer the
1822 // self-type from one of the other inputs. Without this check,
1823 // these cases wind up being considered ambiguous due to a
1824 // (spurious) ambiguity introduced here.
1825 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1826 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1830 self.probe(|this, _snapshot| {
1831 // the code below doesn't care about regions, and the
1832 // self-ty here doesn't escape this probe, so just erase
1834 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1835 let poly_trait_ref = match self_ty.sty {
1836 ty::TyDynamic(ref data, ..) => {
1837 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1838 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1839 pushing candidate");
1840 candidates.vec.push(BuiltinObjectCandidate);
1844 match data.principal() {
1845 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1849 ty::TyInfer(ty::TyVar(_)) => {
1850 debug!("assemble_candidates_from_object_ty: ambiguous");
1851 candidates.ambiguous = true; // could wind up being an object type
1859 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1862 // Count only those upcast versions that match the trait-ref
1863 // we are looking for. Specifically, do not only check for the
1864 // correct trait, but also the correct type parameters.
1865 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1866 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1867 let upcast_trait_refs =
1868 util::supertraits(this.tcx(), poly_trait_ref)
1869 .filter(|upcast_trait_ref| {
1870 this.probe(|this, _| {
1871 let upcast_trait_ref = upcast_trait_ref.clone();
1872 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1877 if upcast_trait_refs > 1 {
1878 // can be upcast in many ways; need more type information
1879 candidates.ambiguous = true;
1880 } else if upcast_trait_refs == 1 {
1881 candidates.vec.push(ObjectCandidate);
1886 /// Search for unsizing that might apply to `obligation`.
1887 fn assemble_candidates_for_unsizing(&mut self,
1888 obligation: &TraitObligation<'tcx>,
1889 candidates: &mut SelectionCandidateSet<'tcx>) {
1890 // We currently never consider higher-ranked obligations e.g.
1891 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1892 // because they are a priori invalid, and we could potentially add support
1893 // for them later, it's just that there isn't really a strong need for it.
1894 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1895 // impl, and those are generally applied to concrete types.
1897 // That said, one might try to write a fn with a where clause like
1898 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1899 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1900 // Still, you'd be more likely to write that where clause as
1902 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1903 // obligation above. Should be possible to extend this in the future.
1904 let source = match obligation.self_ty().no_late_bound_regions() {
1907 // Don't add any candidates if there are bound regions.
1911 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1913 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1916 let may_apply = match (&source.sty, &target.sty) {
1917 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1918 (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1919 // Upcasts permit two things:
1921 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1922 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1924 // Note that neither of these changes requires any
1925 // change at runtime. Eventually this will be
1928 // We always upcast when we can because of reason
1929 // #2 (region bounds).
1930 match (data_a.principal(), data_b.principal()) {
1931 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1932 data_b.auto_traits()
1933 // All of a's auto traits need to be in b's auto traits.
1934 .all(|b| data_a.auto_traits().any(|a| a == b)),
1940 (_, &ty::TyDynamic(..)) => true,
1942 // Ambiguous handling is below T -> Trait, because inference
1943 // variables can still implement Unsize<Trait> and nested
1944 // obligations will have the final say (likely deferred).
1945 (&ty::TyInfer(ty::TyVar(_)), _) |
1946 (_, &ty::TyInfer(ty::TyVar(_))) => {
1947 debug!("assemble_candidates_for_unsizing: ambiguous");
1948 candidates.ambiguous = true;
1953 (&ty::TyArray(..), &ty::TySlice(_)) => true,
1955 // Struct<T> -> Struct<U>.
1956 (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1957 def_id_a == def_id_b
1960 // (.., T) -> (.., U).
1961 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
1962 tys_a.len() == tys_b.len()
1969 candidates.vec.push(BuiltinUnsizeCandidate);
1973 ///////////////////////////////////////////////////////////////////////////
1976 // Winnowing is the process of attempting to resolve ambiguity by
1977 // probing further. During the winnowing process, we unify all
1978 // type variables (ignoring skolemization) and then we also
1979 // attempt to evaluate recursive bounds to see if they are
1982 /// Returns true if `candidate_i` should be dropped in favor of
1983 /// `candidate_j`. Generally speaking we will drop duplicate
1984 /// candidates and prefer where-clause candidates.
1985 /// Returns true if `victim` should be dropped in favor of
1986 /// `other`. Generally speaking we will drop duplicate
1987 /// candidates and prefer where-clause candidates.
1989 /// See the comment for "SelectionCandidate" for more details.
1990 fn candidate_should_be_dropped_in_favor_of<'o>(
1992 victim: &EvaluatedCandidate<'tcx>,
1993 other: &EvaluatedCandidate<'tcx>)
1996 if victim.candidate == other.candidate {
2000 match other.candidate {
2002 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
2003 AutoImplCandidate(..) => {
2005 "default implementations shouldn't be recorded \
2006 when there are other valid candidates");
2010 GeneratorCandidate |
2011 FnPointerCandidate |
2012 BuiltinObjectCandidate |
2013 BuiltinUnsizeCandidate |
2014 BuiltinCandidate { .. } => {
2015 // We have a where-clause so don't go around looking
2020 ProjectionCandidate => {
2021 // Arbitrarily give param candidates priority
2022 // over projection and object candidates.
2025 ParamCandidate(..) => false,
2027 ImplCandidate(other_def) => {
2028 // See if we can toss out `victim` based on specialization.
2029 // This requires us to know *for sure* that the `other` impl applies
2030 // i.e. EvaluatedToOk:
2031 if other.evaluation == EvaluatedToOk {
2032 if let ImplCandidate(victim_def) = victim.candidate {
2033 let tcx = self.tcx().global_tcx();
2034 return tcx.specializes((other_def, victim_def)) ||
2035 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
2045 ///////////////////////////////////////////////////////////////////////////
2048 // These cover the traits that are built-in to the language
2049 // itself. This includes `Copy` and `Sized` for sure. For the
2050 // moment, it also includes `Send` / `Sync` and a few others, but
2051 // those will hopefully change to library-defined traits in the
2054 // HACK: if this returns an error, selection exits without considering
2056 fn assemble_builtin_bound_candidates<'o>(&mut self,
2057 conditions: BuiltinImplConditions<'tcx>,
2058 candidates: &mut SelectionCandidateSet<'tcx>)
2059 -> Result<(),SelectionError<'tcx>>
2062 BuiltinImplConditions::Where(nested) => {
2063 debug!("builtin_bound: nested={:?}", nested);
2064 candidates.vec.push(BuiltinCandidate {
2065 has_nested: nested.skip_binder().len() > 0
2069 BuiltinImplConditions::None => { Ok(()) }
2070 BuiltinImplConditions::Ambiguous => {
2071 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2072 Ok(candidates.ambiguous = true)
2074 BuiltinImplConditions::Never => { Err(Unimplemented) }
2078 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2079 -> BuiltinImplConditions<'tcx>
2081 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
2083 // NOTE: binder moved to (*)
2084 let self_ty = self.infcx.shallow_resolve(
2085 obligation.predicate.skip_binder().self_ty());
2088 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
2089 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
2090 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
2091 ty::TyChar | ty::TyRef(..) | ty::TyGenerator(..) |
2092 ty::TyGeneratorWitness(..) | ty::TyArray(..) | ty::TyClosure(..) |
2093 ty::TyNever | ty::TyError => {
2094 // safe for everything
2095 Where(ty::Binder(Vec::new()))
2098 ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) | ty::TyForeign(..) => Never,
2100 ty::TyTuple(tys, _) => {
2101 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
2104 ty::TyAdt(def, substs) => {
2105 let sized_crit = def.sized_constraint(self.tcx());
2106 // (*) binder moved here
2108 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
2112 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
2113 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
2115 ty::TyInfer(ty::FreshTy(_))
2116 | ty::TyInfer(ty::FreshIntTy(_))
2117 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2118 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2124 fn copy_clone_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2125 -> BuiltinImplConditions<'tcx>
2127 // NOTE: binder moved to (*)
2128 let self_ty = self.infcx.shallow_resolve(
2129 obligation.predicate.skip_binder().self_ty());
2131 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
2134 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
2135 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
2136 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
2137 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
2138 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
2139 Where(ty::Binder(Vec::new()))
2142 ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
2143 ty::TyGenerator(..) | ty::TyGeneratorWitness(..) | ty::TyForeign(..) |
2144 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
2148 ty::TyArray(element_ty, _) => {
2149 // (*) binder moved here
2150 Where(ty::Binder(vec![element_ty]))
2153 ty::TyTuple(tys, _) => {
2154 // (*) binder moved here
2155 Where(ty::Binder(tys.to_vec()))
2158 ty::TyClosure(def_id, substs) => {
2159 let trait_id = obligation.predicate.def_id();
2161 Some(trait_id) == self.tcx().lang_items().copy_trait() &&
2162 self.tcx().has_copy_closures(def_id.krate);
2163 let clone_closures =
2164 Some(trait_id) == self.tcx().lang_items().clone_trait() &&
2165 self.tcx().has_clone_closures(def_id.krate);
2167 if copy_closures || clone_closures {
2168 Where(ty::Binder(substs.upvar_tys(def_id, self.tcx()).collect()))
2174 ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
2175 // Fallback to whatever user-defined impls exist in this case.
2179 ty::TyInfer(ty::TyVar(_)) => {
2180 // Unbound type variable. Might or might not have
2181 // applicable impls and so forth, depending on what
2182 // those type variables wind up being bound to.
2186 ty::TyInfer(ty::FreshTy(_))
2187 | ty::TyInfer(ty::FreshIntTy(_))
2188 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2189 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2195 /// For default impls, we need to break apart a type into its
2196 /// "constituent types" -- meaning, the types that it contains.
2198 /// Here are some (simple) examples:
2201 /// (i32, u32) -> [i32, u32]
2202 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2203 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2204 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2206 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2216 ty::TyInfer(ty::IntVar(_)) |
2217 ty::TyInfer(ty::FloatVar(_)) |
2226 ty::TyProjection(..) |
2227 ty::TyInfer(ty::TyVar(_)) |
2228 ty::TyInfer(ty::FreshTy(_)) |
2229 ty::TyInfer(ty::FreshIntTy(_)) |
2230 ty::TyInfer(ty::FreshFloatTy(_)) => {
2231 bug!("asked to assemble constituent types of unexpected type: {:?}",
2235 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
2236 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
2240 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
2244 ty::TyTuple(ref tys, _) => {
2245 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2249 ty::TyClosure(def_id, ref substs) => {
2250 substs.upvar_tys(def_id, self.tcx()).collect()
2253 ty::TyGenerator(def_id, ref substs, interior) => {
2254 substs.upvar_tys(def_id, self.tcx()).chain(iter::once(interior.witness)).collect()
2257 ty::TyGeneratorWitness(types) => {
2258 // This is sound because no regions in the witness can refer to
2259 // the binder outside the witness. So we'll effectivly reuse
2260 // the implicit binder around the witness.
2261 types.skip_binder().to_vec()
2264 // for `PhantomData<T>`, we pass `T`
2265 ty::TyAdt(def, substs) if def.is_phantom_data() => {
2266 substs.types().collect()
2269 ty::TyAdt(def, substs) => {
2271 .map(|f| f.ty(self.tcx(), substs))
2275 ty::TyAnon(def_id, substs) => {
2276 // We can resolve the `impl Trait` to its concrete type,
2277 // which enforces a DAG between the functions requiring
2278 // the auto trait bounds in question.
2279 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2284 fn collect_predicates_for_types(&mut self,
2285 param_env: ty::ParamEnv<'tcx>,
2286 cause: ObligationCause<'tcx>,
2287 recursion_depth: usize,
2288 trait_def_id: DefId,
2289 types: ty::Binder<Vec<Ty<'tcx>>>)
2290 -> Vec<PredicateObligation<'tcx>>
2292 // Because the types were potentially derived from
2293 // higher-ranked obligations they may reference late-bound
2294 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2295 // yield a type like `for<'a> &'a int`. In general, we
2296 // maintain the invariant that we never manipulate bound
2297 // regions, so we have to process these bound regions somehow.
2299 // The strategy is to:
2301 // 1. Instantiate those regions to skolemized regions (e.g.,
2302 // `for<'a> &'a int` becomes `&0 int`.
2303 // 2. Produce something like `&'0 int : Copy`
2304 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2306 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
2307 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
2309 self.in_snapshot(|this, snapshot| {
2310 let (skol_ty, skol_map) =
2311 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
2312 let Normalized { value: normalized_ty, mut obligations } =
2313 project::normalize_with_depth(this,
2318 let skol_obligation =
2319 this.tcx().predicate_for_trait_def(param_env,
2325 obligations.push(skol_obligation);
2326 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2331 ///////////////////////////////////////////////////////////////////////////
2334 // Confirmation unifies the output type parameters of the trait
2335 // with the values found in the obligation, possibly yielding a
2336 // type error. See `README.md` for more details.
2338 fn confirm_candidate(&mut self,
2339 obligation: &TraitObligation<'tcx>,
2340 candidate: SelectionCandidate<'tcx>)
2341 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2343 debug!("confirm_candidate({:?}, {:?})",
2348 BuiltinCandidate { has_nested } => {
2349 let data = self.confirm_builtin_candidate(obligation, has_nested);
2350 Ok(VtableBuiltin(data))
2353 ParamCandidate(param) => {
2354 let obligations = self.confirm_param_candidate(obligation, param);
2355 Ok(VtableParam(obligations))
2358 AutoImplCandidate(trait_def_id) => {
2359 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2360 Ok(VtableAutoImpl(data))
2363 ImplCandidate(impl_def_id) => {
2364 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2367 ClosureCandidate => {
2368 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2369 Ok(VtableClosure(vtable_closure))
2372 GeneratorCandidate => {
2373 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2374 Ok(VtableGenerator(vtable_generator))
2377 BuiltinObjectCandidate => {
2378 // This indicates something like `(Trait+Send) :
2379 // Send`. In this case, we know that this holds
2380 // because that's what the object type is telling us,
2381 // and there's really no additional obligations to
2382 // prove and no types in particular to unify etc.
2383 Ok(VtableParam(Vec::new()))
2386 ObjectCandidate => {
2387 let data = self.confirm_object_candidate(obligation);
2388 Ok(VtableObject(data))
2391 FnPointerCandidate => {
2393 self.confirm_fn_pointer_candidate(obligation)?;
2394 Ok(VtableFnPointer(data))
2397 ProjectionCandidate => {
2398 self.confirm_projection_candidate(obligation);
2399 Ok(VtableParam(Vec::new()))
2402 BuiltinUnsizeCandidate => {
2403 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2404 Ok(VtableBuiltin(data))
2409 fn confirm_projection_candidate(&mut self,
2410 obligation: &TraitObligation<'tcx>)
2412 self.in_snapshot(|this, snapshot| {
2414 this.match_projection_obligation_against_definition_bounds(obligation,
2420 fn confirm_param_candidate(&mut self,
2421 obligation: &TraitObligation<'tcx>,
2422 param: ty::PolyTraitRef<'tcx>)
2423 -> Vec<PredicateObligation<'tcx>>
2425 debug!("confirm_param_candidate({:?},{:?})",
2429 // During evaluation, we already checked that this
2430 // where-clause trait-ref could be unified with the obligation
2431 // trait-ref. Repeat that unification now without any
2432 // transactional boundary; it should not fail.
2433 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2434 Ok(obligations) => obligations,
2436 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2443 fn confirm_builtin_candidate(&mut self,
2444 obligation: &TraitObligation<'tcx>,
2446 -> VtableBuiltinData<PredicateObligation<'tcx>>
2448 debug!("confirm_builtin_candidate({:?}, {:?})",
2449 obligation, has_nested);
2451 let lang_items = self.tcx().lang_items();
2452 let obligations = if has_nested {
2453 let trait_def = obligation.predicate.def_id();
2454 let conditions = match trait_def {
2455 _ if Some(trait_def) == lang_items.sized_trait() => {
2456 self.sized_conditions(obligation)
2458 _ if Some(trait_def) == lang_items.copy_trait() => {
2459 self.copy_clone_conditions(obligation)
2461 _ if Some(trait_def) == lang_items.clone_trait() => {
2462 self.copy_clone_conditions(obligation)
2464 _ => bug!("unexpected builtin trait {:?}", trait_def)
2466 let nested = match conditions {
2467 BuiltinImplConditions::Where(nested) => nested,
2468 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2472 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2473 self.collect_predicates_for_types(obligation.param_env,
2475 obligation.recursion_depth+1,
2482 debug!("confirm_builtin_candidate: obligations={:?}",
2485 VtableBuiltinData { nested: obligations }
2488 /// This handles the case where a `auto trait Foo` impl is being used.
2489 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2491 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2492 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2493 fn confirm_auto_impl_candidate(&mut self,
2494 obligation: &TraitObligation<'tcx>,
2495 trait_def_id: DefId)
2496 -> VtableAutoImplData<PredicateObligation<'tcx>>
2498 debug!("confirm_auto_impl_candidate({:?}, {:?})",
2502 // binder is moved below
2503 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2504 let types = self.constituent_types_for_ty(self_ty);
2505 self.vtable_auto_impl(obligation, trait_def_id, ty::Binder(types))
2508 /// See `confirm_auto_impl_candidate`
2509 fn vtable_auto_impl(&mut self,
2510 obligation: &TraitObligation<'tcx>,
2511 trait_def_id: DefId,
2512 nested: ty::Binder<Vec<Ty<'tcx>>>)
2513 -> VtableAutoImplData<PredicateObligation<'tcx>>
2515 debug!("vtable_auto_impl: nested={:?}", nested);
2517 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2518 let mut obligations = self.collect_predicates_for_types(
2519 obligation.param_env,
2521 obligation.recursion_depth+1,
2525 let trait_obligations = self.in_snapshot(|this, snapshot| {
2526 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2527 let (trait_ref, skol_map) =
2528 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2529 let cause = obligation.derived_cause(ImplDerivedObligation);
2530 this.impl_or_trait_obligations(cause,
2531 obligation.recursion_depth + 1,
2532 obligation.param_env,
2539 obligations.extend(trait_obligations);
2541 debug!("vtable_auto_impl: obligations={:?}", obligations);
2543 VtableAutoImplData {
2549 fn confirm_impl_candidate(&mut self,
2550 obligation: &TraitObligation<'tcx>,
2552 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2554 debug!("confirm_impl_candidate({:?},{:?})",
2558 // First, create the substitutions by matching the impl again,
2559 // this time not in a probe.
2560 self.in_snapshot(|this, snapshot| {
2561 let (substs, skol_map) =
2562 this.rematch_impl(impl_def_id, obligation,
2564 debug!("confirm_impl_candidate substs={:?}", substs);
2565 let cause = obligation.derived_cause(ImplDerivedObligation);
2566 this.vtable_impl(impl_def_id,
2569 obligation.recursion_depth + 1,
2570 obligation.param_env,
2576 fn vtable_impl(&mut self,
2578 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2579 cause: ObligationCause<'tcx>,
2580 recursion_depth: usize,
2581 param_env: ty::ParamEnv<'tcx>,
2582 skol_map: infer::SkolemizationMap<'tcx>,
2583 snapshot: &infer::CombinedSnapshot)
2584 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2586 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2592 let mut impl_obligations =
2593 self.impl_or_trait_obligations(cause,
2601 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2605 // Because of RFC447, the impl-trait-ref and obligations
2606 // are sufficient to determine the impl substs, without
2607 // relying on projections in the impl-trait-ref.
2609 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2610 impl_obligations.append(&mut substs.obligations);
2612 VtableImplData { impl_def_id,
2613 substs: substs.value,
2614 nested: impl_obligations }
2617 fn confirm_object_candidate(&mut self,
2618 obligation: &TraitObligation<'tcx>)
2619 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2621 debug!("confirm_object_candidate({:?})",
2624 // FIXME skipping binder here seems wrong -- we should
2625 // probably flatten the binder from the obligation and the
2626 // binder from the object. Have to try to make a broken test
2627 // case that results. -nmatsakis
2628 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2629 let poly_trait_ref = match self_ty.sty {
2630 ty::TyDynamic(ref data, ..) => {
2631 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2634 span_bug!(obligation.cause.span,
2635 "object candidate with non-object");
2639 let mut upcast_trait_ref = None;
2643 let tcx = self.tcx();
2645 // We want to find the first supertrait in the list of
2646 // supertraits that we can unify with, and do that
2647 // unification. We know that there is exactly one in the list
2648 // where we can unify because otherwise select would have
2649 // reported an ambiguity. (When we do find a match, also
2650 // record it for later.)
2652 util::supertraits(tcx, poly_trait_ref)
2656 |this, _| this.match_poly_trait_ref(obligation, t))
2658 Ok(_) => { upcast_trait_ref = Some(t); false }
2663 // Additionally, for each of the nonmatching predicates that
2664 // we pass over, we sum up the set of number of vtable
2665 // entries, so that we can compute the offset for the selected
2668 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2674 upcast_trait_ref: upcast_trait_ref.unwrap(),
2680 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2681 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2683 debug!("confirm_fn_pointer_candidate({:?})",
2686 // ok to skip binder; it is reintroduced below
2687 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2688 let sig = self_ty.fn_sig(self.tcx());
2690 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2693 util::TupleArgumentsFlag::Yes)
2694 .map_bound(|(trait_ref, _)| trait_ref);
2696 let Normalized { value: trait_ref, obligations } =
2697 project::normalize_with_depth(self,
2698 obligation.param_env,
2699 obligation.cause.clone(),
2700 obligation.recursion_depth + 1,
2703 self.confirm_poly_trait_refs(obligation.cause.clone(),
2704 obligation.param_env,
2705 obligation.predicate.to_poly_trait_ref(),
2707 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2710 fn confirm_generator_candidate(&mut self,
2711 obligation: &TraitObligation<'tcx>)
2712 -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
2713 SelectionError<'tcx>>
2715 // ok to skip binder because the substs on generator types never
2716 // touch bound regions, they just capture the in-scope
2717 // type/region parameters
2718 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2719 let (closure_def_id, substs) = match self_ty.sty {
2720 ty::TyGenerator(id, substs, _) => (id, substs),
2721 _ => bug!("closure candidate for non-closure {:?}", obligation)
2724 debug!("confirm_generator_candidate({:?},{:?},{:?})",
2730 self.generator_trait_ref_unnormalized(obligation, closure_def_id, substs);
2734 } = normalize_with_depth(self,
2735 obligation.param_env,
2736 obligation.cause.clone(),
2737 obligation.recursion_depth+1,
2740 debug!("confirm_generator_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2745 self.confirm_poly_trait_refs(obligation.cause.clone(),
2746 obligation.param_env,
2747 obligation.predicate.to_poly_trait_ref(),
2750 Ok(VtableGeneratorData {
2751 closure_def_id: closure_def_id,
2752 substs: substs.clone(),
2757 fn confirm_closure_candidate(&mut self,
2758 obligation: &TraitObligation<'tcx>)
2759 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2760 SelectionError<'tcx>>
2762 debug!("confirm_closure_candidate({:?})", obligation);
2764 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.0.def_id()) {
2766 None => bug!("closure candidate for non-fn trait {:?}", obligation)
2769 // ok to skip binder because the substs on closure types never
2770 // touch bound regions, they just capture the in-scope
2771 // type/region parameters
2772 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2773 let (closure_def_id, substs) = match self_ty.sty {
2774 ty::TyClosure(id, substs) => (id, substs),
2775 _ => bug!("closure candidate for non-closure {:?}", obligation)
2779 self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
2783 } = normalize_with_depth(self,
2784 obligation.param_env,
2785 obligation.cause.clone(),
2786 obligation.recursion_depth+1,
2789 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2794 self.confirm_poly_trait_refs(obligation.cause.clone(),
2795 obligation.param_env,
2796 obligation.predicate.to_poly_trait_ref(),
2799 obligations.push(Obligation::new(
2800 obligation.cause.clone(),
2801 obligation.param_env,
2802 ty::Predicate::ClosureKind(closure_def_id, substs, kind)));
2804 Ok(VtableClosureData {
2806 substs: substs.clone(),
2811 /// In the case of closure types and fn pointers,
2812 /// we currently treat the input type parameters on the trait as
2813 /// outputs. This means that when we have a match we have only
2814 /// considered the self type, so we have to go back and make sure
2815 /// to relate the argument types too. This is kind of wrong, but
2816 /// since we control the full set of impls, also not that wrong,
2817 /// and it DOES yield better error messages (since we don't report
2818 /// errors as if there is no applicable impl, but rather report
2819 /// errors are about mismatched argument types.
2821 /// Here is an example. Imagine we have a closure expression
2822 /// and we desugared it so that the type of the expression is
2823 /// `Closure`, and `Closure` expects an int as argument. Then it
2824 /// is "as if" the compiler generated this impl:
2826 /// impl Fn(int) for Closure { ... }
2828 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2829 /// we have matched the self-type `Closure`. At this point we'll
2830 /// compare the `int` to `usize` and generate an error.
2832 /// Note that this checking occurs *after* the impl has selected,
2833 /// because these output type parameters should not affect the
2834 /// selection of the impl. Therefore, if there is a mismatch, we
2835 /// report an error to the user.
2836 fn confirm_poly_trait_refs(&mut self,
2837 obligation_cause: ObligationCause<'tcx>,
2838 obligation_param_env: ty::ParamEnv<'tcx>,
2839 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2840 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2841 -> Result<(), SelectionError<'tcx>>
2843 let obligation_trait_ref = obligation_trait_ref.clone();
2845 .at(&obligation_cause, obligation_param_env)
2846 .sup(obligation_trait_ref, expected_trait_ref)
2847 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2848 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2851 fn confirm_builtin_unsize_candidate(&mut self,
2852 obligation: &TraitObligation<'tcx>,)
2853 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>>
2855 let tcx = self.tcx();
2857 // assemble_candidates_for_unsizing should ensure there are no late bound
2858 // regions here. See the comment there for more details.
2859 let source = self.infcx.shallow_resolve(
2860 obligation.self_ty().no_late_bound_regions().unwrap());
2861 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2862 let target = self.infcx.shallow_resolve(target);
2864 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2867 let mut nested = vec![];
2868 match (&source.sty, &target.sty) {
2869 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2870 (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2871 // See assemble_candidates_for_unsizing for more info.
2872 // Binders reintroduced below in call to mk_existential_predicates.
2873 let principal = data_a.skip_binder().principal();
2874 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2875 .chain(data_a.skip_binder().projection_bounds()
2876 .map(|x| ty::ExistentialPredicate::Projection(x)))
2877 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2878 let new_trait = tcx.mk_dynamic(
2879 ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2880 let InferOk { obligations, .. } =
2881 self.infcx.at(&obligation.cause, obligation.param_env)
2882 .eq(target, new_trait)
2883 .map_err(|_| Unimplemented)?;
2884 self.inferred_obligations.extend(obligations);
2886 // Register one obligation for 'a: 'b.
2887 let cause = ObligationCause::new(obligation.cause.span,
2888 obligation.cause.body_id,
2889 ObjectCastObligation(target));
2890 let outlives = ty::OutlivesPredicate(r_a, r_b);
2891 nested.push(Obligation::with_depth(cause,
2892 obligation.recursion_depth + 1,
2893 obligation.param_env,
2894 ty::Binder(outlives).to_predicate()));
2898 (_, &ty::TyDynamic(ref data, r)) => {
2899 let mut object_dids =
2900 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2901 if let Some(did) = object_dids.find(|did| {
2902 !tcx.is_object_safe(*did)
2904 return Err(TraitNotObjectSafe(did))
2907 let cause = ObligationCause::new(obligation.cause.span,
2908 obligation.cause.body_id,
2909 ObjectCastObligation(target));
2910 let mut push = |predicate| {
2911 nested.push(Obligation::with_depth(cause.clone(),
2912 obligation.recursion_depth + 1,
2913 obligation.param_env,
2917 // Create obligations:
2918 // - Casting T to Trait
2919 // - For all the various builtin bounds attached to the object cast. (In other
2920 // words, if the object type is Foo+Send, this would create an obligation for the
2922 // - Projection predicates
2923 for predicate in data.iter() {
2924 push(predicate.with_self_ty(tcx, source));
2927 // We can only make objects from sized types.
2928 let tr = ty::TraitRef {
2929 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2930 substs: tcx.mk_substs_trait(source, &[]),
2932 push(tr.to_predicate());
2934 // If the type is `Foo+'a`, ensures that the type
2935 // being cast to `Foo+'a` outlives `'a`:
2936 let outlives = ty::OutlivesPredicate(source, r);
2937 push(ty::Binder(outlives).to_predicate());
2941 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2942 let InferOk { obligations, .. } =
2943 self.infcx.at(&obligation.cause, obligation.param_env)
2945 .map_err(|_| Unimplemented)?;
2946 self.inferred_obligations.extend(obligations);
2949 // Struct<T> -> Struct<U>.
2950 (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2953 .map(|f| tcx.type_of(f.did))
2954 .collect::<Vec<_>>();
2956 // The last field of the structure has to exist and contain type parameters.
2957 let field = if let Some(&field) = fields.last() {
2960 return Err(Unimplemented);
2962 let mut ty_params = BitVector::new(substs_a.types().count());
2963 let mut found = false;
2964 for ty in field.walk() {
2965 if let ty::TyParam(p) = ty.sty {
2966 ty_params.insert(p.idx as usize);
2971 return Err(Unimplemented);
2974 // Replace type parameters used in unsizing with
2975 // TyError and ensure they do not affect any other fields.
2976 // This could be checked after type collection for any struct
2977 // with a potentially unsized trailing field.
2978 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2979 if ty_params.contains(i) {
2980 Kind::from(tcx.types.err)
2985 let substs = tcx.mk_substs(params);
2986 for &ty in fields.split_last().unwrap().1 {
2987 if ty.subst(tcx, substs).references_error() {
2988 return Err(Unimplemented);
2992 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2993 let inner_source = field.subst(tcx, substs_a);
2994 let inner_target = field.subst(tcx, substs_b);
2996 // Check that the source struct with the target's
2997 // unsized parameters is equal to the target.
2998 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2999 if ty_params.contains(i) {
3000 substs_b.type_at(i).into()
3005 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3006 let InferOk { obligations, .. } =
3007 self.infcx.at(&obligation.cause, obligation.param_env)
3008 .eq(target, new_struct)
3009 .map_err(|_| Unimplemented)?;
3010 self.inferred_obligations.extend(obligations);
3012 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3013 nested.push(tcx.predicate_for_trait_def(
3014 obligation.param_env,
3015 obligation.cause.clone(),
3016 obligation.predicate.def_id(),
3017 obligation.recursion_depth + 1,
3022 // (.., T) -> (.., U).
3023 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
3024 assert_eq!(tys_a.len(), tys_b.len());
3026 // The last field of the tuple has to exist.
3027 let (a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3030 return Err(Unimplemented);
3032 let b_last = tys_b.last().unwrap();
3034 // Check that the source tuple with the target's
3035 // last element is equal to the target.
3036 let new_tuple = tcx.mk_tup(a_mid.iter().chain(Some(b_last)), false);
3037 let InferOk { obligations, .. } =
3038 self.infcx.at(&obligation.cause, obligation.param_env)
3039 .eq(target, new_tuple)
3040 .map_err(|_| Unimplemented)?;
3041 self.inferred_obligations.extend(obligations);
3043 // Construct the nested T: Unsize<U> predicate.
3044 nested.push(tcx.predicate_for_trait_def(
3045 obligation.param_env,
3046 obligation.cause.clone(),
3047 obligation.predicate.def_id(),
3048 obligation.recursion_depth + 1,
3056 Ok(VtableBuiltinData { nested: nested })
3059 ///////////////////////////////////////////////////////////////////////////
3062 // Matching is a common path used for both evaluation and
3063 // confirmation. It basically unifies types that appear in impls
3064 // and traits. This does affect the surrounding environment;
3065 // therefore, when used during evaluation, match routines must be
3066 // run inside of a `probe()` so that their side-effects are
3069 fn rematch_impl(&mut self,
3071 obligation: &TraitObligation<'tcx>,
3072 snapshot: &infer::CombinedSnapshot)
3073 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
3074 infer::SkolemizationMap<'tcx>)
3076 match self.match_impl(impl_def_id, obligation, snapshot) {
3077 Ok((substs, skol_map)) => (substs, skol_map),
3079 bug!("Impl {:?} was matchable against {:?} but now is not",
3086 fn match_impl(&mut self,
3088 obligation: &TraitObligation<'tcx>,
3089 snapshot: &infer::CombinedSnapshot)
3090 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
3091 infer::SkolemizationMap<'tcx>), ()>
3093 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3095 // Before we create the substitutions and everything, first
3096 // consider a "quick reject". This avoids creating more types
3097 // and so forth that we need to.
3098 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3102 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
3103 &obligation.predicate,
3105 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3107 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
3110 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
3113 let impl_trait_ref =
3114 project::normalize_with_depth(self,
3115 obligation.param_env,
3116 obligation.cause.clone(),
3117 obligation.recursion_depth + 1,
3120 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
3121 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3125 skol_obligation_trait_ref);
3127 let InferOk { obligations, .. } =
3128 self.infcx.at(&obligation.cause, obligation.param_env)
3129 .eq(skol_obligation_trait_ref, impl_trait_ref.value)
3131 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
3134 self.inferred_obligations.extend(obligations);
3136 if let Err(e) = self.infcx.leak_check(false,
3137 obligation.cause.span,
3140 debug!("match_impl: failed leak check due to `{}`", e);
3144 debug!("match_impl: success impl_substs={:?}", impl_substs);
3147 obligations: impl_trait_ref.obligations
3151 fn fast_reject_trait_refs(&mut self,
3152 obligation: &TraitObligation,
3153 impl_trait_ref: &ty::TraitRef)
3156 // We can avoid creating type variables and doing the full
3157 // substitution if we find that any of the input types, when
3158 // simplified, do not match.
3160 obligation.predicate.skip_binder().input_types()
3161 .zip(impl_trait_ref.input_types())
3162 .any(|(obligation_ty, impl_ty)| {
3163 let simplified_obligation_ty =
3164 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3165 let simplified_impl_ty =
3166 fast_reject::simplify_type(self.tcx(), impl_ty, false);
3168 simplified_obligation_ty.is_some() &&
3169 simplified_impl_ty.is_some() &&
3170 simplified_obligation_ty != simplified_impl_ty
3174 /// Normalize `where_clause_trait_ref` and try to match it against
3175 /// `obligation`. If successful, return any predicates that
3176 /// result from the normalization. Normalization is necessary
3177 /// because where-clauses are stored in the parameter environment
3179 fn match_where_clause_trait_ref(&mut self,
3180 obligation: &TraitObligation<'tcx>,
3181 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
3182 -> Result<Vec<PredicateObligation<'tcx>>,()>
3184 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
3188 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3189 /// obligation is satisfied.
3190 fn match_poly_trait_ref(&mut self,
3191 obligation: &TraitObligation<'tcx>,
3192 poly_trait_ref: ty::PolyTraitRef<'tcx>)
3195 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3199 self.infcx.at(&obligation.cause, obligation.param_env)
3200 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3201 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
3205 ///////////////////////////////////////////////////////////////////////////
3208 fn match_fresh_trait_refs(&self,
3209 previous: &ty::PolyTraitRef<'tcx>,
3210 current: &ty::PolyTraitRef<'tcx>)
3213 let mut matcher = ty::_match::Match::new(self.tcx());
3214 matcher.relate(previous, current).is_ok()
3217 fn push_stack<'o,'s:'o>(&mut self,
3218 previous_stack: TraitObligationStackList<'s, 'tcx>,
3219 obligation: &'o TraitObligation<'tcx>)
3220 -> TraitObligationStack<'o, 'tcx>
3222 let fresh_trait_ref =
3223 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3225 TraitObligationStack {
3228 previous: previous_stack,
3232 fn closure_trait_ref_unnormalized(&mut self,
3233 obligation: &TraitObligation<'tcx>,
3234 closure_def_id: DefId,
3235 substs: ty::ClosureSubsts<'tcx>)
3236 -> ty::PolyTraitRef<'tcx>
3238 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3239 let ty::Binder((trait_ref, _)) =
3240 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
3241 obligation.predicate.0.self_ty(), // (1)
3243 util::TupleArgumentsFlag::No);
3244 // (1) Feels icky to skip the binder here, but OTOH we know
3245 // that the self-type is an unboxed closure type and hence is
3246 // in fact unparameterized (or at least does not reference any
3247 // regions bound in the obligation). Still probably some
3248 // refactoring could make this nicer.
3250 ty::Binder(trait_ref)
3253 fn generator_trait_ref_unnormalized(&mut self,
3254 obligation: &TraitObligation<'tcx>,
3255 closure_def_id: DefId,
3256 substs: ty::ClosureSubsts<'tcx>)
3257 -> ty::PolyTraitRef<'tcx>
3259 let gen_sig = substs.generator_poly_sig(closure_def_id, self.tcx());
3260 let ty::Binder((trait_ref, ..)) =
3261 self.tcx().generator_trait_ref_and_outputs(obligation.predicate.def_id(),
3262 obligation.predicate.0.self_ty(), // (1)
3264 // (1) Feels icky to skip the binder here, but OTOH we know
3265 // that the self-type is an generator type and hence is
3266 // in fact unparameterized (or at least does not reference any
3267 // regions bound in the obligation). Still probably some
3268 // refactoring could make this nicer.
3270 ty::Binder(trait_ref)
3273 /// Returns the obligations that are implied by instantiating an
3274 /// impl or trait. The obligations are substituted and fully
3275 /// normalized. This is used when confirming an impl or default
3277 fn impl_or_trait_obligations(&mut self,
3278 cause: ObligationCause<'tcx>,
3279 recursion_depth: usize,
3280 param_env: ty::ParamEnv<'tcx>,
3281 def_id: DefId, // of impl or trait
3282 substs: &Substs<'tcx>, // for impl or trait
3283 skol_map: infer::SkolemizationMap<'tcx>,
3284 snapshot: &infer::CombinedSnapshot)
3285 -> Vec<PredicateObligation<'tcx>>
3287 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3288 let tcx = self.tcx();
3290 // To allow for one-pass evaluation of the nested obligation,
3291 // each predicate must be preceded by the obligations required
3293 // for example, if we have:
3294 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3295 // the impl will have the following predicates:
3296 // <V as Iterator>::Item = U,
3297 // U: Iterator, U: Sized,
3298 // V: Iterator, V: Sized,
3299 // <U as Iterator>::Item: Copy
3300 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3301 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3302 // `$1: Copy`, so we must ensure the obligations are emitted in
3304 let predicates = tcx.predicates_of(def_id);
3305 assert_eq!(predicates.parent, None);
3306 let mut predicates: Vec<_> = predicates.predicates.iter().flat_map(|predicate| {
3307 let predicate = normalize_with_depth(self, param_env, cause.clone(), recursion_depth,
3308 &predicate.subst(tcx, substs));
3309 predicate.obligations.into_iter().chain(
3311 cause: cause.clone(),
3314 predicate: predicate.value
3317 // We are performing deduplication here to avoid exponential blowups
3318 // (#38528) from happening, but the real cause of the duplication is
3319 // unknown. What we know is that the deduplication avoids exponential
3320 // amount of predicates being propogated when processing deeply nested
3322 let mut seen = FxHashSet();
3323 predicates.retain(|i| seen.insert(i.clone()));
3324 self.infcx().plug_leaks(skol_map, snapshot, predicates)
3328 impl<'tcx> TraitObligation<'tcx> {
3329 #[allow(unused_comparisons)]
3330 pub fn derived_cause(&self,
3331 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
3332 -> ObligationCause<'tcx>
3335 * Creates a cause for obligations that are derived from
3336 * `obligation` by a recursive search (e.g., for a builtin
3337 * bound, or eventually a `auto trait Foo`). If `obligation`
3338 * is itself a derived obligation, this is just a clone, but
3339 * otherwise we create a "derived obligation" cause so as to
3340 * keep track of the original root obligation for error
3344 let obligation = self;
3346 // NOTE(flaper87): As of now, it keeps track of the whole error
3347 // chain. Ideally, we should have a way to configure this either
3348 // by using -Z verbose or just a CLI argument.
3349 if obligation.recursion_depth >= 0 {
3350 let derived_cause = DerivedObligationCause {
3351 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3352 parent_code: Rc::new(obligation.cause.code.clone())
3354 let derived_code = variant(derived_cause);
3355 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3357 obligation.cause.clone()
3362 impl<'tcx> SelectionCache<'tcx> {
3363 pub fn new() -> SelectionCache<'tcx> {
3365 hashmap: RefCell::new(FxHashMap())
3369 pub fn clear(&self) {
3370 *self.hashmap.borrow_mut() = FxHashMap()
3374 impl<'tcx> EvaluationCache<'tcx> {
3375 pub fn new() -> EvaluationCache<'tcx> {
3377 hashmap: RefCell::new(FxHashMap())
3381 pub fn clear(&self) {
3382 *self.hashmap.borrow_mut() = FxHashMap()
3386 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
3387 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
3388 TraitObligationStackList::with(self)
3391 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
3396 #[derive(Copy, Clone)]
3397 struct TraitObligationStackList<'o,'tcx:'o> {
3398 head: Option<&'o TraitObligationStack<'o,'tcx>>
3401 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
3402 fn empty() -> TraitObligationStackList<'o,'tcx> {
3403 TraitObligationStackList { head: None }
3406 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
3407 TraitObligationStackList { head: Some(r) }
3411 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
3412 type Item = &'o TraitObligationStack<'o,'tcx>;
3414 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3425 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3426 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3427 write!(f, "TraitObligationStack({:?})", self.obligation)
3432 pub struct WithDepNode<T> {
3433 dep_node: DepNodeIndex,
3437 impl<T: Clone> WithDepNode<T> {
3438 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3439 WithDepNode { dep_node, cached_value }
3442 pub fn get(&self, tcx: TyCtxt) -> T {
3443 tcx.dep_graph.read_index(self.dep_node);
3444 self.cached_value.clone()