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/traits/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, TraitQueryMode};
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, Overflow};
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::{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::bit_set::BitSet;
48 use rustc_data_structures::sync::Lock;
54 use rustc_target::spec::abi::Abi;
56 use util::nodemap::{FxHashMap, FxHashSet};
59 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
60 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
62 /// Freshener used specifically for skolemizing entries on the
63 /// obligation stack. This ensures that all entries on the stack
64 /// at one time will have the same set of skolemized entries,
65 /// which is important for checking for trait bounds that
66 /// recursively require themselves.
67 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
69 /// If true, indicates that the evaluation should be conservative
70 /// and consider the possibility of types outside this crate.
71 /// This comes up primarily when resolving ambiguity. Imagine
72 /// there is some trait reference `$0 : Bar` where `$0` is an
73 /// inference variable. If `intercrate` is true, then we can never
74 /// say for sure that this reference is not implemented, even if
75 /// there are *no impls at all for `Bar`*, because `$0` could be
76 /// bound to some type that in a downstream crate that implements
77 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
78 /// though, we set this to false, because we are only interested
79 /// in types that the user could actually have written --- in
80 /// other words, we consider `$0 : Bar` to be unimplemented if
81 /// there is no type that the user could *actually name* that
82 /// would satisfy it. This avoids crippling inference, basically.
83 intercrate: Option<IntercrateMode>,
85 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
87 /// Controls whether or not to filter out negative impls when selecting.
88 /// This is used in librustdoc to distinguish between the lack of an impl
89 /// and a negative impl
90 allow_negative_impls: bool,
92 /// The mode that trait queries run in, which informs our error handling
93 /// policy. In essence, canonicalized queries need their errors propagated
94 /// rather than immediately reported because we do not have accurate spans.
95 query_mode: TraitQueryMode,
98 #[derive(Clone, Debug)]
99 pub enum IntercrateAmbiguityCause {
102 self_desc: Option<String>,
104 UpstreamCrateUpdate {
106 self_desc: Option<String>,
110 impl IntercrateAmbiguityCause {
111 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
112 /// See #23980 for details.
113 pub fn add_intercrate_ambiguity_hint<'a, 'tcx>(&self,
114 err: &mut ::errors::DiagnosticBuilder) {
115 err.note(&self.intercrate_ambiguity_hint());
118 pub fn intercrate_ambiguity_hint(&self) -> String {
120 &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
121 let self_desc = if let &Some(ref ty) = self_desc {
122 format!(" for type `{}`", ty)
123 } else { String::new() };
124 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
126 &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
127 let self_desc = if let &Some(ref ty) = self_desc {
128 format!(" for type `{}`", ty)
129 } else { String::new() };
130 format!("upstream crates may add new impl of trait `{}`{} \
132 trait_desc, self_desc)
138 // A stack that walks back up the stack frame.
139 struct TraitObligationStack<'prev, 'tcx: 'prev> {
140 obligation: &'prev TraitObligation<'tcx>,
142 /// Trait ref from `obligation` but skolemized with the
143 /// selection-context's freshener. Used to check for recursion.
144 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
146 previous: TraitObligationStackList<'prev, 'tcx>,
150 pub struct SelectionCache<'tcx> {
151 hashmap: Lock<FxHashMap<ty::TraitRef<'tcx>,
152 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>>,
155 /// The selection process begins by considering all impls, where
156 /// clauses, and so forth that might resolve an obligation. Sometimes
157 /// we'll be able to say definitively that (e.g.) an impl does not
158 /// apply to the obligation: perhaps it is defined for `usize` but the
159 /// obligation is for `int`. In that case, we drop the impl out of the
160 /// list. But the other cases are considered *candidates*.
162 /// For selection to succeed, there must be exactly one matching
163 /// candidate. If the obligation is fully known, this is guaranteed
164 /// by coherence. However, if the obligation contains type parameters
165 /// or variables, there may be multiple such impls.
167 /// It is not a real problem if multiple matching impls exist because
168 /// of type variables - it just means the obligation isn't sufficiently
169 /// elaborated. In that case we report an ambiguity, and the caller can
170 /// try again after more type information has been gathered or report a
171 /// "type annotations required" error.
173 /// However, with type parameters, this can be a real problem - type
174 /// parameters don't unify with regular types, but they *can* unify
175 /// with variables from blanket impls, and (unless we know its bounds
176 /// will always be satisfied) picking the blanket impl will be wrong
177 /// for at least *some* substitutions. To make this concrete, if we have
179 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
180 /// impl<T: fmt::Debug> AsDebug for T {
182 /// fn debug(self) -> fmt::Debug { self }
184 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
186 /// we can't just use the impl to resolve the <T as AsDebug> obligation
187 /// - a type from another crate (that doesn't implement fmt::Debug) could
188 /// implement AsDebug.
190 /// Because where-clauses match the type exactly, multiple clauses can
191 /// only match if there are unresolved variables, and we can mostly just
192 /// report this ambiguity in that case. This is still a problem - we can't
193 /// *do anything* with ambiguities that involve only regions. This is issue
196 /// If a single where-clause matches and there are no inference
197 /// variables left, then it definitely matches and we can just select
200 /// In fact, we even select the where-clause when the obligation contains
201 /// inference variables. The can lead to inference making "leaps of logic",
202 /// for example in this situation:
204 /// pub trait Foo<T> { fn foo(&self) -> T; }
205 /// impl<T> Foo<()> for T { fn foo(&self) { } }
206 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
208 /// pub fn foo<T>(t: T) where T: Foo<bool> {
209 /// println!("{:?}", <T as Foo<_>>::foo(&t));
211 /// fn main() { foo(false); }
213 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
214 /// impl and the where-clause. We select the where-clause and unify $0=bool,
215 /// so the program prints "false". However, if the where-clause is omitted,
216 /// the blanket impl is selected, we unify $0=(), and the program prints
219 /// Exactly the same issues apply to projection and object candidates, except
220 /// that we can have both a projection candidate and a where-clause candidate
221 /// for the same obligation. In that case either would do (except that
222 /// different "leaps of logic" would occur if inference variables are
223 /// present), and we just pick the where-clause. This is, for example,
224 /// required for associated types to work in default impls, as the bounds
225 /// are visible both as projection bounds and as where-clauses from the
226 /// parameter environment.
227 #[derive(PartialEq,Eq,Debug,Clone)]
228 enum SelectionCandidate<'tcx> {
229 /// If has_nested is false, there are no *further* obligations
230 BuiltinCandidate { has_nested: bool },
231 ParamCandidate(ty::PolyTraitRef<'tcx>),
232 ImplCandidate(DefId),
233 AutoImplCandidate(DefId),
235 /// This is a trait matching with a projected type as `Self`, and
236 /// we found an applicable bound in the trait definition.
239 /// Implementation of a `Fn`-family trait by one of the anonymous types
240 /// generated for a `||` expression.
243 /// Implementation of a `Generator` trait by one of the anonymous types
244 /// generated for a generator.
247 /// Implementation of a `Fn`-family trait by one of the anonymous
248 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
253 BuiltinObjectCandidate,
255 BuiltinUnsizeCandidate,
258 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
259 type Lifted = SelectionCandidate<'tcx>;
260 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
262 BuiltinCandidate { has_nested } => {
267 ImplCandidate(def_id) => ImplCandidate(def_id),
268 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
269 ProjectionCandidate => ProjectionCandidate,
270 FnPointerCandidate => FnPointerCandidate,
271 ObjectCandidate => ObjectCandidate,
272 BuiltinObjectCandidate => BuiltinObjectCandidate,
273 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
274 ClosureCandidate => ClosureCandidate,
275 GeneratorCandidate => GeneratorCandidate,
277 ParamCandidate(ref trait_ref) => {
278 return tcx.lift(trait_ref).map(ParamCandidate);
284 struct SelectionCandidateSet<'tcx> {
285 // a list of candidates that definitely apply to the current
286 // obligation (meaning: types unify).
287 vec: Vec<SelectionCandidate<'tcx>>,
289 // if this is true, then there were candidates that might or might
290 // not have applied, but we couldn't tell. This occurs when some
291 // of the input types are type variables, in which case there are
292 // various "builtin" rules that might or might not trigger.
296 #[derive(PartialEq,Eq,Debug,Clone)]
297 struct EvaluatedCandidate<'tcx> {
298 candidate: SelectionCandidate<'tcx>,
299 evaluation: EvaluationResult,
302 /// When does the builtin impl for `T: Trait` apply?
303 enum BuiltinImplConditions<'tcx> {
304 /// The impl is conditional on T1,T2,.. : Trait
305 Where(ty::Binder<Vec<Ty<'tcx>>>),
306 /// There is no built-in impl. There may be some other
307 /// candidate (a where-clause or user-defined impl).
309 /// It is unknown whether there is an impl.
313 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
314 /// The result of trait evaluation. The order is important
315 /// here as the evaluation of a list is the maximum of the
318 /// The evaluation results are ordered:
319 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
320 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
321 /// - the "union" of evaluation results is equal to their maximum -
322 /// all the "potential success" candidates can potentially succeed,
323 /// so they are no-ops when unioned with a definite error, and within
324 /// the categories it's easy to see that the unions are correct.
325 pub enum EvaluationResult {
326 /// Evaluation successful
328 /// Evaluation is known to be ambiguous - it *might* hold for some
329 /// assignment of inference variables, but it might not.
331 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
332 /// know whether this obligation holds or not - it is the result we
333 /// would get with an empty stack, and therefore is cacheable.
335 /// Evaluation failed because of recursion involving inference
336 /// variables. We are somewhat imprecise there, so we don't actually
337 /// know the real result.
339 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
341 /// Evaluation failed because we encountered an obligation we are already
342 /// trying to prove on this branch.
344 /// We know this branch can't be a part of a minimal proof-tree for
345 /// the "root" of our cycle, because then we could cut out the recursion
346 /// and maintain a valid proof tree. However, this does not mean
347 /// that all the obligations on this branch do not hold - it's possible
348 /// that we entered this branch "speculatively", and that there
349 /// might be some other way to prove this obligation that does not
350 /// go through this cycle - so we can't cache this as a failure.
352 /// For example, suppose we have this:
354 /// ```rust,ignore (pseudo-Rust)
355 /// pub trait Trait { fn xyz(); }
356 /// // This impl is "useless", but we can still have
357 /// // an `impl Trait for SomeUnsizedType` somewhere.
358 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
360 /// pub fn foo<T: Trait + ?Sized>() {
361 /// <T as Trait>::xyz();
365 /// When checking `foo`, we have to prove `T: Trait`. This basically
366 /// translates into this:
369 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
372 /// When we try to prove it, we first go the first option, which
373 /// recurses. This shows us that the impl is "useless" - it won't
374 /// tell us that `T: Trait` unless it already implemented `Trait`
375 /// by some other means. However, that does not prevent `T: Trait`
376 /// does not hold, because of the bound (which can indeed be satisfied
377 /// by `SomeUnsizedType` from another crate).
379 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
380 /// ought to convert it to an `EvaluatedToErr`, because we know
381 /// there definitely isn't a proof tree for that obligation. Not
382 /// doing so is still sound - there isn't any proof tree, so the
383 /// branch still can't be a part of a minimal one - but does not
384 /// re-enable caching.
386 /// Evaluation failed
390 impl EvaluationResult {
391 pub fn may_apply(self) -> bool {
395 EvaluatedToUnknown => true,
398 EvaluatedToRecur => false
402 fn is_stack_dependent(self) -> bool {
405 EvaluatedToRecur => true,
409 EvaluatedToErr => false,
414 impl_stable_hash_for!(enum self::EvaluationResult {
422 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
423 /// Indicates that trait evaluation caused overflow.
424 pub struct OverflowError;
426 impl_stable_hash_for!(struct OverflowError { });
428 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
429 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
430 SelectionError::Overflow
435 pub struct EvaluationCache<'tcx> {
436 hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>
439 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
440 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
443 freshener: infcx.freshener(),
445 intercrate_ambiguity_causes: None,
446 allow_negative_impls: false,
447 query_mode: TraitQueryMode::Standard,
451 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
452 mode: IntercrateMode) -> SelectionContext<'cx, 'gcx, 'tcx> {
453 debug!("intercrate({:?})", mode);
456 freshener: infcx.freshener(),
457 intercrate: Some(mode),
458 intercrate_ambiguity_causes: None,
459 allow_negative_impls: false,
460 query_mode: TraitQueryMode::Standard,
464 pub fn with_negative(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
465 allow_negative_impls: bool) -> SelectionContext<'cx, 'gcx, 'tcx> {
466 debug!("with_negative({:?})", allow_negative_impls);
469 freshener: infcx.freshener(),
471 intercrate_ambiguity_causes: None,
472 allow_negative_impls,
473 query_mode: TraitQueryMode::Standard,
477 pub fn with_query_mode(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
478 query_mode: TraitQueryMode) -> SelectionContext<'cx, 'gcx, 'tcx> {
479 debug!("with_query_mode({:?})", query_mode);
482 freshener: infcx.freshener(),
484 intercrate_ambiguity_causes: None,
485 allow_negative_impls: false,
490 /// Enables tracking of intercrate ambiguity causes. These are
491 /// used in coherence to give improved diagnostics. We don't do
492 /// this until we detect a coherence error because it can lead to
493 /// false overflow results (#47139) and because it costs
494 /// computation time.
495 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
496 assert!(self.intercrate.is_some());
497 assert!(self.intercrate_ambiguity_causes.is_none());
498 self.intercrate_ambiguity_causes = Some(vec![]);
499 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
502 /// Gets the intercrate ambiguity causes collected since tracking
503 /// was enabled and disables tracking at the same time. If
504 /// tracking is not enabled, just returns an empty vector.
505 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
506 assert!(self.intercrate.is_some());
507 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
510 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
514 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
518 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
522 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
524 fn in_snapshot<R, F>(&mut self, f: F) -> R
525 where F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R
527 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
530 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
532 fn probe<R, F>(&mut self, f: F) -> R
533 where F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R
535 self.infcx.probe(|snapshot| f(self, snapshot))
538 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
539 /// the transaction fails and s.t. old obligations are retained.
540 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
541 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
543 self.infcx.commit_if_ok(|snapshot| f(self, snapshot))
547 ///////////////////////////////////////////////////////////////////////////
550 // The selection phase tries to identify *how* an obligation will
551 // be resolved. For example, it will identify which impl or
552 // parameter bound is to be used. The process can be inconclusive
553 // if the self type in the obligation is not fully inferred. Selection
554 // can result in an error in one of two ways:
556 // 1. If no applicable impl or parameter bound can be found.
557 // 2. If the output type parameters in the obligation do not match
558 // those specified by the impl/bound. For example, if the obligation
559 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
560 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
562 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
563 /// type environment by performing unification.
564 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
565 -> SelectionResult<'tcx, Selection<'tcx>> {
566 debug!("select({:?})", obligation);
567 debug_assert!(!obligation.predicate.has_escaping_regions());
569 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
571 let candidate = match self.candidate_from_obligation(&stack) {
572 Err(SelectionError::Overflow) => {
573 // In standard mode, overflow must have been caught and reported
575 assert!(self.query_mode == TraitQueryMode::Canonical);
576 return Err(SelectionError::Overflow);
578 Err(e) => { return Err(e); },
579 Ok(None) => { return Ok(None); },
580 Ok(Some(candidate)) => candidate
583 match self.confirm_candidate(obligation, candidate) {
584 Err(SelectionError::Overflow) => {
585 assert!(self.query_mode == TraitQueryMode::Canonical);
586 return Err(SelectionError::Overflow);
589 Ok(candidate) => Ok(Some(candidate))
593 ///////////////////////////////////////////////////////////////////////////
596 // Tests whether an obligation can be selected or whether an impl
597 // can be applied to particular types. It skips the "confirmation"
598 // step and hence completely ignores output type parameters.
600 // The result is "true" if the obligation *may* hold and "false" if
601 // we can be sure it does not.
603 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
604 pub fn predicate_may_hold_fatal(&mut self,
605 obligation: &PredicateObligation<'tcx>)
608 debug!("predicate_may_hold_fatal({:?})",
611 // This fatal query is a stopgap that should only be used in standard mode,
612 // where we do not expect overflow to be propagated.
613 assert!(self.query_mode == TraitQueryMode::Standard);
615 self.evaluate_obligation_recursively(obligation)
616 .expect("Overflow should be caught earlier in standard query mode")
620 /// Evaluates whether the obligation `obligation` can be satisfied and returns
621 /// an `EvaluationResult`.
622 pub fn evaluate_obligation_recursively(&mut self,
623 obligation: &PredicateObligation<'tcx>)
624 -> Result<EvaluationResult, OverflowError>
626 self.probe(|this, _| {
627 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
631 /// Evaluates the predicates in `predicates` recursively. Note that
632 /// this applies projections in the predicates, and therefore
633 /// is run within an inference probe.
634 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
635 stack: TraitObligationStackList<'o, 'tcx>,
637 -> Result<EvaluationResult, OverflowError>
638 where I : IntoIterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
640 let mut result = EvaluatedToOk;
641 for obligation in predicates {
642 let eval = self.evaluate_predicate_recursively(stack, obligation)?;
643 debug!("evaluate_predicate_recursively({:?}) = {:?}",
645 if let EvaluatedToErr = eval {
646 // fast-path - EvaluatedToErr is the top of the lattice,
647 // so we don't need to look on the other predicates.
648 return Ok(EvaluatedToErr);
650 result = cmp::max(result, eval);
656 fn evaluate_predicate_recursively<'o>(&mut self,
657 previous_stack: TraitObligationStackList<'o, 'tcx>,
658 obligation: &PredicateObligation<'tcx>)
659 -> Result<EvaluationResult, OverflowError>
661 debug!("evaluate_predicate_recursively({:?})",
664 match obligation.predicate {
665 ty::Predicate::Trait(ref t) => {
666 debug_assert!(!t.has_escaping_regions());
667 let obligation = obligation.with(t.clone());
668 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
671 ty::Predicate::Subtype(ref p) => {
672 // does this code ever run?
673 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
674 Some(Ok(InferOk { obligations, .. })) => {
675 self.evaluate_predicates_recursively(previous_stack, &obligations)
677 Some(Err(_)) => Ok(EvaluatedToErr),
678 None => Ok(EvaluatedToAmbig),
682 ty::Predicate::WellFormed(ty) => {
683 match ty::wf::obligations(self.infcx,
684 obligation.param_env,
685 obligation.cause.body_id,
686 ty, obligation.cause.span) {
688 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
690 Ok(EvaluatedToAmbig),
694 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
695 // we do not consider region relationships when
696 // evaluating trait matches
700 ty::Predicate::ObjectSafe(trait_def_id) => {
701 if self.tcx().is_object_safe(trait_def_id) {
708 ty::Predicate::Projection(ref data) => {
709 let project_obligation = obligation.with(data.clone());
710 match project::poly_project_and_unify_type(self, &project_obligation) {
711 Ok(Some(subobligations)) => {
712 let result = self.evaluate_predicates_recursively(previous_stack,
713 subobligations.iter());
715 ProjectionCacheKey::from_poly_projection_predicate(self, data)
717 self.infcx.projection_cache.borrow_mut().complete(key);
730 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
731 match self.infcx.closure_kind(closure_def_id, closure_substs) {
732 Some(closure_kind) => {
733 if closure_kind.extends(kind) {
745 ty::Predicate::ConstEvaluatable(def_id, substs) => {
746 let tcx = self.tcx();
747 match tcx.lift_to_global(&(obligation.param_env, substs)) {
748 Some((param_env, substs)) => {
749 let instance = ty::Instance::resolve(
755 if let Some(instance) = instance {
760 match self.tcx().const_eval(param_env.and(cid)) {
761 Ok(_) => Ok(EvaluatedToOk),
762 Err(_) => Ok(EvaluatedToErr)
769 // Inference variables still left in param_env or substs.
777 fn evaluate_trait_predicate_recursively<'o>(&mut self,
778 previous_stack: TraitObligationStackList<'o, 'tcx>,
779 mut obligation: TraitObligation<'tcx>)
780 -> Result<EvaluationResult, OverflowError>
782 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
784 if self.intercrate.is_none() && obligation.is_global()
785 && obligation.param_env.caller_bounds.iter().all(|bound| bound.needs_subst()) {
786 // If a param env has no global bounds, global obligations do not
787 // depend on its particular value in order to work, so we can clear
788 // out the param env and get better caching.
789 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
790 obligation.param_env = obligation.param_env.without_caller_bounds();
793 let stack = self.push_stack(previous_stack, &obligation);
794 let fresh_trait_ref = stack.fresh_trait_ref;
795 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
796 debug!("CACHE HIT: EVAL({:?})={:?}",
802 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
803 let result = result?;
805 debug!("CACHE MISS: EVAL({:?})={:?}",
808 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
813 fn evaluate_stack<'o>(&mut self,
814 stack: &TraitObligationStack<'o, 'tcx>)
815 -> Result<EvaluationResult, OverflowError>
817 // In intercrate mode, whenever any of the types are unbound,
818 // there can always be an impl. Even if there are no impls in
819 // this crate, perhaps the type would be unified with
820 // something from another crate that does provide an impl.
822 // In intra mode, we must still be conservative. The reason is
823 // that we want to avoid cycles. Imagine an impl like:
825 // impl<T:Eq> Eq for Vec<T>
827 // and a trait reference like `$0 : Eq` where `$0` is an
828 // unbound variable. When we evaluate this trait-reference, we
829 // will unify `$0` with `Vec<$1>` (for some fresh variable
830 // `$1`), on the condition that `$1 : Eq`. We will then wind
831 // up with many candidates (since that are other `Eq` impls
832 // that apply) and try to winnow things down. This results in
833 // a recursive evaluation that `$1 : Eq` -- as you can
834 // imagine, this is just where we started. To avoid that, we
835 // check for unbound variables and return an ambiguous (hence possible)
836 // match if we've seen this trait before.
838 // This suffices to allow chains like `FnMut` implemented in
839 // terms of `Fn` etc, but we could probably make this more
841 let unbound_input_types =
842 stack.fresh_trait_ref.skip_binder().input_types().any(|ty| ty.is_fresh());
843 // this check was an imperfect workaround for a bug n the old
844 // intercrate mode, it should be removed when that goes away.
845 if unbound_input_types &&
846 self.intercrate == Some(IntercrateMode::Issue43355)
848 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
849 stack.fresh_trait_ref);
850 // Heuristics: show the diagnostics when there are no candidates in crate.
851 if self.intercrate_ambiguity_causes.is_some() {
852 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
853 if let Ok(candidate_set) = self.assemble_candidates(stack) {
854 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
855 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
856 let self_ty = trait_ref.self_ty();
857 let cause = IntercrateAmbiguityCause::DownstreamCrate {
858 trait_desc: trait_ref.to_string(),
859 self_desc: if self_ty.has_concrete_skeleton() {
860 Some(self_ty.to_string())
865 debug!("evaluate_stack: pushing cause = {:?}", cause);
866 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
870 return Ok(EvaluatedToAmbig);
872 if unbound_input_types &&
873 stack.iter().skip(1).any(
874 |prev| stack.obligation.param_env == prev.obligation.param_env &&
875 self.match_fresh_trait_refs(&stack.fresh_trait_ref,
876 &prev.fresh_trait_ref))
878 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
879 stack.fresh_trait_ref);
880 return Ok(EvaluatedToUnknown);
883 // If there is any previous entry on the stack that precisely
884 // matches this obligation, then we can assume that the
885 // obligation is satisfied for now (still all other conditions
886 // must be met of course). One obvious case this comes up is
887 // marker traits like `Send`. Think of a linked list:
889 // struct List<T> { data: T, next: Option<Box<List<T>>> {
891 // `Box<List<T>>` will be `Send` if `T` is `Send` and
892 // `Option<Box<List<T>>>` is `Send`, and in turn
893 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
896 // Note that we do this comparison using the `fresh_trait_ref`
897 // fields. Because these have all been skolemized using
898 // `self.freshener`, we can be sure that (a) this will not
899 // affect the inferencer state and (b) that if we see two
900 // skolemized types with the same index, they refer to the
901 // same unbound type variable.
902 if let Some(rec_index) =
904 .skip(1) // skip top-most frame
905 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
906 stack.fresh_trait_ref == prev.fresh_trait_ref)
908 debug!("evaluate_stack({:?}) --> recursive",
909 stack.fresh_trait_ref);
910 let cycle = stack.iter().skip(1).take(rec_index+1);
911 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
912 if self.coinductive_match(cycle) {
913 debug!("evaluate_stack({:?}) --> recursive, coinductive",
914 stack.fresh_trait_ref);
915 return Ok(EvaluatedToOk);
917 debug!("evaluate_stack({:?}) --> recursive, inductive",
918 stack.fresh_trait_ref);
919 return Ok(EvaluatedToRecur);
923 match self.candidate_from_obligation(stack) {
924 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
925 Ok(None) => Ok(EvaluatedToAmbig),
926 Err(Overflow) => Err(OverflowError),
927 Err(..) => Ok(EvaluatedToErr)
931 /// For defaulted traits, we use a co-inductive strategy to solve, so
932 /// that recursion is ok. This routine returns true if the top of the
933 /// stack (`cycle[0]`):
935 /// - is a defaulted trait, and
936 /// - it also appears in the backtrace at some position `X`; and,
937 /// - all the predicates at positions `X..` between `X` an the top are
938 /// also defaulted traits.
939 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
940 where I: Iterator<Item=ty::Predicate<'tcx>>
942 let mut cycle = cycle;
943 cycle.all(|predicate| self.coinductive_predicate(predicate))
946 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
947 let result = match predicate {
948 ty::Predicate::Trait(ref data) => {
949 self.tcx().trait_is_auto(data.def_id())
955 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
959 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
960 /// obligations are met. Returns true if `candidate` remains viable after this further
962 fn evaluate_candidate<'o>(&mut self,
963 stack: &TraitObligationStack<'o, 'tcx>,
964 candidate: &SelectionCandidate<'tcx>)
965 -> Result<EvaluationResult, OverflowError>
967 debug!("evaluate_candidate: depth={} candidate={:?}",
968 stack.obligation.recursion_depth, candidate);
969 let result = self.probe(|this, _| {
970 let candidate = (*candidate).clone();
971 match this.confirm_candidate(stack.obligation, candidate) {
973 this.evaluate_predicates_recursively(
975 selection.nested_obligations().iter())
977 Err(..) => Ok(EvaluatedToErr)
980 debug!("evaluate_candidate: depth={} result={:?}",
981 stack.obligation.recursion_depth, result);
985 fn check_evaluation_cache(&self,
986 param_env: ty::ParamEnv<'tcx>,
987 trait_ref: ty::PolyTraitRef<'tcx>)
988 -> Option<EvaluationResult>
990 let tcx = self.tcx();
991 if self.can_use_global_caches(param_env) {
992 let cache = tcx.evaluation_cache.hashmap.borrow();
993 if let Some(cached) = cache.get(&trait_ref) {
994 return Some(cached.get(tcx));
997 self.infcx.evaluation_cache.hashmap
1000 .map(|v| v.get(tcx))
1003 fn insert_evaluation_cache(&mut self,
1004 param_env: ty::ParamEnv<'tcx>,
1005 trait_ref: ty::PolyTraitRef<'tcx>,
1006 dep_node: DepNodeIndex,
1007 result: EvaluationResult)
1009 // Avoid caching results that depend on more than just the trait-ref
1010 // - the stack can create recursion.
1011 if result.is_stack_dependent() {
1015 if self.can_use_global_caches(param_env) {
1016 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1018 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1022 // This may overwrite the cache with the same value
1023 // FIXME: Due to #50507 this overwrites the different values
1024 // This should be changed to use HashMapExt::insert_same
1025 // when that is fixed
1026 self.tcx().evaluation_cache
1027 .hashmap.borrow_mut()
1028 .insert(trait_ref, WithDepNode::new(dep_node, result));
1034 "insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
1038 self.infcx.evaluation_cache.hashmap
1040 .insert(trait_ref, WithDepNode::new(dep_node, result));
1043 ///////////////////////////////////////////////////////////////////////////
1044 // CANDIDATE ASSEMBLY
1046 // The selection process begins by examining all in-scope impls,
1047 // caller obligations, and so forth and assembling a list of
1048 // candidates. See [rustc guide] for more details.
1051 // https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1053 fn candidate_from_obligation<'o>(&mut self,
1054 stack: &TraitObligationStack<'o, 'tcx>)
1055 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1057 // Watch out for overflow. This intentionally bypasses (and does
1058 // not update) the cache.
1059 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1060 if stack.obligation.recursion_depth >= recursion_limit {
1061 match self.query_mode {
1062 TraitQueryMode::Standard => {
1063 self.infcx().report_overflow_error(&stack.obligation, true);
1065 TraitQueryMode::Canonical => {
1066 return Err(Overflow);
1071 // Check the cache. Note that we skolemize the trait-ref
1072 // separately rather than using `stack.fresh_trait_ref` -- this
1073 // is because we want the unbound variables to be replaced
1074 // with fresh skolemized types starting from index 0.
1075 let cache_fresh_trait_pred =
1076 self.infcx.freshen(stack.obligation.predicate.clone());
1077 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1078 cache_fresh_trait_pred,
1080 debug_assert!(!stack.obligation.predicate.has_escaping_regions());
1082 if let Some(c) = self.check_candidate_cache(stack.obligation.param_env,
1083 &cache_fresh_trait_pred) {
1084 debug!("CACHE HIT: SELECT({:?})={:?}",
1085 cache_fresh_trait_pred,
1090 // If no match, compute result and insert into cache.
1091 let (candidate, dep_node) = self.in_task(|this| {
1092 this.candidate_from_obligation_no_cache(stack)
1095 debug!("CACHE MISS: SELECT({:?})={:?}",
1096 cache_fresh_trait_pred, candidate);
1097 self.insert_candidate_cache(stack.obligation.param_env,
1098 cache_fresh_trait_pred,
1104 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1105 where OP: FnOnce(&mut Self) -> R
1107 let (result, dep_node) = self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || {
1110 self.tcx().dep_graph.read_index(dep_node);
1114 // Treat negative impls as unimplemented
1115 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
1116 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1117 if let ImplCandidate(def_id) = candidate {
1118 if !self.allow_negative_impls &&
1119 self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative {
1120 return Err(Unimplemented)
1126 fn candidate_from_obligation_no_cache<'o>(&mut self,
1127 stack: &TraitObligationStack<'o, 'tcx>)
1128 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
1130 if stack.obligation.predicate.references_error() {
1131 // If we encounter a `Error`, we generally prefer the
1132 // most "optimistic" result in response -- that is, the
1133 // one least likely to report downstream errors. But
1134 // because this routine is shared by coherence and by
1135 // trait selection, there isn't an obvious "right" choice
1136 // here in that respect, so we opt to just return
1137 // ambiguity and let the upstream clients sort it out.
1141 match self.is_knowable(stack) {
1144 debug!("coherence stage: not knowable");
1145 if self.intercrate_ambiguity_causes.is_some() {
1146 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1147 // Heuristics: show the diagnostics when there are no candidates in crate.
1148 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1149 let no_candidates_apply =
1153 .map(|c| self.evaluate_candidate(stack, &c))
1154 .collect::<Result<Vec<_>, OverflowError>>()?
1156 .all(|r| !r.may_apply());
1157 if !candidate_set.ambiguous && no_candidates_apply {
1158 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1159 let self_ty = trait_ref.self_ty();
1160 let trait_desc = trait_ref.to_string();
1161 let self_desc = if self_ty.has_concrete_skeleton() {
1162 Some(self_ty.to_string())
1166 let cause = if let Conflict::Upstream = conflict {
1167 IntercrateAmbiguityCause::UpstreamCrateUpdate {
1172 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1174 debug!("evaluate_stack: pushing cause = {:?}", cause);
1175 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1183 let candidate_set = self.assemble_candidates(stack)?;
1185 if candidate_set.ambiguous {
1186 debug!("candidate set contains ambig");
1190 let mut candidates = candidate_set.vec;
1192 debug!("assembled {} candidates for {:?}: {:?}",
1197 // At this point, we know that each of the entries in the
1198 // candidate set is *individually* applicable. Now we have to
1199 // figure out if they contain mutual incompatibilities. This
1200 // frequently arises if we have an unconstrained input type --
1201 // for example, we are looking for $0:Eq where $0 is some
1202 // unconstrained type variable. In that case, we'll get a
1203 // candidate which assumes $0 == int, one that assumes $0 ==
1204 // usize, etc. This spells an ambiguity.
1206 // If there is more than one candidate, first winnow them down
1207 // by considering extra conditions (nested obligations and so
1208 // forth). We don't winnow if there is exactly one
1209 // candidate. This is a relatively minor distinction but it
1210 // can lead to better inference and error-reporting. An
1211 // example would be if there was an impl:
1213 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1215 // and we were to see some code `foo.push_clone()` where `boo`
1216 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1217 // we were to winnow, we'd wind up with zero candidates.
1218 // Instead, we select the right impl now but report `Bar does
1219 // not implement Clone`.
1220 if candidates.len() == 1 {
1221 return self.filter_negative_impls(candidates.pop().unwrap());
1224 // Winnow, but record the exact outcome of evaluation, which
1225 // is needed for specialization. Propagate overflow if it occurs.
1226 let candidates: Result<Vec<Option<EvaluatedCandidate>>, _> = candidates
1228 .map(|c| match self.evaluate_candidate(stack, &c) {
1229 Ok(eval) if eval.may_apply() => Ok(Some(EvaluatedCandidate {
1234 Err(OverflowError) => Err(Overflow),
1238 let mut candidates: Vec<EvaluatedCandidate> =
1239 candidates?.into_iter().filter_map(|c| c).collect();
1241 debug!("winnowed to {} candidates for {:?}: {:?}",
1246 // If there are STILL multiple candidate, we can further
1247 // reduce the list by dropping duplicates -- including
1248 // resolving specializations.
1249 if candidates.len() > 1 {
1251 while i < candidates.len() {
1253 (0..candidates.len())
1254 .filter(|&j| i != j)
1255 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
1258 debug!("Dropping candidate #{}/{}: {:?}",
1259 i, candidates.len(), candidates[i]);
1260 candidates.swap_remove(i);
1262 debug!("Retaining candidate #{}/{}: {:?}",
1263 i, candidates.len(), candidates[i]);
1266 // If there are *STILL* multiple candidates, give up
1267 // and report ambiguity.
1269 debug!("multiple matches, ambig");
1276 // If there are *NO* candidates, then there are no impls --
1277 // that we know of, anyway. Note that in the case where there
1278 // are unbound type variables within the obligation, it might
1279 // be the case that you could still satisfy the obligation
1280 // from another crate by instantiating the type variables with
1281 // a type from another crate that does have an impl. This case
1282 // is checked for in `evaluate_stack` (and hence users
1283 // who might care about this case, like coherence, should use
1285 if candidates.is_empty() {
1286 return Err(Unimplemented);
1289 // Just one candidate left.
1290 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1293 fn is_knowable<'o>(&mut self,
1294 stack: &TraitObligationStack<'o, 'tcx>)
1297 debug!("is_knowable(intercrate={:?})", self.intercrate);
1299 if !self.intercrate.is_some() {
1303 let obligation = &stack.obligation;
1304 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1306 // ok to skip binder because of the nature of the
1307 // trait-ref-is-knowable check, which does not care about
1309 let trait_ref = predicate.skip_binder().trait_ref;
1311 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1312 if let (Some(Conflict::Downstream { used_to_be_broken: true }),
1313 Some(IntercrateMode::Issue43355)) = (result, self.intercrate) {
1314 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1321 /// Returns true if the global caches can be used.
1322 /// Do note that if the type itself is not in the
1323 /// global tcx, the local caches will be used.
1324 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1325 // If there are any where-clauses in scope, then we always use
1326 // a cache local to this particular scope. Otherwise, we
1327 // switch to a global cache. We used to try and draw
1328 // finer-grained distinctions, but that led to a serious of
1329 // annoying and weird bugs like #22019 and #18290. This simple
1330 // rule seems to be pretty clearly safe and also still retains
1331 // a very high hit rate (~95% when compiling rustc).
1332 if !param_env.caller_bounds.is_empty() {
1336 // Avoid using the master cache during coherence and just rely
1337 // on the local cache. This effectively disables caching
1338 // during coherence. It is really just a simplification to
1339 // avoid us having to fear that coherence results "pollute"
1340 // the master cache. Since coherence executes pretty quickly,
1341 // it's not worth going to more trouble to increase the
1342 // hit-rate I don't think.
1343 if self.intercrate.is_some() {
1347 // Otherwise, we can use the global cache.
1351 fn check_candidate_cache(&mut self,
1352 param_env: ty::ParamEnv<'tcx>,
1353 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1354 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1356 let tcx = self.tcx();
1357 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1358 if self.can_use_global_caches(param_env) {
1359 let cache = tcx.selection_cache.hashmap.borrow();
1360 if let Some(cached) = cache.get(&trait_ref) {
1361 return Some(cached.get(tcx));
1364 self.infcx.selection_cache.hashmap
1367 .map(|v| v.get(tcx))
1370 fn insert_candidate_cache(&mut self,
1371 param_env: ty::ParamEnv<'tcx>,
1372 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1373 dep_node: DepNodeIndex,
1374 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1376 let tcx = self.tcx();
1377 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1378 if self.can_use_global_caches(param_env) {
1379 if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1380 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1382 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1386 // This may overwrite the cache with the same value
1388 .hashmap.borrow_mut()
1389 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1396 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1400 self.infcx.selection_cache.hashmap
1402 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1405 fn assemble_candidates<'o>(&mut self,
1406 stack: &TraitObligationStack<'o, 'tcx>)
1407 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1409 let TraitObligationStack { obligation, .. } = *stack;
1410 let ref obligation = Obligation {
1411 param_env: obligation.param_env,
1412 cause: obligation.cause.clone(),
1413 recursion_depth: obligation.recursion_depth,
1414 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1417 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1418 // Self is a type variable (e.g. `_: AsRef<str>`).
1420 // This is somewhat problematic, as the current scheme can't really
1421 // handle it turning to be a projection. This does end up as truly
1422 // ambiguous in most cases anyway.
1424 // Take the fast path out - this also improves
1425 // performance by preventing assemble_candidates_from_impls from
1426 // matching every impl for this trait.
1427 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1430 let mut candidates = SelectionCandidateSet {
1435 // Other bounds. Consider both in-scope bounds from fn decl
1436 // and applicable impls. There is a certain set of precedence rules here.
1438 let def_id = obligation.predicate.def_id();
1439 let lang_items = self.tcx().lang_items();
1440 if lang_items.copy_trait() == Some(def_id) {
1441 debug!("obligation self ty is {:?}",
1442 obligation.predicate.skip_binder().self_ty());
1444 // User-defined copy impls are permitted, but only for
1445 // structs and enums.
1446 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1448 // For other types, we'll use the builtin rules.
1449 let copy_conditions = self.copy_clone_conditions(obligation);
1450 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1451 } else if lang_items.sized_trait() == Some(def_id) {
1452 // Sized is never implementable by end-users, it is
1453 // always automatically computed.
1454 let sized_conditions = self.sized_conditions(obligation);
1455 self.assemble_builtin_bound_candidates(sized_conditions,
1457 } else if lang_items.unsize_trait() == Some(def_id) {
1458 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1460 if lang_items.clone_trait() == Some(def_id) {
1461 // Same builtin conditions as `Copy`, i.e. every type which has builtin support
1462 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1463 // types have builtin support for `Clone`.
1464 let clone_conditions = self.copy_clone_conditions(obligation);
1465 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1468 self.assemble_generator_candidates(obligation, &mut candidates)?;
1469 self.assemble_closure_candidates(obligation, &mut candidates)?;
1470 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1471 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1472 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1475 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1476 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1477 // Auto implementations have lower priority, so we only
1478 // consider triggering a default if there is no other impl that can apply.
1479 if candidates.vec.is_empty() {
1480 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1482 debug!("candidate list size: {}", candidates.vec.len());
1486 fn assemble_candidates_from_projected_tys(&mut self,
1487 obligation: &TraitObligation<'tcx>,
1488 candidates: &mut SelectionCandidateSet<'tcx>)
1490 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1492 // before we go into the whole skolemization thing, just
1493 // quickly check if the self-type is a projection at all.
1494 match obligation.predicate.skip_binder().trait_ref.self_ty().sty {
1495 ty::Projection(_) | ty::Opaque(..) => {}
1496 ty::Infer(ty::TyVar(_)) => {
1497 span_bug!(obligation.cause.span,
1498 "Self=_ should have been handled by assemble_candidates");
1503 let result = self.probe(|this, snapshot| {
1504 this.match_projection_obligation_against_definition_bounds(obligation,
1509 candidates.vec.push(ProjectionCandidate);
1513 fn match_projection_obligation_against_definition_bounds(
1515 obligation: &TraitObligation<'tcx>,
1516 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
1519 let poly_trait_predicate =
1520 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1521 let (skol_trait_predicate, skol_map) =
1522 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate);
1523 debug!("match_projection_obligation_against_definition_bounds: \
1524 skol_trait_predicate={:?} skol_map={:?}",
1525 skol_trait_predicate,
1528 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1529 ty::Projection(ref data) =>
1530 (data.trait_ref(self.tcx()).def_id, data.substs),
1531 ty::Opaque(def_id, substs) => (def_id, substs),
1534 obligation.cause.span,
1535 "match_projection_obligation_against_definition_bounds() called \
1536 but self-ty not a projection: {:?}",
1537 skol_trait_predicate.trait_ref.self_ty());
1540 debug!("match_projection_obligation_against_definition_bounds: \
1541 def_id={:?}, substs={:?}",
1544 let predicates_of = self.tcx().predicates_of(def_id);
1545 let bounds = predicates_of.instantiate(self.tcx(), substs);
1546 debug!("match_projection_obligation_against_definition_bounds: \
1550 let matching_bound =
1551 util::elaborate_predicates(self.tcx(), bounds.predicates)
1555 |this, _| this.match_projection(obligation,
1557 skol_trait_predicate.trait_ref.clone(),
1561 debug!("match_projection_obligation_against_definition_bounds: \
1562 matching_bound={:?}",
1564 match matching_bound {
1567 // Repeat the successful match, if any, this time outside of a probe.
1568 let result = self.match_projection(obligation,
1570 skol_trait_predicate.trait_ref.clone(),
1574 self.infcx.pop_skolemized(skol_map, snapshot);
1582 fn match_projection(&mut self,
1583 obligation: &TraitObligation<'tcx>,
1584 trait_bound: ty::PolyTraitRef<'tcx>,
1585 skol_trait_ref: ty::TraitRef<'tcx>,
1586 skol_map: &infer::SkolemizationMap<'tcx>,
1587 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
1590 debug_assert!(!skol_trait_ref.has_escaping_regions());
1591 if self.infcx.at(&obligation.cause, obligation.param_env)
1592 .sup(ty::Binder::dummy(skol_trait_ref), trait_bound).is_err() {
1596 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1599 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1600 /// supplied to find out whether it is listed among them.
1602 /// Never affects inference environment.
1603 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1604 stack: &TraitObligationStack<'o, 'tcx>,
1605 candidates: &mut SelectionCandidateSet<'tcx>)
1606 -> Result<(),SelectionError<'tcx>>
1608 debug!("assemble_candidates_from_caller_bounds({:?})",
1612 stack.obligation.param_env.caller_bounds
1614 .filter_map(|o| o.to_opt_poly_trait_ref());
1616 // micro-optimization: filter out predicates relating to different
1618 let matching_bounds =
1619 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1621 // keep only those bounds which may apply, and propagate overflow if it occurs
1622 let mut param_candidates = vec![];
1623 for bound in matching_bounds {
1624 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1626 param_candidates.push(ParamCandidate(bound));
1630 candidates.vec.extend(param_candidates);
1635 fn evaluate_where_clause<'o>(&mut self,
1636 stack: &TraitObligationStack<'o, 'tcx>,
1637 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1638 -> Result<EvaluationResult, OverflowError>
1640 self.probe(move |this, _| {
1641 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1642 Ok(obligations) => {
1643 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1645 Err(()) => Ok(EvaluatedToErr)
1650 fn assemble_generator_candidates(&mut self,
1651 obligation: &TraitObligation<'tcx>,
1652 candidates: &mut SelectionCandidateSet<'tcx>)
1653 -> Result<(),SelectionError<'tcx>>
1655 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1659 // ok to skip binder because the substs on generator types never
1660 // touch bound regions, they just capture the in-scope
1661 // type/region parameters
1662 let self_ty = *obligation.self_ty().skip_binder();
1664 ty::Generator(..) => {
1665 debug!("assemble_generator_candidates: self_ty={:?} obligation={:?}",
1669 candidates.vec.push(GeneratorCandidate);
1672 ty::Infer(ty::TyVar(_)) => {
1673 debug!("assemble_generator_candidates: ambiguous self-type");
1674 candidates.ambiguous = true;
1677 _ => { return Ok(()); }
1681 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1682 /// FnMut<..>` where `X` is a closure type.
1684 /// Note: the type parameters on a closure candidate are modeled as *output* type
1685 /// parameters and hence do not affect whether this trait is a match or not. They will be
1686 /// unified during the confirmation step.
1687 fn assemble_closure_candidates(&mut self,
1688 obligation: &TraitObligation<'tcx>,
1689 candidates: &mut SelectionCandidateSet<'tcx>)
1690 -> Result<(),SelectionError<'tcx>>
1692 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()) {
1694 None => { return Ok(()); }
1697 // ok to skip binder because the substs on closure types never
1698 // touch bound regions, they just capture the in-scope
1699 // type/region parameters
1700 match obligation.self_ty().skip_binder().sty {
1701 ty::Closure(closure_def_id, closure_substs) => {
1702 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}",
1704 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1705 Some(closure_kind) => {
1706 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1707 if closure_kind.extends(kind) {
1708 candidates.vec.push(ClosureCandidate);
1712 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1713 candidates.vec.push(ClosureCandidate);
1718 ty::Infer(ty::TyVar(_)) => {
1719 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1720 candidates.ambiguous = true;
1723 _ => { return Ok(()); }
1727 /// Implement one of the `Fn()` family for a fn pointer.
1728 fn assemble_fn_pointer_candidates(&mut self,
1729 obligation: &TraitObligation<'tcx>,
1730 candidates: &mut SelectionCandidateSet<'tcx>)
1731 -> Result<(),SelectionError<'tcx>>
1733 // We provide impl of all fn traits for fn pointers.
1734 if self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()).is_none() {
1738 // ok to skip binder because what we are inspecting doesn't involve bound regions
1739 let self_ty = *obligation.self_ty().skip_binder();
1741 ty::Infer(ty::TyVar(_)) => {
1742 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1743 candidates.ambiguous = true; // could wind up being a fn() type
1746 // provide an impl, but only for suitable `fn` pointers
1747 ty::FnDef(..) | ty::FnPtr(_) => {
1749 unsafety: hir::Unsafety::Normal,
1753 } = self_ty.fn_sig(self.tcx()).skip_binder() {
1754 candidates.vec.push(FnPointerCandidate);
1764 /// Search for impls that might apply to `obligation`.
1765 fn assemble_candidates_from_impls(&mut self,
1766 obligation: &TraitObligation<'tcx>,
1767 candidates: &mut SelectionCandidateSet<'tcx>)
1768 -> Result<(), SelectionError<'tcx>>
1770 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1772 self.tcx().for_each_relevant_impl(
1773 obligation.predicate.def_id(),
1774 obligation.predicate.skip_binder().trait_ref.self_ty(),
1776 self.probe(|this, snapshot| { /* [1] */
1777 match this.match_impl(impl_def_id, obligation, snapshot) {
1779 candidates.vec.push(ImplCandidate(impl_def_id));
1781 // NB: we can safely drop the skol map
1782 // since we are in a probe [1]
1783 mem::drop(skol_map);
1794 fn assemble_candidates_from_auto_impls(&mut self,
1795 obligation: &TraitObligation<'tcx>,
1796 candidates: &mut SelectionCandidateSet<'tcx>)
1797 -> Result<(), SelectionError<'tcx>>
1799 // OK to skip binder here because the tests we do below do not involve bound regions
1800 let self_ty = *obligation.self_ty().skip_binder();
1801 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
1803 let def_id = obligation.predicate.def_id();
1805 if self.tcx().trait_is_auto(def_id) {
1807 ty::Dynamic(..) => {
1808 // For object types, we don't know what the closed
1809 // over types are. This means we conservatively
1810 // say nothing; a candidate may be added by
1811 // `assemble_candidates_from_object_ty`.
1813 ty::Foreign(..) => {
1814 // Since the contents of foreign types is unknown,
1815 // we don't add any `..` impl. Default traits could
1816 // still be provided by a manual implementation for
1817 // this trait and type.
1820 ty::Projection(..) => {
1821 // In these cases, we don't know what the actual
1822 // type is. Therefore, we cannot break it down
1823 // into its constituent types. So we don't
1824 // consider the `..` impl but instead just add no
1825 // candidates: this means that typeck will only
1826 // succeed if there is another reason to believe
1827 // that this obligation holds. That could be a
1828 // where-clause or, in the case of an object type,
1829 // it could be that the object type lists the
1830 // trait (e.g. `Foo+Send : Send`). See
1831 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1832 // for an example of a test case that exercises
1835 ty::Infer(ty::TyVar(_)) => {
1836 // the auto impl might apply, we don't know
1837 candidates.ambiguous = true;
1840 candidates.vec.push(AutoImplCandidate(def_id.clone()))
1848 /// Search for impls that might apply to `obligation`.
1849 fn assemble_candidates_from_object_ty(&mut self,
1850 obligation: &TraitObligation<'tcx>,
1851 candidates: &mut SelectionCandidateSet<'tcx>)
1853 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1854 obligation.self_ty().skip_binder());
1856 // Object-safety candidates are only applicable to object-safe
1857 // traits. Including this check is useful because it helps
1858 // inference in cases of traits like `BorrowFrom`, which are
1859 // not object-safe, and which rely on being able to infer the
1860 // self-type from one of the other inputs. Without this check,
1861 // these cases wind up being considered ambiguous due to a
1862 // (spurious) ambiguity introduced here.
1863 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1864 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1868 self.probe(|this, _snapshot| {
1869 // the code below doesn't care about regions, and the
1870 // self-ty here doesn't escape this probe, so just erase
1872 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1873 let poly_trait_ref = match self_ty.sty {
1874 ty::Dynamic(ref data, ..) => {
1875 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1876 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1877 pushing candidate");
1878 candidates.vec.push(BuiltinObjectCandidate);
1882 match data.principal() {
1883 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1887 ty::Infer(ty::TyVar(_)) => {
1888 debug!("assemble_candidates_from_object_ty: ambiguous");
1889 candidates.ambiguous = true; // could wind up being an object type
1897 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1900 // Count only those upcast versions that match the trait-ref
1901 // we are looking for. Specifically, do not only check for the
1902 // correct trait, but also the correct type parameters.
1903 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1904 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1905 let upcast_trait_refs =
1906 util::supertraits(this.tcx(), poly_trait_ref)
1907 .filter(|upcast_trait_ref| {
1908 this.probe(|this, _| {
1909 let upcast_trait_ref = upcast_trait_ref.clone();
1910 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1915 if upcast_trait_refs > 1 {
1916 // can be upcast in many ways; need more type information
1917 candidates.ambiguous = true;
1918 } else if upcast_trait_refs == 1 {
1919 candidates.vec.push(ObjectCandidate);
1924 /// Search for unsizing that might apply to `obligation`.
1925 fn assemble_candidates_for_unsizing(&mut self,
1926 obligation: &TraitObligation<'tcx>,
1927 candidates: &mut SelectionCandidateSet<'tcx>) {
1928 // We currently never consider higher-ranked obligations e.g.
1929 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1930 // because they are a priori invalid, and we could potentially add support
1931 // for them later, it's just that there isn't really a strong need for it.
1932 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1933 // impl, and those are generally applied to concrete types.
1935 // That said, one might try to write a fn with a where clause like
1936 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1937 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1938 // Still, you'd be more likely to write that where clause as
1940 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1941 // obligation above. Should be possible to extend this in the future.
1942 let source = match obligation.self_ty().no_late_bound_regions() {
1945 // Don't add any candidates if there are bound regions.
1949 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1951 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1954 let may_apply = match (&source.sty, &target.sty) {
1955 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1956 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
1957 // Upcasts permit two things:
1959 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1960 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1962 // Note that neither of these changes requires any
1963 // change at runtime. Eventually this will be
1966 // We always upcast when we can because of reason
1967 // #2 (region bounds).
1968 match (data_a.principal(), data_b.principal()) {
1969 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1970 data_b.auto_traits()
1971 // All of a's auto traits need to be in b's auto traits.
1972 .all(|b| data_a.auto_traits().any(|a| a == b)),
1978 (_, &ty::Dynamic(..)) => true,
1980 // Ambiguous handling is below T -> Trait, because inference
1981 // variables can still implement Unsize<Trait> and nested
1982 // obligations will have the final say (likely deferred).
1983 (&ty::Infer(ty::TyVar(_)), _) |
1984 (_, &ty::Infer(ty::TyVar(_))) => {
1985 debug!("assemble_candidates_for_unsizing: ambiguous");
1986 candidates.ambiguous = true;
1991 (&ty::Array(..), &ty::Slice(_)) => true,
1993 // Struct<T> -> Struct<U>.
1994 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
1995 def_id_a == def_id_b
1998 // (.., T) -> (.., U).
1999 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
2000 tys_a.len() == tys_b.len()
2007 candidates.vec.push(BuiltinUnsizeCandidate);
2011 ///////////////////////////////////////////////////////////////////////////
2014 // Winnowing is the process of attempting to resolve ambiguity by
2015 // probing further. During the winnowing process, we unify all
2016 // type variables (ignoring skolemization) and then we also
2017 // attempt to evaluate recursive bounds to see if they are
2020 /// Returns true if `victim` should be dropped in favor of
2021 /// `other`. Generally speaking we will drop duplicate
2022 /// candidates and prefer where-clause candidates.
2024 /// See the comment for "SelectionCandidate" for more details.
2025 fn candidate_should_be_dropped_in_favor_of<'o>(
2027 victim: &EvaluatedCandidate<'tcx>,
2028 other: &EvaluatedCandidate<'tcx>)
2031 // Check if a bound would previously have been removed when normalizing
2032 // the param_env so that it can be given the lowest priority. See
2033 // #50825 for the motivation for this.
2034 let is_global = |cand: &ty::PolyTraitRef<'_>| {
2035 cand.is_global() && !cand.has_late_bound_regions()
2038 if victim.candidate == other.candidate {
2042 match other.candidate {
2043 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2044 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2045 // lifetime of a variable.
2046 BuiltinCandidate { has_nested: false } => true,
2047 ParamCandidate(ref cand) => match victim.candidate {
2048 AutoImplCandidate(..) => {
2050 "default implementations shouldn't be recorded \
2051 when there are other valid candidates");
2053 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2054 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2055 // lifetime of a variable.
2056 BuiltinCandidate { has_nested: false } => false,
2059 GeneratorCandidate |
2060 FnPointerCandidate |
2061 BuiltinObjectCandidate |
2062 BuiltinUnsizeCandidate |
2063 BuiltinCandidate { .. } => {
2064 // Global bounds from the where clause should be ignored
2065 // here (see issue #50825). Otherwise, we have a where
2066 // clause so don't go around looking for impls.
2070 ProjectionCandidate => {
2071 // Arbitrarily give param candidates priority
2072 // over projection and object candidates.
2075 ParamCandidate(..) => false,
2078 ProjectionCandidate => match victim.candidate {
2079 AutoImplCandidate(..) => {
2081 "default implementations shouldn't be recorded \
2082 when there are other valid candidates");
2084 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2085 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2086 // lifetime of a variable.
2087 BuiltinCandidate { has_nested: false } => false,
2090 GeneratorCandidate |
2091 FnPointerCandidate |
2092 BuiltinObjectCandidate |
2093 BuiltinUnsizeCandidate |
2094 BuiltinCandidate { .. } => {
2098 ProjectionCandidate => {
2099 // Arbitrarily give param candidates priority
2100 // over projection and object candidates.
2103 ParamCandidate(ref cand) => is_global(cand),
2105 ImplCandidate(other_def) => {
2106 // See if we can toss out `victim` based on specialization.
2107 // This requires us to know *for sure* that the `other` impl applies
2108 // i.e. EvaluatedToOk:
2109 if other.evaluation == EvaluatedToOk {
2110 match victim.candidate {
2111 ImplCandidate(victim_def) => {
2112 let tcx = self.tcx().global_tcx();
2113 return tcx.specializes((other_def, victim_def)) ||
2114 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
2116 ParamCandidate(ref cand) => {
2117 // Prefer the impl to a global where clause candidate.
2118 return is_global(cand);
2127 GeneratorCandidate |
2128 FnPointerCandidate |
2129 BuiltinObjectCandidate |
2130 BuiltinUnsizeCandidate |
2131 BuiltinCandidate { has_nested: true } => {
2132 match victim.candidate {
2133 ParamCandidate(ref cand) => {
2134 // Prefer these to a global where-clause bound
2135 // (see issue #50825)
2136 is_global(cand) && other.evaluation == EvaluatedToOk
2145 ///////////////////////////////////////////////////////////////////////////
2148 // These cover the traits that are built-in to the language
2149 // itself: `Copy`, `Clone` and `Sized`.
2151 fn assemble_builtin_bound_candidates<'o>(&mut self,
2152 conditions: BuiltinImplConditions<'tcx>,
2153 candidates: &mut SelectionCandidateSet<'tcx>)
2154 -> Result<(),SelectionError<'tcx>>
2157 BuiltinImplConditions::Where(nested) => {
2158 debug!("builtin_bound: nested={:?}", nested);
2159 candidates.vec.push(BuiltinCandidate {
2160 has_nested: nested.skip_binder().len() > 0
2164 BuiltinImplConditions::None => { Ok(()) }
2165 BuiltinImplConditions::Ambiguous => {
2166 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2167 Ok(candidates.ambiguous = true)
2172 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2173 -> BuiltinImplConditions<'tcx>
2175 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2177 // NOTE: binder moved to (*)
2178 let self_ty = self.infcx.shallow_resolve(
2179 obligation.predicate.skip_binder().self_ty());
2182 ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
2183 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
2184 ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
2185 ty::Char | ty::Ref(..) | ty::Generator(..) |
2186 ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
2187 ty::Never | ty::Error => {
2188 // safe for everything
2189 Where(ty::Binder::dummy(Vec::new()))
2192 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2195 Where(ty::Binder::bind(tys.last().into_iter().cloned().collect()))
2198 ty::Adt(def, substs) => {
2199 let sized_crit = def.sized_constraint(self.tcx());
2200 // (*) binder moved here
2201 Where(ty::Binder::bind(
2202 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
2206 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2207 ty::Infer(ty::TyVar(_)) => Ambiguous,
2209 ty::Infer(ty::CanonicalTy(_)) |
2210 ty::Infer(ty::FreshTy(_)) |
2211 ty::Infer(ty::FreshIntTy(_)) |
2212 ty::Infer(ty::FreshFloatTy(_)) => {
2213 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2219 fn copy_clone_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2220 -> BuiltinImplConditions<'tcx>
2222 // NOTE: binder moved to (*)
2223 let self_ty = self.infcx.shallow_resolve(
2224 obligation.predicate.skip_binder().self_ty());
2226 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2229 ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
2230 ty::FnDef(..) | ty::FnPtr(_) | ty::Error => {
2231 Where(ty::Binder::dummy(Vec::new()))
2234 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
2235 ty::Char | ty::RawPtr(..) | ty::Never |
2236 ty::Ref(_, _, hir::MutImmutable) => {
2237 // Implementations provided in libcore
2241 ty::Dynamic(..) | ty::Str | ty::Slice(..) |
2242 ty::Generator(..) | ty::GeneratorWitness(..) | ty::Foreign(..) |
2243 ty::Ref(_, _, hir::MutMutable) => {
2247 ty::Array(element_ty, _) => {
2248 // (*) binder moved here
2249 Where(ty::Binder::bind(vec![element_ty]))
2253 // (*) binder moved here
2254 Where(ty::Binder::bind(tys.to_vec()))
2257 ty::Closure(def_id, substs) => {
2258 let trait_id = obligation.predicate.def_id();
2259 let is_copy_trait = Some(trait_id) == self.tcx().lang_items().copy_trait();
2260 let is_clone_trait = Some(trait_id) == self.tcx().lang_items().clone_trait();
2261 if is_copy_trait || is_clone_trait {
2262 Where(ty::Binder::bind(substs.upvar_tys(def_id, self.tcx()).collect()))
2268 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2269 // Fallback to whatever user-defined impls exist in this case.
2273 ty::Infer(ty::TyVar(_)) => {
2274 // Unbound type variable. Might or might not have
2275 // applicable impls and so forth, depending on what
2276 // those type variables wind up being bound to.
2280 ty::Infer(ty::CanonicalTy(_)) |
2281 ty::Infer(ty::FreshTy(_)) |
2282 ty::Infer(ty::FreshIntTy(_)) |
2283 ty::Infer(ty::FreshFloatTy(_)) => {
2284 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2290 /// For default impls, we need to break apart a type into its
2291 /// "constituent types" -- meaning, the types that it contains.
2293 /// Here are some (simple) examples:
2296 /// (i32, u32) -> [i32, u32]
2297 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2298 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2299 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2301 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2311 ty::Infer(ty::IntVar(_)) |
2312 ty::Infer(ty::FloatVar(_)) |
2321 ty::Projection(..) |
2322 ty::Infer(ty::CanonicalTy(_)) |
2323 ty::Infer(ty::TyVar(_)) |
2324 ty::Infer(ty::FreshTy(_)) |
2325 ty::Infer(ty::FreshIntTy(_)) |
2326 ty::Infer(ty::FreshFloatTy(_)) => {
2327 bug!("asked to assemble constituent types of unexpected type: {:?}",
2331 ty::RawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
2332 ty::Ref(_, element_ty, _) => {
2336 ty::Array(element_ty, _) | ty::Slice(element_ty) => {
2340 ty::Tuple(ref tys) => {
2341 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2345 ty::Closure(def_id, ref substs) => {
2346 substs.upvar_tys(def_id, self.tcx()).collect()
2349 ty::Generator(def_id, ref substs, _) => {
2350 let witness = substs.witness(def_id, self.tcx());
2351 substs.upvar_tys(def_id, self.tcx()).chain(iter::once(witness)).collect()
2354 ty::GeneratorWitness(types) => {
2355 // This is sound because no regions in the witness can refer to
2356 // the binder outside the witness. So we'll effectivly reuse
2357 // the implicit binder around the witness.
2358 types.skip_binder().to_vec()
2361 // for `PhantomData<T>`, we pass `T`
2362 ty::Adt(def, substs) if def.is_phantom_data() => {
2363 substs.types().collect()
2366 ty::Adt(def, substs) => {
2368 .map(|f| f.ty(self.tcx(), substs))
2372 ty::Opaque(def_id, substs) => {
2373 // We can resolve the `impl Trait` to its concrete type,
2374 // which enforces a DAG between the functions requiring
2375 // the auto trait bounds in question.
2376 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2381 fn collect_predicates_for_types(&mut self,
2382 param_env: ty::ParamEnv<'tcx>,
2383 cause: ObligationCause<'tcx>,
2384 recursion_depth: usize,
2385 trait_def_id: DefId,
2386 types: ty::Binder<Vec<Ty<'tcx>>>)
2387 -> Vec<PredicateObligation<'tcx>>
2389 // Because the types were potentially derived from
2390 // higher-ranked obligations they may reference late-bound
2391 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2392 // yield a type like `for<'a> &'a int`. In general, we
2393 // maintain the invariant that we never manipulate bound
2394 // regions, so we have to process these bound regions somehow.
2396 // The strategy is to:
2398 // 1. Instantiate those regions to skolemized regions (e.g.,
2399 // `for<'a> &'a int` becomes `&0 int`.
2400 // 2. Produce something like `&'0 int : Copy`
2401 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2403 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
2404 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2406 self.in_snapshot(|this, snapshot| {
2407 let (skol_ty, skol_map) =
2408 this.infcx().skolemize_late_bound_regions(&ty);
2409 let Normalized { value: normalized_ty, mut obligations } =
2410 project::normalize_with_depth(this,
2415 let skol_obligation =
2416 this.tcx().predicate_for_trait_def(param_env,
2422 obligations.push(skol_obligation);
2423 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2428 ///////////////////////////////////////////////////////////////////////////
2431 // Confirmation unifies the output type parameters of the trait
2432 // with the values found in the obligation, possibly yielding a
2433 // type error. See [rustc guide] for more details.
2436 // https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#confirmation
2438 fn confirm_candidate(&mut self,
2439 obligation: &TraitObligation<'tcx>,
2440 candidate: SelectionCandidate<'tcx>)
2441 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2443 debug!("confirm_candidate({:?}, {:?})",
2448 BuiltinCandidate { has_nested } => {
2449 let data = self.confirm_builtin_candidate(obligation, has_nested);
2450 Ok(VtableBuiltin(data))
2453 ParamCandidate(param) => {
2454 let obligations = self.confirm_param_candidate(obligation, param);
2455 Ok(VtableParam(obligations))
2458 AutoImplCandidate(trait_def_id) => {
2459 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2460 Ok(VtableAutoImpl(data))
2463 ImplCandidate(impl_def_id) => {
2464 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2467 ClosureCandidate => {
2468 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2469 Ok(VtableClosure(vtable_closure))
2472 GeneratorCandidate => {
2473 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2474 Ok(VtableGenerator(vtable_generator))
2477 BuiltinObjectCandidate => {
2478 // This indicates something like `(Trait+Send) :
2479 // Send`. In this case, we know that this holds
2480 // because that's what the object type is telling us,
2481 // and there's really no additional obligations to
2482 // prove and no types in particular to unify etc.
2483 Ok(VtableParam(Vec::new()))
2486 ObjectCandidate => {
2487 let data = self.confirm_object_candidate(obligation);
2488 Ok(VtableObject(data))
2491 FnPointerCandidate => {
2493 self.confirm_fn_pointer_candidate(obligation)?;
2494 Ok(VtableFnPointer(data))
2497 ProjectionCandidate => {
2498 self.confirm_projection_candidate(obligation);
2499 Ok(VtableParam(Vec::new()))
2502 BuiltinUnsizeCandidate => {
2503 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2504 Ok(VtableBuiltin(data))
2509 fn confirm_projection_candidate(&mut self,
2510 obligation: &TraitObligation<'tcx>)
2512 self.in_snapshot(|this, snapshot| {
2514 this.match_projection_obligation_against_definition_bounds(obligation,
2520 fn confirm_param_candidate(&mut self,
2521 obligation: &TraitObligation<'tcx>,
2522 param: ty::PolyTraitRef<'tcx>)
2523 -> Vec<PredicateObligation<'tcx>>
2525 debug!("confirm_param_candidate({:?},{:?})",
2529 // During evaluation, we already checked that this
2530 // where-clause trait-ref could be unified with the obligation
2531 // trait-ref. Repeat that unification now without any
2532 // transactional boundary; it should not fail.
2533 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2534 Ok(obligations) => obligations,
2536 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2543 fn confirm_builtin_candidate(&mut self,
2544 obligation: &TraitObligation<'tcx>,
2546 -> VtableBuiltinData<PredicateObligation<'tcx>>
2548 debug!("confirm_builtin_candidate({:?}, {:?})",
2549 obligation, has_nested);
2551 let lang_items = self.tcx().lang_items();
2552 let obligations = if has_nested {
2553 let trait_def = obligation.predicate.def_id();
2554 let conditions = match trait_def {
2555 _ if Some(trait_def) == lang_items.sized_trait() => {
2556 self.sized_conditions(obligation)
2558 _ if Some(trait_def) == lang_items.copy_trait() => {
2559 self.copy_clone_conditions(obligation)
2561 _ if Some(trait_def) == lang_items.clone_trait() => {
2562 self.copy_clone_conditions(obligation)
2564 _ => bug!("unexpected builtin trait {:?}", trait_def)
2566 let nested = match conditions {
2567 BuiltinImplConditions::Where(nested) => nested,
2568 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2572 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2573 self.collect_predicates_for_types(obligation.param_env,
2575 obligation.recursion_depth+1,
2582 debug!("confirm_builtin_candidate: obligations={:?}",
2585 VtableBuiltinData { nested: obligations }
2588 /// This handles the case where a `auto trait Foo` impl is being used.
2589 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2591 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2592 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2593 fn confirm_auto_impl_candidate(&mut self,
2594 obligation: &TraitObligation<'tcx>,
2595 trait_def_id: DefId)
2596 -> VtableAutoImplData<PredicateObligation<'tcx>>
2598 debug!("confirm_auto_impl_candidate({:?}, {:?})",
2602 let types = obligation.predicate.map_bound(|inner| {
2603 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2604 self.constituent_types_for_ty(self_ty)
2606 self.vtable_auto_impl(obligation, trait_def_id, types)
2609 /// See `confirm_auto_impl_candidate`
2610 fn vtable_auto_impl(&mut self,
2611 obligation: &TraitObligation<'tcx>,
2612 trait_def_id: DefId,
2613 nested: ty::Binder<Vec<Ty<'tcx>>>)
2614 -> VtableAutoImplData<PredicateObligation<'tcx>>
2616 debug!("vtable_auto_impl: nested={:?}", nested);
2618 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2619 let mut obligations = self.collect_predicates_for_types(
2620 obligation.param_env,
2622 obligation.recursion_depth+1,
2626 let trait_obligations = self.in_snapshot(|this, snapshot| {
2627 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2628 let (trait_ref, skol_map) =
2629 this.infcx().skolemize_late_bound_regions(&poly_trait_ref);
2630 let cause = obligation.derived_cause(ImplDerivedObligation);
2631 this.impl_or_trait_obligations(cause,
2632 obligation.recursion_depth + 1,
2633 obligation.param_env,
2640 obligations.extend(trait_obligations);
2642 debug!("vtable_auto_impl: obligations={:?}", obligations);
2644 VtableAutoImplData {
2650 fn confirm_impl_candidate(&mut self,
2651 obligation: &TraitObligation<'tcx>,
2653 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2655 debug!("confirm_impl_candidate({:?},{:?})",
2659 // First, create the substitutions by matching the impl again,
2660 // this time not in a probe.
2661 self.in_snapshot(|this, snapshot| {
2662 let (substs, skol_map) =
2663 this.rematch_impl(impl_def_id, obligation,
2665 debug!("confirm_impl_candidate substs={:?}", substs);
2666 let cause = obligation.derived_cause(ImplDerivedObligation);
2667 this.vtable_impl(impl_def_id,
2670 obligation.recursion_depth + 1,
2671 obligation.param_env,
2677 fn vtable_impl(&mut self,
2679 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2680 cause: ObligationCause<'tcx>,
2681 recursion_depth: usize,
2682 param_env: ty::ParamEnv<'tcx>,
2683 skol_map: infer::SkolemizationMap<'tcx>,
2684 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
2685 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2687 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2693 let mut impl_obligations =
2694 self.impl_or_trait_obligations(cause,
2702 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2706 // Because of RFC447, the impl-trait-ref and obligations
2707 // are sufficient to determine the impl substs, without
2708 // relying on projections in the impl-trait-ref.
2710 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2711 impl_obligations.append(&mut substs.obligations);
2713 VtableImplData { impl_def_id,
2714 substs: substs.value,
2715 nested: impl_obligations }
2718 fn confirm_object_candidate(&mut self,
2719 obligation: &TraitObligation<'tcx>)
2720 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2722 debug!("confirm_object_candidate({:?})",
2725 // FIXME skipping binder here seems wrong -- we should
2726 // probably flatten the binder from the obligation and the
2727 // binder from the object. Have to try to make a broken test
2728 // case that results. -nmatsakis
2729 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2730 let poly_trait_ref = match self_ty.sty {
2731 ty::Dynamic(ref data, ..) => {
2732 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2735 span_bug!(obligation.cause.span,
2736 "object candidate with non-object");
2740 let mut upcast_trait_ref = None;
2741 let mut nested = vec![];
2745 let tcx = self.tcx();
2747 // We want to find the first supertrait in the list of
2748 // supertraits that we can unify with, and do that
2749 // unification. We know that there is exactly one in the list
2750 // where we can unify because otherwise select would have
2751 // reported an ambiguity. (When we do find a match, also
2752 // record it for later.)
2754 util::supertraits(tcx, poly_trait_ref)
2758 |this, _| this.match_poly_trait_ref(obligation, t))
2760 Ok(obligations) => {
2761 upcast_trait_ref = Some(t);
2762 nested.extend(obligations);
2769 // Additionally, for each of the nonmatching predicates that
2770 // we pass over, we sum up the set of number of vtable
2771 // entries, so that we can compute the offset for the selected
2774 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2780 upcast_trait_ref: upcast_trait_ref.unwrap(),
2786 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2787 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2789 debug!("confirm_fn_pointer_candidate({:?})",
2792 // ok to skip binder; it is reintroduced below
2793 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2794 let sig = self_ty.fn_sig(self.tcx());
2796 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2799 util::TupleArgumentsFlag::Yes)
2800 .map_bound(|(trait_ref, _)| trait_ref);
2802 let Normalized { value: trait_ref, obligations } =
2803 project::normalize_with_depth(self,
2804 obligation.param_env,
2805 obligation.cause.clone(),
2806 obligation.recursion_depth + 1,
2809 self.confirm_poly_trait_refs(obligation.cause.clone(),
2810 obligation.param_env,
2811 obligation.predicate.to_poly_trait_ref(),
2813 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2816 fn confirm_generator_candidate(&mut self,
2817 obligation: &TraitObligation<'tcx>)
2818 -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
2819 SelectionError<'tcx>>
2821 // ok to skip binder because the substs on generator types never
2822 // touch bound regions, they just capture the in-scope
2823 // type/region parameters
2824 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2825 let (generator_def_id, substs) = match self_ty.sty {
2826 ty::Generator(id, substs, _) => (id, substs),
2827 _ => bug!("closure candidate for non-closure {:?}", obligation)
2830 debug!("confirm_generator_candidate({:?},{:?},{:?})",
2836 self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
2840 } = normalize_with_depth(self,
2841 obligation.param_env,
2842 obligation.cause.clone(),
2843 obligation.recursion_depth+1,
2846 debug!("confirm_generator_candidate(generator_def_id={:?}, \
2847 trait_ref={:?}, obligations={:?})",
2853 self.confirm_poly_trait_refs(obligation.cause.clone(),
2854 obligation.param_env,
2855 obligation.predicate.to_poly_trait_ref(),
2858 Ok(VtableGeneratorData {
2859 generator_def_id: generator_def_id,
2860 substs: substs.clone(),
2865 fn confirm_closure_candidate(&mut self,
2866 obligation: &TraitObligation<'tcx>)
2867 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2868 SelectionError<'tcx>>
2870 debug!("confirm_closure_candidate({:?})", obligation);
2872 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()) {
2874 None => bug!("closure candidate for non-fn trait {:?}", obligation)
2877 // ok to skip binder because the substs on closure types never
2878 // touch bound regions, they just capture the in-scope
2879 // type/region parameters
2880 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2881 let (closure_def_id, substs) = match self_ty.sty {
2882 ty::Closure(id, substs) => (id, substs),
2883 _ => bug!("closure candidate for non-closure {:?}", obligation)
2887 self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
2891 } = normalize_with_depth(self,
2892 obligation.param_env,
2893 obligation.cause.clone(),
2894 obligation.recursion_depth+1,
2897 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2903 self.confirm_poly_trait_refs(obligation.cause.clone(),
2904 obligation.param_env,
2905 obligation.predicate.to_poly_trait_ref(),
2908 obligations.push(Obligation::new(
2909 obligation.cause.clone(),
2910 obligation.param_env,
2911 ty::Predicate::ClosureKind(closure_def_id, substs, kind)));
2913 Ok(VtableClosureData {
2915 substs: substs.clone(),
2920 /// In the case of closure types and fn pointers,
2921 /// we currently treat the input type parameters on the trait as
2922 /// outputs. This means that when we have a match we have only
2923 /// considered the self type, so we have to go back and make sure
2924 /// to relate the argument types too. This is kind of wrong, but
2925 /// since we control the full set of impls, also not that wrong,
2926 /// and it DOES yield better error messages (since we don't report
2927 /// errors as if there is no applicable impl, but rather report
2928 /// errors are about mismatched argument types.
2930 /// Here is an example. Imagine we have a closure expression
2931 /// and we desugared it so that the type of the expression is
2932 /// `Closure`, and `Closure` expects an int as argument. Then it
2933 /// is "as if" the compiler generated this impl:
2935 /// impl Fn(int) for Closure { ... }
2937 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2938 /// we have matched the self-type `Closure`. At this point we'll
2939 /// compare the `int` to `usize` and generate an error.
2941 /// Note that this checking occurs *after* the impl has selected,
2942 /// because these output type parameters should not affect the
2943 /// selection of the impl. Therefore, if there is a mismatch, we
2944 /// report an error to the user.
2945 fn confirm_poly_trait_refs(&mut self,
2946 obligation_cause: ObligationCause<'tcx>,
2947 obligation_param_env: ty::ParamEnv<'tcx>,
2948 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2949 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2950 -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>>
2952 let obligation_trait_ref = obligation_trait_ref.clone();
2954 .at(&obligation_cause, obligation_param_env)
2955 .sup(obligation_trait_ref, expected_trait_ref)
2956 .map(|InferOk { obligations, .. }| obligations)
2957 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2960 fn confirm_builtin_unsize_candidate(&mut self,
2961 obligation: &TraitObligation<'tcx>,)
2962 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>>
2964 let tcx = self.tcx();
2966 // assemble_candidates_for_unsizing should ensure there are no late bound
2967 // regions here. See the comment there for more details.
2968 let source = self.infcx.shallow_resolve(
2969 obligation.self_ty().no_late_bound_regions().unwrap());
2970 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2971 let target = self.infcx.shallow_resolve(target);
2973 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2976 let mut nested = vec![];
2977 match (&source.sty, &target.sty) {
2978 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2979 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
2980 // See assemble_candidates_for_unsizing for more info.
2981 let existential_predicates = data_a.map_bound(|data_a| {
2982 let principal = data_a.principal();
2983 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2984 .chain(data_a.projection_bounds()
2985 .map(|x| ty::ExistentialPredicate::Projection(x)))
2986 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2987 tcx.mk_existential_predicates(iter)
2989 let new_trait = tcx.mk_dynamic(existential_predicates, r_b);
2990 let InferOk { obligations, .. } =
2991 self.infcx.at(&obligation.cause, obligation.param_env)
2992 .eq(target, new_trait)
2993 .map_err(|_| Unimplemented)?;
2994 nested.extend(obligations);
2996 // Register one obligation for 'a: 'b.
2997 let cause = ObligationCause::new(obligation.cause.span,
2998 obligation.cause.body_id,
2999 ObjectCastObligation(target));
3000 let outlives = ty::OutlivesPredicate(r_a, r_b);
3001 nested.push(Obligation::with_depth(cause,
3002 obligation.recursion_depth + 1,
3003 obligation.param_env,
3004 ty::Binder::bind(outlives).to_predicate()));
3008 (_, &ty::Dynamic(ref data, r)) => {
3009 let mut object_dids =
3010 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
3011 if let Some(did) = object_dids.find(|did| {
3012 !tcx.is_object_safe(*did)
3014 return Err(TraitNotObjectSafe(did))
3017 let cause = ObligationCause::new(obligation.cause.span,
3018 obligation.cause.body_id,
3019 ObjectCastObligation(target));
3020 let mut push = |predicate| {
3021 nested.push(Obligation::with_depth(cause.clone(),
3022 obligation.recursion_depth + 1,
3023 obligation.param_env,
3027 // Create obligations:
3028 // - Casting T to Trait
3029 // - For all the various builtin bounds attached to the object cast. (In other
3030 // words, if the object type is Foo+Send, this would create an obligation for the
3032 // - Projection predicates
3033 for predicate in data.iter() {
3034 push(predicate.with_self_ty(tcx, source));
3037 // We can only make objects from sized types.
3038 let tr = ty::TraitRef {
3039 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
3040 substs: tcx.mk_substs_trait(source, &[]),
3042 push(tr.to_predicate());
3044 // If the type is `Foo+'a`, ensures that the type
3045 // being cast to `Foo+'a` outlives `'a`:
3046 let outlives = ty::OutlivesPredicate(source, r);
3047 push(ty::Binder::dummy(outlives).to_predicate());
3051 (&ty::Array(a, _), &ty::Slice(b)) => {
3052 let InferOk { obligations, .. } =
3053 self.infcx.at(&obligation.cause, obligation.param_env)
3055 .map_err(|_| Unimplemented)?;
3056 nested.extend(obligations);
3059 // Struct<T> -> Struct<U>.
3060 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3063 .map(|f| tcx.type_of(f.did))
3064 .collect::<Vec<_>>();
3066 // The last field of the structure has to exist and contain type parameters.
3067 let field = if let Some(&field) = fields.last() {
3070 return Err(Unimplemented);
3072 let mut ty_params = BitSet::new_empty(substs_a.types().count());
3073 let mut found = false;
3074 for ty in field.walk() {
3075 if let ty::Param(p) = ty.sty {
3076 ty_params.insert(p.idx as usize);
3081 return Err(Unimplemented);
3084 // Replace type parameters used in unsizing with
3085 // Error and ensure they do not affect any other fields.
3086 // This could be checked after type collection for any struct
3087 // with a potentially unsized trailing field.
3088 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3089 if ty_params.contains(i) {
3090 tcx.types.err.into()
3095 let substs = tcx.mk_substs(params);
3096 for &ty in fields.split_last().unwrap().1 {
3097 if ty.subst(tcx, substs).references_error() {
3098 return Err(Unimplemented);
3102 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3103 let inner_source = field.subst(tcx, substs_a);
3104 let inner_target = field.subst(tcx, substs_b);
3106 // Check that the source struct with the target's
3107 // unsized parameters is equal to the target.
3108 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3109 if ty_params.contains(i) {
3110 substs_b.type_at(i).into()
3115 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3116 let InferOk { obligations, .. } =
3117 self.infcx.at(&obligation.cause, obligation.param_env)
3118 .eq(target, new_struct)
3119 .map_err(|_| Unimplemented)?;
3120 nested.extend(obligations);
3122 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3123 nested.push(tcx.predicate_for_trait_def(
3124 obligation.param_env,
3125 obligation.cause.clone(),
3126 obligation.predicate.def_id(),
3127 obligation.recursion_depth + 1,
3129 &[inner_target.into()]));
3132 // (.., T) -> (.., U).
3133 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3134 assert_eq!(tys_a.len(), tys_b.len());
3136 // The last field of the tuple has to exist.
3137 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3140 return Err(Unimplemented);
3142 let &b_last = tys_b.last().unwrap();
3144 // Check that the source tuple with the target's
3145 // last element is equal to the target.
3146 let new_tuple = tcx.mk_tup(a_mid.iter().cloned().chain(iter::once(b_last)));
3147 let InferOk { obligations, .. } =
3148 self.infcx.at(&obligation.cause, obligation.param_env)
3149 .eq(target, new_tuple)
3150 .map_err(|_| Unimplemented)?;
3151 nested.extend(obligations);
3153 // Construct the nested T: Unsize<U> predicate.
3154 nested.push(tcx.predicate_for_trait_def(
3155 obligation.param_env,
3156 obligation.cause.clone(),
3157 obligation.predicate.def_id(),
3158 obligation.recursion_depth + 1,
3166 Ok(VtableBuiltinData { nested: nested })
3169 ///////////////////////////////////////////////////////////////////////////
3172 // Matching is a common path used for both evaluation and
3173 // confirmation. It basically unifies types that appear in impls
3174 // and traits. This does affect the surrounding environment;
3175 // therefore, when used during evaluation, match routines must be
3176 // run inside of a `probe()` so that their side-effects are
3179 fn rematch_impl(&mut self,
3181 obligation: &TraitObligation<'tcx>,
3182 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
3183 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
3184 infer::SkolemizationMap<'tcx>)
3186 match self.match_impl(impl_def_id, obligation, snapshot) {
3187 Ok((substs, skol_map)) => (substs, skol_map),
3189 bug!("Impl {:?} was matchable against {:?} but now is not",
3196 fn match_impl(&mut self,
3198 obligation: &TraitObligation<'tcx>,
3199 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
3200 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
3201 infer::SkolemizationMap<'tcx>), ()>
3203 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3205 // Before we create the substitutions and everything, first
3206 // consider a "quick reject". This avoids creating more types
3207 // and so forth that we need to.
3208 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3212 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
3213 &obligation.predicate);
3214 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3216 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
3219 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
3222 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
3223 project::normalize_with_depth(self,
3224 obligation.param_env,
3225 obligation.cause.clone(),
3226 obligation.recursion_depth + 1,
3229 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
3230 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3234 skol_obligation_trait_ref);
3236 let InferOk { obligations, .. } =
3237 self.infcx.at(&obligation.cause, obligation.param_env)
3238 .eq(skol_obligation_trait_ref, impl_trait_ref)
3240 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
3243 nested_obligations.extend(obligations);
3245 if let Err(e) = self.infcx.leak_check(false,
3246 obligation.cause.span,
3249 debug!("match_impl: failed leak check due to `{}`", e);
3253 debug!("match_impl: success impl_substs={:?}", impl_substs);
3256 obligations: nested_obligations
3260 fn fast_reject_trait_refs(&mut self,
3261 obligation: &TraitObligation,
3262 impl_trait_ref: &ty::TraitRef)
3265 // We can avoid creating type variables and doing the full
3266 // substitution if we find that any of the input types, when
3267 // simplified, do not match.
3269 obligation.predicate.skip_binder().input_types()
3270 .zip(impl_trait_ref.input_types())
3271 .any(|(obligation_ty, impl_ty)| {
3272 let simplified_obligation_ty =
3273 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3274 let simplified_impl_ty =
3275 fast_reject::simplify_type(self.tcx(), impl_ty, false);
3277 simplified_obligation_ty.is_some() &&
3278 simplified_impl_ty.is_some() &&
3279 simplified_obligation_ty != simplified_impl_ty
3283 /// Normalize `where_clause_trait_ref` and try to match it against
3284 /// `obligation`. If successful, return any predicates that
3285 /// result from the normalization. Normalization is necessary
3286 /// because where-clauses are stored in the parameter environment
3288 fn match_where_clause_trait_ref(&mut self,
3289 obligation: &TraitObligation<'tcx>,
3290 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
3291 -> Result<Vec<PredicateObligation<'tcx>>,()>
3293 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3296 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3297 /// obligation is satisfied.
3298 fn match_poly_trait_ref(&mut self,
3299 obligation: &TraitObligation<'tcx>,
3300 poly_trait_ref: ty::PolyTraitRef<'tcx>)
3301 -> Result<Vec<PredicateObligation<'tcx>>,()>
3303 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3307 self.infcx.at(&obligation.cause, obligation.param_env)
3308 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3309 .map(|InferOk { obligations, .. }| obligations)
3313 ///////////////////////////////////////////////////////////////////////////
3316 fn match_fresh_trait_refs(&self,
3317 previous: &ty::PolyTraitRef<'tcx>,
3318 current: &ty::PolyTraitRef<'tcx>)
3321 let mut matcher = ty::_match::Match::new(self.tcx());
3322 matcher.relate(previous, current).is_ok()
3325 fn push_stack<'o,'s:'o>(&mut self,
3326 previous_stack: TraitObligationStackList<'s, 'tcx>,
3327 obligation: &'o TraitObligation<'tcx>)
3328 -> TraitObligationStack<'o, 'tcx>
3330 let fresh_trait_ref =
3331 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3333 TraitObligationStack {
3336 previous: previous_stack,
3340 fn closure_trait_ref_unnormalized(&mut self,
3341 obligation: &TraitObligation<'tcx>,
3342 closure_def_id: DefId,
3343 substs: ty::ClosureSubsts<'tcx>)
3344 -> ty::PolyTraitRef<'tcx>
3346 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3348 // (1) Feels icky to skip the binder here, but OTOH we know
3349 // that the self-type is an unboxed closure type and hence is
3350 // in fact unparameterized (or at least does not reference any
3351 // regions bound in the obligation). Still probably some
3352 // refactoring could make this nicer.
3354 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
3355 obligation.predicate
3356 .skip_binder().self_ty(), // (1)
3358 util::TupleArgumentsFlag::No)
3359 .map_bound(|(trait_ref, _)| trait_ref)
3362 fn generator_trait_ref_unnormalized(&mut self,
3363 obligation: &TraitObligation<'tcx>,
3364 closure_def_id: DefId,
3365 substs: ty::GeneratorSubsts<'tcx>)
3366 -> ty::PolyTraitRef<'tcx>
3368 let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
3370 // (1) Feels icky to skip the binder here, but OTOH we know
3371 // that the self-type is an generator type and hence is
3372 // in fact unparameterized (or at least does not reference any
3373 // regions bound in the obligation). Still probably some
3374 // refactoring could make this nicer.
3376 self.tcx().generator_trait_ref_and_outputs(obligation.predicate.def_id(),
3377 obligation.predicate
3378 .skip_binder().self_ty(), // (1)
3380 .map_bound(|(trait_ref, ..)| trait_ref)
3383 /// Returns the obligations that are implied by instantiating an
3384 /// impl or trait. The obligations are substituted and fully
3385 /// normalized. This is used when confirming an impl or default
3387 fn impl_or_trait_obligations(&mut self,
3388 cause: ObligationCause<'tcx>,
3389 recursion_depth: usize,
3390 param_env: ty::ParamEnv<'tcx>,
3391 def_id: DefId, // of impl or trait
3392 substs: &Substs<'tcx>, // for impl or trait
3393 skol_map: infer::SkolemizationMap<'tcx>,
3394 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
3395 -> Vec<PredicateObligation<'tcx>>
3397 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3398 let tcx = self.tcx();
3400 // To allow for one-pass evaluation of the nested obligation,
3401 // each predicate must be preceded by the obligations required
3403 // for example, if we have:
3404 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3405 // the impl will have the following predicates:
3406 // <V as Iterator>::Item = U,
3407 // U: Iterator, U: Sized,
3408 // V: Iterator, V: Sized,
3409 // <U as Iterator>::Item: Copy
3410 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3411 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3412 // `$1: Copy`, so we must ensure the obligations are emitted in
3414 let predicates = tcx.predicates_of(def_id);
3415 assert_eq!(predicates.parent, None);
3416 let mut predicates: Vec<_> = predicates.predicates.iter().flat_map(|predicate| {
3417 let predicate = normalize_with_depth(self, param_env, cause.clone(), recursion_depth,
3418 &predicate.subst(tcx, substs));
3419 predicate.obligations.into_iter().chain(
3421 cause: cause.clone(),
3424 predicate: predicate.value
3428 // We are performing deduplication here to avoid exponential blowups
3429 // (#38528) from happening, but the real cause of the duplication is
3430 // unknown. What we know is that the deduplication avoids exponential
3431 // amount of predicates being propagated when processing deeply nested
3434 // This code is hot enough that it's worth avoiding the allocation
3435 // required for the FxHashSet when possible. Special-casing lengths 0,
3436 // 1 and 2 covers roughly 75--80% of the cases.
3437 if predicates.len() <= 1 {
3438 // No possibility of duplicates.
3439 } else if predicates.len() == 2 {
3440 // Only two elements. Drop the second if they are equal.
3441 if predicates[0] == predicates[1] {
3442 predicates.truncate(1);
3445 // Three or more elements. Use a general deduplication process.
3446 let mut seen = FxHashSet();
3447 predicates.retain(|i| seen.insert(i.clone()));
3449 self.infcx().plug_leaks(skol_map, snapshot, predicates)
3453 impl<'tcx> TraitObligation<'tcx> {
3454 #[allow(unused_comparisons)]
3455 pub fn derived_cause(&self,
3456 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
3457 -> ObligationCause<'tcx>
3460 * Creates a cause for obligations that are derived from
3461 * `obligation` by a recursive search (e.g., for a builtin
3462 * bound, or eventually a `auto trait Foo`). If `obligation`
3463 * is itself a derived obligation, this is just a clone, but
3464 * otherwise we create a "derived obligation" cause so as to
3465 * keep track of the original root obligation for error
3469 let obligation = self;
3471 // NOTE(flaper87): As of now, it keeps track of the whole error
3472 // chain. Ideally, we should have a way to configure this either
3473 // by using -Z verbose or just a CLI argument.
3474 if obligation.recursion_depth >= 0 {
3475 let derived_cause = DerivedObligationCause {
3476 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3477 parent_code: Rc::new(obligation.cause.code.clone())
3479 let derived_code = variant(derived_cause);
3480 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3482 obligation.cause.clone()
3487 impl<'tcx> SelectionCache<'tcx> {
3488 pub fn new() -> SelectionCache<'tcx> {
3490 hashmap: Lock::new(FxHashMap())
3494 pub fn clear(&self) {
3495 *self.hashmap.borrow_mut() = FxHashMap()
3499 impl<'tcx> EvaluationCache<'tcx> {
3500 pub fn new() -> EvaluationCache<'tcx> {
3502 hashmap: Lock::new(FxHashMap())
3506 pub fn clear(&self) {
3507 *self.hashmap.borrow_mut() = FxHashMap()
3511 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
3512 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
3513 TraitObligationStackList::with(self)
3516 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
3521 #[derive(Copy, Clone)]
3522 struct TraitObligationStackList<'o,'tcx:'o> {
3523 head: Option<&'o TraitObligationStack<'o,'tcx>>
3526 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
3527 fn empty() -> TraitObligationStackList<'o,'tcx> {
3528 TraitObligationStackList { head: None }
3531 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
3532 TraitObligationStackList { head: Some(r) }
3536 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
3537 type Item = &'o TraitObligationStack<'o,'tcx>;
3539 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3550 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3551 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3552 write!(f, "TraitObligationStack({:?})", self.obligation)
3556 #[derive(Clone, Eq, PartialEq)]
3557 pub struct WithDepNode<T> {
3558 dep_node: DepNodeIndex,
3562 impl<T: Clone> WithDepNode<T> {
3563 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3564 WithDepNode { dep_node, cached_value }
3567 pub fn get(&self, tcx: TyCtxt) -> T {
3568 tcx.dep_graph.read_index(self.dep_node);
3569 self.cached_value.clone()