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 [rustc guide] for more info on how this works.
13 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/trait-resolution.html#selection
15 use self::SelectionCandidate::*;
16 use self::EvaluationResult::*;
18 use super::coherence::{self, Conflict};
19 use super::DerivedObligationCause;
20 use super::IntercrateMode;
22 use super::project::{normalize_with_depth, Normalized, ProjectionCacheKey};
23 use super::{PredicateObligation, TraitObligation, ObligationCause};
24 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
25 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
26 use super::{ObjectCastObligation, Obligation};
27 use super::TraitNotObjectSafe;
29 use super::SelectionResult;
30 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure, VtableGenerator,
31 VtableFnPointer, VtableObject, VtableAutoImpl};
32 use super::{VtableImplData, VtableObjectData, VtableBuiltinData, VtableGeneratorData,
33 VtableClosureData, VtableAutoImplData, VtableFnPointerData};
36 use dep_graph::{DepNodeIndex, DepKind};
37 use hir::def_id::DefId;
39 use infer::{InferCtxt, InferOk, TypeFreshener};
40 use ty::subst::{Kind, Subst, Substs};
41 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
43 use ty::relate::TypeRelation;
44 use middle::lang_items;
46 use rustc_data_structures::bitvec::BitVector;
47 use rustc_data_structures::snapshot_vec::{SnapshotVecDelegate, SnapshotVec};
49 use std::cell::RefCell;
52 use std::marker::PhantomData;
58 use util::nodemap::{FxHashMap, FxHashSet};
60 struct InferredObligationsSnapshotVecDelegate<'tcx> {
61 phantom: PhantomData<&'tcx i32>,
63 impl<'tcx> SnapshotVecDelegate for InferredObligationsSnapshotVecDelegate<'tcx> {
64 type Value = PredicateObligation<'tcx>;
66 fn reverse(_: &mut Vec<Self::Value>, _: Self::Undo) {}
69 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
70 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
72 /// Freshener used specifically for skolemizing entries on the
73 /// obligation stack. This ensures that all entries on the stack
74 /// at one time will have the same set of skolemized entries,
75 /// which is important for checking for trait bounds that
76 /// recursively require themselves.
77 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
79 /// If true, indicates that the evaluation should be conservative
80 /// and consider the possibility of types outside this crate.
81 /// This comes up primarily when resolving ambiguity. Imagine
82 /// there is some trait reference `$0 : Bar` where `$0` is an
83 /// inference variable. If `intercrate` is true, then we can never
84 /// say for sure that this reference is not implemented, even if
85 /// there are *no impls at all for `Bar`*, because `$0` could be
86 /// bound to some type that in a downstream crate that implements
87 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
88 /// though, we set this to false, because we are only interested
89 /// in types that the user could actually have written --- in
90 /// other words, we consider `$0 : Bar` to be unimplemented if
91 /// there is no type that the user could *actually name* that
92 /// would satisfy it. This avoids crippling inference, basically.
93 intercrate: Option<IntercrateMode>,
95 inferred_obligations: SnapshotVec<InferredObligationsSnapshotVecDelegate<'tcx>>,
97 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
99 /// Controls whether or not to filter out negative impls when selecting.
100 /// This is used in librustdoc to distinguish between the lack of an impl
101 /// and a negative impl
102 allow_negative_impls: bool
105 #[derive(Clone, Debug)]
106 pub enum IntercrateAmbiguityCause {
109 self_desc: Option<String>,
111 UpstreamCrateUpdate {
113 self_desc: Option<String>,
117 impl IntercrateAmbiguityCause {
118 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
119 /// See #23980 for details.
120 pub fn add_intercrate_ambiguity_hint<'a, 'tcx>(&self,
121 err: &mut ::errors::DiagnosticBuilder) {
122 err.note(&self.intercrate_ambiguity_hint());
125 pub fn intercrate_ambiguity_hint(&self) -> String {
127 &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
128 let self_desc = if let &Some(ref ty) = self_desc {
129 format!(" for type `{}`", ty)
130 } else { "".to_string() };
131 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
133 &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
134 let self_desc = if let &Some(ref ty) = self_desc {
135 format!(" for type `{}`", ty)
136 } else { "".to_string() };
137 format!("upstream crates may add new impl of trait `{}`{} \
139 trait_desc, self_desc)
145 // A stack that walks back up the stack frame.
146 struct TraitObligationStack<'prev, 'tcx: 'prev> {
147 obligation: &'prev TraitObligation<'tcx>,
149 /// Trait ref from `obligation` but skolemized with the
150 /// selection-context's freshener. Used to check for recursion.
151 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
153 previous: TraitObligationStackList<'prev, 'tcx>,
157 pub struct SelectionCache<'tcx> {
158 hashmap: RefCell<FxHashMap<ty::TraitRef<'tcx>,
159 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>>,
162 /// The selection process begins by considering all impls, where
163 /// clauses, and so forth that might resolve an obligation. Sometimes
164 /// we'll be able to say definitively that (e.g.) an impl does not
165 /// apply to the obligation: perhaps it is defined for `usize` but the
166 /// obligation is for `int`. In that case, we drop the impl out of the
167 /// list. But the other cases are considered *candidates*.
169 /// For selection to succeed, there must be exactly one matching
170 /// candidate. If the obligation is fully known, this is guaranteed
171 /// by coherence. However, if the obligation contains type parameters
172 /// or variables, there may be multiple such impls.
174 /// It is not a real problem if multiple matching impls exist because
175 /// of type variables - it just means the obligation isn't sufficiently
176 /// elaborated. In that case we report an ambiguity, and the caller can
177 /// try again after more type information has been gathered or report a
178 /// "type annotations required" error.
180 /// However, with type parameters, this can be a real problem - type
181 /// parameters don't unify with regular types, but they *can* unify
182 /// with variables from blanket impls, and (unless we know its bounds
183 /// will always be satisfied) picking the blanket impl will be wrong
184 /// for at least *some* substitutions. To make this concrete, if we have
186 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
187 /// impl<T: fmt::Debug> AsDebug for T {
189 /// fn debug(self) -> fmt::Debug { self }
191 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
193 /// we can't just use the impl to resolve the <T as AsDebug> obligation
194 /// - a type from another crate (that doesn't implement fmt::Debug) could
195 /// implement AsDebug.
197 /// Because where-clauses match the type exactly, multiple clauses can
198 /// only match if there are unresolved variables, and we can mostly just
199 /// report this ambiguity in that case. This is still a problem - we can't
200 /// *do anything* with ambiguities that involve only regions. This is issue
203 /// If a single where-clause matches and there are no inference
204 /// variables left, then it definitely matches and we can just select
207 /// In fact, we even select the where-clause when the obligation contains
208 /// inference variables. The can lead to inference making "leaps of logic",
209 /// for example in this situation:
211 /// pub trait Foo<T> { fn foo(&self) -> T; }
212 /// impl<T> Foo<()> for T { fn foo(&self) { } }
213 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
215 /// pub fn foo<T>(t: T) where T: Foo<bool> {
216 /// println!("{:?}", <T as Foo<_>>::foo(&t));
218 /// fn main() { foo(false); }
220 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
221 /// impl and the where-clause. We select the where-clause and unify $0=bool,
222 /// so the program prints "false". However, if the where-clause is omitted,
223 /// the blanket impl is selected, we unify $0=(), and the program prints
226 /// Exactly the same issues apply to projection and object candidates, except
227 /// that we can have both a projection candidate and a where-clause candidate
228 /// for the same obligation. In that case either would do (except that
229 /// different "leaps of logic" would occur if inference variables are
230 /// present), and we just pick the where-clause. This is, for example,
231 /// required for associated types to work in default impls, as the bounds
232 /// are visible both as projection bounds and as where-clauses from the
233 /// parameter environment.
234 #[derive(PartialEq,Eq,Debug,Clone)]
235 enum SelectionCandidate<'tcx> {
236 BuiltinCandidate { has_nested: bool },
237 ParamCandidate(ty::PolyTraitRef<'tcx>),
238 ImplCandidate(DefId),
239 AutoImplCandidate(DefId),
241 /// This is a trait matching with a projected type as `Self`, and
242 /// we found an applicable bound in the trait definition.
245 /// Implementation of a `Fn`-family trait by one of the anonymous types
246 /// generated for a `||` expression.
249 /// Implementation of a `Generator` trait by one of the anonymous types
250 /// generated for a generator.
253 /// Implementation of a `Fn`-family trait by one of the anonymous
254 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
259 BuiltinObjectCandidate,
261 BuiltinUnsizeCandidate,
264 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
265 type Lifted = SelectionCandidate<'tcx>;
266 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
268 BuiltinCandidate { has_nested } => {
273 ImplCandidate(def_id) => ImplCandidate(def_id),
274 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
275 ProjectionCandidate => ProjectionCandidate,
276 FnPointerCandidate => FnPointerCandidate,
277 ObjectCandidate => ObjectCandidate,
278 BuiltinObjectCandidate => BuiltinObjectCandidate,
279 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
280 ClosureCandidate => ClosureCandidate,
281 GeneratorCandidate => GeneratorCandidate,
283 ParamCandidate(ref trait_ref) => {
284 return tcx.lift(trait_ref).map(ParamCandidate);
290 struct SelectionCandidateSet<'tcx> {
291 // a list of candidates that definitely apply to the current
292 // obligation (meaning: types unify).
293 vec: Vec<SelectionCandidate<'tcx>>,
295 // if this is true, then there were candidates that might or might
296 // not have applied, but we couldn't tell. This occurs when some
297 // of the input types are type variables, in which case there are
298 // various "builtin" rules that might or might not trigger.
302 #[derive(PartialEq,Eq,Debug,Clone)]
303 struct EvaluatedCandidate<'tcx> {
304 candidate: SelectionCandidate<'tcx>,
305 evaluation: EvaluationResult,
308 /// When does the builtin impl for `T: Trait` apply?
309 enum BuiltinImplConditions<'tcx> {
310 /// The impl is conditional on T1,T2,.. : Trait
311 Where(ty::Binder<Vec<Ty<'tcx>>>),
312 /// There is no built-in impl. There may be some other
313 /// candidate (a where-clause or user-defined impl).
315 /// There is *no* impl for this, builtin or not. Ignore
316 /// all where-clauses.
318 /// It is unknown whether there is an impl.
322 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
323 /// The result of trait evaluation. The order is important
324 /// here as the evaluation of a list is the maximum of the
327 /// The evaluation results are ordered:
328 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
329 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
330 /// - the "union" of evaluation results is equal to their maximum -
331 /// all the "potential success" candidates can potentially succeed,
332 /// so they are no-ops when unioned with a definite error, and within
333 /// the categories it's easy to see that the unions are correct.
334 enum EvaluationResult {
335 /// Evaluation successful
337 /// Evaluation is known to be ambiguous - it *might* hold for some
338 /// assignment of inference variables, but it might not.
340 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
341 /// know whether this obligation holds or not - it is the result we
342 /// would get with an empty stack, and therefore is cacheable.
344 /// Evaluation failed because of recursion involving inference
345 /// variables. We are somewhat imprecise there, so we don't actually
346 /// know the real result.
348 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
350 /// Evaluation failed because we encountered an obligation we are already
351 /// trying to prove on this branch.
353 /// We know this branch can't be a part of a minimal proof-tree for
354 /// the "root" of our cycle, because then we could cut out the recursion
355 /// and maintain a valid proof tree. However, this does not mean
356 /// that all the obligations on this branch do not hold - it's possible
357 /// that we entered this branch "speculatively", and that there
358 /// might be some other way to prove this obligation that does not
359 /// go through this cycle - so we can't cache this as a failure.
361 /// For example, suppose we have this:
363 /// ```rust,ignore (pseudo-Rust)
364 /// pub trait Trait { fn xyz(); }
365 /// // This impl is "useless", but we can still have
366 /// // an `impl Trait for SomeUnsizedType` somewhere.
367 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
369 /// pub fn foo<T: Trait + ?Sized>() {
370 /// <T as Trait>::xyz();
374 /// When checking `foo`, we have to prove `T: Trait`. This basically
375 /// translates into this:
377 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
379 /// When we try to prove it, we first go the first option, which
380 /// recurses. This shows us that the impl is "useless" - it won't
381 /// tell us that `T: Trait` unless it already implemented `Trait`
382 /// by some other means. However, that does not prevent `T: Trait`
383 /// does not hold, because of the bound (which can indeed be satisfied
384 /// by `SomeUnsizedType` from another crate).
386 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
387 /// ought to convert it to an `EvaluatedToErr`, because we know
388 /// there definitely isn't a proof tree for that obligation. Not
389 /// doing so is still sound - there isn't any proof tree, so the
390 /// branch still can't be a part of a minimal one - but does not
391 /// re-enable caching.
393 /// Evaluation failed
397 impl EvaluationResult {
398 fn may_apply(self) -> bool {
402 EvaluatedToUnknown => true,
405 EvaluatedToRecur => false
409 fn is_stack_dependent(self) -> bool {
412 EvaluatedToRecur => true,
416 EvaluatedToErr => false,
422 pub struct EvaluationCache<'tcx> {
423 hashmap: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>
426 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
427 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
430 freshener: infcx.freshener(),
432 inferred_obligations: SnapshotVec::new(),
433 intercrate_ambiguity_causes: None,
434 allow_negative_impls: false,
438 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
439 mode: IntercrateMode) -> SelectionContext<'cx, 'gcx, 'tcx> {
440 debug!("intercrate({:?})", mode);
443 freshener: infcx.freshener(),
444 intercrate: Some(mode),
445 inferred_obligations: SnapshotVec::new(),
446 intercrate_ambiguity_causes: None,
447 allow_negative_impls: false,
451 pub fn with_negative(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
452 allow_negative_impls: bool) -> SelectionContext<'cx, 'gcx, 'tcx> {
453 debug!("with_negative({:?})", allow_negative_impls);
456 freshener: infcx.freshener(),
458 inferred_obligations: SnapshotVec::new(),
459 intercrate_ambiguity_causes: None,
460 allow_negative_impls,
464 /// Enables tracking of intercrate ambiguity causes. These are
465 /// used in coherence to give improved diagnostics. We don't do
466 /// this until we detect a coherence error because it can lead to
467 /// false overflow results (#47139) and because it costs
468 /// computation time.
469 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
470 assert!(self.intercrate.is_some());
471 assert!(self.intercrate_ambiguity_causes.is_none());
472 self.intercrate_ambiguity_causes = Some(vec![]);
473 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
476 /// Gets the intercrate ambiguity causes collected since tracking
477 /// was enabled and disables tracking at the same time. If
478 /// tracking is not enabled, just returns an empty vector.
479 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
480 assert!(self.intercrate.is_some());
481 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
484 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
488 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
492 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
496 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
498 fn in_snapshot<R, F>(&mut self, f: F) -> R
499 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
501 // The irrefutable nature of the operation means we don't need to snapshot the
502 // inferred_obligations vector.
503 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
506 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
508 fn probe<R, F>(&mut self, f: F) -> R
509 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
511 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
512 let result = self.infcx.probe(|snapshot| f(self, snapshot));
513 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
517 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
518 /// the transaction fails and s.t. old obligations are retained.
519 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
520 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
522 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
523 match self.infcx.commit_if_ok(|snapshot| f(self, snapshot)) {
525 self.inferred_obligations.commit(inferred_obligations_snapshot);
529 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
536 ///////////////////////////////////////////////////////////////////////////
539 // The selection phase tries to identify *how* an obligation will
540 // be resolved. For example, it will identify which impl or
541 // parameter bound is to be used. The process can be inconclusive
542 // if the self type in the obligation is not fully inferred. Selection
543 // can result in an error in one of two ways:
545 // 1. If no applicable impl or parameter bound can be found.
546 // 2. If the output type parameters in the obligation do not match
547 // those specified by the impl/bound. For example, if the obligation
548 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
549 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
551 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
552 /// type environment by performing unification.
553 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
554 -> SelectionResult<'tcx, Selection<'tcx>> {
555 debug!("select({:?})", obligation);
556 assert!(!obligation.predicate.has_escaping_regions());
558 let tcx = self.tcx();
560 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
561 let ret = match self.candidate_from_obligation(&stack)? {
564 let mut candidate = self.confirm_candidate(obligation, candidate)?;
565 let inferred_obligations = (*self.inferred_obligations).into_iter().cloned();
566 candidate.nested_obligations_mut().extend(inferred_obligations);
571 // Test whether this is a `()` which was produced by defaulting a
572 // diverging type variable with `!` disabled. If so, we may need
573 // to raise a warning.
574 if obligation.predicate.skip_binder().self_ty().is_defaulted_unit() {
575 let mut raise_warning = true;
576 // Don't raise a warning if the trait is implemented for ! and only
577 // permits a trivial implementation for !. This stops us warning
578 // about (for example) `(): Clone` becoming `!: Clone` because such
579 // a switch can't cause code to stop compiling or execute
581 let mut never_obligation = obligation.clone();
582 let def_id = never_obligation.predicate.skip_binder().trait_ref.def_id;
583 never_obligation.predicate = never_obligation.predicate.map_bound(|mut trait_pred| {
584 // Swap out () with ! so we can check if the trait is impld for !
586 let trait_ref = &mut trait_pred.trait_ref;
587 let unit_substs = trait_ref.substs;
588 let mut never_substs = Vec::with_capacity(unit_substs.len());
589 never_substs.push(tcx.types.never.into());
590 never_substs.extend(&unit_substs[1..]);
591 trait_ref.substs = tcx.intern_substs(&never_substs);
595 if let Ok(Some(..)) = self.select(&never_obligation) {
596 if !tcx.trait_relevant_for_never(def_id) {
597 // The trait is also implemented for ! and the resulting
598 // implementation cannot actually be invoked in any way.
599 raise_warning = false;
604 tcx.lint_node(lint::builtin::RESOLVE_TRAIT_ON_DEFAULTED_UNIT,
605 obligation.cause.body_id,
606 obligation.cause.span,
607 &format!("code relies on type inference rules which are likely \
614 ///////////////////////////////////////////////////////////////////////////
617 // Tests whether an obligation can be selected or whether an impl
618 // can be applied to particular types. It skips the "confirmation"
619 // step and hence completely ignores output type parameters.
621 // The result is "true" if the obligation *may* hold and "false" if
622 // we can be sure it does not.
624 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
625 pub fn evaluate_obligation(&mut self,
626 obligation: &PredicateObligation<'tcx>)
629 debug!("evaluate_obligation({:?})",
632 self.probe(|this, _| {
633 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
638 /// Evaluates whether the obligation `obligation` can be satisfied,
639 /// and returns `false` if not certain. However, this is not entirely
640 /// accurate if inference variables are involved.
641 pub fn evaluate_obligation_conservatively(&mut self,
642 obligation: &PredicateObligation<'tcx>)
645 debug!("evaluate_obligation_conservatively({:?})",
648 self.probe(|this, _| {
649 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
654 /// Evaluates the predicates in `predicates` recursively. Note that
655 /// this applies projections in the predicates, and therefore
656 /// is run within an inference probe.
657 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
658 stack: TraitObligationStackList<'o, 'tcx>,
661 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
663 let mut result = EvaluatedToOk;
664 for obligation in predicates {
665 let eval = self.evaluate_predicate_recursively(stack, obligation);
666 debug!("evaluate_predicate_recursively({:?}) = {:?}",
668 if let EvaluatedToErr = eval {
669 // fast-path - EvaluatedToErr is the top of the lattice,
670 // so we don't need to look on the other predicates.
671 return EvaluatedToErr;
673 result = cmp::max(result, eval);
679 fn evaluate_predicate_recursively<'o>(&mut self,
680 previous_stack: TraitObligationStackList<'o, 'tcx>,
681 obligation: &PredicateObligation<'tcx>)
684 debug!("evaluate_predicate_recursively({:?})",
687 match obligation.predicate {
688 ty::Predicate::Trait(ref t) => {
689 assert!(!t.has_escaping_regions());
690 let obligation = obligation.with(t.clone());
691 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
694 ty::Predicate::Equate(ref p) => {
695 // does this code ever run?
696 match self.infcx.equality_predicate(&obligation.cause, obligation.param_env, p) {
697 Ok(InferOk { obligations, .. }) => {
698 self.inferred_obligations.extend(obligations);
701 Err(_) => EvaluatedToErr
705 ty::Predicate::Subtype(ref p) => {
706 // does this code ever run?
707 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
708 Some(Ok(InferOk { obligations, .. })) => {
709 self.inferred_obligations.extend(obligations);
712 Some(Err(_)) => EvaluatedToErr,
713 None => EvaluatedToAmbig,
717 ty::Predicate::WellFormed(ty) => {
718 match ty::wf::obligations(self.infcx,
719 obligation.param_env,
720 obligation.cause.body_id,
721 ty, obligation.cause.span) {
723 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
729 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
730 // we do not consider region relationships when
731 // evaluating trait matches
735 ty::Predicate::ObjectSafe(trait_def_id) => {
736 if self.tcx().is_object_safe(trait_def_id) {
743 ty::Predicate::Projection(ref data) => {
744 let project_obligation = obligation.with(data.clone());
745 match project::poly_project_and_unify_type(self, &project_obligation) {
746 Ok(Some(subobligations)) => {
747 let result = self.evaluate_predicates_recursively(previous_stack,
748 subobligations.iter());
750 ProjectionCacheKey::from_poly_projection_predicate(self, data)
752 self.infcx.projection_cache.borrow_mut().complete(key);
765 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
766 match self.infcx.closure_kind(closure_def_id, closure_substs) {
767 Some(closure_kind) => {
768 if closure_kind.extends(kind) {
780 ty::Predicate::ConstEvaluatable(def_id, substs) => {
781 match self.tcx().lift_to_global(&(obligation.param_env, substs)) {
782 Some((param_env, substs)) => {
783 match self.tcx().const_eval(param_env.and((def_id, substs))) {
784 Ok(_) => EvaluatedToOk,
785 Err(_) => EvaluatedToErr
789 // Inference variables still left in param_env or substs.
797 fn evaluate_trait_predicate_recursively<'o>(&mut self,
798 previous_stack: TraitObligationStackList<'o, 'tcx>,
799 mut obligation: TraitObligation<'tcx>)
802 debug!("evaluate_trait_predicate_recursively({:?})",
805 if !self.intercrate.is_some() && obligation.is_global() {
806 // If a param env is consistent, global obligations do not depend on its particular
807 // value in order to work, so we can clear out the param env and get better
808 // caching. (If the current param env is inconsistent, we don't care what happens).
809 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
810 obligation.param_env = ty::ParamEnv::empty(obligation.param_env.reveal);
813 let stack = self.push_stack(previous_stack, &obligation);
814 let fresh_trait_ref = stack.fresh_trait_ref;
815 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
816 debug!("CACHE HIT: EVAL({:?})={:?}",
822 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
824 debug!("CACHE MISS: EVAL({:?})={:?}",
827 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
832 fn evaluate_stack<'o>(&mut self,
833 stack: &TraitObligationStack<'o, 'tcx>)
836 // In intercrate mode, whenever any of the types are unbound,
837 // there can always be an impl. Even if there are no impls in
838 // this crate, perhaps the type would be unified with
839 // something from another crate that does provide an impl.
841 // In intra mode, we must still be conservative. The reason is
842 // that we want to avoid cycles. Imagine an impl like:
844 // impl<T:Eq> Eq for Vec<T>
846 // and a trait reference like `$0 : Eq` where `$0` is an
847 // unbound variable. When we evaluate this trait-reference, we
848 // will unify `$0` with `Vec<$1>` (for some fresh variable
849 // `$1`), on the condition that `$1 : Eq`. We will then wind
850 // up with many candidates (since that are other `Eq` impls
851 // that apply) and try to winnow things down. This results in
852 // a recursive evaluation that `$1 : Eq` -- as you can
853 // imagine, this is just where we started. To avoid that, we
854 // check for unbound variables and return an ambiguous (hence possible)
855 // match if we've seen this trait before.
857 // This suffices to allow chains like `FnMut` implemented in
858 // terms of `Fn` etc, but we could probably make this more
860 let unbound_input_types = stack.fresh_trait_ref.input_types().any(|ty| ty.is_fresh());
861 // this check was an imperfect workaround for a bug n the old
862 // intercrate mode, it should be removed when that goes away.
863 if unbound_input_types &&
864 self.intercrate == Some(IntercrateMode::Issue43355)
866 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
867 stack.fresh_trait_ref);
868 // Heuristics: show the diagnostics when there are no candidates in crate.
869 if self.intercrate_ambiguity_causes.is_some() {
870 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
871 if let Ok(candidate_set) = self.assemble_candidates(stack) {
872 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
873 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
874 let self_ty = trait_ref.self_ty();
875 let cause = IntercrateAmbiguityCause::DownstreamCrate {
876 trait_desc: trait_ref.to_string(),
877 self_desc: if self_ty.has_concrete_skeleton() {
878 Some(self_ty.to_string())
883 debug!("evaluate_stack: pushing cause = {:?}", cause);
884 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
888 return EvaluatedToAmbig;
890 if unbound_input_types &&
891 stack.iter().skip(1).any(
892 |prev| stack.obligation.param_env == prev.obligation.param_env &&
893 self.match_fresh_trait_refs(&stack.fresh_trait_ref,
894 &prev.fresh_trait_ref))
896 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
897 stack.fresh_trait_ref);
898 return EvaluatedToUnknown;
901 // If there is any previous entry on the stack that precisely
902 // matches this obligation, then we can assume that the
903 // obligation is satisfied for now (still all other conditions
904 // must be met of course). One obvious case this comes up is
905 // marker traits like `Send`. Think of a linked list:
907 // struct List<T> { data: T, next: Option<Box<List<T>>> {
909 // `Box<List<T>>` will be `Send` if `T` is `Send` and
910 // `Option<Box<List<T>>>` is `Send`, and in turn
911 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
914 // Note that we do this comparison using the `fresh_trait_ref`
915 // fields. Because these have all been skolemized using
916 // `self.freshener`, we can be sure that (a) this will not
917 // affect the inferencer state and (b) that if we see two
918 // skolemized types with the same index, they refer to the
919 // same unbound type variable.
920 if let Some(rec_index) =
922 .skip(1) // skip top-most frame
923 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
924 stack.fresh_trait_ref == prev.fresh_trait_ref)
926 debug!("evaluate_stack({:?}) --> recursive",
927 stack.fresh_trait_ref);
928 let cycle = stack.iter().skip(1).take(rec_index+1);
929 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
930 if self.coinductive_match(cycle) {
931 debug!("evaluate_stack({:?}) --> recursive, coinductive",
932 stack.fresh_trait_ref);
933 return EvaluatedToOk;
935 debug!("evaluate_stack({:?}) --> recursive, inductive",
936 stack.fresh_trait_ref);
937 return EvaluatedToRecur;
941 match self.candidate_from_obligation(stack) {
942 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
943 Ok(None) => EvaluatedToAmbig,
944 Err(..) => EvaluatedToErr
948 /// For defaulted traits, we use a co-inductive strategy to solve, so
949 /// that recursion is ok. This routine returns true if the top of the
950 /// stack (`cycle[0]`):
952 /// - is a defaulted trait, and
953 /// - it also appears in the backtrace at some position `X`; and,
954 /// - all the predicates at positions `X..` between `X` an the top are
955 /// also defaulted traits.
956 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
957 where I: Iterator<Item=ty::Predicate<'tcx>>
959 let mut cycle = cycle;
960 cycle.all(|predicate| self.coinductive_predicate(predicate))
963 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
964 let result = match predicate {
965 ty::Predicate::Trait(ref data) => {
966 self.tcx().trait_is_auto(data.def_id())
972 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
976 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
977 /// obligations are met. Returns true if `candidate` remains viable after this further
979 fn evaluate_candidate<'o>(&mut self,
980 stack: &TraitObligationStack<'o, 'tcx>,
981 candidate: &SelectionCandidate<'tcx>)
984 debug!("evaluate_candidate: depth={} candidate={:?}",
985 stack.obligation.recursion_depth, candidate);
986 let result = self.probe(|this, _| {
987 let candidate = (*candidate).clone();
988 match this.confirm_candidate(stack.obligation, candidate) {
990 this.evaluate_predicates_recursively(
992 selection.nested_obligations().iter())
994 Err(..) => EvaluatedToErr
997 debug!("evaluate_candidate: depth={} result={:?}",
998 stack.obligation.recursion_depth, result);
1002 fn check_evaluation_cache(&self,
1003 param_env: ty::ParamEnv<'tcx>,
1004 trait_ref: ty::PolyTraitRef<'tcx>)
1005 -> Option<EvaluationResult>
1007 let tcx = self.tcx();
1008 if self.can_use_global_caches(param_env) {
1009 let cache = tcx.evaluation_cache.hashmap.borrow();
1010 if let Some(cached) = cache.get(&trait_ref) {
1011 return Some(cached.get(tcx));
1014 self.infcx.evaluation_cache.hashmap
1017 .map(|v| v.get(tcx))
1020 fn insert_evaluation_cache(&mut self,
1021 param_env: ty::ParamEnv<'tcx>,
1022 trait_ref: ty::PolyTraitRef<'tcx>,
1023 dep_node: DepNodeIndex,
1024 result: EvaluationResult)
1026 // Avoid caching results that depend on more than just the trait-ref
1027 // - the stack can create recursion.
1028 if result.is_stack_dependent() {
1032 if self.can_use_global_caches(param_env) {
1033 let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
1034 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1035 cache.insert(trait_ref, WithDepNode::new(dep_node, result));
1040 self.infcx.evaluation_cache.hashmap
1042 .insert(trait_ref, WithDepNode::new(dep_node, result));
1045 ///////////////////////////////////////////////////////////////////////////
1046 // CANDIDATE ASSEMBLY
1048 // The selection process begins by examining all in-scope impls,
1049 // caller obligations, and so forth and assembling a list of
1050 // candidates. See [rustc guide] for more details.
1053 // https://rust-lang-nursery.github.io/rustc-guide/trait-resolution.html#candidate-assembly
1055 fn candidate_from_obligation<'o>(&mut self,
1056 stack: &TraitObligationStack<'o, 'tcx>)
1057 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1059 // Watch out for overflow. This intentionally bypasses (and does
1060 // not update) the cache.
1061 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
1062 if stack.obligation.recursion_depth >= recursion_limit {
1063 self.infcx().report_overflow_error(&stack.obligation, true);
1066 // Check the cache. Note that we skolemize the trait-ref
1067 // separately rather than using `stack.fresh_trait_ref` -- this
1068 // is because we want the unbound variables to be replaced
1069 // with fresh skolemized types starting from index 0.
1070 let cache_fresh_trait_pred =
1071 self.infcx.freshen(stack.obligation.predicate.clone());
1072 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1073 cache_fresh_trait_pred,
1075 assert!(!stack.obligation.predicate.has_escaping_regions());
1077 if let Some(c) = self.check_candidate_cache(stack.obligation.param_env,
1078 &cache_fresh_trait_pred) {
1079 debug!("CACHE HIT: SELECT({:?})={:?}",
1080 cache_fresh_trait_pred,
1085 // If no match, compute result and insert into cache.
1086 let (candidate, dep_node) = self.in_task(|this| {
1087 this.candidate_from_obligation_no_cache(stack)
1090 debug!("CACHE MISS: SELECT({:?})={:?}",
1091 cache_fresh_trait_pred, candidate);
1092 self.insert_candidate_cache(stack.obligation.param_env,
1093 cache_fresh_trait_pred,
1099 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1100 where OP: FnOnce(&mut Self) -> R
1102 let (result, dep_node) = self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || {
1105 self.tcx().dep_graph.read_index(dep_node);
1109 // Treat negative impls as unimplemented
1110 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
1111 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1112 if let ImplCandidate(def_id) = candidate {
1113 if !self.allow_negative_impls &&
1114 self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative {
1115 return Err(Unimplemented)
1121 fn candidate_from_obligation_no_cache<'o>(&mut self,
1122 stack: &TraitObligationStack<'o, 'tcx>)
1123 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1125 if stack.obligation.predicate.references_error() {
1126 // If we encounter a `TyError`, we generally prefer the
1127 // most "optimistic" result in response -- that is, the
1128 // one least likely to report downstream errors. But
1129 // because this routine is shared by coherence and by
1130 // trait selection, there isn't an obvious "right" choice
1131 // here in that respect, so we opt to just return
1132 // ambiguity and let the upstream clients sort it out.
1136 match self.is_knowable(stack) {
1139 debug!("coherence stage: not knowable");
1140 if self.intercrate_ambiguity_causes.is_some() {
1141 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1142 // Heuristics: show the diagnostics when there are no candidates in crate.
1143 let candidate_set = self.assemble_candidates(stack)?;
1144 if !candidate_set.ambiguous && candidate_set.vec.iter().all(|c| {
1145 !self.evaluate_candidate(stack, &c).may_apply()
1147 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1148 let self_ty = trait_ref.self_ty();
1149 let trait_desc = trait_ref.to_string();
1150 let self_desc = if self_ty.has_concrete_skeleton() {
1151 Some(self_ty.to_string())
1155 let cause = if let Conflict::Upstream = conflict {
1156 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1158 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1160 debug!("evaluate_stack: pushing cause = {:?}", cause);
1161 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1168 let candidate_set = self.assemble_candidates(stack)?;
1170 if candidate_set.ambiguous {
1171 debug!("candidate set contains ambig");
1175 let mut candidates = candidate_set.vec;
1177 debug!("assembled {} candidates for {:?}: {:?}",
1182 // At this point, we know that each of the entries in the
1183 // candidate set is *individually* applicable. Now we have to
1184 // figure out if they contain mutual incompatibilities. This
1185 // frequently arises if we have an unconstrained input type --
1186 // for example, we are looking for $0:Eq where $0 is some
1187 // unconstrained type variable. In that case, we'll get a
1188 // candidate which assumes $0 == int, one that assumes $0 ==
1189 // usize, etc. This spells an ambiguity.
1191 // If there is more than one candidate, first winnow them down
1192 // by considering extra conditions (nested obligations and so
1193 // forth). We don't winnow if there is exactly one
1194 // candidate. This is a relatively minor distinction but it
1195 // can lead to better inference and error-reporting. An
1196 // example would be if there was an impl:
1198 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1200 // and we were to see some code `foo.push_clone()` where `boo`
1201 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1202 // we were to winnow, we'd wind up with zero candidates.
1203 // Instead, we select the right impl now but report `Bar does
1204 // not implement Clone`.
1205 if candidates.len() == 1 {
1206 return self.filter_negative_impls(candidates.pop().unwrap());
1209 // Winnow, but record the exact outcome of evaluation, which
1210 // is needed for specialization.
1211 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
1212 let eval = self.evaluate_candidate(stack, &c);
1213 if eval.may_apply() {
1214 Some(EvaluatedCandidate {
1223 // If there are STILL multiple candidate, we can further
1224 // reduce the list by dropping duplicates -- including
1225 // resolving specializations.
1226 if candidates.len() > 1 {
1228 while i < candidates.len() {
1230 (0..candidates.len())
1231 .filter(|&j| i != j)
1232 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
1235 debug!("Dropping candidate #{}/{}: {:?}",
1236 i, candidates.len(), candidates[i]);
1237 candidates.swap_remove(i);
1239 debug!("Retaining candidate #{}/{}: {:?}",
1240 i, candidates.len(), candidates[i]);
1243 // If there are *STILL* multiple candidates, give up
1244 // and report ambiguity.
1246 debug!("multiple matches, ambig");
1253 // If there are *NO* candidates, then there are no impls --
1254 // that we know of, anyway. Note that in the case where there
1255 // are unbound type variables within the obligation, it might
1256 // be the case that you could still satisfy the obligation
1257 // from another crate by instantiating the type variables with
1258 // a type from another crate that does have an impl. This case
1259 // is checked for in `evaluate_stack` (and hence users
1260 // who might care about this case, like coherence, should use
1262 if candidates.is_empty() {
1263 return Err(Unimplemented);
1266 // Just one candidate left.
1267 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1270 fn is_knowable<'o>(&mut self,
1271 stack: &TraitObligationStack<'o, 'tcx>)
1274 debug!("is_knowable(intercrate={:?})", self.intercrate);
1276 if !self.intercrate.is_some() {
1280 let obligation = &stack.obligation;
1281 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1283 // ok to skip binder because of the nature of the
1284 // trait-ref-is-knowable check, which does not care about
1286 let trait_ref = predicate.skip_binder().trait_ref;
1288 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1289 if let (Some(Conflict::Downstream { used_to_be_broken: true }),
1290 Some(IntercrateMode::Issue43355)) = (result, self.intercrate) {
1291 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1298 /// Returns true if the global caches can be used.
1299 /// Do note that if the type itself is not in the
1300 /// global tcx, the local caches will be used.
1301 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1302 // If there are any where-clauses in scope, then we always use
1303 // a cache local to this particular scope. Otherwise, we
1304 // switch to a global cache. We used to try and draw
1305 // finer-grained distinctions, but that led to a serious of
1306 // annoying and weird bugs like #22019 and #18290. This simple
1307 // rule seems to be pretty clearly safe and also still retains
1308 // a very high hit rate (~95% when compiling rustc).
1309 if !param_env.caller_bounds.is_empty() {
1313 // Avoid using the master cache during coherence and just rely
1314 // on the local cache. This effectively disables caching
1315 // during coherence. It is really just a simplification to
1316 // avoid us having to fear that coherence results "pollute"
1317 // the master cache. Since coherence executes pretty quickly,
1318 // it's not worth going to more trouble to increase the
1319 // hit-rate I don't think.
1320 if self.intercrate.is_some() {
1324 // Otherwise, we can use the global cache.
1328 fn check_candidate_cache(&mut self,
1329 param_env: ty::ParamEnv<'tcx>,
1330 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1331 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1333 let tcx = self.tcx();
1334 let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1335 if self.can_use_global_caches(param_env) {
1336 let cache = tcx.selection_cache.hashmap.borrow();
1337 if let Some(cached) = cache.get(&trait_ref) {
1338 return Some(cached.get(tcx));
1341 self.infcx.selection_cache.hashmap
1344 .map(|v| v.get(tcx))
1347 fn insert_candidate_cache(&mut self,
1348 param_env: ty::ParamEnv<'tcx>,
1349 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1350 dep_node: DepNodeIndex,
1351 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1353 let tcx = self.tcx();
1354 let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1355 if self.can_use_global_caches(param_env) {
1356 let mut cache = tcx.selection_cache.hashmap.borrow_mut();
1357 if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1358 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1359 cache.insert(trait_ref, WithDepNode::new(dep_node, candidate));
1365 self.infcx.selection_cache.hashmap
1367 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1370 fn assemble_candidates<'o>(&mut self,
1371 stack: &TraitObligationStack<'o, 'tcx>)
1372 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1374 let TraitObligationStack { obligation, .. } = *stack;
1375 let ref obligation = Obligation {
1376 param_env: obligation.param_env,
1377 cause: obligation.cause.clone(),
1378 recursion_depth: obligation.recursion_depth,
1379 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1382 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1383 // Self is a type variable (e.g. `_: AsRef<str>`).
1385 // This is somewhat problematic, as the current scheme can't really
1386 // handle it turning to be a projection. This does end up as truly
1387 // ambiguous in most cases anyway.
1389 // Take the fast path out - this also improves
1390 // performance by preventing assemble_candidates_from_impls from
1391 // matching every impl for this trait.
1392 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1395 let mut candidates = SelectionCandidateSet {
1400 // Other bounds. Consider both in-scope bounds from fn decl
1401 // and applicable impls. There is a certain set of precedence rules here.
1403 let def_id = obligation.predicate.def_id();
1404 let lang_items = self.tcx().lang_items();
1405 if lang_items.copy_trait() == Some(def_id) {
1406 debug!("obligation self ty is {:?}",
1407 obligation.predicate.0.self_ty());
1409 // User-defined copy impls are permitted, but only for
1410 // structs and enums.
1411 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1413 // For other types, we'll use the builtin rules.
1414 let copy_conditions = self.copy_clone_conditions(obligation);
1415 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1416 } else if lang_items.sized_trait() == Some(def_id) {
1417 // Sized is never implementable by end-users, it is
1418 // always automatically computed.
1419 let sized_conditions = self.sized_conditions(obligation);
1420 self.assemble_builtin_bound_candidates(sized_conditions,
1422 } else if lang_items.unsize_trait() == Some(def_id) {
1423 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1425 if lang_items.clone_trait() == Some(def_id) {
1426 // Same builtin conditions as `Copy`, i.e. every type which has builtin support
1427 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1428 // types have builtin support for `Clone`.
1429 let clone_conditions = self.copy_clone_conditions(obligation);
1430 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1433 self.assemble_generator_candidates(obligation, &mut candidates)?;
1434 self.assemble_closure_candidates(obligation, &mut candidates)?;
1435 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1436 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1437 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1440 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1441 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1442 // Auto implementations have lower priority, so we only
1443 // consider triggering a default if there is no other impl that can apply.
1444 if candidates.vec.is_empty() {
1445 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1447 debug!("candidate list size: {}", candidates.vec.len());
1451 fn assemble_candidates_from_projected_tys(&mut self,
1452 obligation: &TraitObligation<'tcx>,
1453 candidates: &mut SelectionCandidateSet<'tcx>)
1455 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1457 // before we go into the whole skolemization thing, just
1458 // quickly check if the self-type is a projection at all.
1459 match obligation.predicate.0.trait_ref.self_ty().sty {
1460 ty::TyProjection(_) | ty::TyAnon(..) => {}
1461 ty::TyInfer(ty::TyVar(_)) => {
1462 span_bug!(obligation.cause.span,
1463 "Self=_ should have been handled by assemble_candidates");
1468 let result = self.probe(|this, snapshot| {
1469 this.match_projection_obligation_against_definition_bounds(obligation,
1474 candidates.vec.push(ProjectionCandidate);
1478 fn match_projection_obligation_against_definition_bounds(
1480 obligation: &TraitObligation<'tcx>,
1481 snapshot: &infer::CombinedSnapshot)
1484 let poly_trait_predicate =
1485 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1486 let (skol_trait_predicate, skol_map) =
1487 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1488 debug!("match_projection_obligation_against_definition_bounds: \
1489 skol_trait_predicate={:?} skol_map={:?}",
1490 skol_trait_predicate,
1493 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1494 ty::TyProjection(ref data) =>
1495 (data.trait_ref(self.tcx()).def_id, data.substs),
1496 ty::TyAnon(def_id, substs) => (def_id, substs),
1499 obligation.cause.span,
1500 "match_projection_obligation_against_definition_bounds() called \
1501 but self-ty not a projection: {:?}",
1502 skol_trait_predicate.trait_ref.self_ty());
1505 debug!("match_projection_obligation_against_definition_bounds: \
1506 def_id={:?}, substs={:?}",
1509 let predicates_of = self.tcx().predicates_of(def_id);
1510 let bounds = predicates_of.instantiate(self.tcx(), substs);
1511 debug!("match_projection_obligation_against_definition_bounds: \
1515 let matching_bound =
1516 util::elaborate_predicates(self.tcx(), bounds.predicates)
1520 |this, _| this.match_projection(obligation,
1522 skol_trait_predicate.trait_ref.clone(),
1526 debug!("match_projection_obligation_against_definition_bounds: \
1527 matching_bound={:?}",
1529 match matching_bound {
1532 // Repeat the successful match, if any, this time outside of a probe.
1533 let result = self.match_projection(obligation,
1535 skol_trait_predicate.trait_ref.clone(),
1539 self.infcx.pop_skolemized(skol_map, snapshot);
1547 fn match_projection(&mut self,
1548 obligation: &TraitObligation<'tcx>,
1549 trait_bound: ty::PolyTraitRef<'tcx>,
1550 skol_trait_ref: ty::TraitRef<'tcx>,
1551 skol_map: &infer::SkolemizationMap<'tcx>,
1552 snapshot: &infer::CombinedSnapshot)
1555 assert!(!skol_trait_ref.has_escaping_regions());
1556 match self.infcx.at(&obligation.cause, obligation.param_env)
1557 .sup(ty::Binder(skol_trait_ref), trait_bound) {
1558 Ok(InferOk { obligations, .. }) => {
1559 self.inferred_obligations.extend(obligations);
1561 Err(_) => { return false; }
1564 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1567 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1568 /// supplied to find out whether it is listed among them.
1570 /// Never affects inference environment.
1571 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1572 stack: &TraitObligationStack<'o, 'tcx>,
1573 candidates: &mut SelectionCandidateSet<'tcx>)
1574 -> Result<(),SelectionError<'tcx>>
1576 debug!("assemble_candidates_from_caller_bounds({:?})",
1580 stack.obligation.param_env.caller_bounds
1582 .filter_map(|o| o.to_opt_poly_trait_ref());
1584 // micro-optimization: filter out predicates relating to different
1586 let matching_bounds =
1587 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1589 let matching_bounds =
1590 matching_bounds.filter(
1591 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1593 let param_candidates =
1594 matching_bounds.map(|bound| ParamCandidate(bound));
1596 candidates.vec.extend(param_candidates);
1601 fn evaluate_where_clause<'o>(&mut self,
1602 stack: &TraitObligationStack<'o, 'tcx>,
1603 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1606 self.probe(move |this, _| {
1607 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1608 Ok(obligations) => {
1609 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1611 Err(()) => EvaluatedToErr
1616 fn assemble_generator_candidates(&mut self,
1617 obligation: &TraitObligation<'tcx>,
1618 candidates: &mut SelectionCandidateSet<'tcx>)
1619 -> Result<(),SelectionError<'tcx>>
1621 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1625 // ok to skip binder because the substs on generator types never
1626 // touch bound regions, they just capture the in-scope
1627 // type/region parameters
1628 let self_ty = *obligation.self_ty().skip_binder();
1630 ty::TyGenerator(..) => {
1631 debug!("assemble_generator_candidates: self_ty={:?} obligation={:?}",
1635 candidates.vec.push(GeneratorCandidate);
1638 ty::TyInfer(ty::TyVar(_)) => {
1639 debug!("assemble_generator_candidates: ambiguous self-type");
1640 candidates.ambiguous = true;
1643 _ => { return Ok(()); }
1647 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1648 /// FnMut<..>` where `X` is a closure type.
1650 /// Note: the type parameters on a closure candidate are modeled as *output* type
1651 /// parameters and hence do not affect whether this trait is a match or not. They will be
1652 /// unified during the confirmation step.
1653 fn assemble_closure_candidates(&mut self,
1654 obligation: &TraitObligation<'tcx>,
1655 candidates: &mut SelectionCandidateSet<'tcx>)
1656 -> Result<(),SelectionError<'tcx>>
1658 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.0.def_id()) {
1660 None => { return Ok(()); }
1663 // ok to skip binder because the substs on closure types never
1664 // touch bound regions, they just capture the in-scope
1665 // type/region parameters
1666 match obligation.self_ty().skip_binder().sty {
1667 ty::TyClosure(closure_def_id, closure_substs) => {
1668 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}",
1670 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1671 Some(closure_kind) => {
1672 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1673 if closure_kind.extends(kind) {
1674 candidates.vec.push(ClosureCandidate);
1678 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1679 candidates.vec.push(ClosureCandidate);
1684 ty::TyInfer(ty::TyVar(_)) => {
1685 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1686 candidates.ambiguous = true;
1689 _ => { return Ok(()); }
1693 /// Implement one of the `Fn()` family for a fn pointer.
1694 fn assemble_fn_pointer_candidates(&mut self,
1695 obligation: &TraitObligation<'tcx>,
1696 candidates: &mut SelectionCandidateSet<'tcx>)
1697 -> Result<(),SelectionError<'tcx>>
1699 // We provide impl of all fn traits for fn pointers.
1700 if self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()).is_none() {
1704 // ok to skip binder because what we are inspecting doesn't involve bound regions
1705 let self_ty = *obligation.self_ty().skip_binder();
1707 ty::TyInfer(ty::TyVar(_)) => {
1708 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1709 candidates.ambiguous = true; // could wind up being a fn() type
1712 // provide an impl, but only for suitable `fn` pointers
1713 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
1714 if let ty::Binder(ty::FnSig {
1715 unsafety: hir::Unsafety::Normal,
1719 }) = self_ty.fn_sig(self.tcx()) {
1720 candidates.vec.push(FnPointerCandidate);
1730 /// Search for impls that might apply to `obligation`.
1731 fn assemble_candidates_from_impls(&mut self,
1732 obligation: &TraitObligation<'tcx>,
1733 candidates: &mut SelectionCandidateSet<'tcx>)
1734 -> Result<(), SelectionError<'tcx>>
1736 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1738 self.tcx().for_each_relevant_impl(
1739 obligation.predicate.def_id(),
1740 obligation.predicate.0.trait_ref.self_ty(),
1742 self.probe(|this, snapshot| { /* [1] */
1743 match this.match_impl(impl_def_id, obligation, snapshot) {
1745 candidates.vec.push(ImplCandidate(impl_def_id));
1747 // NB: we can safely drop the skol map
1748 // since we are in a probe [1]
1749 mem::drop(skol_map);
1760 fn assemble_candidates_from_auto_impls(&mut self,
1761 obligation: &TraitObligation<'tcx>,
1762 candidates: &mut SelectionCandidateSet<'tcx>)
1763 -> Result<(), SelectionError<'tcx>>
1765 // OK to skip binder here because the tests we do below do not involve bound regions
1766 let self_ty = *obligation.self_ty().skip_binder();
1767 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
1769 let def_id = obligation.predicate.def_id();
1771 if self.tcx().trait_is_auto(def_id) {
1773 ty::TyDynamic(..) => {
1774 // For object types, we don't know what the closed
1775 // over types are. This means we conservatively
1776 // say nothing; a candidate may be added by
1777 // `assemble_candidates_from_object_ty`.
1779 ty::TyForeign(..) => {
1780 // Since the contents of foreign types is unknown,
1781 // we don't add any `..` impl. Default traits could
1782 // still be provided by a manual implementation for
1783 // this trait and type.
1786 ty::TyProjection(..) => {
1787 // In these cases, we don't know what the actual
1788 // type is. Therefore, we cannot break it down
1789 // into its constituent types. So we don't
1790 // consider the `..` impl but instead just add no
1791 // candidates: this means that typeck will only
1792 // succeed if there is another reason to believe
1793 // that this obligation holds. That could be a
1794 // where-clause or, in the case of an object type,
1795 // it could be that the object type lists the
1796 // trait (e.g. `Foo+Send : Send`). See
1797 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1798 // for an example of a test case that exercises
1801 ty::TyInfer(ty::TyVar(_)) => {
1802 // the auto impl might apply, we don't know
1803 candidates.ambiguous = true;
1806 candidates.vec.push(AutoImplCandidate(def_id.clone()))
1814 /// Search for impls that might apply to `obligation`.
1815 fn assemble_candidates_from_object_ty(&mut self,
1816 obligation: &TraitObligation<'tcx>,
1817 candidates: &mut SelectionCandidateSet<'tcx>)
1819 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1820 obligation.self_ty().skip_binder());
1822 // Object-safety candidates are only applicable to object-safe
1823 // traits. Including this check is useful because it helps
1824 // inference in cases of traits like `BorrowFrom`, which are
1825 // not object-safe, and which rely on being able to infer the
1826 // self-type from one of the other inputs. Without this check,
1827 // these cases wind up being considered ambiguous due to a
1828 // (spurious) ambiguity introduced here.
1829 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1830 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1834 self.probe(|this, _snapshot| {
1835 // the code below doesn't care about regions, and the
1836 // self-ty here doesn't escape this probe, so just erase
1838 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1839 let poly_trait_ref = match self_ty.sty {
1840 ty::TyDynamic(ref data, ..) => {
1841 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1842 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1843 pushing candidate");
1844 candidates.vec.push(BuiltinObjectCandidate);
1848 match data.principal() {
1849 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1853 ty::TyInfer(ty::TyVar(_)) => {
1854 debug!("assemble_candidates_from_object_ty: ambiguous");
1855 candidates.ambiguous = true; // could wind up being an object type
1863 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1866 // Count only those upcast versions that match the trait-ref
1867 // we are looking for. Specifically, do not only check for the
1868 // correct trait, but also the correct type parameters.
1869 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1870 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1871 let upcast_trait_refs =
1872 util::supertraits(this.tcx(), poly_trait_ref)
1873 .filter(|upcast_trait_ref| {
1874 this.probe(|this, _| {
1875 let upcast_trait_ref = upcast_trait_ref.clone();
1876 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1881 if upcast_trait_refs > 1 {
1882 // can be upcast in many ways; need more type information
1883 candidates.ambiguous = true;
1884 } else if upcast_trait_refs == 1 {
1885 candidates.vec.push(ObjectCandidate);
1890 /// Search for unsizing that might apply to `obligation`.
1891 fn assemble_candidates_for_unsizing(&mut self,
1892 obligation: &TraitObligation<'tcx>,
1893 candidates: &mut SelectionCandidateSet<'tcx>) {
1894 // We currently never consider higher-ranked obligations e.g.
1895 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1896 // because they are a priori invalid, and we could potentially add support
1897 // for them later, it's just that there isn't really a strong need for it.
1898 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1899 // impl, and those are generally applied to concrete types.
1901 // That said, one might try to write a fn with a where clause like
1902 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1903 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1904 // Still, you'd be more likely to write that where clause as
1906 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1907 // obligation above. Should be possible to extend this in the future.
1908 let source = match obligation.self_ty().no_late_bound_regions() {
1911 // Don't add any candidates if there are bound regions.
1915 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1917 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1920 let may_apply = match (&source.sty, &target.sty) {
1921 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1922 (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1923 // Upcasts permit two things:
1925 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1926 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1928 // Note that neither of these changes requires any
1929 // change at runtime. Eventually this will be
1932 // We always upcast when we can because of reason
1933 // #2 (region bounds).
1934 match (data_a.principal(), data_b.principal()) {
1935 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1936 data_b.auto_traits()
1937 // All of a's auto traits need to be in b's auto traits.
1938 .all(|b| data_a.auto_traits().any(|a| a == b)),
1944 (_, &ty::TyDynamic(..)) => true,
1946 // Ambiguous handling is below T -> Trait, because inference
1947 // variables can still implement Unsize<Trait> and nested
1948 // obligations will have the final say (likely deferred).
1949 (&ty::TyInfer(ty::TyVar(_)), _) |
1950 (_, &ty::TyInfer(ty::TyVar(_))) => {
1951 debug!("assemble_candidates_for_unsizing: ambiguous");
1952 candidates.ambiguous = true;
1957 (&ty::TyArray(..), &ty::TySlice(_)) => true,
1959 // Struct<T> -> Struct<U>.
1960 (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1961 def_id_a == def_id_b
1964 // (.., T) -> (.., U).
1965 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
1966 tys_a.len() == tys_b.len()
1973 candidates.vec.push(BuiltinUnsizeCandidate);
1977 ///////////////////////////////////////////////////////////////////////////
1980 // Winnowing is the process of attempting to resolve ambiguity by
1981 // probing further. During the winnowing process, we unify all
1982 // type variables (ignoring skolemization) and then we also
1983 // attempt to evaluate recursive bounds to see if they are
1986 /// Returns true if `candidate_i` should be dropped in favor of
1987 /// `candidate_j`. Generally speaking we will drop duplicate
1988 /// candidates and prefer where-clause candidates.
1989 /// Returns true if `victim` should be dropped in favor of
1990 /// `other`. Generally speaking we will drop duplicate
1991 /// candidates and prefer where-clause candidates.
1993 /// See the comment for "SelectionCandidate" for more details.
1994 fn candidate_should_be_dropped_in_favor_of<'o>(
1996 victim: &EvaluatedCandidate<'tcx>,
1997 other: &EvaluatedCandidate<'tcx>)
2000 if victim.candidate == other.candidate {
2004 match other.candidate {
2006 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
2007 AutoImplCandidate(..) => {
2009 "default implementations shouldn't be recorded \
2010 when there are other valid candidates");
2014 GeneratorCandidate |
2015 FnPointerCandidate |
2016 BuiltinObjectCandidate |
2017 BuiltinUnsizeCandidate |
2018 BuiltinCandidate { .. } => {
2019 // We have a where-clause so don't go around looking
2024 ProjectionCandidate => {
2025 // Arbitrarily give param candidates priority
2026 // over projection and object candidates.
2029 ParamCandidate(..) => false,
2031 ImplCandidate(other_def) => {
2032 // See if we can toss out `victim` based on specialization.
2033 // This requires us to know *for sure* that the `other` impl applies
2034 // i.e. EvaluatedToOk:
2035 if other.evaluation == EvaluatedToOk {
2036 if let ImplCandidate(victim_def) = victim.candidate {
2037 let tcx = self.tcx().global_tcx();
2038 return tcx.specializes((other_def, victim_def)) ||
2039 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
2049 ///////////////////////////////////////////////////////////////////////////
2052 // These cover the traits that are built-in to the language
2053 // itself. This includes `Copy` and `Sized` for sure. For the
2054 // moment, it also includes `Send` / `Sync` and a few others, but
2055 // those will hopefully change to library-defined traits in the
2058 // HACK: if this returns an error, selection exits without considering
2060 fn assemble_builtin_bound_candidates<'o>(&mut self,
2061 conditions: BuiltinImplConditions<'tcx>,
2062 candidates: &mut SelectionCandidateSet<'tcx>)
2063 -> Result<(),SelectionError<'tcx>>
2066 BuiltinImplConditions::Where(nested) => {
2067 debug!("builtin_bound: nested={:?}", nested);
2068 candidates.vec.push(BuiltinCandidate {
2069 has_nested: nested.skip_binder().len() > 0
2073 BuiltinImplConditions::None => { Ok(()) }
2074 BuiltinImplConditions::Ambiguous => {
2075 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2076 Ok(candidates.ambiguous = true)
2078 BuiltinImplConditions::Never => { Err(Unimplemented) }
2082 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2083 -> BuiltinImplConditions<'tcx>
2085 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
2087 // NOTE: binder moved to (*)
2088 let self_ty = self.infcx.shallow_resolve(
2089 obligation.predicate.skip_binder().self_ty());
2092 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
2093 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
2094 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
2095 ty::TyChar | ty::TyRef(..) | ty::TyGenerator(..) |
2096 ty::TyGeneratorWitness(..) | ty::TyArray(..) | ty::TyClosure(..) |
2097 ty::TyNever | ty::TyError => {
2098 // safe for everything
2099 Where(ty::Binder(Vec::new()))
2102 ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) | ty::TyForeign(..) => Never,
2104 ty::TyTuple(tys, _) => {
2105 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
2108 ty::TyAdt(def, substs) => {
2109 let sized_crit = def.sized_constraint(self.tcx());
2110 // (*) binder moved here
2112 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
2116 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
2117 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
2119 ty::TyInfer(ty::FreshTy(_))
2120 | ty::TyInfer(ty::FreshIntTy(_))
2121 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2122 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2128 fn copy_clone_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2129 -> BuiltinImplConditions<'tcx>
2131 // NOTE: binder moved to (*)
2132 let self_ty = self.infcx.shallow_resolve(
2133 obligation.predicate.skip_binder().self_ty());
2135 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
2138 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
2139 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
2140 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
2141 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
2142 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
2143 Where(ty::Binder(Vec::new()))
2146 ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
2147 ty::TyGenerator(..) | ty::TyGeneratorWitness(..) | ty::TyForeign(..) |
2148 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
2152 ty::TyArray(element_ty, _) => {
2153 // (*) binder moved here
2154 Where(ty::Binder(vec![element_ty]))
2157 ty::TyTuple(tys, _) => {
2158 // (*) binder moved here
2159 Where(ty::Binder(tys.to_vec()))
2162 ty::TyClosure(def_id, substs) => {
2163 let trait_id = obligation.predicate.def_id();
2165 Some(trait_id) == self.tcx().lang_items().copy_trait() &&
2166 self.tcx().has_copy_closures(def_id.krate);
2167 let clone_closures =
2168 Some(trait_id) == self.tcx().lang_items().clone_trait() &&
2169 self.tcx().has_clone_closures(def_id.krate);
2171 if copy_closures || clone_closures {
2172 Where(ty::Binder(substs.upvar_tys(def_id, self.tcx()).collect()))
2178 ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
2179 // Fallback to whatever user-defined impls exist in this case.
2183 ty::TyInfer(ty::TyVar(_)) => {
2184 // Unbound type variable. Might or might not have
2185 // applicable impls and so forth, depending on what
2186 // those type variables wind up being bound to.
2190 ty::TyInfer(ty::FreshTy(_))
2191 | ty::TyInfer(ty::FreshIntTy(_))
2192 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2193 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2199 /// For default impls, we need to break apart a type into its
2200 /// "constituent types" -- meaning, the types that it contains.
2202 /// Here are some (simple) examples:
2205 /// (i32, u32) -> [i32, u32]
2206 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2207 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2208 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2210 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2220 ty::TyInfer(ty::IntVar(_)) |
2221 ty::TyInfer(ty::FloatVar(_)) |
2230 ty::TyProjection(..) |
2231 ty::TyInfer(ty::TyVar(_)) |
2232 ty::TyInfer(ty::FreshTy(_)) |
2233 ty::TyInfer(ty::FreshIntTy(_)) |
2234 ty::TyInfer(ty::FreshFloatTy(_)) => {
2235 bug!("asked to assemble constituent types of unexpected type: {:?}",
2239 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
2240 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
2244 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
2248 ty::TyTuple(ref tys, _) => {
2249 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2253 ty::TyClosure(def_id, ref substs) => {
2254 substs.upvar_tys(def_id, self.tcx()).collect()
2257 ty::TyGenerator(def_id, ref substs, interior) => {
2258 substs.upvar_tys(def_id, self.tcx()).chain(iter::once(interior.witness)).collect()
2261 ty::TyGeneratorWitness(types) => {
2262 // This is sound because no regions in the witness can refer to
2263 // the binder outside the witness. So we'll effectivly reuse
2264 // the implicit binder around the witness.
2265 types.skip_binder().to_vec()
2268 // for `PhantomData<T>`, we pass `T`
2269 ty::TyAdt(def, substs) if def.is_phantom_data() => {
2270 substs.types().collect()
2273 ty::TyAdt(def, substs) => {
2275 .map(|f| f.ty(self.tcx(), substs))
2279 ty::TyAnon(def_id, substs) => {
2280 // We can resolve the `impl Trait` to its concrete type,
2281 // which enforces a DAG between the functions requiring
2282 // the auto trait bounds in question.
2283 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2288 fn collect_predicates_for_types(&mut self,
2289 param_env: ty::ParamEnv<'tcx>,
2290 cause: ObligationCause<'tcx>,
2291 recursion_depth: usize,
2292 trait_def_id: DefId,
2293 types: ty::Binder<Vec<Ty<'tcx>>>)
2294 -> Vec<PredicateObligation<'tcx>>
2296 // Because the types were potentially derived from
2297 // higher-ranked obligations they may reference late-bound
2298 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2299 // yield a type like `for<'a> &'a int`. In general, we
2300 // maintain the invariant that we never manipulate bound
2301 // regions, so we have to process these bound regions somehow.
2303 // The strategy is to:
2305 // 1. Instantiate those regions to skolemized regions (e.g.,
2306 // `for<'a> &'a int` becomes `&0 int`.
2307 // 2. Produce something like `&'0 int : Copy`
2308 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2310 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
2311 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
2313 self.in_snapshot(|this, snapshot| {
2314 let (skol_ty, skol_map) =
2315 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
2316 let Normalized { value: normalized_ty, mut obligations } =
2317 project::normalize_with_depth(this,
2322 let skol_obligation =
2323 this.tcx().predicate_for_trait_def(param_env,
2329 obligations.push(skol_obligation);
2330 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2335 ///////////////////////////////////////////////////////////////////////////
2338 // Confirmation unifies the output type parameters of the trait
2339 // with the values found in the obligation, possibly yielding a
2340 // type error. See [rustc guide] for more details.
2343 // https://rust-lang-nursery.github.io/rustc-guide/trait-resolution.html#confirmation
2345 fn confirm_candidate(&mut self,
2346 obligation: &TraitObligation<'tcx>,
2347 candidate: SelectionCandidate<'tcx>)
2348 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2350 debug!("confirm_candidate({:?}, {:?})",
2355 BuiltinCandidate { has_nested } => {
2356 let data = self.confirm_builtin_candidate(obligation, has_nested);
2357 Ok(VtableBuiltin(data))
2360 ParamCandidate(param) => {
2361 let obligations = self.confirm_param_candidate(obligation, param);
2362 Ok(VtableParam(obligations))
2365 AutoImplCandidate(trait_def_id) => {
2366 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2367 Ok(VtableAutoImpl(data))
2370 ImplCandidate(impl_def_id) => {
2371 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2374 ClosureCandidate => {
2375 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2376 Ok(VtableClosure(vtable_closure))
2379 GeneratorCandidate => {
2380 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2381 Ok(VtableGenerator(vtable_generator))
2384 BuiltinObjectCandidate => {
2385 // This indicates something like `(Trait+Send) :
2386 // Send`. In this case, we know that this holds
2387 // because that's what the object type is telling us,
2388 // and there's really no additional obligations to
2389 // prove and no types in particular to unify etc.
2390 Ok(VtableParam(Vec::new()))
2393 ObjectCandidate => {
2394 let data = self.confirm_object_candidate(obligation);
2395 Ok(VtableObject(data))
2398 FnPointerCandidate => {
2400 self.confirm_fn_pointer_candidate(obligation)?;
2401 Ok(VtableFnPointer(data))
2404 ProjectionCandidate => {
2405 self.confirm_projection_candidate(obligation);
2406 Ok(VtableParam(Vec::new()))
2409 BuiltinUnsizeCandidate => {
2410 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2411 Ok(VtableBuiltin(data))
2416 fn confirm_projection_candidate(&mut self,
2417 obligation: &TraitObligation<'tcx>)
2419 self.in_snapshot(|this, snapshot| {
2421 this.match_projection_obligation_against_definition_bounds(obligation,
2427 fn confirm_param_candidate(&mut self,
2428 obligation: &TraitObligation<'tcx>,
2429 param: ty::PolyTraitRef<'tcx>)
2430 -> Vec<PredicateObligation<'tcx>>
2432 debug!("confirm_param_candidate({:?},{:?})",
2436 // During evaluation, we already checked that this
2437 // where-clause trait-ref could be unified with the obligation
2438 // trait-ref. Repeat that unification now without any
2439 // transactional boundary; it should not fail.
2440 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2441 Ok(obligations) => obligations,
2443 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2450 fn confirm_builtin_candidate(&mut self,
2451 obligation: &TraitObligation<'tcx>,
2453 -> VtableBuiltinData<PredicateObligation<'tcx>>
2455 debug!("confirm_builtin_candidate({:?}, {:?})",
2456 obligation, has_nested);
2458 let lang_items = self.tcx().lang_items();
2459 let obligations = if has_nested {
2460 let trait_def = obligation.predicate.def_id();
2461 let conditions = match trait_def {
2462 _ if Some(trait_def) == lang_items.sized_trait() => {
2463 self.sized_conditions(obligation)
2465 _ if Some(trait_def) == lang_items.copy_trait() => {
2466 self.copy_clone_conditions(obligation)
2468 _ if Some(trait_def) == lang_items.clone_trait() => {
2469 self.copy_clone_conditions(obligation)
2471 _ => bug!("unexpected builtin trait {:?}", trait_def)
2473 let nested = match conditions {
2474 BuiltinImplConditions::Where(nested) => nested,
2475 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2479 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2480 self.collect_predicates_for_types(obligation.param_env,
2482 obligation.recursion_depth+1,
2489 debug!("confirm_builtin_candidate: obligations={:?}",
2492 VtableBuiltinData { nested: obligations }
2495 /// This handles the case where a `auto trait Foo` impl is being used.
2496 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2498 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2499 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2500 fn confirm_auto_impl_candidate(&mut self,
2501 obligation: &TraitObligation<'tcx>,
2502 trait_def_id: DefId)
2503 -> VtableAutoImplData<PredicateObligation<'tcx>>
2505 debug!("confirm_auto_impl_candidate({:?}, {:?})",
2509 // binder is moved below
2510 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2511 let types = self.constituent_types_for_ty(self_ty);
2512 self.vtable_auto_impl(obligation, trait_def_id, ty::Binder(types))
2515 /// See `confirm_auto_impl_candidate`
2516 fn vtable_auto_impl(&mut self,
2517 obligation: &TraitObligation<'tcx>,
2518 trait_def_id: DefId,
2519 nested: ty::Binder<Vec<Ty<'tcx>>>)
2520 -> VtableAutoImplData<PredicateObligation<'tcx>>
2522 debug!("vtable_auto_impl: nested={:?}", nested);
2524 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2525 let mut obligations = self.collect_predicates_for_types(
2526 obligation.param_env,
2528 obligation.recursion_depth+1,
2532 let trait_obligations = self.in_snapshot(|this, snapshot| {
2533 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2534 let (trait_ref, skol_map) =
2535 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2536 let cause = obligation.derived_cause(ImplDerivedObligation);
2537 this.impl_or_trait_obligations(cause,
2538 obligation.recursion_depth + 1,
2539 obligation.param_env,
2546 obligations.extend(trait_obligations);
2548 debug!("vtable_auto_impl: obligations={:?}", obligations);
2550 VtableAutoImplData {
2556 fn confirm_impl_candidate(&mut self,
2557 obligation: &TraitObligation<'tcx>,
2559 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2561 debug!("confirm_impl_candidate({:?},{:?})",
2565 // First, create the substitutions by matching the impl again,
2566 // this time not in a probe.
2567 self.in_snapshot(|this, snapshot| {
2568 let (substs, skol_map) =
2569 this.rematch_impl(impl_def_id, obligation,
2571 debug!("confirm_impl_candidate substs={:?}", substs);
2572 let cause = obligation.derived_cause(ImplDerivedObligation);
2573 this.vtable_impl(impl_def_id,
2576 obligation.recursion_depth + 1,
2577 obligation.param_env,
2583 fn vtable_impl(&mut self,
2585 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2586 cause: ObligationCause<'tcx>,
2587 recursion_depth: usize,
2588 param_env: ty::ParamEnv<'tcx>,
2589 skol_map: infer::SkolemizationMap<'tcx>,
2590 snapshot: &infer::CombinedSnapshot)
2591 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2593 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2599 let mut impl_obligations =
2600 self.impl_or_trait_obligations(cause,
2608 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2612 // Because of RFC447, the impl-trait-ref and obligations
2613 // are sufficient to determine the impl substs, without
2614 // relying on projections in the impl-trait-ref.
2616 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2617 impl_obligations.append(&mut substs.obligations);
2619 VtableImplData { impl_def_id,
2620 substs: substs.value,
2621 nested: impl_obligations }
2624 fn confirm_object_candidate(&mut self,
2625 obligation: &TraitObligation<'tcx>)
2626 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2628 debug!("confirm_object_candidate({:?})",
2631 // FIXME skipping binder here seems wrong -- we should
2632 // probably flatten the binder from the obligation and the
2633 // binder from the object. Have to try to make a broken test
2634 // case that results. -nmatsakis
2635 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2636 let poly_trait_ref = match self_ty.sty {
2637 ty::TyDynamic(ref data, ..) => {
2638 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2641 span_bug!(obligation.cause.span,
2642 "object candidate with non-object");
2646 let mut upcast_trait_ref = None;
2650 let tcx = self.tcx();
2652 // We want to find the first supertrait in the list of
2653 // supertraits that we can unify with, and do that
2654 // unification. We know that there is exactly one in the list
2655 // where we can unify because otherwise select would have
2656 // reported an ambiguity. (When we do find a match, also
2657 // record it for later.)
2659 util::supertraits(tcx, poly_trait_ref)
2663 |this, _| this.match_poly_trait_ref(obligation, t))
2665 Ok(_) => { upcast_trait_ref = Some(t); false }
2670 // Additionally, for each of the nonmatching predicates that
2671 // we pass over, we sum up the set of number of vtable
2672 // entries, so that we can compute the offset for the selected
2675 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2681 upcast_trait_ref: upcast_trait_ref.unwrap(),
2687 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2688 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2690 debug!("confirm_fn_pointer_candidate({:?})",
2693 // ok to skip binder; it is reintroduced below
2694 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2695 let sig = self_ty.fn_sig(self.tcx());
2697 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2700 util::TupleArgumentsFlag::Yes)
2701 .map_bound(|(trait_ref, _)| trait_ref);
2703 let Normalized { value: trait_ref, obligations } =
2704 project::normalize_with_depth(self,
2705 obligation.param_env,
2706 obligation.cause.clone(),
2707 obligation.recursion_depth + 1,
2710 self.confirm_poly_trait_refs(obligation.cause.clone(),
2711 obligation.param_env,
2712 obligation.predicate.to_poly_trait_ref(),
2714 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2717 fn confirm_generator_candidate(&mut self,
2718 obligation: &TraitObligation<'tcx>)
2719 -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
2720 SelectionError<'tcx>>
2722 // ok to skip binder because the substs on generator types never
2723 // touch bound regions, they just capture the in-scope
2724 // type/region parameters
2725 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2726 let (closure_def_id, substs) = match self_ty.sty {
2727 ty::TyGenerator(id, substs, _) => (id, substs),
2728 _ => bug!("closure candidate for non-closure {:?}", obligation)
2731 debug!("confirm_generator_candidate({:?},{:?},{:?})",
2737 self.generator_trait_ref_unnormalized(obligation, closure_def_id, substs);
2741 } = normalize_with_depth(self,
2742 obligation.param_env,
2743 obligation.cause.clone(),
2744 obligation.recursion_depth+1,
2747 debug!("confirm_generator_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2752 self.confirm_poly_trait_refs(obligation.cause.clone(),
2753 obligation.param_env,
2754 obligation.predicate.to_poly_trait_ref(),
2757 Ok(VtableGeneratorData {
2758 closure_def_id: closure_def_id,
2759 substs: substs.clone(),
2764 fn confirm_closure_candidate(&mut self,
2765 obligation: &TraitObligation<'tcx>)
2766 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2767 SelectionError<'tcx>>
2769 debug!("confirm_closure_candidate({:?})", obligation);
2771 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.0.def_id()) {
2773 None => bug!("closure candidate for non-fn trait {:?}", obligation)
2776 // ok to skip binder because the substs on closure types never
2777 // touch bound regions, they just capture the in-scope
2778 // type/region parameters
2779 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2780 let (closure_def_id, substs) = match self_ty.sty {
2781 ty::TyClosure(id, substs) => (id, substs),
2782 _ => bug!("closure candidate for non-closure {:?}", obligation)
2786 self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
2790 } = normalize_with_depth(self,
2791 obligation.param_env,
2792 obligation.cause.clone(),
2793 obligation.recursion_depth+1,
2796 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2801 self.confirm_poly_trait_refs(obligation.cause.clone(),
2802 obligation.param_env,
2803 obligation.predicate.to_poly_trait_ref(),
2806 obligations.push(Obligation::new(
2807 obligation.cause.clone(),
2808 obligation.param_env,
2809 ty::Predicate::ClosureKind(closure_def_id, substs, kind)));
2811 Ok(VtableClosureData {
2813 substs: substs.clone(),
2818 /// In the case of closure types and fn pointers,
2819 /// we currently treat the input type parameters on the trait as
2820 /// outputs. This means that when we have a match we have only
2821 /// considered the self type, so we have to go back and make sure
2822 /// to relate the argument types too. This is kind of wrong, but
2823 /// since we control the full set of impls, also not that wrong,
2824 /// and it DOES yield better error messages (since we don't report
2825 /// errors as if there is no applicable impl, but rather report
2826 /// errors are about mismatched argument types.
2828 /// Here is an example. Imagine we have a closure expression
2829 /// and we desugared it so that the type of the expression is
2830 /// `Closure`, and `Closure` expects an int as argument. Then it
2831 /// is "as if" the compiler generated this impl:
2833 /// impl Fn(int) for Closure { ... }
2835 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2836 /// we have matched the self-type `Closure`. At this point we'll
2837 /// compare the `int` to `usize` and generate an error.
2839 /// Note that this checking occurs *after* the impl has selected,
2840 /// because these output type parameters should not affect the
2841 /// selection of the impl. Therefore, if there is a mismatch, we
2842 /// report an error to the user.
2843 fn confirm_poly_trait_refs(&mut self,
2844 obligation_cause: ObligationCause<'tcx>,
2845 obligation_param_env: ty::ParamEnv<'tcx>,
2846 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2847 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2848 -> Result<(), SelectionError<'tcx>>
2850 let obligation_trait_ref = obligation_trait_ref.clone();
2852 .at(&obligation_cause, obligation_param_env)
2853 .sup(obligation_trait_ref, expected_trait_ref)
2854 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2855 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2858 fn confirm_builtin_unsize_candidate(&mut self,
2859 obligation: &TraitObligation<'tcx>,)
2860 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>>
2862 let tcx = self.tcx();
2864 // assemble_candidates_for_unsizing should ensure there are no late bound
2865 // regions here. See the comment there for more details.
2866 let source = self.infcx.shallow_resolve(
2867 obligation.self_ty().no_late_bound_regions().unwrap());
2868 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2869 let target = self.infcx.shallow_resolve(target);
2871 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2874 let mut nested = vec![];
2875 match (&source.sty, &target.sty) {
2876 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2877 (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2878 // See assemble_candidates_for_unsizing for more info.
2879 // Binders reintroduced below in call to mk_existential_predicates.
2880 let principal = data_a.skip_binder().principal();
2881 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2882 .chain(data_a.skip_binder().projection_bounds()
2883 .map(|x| ty::ExistentialPredicate::Projection(x)))
2884 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2885 let new_trait = tcx.mk_dynamic(
2886 ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2887 let InferOk { obligations, .. } =
2888 self.infcx.at(&obligation.cause, obligation.param_env)
2889 .eq(target, new_trait)
2890 .map_err(|_| Unimplemented)?;
2891 self.inferred_obligations.extend(obligations);
2893 // Register one obligation for 'a: 'b.
2894 let cause = ObligationCause::new(obligation.cause.span,
2895 obligation.cause.body_id,
2896 ObjectCastObligation(target));
2897 let outlives = ty::OutlivesPredicate(r_a, r_b);
2898 nested.push(Obligation::with_depth(cause,
2899 obligation.recursion_depth + 1,
2900 obligation.param_env,
2901 ty::Binder(outlives).to_predicate()));
2905 (_, &ty::TyDynamic(ref data, r)) => {
2906 let mut object_dids =
2907 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2908 if let Some(did) = object_dids.find(|did| {
2909 !tcx.is_object_safe(*did)
2911 return Err(TraitNotObjectSafe(did))
2914 let cause = ObligationCause::new(obligation.cause.span,
2915 obligation.cause.body_id,
2916 ObjectCastObligation(target));
2917 let mut push = |predicate| {
2918 nested.push(Obligation::with_depth(cause.clone(),
2919 obligation.recursion_depth + 1,
2920 obligation.param_env,
2924 // Create obligations:
2925 // - Casting T to Trait
2926 // - For all the various builtin bounds attached to the object cast. (In other
2927 // words, if the object type is Foo+Send, this would create an obligation for the
2929 // - Projection predicates
2930 for predicate in data.iter() {
2931 push(predicate.with_self_ty(tcx, source));
2934 // We can only make objects from sized types.
2935 let tr = ty::TraitRef {
2936 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2937 substs: tcx.mk_substs_trait(source, &[]),
2939 push(tr.to_predicate());
2941 // If the type is `Foo+'a`, ensures that the type
2942 // being cast to `Foo+'a` outlives `'a`:
2943 let outlives = ty::OutlivesPredicate(source, r);
2944 push(ty::Binder(outlives).to_predicate());
2948 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2949 let InferOk { obligations, .. } =
2950 self.infcx.at(&obligation.cause, obligation.param_env)
2952 .map_err(|_| Unimplemented)?;
2953 self.inferred_obligations.extend(obligations);
2956 // Struct<T> -> Struct<U>.
2957 (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2960 .map(|f| tcx.type_of(f.did))
2961 .collect::<Vec<_>>();
2963 // The last field of the structure has to exist and contain type parameters.
2964 let field = if let Some(&field) = fields.last() {
2967 return Err(Unimplemented);
2969 let mut ty_params = BitVector::new(substs_a.types().count());
2970 let mut found = false;
2971 for ty in field.walk() {
2972 if let ty::TyParam(p) = ty.sty {
2973 ty_params.insert(p.idx as usize);
2978 return Err(Unimplemented);
2981 // Replace type parameters used in unsizing with
2982 // TyError and ensure they do not affect any other fields.
2983 // This could be checked after type collection for any struct
2984 // with a potentially unsized trailing field.
2985 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2986 if ty_params.contains(i) {
2987 Kind::from(tcx.types.err)
2992 let substs = tcx.mk_substs(params);
2993 for &ty in fields.split_last().unwrap().1 {
2994 if ty.subst(tcx, substs).references_error() {
2995 return Err(Unimplemented);
2999 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3000 let inner_source = field.subst(tcx, substs_a);
3001 let inner_target = field.subst(tcx, substs_b);
3003 // Check that the source struct with the target's
3004 // unsized parameters is equal to the target.
3005 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3006 if ty_params.contains(i) {
3007 substs_b.type_at(i).into()
3012 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3013 let InferOk { obligations, .. } =
3014 self.infcx.at(&obligation.cause, obligation.param_env)
3015 .eq(target, new_struct)
3016 .map_err(|_| Unimplemented)?;
3017 self.inferred_obligations.extend(obligations);
3019 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3020 nested.push(tcx.predicate_for_trait_def(
3021 obligation.param_env,
3022 obligation.cause.clone(),
3023 obligation.predicate.def_id(),
3024 obligation.recursion_depth + 1,
3029 // (.., T) -> (.., U).
3030 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
3031 assert_eq!(tys_a.len(), tys_b.len());
3033 // The last field of the tuple has to exist.
3034 let (a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3037 return Err(Unimplemented);
3039 let b_last = tys_b.last().unwrap();
3041 // Check that the source tuple with the target's
3042 // last element is equal to the target.
3043 let new_tuple = tcx.mk_tup(a_mid.iter().chain(Some(b_last)), false);
3044 let InferOk { obligations, .. } =
3045 self.infcx.at(&obligation.cause, obligation.param_env)
3046 .eq(target, new_tuple)
3047 .map_err(|_| Unimplemented)?;
3048 self.inferred_obligations.extend(obligations);
3050 // Construct the nested T: Unsize<U> predicate.
3051 nested.push(tcx.predicate_for_trait_def(
3052 obligation.param_env,
3053 obligation.cause.clone(),
3054 obligation.predicate.def_id(),
3055 obligation.recursion_depth + 1,
3063 Ok(VtableBuiltinData { nested: nested })
3066 ///////////////////////////////////////////////////////////////////////////
3069 // Matching is a common path used for both evaluation and
3070 // confirmation. It basically unifies types that appear in impls
3071 // and traits. This does affect the surrounding environment;
3072 // therefore, when used during evaluation, match routines must be
3073 // run inside of a `probe()` so that their side-effects are
3076 fn rematch_impl(&mut self,
3078 obligation: &TraitObligation<'tcx>,
3079 snapshot: &infer::CombinedSnapshot)
3080 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
3081 infer::SkolemizationMap<'tcx>)
3083 match self.match_impl(impl_def_id, obligation, snapshot) {
3084 Ok((substs, skol_map)) => (substs, skol_map),
3086 bug!("Impl {:?} was matchable against {:?} but now is not",
3093 fn match_impl(&mut self,
3095 obligation: &TraitObligation<'tcx>,
3096 snapshot: &infer::CombinedSnapshot)
3097 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
3098 infer::SkolemizationMap<'tcx>), ()>
3100 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3102 // Before we create the substitutions and everything, first
3103 // consider a "quick reject". This avoids creating more types
3104 // and so forth that we need to.
3105 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3109 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
3110 &obligation.predicate,
3112 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3114 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
3117 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
3120 let impl_trait_ref =
3121 project::normalize_with_depth(self,
3122 obligation.param_env,
3123 obligation.cause.clone(),
3124 obligation.recursion_depth + 1,
3127 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
3128 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3132 skol_obligation_trait_ref);
3134 let InferOk { obligations, .. } =
3135 self.infcx.at(&obligation.cause, obligation.param_env)
3136 .eq(skol_obligation_trait_ref, impl_trait_ref.value)
3138 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
3141 self.inferred_obligations.extend(obligations);
3143 if let Err(e) = self.infcx.leak_check(false,
3144 obligation.cause.span,
3147 debug!("match_impl: failed leak check due to `{}`", e);
3151 debug!("match_impl: success impl_substs={:?}", impl_substs);
3154 obligations: impl_trait_ref.obligations
3158 fn fast_reject_trait_refs(&mut self,
3159 obligation: &TraitObligation,
3160 impl_trait_ref: &ty::TraitRef)
3163 // We can avoid creating type variables and doing the full
3164 // substitution if we find that any of the input types, when
3165 // simplified, do not match.
3167 obligation.predicate.skip_binder().input_types()
3168 .zip(impl_trait_ref.input_types())
3169 .any(|(obligation_ty, impl_ty)| {
3170 let simplified_obligation_ty =
3171 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3172 let simplified_impl_ty =
3173 fast_reject::simplify_type(self.tcx(), impl_ty, false);
3175 simplified_obligation_ty.is_some() &&
3176 simplified_impl_ty.is_some() &&
3177 simplified_obligation_ty != simplified_impl_ty
3181 /// Normalize `where_clause_trait_ref` and try to match it against
3182 /// `obligation`. If successful, return any predicates that
3183 /// result from the normalization. Normalization is necessary
3184 /// because where-clauses are stored in the parameter environment
3186 fn match_where_clause_trait_ref(&mut self,
3187 obligation: &TraitObligation<'tcx>,
3188 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
3189 -> Result<Vec<PredicateObligation<'tcx>>,()>
3191 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
3195 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3196 /// obligation is satisfied.
3197 fn match_poly_trait_ref(&mut self,
3198 obligation: &TraitObligation<'tcx>,
3199 poly_trait_ref: ty::PolyTraitRef<'tcx>)
3202 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3206 self.infcx.at(&obligation.cause, obligation.param_env)
3207 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3208 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
3212 ///////////////////////////////////////////////////////////////////////////
3215 fn match_fresh_trait_refs(&self,
3216 previous: &ty::PolyTraitRef<'tcx>,
3217 current: &ty::PolyTraitRef<'tcx>)
3220 let mut matcher = ty::_match::Match::new(self.tcx());
3221 matcher.relate(previous, current).is_ok()
3224 fn push_stack<'o,'s:'o>(&mut self,
3225 previous_stack: TraitObligationStackList<'s, 'tcx>,
3226 obligation: &'o TraitObligation<'tcx>)
3227 -> TraitObligationStack<'o, 'tcx>
3229 let fresh_trait_ref =
3230 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3232 TraitObligationStack {
3235 previous: previous_stack,
3239 fn closure_trait_ref_unnormalized(&mut self,
3240 obligation: &TraitObligation<'tcx>,
3241 closure_def_id: DefId,
3242 substs: ty::ClosureSubsts<'tcx>)
3243 -> ty::PolyTraitRef<'tcx>
3245 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3246 let ty::Binder((trait_ref, _)) =
3247 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
3248 obligation.predicate.0.self_ty(), // (1)
3250 util::TupleArgumentsFlag::No);
3251 // (1) Feels icky to skip the binder here, but OTOH we know
3252 // that the self-type is an unboxed closure type and hence is
3253 // in fact unparameterized (or at least does not reference any
3254 // regions bound in the obligation). Still probably some
3255 // refactoring could make this nicer.
3257 ty::Binder(trait_ref)
3260 fn generator_trait_ref_unnormalized(&mut self,
3261 obligation: &TraitObligation<'tcx>,
3262 closure_def_id: DefId,
3263 substs: ty::ClosureSubsts<'tcx>)
3264 -> ty::PolyTraitRef<'tcx>
3266 let gen_sig = substs.generator_poly_sig(closure_def_id, self.tcx());
3267 let ty::Binder((trait_ref, ..)) =
3268 self.tcx().generator_trait_ref_and_outputs(obligation.predicate.def_id(),
3269 obligation.predicate.0.self_ty(), // (1)
3271 // (1) Feels icky to skip the binder here, but OTOH we know
3272 // that the self-type is an generator type and hence is
3273 // in fact unparameterized (or at least does not reference any
3274 // regions bound in the obligation). Still probably some
3275 // refactoring could make this nicer.
3277 ty::Binder(trait_ref)
3280 /// Returns the obligations that are implied by instantiating an
3281 /// impl or trait. The obligations are substituted and fully
3282 /// normalized. This is used when confirming an impl or default
3284 fn impl_or_trait_obligations(&mut self,
3285 cause: ObligationCause<'tcx>,
3286 recursion_depth: usize,
3287 param_env: ty::ParamEnv<'tcx>,
3288 def_id: DefId, // of impl or trait
3289 substs: &Substs<'tcx>, // for impl or trait
3290 skol_map: infer::SkolemizationMap<'tcx>,
3291 snapshot: &infer::CombinedSnapshot)
3292 -> Vec<PredicateObligation<'tcx>>
3294 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3295 let tcx = self.tcx();
3297 // To allow for one-pass evaluation of the nested obligation,
3298 // each predicate must be preceded by the obligations required
3300 // for example, if we have:
3301 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3302 // the impl will have the following predicates:
3303 // <V as Iterator>::Item = U,
3304 // U: Iterator, U: Sized,
3305 // V: Iterator, V: Sized,
3306 // <U as Iterator>::Item: Copy
3307 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3308 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3309 // `$1: Copy`, so we must ensure the obligations are emitted in
3311 let predicates = tcx.predicates_of(def_id);
3312 assert_eq!(predicates.parent, None);
3313 let mut predicates: Vec<_> = predicates.predicates.iter().flat_map(|predicate| {
3314 let predicate = normalize_with_depth(self, param_env, cause.clone(), recursion_depth,
3315 &predicate.subst(tcx, substs));
3316 predicate.obligations.into_iter().chain(
3318 cause: cause.clone(),
3321 predicate: predicate.value
3324 // We are performing deduplication here to avoid exponential blowups
3325 // (#38528) from happening, but the real cause of the duplication is
3326 // unknown. What we know is that the deduplication avoids exponential
3327 // amount of predicates being propogated when processing deeply nested
3329 let mut seen = FxHashSet();
3330 predicates.retain(|i| seen.insert(i.clone()));
3331 self.infcx().plug_leaks(skol_map, snapshot, predicates)
3335 impl<'tcx> TraitObligation<'tcx> {
3336 #[allow(unused_comparisons)]
3337 pub fn derived_cause(&self,
3338 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
3339 -> ObligationCause<'tcx>
3342 * Creates a cause for obligations that are derived from
3343 * `obligation` by a recursive search (e.g., for a builtin
3344 * bound, or eventually a `auto trait Foo`). If `obligation`
3345 * is itself a derived obligation, this is just a clone, but
3346 * otherwise we create a "derived obligation" cause so as to
3347 * keep track of the original root obligation for error
3351 let obligation = self;
3353 // NOTE(flaper87): As of now, it keeps track of the whole error
3354 // chain. Ideally, we should have a way to configure this either
3355 // by using -Z verbose or just a CLI argument.
3356 if obligation.recursion_depth >= 0 {
3357 let derived_cause = DerivedObligationCause {
3358 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3359 parent_code: Rc::new(obligation.cause.code.clone())
3361 let derived_code = variant(derived_cause);
3362 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3364 obligation.cause.clone()
3369 impl<'tcx> SelectionCache<'tcx> {
3370 pub fn new() -> SelectionCache<'tcx> {
3372 hashmap: RefCell::new(FxHashMap())
3376 pub fn clear(&self) {
3377 *self.hashmap.borrow_mut() = FxHashMap()
3381 impl<'tcx> EvaluationCache<'tcx> {
3382 pub fn new() -> EvaluationCache<'tcx> {
3384 hashmap: RefCell::new(FxHashMap())
3388 pub fn clear(&self) {
3389 *self.hashmap.borrow_mut() = FxHashMap()
3393 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
3394 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
3395 TraitObligationStackList::with(self)
3398 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
3403 #[derive(Copy, Clone)]
3404 struct TraitObligationStackList<'o,'tcx:'o> {
3405 head: Option<&'o TraitObligationStack<'o,'tcx>>
3408 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
3409 fn empty() -> TraitObligationStackList<'o,'tcx> {
3410 TraitObligationStackList { head: None }
3413 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
3414 TraitObligationStackList { head: Some(r) }
3418 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
3419 type Item = &'o TraitObligationStack<'o,'tcx>;
3421 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3432 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3434 write!(f, "TraitObligationStack({:?})", self.obligation)
3439 pub struct WithDepNode<T> {
3440 dep_node: DepNodeIndex,
3444 impl<T: Clone> WithDepNode<T> {
3445 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3446 WithDepNode { dep_node, cached_value }
3449 pub fn get(&self, tcx: TyCtxt) -> T {
3450 tcx.dep_graph.read_index(self.dep_node);
3451 self.cached_value.clone()