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;
45 use mir::interpret::{GlobalId};
47 use rustc_data_structures::bitvec::BitVector;
49 use std::cell::RefCell;
57 use util::nodemap::{FxHashMap, FxHashSet};
60 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
61 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
63 /// Freshener used specifically for skolemizing entries on the
64 /// obligation stack. This ensures that all entries on the stack
65 /// at one time will have the same set of skolemized entries,
66 /// which is important for checking for trait bounds that
67 /// recursively require themselves.
68 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
70 /// If true, indicates that the evaluation should be conservative
71 /// and consider the possibility of types outside this crate.
72 /// This comes up primarily when resolving ambiguity. Imagine
73 /// there is some trait reference `$0 : Bar` where `$0` is an
74 /// inference variable. If `intercrate` is true, then we can never
75 /// say for sure that this reference is not implemented, even if
76 /// there are *no impls at all for `Bar`*, because `$0` could be
77 /// bound to some type that in a downstream crate that implements
78 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
79 /// though, we set this to false, because we are only interested
80 /// in types that the user could actually have written --- in
81 /// other words, we consider `$0 : Bar` to be unimplemented if
82 /// there is no type that the user could *actually name* that
83 /// would satisfy it. This avoids crippling inference, basically.
84 intercrate: Option<IntercrateMode>,
86 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
88 /// Controls whether or not to filter out negative impls when selecting.
89 /// This is used in librustdoc to distinguish between the lack of an impl
90 /// and a negative impl
91 allow_negative_impls: bool
94 #[derive(Clone, Debug)]
95 pub enum IntercrateAmbiguityCause {
98 self_desc: Option<String>,
100 UpstreamCrateUpdate {
102 self_desc: Option<String>,
106 impl IntercrateAmbiguityCause {
107 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
108 /// See #23980 for details.
109 pub fn add_intercrate_ambiguity_hint<'a, 'tcx>(&self,
110 err: &mut ::errors::DiagnosticBuilder) {
111 err.note(&self.intercrate_ambiguity_hint());
114 pub fn intercrate_ambiguity_hint(&self) -> String {
116 &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
117 let self_desc = if let &Some(ref ty) = self_desc {
118 format!(" for type `{}`", ty)
119 } else { "".to_string() };
120 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
122 &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
123 let self_desc = if let &Some(ref ty) = self_desc {
124 format!(" for type `{}`", ty)
125 } else { "".to_string() };
126 format!("upstream crates may add new impl of trait `{}`{} \
128 trait_desc, self_desc)
134 // A stack that walks back up the stack frame.
135 struct TraitObligationStack<'prev, 'tcx: 'prev> {
136 obligation: &'prev TraitObligation<'tcx>,
138 /// Trait ref from `obligation` but skolemized with the
139 /// selection-context's freshener. Used to check for recursion.
140 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
142 previous: TraitObligationStackList<'prev, 'tcx>,
146 pub struct SelectionCache<'tcx> {
147 hashmap: RefCell<FxHashMap<ty::TraitRef<'tcx>,
148 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>>,
151 /// The selection process begins by considering all impls, where
152 /// clauses, and so forth that might resolve an obligation. Sometimes
153 /// we'll be able to say definitively that (e.g.) an impl does not
154 /// apply to the obligation: perhaps it is defined for `usize` but the
155 /// obligation is for `int`. In that case, we drop the impl out of the
156 /// list. But the other cases are considered *candidates*.
158 /// For selection to succeed, there must be exactly one matching
159 /// candidate. If the obligation is fully known, this is guaranteed
160 /// by coherence. However, if the obligation contains type parameters
161 /// or variables, there may be multiple such impls.
163 /// It is not a real problem if multiple matching impls exist because
164 /// of type variables - it just means the obligation isn't sufficiently
165 /// elaborated. In that case we report an ambiguity, and the caller can
166 /// try again after more type information has been gathered or report a
167 /// "type annotations required" error.
169 /// However, with type parameters, this can be a real problem - type
170 /// parameters don't unify with regular types, but they *can* unify
171 /// with variables from blanket impls, and (unless we know its bounds
172 /// will always be satisfied) picking the blanket impl will be wrong
173 /// for at least *some* substitutions. To make this concrete, if we have
175 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
176 /// impl<T: fmt::Debug> AsDebug for T {
178 /// fn debug(self) -> fmt::Debug { self }
180 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
182 /// we can't just use the impl to resolve the <T as AsDebug> obligation
183 /// - a type from another crate (that doesn't implement fmt::Debug) could
184 /// implement AsDebug.
186 /// Because where-clauses match the type exactly, multiple clauses can
187 /// only match if there are unresolved variables, and we can mostly just
188 /// report this ambiguity in that case. This is still a problem - we can't
189 /// *do anything* with ambiguities that involve only regions. This is issue
192 /// If a single where-clause matches and there are no inference
193 /// variables left, then it definitely matches and we can just select
196 /// In fact, we even select the where-clause when the obligation contains
197 /// inference variables. The can lead to inference making "leaps of logic",
198 /// for example in this situation:
200 /// pub trait Foo<T> { fn foo(&self) -> T; }
201 /// impl<T> Foo<()> for T { fn foo(&self) { } }
202 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
204 /// pub fn foo<T>(t: T) where T: Foo<bool> {
205 /// println!("{:?}", <T as Foo<_>>::foo(&t));
207 /// fn main() { foo(false); }
209 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
210 /// impl and the where-clause. We select the where-clause and unify $0=bool,
211 /// so the program prints "false". However, if the where-clause is omitted,
212 /// the blanket impl is selected, we unify $0=(), and the program prints
215 /// Exactly the same issues apply to projection and object candidates, except
216 /// that we can have both a projection candidate and a where-clause candidate
217 /// for the same obligation. In that case either would do (except that
218 /// different "leaps of logic" would occur if inference variables are
219 /// present), and we just pick the where-clause. This is, for example,
220 /// required for associated types to work in default impls, as the bounds
221 /// are visible both as projection bounds and as where-clauses from the
222 /// parameter environment.
223 #[derive(PartialEq,Eq,Debug,Clone)]
224 enum SelectionCandidate<'tcx> {
225 BuiltinCandidate { has_nested: bool },
226 ParamCandidate(ty::PolyTraitRef<'tcx>),
227 ImplCandidate(DefId),
228 AutoImplCandidate(DefId),
230 /// This is a trait matching with a projected type as `Self`, and
231 /// we found an applicable bound in the trait definition.
234 /// Implementation of a `Fn`-family trait by one of the anonymous types
235 /// generated for a `||` expression.
238 /// Implementation of a `Generator` trait by one of the anonymous types
239 /// generated for a generator.
242 /// Implementation of a `Fn`-family trait by one of the anonymous
243 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
248 BuiltinObjectCandidate,
250 BuiltinUnsizeCandidate,
253 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
254 type Lifted = SelectionCandidate<'tcx>;
255 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
257 BuiltinCandidate { has_nested } => {
262 ImplCandidate(def_id) => ImplCandidate(def_id),
263 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
264 ProjectionCandidate => ProjectionCandidate,
265 FnPointerCandidate => FnPointerCandidate,
266 ObjectCandidate => ObjectCandidate,
267 BuiltinObjectCandidate => BuiltinObjectCandidate,
268 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
269 ClosureCandidate => ClosureCandidate,
270 GeneratorCandidate => GeneratorCandidate,
272 ParamCandidate(ref trait_ref) => {
273 return tcx.lift(trait_ref).map(ParamCandidate);
279 struct SelectionCandidateSet<'tcx> {
280 // a list of candidates that definitely apply to the current
281 // obligation (meaning: types unify).
282 vec: Vec<SelectionCandidate<'tcx>>,
284 // if this is true, then there were candidates that might or might
285 // not have applied, but we couldn't tell. This occurs when some
286 // of the input types are type variables, in which case there are
287 // various "builtin" rules that might or might not trigger.
291 #[derive(PartialEq,Eq,Debug,Clone)]
292 struct EvaluatedCandidate<'tcx> {
293 candidate: SelectionCandidate<'tcx>,
294 evaluation: EvaluationResult,
297 /// When does the builtin impl for `T: Trait` apply?
298 enum BuiltinImplConditions<'tcx> {
299 /// The impl is conditional on T1,T2,.. : Trait
300 Where(ty::Binder<Vec<Ty<'tcx>>>),
301 /// There is no built-in impl. There may be some other
302 /// candidate (a where-clause or user-defined impl).
304 /// There is *no* impl for this, builtin or not. Ignore
305 /// all where-clauses.
307 /// It is unknown whether there is an impl.
311 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
312 /// The result of trait evaluation. The order is important
313 /// here as the evaluation of a list is the maximum of the
316 /// The evaluation results are ordered:
317 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
318 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
319 /// - the "union" of evaluation results is equal to their maximum -
320 /// all the "potential success" candidates can potentially succeed,
321 /// so they are no-ops when unioned with a definite error, and within
322 /// the categories it's easy to see that the unions are correct.
323 enum EvaluationResult {
324 /// Evaluation successful
326 /// Evaluation is known to be ambiguous - it *might* hold for some
327 /// assignment of inference variables, but it might not.
329 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
330 /// know whether this obligation holds or not - it is the result we
331 /// would get with an empty stack, and therefore is cacheable.
333 /// Evaluation failed because of recursion involving inference
334 /// variables. We are somewhat imprecise there, so we don't actually
335 /// know the real result.
337 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
339 /// Evaluation failed because we encountered an obligation we are already
340 /// trying to prove on this branch.
342 /// We know this branch can't be a part of a minimal proof-tree for
343 /// the "root" of our cycle, because then we could cut out the recursion
344 /// and maintain a valid proof tree. However, this does not mean
345 /// that all the obligations on this branch do not hold - it's possible
346 /// that we entered this branch "speculatively", and that there
347 /// might be some other way to prove this obligation that does not
348 /// go through this cycle - so we can't cache this as a failure.
350 /// For example, suppose we have this:
352 /// ```rust,ignore (pseudo-Rust)
353 /// pub trait Trait { fn xyz(); }
354 /// // This impl is "useless", but we can still have
355 /// // an `impl Trait for SomeUnsizedType` somewhere.
356 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
358 /// pub fn foo<T: Trait + ?Sized>() {
359 /// <T as Trait>::xyz();
363 /// When checking `foo`, we have to prove `T: Trait`. This basically
364 /// translates into this:
366 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
368 /// When we try to prove it, we first go the first option, which
369 /// recurses. This shows us that the impl is "useless" - it won't
370 /// tell us that `T: Trait` unless it already implemented `Trait`
371 /// by some other means. However, that does not prevent `T: Trait`
372 /// does not hold, because of the bound (which can indeed be satisfied
373 /// by `SomeUnsizedType` from another crate).
375 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
376 /// ought to convert it to an `EvaluatedToErr`, because we know
377 /// there definitely isn't a proof tree for that obligation. Not
378 /// doing so is still sound - there isn't any proof tree, so the
379 /// branch still can't be a part of a minimal one - but does not
380 /// re-enable caching.
382 /// Evaluation failed
386 impl EvaluationResult {
387 fn may_apply(self) -> bool {
391 EvaluatedToUnknown => true,
394 EvaluatedToRecur => false
398 fn is_stack_dependent(self) -> bool {
401 EvaluatedToRecur => true,
405 EvaluatedToErr => false,
411 pub struct EvaluationCache<'tcx> {
412 hashmap: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>
415 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
416 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
419 freshener: infcx.freshener(),
421 intercrate_ambiguity_causes: None,
422 allow_negative_impls: false,
426 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
427 mode: IntercrateMode) -> SelectionContext<'cx, 'gcx, 'tcx> {
428 debug!("intercrate({:?})", mode);
431 freshener: infcx.freshener(),
432 intercrate: Some(mode),
433 intercrate_ambiguity_causes: None,
434 allow_negative_impls: false,
438 pub fn with_negative(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
439 allow_negative_impls: bool) -> SelectionContext<'cx, 'gcx, 'tcx> {
440 debug!("with_negative({:?})", allow_negative_impls);
443 freshener: infcx.freshener(),
445 intercrate_ambiguity_causes: None,
446 allow_negative_impls,
450 /// Enables tracking of intercrate ambiguity causes. These are
451 /// used in coherence to give improved diagnostics. We don't do
452 /// this until we detect a coherence error because it can lead to
453 /// false overflow results (#47139) and because it costs
454 /// computation time.
455 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
456 assert!(self.intercrate.is_some());
457 assert!(self.intercrate_ambiguity_causes.is_none());
458 self.intercrate_ambiguity_causes = Some(vec![]);
459 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
462 /// Gets the intercrate ambiguity causes collected since tracking
463 /// was enabled and disables tracking at the same time. If
464 /// tracking is not enabled, just returns an empty vector.
465 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
466 assert!(self.intercrate.is_some());
467 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
470 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
474 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
478 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
482 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
484 fn in_snapshot<R, F>(&mut self, f: F) -> R
485 where F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R
487 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
490 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
492 fn probe<R, F>(&mut self, f: F) -> R
493 where F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R
495 self.infcx.probe(|snapshot| f(self, snapshot))
498 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
499 /// the transaction fails and s.t. old obligations are retained.
500 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
501 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
503 self.infcx.commit_if_ok(|snapshot| f(self, snapshot))
507 ///////////////////////////////////////////////////////////////////////////
510 // The selection phase tries to identify *how* an obligation will
511 // be resolved. For example, it will identify which impl or
512 // parameter bound is to be used. The process can be inconclusive
513 // if the self type in the obligation is not fully inferred. Selection
514 // can result in an error in one of two ways:
516 // 1. If no applicable impl or parameter bound can be found.
517 // 2. If the output type parameters in the obligation do not match
518 // those specified by the impl/bound. For example, if the obligation
519 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
520 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
522 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
523 /// type environment by performing unification.
524 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
525 -> SelectionResult<'tcx, Selection<'tcx>> {
526 debug!("select({:?})", obligation);
527 assert!(!obligation.predicate.has_escaping_regions());
529 let tcx = self.tcx();
531 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
532 let ret = match self.candidate_from_obligation(&stack)? {
534 Some(candidate) => Some(self.confirm_candidate(obligation, candidate)?)
537 // Test whether this is a `()` which was produced by defaulting a
538 // diverging type variable with `!` disabled. If so, we may need
539 // to raise a warning.
540 if obligation.predicate.skip_binder().self_ty().is_defaulted_unit() {
541 let mut raise_warning = true;
542 // Don't raise a warning if the trait is implemented for ! and only
543 // permits a trivial implementation for !. This stops us warning
544 // about (for example) `(): Clone` becoming `!: Clone` because such
545 // a switch can't cause code to stop compiling or execute
547 let mut never_obligation = obligation.clone();
548 let def_id = never_obligation.predicate.skip_binder().trait_ref.def_id;
549 never_obligation.predicate = never_obligation.predicate.map_bound(|mut trait_pred| {
550 // Swap out () with ! so we can check if the trait is impld for !
552 let trait_ref = &mut trait_pred.trait_ref;
553 let unit_substs = trait_ref.substs;
554 let mut never_substs = Vec::with_capacity(unit_substs.len());
555 never_substs.push(tcx.types.never.into());
556 never_substs.extend(&unit_substs[1..]);
557 trait_ref.substs = tcx.intern_substs(&never_substs);
561 if let Ok(Some(..)) = self.select(&never_obligation) {
562 if !tcx.trait_relevant_for_never(def_id) {
563 // The trait is also implemented for ! and the resulting
564 // implementation cannot actually be invoked in any way.
565 raise_warning = false;
570 tcx.lint_node(lint::builtin::RESOLVE_TRAIT_ON_DEFAULTED_UNIT,
571 obligation.cause.body_id,
572 obligation.cause.span,
573 &format!("code relies on type inference rules which are likely \
580 ///////////////////////////////////////////////////////////////////////////
583 // Tests whether an obligation can be selected or whether an impl
584 // can be applied to particular types. It skips the "confirmation"
585 // step and hence completely ignores output type parameters.
587 // The result is "true" if the obligation *may* hold and "false" if
588 // we can be sure it does not.
590 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
591 pub fn evaluate_obligation(&mut self,
592 obligation: &PredicateObligation<'tcx>)
595 debug!("evaluate_obligation({:?})",
598 self.probe(|this, _| {
599 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
604 /// Evaluates whether the obligation `obligation` can be satisfied,
605 /// and returns `false` if not certain. However, this is not entirely
606 /// accurate if inference variables are involved.
607 pub fn evaluate_obligation_conservatively(&mut self,
608 obligation: &PredicateObligation<'tcx>)
611 debug!("evaluate_obligation_conservatively({:?})",
614 self.probe(|this, _| {
615 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
620 /// Evaluates the predicates in `predicates` recursively. Note that
621 /// this applies projections in the predicates, and therefore
622 /// is run within an inference probe.
623 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
624 stack: TraitObligationStackList<'o, 'tcx>,
627 where I : IntoIterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
629 let mut result = EvaluatedToOk;
630 for obligation in predicates {
631 let eval = self.evaluate_predicate_recursively(stack, obligation);
632 debug!("evaluate_predicate_recursively({:?}) = {:?}",
634 if let EvaluatedToErr = eval {
635 // fast-path - EvaluatedToErr is the top of the lattice,
636 // so we don't need to look on the other predicates.
637 return EvaluatedToErr;
639 result = cmp::max(result, eval);
645 fn evaluate_predicate_recursively<'o>(&mut self,
646 previous_stack: TraitObligationStackList<'o, 'tcx>,
647 obligation: &PredicateObligation<'tcx>)
650 debug!("evaluate_predicate_recursively({:?})",
653 match obligation.predicate {
654 ty::Predicate::Trait(ref t) => {
655 assert!(!t.has_escaping_regions());
656 let obligation = obligation.with(t.clone());
657 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
660 ty::Predicate::Subtype(ref p) => {
661 // does this code ever run?
662 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
663 Some(Ok(InferOk { obligations, .. })) => {
664 self.evaluate_predicates_recursively(previous_stack, &obligations);
667 Some(Err(_)) => EvaluatedToErr,
668 None => EvaluatedToAmbig,
672 ty::Predicate::WellFormed(ty) => {
673 match ty::wf::obligations(self.infcx,
674 obligation.param_env,
675 obligation.cause.body_id,
676 ty, obligation.cause.span) {
678 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
684 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
685 // we do not consider region relationships when
686 // evaluating trait matches
690 ty::Predicate::ObjectSafe(trait_def_id) => {
691 if self.tcx().is_object_safe(trait_def_id) {
698 ty::Predicate::Projection(ref data) => {
699 let project_obligation = obligation.with(data.clone());
700 match project::poly_project_and_unify_type(self, &project_obligation) {
701 Ok(Some(subobligations)) => {
702 let result = self.evaluate_predicates_recursively(previous_stack,
703 subobligations.iter());
705 ProjectionCacheKey::from_poly_projection_predicate(self, data)
707 self.infcx.projection_cache.borrow_mut().complete(key);
720 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
721 match self.infcx.closure_kind(closure_def_id, closure_substs) {
722 Some(closure_kind) => {
723 if closure_kind.extends(kind) {
735 ty::Predicate::ConstEvaluatable(def_id, substs) => {
736 let tcx = self.tcx();
737 match tcx.lift_to_global(&(obligation.param_env, substs)) {
738 Some((param_env, substs)) => {
739 let instance = ty::Instance::resolve(
745 if let Some(instance) = instance {
750 match self.tcx().const_eval(param_env.and(cid)) {
751 Ok(_) => EvaluatedToOk,
752 Err(_) => EvaluatedToErr
759 // Inference variables still left in param_env or substs.
767 fn evaluate_trait_predicate_recursively<'o>(&mut self,
768 previous_stack: TraitObligationStackList<'o, 'tcx>,
769 mut obligation: TraitObligation<'tcx>)
772 debug!("evaluate_trait_predicate_recursively({:?})",
775 if !self.intercrate.is_some() && obligation.is_global() {
776 // If a param env is consistent, global obligations do not depend on its particular
777 // value in order to work, so we can clear out the param env and get better
778 // caching. (If the current param env is inconsistent, we don't care what happens).
779 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
780 obligation.param_env = obligation.param_env.without_caller_bounds();
783 let stack = self.push_stack(previous_stack, &obligation);
784 let fresh_trait_ref = stack.fresh_trait_ref;
785 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
786 debug!("CACHE HIT: EVAL({:?})={:?}",
792 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
794 debug!("CACHE MISS: EVAL({:?})={:?}",
797 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
802 fn evaluate_stack<'o>(&mut self,
803 stack: &TraitObligationStack<'o, 'tcx>)
806 // In intercrate mode, whenever any of the types are unbound,
807 // there can always be an impl. Even if there are no impls in
808 // this crate, perhaps the type would be unified with
809 // something from another crate that does provide an impl.
811 // In intra mode, we must still be conservative. The reason is
812 // that we want to avoid cycles. Imagine an impl like:
814 // impl<T:Eq> Eq for Vec<T>
816 // and a trait reference like `$0 : Eq` where `$0` is an
817 // unbound variable. When we evaluate this trait-reference, we
818 // will unify `$0` with `Vec<$1>` (for some fresh variable
819 // `$1`), on the condition that `$1 : Eq`. We will then wind
820 // up with many candidates (since that are other `Eq` impls
821 // that apply) and try to winnow things down. This results in
822 // a recursive evaluation that `$1 : Eq` -- as you can
823 // imagine, this is just where we started. To avoid that, we
824 // check for unbound variables and return an ambiguous (hence possible)
825 // match if we've seen this trait before.
827 // This suffices to allow chains like `FnMut` implemented in
828 // terms of `Fn` etc, but we could probably make this more
830 let unbound_input_types = stack.fresh_trait_ref.input_types().any(|ty| ty.is_fresh());
831 // this check was an imperfect workaround for a bug n the old
832 // intercrate mode, it should be removed when that goes away.
833 if unbound_input_types &&
834 self.intercrate == Some(IntercrateMode::Issue43355)
836 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
837 stack.fresh_trait_ref);
838 // Heuristics: show the diagnostics when there are no candidates in crate.
839 if self.intercrate_ambiguity_causes.is_some() {
840 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
841 if let Ok(candidate_set) = self.assemble_candidates(stack) {
842 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
843 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
844 let self_ty = trait_ref.self_ty();
845 let cause = IntercrateAmbiguityCause::DownstreamCrate {
846 trait_desc: trait_ref.to_string(),
847 self_desc: if self_ty.has_concrete_skeleton() {
848 Some(self_ty.to_string())
853 debug!("evaluate_stack: pushing cause = {:?}", cause);
854 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
858 return EvaluatedToAmbig;
860 if unbound_input_types &&
861 stack.iter().skip(1).any(
862 |prev| stack.obligation.param_env == prev.obligation.param_env &&
863 self.match_fresh_trait_refs(&stack.fresh_trait_ref,
864 &prev.fresh_trait_ref))
866 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
867 stack.fresh_trait_ref);
868 return EvaluatedToUnknown;
871 // If there is any previous entry on the stack that precisely
872 // matches this obligation, then we can assume that the
873 // obligation is satisfied for now (still all other conditions
874 // must be met of course). One obvious case this comes up is
875 // marker traits like `Send`. Think of a linked list:
877 // struct List<T> { data: T, next: Option<Box<List<T>>> {
879 // `Box<List<T>>` will be `Send` if `T` is `Send` and
880 // `Option<Box<List<T>>>` is `Send`, and in turn
881 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
884 // Note that we do this comparison using the `fresh_trait_ref`
885 // fields. Because these have all been skolemized using
886 // `self.freshener`, we can be sure that (a) this will not
887 // affect the inferencer state and (b) that if we see two
888 // skolemized types with the same index, they refer to the
889 // same unbound type variable.
890 if let Some(rec_index) =
892 .skip(1) // skip top-most frame
893 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
894 stack.fresh_trait_ref == prev.fresh_trait_ref)
896 debug!("evaluate_stack({:?}) --> recursive",
897 stack.fresh_trait_ref);
898 let cycle = stack.iter().skip(1).take(rec_index+1);
899 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
900 if self.coinductive_match(cycle) {
901 debug!("evaluate_stack({:?}) --> recursive, coinductive",
902 stack.fresh_trait_ref);
903 return EvaluatedToOk;
905 debug!("evaluate_stack({:?}) --> recursive, inductive",
906 stack.fresh_trait_ref);
907 return EvaluatedToRecur;
911 match self.candidate_from_obligation(stack) {
912 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
913 Ok(None) => EvaluatedToAmbig,
914 Err(..) => EvaluatedToErr
918 /// For defaulted traits, we use a co-inductive strategy to solve, so
919 /// that recursion is ok. This routine returns true if the top of the
920 /// stack (`cycle[0]`):
922 /// - is a defaulted trait, and
923 /// - it also appears in the backtrace at some position `X`; and,
924 /// - all the predicates at positions `X..` between `X` an the top are
925 /// also defaulted traits.
926 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
927 where I: Iterator<Item=ty::Predicate<'tcx>>
929 let mut cycle = cycle;
930 cycle.all(|predicate| self.coinductive_predicate(predicate))
933 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
934 let result = match predicate {
935 ty::Predicate::Trait(ref data) => {
936 self.tcx().trait_is_auto(data.def_id())
942 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
946 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
947 /// obligations are met. Returns true if `candidate` remains viable after this further
949 fn evaluate_candidate<'o>(&mut self,
950 stack: &TraitObligationStack<'o, 'tcx>,
951 candidate: &SelectionCandidate<'tcx>)
954 debug!("evaluate_candidate: depth={} candidate={:?}",
955 stack.obligation.recursion_depth, candidate);
956 let result = self.probe(|this, _| {
957 let candidate = (*candidate).clone();
958 match this.confirm_candidate(stack.obligation, candidate) {
960 this.evaluate_predicates_recursively(
962 selection.nested_obligations().iter())
964 Err(..) => EvaluatedToErr
967 debug!("evaluate_candidate: depth={} result={:?}",
968 stack.obligation.recursion_depth, result);
972 fn check_evaluation_cache(&self,
973 param_env: ty::ParamEnv<'tcx>,
974 trait_ref: ty::PolyTraitRef<'tcx>)
975 -> Option<EvaluationResult>
977 let tcx = self.tcx();
978 if self.can_use_global_caches(param_env) {
979 let cache = tcx.evaluation_cache.hashmap.borrow();
980 if let Some(cached) = cache.get(&trait_ref) {
981 return Some(cached.get(tcx));
984 self.infcx.evaluation_cache.hashmap
990 fn insert_evaluation_cache(&mut self,
991 param_env: ty::ParamEnv<'tcx>,
992 trait_ref: ty::PolyTraitRef<'tcx>,
993 dep_node: DepNodeIndex,
994 result: EvaluationResult)
996 // Avoid caching results that depend on more than just the trait-ref
997 // - the stack can create recursion.
998 if result.is_stack_dependent() {
1002 if self.can_use_global_caches(param_env) {
1003 let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
1004 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1005 cache.insert(trait_ref, WithDepNode::new(dep_node, result));
1010 self.infcx.evaluation_cache.hashmap
1012 .insert(trait_ref, WithDepNode::new(dep_node, result));
1015 ///////////////////////////////////////////////////////////////////////////
1016 // CANDIDATE ASSEMBLY
1018 // The selection process begins by examining all in-scope impls,
1019 // caller obligations, and so forth and assembling a list of
1020 // candidates. See [rustc guide] for more details.
1023 // https://rust-lang-nursery.github.io/rustc-guide/trait-resolution.html#candidate-assembly
1025 fn candidate_from_obligation<'o>(&mut self,
1026 stack: &TraitObligationStack<'o, 'tcx>)
1027 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1029 // Watch out for overflow. This intentionally bypasses (and does
1030 // not update) the cache.
1031 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
1032 if stack.obligation.recursion_depth >= recursion_limit {
1033 self.infcx().report_overflow_error(&stack.obligation, true);
1036 // Check the cache. Note that we skolemize the trait-ref
1037 // separately rather than using `stack.fresh_trait_ref` -- this
1038 // is because we want the unbound variables to be replaced
1039 // with fresh skolemized types starting from index 0.
1040 let cache_fresh_trait_pred =
1041 self.infcx.freshen(stack.obligation.predicate.clone());
1042 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1043 cache_fresh_trait_pred,
1045 assert!(!stack.obligation.predicate.has_escaping_regions());
1047 if let Some(c) = self.check_candidate_cache(stack.obligation.param_env,
1048 &cache_fresh_trait_pred) {
1049 debug!("CACHE HIT: SELECT({:?})={:?}",
1050 cache_fresh_trait_pred,
1055 // If no match, compute result and insert into cache.
1056 let (candidate, dep_node) = self.in_task(|this| {
1057 this.candidate_from_obligation_no_cache(stack)
1060 debug!("CACHE MISS: SELECT({:?})={:?}",
1061 cache_fresh_trait_pred, candidate);
1062 self.insert_candidate_cache(stack.obligation.param_env,
1063 cache_fresh_trait_pred,
1069 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1070 where OP: FnOnce(&mut Self) -> R
1072 let (result, dep_node) = self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || {
1075 self.tcx().dep_graph.read_index(dep_node);
1079 // Treat negative impls as unimplemented
1080 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
1081 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1082 if let ImplCandidate(def_id) = candidate {
1083 if !self.allow_negative_impls &&
1084 self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative {
1085 return Err(Unimplemented)
1091 fn candidate_from_obligation_no_cache<'o>(&mut self,
1092 stack: &TraitObligationStack<'o, 'tcx>)
1093 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1095 if stack.obligation.predicate.references_error() {
1096 // If we encounter a `TyError`, we generally prefer the
1097 // most "optimistic" result in response -- that is, the
1098 // one least likely to report downstream errors. But
1099 // because this routine is shared by coherence and by
1100 // trait selection, there isn't an obvious "right" choice
1101 // here in that respect, so we opt to just return
1102 // ambiguity and let the upstream clients sort it out.
1106 match self.is_knowable(stack) {
1109 debug!("coherence stage: not knowable");
1110 if self.intercrate_ambiguity_causes.is_some() {
1111 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1112 // Heuristics: show the diagnostics when there are no candidates in crate.
1113 let candidate_set = self.assemble_candidates(stack)?;
1114 if !candidate_set.ambiguous && candidate_set.vec.iter().all(|c| {
1115 !self.evaluate_candidate(stack, &c).may_apply()
1117 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1118 let self_ty = trait_ref.self_ty();
1119 let trait_desc = trait_ref.to_string();
1120 let self_desc = if self_ty.has_concrete_skeleton() {
1121 Some(self_ty.to_string())
1125 let cause = if let Conflict::Upstream = conflict {
1126 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1128 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1130 debug!("evaluate_stack: pushing cause = {:?}", cause);
1131 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1138 let candidate_set = self.assemble_candidates(stack)?;
1140 if candidate_set.ambiguous {
1141 debug!("candidate set contains ambig");
1145 let mut candidates = candidate_set.vec;
1147 debug!("assembled {} candidates for {:?}: {:?}",
1152 // At this point, we know that each of the entries in the
1153 // candidate set is *individually* applicable. Now we have to
1154 // figure out if they contain mutual incompatibilities. This
1155 // frequently arises if we have an unconstrained input type --
1156 // for example, we are looking for $0:Eq where $0 is some
1157 // unconstrained type variable. In that case, we'll get a
1158 // candidate which assumes $0 == int, one that assumes $0 ==
1159 // usize, etc. This spells an ambiguity.
1161 // If there is more than one candidate, first winnow them down
1162 // by considering extra conditions (nested obligations and so
1163 // forth). We don't winnow if there is exactly one
1164 // candidate. This is a relatively minor distinction but it
1165 // can lead to better inference and error-reporting. An
1166 // example would be if there was an impl:
1168 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1170 // and we were to see some code `foo.push_clone()` where `boo`
1171 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1172 // we were to winnow, we'd wind up with zero candidates.
1173 // Instead, we select the right impl now but report `Bar does
1174 // not implement Clone`.
1175 if candidates.len() == 1 {
1176 return self.filter_negative_impls(candidates.pop().unwrap());
1179 // Winnow, but record the exact outcome of evaluation, which
1180 // is needed for specialization.
1181 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
1182 let eval = self.evaluate_candidate(stack, &c);
1183 if eval.may_apply() {
1184 Some(EvaluatedCandidate {
1193 // If there are STILL multiple candidate, we can further
1194 // reduce the list by dropping duplicates -- including
1195 // resolving specializations.
1196 if candidates.len() > 1 {
1198 while i < candidates.len() {
1200 (0..candidates.len())
1201 .filter(|&j| i != j)
1202 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
1205 debug!("Dropping candidate #{}/{}: {:?}",
1206 i, candidates.len(), candidates[i]);
1207 candidates.swap_remove(i);
1209 debug!("Retaining candidate #{}/{}: {:?}",
1210 i, candidates.len(), candidates[i]);
1213 // If there are *STILL* multiple candidates, give up
1214 // and report ambiguity.
1216 debug!("multiple matches, ambig");
1223 // If there are *NO* candidates, then there are no impls --
1224 // that we know of, anyway. Note that in the case where there
1225 // are unbound type variables within the obligation, it might
1226 // be the case that you could still satisfy the obligation
1227 // from another crate by instantiating the type variables with
1228 // a type from another crate that does have an impl. This case
1229 // is checked for in `evaluate_stack` (and hence users
1230 // who might care about this case, like coherence, should use
1232 if candidates.is_empty() {
1233 return Err(Unimplemented);
1236 // Just one candidate left.
1237 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1240 fn is_knowable<'o>(&mut self,
1241 stack: &TraitObligationStack<'o, 'tcx>)
1244 debug!("is_knowable(intercrate={:?})", self.intercrate);
1246 if !self.intercrate.is_some() {
1250 let obligation = &stack.obligation;
1251 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1253 // ok to skip binder because of the nature of the
1254 // trait-ref-is-knowable check, which does not care about
1256 let trait_ref = predicate.skip_binder().trait_ref;
1258 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1259 if let (Some(Conflict::Downstream { used_to_be_broken: true }),
1260 Some(IntercrateMode::Issue43355)) = (result, self.intercrate) {
1261 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1268 /// Returns true if the global caches can be used.
1269 /// Do note that if the type itself is not in the
1270 /// global tcx, the local caches will be used.
1271 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1272 // If there are any where-clauses in scope, then we always use
1273 // a cache local to this particular scope. Otherwise, we
1274 // switch to a global cache. We used to try and draw
1275 // finer-grained distinctions, but that led to a serious of
1276 // annoying and weird bugs like #22019 and #18290. This simple
1277 // rule seems to be pretty clearly safe and also still retains
1278 // a very high hit rate (~95% when compiling rustc).
1279 if !param_env.caller_bounds.is_empty() {
1283 // Avoid using the master cache during coherence and just rely
1284 // on the local cache. This effectively disables caching
1285 // during coherence. It is really just a simplification to
1286 // avoid us having to fear that coherence results "pollute"
1287 // the master cache. Since coherence executes pretty quickly,
1288 // it's not worth going to more trouble to increase the
1289 // hit-rate I don't think.
1290 if self.intercrate.is_some() {
1294 // Otherwise, we can use the global cache.
1298 fn check_candidate_cache(&mut self,
1299 param_env: ty::ParamEnv<'tcx>,
1300 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1301 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1303 let tcx = self.tcx();
1304 let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1305 if self.can_use_global_caches(param_env) {
1306 let cache = tcx.selection_cache.hashmap.borrow();
1307 if let Some(cached) = cache.get(&trait_ref) {
1308 return Some(cached.get(tcx));
1311 self.infcx.selection_cache.hashmap
1314 .map(|v| v.get(tcx))
1317 fn insert_candidate_cache(&mut self,
1318 param_env: ty::ParamEnv<'tcx>,
1319 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1320 dep_node: DepNodeIndex,
1321 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1323 let tcx = self.tcx();
1324 let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1325 if self.can_use_global_caches(param_env) {
1326 let mut cache = tcx.selection_cache.hashmap.borrow_mut();
1327 if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1328 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1329 cache.insert(trait_ref, WithDepNode::new(dep_node, candidate));
1335 self.infcx.selection_cache.hashmap
1337 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1340 fn assemble_candidates<'o>(&mut self,
1341 stack: &TraitObligationStack<'o, 'tcx>)
1342 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1344 let TraitObligationStack { obligation, .. } = *stack;
1345 let ref obligation = Obligation {
1346 param_env: obligation.param_env,
1347 cause: obligation.cause.clone(),
1348 recursion_depth: obligation.recursion_depth,
1349 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1352 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1353 // Self is a type variable (e.g. `_: AsRef<str>`).
1355 // This is somewhat problematic, as the current scheme can't really
1356 // handle it turning to be a projection. This does end up as truly
1357 // ambiguous in most cases anyway.
1359 // Take the fast path out - this also improves
1360 // performance by preventing assemble_candidates_from_impls from
1361 // matching every impl for this trait.
1362 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1365 let mut candidates = SelectionCandidateSet {
1370 // Other bounds. Consider both in-scope bounds from fn decl
1371 // and applicable impls. There is a certain set of precedence rules here.
1373 let def_id = obligation.predicate.def_id();
1374 let lang_items = self.tcx().lang_items();
1375 if lang_items.copy_trait() == Some(def_id) {
1376 debug!("obligation self ty is {:?}",
1377 obligation.predicate.0.self_ty());
1379 // User-defined copy impls are permitted, but only for
1380 // structs and enums.
1381 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1383 // For other types, we'll use the builtin rules.
1384 let copy_conditions = self.copy_clone_conditions(obligation);
1385 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1386 } else if lang_items.sized_trait() == Some(def_id) {
1387 // Sized is never implementable by end-users, it is
1388 // always automatically computed.
1389 let sized_conditions = self.sized_conditions(obligation);
1390 self.assemble_builtin_bound_candidates(sized_conditions,
1392 } else if lang_items.unsize_trait() == Some(def_id) {
1393 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1395 if lang_items.clone_trait() == Some(def_id) {
1396 // Same builtin conditions as `Copy`, i.e. every type which has builtin support
1397 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1398 // types have builtin support for `Clone`.
1399 let clone_conditions = self.copy_clone_conditions(obligation);
1400 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1403 self.assemble_generator_candidates(obligation, &mut candidates)?;
1404 self.assemble_closure_candidates(obligation, &mut candidates)?;
1405 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1406 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1407 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1410 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1411 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1412 // Auto implementations have lower priority, so we only
1413 // consider triggering a default if there is no other impl that can apply.
1414 if candidates.vec.is_empty() {
1415 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1417 debug!("candidate list size: {}", candidates.vec.len());
1421 fn assemble_candidates_from_projected_tys(&mut self,
1422 obligation: &TraitObligation<'tcx>,
1423 candidates: &mut SelectionCandidateSet<'tcx>)
1425 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1427 // before we go into the whole skolemization thing, just
1428 // quickly check if the self-type is a projection at all.
1429 match obligation.predicate.0.trait_ref.self_ty().sty {
1430 ty::TyProjection(_) | ty::TyAnon(..) => {}
1431 ty::TyInfer(ty::TyVar(_)) => {
1432 span_bug!(obligation.cause.span,
1433 "Self=_ should have been handled by assemble_candidates");
1438 let result = self.probe(|this, snapshot| {
1439 this.match_projection_obligation_against_definition_bounds(obligation,
1444 candidates.vec.push(ProjectionCandidate);
1448 fn match_projection_obligation_against_definition_bounds(
1450 obligation: &TraitObligation<'tcx>,
1451 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
1454 let poly_trait_predicate =
1455 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1456 let (skol_trait_predicate, skol_map) =
1457 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1458 debug!("match_projection_obligation_against_definition_bounds: \
1459 skol_trait_predicate={:?} skol_map={:?}",
1460 skol_trait_predicate,
1463 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1464 ty::TyProjection(ref data) =>
1465 (data.trait_ref(self.tcx()).def_id, data.substs),
1466 ty::TyAnon(def_id, substs) => (def_id, substs),
1469 obligation.cause.span,
1470 "match_projection_obligation_against_definition_bounds() called \
1471 but self-ty not a projection: {:?}",
1472 skol_trait_predicate.trait_ref.self_ty());
1475 debug!("match_projection_obligation_against_definition_bounds: \
1476 def_id={:?}, substs={:?}",
1479 let predicates_of = self.tcx().predicates_of(def_id);
1480 let bounds = predicates_of.instantiate(self.tcx(), substs);
1481 debug!("match_projection_obligation_against_definition_bounds: \
1485 let matching_bound =
1486 util::elaborate_predicates(self.tcx(), bounds.predicates)
1490 |this, _| this.match_projection(obligation,
1492 skol_trait_predicate.trait_ref.clone(),
1496 debug!("match_projection_obligation_against_definition_bounds: \
1497 matching_bound={:?}",
1499 match matching_bound {
1502 // Repeat the successful match, if any, this time outside of a probe.
1503 let result = self.match_projection(obligation,
1505 skol_trait_predicate.trait_ref.clone(),
1509 self.infcx.pop_skolemized(skol_map, snapshot);
1517 fn match_projection(&mut self,
1518 obligation: &TraitObligation<'tcx>,
1519 trait_bound: ty::PolyTraitRef<'tcx>,
1520 skol_trait_ref: ty::TraitRef<'tcx>,
1521 skol_map: &infer::SkolemizationMap<'tcx>,
1522 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
1525 assert!(!skol_trait_ref.has_escaping_regions());
1526 if let Err(_) = self.infcx.at(&obligation.cause, obligation.param_env)
1527 .sup(ty::Binder(skol_trait_ref), trait_bound) {
1531 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1534 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1535 /// supplied to find out whether it is listed among them.
1537 /// Never affects inference environment.
1538 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1539 stack: &TraitObligationStack<'o, 'tcx>,
1540 candidates: &mut SelectionCandidateSet<'tcx>)
1541 -> Result<(),SelectionError<'tcx>>
1543 debug!("assemble_candidates_from_caller_bounds({:?})",
1547 stack.obligation.param_env.caller_bounds
1549 .filter_map(|o| o.to_opt_poly_trait_ref());
1551 // micro-optimization: filter out predicates relating to different
1553 let matching_bounds =
1554 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1556 let matching_bounds =
1557 matching_bounds.filter(
1558 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1560 let param_candidates =
1561 matching_bounds.map(|bound| ParamCandidate(bound));
1563 candidates.vec.extend(param_candidates);
1568 fn evaluate_where_clause<'o>(&mut self,
1569 stack: &TraitObligationStack<'o, 'tcx>,
1570 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1573 self.probe(move |this, _| {
1574 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1575 Ok(obligations) => {
1576 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1578 Err(()) => EvaluatedToErr
1583 fn assemble_generator_candidates(&mut self,
1584 obligation: &TraitObligation<'tcx>,
1585 candidates: &mut SelectionCandidateSet<'tcx>)
1586 -> Result<(),SelectionError<'tcx>>
1588 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1592 // ok to skip binder because the substs on generator types never
1593 // touch bound regions, they just capture the in-scope
1594 // type/region parameters
1595 let self_ty = *obligation.self_ty().skip_binder();
1597 ty::TyGenerator(..) => {
1598 debug!("assemble_generator_candidates: self_ty={:?} obligation={:?}",
1602 candidates.vec.push(GeneratorCandidate);
1605 ty::TyInfer(ty::TyVar(_)) => {
1606 debug!("assemble_generator_candidates: ambiguous self-type");
1607 candidates.ambiguous = true;
1610 _ => { return Ok(()); }
1614 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1615 /// FnMut<..>` where `X` is a closure type.
1617 /// Note: the type parameters on a closure candidate are modeled as *output* type
1618 /// parameters and hence do not affect whether this trait is a match or not. They will be
1619 /// unified during the confirmation step.
1620 fn assemble_closure_candidates(&mut self,
1621 obligation: &TraitObligation<'tcx>,
1622 candidates: &mut SelectionCandidateSet<'tcx>)
1623 -> Result<(),SelectionError<'tcx>>
1625 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.0.def_id()) {
1627 None => { return Ok(()); }
1630 // ok to skip binder because the substs on closure types never
1631 // touch bound regions, they just capture the in-scope
1632 // type/region parameters
1633 match obligation.self_ty().skip_binder().sty {
1634 ty::TyClosure(closure_def_id, closure_substs) => {
1635 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}",
1637 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1638 Some(closure_kind) => {
1639 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1640 if closure_kind.extends(kind) {
1641 candidates.vec.push(ClosureCandidate);
1645 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1646 candidates.vec.push(ClosureCandidate);
1651 ty::TyInfer(ty::TyVar(_)) => {
1652 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1653 candidates.ambiguous = true;
1656 _ => { return Ok(()); }
1660 /// Implement one of the `Fn()` family for a fn pointer.
1661 fn assemble_fn_pointer_candidates(&mut self,
1662 obligation: &TraitObligation<'tcx>,
1663 candidates: &mut SelectionCandidateSet<'tcx>)
1664 -> Result<(),SelectionError<'tcx>>
1666 // We provide impl of all fn traits for fn pointers.
1667 if self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()).is_none() {
1671 // ok to skip binder because what we are inspecting doesn't involve bound regions
1672 let self_ty = *obligation.self_ty().skip_binder();
1674 ty::TyInfer(ty::TyVar(_)) => {
1675 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1676 candidates.ambiguous = true; // could wind up being a fn() type
1679 // provide an impl, but only for suitable `fn` pointers
1680 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
1681 if let ty::Binder(ty::FnSig {
1682 unsafety: hir::Unsafety::Normal,
1686 }) = self_ty.fn_sig(self.tcx()) {
1687 candidates.vec.push(FnPointerCandidate);
1697 /// Search for impls that might apply to `obligation`.
1698 fn assemble_candidates_from_impls(&mut self,
1699 obligation: &TraitObligation<'tcx>,
1700 candidates: &mut SelectionCandidateSet<'tcx>)
1701 -> Result<(), SelectionError<'tcx>>
1703 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1705 self.tcx().for_each_relevant_impl(
1706 obligation.predicate.def_id(),
1707 obligation.predicate.0.trait_ref.self_ty(),
1709 self.probe(|this, snapshot| { /* [1] */
1710 match this.match_impl(impl_def_id, obligation, snapshot) {
1712 candidates.vec.push(ImplCandidate(impl_def_id));
1714 // NB: we can safely drop the skol map
1715 // since we are in a probe [1]
1716 mem::drop(skol_map);
1727 fn assemble_candidates_from_auto_impls(&mut self,
1728 obligation: &TraitObligation<'tcx>,
1729 candidates: &mut SelectionCandidateSet<'tcx>)
1730 -> Result<(), SelectionError<'tcx>>
1732 // OK to skip binder here because the tests we do below do not involve bound regions
1733 let self_ty = *obligation.self_ty().skip_binder();
1734 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
1736 let def_id = obligation.predicate.def_id();
1738 if self.tcx().trait_is_auto(def_id) {
1740 ty::TyDynamic(..) => {
1741 // For object types, we don't know what the closed
1742 // over types are. This means we conservatively
1743 // say nothing; a candidate may be added by
1744 // `assemble_candidates_from_object_ty`.
1746 ty::TyForeign(..) => {
1747 // Since the contents of foreign types is unknown,
1748 // we don't add any `..` impl. Default traits could
1749 // still be provided by a manual implementation for
1750 // this trait and type.
1753 ty::TyProjection(..) => {
1754 // In these cases, we don't know what the actual
1755 // type is. Therefore, we cannot break it down
1756 // into its constituent types. So we don't
1757 // consider the `..` impl but instead just add no
1758 // candidates: this means that typeck will only
1759 // succeed if there is another reason to believe
1760 // that this obligation holds. That could be a
1761 // where-clause or, in the case of an object type,
1762 // it could be that the object type lists the
1763 // trait (e.g. `Foo+Send : Send`). See
1764 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1765 // for an example of a test case that exercises
1768 ty::TyInfer(ty::TyVar(_)) => {
1769 // the auto impl might apply, we don't know
1770 candidates.ambiguous = true;
1773 candidates.vec.push(AutoImplCandidate(def_id.clone()))
1781 /// Search for impls that might apply to `obligation`.
1782 fn assemble_candidates_from_object_ty(&mut self,
1783 obligation: &TraitObligation<'tcx>,
1784 candidates: &mut SelectionCandidateSet<'tcx>)
1786 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1787 obligation.self_ty().skip_binder());
1789 // Object-safety candidates are only applicable to object-safe
1790 // traits. Including this check is useful because it helps
1791 // inference in cases of traits like `BorrowFrom`, which are
1792 // not object-safe, and which rely on being able to infer the
1793 // self-type from one of the other inputs. Without this check,
1794 // these cases wind up being considered ambiguous due to a
1795 // (spurious) ambiguity introduced here.
1796 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1797 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1801 self.probe(|this, _snapshot| {
1802 // the code below doesn't care about regions, and the
1803 // self-ty here doesn't escape this probe, so just erase
1805 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1806 let poly_trait_ref = match self_ty.sty {
1807 ty::TyDynamic(ref data, ..) => {
1808 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1809 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1810 pushing candidate");
1811 candidates.vec.push(BuiltinObjectCandidate);
1815 match data.principal() {
1816 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1820 ty::TyInfer(ty::TyVar(_)) => {
1821 debug!("assemble_candidates_from_object_ty: ambiguous");
1822 candidates.ambiguous = true; // could wind up being an object type
1830 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1833 // Count only those upcast versions that match the trait-ref
1834 // we are looking for. Specifically, do not only check for the
1835 // correct trait, but also the correct type parameters.
1836 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1837 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1838 let upcast_trait_refs =
1839 util::supertraits(this.tcx(), poly_trait_ref)
1840 .filter(|upcast_trait_ref| {
1841 this.probe(|this, _| {
1842 let upcast_trait_ref = upcast_trait_ref.clone();
1843 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1848 if upcast_trait_refs > 1 {
1849 // can be upcast in many ways; need more type information
1850 candidates.ambiguous = true;
1851 } else if upcast_trait_refs == 1 {
1852 candidates.vec.push(ObjectCandidate);
1857 /// Search for unsizing that might apply to `obligation`.
1858 fn assemble_candidates_for_unsizing(&mut self,
1859 obligation: &TraitObligation<'tcx>,
1860 candidates: &mut SelectionCandidateSet<'tcx>) {
1861 // We currently never consider higher-ranked obligations e.g.
1862 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1863 // because they are a priori invalid, and we could potentially add support
1864 // for them later, it's just that there isn't really a strong need for it.
1865 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1866 // impl, and those are generally applied to concrete types.
1868 // That said, one might try to write a fn with a where clause like
1869 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1870 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1871 // Still, you'd be more likely to write that where clause as
1873 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1874 // obligation above. Should be possible to extend this in the future.
1875 let source = match obligation.self_ty().no_late_bound_regions() {
1878 // Don't add any candidates if there are bound regions.
1882 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1884 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1887 let may_apply = match (&source.sty, &target.sty) {
1888 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1889 (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1890 // Upcasts permit two things:
1892 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1893 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1895 // Note that neither of these changes requires any
1896 // change at runtime. Eventually this will be
1899 // We always upcast when we can because of reason
1900 // #2 (region bounds).
1901 match (data_a.principal(), data_b.principal()) {
1902 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1903 data_b.auto_traits()
1904 // All of a's auto traits need to be in b's auto traits.
1905 .all(|b| data_a.auto_traits().any(|a| a == b)),
1911 (_, &ty::TyDynamic(..)) => true,
1913 // Ambiguous handling is below T -> Trait, because inference
1914 // variables can still implement Unsize<Trait> and nested
1915 // obligations will have the final say (likely deferred).
1916 (&ty::TyInfer(ty::TyVar(_)), _) |
1917 (_, &ty::TyInfer(ty::TyVar(_))) => {
1918 debug!("assemble_candidates_for_unsizing: ambiguous");
1919 candidates.ambiguous = true;
1924 (&ty::TyArray(..), &ty::TySlice(_)) => true,
1926 // Struct<T> -> Struct<U>.
1927 (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1928 def_id_a == def_id_b
1931 // (.., T) -> (.., U).
1932 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
1933 tys_a.len() == tys_b.len()
1940 candidates.vec.push(BuiltinUnsizeCandidate);
1944 ///////////////////////////////////////////////////////////////////////////
1947 // Winnowing is the process of attempting to resolve ambiguity by
1948 // probing further. During the winnowing process, we unify all
1949 // type variables (ignoring skolemization) and then we also
1950 // attempt to evaluate recursive bounds to see if they are
1953 /// Returns true if `candidate_i` should be dropped in favor of
1954 /// `candidate_j`. Generally speaking we will drop duplicate
1955 /// candidates and prefer where-clause candidates.
1956 /// Returns true if `victim` should be dropped in favor of
1957 /// `other`. Generally speaking we will drop duplicate
1958 /// candidates and prefer where-clause candidates.
1960 /// See the comment for "SelectionCandidate" for more details.
1961 fn candidate_should_be_dropped_in_favor_of<'o>(
1963 victim: &EvaluatedCandidate<'tcx>,
1964 other: &EvaluatedCandidate<'tcx>)
1967 if victim.candidate == other.candidate {
1971 match other.candidate {
1973 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1974 AutoImplCandidate(..) => {
1976 "default implementations shouldn't be recorded \
1977 when there are other valid candidates");
1981 GeneratorCandidate |
1982 FnPointerCandidate |
1983 BuiltinObjectCandidate |
1984 BuiltinUnsizeCandidate |
1985 BuiltinCandidate { .. } => {
1986 // We have a where-clause so don't go around looking
1991 ProjectionCandidate => {
1992 // Arbitrarily give param candidates priority
1993 // over projection and object candidates.
1996 ParamCandidate(..) => false,
1998 ImplCandidate(other_def) => {
1999 // See if we can toss out `victim` based on specialization.
2000 // This requires us to know *for sure* that the `other` impl applies
2001 // i.e. EvaluatedToOk:
2002 if other.evaluation == EvaluatedToOk {
2003 if let ImplCandidate(victim_def) = victim.candidate {
2004 let tcx = self.tcx().global_tcx();
2005 return tcx.specializes((other_def, victim_def)) ||
2006 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
2016 ///////////////////////////////////////////////////////////////////////////
2019 // These cover the traits that are built-in to the language
2020 // itself. This includes `Copy` and `Sized` for sure. For the
2021 // moment, it also includes `Send` / `Sync` and a few others, but
2022 // those will hopefully change to library-defined traits in the
2025 // HACK: if this returns an error, selection exits without considering
2027 fn assemble_builtin_bound_candidates<'o>(&mut self,
2028 conditions: BuiltinImplConditions<'tcx>,
2029 candidates: &mut SelectionCandidateSet<'tcx>)
2030 -> Result<(),SelectionError<'tcx>>
2033 BuiltinImplConditions::Where(nested) => {
2034 debug!("builtin_bound: nested={:?}", nested);
2035 candidates.vec.push(BuiltinCandidate {
2036 has_nested: nested.skip_binder().len() > 0
2040 BuiltinImplConditions::None => { Ok(()) }
2041 BuiltinImplConditions::Ambiguous => {
2042 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2043 Ok(candidates.ambiguous = true)
2045 BuiltinImplConditions::Never => { Err(Unimplemented) }
2049 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2050 -> BuiltinImplConditions<'tcx>
2052 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
2054 // NOTE: binder moved to (*)
2055 let self_ty = self.infcx.shallow_resolve(
2056 obligation.predicate.skip_binder().self_ty());
2059 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
2060 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
2061 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
2062 ty::TyChar | ty::TyRef(..) | ty::TyGenerator(..) |
2063 ty::TyGeneratorWitness(..) | ty::TyArray(..) | ty::TyClosure(..) |
2064 ty::TyNever | ty::TyError => {
2065 // safe for everything
2066 Where(ty::Binder(Vec::new()))
2069 ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) | ty::TyForeign(..) => Never,
2071 ty::TyTuple(tys, _) => {
2072 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
2075 ty::TyAdt(def, substs) => {
2076 let sized_crit = def.sized_constraint(self.tcx());
2077 // (*) binder moved here
2079 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
2083 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
2084 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
2086 ty::TyInfer(ty::FreshTy(_))
2087 | ty::TyInfer(ty::FreshIntTy(_))
2088 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2089 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2095 fn copy_clone_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2096 -> BuiltinImplConditions<'tcx>
2098 // NOTE: binder moved to (*)
2099 let self_ty = self.infcx.shallow_resolve(
2100 obligation.predicate.skip_binder().self_ty());
2102 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
2105 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
2106 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
2107 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
2108 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
2109 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
2110 Where(ty::Binder(Vec::new()))
2113 ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
2114 ty::TyGenerator(..) | ty::TyGeneratorWitness(..) | ty::TyForeign(..) |
2115 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
2119 ty::TyArray(element_ty, _) => {
2120 // (*) binder moved here
2121 Where(ty::Binder(vec![element_ty]))
2124 ty::TyTuple(tys, _) => {
2125 // (*) binder moved here
2126 Where(ty::Binder(tys.to_vec()))
2129 ty::TyClosure(def_id, substs) => {
2130 let trait_id = obligation.predicate.def_id();
2132 Some(trait_id) == self.tcx().lang_items().copy_trait() &&
2133 self.tcx().has_copy_closures(def_id.krate);
2134 let clone_closures =
2135 Some(trait_id) == self.tcx().lang_items().clone_trait() &&
2136 self.tcx().has_clone_closures(def_id.krate);
2138 if copy_closures || clone_closures {
2139 Where(ty::Binder(substs.upvar_tys(def_id, self.tcx()).collect()))
2145 ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
2146 // Fallback to whatever user-defined impls exist in this case.
2150 ty::TyInfer(ty::TyVar(_)) => {
2151 // Unbound type variable. Might or might not have
2152 // applicable impls and so forth, depending on what
2153 // those type variables wind up being bound to.
2157 ty::TyInfer(ty::FreshTy(_))
2158 | ty::TyInfer(ty::FreshIntTy(_))
2159 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2160 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2166 /// For default impls, we need to break apart a type into its
2167 /// "constituent types" -- meaning, the types that it contains.
2169 /// Here are some (simple) examples:
2172 /// (i32, u32) -> [i32, u32]
2173 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2174 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2175 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2177 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2187 ty::TyInfer(ty::IntVar(_)) |
2188 ty::TyInfer(ty::FloatVar(_)) |
2197 ty::TyProjection(..) |
2198 ty::TyInfer(ty::TyVar(_)) |
2199 ty::TyInfer(ty::FreshTy(_)) |
2200 ty::TyInfer(ty::FreshIntTy(_)) |
2201 ty::TyInfer(ty::FreshFloatTy(_)) => {
2202 bug!("asked to assemble constituent types of unexpected type: {:?}",
2206 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
2207 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
2211 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
2215 ty::TyTuple(ref tys, _) => {
2216 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2220 ty::TyClosure(def_id, ref substs) => {
2221 substs.upvar_tys(def_id, self.tcx()).collect()
2224 ty::TyGenerator(def_id, ref substs, interior) => {
2225 substs.upvar_tys(def_id, self.tcx()).chain(iter::once(interior.witness)).collect()
2228 ty::TyGeneratorWitness(types) => {
2229 // This is sound because no regions in the witness can refer to
2230 // the binder outside the witness. So we'll effectivly reuse
2231 // the implicit binder around the witness.
2232 types.skip_binder().to_vec()
2235 // for `PhantomData<T>`, we pass `T`
2236 ty::TyAdt(def, substs) if def.is_phantom_data() => {
2237 substs.types().collect()
2240 ty::TyAdt(def, substs) => {
2242 .map(|f| f.ty(self.tcx(), substs))
2246 ty::TyAnon(def_id, substs) => {
2247 // We can resolve the `impl Trait` to its concrete type,
2248 // which enforces a DAG between the functions requiring
2249 // the auto trait bounds in question.
2250 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2255 fn collect_predicates_for_types(&mut self,
2256 param_env: ty::ParamEnv<'tcx>,
2257 cause: ObligationCause<'tcx>,
2258 recursion_depth: usize,
2259 trait_def_id: DefId,
2260 types: ty::Binder<Vec<Ty<'tcx>>>)
2261 -> Vec<PredicateObligation<'tcx>>
2263 // Because the types were potentially derived from
2264 // higher-ranked obligations they may reference late-bound
2265 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2266 // yield a type like `for<'a> &'a int`. In general, we
2267 // maintain the invariant that we never manipulate bound
2268 // regions, so we have to process these bound regions somehow.
2270 // The strategy is to:
2272 // 1. Instantiate those regions to skolemized regions (e.g.,
2273 // `for<'a> &'a int` becomes `&0 int`.
2274 // 2. Produce something like `&'0 int : Copy`
2275 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2277 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
2278 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
2280 self.in_snapshot(|this, snapshot| {
2281 let (skol_ty, skol_map) =
2282 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
2283 let Normalized { value: normalized_ty, mut obligations } =
2284 project::normalize_with_depth(this,
2289 let skol_obligation =
2290 this.tcx().predicate_for_trait_def(param_env,
2296 obligations.push(skol_obligation);
2297 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2302 ///////////////////////////////////////////////////////////////////////////
2305 // Confirmation unifies the output type parameters of the trait
2306 // with the values found in the obligation, possibly yielding a
2307 // type error. See [rustc guide] for more details.
2310 // https://rust-lang-nursery.github.io/rustc-guide/trait-resolution.html#confirmation
2312 fn confirm_candidate(&mut self,
2313 obligation: &TraitObligation<'tcx>,
2314 candidate: SelectionCandidate<'tcx>)
2315 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2317 debug!("confirm_candidate({:?}, {:?})",
2322 BuiltinCandidate { has_nested } => {
2323 let data = self.confirm_builtin_candidate(obligation, has_nested);
2324 Ok(VtableBuiltin(data))
2327 ParamCandidate(param) => {
2328 let obligations = self.confirm_param_candidate(obligation, param);
2329 Ok(VtableParam(obligations))
2332 AutoImplCandidate(trait_def_id) => {
2333 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2334 Ok(VtableAutoImpl(data))
2337 ImplCandidate(impl_def_id) => {
2338 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2341 ClosureCandidate => {
2342 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2343 Ok(VtableClosure(vtable_closure))
2346 GeneratorCandidate => {
2347 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2348 Ok(VtableGenerator(vtable_generator))
2351 BuiltinObjectCandidate => {
2352 // This indicates something like `(Trait+Send) :
2353 // Send`. In this case, we know that this holds
2354 // because that's what the object type is telling us,
2355 // and there's really no additional obligations to
2356 // prove and no types in particular to unify etc.
2357 Ok(VtableParam(Vec::new()))
2360 ObjectCandidate => {
2361 let data = self.confirm_object_candidate(obligation);
2362 Ok(VtableObject(data))
2365 FnPointerCandidate => {
2367 self.confirm_fn_pointer_candidate(obligation)?;
2368 Ok(VtableFnPointer(data))
2371 ProjectionCandidate => {
2372 self.confirm_projection_candidate(obligation);
2373 Ok(VtableParam(Vec::new()))
2376 BuiltinUnsizeCandidate => {
2377 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2378 Ok(VtableBuiltin(data))
2383 fn confirm_projection_candidate(&mut self,
2384 obligation: &TraitObligation<'tcx>)
2386 self.in_snapshot(|this, snapshot| {
2388 this.match_projection_obligation_against_definition_bounds(obligation,
2394 fn confirm_param_candidate(&mut self,
2395 obligation: &TraitObligation<'tcx>,
2396 param: ty::PolyTraitRef<'tcx>)
2397 -> Vec<PredicateObligation<'tcx>>
2399 debug!("confirm_param_candidate({:?},{:?})",
2403 // During evaluation, we already checked that this
2404 // where-clause trait-ref could be unified with the obligation
2405 // trait-ref. Repeat that unification now without any
2406 // transactional boundary; it should not fail.
2407 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2408 Ok(obligations) => obligations,
2410 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2417 fn confirm_builtin_candidate(&mut self,
2418 obligation: &TraitObligation<'tcx>,
2420 -> VtableBuiltinData<PredicateObligation<'tcx>>
2422 debug!("confirm_builtin_candidate({:?}, {:?})",
2423 obligation, has_nested);
2425 let lang_items = self.tcx().lang_items();
2426 let obligations = if has_nested {
2427 let trait_def = obligation.predicate.def_id();
2428 let conditions = match trait_def {
2429 _ if Some(trait_def) == lang_items.sized_trait() => {
2430 self.sized_conditions(obligation)
2432 _ if Some(trait_def) == lang_items.copy_trait() => {
2433 self.copy_clone_conditions(obligation)
2435 _ if Some(trait_def) == lang_items.clone_trait() => {
2436 self.copy_clone_conditions(obligation)
2438 _ => bug!("unexpected builtin trait {:?}", trait_def)
2440 let nested = match conditions {
2441 BuiltinImplConditions::Where(nested) => nested,
2442 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2446 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2447 self.collect_predicates_for_types(obligation.param_env,
2449 obligation.recursion_depth+1,
2456 debug!("confirm_builtin_candidate: obligations={:?}",
2459 VtableBuiltinData { nested: obligations }
2462 /// This handles the case where a `auto trait Foo` impl is being used.
2463 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2465 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2466 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2467 fn confirm_auto_impl_candidate(&mut self,
2468 obligation: &TraitObligation<'tcx>,
2469 trait_def_id: DefId)
2470 -> VtableAutoImplData<PredicateObligation<'tcx>>
2472 debug!("confirm_auto_impl_candidate({:?}, {:?})",
2476 // binder is moved below
2477 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2478 let types = self.constituent_types_for_ty(self_ty);
2479 self.vtable_auto_impl(obligation, trait_def_id, ty::Binder(types))
2482 /// See `confirm_auto_impl_candidate`
2483 fn vtable_auto_impl(&mut self,
2484 obligation: &TraitObligation<'tcx>,
2485 trait_def_id: DefId,
2486 nested: ty::Binder<Vec<Ty<'tcx>>>)
2487 -> VtableAutoImplData<PredicateObligation<'tcx>>
2489 debug!("vtable_auto_impl: nested={:?}", nested);
2491 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2492 let mut obligations = self.collect_predicates_for_types(
2493 obligation.param_env,
2495 obligation.recursion_depth+1,
2499 let trait_obligations = self.in_snapshot(|this, snapshot| {
2500 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2501 let (trait_ref, skol_map) =
2502 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2503 let cause = obligation.derived_cause(ImplDerivedObligation);
2504 this.impl_or_trait_obligations(cause,
2505 obligation.recursion_depth + 1,
2506 obligation.param_env,
2513 obligations.extend(trait_obligations);
2515 debug!("vtable_auto_impl: obligations={:?}", obligations);
2517 VtableAutoImplData {
2523 fn confirm_impl_candidate(&mut self,
2524 obligation: &TraitObligation<'tcx>,
2526 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2528 debug!("confirm_impl_candidate({:?},{:?})",
2532 // First, create the substitutions by matching the impl again,
2533 // this time not in a probe.
2534 self.in_snapshot(|this, snapshot| {
2535 let (substs, skol_map) =
2536 this.rematch_impl(impl_def_id, obligation,
2538 debug!("confirm_impl_candidate substs={:?}", substs);
2539 let cause = obligation.derived_cause(ImplDerivedObligation);
2540 this.vtable_impl(impl_def_id,
2543 obligation.recursion_depth + 1,
2544 obligation.param_env,
2550 fn vtable_impl(&mut self,
2552 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2553 cause: ObligationCause<'tcx>,
2554 recursion_depth: usize,
2555 param_env: ty::ParamEnv<'tcx>,
2556 skol_map: infer::SkolemizationMap<'tcx>,
2557 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
2558 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2560 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2566 let mut impl_obligations =
2567 self.impl_or_trait_obligations(cause,
2575 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2579 // Because of RFC447, the impl-trait-ref and obligations
2580 // are sufficient to determine the impl substs, without
2581 // relying on projections in the impl-trait-ref.
2583 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2584 impl_obligations.append(&mut substs.obligations);
2586 VtableImplData { impl_def_id,
2587 substs: substs.value,
2588 nested: impl_obligations }
2591 fn confirm_object_candidate(&mut self,
2592 obligation: &TraitObligation<'tcx>)
2593 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2595 debug!("confirm_object_candidate({:?})",
2598 // FIXME skipping binder here seems wrong -- we should
2599 // probably flatten the binder from the obligation and the
2600 // binder from the object. Have to try to make a broken test
2601 // case that results. -nmatsakis
2602 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2603 let poly_trait_ref = match self_ty.sty {
2604 ty::TyDynamic(ref data, ..) => {
2605 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2608 span_bug!(obligation.cause.span,
2609 "object candidate with non-object");
2613 let mut upcast_trait_ref = None;
2614 let mut nested = vec![];
2618 let tcx = self.tcx();
2620 // We want to find the first supertrait in the list of
2621 // supertraits that we can unify with, and do that
2622 // unification. We know that there is exactly one in the list
2623 // where we can unify because otherwise select would have
2624 // reported an ambiguity. (When we do find a match, also
2625 // record it for later.)
2627 util::supertraits(tcx, poly_trait_ref)
2631 |this, _| this.match_poly_trait_ref(obligation, t))
2633 Ok(obligations) => {
2634 upcast_trait_ref = Some(t);
2635 nested.extend(obligations);
2642 // Additionally, for each of the nonmatching predicates that
2643 // we pass over, we sum up the set of number of vtable
2644 // entries, so that we can compute the offset for the selected
2647 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2653 upcast_trait_ref: upcast_trait_ref.unwrap(),
2659 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2660 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2662 debug!("confirm_fn_pointer_candidate({:?})",
2665 // ok to skip binder; it is reintroduced below
2666 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2667 let sig = self_ty.fn_sig(self.tcx());
2669 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2672 util::TupleArgumentsFlag::Yes)
2673 .map_bound(|(trait_ref, _)| trait_ref);
2675 let Normalized { value: trait_ref, obligations } =
2676 project::normalize_with_depth(self,
2677 obligation.param_env,
2678 obligation.cause.clone(),
2679 obligation.recursion_depth + 1,
2682 self.confirm_poly_trait_refs(obligation.cause.clone(),
2683 obligation.param_env,
2684 obligation.predicate.to_poly_trait_ref(),
2686 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2689 fn confirm_generator_candidate(&mut self,
2690 obligation: &TraitObligation<'tcx>)
2691 -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
2692 SelectionError<'tcx>>
2694 // ok to skip binder because the substs on generator types never
2695 // touch bound regions, they just capture the in-scope
2696 // type/region parameters
2697 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2698 let (closure_def_id, substs) = match self_ty.sty {
2699 ty::TyGenerator(id, substs, _) => (id, substs),
2700 _ => bug!("closure candidate for non-closure {:?}", obligation)
2703 debug!("confirm_generator_candidate({:?},{:?},{:?})",
2709 self.generator_trait_ref_unnormalized(obligation, closure_def_id, substs);
2713 } = normalize_with_depth(self,
2714 obligation.param_env,
2715 obligation.cause.clone(),
2716 obligation.recursion_depth+1,
2719 debug!("confirm_generator_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2725 self.confirm_poly_trait_refs(obligation.cause.clone(),
2726 obligation.param_env,
2727 obligation.predicate.to_poly_trait_ref(),
2730 Ok(VtableGeneratorData {
2731 closure_def_id: closure_def_id,
2732 substs: substs.clone(),
2737 fn confirm_closure_candidate(&mut self,
2738 obligation: &TraitObligation<'tcx>)
2739 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2740 SelectionError<'tcx>>
2742 debug!("confirm_closure_candidate({:?})", obligation);
2744 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.0.def_id()) {
2746 None => bug!("closure candidate for non-fn trait {:?}", obligation)
2749 // ok to skip binder because the substs on closure types never
2750 // touch bound regions, they just capture the in-scope
2751 // type/region parameters
2752 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2753 let (closure_def_id, substs) = match self_ty.sty {
2754 ty::TyClosure(id, substs) => (id, substs),
2755 _ => bug!("closure candidate for non-closure {:?}", obligation)
2759 self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
2763 } = normalize_with_depth(self,
2764 obligation.param_env,
2765 obligation.cause.clone(),
2766 obligation.recursion_depth+1,
2769 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2775 self.confirm_poly_trait_refs(obligation.cause.clone(),
2776 obligation.param_env,
2777 obligation.predicate.to_poly_trait_ref(),
2780 obligations.push(Obligation::new(
2781 obligation.cause.clone(),
2782 obligation.param_env,
2783 ty::Predicate::ClosureKind(closure_def_id, substs, kind)));
2785 Ok(VtableClosureData {
2787 substs: substs.clone(),
2792 /// In the case of closure types and fn pointers,
2793 /// we currently treat the input type parameters on the trait as
2794 /// outputs. This means that when we have a match we have only
2795 /// considered the self type, so we have to go back and make sure
2796 /// to relate the argument types too. This is kind of wrong, but
2797 /// since we control the full set of impls, also not that wrong,
2798 /// and it DOES yield better error messages (since we don't report
2799 /// errors as if there is no applicable impl, but rather report
2800 /// errors are about mismatched argument types.
2802 /// Here is an example. Imagine we have a closure expression
2803 /// and we desugared it so that the type of the expression is
2804 /// `Closure`, and `Closure` expects an int as argument. Then it
2805 /// is "as if" the compiler generated this impl:
2807 /// impl Fn(int) for Closure { ... }
2809 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2810 /// we have matched the self-type `Closure`. At this point we'll
2811 /// compare the `int` to `usize` and generate an error.
2813 /// Note that this checking occurs *after* the impl has selected,
2814 /// because these output type parameters should not affect the
2815 /// selection of the impl. Therefore, if there is a mismatch, we
2816 /// report an error to the user.
2817 fn confirm_poly_trait_refs(&mut self,
2818 obligation_cause: ObligationCause<'tcx>,
2819 obligation_param_env: ty::ParamEnv<'tcx>,
2820 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2821 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2822 -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>>
2824 let obligation_trait_ref = obligation_trait_ref.clone();
2826 .at(&obligation_cause, obligation_param_env)
2827 .sup(obligation_trait_ref, expected_trait_ref)
2828 .map(|InferOk { obligations, .. }| obligations)
2829 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2832 fn confirm_builtin_unsize_candidate(&mut self,
2833 obligation: &TraitObligation<'tcx>,)
2834 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>>
2836 let tcx = self.tcx();
2838 // assemble_candidates_for_unsizing should ensure there are no late bound
2839 // regions here. See the comment there for more details.
2840 let source = self.infcx.shallow_resolve(
2841 obligation.self_ty().no_late_bound_regions().unwrap());
2842 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2843 let target = self.infcx.shallow_resolve(target);
2845 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2848 let mut nested = vec![];
2849 match (&source.sty, &target.sty) {
2850 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2851 (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2852 // See assemble_candidates_for_unsizing for more info.
2853 // Binders reintroduced below in call to mk_existential_predicates.
2854 let principal = data_a.skip_binder().principal();
2855 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2856 .chain(data_a.skip_binder().projection_bounds()
2857 .map(|x| ty::ExistentialPredicate::Projection(x)))
2858 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2859 let new_trait = tcx.mk_dynamic(
2860 ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2861 let InferOk { obligations, .. } =
2862 self.infcx.at(&obligation.cause, obligation.param_env)
2863 .eq(target, new_trait)
2864 .map_err(|_| Unimplemented)?;
2865 nested.extend(obligations);
2867 // Register one obligation for 'a: 'b.
2868 let cause = ObligationCause::new(obligation.cause.span,
2869 obligation.cause.body_id,
2870 ObjectCastObligation(target));
2871 let outlives = ty::OutlivesPredicate(r_a, r_b);
2872 nested.push(Obligation::with_depth(cause,
2873 obligation.recursion_depth + 1,
2874 obligation.param_env,
2875 ty::Binder(outlives).to_predicate()));
2879 (_, &ty::TyDynamic(ref data, r)) => {
2880 let mut object_dids =
2881 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2882 if let Some(did) = object_dids.find(|did| {
2883 !tcx.is_object_safe(*did)
2885 return Err(TraitNotObjectSafe(did))
2888 let cause = ObligationCause::new(obligation.cause.span,
2889 obligation.cause.body_id,
2890 ObjectCastObligation(target));
2891 let mut push = |predicate| {
2892 nested.push(Obligation::with_depth(cause.clone(),
2893 obligation.recursion_depth + 1,
2894 obligation.param_env,
2898 // Create obligations:
2899 // - Casting T to Trait
2900 // - For all the various builtin bounds attached to the object cast. (In other
2901 // words, if the object type is Foo+Send, this would create an obligation for the
2903 // - Projection predicates
2904 for predicate in data.iter() {
2905 push(predicate.with_self_ty(tcx, source));
2908 // We can only make objects from sized types.
2909 let tr = ty::TraitRef {
2910 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2911 substs: tcx.mk_substs_trait(source, &[]),
2913 push(tr.to_predicate());
2915 // If the type is `Foo+'a`, ensures that the type
2916 // being cast to `Foo+'a` outlives `'a`:
2917 let outlives = ty::OutlivesPredicate(source, r);
2918 push(ty::Binder(outlives).to_predicate());
2922 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2923 let InferOk { obligations, .. } =
2924 self.infcx.at(&obligation.cause, obligation.param_env)
2926 .map_err(|_| Unimplemented)?;
2927 nested.extend(obligations);
2930 // Struct<T> -> Struct<U>.
2931 (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2934 .map(|f| tcx.type_of(f.did))
2935 .collect::<Vec<_>>();
2937 // The last field of the structure has to exist and contain type parameters.
2938 let field = if let Some(&field) = fields.last() {
2941 return Err(Unimplemented);
2943 let mut ty_params = BitVector::new(substs_a.types().count());
2944 let mut found = false;
2945 for ty in field.walk() {
2946 if let ty::TyParam(p) = ty.sty {
2947 ty_params.insert(p.idx as usize);
2952 return Err(Unimplemented);
2955 // Replace type parameters used in unsizing with
2956 // TyError and ensure they do not affect any other fields.
2957 // This could be checked after type collection for any struct
2958 // with a potentially unsized trailing field.
2959 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2960 if ty_params.contains(i) {
2961 Kind::from(tcx.types.err)
2966 let substs = tcx.mk_substs(params);
2967 for &ty in fields.split_last().unwrap().1 {
2968 if ty.subst(tcx, substs).references_error() {
2969 return Err(Unimplemented);
2973 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2974 let inner_source = field.subst(tcx, substs_a);
2975 let inner_target = field.subst(tcx, substs_b);
2977 // Check that the source struct with the target's
2978 // unsized parameters is equal to the target.
2979 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2980 if ty_params.contains(i) {
2981 substs_b.type_at(i).into()
2986 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
2987 let InferOk { obligations, .. } =
2988 self.infcx.at(&obligation.cause, obligation.param_env)
2989 .eq(target, new_struct)
2990 .map_err(|_| Unimplemented)?;
2991 nested.extend(obligations);
2993 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2994 nested.push(tcx.predicate_for_trait_def(
2995 obligation.param_env,
2996 obligation.cause.clone(),
2997 obligation.predicate.def_id(),
2998 obligation.recursion_depth + 1,
3003 // (.., T) -> (.., U).
3004 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
3005 assert_eq!(tys_a.len(), tys_b.len());
3007 // The last field of the tuple has to exist.
3008 let (a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3011 return Err(Unimplemented);
3013 let b_last = tys_b.last().unwrap();
3015 // Check that the source tuple with the target's
3016 // last element is equal to the target.
3017 let new_tuple = tcx.mk_tup(a_mid.iter().chain(Some(b_last)), false);
3018 let InferOk { obligations, .. } =
3019 self.infcx.at(&obligation.cause, obligation.param_env)
3020 .eq(target, new_tuple)
3021 .map_err(|_| Unimplemented)?;
3022 nested.extend(obligations);
3024 // Construct the nested T: Unsize<U> predicate.
3025 nested.push(tcx.predicate_for_trait_def(
3026 obligation.param_env,
3027 obligation.cause.clone(),
3028 obligation.predicate.def_id(),
3029 obligation.recursion_depth + 1,
3037 Ok(VtableBuiltinData { nested: nested })
3040 ///////////////////////////////////////////////////////////////////////////
3043 // Matching is a common path used for both evaluation and
3044 // confirmation. It basically unifies types that appear in impls
3045 // and traits. This does affect the surrounding environment;
3046 // therefore, when used during evaluation, match routines must be
3047 // run inside of a `probe()` so that their side-effects are
3050 fn rematch_impl(&mut self,
3052 obligation: &TraitObligation<'tcx>,
3053 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
3054 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
3055 infer::SkolemizationMap<'tcx>)
3057 match self.match_impl(impl_def_id, obligation, snapshot) {
3058 Ok((substs, skol_map)) => (substs, skol_map),
3060 bug!("Impl {:?} was matchable against {:?} but now is not",
3067 fn match_impl(&mut self,
3069 obligation: &TraitObligation<'tcx>,
3070 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
3071 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
3072 infer::SkolemizationMap<'tcx>), ()>
3074 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3076 // Before we create the substitutions and everything, first
3077 // consider a "quick reject". This avoids creating more types
3078 // and so forth that we need to.
3079 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3083 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
3084 &obligation.predicate,
3086 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3088 let impl_substs = self.infcx.fresh_substs_for_item(obligation.param_env.universe,
3089 obligation.cause.span,
3092 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
3095 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
3096 project::normalize_with_depth(self,
3097 obligation.param_env,
3098 obligation.cause.clone(),
3099 obligation.recursion_depth + 1,
3102 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
3103 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3107 skol_obligation_trait_ref);
3109 let InferOk { obligations, .. } =
3110 self.infcx.at(&obligation.cause, obligation.param_env)
3111 .eq(skol_obligation_trait_ref, impl_trait_ref)
3113 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
3116 nested_obligations.extend(obligations);
3118 if let Err(e) = self.infcx.leak_check(false,
3119 obligation.cause.span,
3122 debug!("match_impl: failed leak check due to `{}`", e);
3126 debug!("match_impl: success impl_substs={:?}", impl_substs);
3129 obligations: nested_obligations
3133 fn fast_reject_trait_refs(&mut self,
3134 obligation: &TraitObligation,
3135 impl_trait_ref: &ty::TraitRef)
3138 // We can avoid creating type variables and doing the full
3139 // substitution if we find that any of the input types, when
3140 // simplified, do not match.
3142 obligation.predicate.skip_binder().input_types()
3143 .zip(impl_trait_ref.input_types())
3144 .any(|(obligation_ty, impl_ty)| {
3145 let simplified_obligation_ty =
3146 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3147 let simplified_impl_ty =
3148 fast_reject::simplify_type(self.tcx(), impl_ty, false);
3150 simplified_obligation_ty.is_some() &&
3151 simplified_impl_ty.is_some() &&
3152 simplified_obligation_ty != simplified_impl_ty
3156 /// Normalize `where_clause_trait_ref` and try to match it against
3157 /// `obligation`. If successful, return any predicates that
3158 /// result from the normalization. Normalization is necessary
3159 /// because where-clauses are stored in the parameter environment
3161 fn match_where_clause_trait_ref(&mut self,
3162 obligation: &TraitObligation<'tcx>,
3163 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
3164 -> Result<Vec<PredicateObligation<'tcx>>,()>
3166 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3169 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3170 /// obligation is satisfied.
3171 fn match_poly_trait_ref(&mut self,
3172 obligation: &TraitObligation<'tcx>,
3173 poly_trait_ref: ty::PolyTraitRef<'tcx>)
3174 -> Result<Vec<PredicateObligation<'tcx>>,()>
3176 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3180 self.infcx.at(&obligation.cause, obligation.param_env)
3181 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3182 .map(|InferOk { obligations, .. }| obligations)
3186 ///////////////////////////////////////////////////////////////////////////
3189 fn match_fresh_trait_refs(&self,
3190 previous: &ty::PolyTraitRef<'tcx>,
3191 current: &ty::PolyTraitRef<'tcx>)
3194 let mut matcher = ty::_match::Match::new(self.tcx());
3195 matcher.relate(previous, current).is_ok()
3198 fn push_stack<'o,'s:'o>(&mut self,
3199 previous_stack: TraitObligationStackList<'s, 'tcx>,
3200 obligation: &'o TraitObligation<'tcx>)
3201 -> TraitObligationStack<'o, 'tcx>
3203 let fresh_trait_ref =
3204 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3206 TraitObligationStack {
3209 previous: previous_stack,
3213 fn closure_trait_ref_unnormalized(&mut self,
3214 obligation: &TraitObligation<'tcx>,
3215 closure_def_id: DefId,
3216 substs: ty::ClosureSubsts<'tcx>)
3217 -> ty::PolyTraitRef<'tcx>
3219 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3220 let ty::Binder((trait_ref, _)) =
3221 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
3222 obligation.predicate.0.self_ty(), // (1)
3224 util::TupleArgumentsFlag::No);
3225 // (1) Feels icky to skip the binder here, but OTOH we know
3226 // that the self-type is an unboxed closure type and hence is
3227 // in fact unparameterized (or at least does not reference any
3228 // regions bound in the obligation). Still probably some
3229 // refactoring could make this nicer.
3231 ty::Binder(trait_ref)
3234 fn generator_trait_ref_unnormalized(&mut self,
3235 obligation: &TraitObligation<'tcx>,
3236 closure_def_id: DefId,
3237 substs: ty::ClosureSubsts<'tcx>)
3238 -> ty::PolyTraitRef<'tcx>
3240 let gen_sig = substs.generator_poly_sig(closure_def_id, self.tcx());
3241 let ty::Binder((trait_ref, ..)) =
3242 self.tcx().generator_trait_ref_and_outputs(obligation.predicate.def_id(),
3243 obligation.predicate.0.self_ty(), // (1)
3245 // (1) Feels icky to skip the binder here, but OTOH we know
3246 // that the self-type is an generator type and hence is
3247 // in fact unparameterized (or at least does not reference any
3248 // regions bound in the obligation). Still probably some
3249 // refactoring could make this nicer.
3251 ty::Binder(trait_ref)
3254 /// Returns the obligations that are implied by instantiating an
3255 /// impl or trait. The obligations are substituted and fully
3256 /// normalized. This is used when confirming an impl or default
3258 fn impl_or_trait_obligations(&mut self,
3259 cause: ObligationCause<'tcx>,
3260 recursion_depth: usize,
3261 param_env: ty::ParamEnv<'tcx>,
3262 def_id: DefId, // of impl or trait
3263 substs: &Substs<'tcx>, // for impl or trait
3264 skol_map: infer::SkolemizationMap<'tcx>,
3265 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
3266 -> Vec<PredicateObligation<'tcx>>
3268 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3269 let tcx = self.tcx();
3271 // To allow for one-pass evaluation of the nested obligation,
3272 // each predicate must be preceded by the obligations required
3274 // for example, if we have:
3275 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3276 // the impl will have the following predicates:
3277 // <V as Iterator>::Item = U,
3278 // U: Iterator, U: Sized,
3279 // V: Iterator, V: Sized,
3280 // <U as Iterator>::Item: Copy
3281 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3282 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3283 // `$1: Copy`, so we must ensure the obligations are emitted in
3285 let predicates = tcx.predicates_of(def_id);
3286 assert_eq!(predicates.parent, None);
3287 let mut predicates: Vec<_> = predicates.predicates.iter().flat_map(|predicate| {
3288 let predicate = normalize_with_depth(self, param_env, cause.clone(), recursion_depth,
3289 &predicate.subst(tcx, substs));
3290 predicate.obligations.into_iter().chain(
3292 cause: cause.clone(),
3295 predicate: predicate.value
3298 // We are performing deduplication here to avoid exponential blowups
3299 // (#38528) from happening, but the real cause of the duplication is
3300 // unknown. What we know is that the deduplication avoids exponential
3301 // amount of predicates being propogated when processing deeply nested
3303 let mut seen = FxHashSet();
3304 predicates.retain(|i| seen.insert(i.clone()));
3305 self.infcx().plug_leaks(skol_map, snapshot, predicates)
3309 impl<'tcx> TraitObligation<'tcx> {
3310 #[allow(unused_comparisons)]
3311 pub fn derived_cause(&self,
3312 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
3313 -> ObligationCause<'tcx>
3316 * Creates a cause for obligations that are derived from
3317 * `obligation` by a recursive search (e.g., for a builtin
3318 * bound, or eventually a `auto trait Foo`). If `obligation`
3319 * is itself a derived obligation, this is just a clone, but
3320 * otherwise we create a "derived obligation" cause so as to
3321 * keep track of the original root obligation for error
3325 let obligation = self;
3327 // NOTE(flaper87): As of now, it keeps track of the whole error
3328 // chain. Ideally, we should have a way to configure this either
3329 // by using -Z verbose or just a CLI argument.
3330 if obligation.recursion_depth >= 0 {
3331 let derived_cause = DerivedObligationCause {
3332 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3333 parent_code: Rc::new(obligation.cause.code.clone())
3335 let derived_code = variant(derived_cause);
3336 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3338 obligation.cause.clone()
3343 impl<'tcx> SelectionCache<'tcx> {
3344 pub fn new() -> SelectionCache<'tcx> {
3346 hashmap: RefCell::new(FxHashMap())
3350 pub fn clear(&self) {
3351 *self.hashmap.borrow_mut() = FxHashMap()
3355 impl<'tcx> EvaluationCache<'tcx> {
3356 pub fn new() -> EvaluationCache<'tcx> {
3358 hashmap: RefCell::new(FxHashMap())
3362 pub fn clear(&self) {
3363 *self.hashmap.borrow_mut() = FxHashMap()
3367 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
3368 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
3369 TraitObligationStackList::with(self)
3372 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
3377 #[derive(Copy, Clone)]
3378 struct TraitObligationStackList<'o,'tcx:'o> {
3379 head: Option<&'o TraitObligationStack<'o,'tcx>>
3382 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
3383 fn empty() -> TraitObligationStackList<'o,'tcx> {
3384 TraitObligationStackList { head: None }
3387 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
3388 TraitObligationStackList { head: Some(r) }
3392 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
3393 type Item = &'o TraitObligationStack<'o,'tcx>;
3395 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3406 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3407 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3408 write!(f, "TraitObligationStack({:?})", self.obligation)
3413 pub struct WithDepNode<T> {
3414 dep_node: DepNodeIndex,
3418 impl<T: Clone> WithDepNode<T> {
3419 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3420 WithDepNode { dep_node, cached_value }
3423 pub fn get(&self, tcx: TyCtxt) -> T {
3424 tcx.dep_graph.read_index(self.dep_node);
3425 self.cached_value.clone()