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 //! Candidate selection. See the [rustc guide] for more information on how this works.
13 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html#selection
15 use self::EvaluationResult::*;
16 use self::SelectionCandidate::*;
18 use super::coherence::{self, Conflict};
20 use super::project::{normalize_with_depth, Normalized, ProjectionCacheKey};
22 use super::DerivedObligationCause;
24 use super::SelectionResult;
25 use super::TraitNotObjectSafe;
26 use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
27 use super::{IntercrateMode, TraitQueryMode};
28 use super::{ObjectCastObligation, Obligation};
29 use super::{ObligationCause, PredicateObligation, TraitObligation};
30 use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
32 VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
33 VtableObject, VtableParam, VtableTraitAlias,
36 VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
37 VtableGeneratorData, VtableImplData, VtableObjectData, VtableTraitAliasData,
40 use dep_graph::{DepKind, DepNodeIndex};
41 use hir::def_id::DefId;
43 use infer::{InferCtxt, InferOk, TypeFreshener};
44 use middle::lang_items;
45 use mir::interpret::GlobalId;
47 use ty::relate::TypeRelation;
48 use ty::subst::{Subst, Substs};
49 use ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
52 use rustc_data_structures::bit_set::GrowableBitSet;
53 use rustc_data_structures::sync::Lock;
54 use rustc_target::spec::abi::Abi;
60 use util::nodemap::{FxHashMap, FxHashSet};
62 pub struct SelectionContext<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> {
63 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
65 /// Freshener used specifically for entries on the obligation
66 /// stack. This ensures that all entries on the stack at one time
67 /// will have the same set of placeholder entries, which is
68 /// important for checking for trait bounds that recursively
69 /// require themselves.
70 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
72 /// If `true`, indicates that the evaluation should be conservative
73 /// and consider the possibility of types outside this crate.
74 /// This comes up primarily when resolving ambiguity. Imagine
75 /// there is some trait reference `$0: Bar` where `$0` is an
76 /// inference variable. If `intercrate` is true, then we can never
77 /// say for sure that this reference is not implemented, even if
78 /// there are *no impls at all for `Bar`*, because `$0` could be
79 /// bound to some type that in a downstream crate that implements
80 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
81 /// though, we set this to false, because we are only interested
82 /// in types that the user could actually have written --- in
83 /// other words, we consider `$0: Bar` to be unimplemented if
84 /// there is no type that the user could *actually name* that
85 /// would satisfy it. This avoids crippling inference, basically.
86 intercrate: Option<IntercrateMode>,
88 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
90 /// Controls whether or not to filter out negative impls when selecting.
91 /// This is used in librustdoc to distinguish between the lack of an impl
92 /// and a negative impl
93 allow_negative_impls: bool,
95 /// The mode that trait queries run in, which informs our error handling
96 /// policy. In essence, canonicalized queries need their errors propagated
97 /// rather than immediately reported because we do not have accurate spans.
98 query_mode: TraitQueryMode,
101 #[derive(Clone, Debug)]
102 pub enum IntercrateAmbiguityCause {
105 self_desc: Option<String>,
107 UpstreamCrateUpdate {
109 self_desc: Option<String>,
113 impl IntercrateAmbiguityCause {
114 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
115 /// See #23980 for details.
116 pub fn add_intercrate_ambiguity_hint<'a, 'tcx>(
118 err: &mut ::errors::DiagnosticBuilder<'_>,
120 err.note(&self.intercrate_ambiguity_hint());
123 pub fn intercrate_ambiguity_hint(&self) -> String {
125 &IntercrateAmbiguityCause::DownstreamCrate {
129 let self_desc = if let &Some(ref ty) = self_desc {
130 format!(" for type `{}`", ty)
135 "downstream crates may implement trait `{}`{}",
136 trait_desc, self_desc
139 &IntercrateAmbiguityCause::UpstreamCrateUpdate {
143 let self_desc = if let &Some(ref ty) = self_desc {
144 format!(" for type `{}`", ty)
149 "upstream crates may add new impl of trait `{}`{} \
151 trait_desc, self_desc
158 // A stack that walks back up the stack frame.
159 struct TraitObligationStack<'prev, 'tcx: 'prev> {
160 obligation: &'prev TraitObligation<'tcx>,
162 /// Trait ref from `obligation` but "freshened" with the
163 /// selection-context's freshener. Used to check for recursion.
164 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
166 previous: TraitObligationStackList<'prev, 'tcx>,
169 #[derive(Clone, Default)]
170 pub struct SelectionCache<'tcx> {
172 FxHashMap<ty::TraitRef<'tcx>, WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
176 /// The selection process begins by considering all impls, where
177 /// clauses, and so forth that might resolve an obligation. Sometimes
178 /// we'll be able to say definitively that (e.g.) an impl does not
179 /// apply to the obligation: perhaps it is defined for `usize` but the
180 /// obligation is for `int`. In that case, we drop the impl out of the
181 /// list. But the other cases are considered *candidates*.
183 /// For selection to succeed, there must be exactly one matching
184 /// candidate. If the obligation is fully known, this is guaranteed
185 /// by coherence. However, if the obligation contains type parameters
186 /// or variables, there may be multiple such impls.
188 /// It is not a real problem if multiple matching impls exist because
189 /// of type variables - it just means the obligation isn't sufficiently
190 /// elaborated. In that case we report an ambiguity, and the caller can
191 /// try again after more type information has been gathered or report a
192 /// "type annotations required" error.
194 /// However, with type parameters, this can be a real problem - type
195 /// parameters don't unify with regular types, but they *can* unify
196 /// with variables from blanket impls, and (unless we know its bounds
197 /// will always be satisfied) picking the blanket impl will be wrong
198 /// for at least *some* substitutions. To make this concrete, if we have
200 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
201 /// impl<T: fmt::Debug> AsDebug for T {
203 /// fn debug(self) -> fmt::Debug { self }
205 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
207 /// we can't just use the impl to resolve the <T as AsDebug> obligation
208 /// - a type from another crate (that doesn't implement fmt::Debug) could
209 /// implement AsDebug.
211 /// Because where-clauses match the type exactly, multiple clauses can
212 /// only match if there are unresolved variables, and we can mostly just
213 /// report this ambiguity in that case. This is still a problem - we can't
214 /// *do anything* with ambiguities that involve only regions. This is issue
217 /// If a single where-clause matches and there are no inference
218 /// variables left, then it definitely matches and we can just select
221 /// In fact, we even select the where-clause when the obligation contains
222 /// inference variables. The can lead to inference making "leaps of logic",
223 /// for example in this situation:
225 /// pub trait Foo<T> { fn foo(&self) -> T; }
226 /// impl<T> Foo<()> for T { fn foo(&self) { } }
227 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
229 /// pub fn foo<T>(t: T) where T: Foo<bool> {
230 /// println!("{:?}", <T as Foo<_>>::foo(&t));
232 /// fn main() { foo(false); }
234 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
235 /// impl and the where-clause. We select the where-clause and unify $0=bool,
236 /// so the program prints "false". However, if the where-clause is omitted,
237 /// the blanket impl is selected, we unify $0=(), and the program prints
240 /// Exactly the same issues apply to projection and object candidates, except
241 /// that we can have both a projection candidate and a where-clause candidate
242 /// for the same obligation. In that case either would do (except that
243 /// different "leaps of logic" would occur if inference variables are
244 /// present), and we just pick the where-clause. This is, for example,
245 /// required for associated types to work in default impls, as the bounds
246 /// are visible both as projection bounds and as where-clauses from the
247 /// parameter environment.
248 #[derive(PartialEq, Eq, Debug, Clone)]
249 enum SelectionCandidate<'tcx> {
250 /// If has_nested is false, there are no *further* obligations
254 ParamCandidate(ty::PolyTraitRef<'tcx>),
255 ImplCandidate(DefId),
256 AutoImplCandidate(DefId),
258 /// This is a trait matching with a projected type as `Self`, and
259 /// we found an applicable bound in the trait definition.
262 /// Implementation of a `Fn`-family trait by one of the anonymous types
263 /// generated for a `||` expression.
266 /// Implementation of a `Generator` trait by one of the anonymous types
267 /// generated for a generator.
270 /// Implementation of a `Fn`-family trait by one of the anonymous
271 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
274 TraitAliasCandidate(DefId),
278 BuiltinObjectCandidate,
280 BuiltinUnsizeCandidate,
283 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
284 type Lifted = SelectionCandidate<'tcx>;
285 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
287 BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
288 ImplCandidate(def_id) => ImplCandidate(def_id),
289 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
290 ProjectionCandidate => ProjectionCandidate,
291 ClosureCandidate => ClosureCandidate,
292 GeneratorCandidate => GeneratorCandidate,
293 FnPointerCandidate => FnPointerCandidate,
294 TraitAliasCandidate(def_id) => TraitAliasCandidate(def_id),
295 ObjectCandidate => ObjectCandidate,
296 BuiltinObjectCandidate => BuiltinObjectCandidate,
297 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
299 ParamCandidate(ref trait_ref) => {
300 return tcx.lift(trait_ref).map(ParamCandidate);
306 struct SelectionCandidateSet<'tcx> {
307 // a list of candidates that definitely apply to the current
308 // obligation (meaning: types unify).
309 vec: Vec<SelectionCandidate<'tcx>>,
311 // if this is true, then there were candidates that might or might
312 // not have applied, but we couldn't tell. This occurs when some
313 // of the input types are type variables, in which case there are
314 // various "builtin" rules that might or might not trigger.
318 #[derive(PartialEq, Eq, Debug, Clone)]
319 struct EvaluatedCandidate<'tcx> {
320 candidate: SelectionCandidate<'tcx>,
321 evaluation: EvaluationResult,
324 /// When does the builtin impl for `T: Trait` apply?
325 enum BuiltinImplConditions<'tcx> {
326 /// The impl is conditional on T1,T2,.. : Trait
327 Where(ty::Binder<Vec<Ty<'tcx>>>),
328 /// There is no built-in impl. There may be some other
329 /// candidate (a where-clause or user-defined impl).
331 /// It is unknown whether there is an impl.
335 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
336 /// The result of trait evaluation. The order is important
337 /// here as the evaluation of a list is the maximum of the
340 /// The evaluation results are ordered:
341 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
342 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
343 /// - the "union" of evaluation results is equal to their maximum -
344 /// all the "potential success" candidates can potentially succeed,
345 /// so they are no-ops when unioned with a definite error, and within
346 /// the categories it's easy to see that the unions are correct.
347 pub enum EvaluationResult {
348 /// Evaluation successful
350 /// Evaluation is known to be ambiguous - it *might* hold for some
351 /// assignment of inference variables, but it might not.
353 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
354 /// know whether this obligation holds or not - it is the result we
355 /// would get with an empty stack, and therefore is cacheable.
357 /// Evaluation failed because of recursion involving inference
358 /// variables. We are somewhat imprecise there, so we don't actually
359 /// know the real result.
361 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
363 /// Evaluation failed because we encountered an obligation we are already
364 /// trying to prove on this branch.
366 /// We know this branch can't be a part of a minimal proof-tree for
367 /// the "root" of our cycle, because then we could cut out the recursion
368 /// and maintain a valid proof tree. However, this does not mean
369 /// that all the obligations on this branch do not hold - it's possible
370 /// that we entered this branch "speculatively", and that there
371 /// might be some other way to prove this obligation that does not
372 /// go through this cycle - so we can't cache this as a failure.
374 /// For example, suppose we have this:
376 /// ```rust,ignore (pseudo-Rust)
377 /// pub trait Trait { fn xyz(); }
378 /// // This impl is "useless", but we can still have
379 /// // an `impl Trait for SomeUnsizedType` somewhere.
380 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
382 /// pub fn foo<T: Trait + ?Sized>() {
383 /// <T as Trait>::xyz();
387 /// When checking `foo`, we have to prove `T: Trait`. This basically
388 /// translates into this:
391 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
394 /// When we try to prove it, we first go the first option, which
395 /// recurses. This shows us that the impl is "useless" - it won't
396 /// tell us that `T: Trait` unless it already implemented `Trait`
397 /// by some other means. However, that does not prevent `T: Trait`
398 /// does not hold, because of the bound (which can indeed be satisfied
399 /// by `SomeUnsizedType` from another crate).
401 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
402 /// ought to convert it to an `EvaluatedToErr`, because we know
403 /// there definitely isn't a proof tree for that obligation. Not
404 /// doing so is still sound - there isn't any proof tree, so the
405 /// branch still can't be a part of a minimal one - but does not
406 /// re-enable caching.
408 /// Evaluation failed
412 impl EvaluationResult {
413 pub fn may_apply(self) -> bool {
415 EvaluatedToOk | EvaluatedToAmbig | EvaluatedToUnknown => true,
417 EvaluatedToErr | EvaluatedToRecur => false,
421 fn is_stack_dependent(self) -> bool {
423 EvaluatedToUnknown | EvaluatedToRecur => true,
425 EvaluatedToOk | EvaluatedToAmbig | EvaluatedToErr => false,
430 impl_stable_hash_for!(enum self::EvaluationResult {
438 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
439 /// Indicates that trait evaluation caused overflow.
440 pub struct OverflowError;
442 impl_stable_hash_for!(struct OverflowError {});
444 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
445 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
446 SelectionError::Overflow
450 #[derive(Clone, Default)]
451 pub struct EvaluationCache<'tcx> {
452 hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>,
455 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
456 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
459 freshener: infcx.freshener(),
461 intercrate_ambiguity_causes: None,
462 allow_negative_impls: false,
463 query_mode: TraitQueryMode::Standard,
468 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
469 mode: IntercrateMode,
470 ) -> SelectionContext<'cx, 'gcx, 'tcx> {
471 debug!("intercrate({:?})", mode);
474 freshener: infcx.freshener(),
475 intercrate: Some(mode),
476 intercrate_ambiguity_causes: None,
477 allow_negative_impls: false,
478 query_mode: TraitQueryMode::Standard,
482 pub fn with_negative(
483 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
484 allow_negative_impls: bool,
485 ) -> SelectionContext<'cx, 'gcx, 'tcx> {
486 debug!("with_negative({:?})", allow_negative_impls);
489 freshener: infcx.freshener(),
491 intercrate_ambiguity_causes: None,
492 allow_negative_impls,
493 query_mode: TraitQueryMode::Standard,
497 pub fn with_query_mode(
498 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
499 query_mode: TraitQueryMode,
500 ) -> SelectionContext<'cx, 'gcx, 'tcx> {
501 debug!("with_query_mode({:?})", query_mode);
504 freshener: infcx.freshener(),
506 intercrate_ambiguity_causes: None,
507 allow_negative_impls: false,
512 /// Enables tracking of intercrate ambiguity causes. These are
513 /// used in coherence to give improved diagnostics. We don't do
514 /// this until we detect a coherence error because it can lead to
515 /// false overflow results (#47139) and because it costs
516 /// computation time.
517 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
518 assert!(self.intercrate.is_some());
519 assert!(self.intercrate_ambiguity_causes.is_none());
520 self.intercrate_ambiguity_causes = Some(vec![]);
521 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
524 /// Gets the intercrate ambiguity causes collected since tracking
525 /// was enabled and disables tracking at the same time. If
526 /// tracking is not enabled, just returns an empty vector.
527 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
528 assert!(self.intercrate.is_some());
529 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
532 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
536 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
540 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
544 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
546 fn in_snapshot<R, F>(&mut self, f: F) -> R
548 F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R,
550 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
553 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
555 fn probe<R, F>(&mut self, f: F) -> R
557 F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R,
559 self.infcx.probe(|snapshot| f(self, snapshot))
562 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
563 /// the transaction fails and s.t. old obligations are retained.
564 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E>
566 F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> Result<T, E>,
568 self.infcx.commit_if_ok(|snapshot| f(self, snapshot))
571 ///////////////////////////////////////////////////////////////////////////
574 // The selection phase tries to identify *how* an obligation will
575 // be resolved. For example, it will identify which impl or
576 // parameter bound is to be used. The process can be inconclusive
577 // if the self type in the obligation is not fully inferred. Selection
578 // can result in an error in one of two ways:
580 // 1. If no applicable impl or parameter bound can be found.
581 // 2. If the output type parameters in the obligation do not match
582 // those specified by the impl/bound. For example, if the obligation
583 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
584 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
586 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
587 /// type environment by performing unification.
590 obligation: &TraitObligation<'tcx>,
591 ) -> SelectionResult<'tcx, Selection<'tcx>> {
592 debug!("select({:?})", obligation);
593 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
595 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
597 let candidate = match self.candidate_from_obligation(&stack) {
598 Err(SelectionError::Overflow) => {
599 // In standard mode, overflow must have been caught and reported
601 assert!(self.query_mode == TraitQueryMode::Canonical);
602 return Err(SelectionError::Overflow);
610 Ok(Some(candidate)) => candidate,
613 match self.confirm_candidate(obligation, candidate) {
614 Err(SelectionError::Overflow) => {
615 assert!(self.query_mode == TraitQueryMode::Canonical);
616 Err(SelectionError::Overflow)
619 Ok(candidate) => Ok(Some(candidate)),
623 ///////////////////////////////////////////////////////////////////////////
626 // Tests whether an obligation can be selected or whether an impl
627 // can be applied to particular types. It skips the "confirmation"
628 // step and hence completely ignores output type parameters.
630 // The result is "true" if the obligation *may* hold and "false" if
631 // we can be sure it does not.
633 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
634 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
635 debug!("predicate_may_hold_fatal({:?})", obligation);
637 // This fatal query is a stopgap that should only be used in standard mode,
638 // where we do not expect overflow to be propagated.
639 assert!(self.query_mode == TraitQueryMode::Standard);
641 self.evaluate_obligation_recursively(obligation)
642 .expect("Overflow should be caught earlier in standard query mode")
646 /// Evaluates whether the obligation `obligation` can be satisfied and returns
647 /// an `EvaluationResult`.
648 pub fn evaluate_obligation_recursively(
650 obligation: &PredicateObligation<'tcx>,
651 ) -> Result<EvaluationResult, OverflowError> {
652 self.probe(|this, _| {
653 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
657 /// Evaluates the predicates in `predicates` recursively. Note that
658 /// this applies projections in the predicates, and therefore
659 /// is run within an inference probe.
660 fn evaluate_predicates_recursively<'a, 'o, I>(
662 stack: TraitObligationStackList<'o, 'tcx>,
664 ) -> Result<EvaluationResult, OverflowError>
666 I: IntoIterator<Item = &'a PredicateObligation<'tcx>>,
669 let mut result = EvaluatedToOk;
670 for obligation in predicates {
671 let eval = self.evaluate_predicate_recursively(stack, obligation)?;
673 "evaluate_predicate_recursively({:?}) = {:?}",
676 if let EvaluatedToErr = eval {
677 // fast-path - EvaluatedToErr is the top of the lattice,
678 // so we don't need to look on the other predicates.
679 return Ok(EvaluatedToErr);
681 result = cmp::max(result, eval);
687 fn evaluate_predicate_recursively<'o>(
689 previous_stack: TraitObligationStackList<'o, 'tcx>,
690 obligation: &PredicateObligation<'tcx>,
691 ) -> Result<EvaluationResult, OverflowError> {
692 debug!("evaluate_predicate_recursively({:?})", obligation);
694 match obligation.predicate {
695 ty::Predicate::Trait(ref t) => {
696 debug_assert!(!t.has_escaping_bound_vars());
697 let obligation = obligation.with(t.clone());
698 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
701 ty::Predicate::Subtype(ref p) => {
702 // does this code ever run?
704 .subtype_predicate(&obligation.cause, obligation.param_env, p)
706 Some(Ok(InferOk { obligations, .. })) => {
707 self.evaluate_predicates_recursively(previous_stack, &obligations)
709 Some(Err(_)) => Ok(EvaluatedToErr),
710 None => Ok(EvaluatedToAmbig),
714 ty::Predicate::WellFormed(ty) => match ty::wf::obligations(
716 obligation.param_env,
717 obligation.cause.body_id,
719 obligation.cause.span,
721 Some(obligations) => {
722 self.evaluate_predicates_recursively(previous_stack, obligations.iter())
724 None => Ok(EvaluatedToAmbig),
727 ty::Predicate::TypeOutlives(ref binder) => {
728 assert!(!binder.has_escaping_bound_vars());
729 // Check if the type has higher-ranked vars.
730 if binder.skip_binder().0.has_escaping_bound_vars() {
731 // If so, this obligation is an error (for now). Eventually we should be
732 // able to support additional cases here, like `for<'a> &'a str: 'a`.
734 // NOTE: this hack is implemented in both trait fulfillment and
735 // evaluation. If you fix it in one place, make sure you fix it
738 // We don't want to allow this sort of reasoning in intercrate
739 // mode, for backwards-compatibility reasons.
740 if self.intercrate.is_some() {
746 // If the type has no late bound vars, then if we assign all
747 // the inference variables in it to be 'static, then the type
748 // will be 'static itself.
750 // Therefore, `staticize(T): 'a` holds for any `'a`, so this
751 // obligation is fulfilled. Because evaluation works with
752 // staticized types (yes I know this is involved with #21974),
753 // we are 100% OK here.
758 ty::Predicate::RegionOutlives(ref binder) => {
759 let ty::OutlivesPredicate(r_a, r_b) = binder.skip_binder();
762 // for<'a> 'a: 'a. OK
764 } else if **r_a == ty::ReStatic {
765 // 'static: 'x always holds.
767 // This special case is handled somewhat inconsistently - if we
768 // have an inference variable that is supposed to be equal to
769 // `'static`, then we don't allow it to be equated to an LBR,
770 // but if we have a literal `'static`, then we *do*.
772 // This is actually consistent with how our region inference works.
774 // It would appear that this sort of inconsistency would
775 // cause "instability" problems with evaluation caching. However,
776 // evaluation caching is only for trait predicates, and when
777 // trait predicates create nested obligations, they contain
778 // inference variables for all the regions in the trait - the
779 // only way this codepath can be reached from trait predicate
780 // evaluation is when the user typed an explicit `where 'static: 'a`
781 // lifetime bound (in which case we want to return EvaluatedToOk).
783 // If we ever want to handle inference variables that might be
784 // equatable with ReStatic, we need to make sure we are not confused by
785 // technically-allowed-by-RFC-447-but-probably-should-not-be
788 // impl<'a, 's, T> X<'s> for T where T: Debug + 'a, 'a: 's
791 } else if r_a.is_late_bound() || r_b.is_late_bound() {
792 // There is no current way to prove `for<'a> 'a: 'x`
793 // unless `'a = 'x`, because there are no bounds involving
796 // It might be possible to prove `for<'a> 'x: 'a` by forcing `'x`
797 // to be `'static`. However, this is not currently done by type
798 // inference unless `'x` is literally ReStatic. See the comment
801 // We don't want to allow this sort of reasoning in intercrate
802 // mode, for backwards-compatibility reasons.
803 if self.intercrate.is_some() {
809 // Relating 2 inference variable regions. These will
810 // always hold if our query is "staticized".
815 ty::Predicate::ObjectSafe(trait_def_id) => {
816 if self.tcx().is_object_safe(trait_def_id) {
823 ty::Predicate::Projection(ref data) => {
824 let project_obligation = obligation.with(data.clone());
825 match project::poly_project_and_unify_type(self, &project_obligation) {
826 Ok(Some(subobligations)) => {
827 let result = self.evaluate_predicates_recursively(
829 subobligations.iter(),
832 ProjectionCacheKey::from_poly_projection_predicate(self, data)
834 self.infcx.projection_cache.borrow_mut().complete(key);
838 Ok(None) => Ok(EvaluatedToAmbig),
839 Err(_) => Ok(EvaluatedToErr),
843 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
844 match self.infcx.closure_kind(closure_def_id, closure_substs) {
845 Some(closure_kind) => {
846 if closure_kind.extends(kind) {
852 None => Ok(EvaluatedToAmbig),
856 ty::Predicate::ConstEvaluatable(def_id, substs) => {
857 let tcx = self.tcx();
858 match tcx.lift_to_global(&(obligation.param_env, substs)) {
859 Some((param_env, substs)) => {
861 ty::Instance::resolve(tcx.global_tcx(), param_env, def_id, substs);
862 if let Some(instance) = instance {
867 match self.tcx().const_eval(param_env.and(cid)) {
868 Ok(_) => Ok(EvaluatedToOk),
869 Err(_) => Ok(EvaluatedToErr),
876 // Inference variables still left in param_env or substs.
884 fn evaluate_trait_predicate_recursively<'o>(
886 previous_stack: TraitObligationStackList<'o, 'tcx>,
887 mut obligation: TraitObligation<'tcx>,
888 ) -> Result<EvaluationResult, OverflowError> {
889 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
891 if self.intercrate.is_none() && obligation.is_global()
896 .all(|bound| bound.needs_subst())
898 // If a param env has no global bounds, global obligations do not
899 // depend on its particular value in order to work, so we can clear
900 // out the param env and get better caching.
902 "evaluate_trait_predicate_recursively({:?}) - in global",
905 obligation.param_env = obligation.param_env.without_caller_bounds();
908 let stack = self.push_stack(previous_stack, &obligation);
909 let fresh_trait_ref = stack.fresh_trait_ref;
910 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
911 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
915 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
916 let result = result?;
918 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
919 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
924 fn evaluate_stack<'o>(
926 stack: &TraitObligationStack<'o, 'tcx>,
927 ) -> Result<EvaluationResult, OverflowError> {
928 // In intercrate mode, whenever any of the types are unbound,
929 // there can always be an impl. Even if there are no impls in
930 // this crate, perhaps the type would be unified with
931 // something from another crate that does provide an impl.
933 // In intra mode, we must still be conservative. The reason is
934 // that we want to avoid cycles. Imagine an impl like:
936 // impl<T:Eq> Eq for Vec<T>
938 // and a trait reference like `$0 : Eq` where `$0` is an
939 // unbound variable. When we evaluate this trait-reference, we
940 // will unify `$0` with `Vec<$1>` (for some fresh variable
941 // `$1`), on the condition that `$1 : Eq`. We will then wind
942 // up with many candidates (since that are other `Eq` impls
943 // that apply) and try to winnow things down. This results in
944 // a recursive evaluation that `$1 : Eq` -- as you can
945 // imagine, this is just where we started. To avoid that, we
946 // check for unbound variables and return an ambiguous (hence possible)
947 // match if we've seen this trait before.
949 // This suffices to allow chains like `FnMut` implemented in
950 // terms of `Fn` etc, but we could probably make this more
952 let unbound_input_types = stack
956 .any(|ty| ty.is_fresh());
957 // this check was an imperfect workaround for a bug n the old
958 // intercrate mode, it should be removed when that goes away.
959 if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
961 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
962 stack.fresh_trait_ref
964 // Heuristics: show the diagnostics when there are no candidates in crate.
965 if self.intercrate_ambiguity_causes.is_some() {
966 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
967 if let Ok(candidate_set) = self.assemble_candidates(stack) {
968 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
969 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
970 let self_ty = trait_ref.self_ty();
971 let cause = IntercrateAmbiguityCause::DownstreamCrate {
972 trait_desc: trait_ref.to_string(),
973 self_desc: if self_ty.has_concrete_skeleton() {
974 Some(self_ty.to_string())
979 debug!("evaluate_stack: pushing cause = {:?}", cause);
980 self.intercrate_ambiguity_causes
987 return Ok(EvaluatedToAmbig);
989 if unbound_input_types && stack.iter().skip(1).any(|prev| {
990 stack.obligation.param_env == prev.obligation.param_env
991 && self.match_fresh_trait_refs(&stack.fresh_trait_ref, &prev.fresh_trait_ref)
994 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
995 stack.fresh_trait_ref
997 return Ok(EvaluatedToUnknown);
1000 // If there is any previous entry on the stack that precisely
1001 // matches this obligation, then we can assume that the
1002 // obligation is satisfied for now (still all other conditions
1003 // must be met of course). One obvious case this comes up is
1004 // marker traits like `Send`. Think of a linked list:
1006 // struct List<T> { data: T, next: Option<Box<List<T>>> }
1008 // `Box<List<T>>` will be `Send` if `T` is `Send` and
1009 // `Option<Box<List<T>>>` is `Send`, and in turn
1010 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
1013 // Note that we do this comparison using the `fresh_trait_ref`
1014 // fields. Because these have all been freshened using
1015 // `self.freshener`, we can be sure that (a) this will not
1016 // affect the inferencer state and (b) that if we see two
1017 // fresh regions with the same index, they refer to the same
1018 // unbound type variable.
1019 if let Some(rec_index) = stack.iter()
1020 .skip(1) // skip top-most frame
1021 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
1022 stack.fresh_trait_ref == prev.fresh_trait_ref)
1024 debug!("evaluate_stack({:?}) --> recursive", stack.fresh_trait_ref);
1026 let cycle = stack.iter().skip(1).take(rec_index + 1);
1027 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
1028 if self.coinductive_match(cycle) {
1030 "evaluate_stack({:?}) --> recursive, coinductive",
1031 stack.fresh_trait_ref
1033 return Ok(EvaluatedToOk);
1036 "evaluate_stack({:?}) --> recursive, inductive",
1037 stack.fresh_trait_ref
1039 return Ok(EvaluatedToRecur);
1043 match self.candidate_from_obligation(stack) {
1044 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1045 Ok(None) => Ok(EvaluatedToAmbig),
1046 Err(Overflow) => Err(OverflowError),
1047 Err(..) => Ok(EvaluatedToErr),
1051 /// For defaulted traits, we use a co-inductive strategy to solve, so
1052 /// that recursion is ok. This routine returns true if the top of the
1053 /// stack (`cycle[0]`):
1055 /// - is a defaulted trait, and
1056 /// - it also appears in the backtrace at some position `X`; and,
1057 /// - all the predicates at positions `X..` between `X` an the top are
1058 /// also defaulted traits.
1059 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1061 I: Iterator<Item = ty::Predicate<'tcx>>,
1063 let mut cycle = cycle;
1064 cycle.all(|predicate| self.coinductive_predicate(predicate))
1067 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1068 let result = match predicate {
1069 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1072 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1076 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1077 /// obligations are met. Returns true if `candidate` remains viable after this further
1079 fn evaluate_candidate<'o>(
1081 stack: &TraitObligationStack<'o, 'tcx>,
1082 candidate: &SelectionCandidate<'tcx>,
1083 ) -> Result<EvaluationResult, OverflowError> {
1085 "evaluate_candidate: depth={} candidate={:?}",
1086 stack.obligation.recursion_depth, candidate
1088 let result = self.probe(|this, _| {
1089 let candidate = (*candidate).clone();
1090 match this.confirm_candidate(stack.obligation, candidate) {
1091 Ok(selection) => this.evaluate_predicates_recursively(
1093 selection.nested_obligations().iter(),
1095 Err(..) => Ok(EvaluatedToErr),
1099 "evaluate_candidate: depth={} result={:?}",
1100 stack.obligation.recursion_depth, result
1105 fn check_evaluation_cache(
1107 param_env: ty::ParamEnv<'tcx>,
1108 trait_ref: ty::PolyTraitRef<'tcx>,
1109 ) -> Option<EvaluationResult> {
1110 let tcx = self.tcx();
1111 if self.can_use_global_caches(param_env) {
1112 let cache = tcx.evaluation_cache.hashmap.borrow();
1113 if let Some(cached) = cache.get(&trait_ref) {
1114 return Some(cached.get(tcx));
1122 .map(|v| v.get(tcx))
1125 fn insert_evaluation_cache(
1127 param_env: ty::ParamEnv<'tcx>,
1128 trait_ref: ty::PolyTraitRef<'tcx>,
1129 dep_node: DepNodeIndex,
1130 result: EvaluationResult,
1132 // Avoid caching results that depend on more than just the trait-ref
1133 // - the stack can create recursion.
1134 if result.is_stack_dependent() {
1138 if self.can_use_global_caches(param_env) {
1139 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1141 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1144 // This may overwrite the cache with the same value
1145 // FIXME: Due to #50507 this overwrites the different values
1146 // This should be changed to use HashMapExt::insert_same
1147 // when that is fixed
1152 .insert(trait_ref, WithDepNode::new(dep_node, result));
1158 "insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
1165 .insert(trait_ref, WithDepNode::new(dep_node, result));
1168 ///////////////////////////////////////////////////////////////////////////
1169 // CANDIDATE ASSEMBLY
1171 // The selection process begins by examining all in-scope impls,
1172 // caller obligations, and so forth and assembling a list of
1173 // candidates. See the [rustc guide] for more details.
1176 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1178 fn candidate_from_obligation<'o>(
1180 stack: &TraitObligationStack<'o, 'tcx>,
1181 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1182 // Watch out for overflow. This intentionally bypasses (and does
1183 // not update) the cache.
1184 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1185 if stack.obligation.recursion_depth >= recursion_limit {
1186 match self.query_mode {
1187 TraitQueryMode::Standard => {
1188 self.infcx().report_overflow_error(&stack.obligation, true);
1190 TraitQueryMode::Canonical => {
1191 return Err(Overflow);
1196 // Check the cache. Note that we freshen the trait-ref
1197 // separately rather than using `stack.fresh_trait_ref` --
1198 // this is because we want the unbound variables to be
1199 // replaced with fresh types starting from index 0.
1200 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1202 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1203 cache_fresh_trait_pred, stack
1205 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
1208 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1210 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1214 // If no match, compute result and insert into cache.
1215 let (candidate, dep_node) =
1216 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1219 "CACHE MISS: SELECT({:?})={:?}",
1220 cache_fresh_trait_pred, candidate
1222 self.insert_candidate_cache(
1223 stack.obligation.param_env,
1224 cache_fresh_trait_pred,
1231 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1233 OP: FnOnce(&mut Self) -> R,
1235 let (result, dep_node) = self.tcx()
1237 .with_anon_task(DepKind::TraitSelect, || op(self));
1238 self.tcx().dep_graph.read_index(dep_node);
1242 // Treat negative impls as unimplemented
1243 fn filter_negative_impls(
1245 candidate: SelectionCandidate<'tcx>,
1246 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1247 if let ImplCandidate(def_id) = candidate {
1248 if !self.allow_negative_impls
1249 && self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative
1251 return Err(Unimplemented);
1257 fn candidate_from_obligation_no_cache<'o>(
1259 stack: &TraitObligationStack<'o, 'tcx>,
1260 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1261 if stack.obligation.predicate.references_error() {
1262 // If we encounter a `Error`, we generally prefer the
1263 // most "optimistic" result in response -- that is, the
1264 // one least likely to report downstream errors. But
1265 // because this routine is shared by coherence and by
1266 // trait selection, there isn't an obvious "right" choice
1267 // here in that respect, so we opt to just return
1268 // ambiguity and let the upstream clients sort it out.
1272 if let Some(conflict) = self.is_knowable(stack) {
1273 debug!("coherence stage: not knowable");
1274 if self.intercrate_ambiguity_causes.is_some() {
1275 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1276 // Heuristics: show the diagnostics when there are no candidates in crate.
1277 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1278 let mut no_candidates_apply = true;
1280 let evaluated_candidates = candidate_set
1283 .map(|c| self.evaluate_candidate(stack, &c));
1285 for ec in evaluated_candidates {
1289 no_candidates_apply = false;
1293 Err(e) => return Err(e.into()),
1298 if !candidate_set.ambiguous && no_candidates_apply {
1299 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1300 let self_ty = trait_ref.self_ty();
1301 let trait_desc = trait_ref.to_string();
1302 let self_desc = if self_ty.has_concrete_skeleton() {
1303 Some(self_ty.to_string())
1307 let cause = if let Conflict::Upstream = conflict {
1308 IntercrateAmbiguityCause::UpstreamCrateUpdate {
1313 IntercrateAmbiguityCause::DownstreamCrate {
1318 debug!("evaluate_stack: pushing cause = {:?}", cause);
1319 self.intercrate_ambiguity_causes
1329 let candidate_set = self.assemble_candidates(stack)?;
1331 if candidate_set.ambiguous {
1332 debug!("candidate set contains ambig");
1336 let mut candidates = candidate_set.vec;
1339 "assembled {} candidates for {:?}: {:?}",
1345 // At this point, we know that each of the entries in the
1346 // candidate set is *individually* applicable. Now we have to
1347 // figure out if they contain mutual incompatibilities. This
1348 // frequently arises if we have an unconstrained input type --
1349 // for example, we are looking for $0:Eq where $0 is some
1350 // unconstrained type variable. In that case, we'll get a
1351 // candidate which assumes $0 == int, one that assumes $0 ==
1352 // usize, etc. This spells an ambiguity.
1354 // If there is more than one candidate, first winnow them down
1355 // by considering extra conditions (nested obligations and so
1356 // forth). We don't winnow if there is exactly one
1357 // candidate. This is a relatively minor distinction but it
1358 // can lead to better inference and error-reporting. An
1359 // example would be if there was an impl:
1361 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1363 // and we were to see some code `foo.push_clone()` where `boo`
1364 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1365 // we were to winnow, we'd wind up with zero candidates.
1366 // Instead, we select the right impl now but report `Bar does
1367 // not implement Clone`.
1368 if candidates.len() == 1 {
1369 return self.filter_negative_impls(candidates.pop().unwrap());
1372 // Winnow, but record the exact outcome of evaluation, which
1373 // is needed for specialization. Propagate overflow if it occurs.
1374 let mut candidates = candidates
1376 .map(|c| match self.evaluate_candidate(stack, &c) {
1377 Ok(eval) if eval.may_apply() => Ok(Some(EvaluatedCandidate {
1382 Err(OverflowError) => Err(Overflow),
1384 .flat_map(Result::transpose)
1385 .collect::<Result<Vec<_>, _>>()?;
1388 "winnowed to {} candidates for {:?}: {:?}",
1394 // If there are STILL multiple candidates, we can further
1395 // reduce the list by dropping duplicates -- including
1396 // resolving specializations.
1397 if candidates.len() > 1 {
1399 while i < candidates.len() {
1400 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1401 self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1405 "Dropping candidate #{}/{}: {:?}",
1410 candidates.swap_remove(i);
1413 "Retaining candidate #{}/{}: {:?}",
1420 // If there are *STILL* multiple candidates, give up
1421 // and report ambiguity.
1423 debug!("multiple matches, ambig");
1430 // If there are *NO* candidates, then there are no impls --
1431 // that we know of, anyway. Note that in the case where there
1432 // are unbound type variables within the obligation, it might
1433 // be the case that you could still satisfy the obligation
1434 // from another crate by instantiating the type variables with
1435 // a type from another crate that does have an impl. This case
1436 // is checked for in `evaluate_stack` (and hence users
1437 // who might care about this case, like coherence, should use
1439 if candidates.is_empty() {
1440 return Err(Unimplemented);
1443 // Just one candidate left.
1444 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1447 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1448 debug!("is_knowable(intercrate={:?})", self.intercrate);
1450 if !self.intercrate.is_some() {
1454 let obligation = &stack.obligation;
1455 let predicate = self.infcx()
1456 .resolve_type_vars_if_possible(&obligation.predicate);
1458 // OK to skip binder because of the nature of the
1459 // trait-ref-is-knowable check, which does not care about
1461 let trait_ref = predicate.skip_binder().trait_ref;
1463 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1465 Some(Conflict::Downstream {
1466 used_to_be_broken: true,
1468 Some(IntercrateMode::Issue43355),
1469 ) = (result, self.intercrate)
1471 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1478 /// Returns true if the global caches can be used.
1479 /// Do note that if the type itself is not in the
1480 /// global tcx, the local caches will be used.
1481 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1482 // If there are any where-clauses in scope, then we always use
1483 // a cache local to this particular scope. Otherwise, we
1484 // switch to a global cache. We used to try and draw
1485 // finer-grained distinctions, but that led to a serious of
1486 // annoying and weird bugs like #22019 and #18290. This simple
1487 // rule seems to be pretty clearly safe and also still retains
1488 // a very high hit rate (~95% when compiling rustc).
1489 if !param_env.caller_bounds.is_empty() {
1493 // Avoid using the master cache during coherence and just rely
1494 // on the local cache. This effectively disables caching
1495 // during coherence. It is really just a simplification to
1496 // avoid us having to fear that coherence results "pollute"
1497 // the master cache. Since coherence executes pretty quickly,
1498 // it's not worth going to more trouble to increase the
1499 // hit-rate I don't think.
1500 if self.intercrate.is_some() {
1504 // Otherwise, we can use the global cache.
1508 fn check_candidate_cache(
1510 param_env: ty::ParamEnv<'tcx>,
1511 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1512 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1513 let tcx = self.tcx();
1514 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1515 if self.can_use_global_caches(param_env) {
1516 let cache = tcx.selection_cache.hashmap.borrow();
1517 if let Some(cached) = cache.get(&trait_ref) {
1518 return Some(cached.get(tcx));
1526 .map(|v| v.get(tcx))
1529 /// Determines whether can we safely cache the result
1530 /// of selecting an obligation. This is almost always 'true',
1531 /// except when dealing with certain ParamCandidates.
1533 /// Ordinarily, a ParamCandidate will contain no inference variables,
1534 /// since it was usually produced directly from a DefId. However,
1535 /// certain cases (currently only librustdoc's blanket impl finder),
1536 /// a ParamEnv may be explicitly constructed with inference types.
1537 /// When this is the case, we do *not* want to cache the resulting selection
1538 /// candidate. This is due to the fact that it might not always be possible
1539 /// to equate the obligation's trait ref and the candidate's trait ref,
1540 /// if more constraints end up getting added to an inference variable.
1542 /// Because of this, we always want to re-run the full selection
1543 /// process for our obligation the next time we see it, since
1544 /// we might end up picking a different SelectionCandidate (or none at all)
1545 fn can_cache_candidate(&self,
1546 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>
1549 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => {
1550 !trait_ref.skip_binder().input_types().any(|t| t.walk().any(|t_| t_.is_ty_infer()))
1556 fn insert_candidate_cache(
1558 param_env: ty::ParamEnv<'tcx>,
1559 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1560 dep_node: DepNodeIndex,
1561 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1563 let tcx = self.tcx();
1564 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1566 if !self.can_cache_candidate(&candidate) {
1567 debug!("insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1568 candidate is not cacheable", trait_ref, candidate);
1573 if self.can_use_global_caches(param_env) {
1574 if let Err(Overflow) = candidate {
1575 // Don't cache overflow globally; we only produce this
1576 // in certain modes.
1577 } else if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1578 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1580 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1581 trait_ref, candidate,
1583 // This may overwrite the cache with the same value
1587 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1594 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1595 trait_ref, candidate,
1601 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1604 fn assemble_candidates<'o>(
1606 stack: &TraitObligationStack<'o, 'tcx>,
1607 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1608 let TraitObligationStack { obligation, .. } = *stack;
1609 let ref obligation = Obligation {
1610 param_env: obligation.param_env,
1611 cause: obligation.cause.clone(),
1612 recursion_depth: obligation.recursion_depth,
1613 predicate: self.infcx()
1614 .resolve_type_vars_if_possible(&obligation.predicate),
1617 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1618 // Self is a type variable (e.g., `_: AsRef<str>`).
1620 // This is somewhat problematic, as the current scheme can't really
1621 // handle it turning to be a projection. This does end up as truly
1622 // ambiguous in most cases anyway.
1624 // Take the fast path out - this also improves
1625 // performance by preventing assemble_candidates_from_impls from
1626 // matching every impl for this trait.
1627 return Ok(SelectionCandidateSet {
1633 let mut candidates = SelectionCandidateSet {
1638 self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1640 // Other bounds. Consider both in-scope bounds from fn decl
1641 // and applicable impls. There is a certain set of precedence rules here.
1642 let def_id = obligation.predicate.def_id();
1643 let lang_items = self.tcx().lang_items();
1645 if lang_items.copy_trait() == Some(def_id) {
1647 "obligation self ty is {:?}",
1648 obligation.predicate.skip_binder().self_ty()
1651 // User-defined copy impls are permitted, but only for
1652 // structs and enums.
1653 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1655 // For other types, we'll use the builtin rules.
1656 let copy_conditions = self.copy_clone_conditions(obligation);
1657 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1658 } else if lang_items.sized_trait() == Some(def_id) {
1659 // Sized is never implementable by end-users, it is
1660 // always automatically computed.
1661 let sized_conditions = self.sized_conditions(obligation);
1662 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1663 } else if lang_items.unsize_trait() == Some(def_id) {
1664 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1666 if lang_items.clone_trait() == Some(def_id) {
1667 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1668 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1669 // types have builtin support for `Clone`.
1670 let clone_conditions = self.copy_clone_conditions(obligation);
1671 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1674 self.assemble_generator_candidates(obligation, &mut candidates)?;
1675 self.assemble_closure_candidates(obligation, &mut candidates)?;
1676 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1677 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1678 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1681 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1682 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1683 // Auto implementations have lower priority, so we only
1684 // consider triggering a default if there is no other impl that can apply.
1685 if candidates.vec.is_empty() {
1686 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1688 debug!("candidate list size: {}", candidates.vec.len());
1692 fn assemble_candidates_from_projected_tys(
1694 obligation: &TraitObligation<'tcx>,
1695 candidates: &mut SelectionCandidateSet<'tcx>,
1697 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1699 // before we go into the whole placeholder thing, just
1700 // quickly check if the self-type is a projection at all.
1701 match obligation.predicate.skip_binder().trait_ref.self_ty().sty {
1702 ty::Projection(_) | ty::Opaque(..) => {}
1703 ty::Infer(ty::TyVar(_)) => {
1705 obligation.cause.span,
1706 "Self=_ should have been handled by assemble_candidates"
1712 let result = self.probe(|this, snapshot| {
1713 this.match_projection_obligation_against_definition_bounds(obligation, snapshot)
1717 candidates.vec.push(ProjectionCandidate);
1721 fn match_projection_obligation_against_definition_bounds(
1723 obligation: &TraitObligation<'tcx>,
1724 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
1726 let poly_trait_predicate = self.infcx()
1727 .resolve_type_vars_if_possible(&obligation.predicate);
1728 let (skol_trait_predicate, placeholder_map) = self.infcx()
1729 .replace_bound_vars_with_placeholders(&poly_trait_predicate);
1731 "match_projection_obligation_against_definition_bounds: \
1732 skol_trait_predicate={:?} placeholder_map={:?}",
1733 skol_trait_predicate, placeholder_map
1736 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1737 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1738 ty::Opaque(def_id, substs) => (def_id, substs),
1741 obligation.cause.span,
1742 "match_projection_obligation_against_definition_bounds() called \
1743 but self-ty is not a projection: {:?}",
1744 skol_trait_predicate.trait_ref.self_ty()
1749 "match_projection_obligation_against_definition_bounds: \
1750 def_id={:?}, substs={:?}",
1754 let predicates_of = self.tcx().predicates_of(def_id);
1755 let bounds = predicates_of.instantiate(self.tcx(), substs);
1757 "match_projection_obligation_against_definition_bounds: \
1762 let matching_bound = util::elaborate_predicates(self.tcx(), bounds.predicates)
1765 self.probe(|this, _| {
1766 this.match_projection(
1769 skol_trait_predicate.trait_ref.clone(),
1777 "match_projection_obligation_against_definition_bounds: \
1778 matching_bound={:?}",
1781 match matching_bound {
1784 // Repeat the successful match, if any, this time outside of a probe.
1785 let result = self.match_projection(
1788 skol_trait_predicate.trait_ref.clone(),
1793 self.infcx.pop_placeholders(placeholder_map, snapshot);
1801 fn match_projection(
1803 obligation: &TraitObligation<'tcx>,
1804 trait_bound: ty::PolyTraitRef<'tcx>,
1805 skol_trait_ref: ty::TraitRef<'tcx>,
1806 placeholder_map: &infer::PlaceholderMap<'tcx>,
1807 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
1809 debug_assert!(!skol_trait_ref.has_escaping_bound_vars());
1811 .at(&obligation.cause, obligation.param_env)
1812 .sup(ty::Binder::dummy(skol_trait_ref), trait_bound)
1819 .leak_check(false, obligation.cause.span, placeholder_map, snapshot)
1823 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1824 /// supplied to find out whether it is listed among them.
1826 /// Never affects inference environment.
1827 fn assemble_candidates_from_caller_bounds<'o>(
1829 stack: &TraitObligationStack<'o, 'tcx>,
1830 candidates: &mut SelectionCandidateSet<'tcx>,
1831 ) -> Result<(), SelectionError<'tcx>> {
1833 "assemble_candidates_from_caller_bounds({:?})",
1837 let all_bounds = stack
1842 .filter_map(|o| o.to_opt_poly_trait_ref());
1844 // micro-optimization: filter out predicates relating to different
1846 let matching_bounds =
1847 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1849 // keep only those bounds which may apply, and propagate overflow if it occurs
1850 let mut param_candidates = vec![];
1851 for bound in matching_bounds {
1852 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1854 param_candidates.push(ParamCandidate(bound));
1858 candidates.vec.extend(param_candidates);
1863 fn evaluate_where_clause<'o>(
1865 stack: &TraitObligationStack<'o, 'tcx>,
1866 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1867 ) -> Result<EvaluationResult, OverflowError> {
1868 self.probe(move |this, _| {
1869 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1870 Ok(obligations) => {
1871 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1873 Err(()) => Ok(EvaluatedToErr),
1878 fn assemble_generator_candidates(
1880 obligation: &TraitObligation<'tcx>,
1881 candidates: &mut SelectionCandidateSet<'tcx>,
1882 ) -> Result<(), SelectionError<'tcx>> {
1883 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1887 // OK to skip binder because the substs on generator types never
1888 // touch bound regions, they just capture the in-scope
1889 // type/region parameters
1890 let self_ty = *obligation.self_ty().skip_binder();
1892 ty::Generator(..) => {
1894 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1898 candidates.vec.push(GeneratorCandidate);
1900 ty::Infer(ty::TyVar(_)) => {
1901 debug!("assemble_generator_candidates: ambiguous self-type");
1902 candidates.ambiguous = true;
1910 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1911 /// FnMut<..>` where `X` is a closure type.
1913 /// Note: the type parameters on a closure candidate are modeled as *output* type
1914 /// parameters and hence do not affect whether this trait is a match or not. They will be
1915 /// unified during the confirmation step.
1916 fn assemble_closure_candidates(
1918 obligation: &TraitObligation<'tcx>,
1919 candidates: &mut SelectionCandidateSet<'tcx>,
1920 ) -> Result<(), SelectionError<'tcx>> {
1921 let kind = match self.tcx()
1923 .fn_trait_kind(obligation.predicate.def_id())
1931 // OK to skip binder because the substs on closure types never
1932 // touch bound regions, they just capture the in-scope
1933 // type/region parameters
1934 match obligation.self_ty().skip_binder().sty {
1935 ty::Closure(closure_def_id, closure_substs) => {
1937 "assemble_unboxed_candidates: kind={:?} obligation={:?}",
1940 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1941 Some(closure_kind) => {
1943 "assemble_unboxed_candidates: closure_kind = {:?}",
1946 if closure_kind.extends(kind) {
1947 candidates.vec.push(ClosureCandidate);
1951 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1952 candidates.vec.push(ClosureCandidate);
1956 ty::Infer(ty::TyVar(_)) => {
1957 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1958 candidates.ambiguous = true;
1966 /// Implement one of the `Fn()` family for a fn pointer.
1967 fn assemble_fn_pointer_candidates(
1969 obligation: &TraitObligation<'tcx>,
1970 candidates: &mut SelectionCandidateSet<'tcx>,
1971 ) -> Result<(), SelectionError<'tcx>> {
1972 // We provide impl of all fn traits for fn pointers.
1975 .fn_trait_kind(obligation.predicate.def_id())
1981 // OK to skip binder because what we are inspecting doesn't involve bound regions
1982 let self_ty = *obligation.self_ty().skip_binder();
1984 ty::Infer(ty::TyVar(_)) => {
1985 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1986 candidates.ambiguous = true; // could wind up being a fn() type
1988 // provide an impl, but only for suitable `fn` pointers
1989 ty::FnDef(..) | ty::FnPtr(_) => {
1991 unsafety: hir::Unsafety::Normal,
1995 } = self_ty.fn_sig(self.tcx()).skip_binder()
1997 candidates.vec.push(FnPointerCandidate);
2006 /// Search for impls that might apply to `obligation`.
2007 fn assemble_candidates_from_impls(
2009 obligation: &TraitObligation<'tcx>,
2010 candidates: &mut SelectionCandidateSet<'tcx>,
2011 ) -> Result<(), SelectionError<'tcx>> {
2013 "assemble_candidates_from_impls(obligation={:?})",
2017 self.tcx().for_each_relevant_impl(
2018 obligation.predicate.def_id(),
2019 obligation.predicate.skip_binder().trait_ref.self_ty(),
2021 self.probe(|this, snapshot| {
2022 if let Ok(placeholder_map) = this.match_impl(impl_def_id, obligation, snapshot)
2024 candidates.vec.push(ImplCandidate(impl_def_id));
2026 // N.B., we can safely drop the placeholder map
2027 // since we are in a probe.
2028 mem::drop(placeholder_map);
2037 fn assemble_candidates_from_auto_impls(
2039 obligation: &TraitObligation<'tcx>,
2040 candidates: &mut SelectionCandidateSet<'tcx>,
2041 ) -> Result<(), SelectionError<'tcx>> {
2042 // OK to skip binder here because the tests we do below do not involve bound regions
2043 let self_ty = *obligation.self_ty().skip_binder();
2044 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2046 let def_id = obligation.predicate.def_id();
2048 if self.tcx().trait_is_auto(def_id) {
2050 ty::Dynamic(..) => {
2051 // For object types, we don't know what the closed
2052 // over types are. This means we conservatively
2053 // say nothing; a candidate may be added by
2054 // `assemble_candidates_from_object_ty`.
2056 ty::Foreign(..) => {
2057 // Since the contents of foreign types is unknown,
2058 // we don't add any `..` impl. Default traits could
2059 // still be provided by a manual implementation for
2060 // this trait and type.
2062 ty::Param(..) | ty::Projection(..) => {
2063 // In these cases, we don't know what the actual
2064 // type is. Therefore, we cannot break it down
2065 // into its constituent types. So we don't
2066 // consider the `..` impl but instead just add no
2067 // candidates: this means that typeck will only
2068 // succeed if there is another reason to believe
2069 // that this obligation holds. That could be a
2070 // where-clause or, in the case of an object type,
2071 // it could be that the object type lists the
2072 // trait (e.g., `Foo+Send : Send`). See
2073 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2074 // for an example of a test case that exercises
2077 ty::Infer(ty::TyVar(_)) => {
2078 // the auto impl might apply, we don't know
2079 candidates.ambiguous = true;
2081 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2088 /// Search for impls that might apply to `obligation`.
2089 fn assemble_candidates_from_object_ty(
2091 obligation: &TraitObligation<'tcx>,
2092 candidates: &mut SelectionCandidateSet<'tcx>,
2095 "assemble_candidates_from_object_ty(self_ty={:?})",
2096 obligation.self_ty().skip_binder()
2099 self.probe(|this, _snapshot| {
2100 // The code below doesn't care about regions, and the
2101 // self-ty here doesn't escape this probe, so just erase
2103 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
2104 let poly_trait_ref = match self_ty.sty {
2105 ty::Dynamic(ref data, ..) => {
2106 if data.auto_traits()
2107 .any(|did| did == obligation.predicate.def_id())
2110 "assemble_candidates_from_object_ty: matched builtin bound, \
2113 candidates.vec.push(BuiltinObjectCandidate);
2117 data.principal().with_self_ty(this.tcx(), self_ty)
2119 ty::Infer(ty::TyVar(_)) => {
2120 debug!("assemble_candidates_from_object_ty: ambiguous");
2121 candidates.ambiguous = true; // could wind up being an object type
2128 "assemble_candidates_from_object_ty: poly_trait_ref={:?}",
2132 // Count only those upcast versions that match the trait-ref
2133 // we are looking for. Specifically, do not only check for the
2134 // correct trait, but also the correct type parameters.
2135 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2136 // but `Foo` is declared as `trait Foo : Bar<u32>`.
2137 let upcast_trait_refs = util::supertraits(this.tcx(), poly_trait_ref)
2138 .filter(|upcast_trait_ref| {
2139 this.probe(|this, _| {
2140 let upcast_trait_ref = upcast_trait_ref.clone();
2141 this.match_poly_trait_ref(obligation, upcast_trait_ref)
2147 if upcast_trait_refs > 1 {
2148 // Can be upcast in many ways; need more type information.
2149 candidates.ambiguous = true;
2150 } else if upcast_trait_refs == 1 {
2151 candidates.vec.push(ObjectCandidate);
2156 /// Search for unsizing that might apply to `obligation`.
2157 fn assemble_candidates_for_unsizing(
2159 obligation: &TraitObligation<'tcx>,
2160 candidates: &mut SelectionCandidateSet<'tcx>,
2162 // We currently never consider higher-ranked obligations e.g.
2163 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2164 // because they are a priori invalid, and we could potentially add support
2165 // for them later, it's just that there isn't really a strong need for it.
2166 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2167 // impl, and those are generally applied to concrete types.
2169 // That said, one might try to write a fn with a where clause like
2170 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2171 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2172 // Still, you'd be more likely to write that where clause as
2174 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2175 // obligation above. Should be possible to extend this in the future.
2176 let source = match obligation.self_ty().no_bound_vars() {
2179 // Don't add any candidates if there are bound regions.
2183 let target = obligation
2191 "assemble_candidates_for_unsizing(source={:?}, target={:?})",
2195 let may_apply = match (&source.sty, &target.sty) {
2196 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2197 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2198 // Upcasts permit two things:
2200 // 1. Dropping builtin bounds, e.g., `Foo+Send` to `Foo`
2201 // 2. Tightening the region bound, e.g., `Foo+'a` to `Foo+'b` if `'a : 'b`
2203 // Note that neither of these changes requires any
2204 // change at runtime. Eventually this will be
2207 // We always upcast when we can because of reason
2208 // #2 (region bounds).
2209 data_a.principal().def_id() == data_b.principal().def_id()
2210 && data_b.auto_traits()
2211 // All of a's auto traits need to be in b's auto traits.
2212 .all(|b| data_a.auto_traits().any(|a| a == b))
2216 (_, &ty::Dynamic(..)) => true,
2218 // Ambiguous handling is below T -> Trait, because inference
2219 // variables can still implement Unsize<Trait> and nested
2220 // obligations will have the final say (likely deferred).
2221 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2222 debug!("assemble_candidates_for_unsizing: ambiguous");
2223 candidates.ambiguous = true;
2228 (&ty::Array(..), &ty::Slice(_)) => true,
2230 // Struct<T> -> Struct<U>.
2231 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2232 def_id_a == def_id_b
2235 // (.., T) -> (.., U).
2236 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2242 candidates.vec.push(BuiltinUnsizeCandidate);
2246 fn assemble_candidates_for_trait_alias(
2248 obligation: &TraitObligation<'tcx>,
2249 candidates: &mut SelectionCandidateSet<'tcx>,
2250 ) -> Result<(), SelectionError<'tcx>> {
2251 // OK to skip binder here because the tests we do below do not involve bound regions
2252 let self_ty = *obligation.self_ty().skip_binder();
2253 debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
2255 let def_id = obligation.predicate.def_id();
2257 if ty::is_trait_alias(self.tcx(), def_id) {
2258 candidates.vec.push(TraitAliasCandidate(def_id.clone()));
2264 ///////////////////////////////////////////////////////////////////////////
2267 // Winnowing is the process of attempting to resolve ambiguity by
2268 // probing further. During the winnowing process, we unify all
2269 // type variables and then we also attempt to evaluate recursive
2270 // bounds to see if they are satisfied.
2272 /// Returns true if `victim` should be dropped in favor of
2273 /// `other`. Generally speaking we will drop duplicate
2274 /// candidates and prefer where-clause candidates.
2276 /// See the comment for "SelectionCandidate" for more details.
2277 fn candidate_should_be_dropped_in_favor_of<'o>(
2279 victim: &EvaluatedCandidate<'tcx>,
2280 other: &EvaluatedCandidate<'tcx>,
2282 if victim.candidate == other.candidate {
2286 // Check if a bound would previously have been removed when normalizing
2287 // the param_env so that it can be given the lowest priority. See
2288 // #50825 for the motivation for this.
2290 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2292 match other.candidate {
2293 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2294 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2295 // lifetime of a variable.
2296 BuiltinCandidate { has_nested: false } => true,
2297 ParamCandidate(ref cand) => match victim.candidate {
2298 AutoImplCandidate(..) => {
2300 "default implementations shouldn't be recorded \
2301 when there are other valid candidates"
2304 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2305 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2306 // lifetime of a variable.
2307 BuiltinCandidate { has_nested: false } => false,
2310 | GeneratorCandidate
2311 | FnPointerCandidate
2312 | BuiltinObjectCandidate
2313 | BuiltinUnsizeCandidate
2314 | BuiltinCandidate { .. }
2315 | TraitAliasCandidate(..) => {
2316 // Global bounds from the where clause should be ignored
2317 // here (see issue #50825). Otherwise, we have a where
2318 // clause so don't go around looking for impls.
2321 ObjectCandidate | ProjectionCandidate => {
2322 // Arbitrarily give param candidates priority
2323 // over projection and object candidates.
2326 ParamCandidate(..) => false,
2328 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2329 AutoImplCandidate(..) => {
2331 "default implementations shouldn't be recorded \
2332 when there are other valid candidates"
2335 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2336 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2337 // lifetime of a variable.
2338 BuiltinCandidate { has_nested: false } => false,
2341 | GeneratorCandidate
2342 | FnPointerCandidate
2343 | BuiltinObjectCandidate
2344 | BuiltinUnsizeCandidate
2345 | BuiltinCandidate { .. }
2346 | TraitAliasCandidate(..) => true,
2347 ObjectCandidate | ProjectionCandidate => {
2348 // Arbitrarily give param candidates priority
2349 // over projection and object candidates.
2352 ParamCandidate(ref cand) => is_global(cand),
2354 ImplCandidate(other_def) => {
2355 // See if we can toss out `victim` based on specialization.
2356 // This requires us to know *for sure* that the `other` impl applies
2357 // i.e., EvaluatedToOk:
2358 if other.evaluation == EvaluatedToOk {
2359 match victim.candidate {
2360 ImplCandidate(victim_def) => {
2361 let tcx = self.tcx().global_tcx();
2362 return tcx.specializes((other_def, victim_def))
2363 || tcx.impls_are_allowed_to_overlap(other_def, victim_def);
2365 ParamCandidate(ref cand) => {
2366 // Prefer the impl to a global where clause candidate.
2367 return is_global(cand);
2376 | GeneratorCandidate
2377 | FnPointerCandidate
2378 | BuiltinObjectCandidate
2379 | BuiltinUnsizeCandidate
2380 | BuiltinCandidate { has_nested: true } => {
2381 match victim.candidate {
2382 ParamCandidate(ref cand) => {
2383 // Prefer these to a global where-clause bound
2384 // (see issue #50825)
2385 is_global(cand) && other.evaluation == EvaluatedToOk
2394 ///////////////////////////////////////////////////////////////////////////
2397 // These cover the traits that are built-in to the language
2398 // itself: `Copy`, `Clone` and `Sized`.
2400 fn assemble_builtin_bound_candidates<'o>(
2402 conditions: BuiltinImplConditions<'tcx>,
2403 candidates: &mut SelectionCandidateSet<'tcx>,
2404 ) -> Result<(), SelectionError<'tcx>> {
2406 BuiltinImplConditions::Where(nested) => {
2407 debug!("builtin_bound: nested={:?}", nested);
2408 candidates.vec.push(BuiltinCandidate {
2409 has_nested: nested.skip_binder().len() > 0,
2412 BuiltinImplConditions::None => {}
2413 BuiltinImplConditions::Ambiguous => {
2414 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2415 candidates.ambiguous = true;
2422 fn sized_conditions(
2424 obligation: &TraitObligation<'tcx>,
2425 ) -> BuiltinImplConditions<'tcx> {
2426 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2428 // NOTE: binder moved to (*)
2429 let self_ty = self.infcx
2430 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2433 ty::Infer(ty::IntVar(_))
2434 | ty::Infer(ty::FloatVar(_))
2445 | ty::GeneratorWitness(..)
2450 // safe for everything
2451 Where(ty::Binder::dummy(Vec::new()))
2454 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2456 ty::Tuple(tys) => Where(ty::Binder::bind(tys.last().into_iter().cloned().collect())),
2458 ty::Adt(def, substs) => {
2459 let sized_crit = def.sized_constraint(self.tcx());
2460 // (*) binder moved here
2461 Where(ty::Binder::bind(
2464 .map(|ty| ty.subst(self.tcx(), substs))
2469 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2470 ty::Infer(ty::TyVar(_)) => Ambiguous,
2472 ty::UnnormalizedProjection(..)
2473 | ty::Placeholder(..)
2475 | ty::Infer(ty::FreshTy(_))
2476 | ty::Infer(ty::FreshIntTy(_))
2477 | ty::Infer(ty::FreshFloatTy(_)) => {
2479 "asked to assemble builtin bounds of unexpected type: {:?}",
2486 fn copy_clone_conditions(
2488 obligation: &TraitObligation<'tcx>,
2489 ) -> BuiltinImplConditions<'tcx> {
2490 // NOTE: binder moved to (*)
2491 let self_ty = self.infcx
2492 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2494 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2497 ty::Infer(ty::IntVar(_))
2498 | ty::Infer(ty::FloatVar(_))
2501 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2510 | ty::Ref(_, _, hir::MutImmutable) => {
2511 // Implementations provided in libcore
2519 | ty::GeneratorWitness(..)
2521 | ty::Ref(_, _, hir::MutMutable) => None,
2523 ty::Array(element_ty, _) => {
2524 // (*) binder moved here
2525 Where(ty::Binder::bind(vec![element_ty]))
2529 // (*) binder moved here
2530 Where(ty::Binder::bind(tys.to_vec()))
2533 ty::Closure(def_id, substs) => {
2534 let trait_id = obligation.predicate.def_id();
2535 let is_copy_trait = Some(trait_id) == self.tcx().lang_items().copy_trait();
2536 let is_clone_trait = Some(trait_id) == self.tcx().lang_items().clone_trait();
2537 if is_copy_trait || is_clone_trait {
2538 Where(ty::Binder::bind(
2539 substs.upvar_tys(def_id, self.tcx()).collect(),
2546 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2547 // Fallback to whatever user-defined impls exist in this case.
2551 ty::Infer(ty::TyVar(_)) => {
2552 // Unbound type variable. Might or might not have
2553 // applicable impls and so forth, depending on what
2554 // those type variables wind up being bound to.
2558 ty::UnnormalizedProjection(..)
2559 | ty::Placeholder(..)
2561 | ty::Infer(ty::FreshTy(_))
2562 | ty::Infer(ty::FreshIntTy(_))
2563 | ty::Infer(ty::FreshFloatTy(_)) => {
2565 "asked to assemble builtin bounds of unexpected type: {:?}",
2572 /// For default impls, we need to break apart a type into its
2573 /// "constituent types" -- meaning, the types that it contains.
2575 /// Here are some (simple) examples:
2578 /// (i32, u32) -> [i32, u32]
2579 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2580 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2581 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2583 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2593 | ty::Infer(ty::IntVar(_))
2594 | ty::Infer(ty::FloatVar(_))
2596 | ty::Char => Vec::new(),
2598 ty::UnnormalizedProjection(..)
2599 | ty::Placeholder(..)
2603 | ty::Projection(..)
2605 | ty::Infer(ty::TyVar(_))
2606 | ty::Infer(ty::FreshTy(_))
2607 | ty::Infer(ty::FreshIntTy(_))
2608 | ty::Infer(ty::FreshFloatTy(_)) => {
2610 "asked to assemble constituent types of unexpected type: {:?}",
2615 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2619 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2621 ty::Tuple(ref tys) => {
2622 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2626 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(),
2628 ty::Generator(def_id, ref substs, _) => {
2629 let witness = substs.witness(def_id, self.tcx());
2631 .upvar_tys(def_id, self.tcx())
2632 .chain(iter::once(witness))
2636 ty::GeneratorWitness(types) => {
2637 // This is sound because no regions in the witness can refer to
2638 // the binder outside the witness. So we'll effectivly reuse
2639 // the implicit binder around the witness.
2640 types.skip_binder().to_vec()
2643 // for `PhantomData<T>`, we pass `T`
2644 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2646 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2648 ty::Opaque(def_id, substs) => {
2649 // We can resolve the `impl Trait` to its concrete type,
2650 // which enforces a DAG between the functions requiring
2651 // the auto trait bounds in question.
2652 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2657 fn collect_predicates_for_types(
2659 param_env: ty::ParamEnv<'tcx>,
2660 cause: ObligationCause<'tcx>,
2661 recursion_depth: usize,
2662 trait_def_id: DefId,
2663 types: ty::Binder<Vec<Ty<'tcx>>>,
2664 ) -> Vec<PredicateObligation<'tcx>> {
2665 // Because the types were potentially derived from
2666 // higher-ranked obligations they may reference late-bound
2667 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2668 // yield a type like `for<'a> &'a int`. In general, we
2669 // maintain the invariant that we never manipulate bound
2670 // regions, so we have to process these bound regions somehow.
2672 // The strategy is to:
2674 // 1. Instantiate those regions to placeholder regions (e.g.,
2675 // `for<'a> &'a int` becomes `&0 int`.
2676 // 2. Produce something like `&'0 int : Copy`
2677 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2684 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2686 self.in_snapshot(|this, snapshot| {
2687 let (skol_ty, placeholder_map) = this.infcx()
2688 .replace_bound_vars_with_placeholders(&ty);
2690 value: normalized_ty,
2692 } = project::normalize_with_depth(
2699 let skol_obligation = this.tcx().predicate_for_trait_def(
2707 obligations.push(skol_obligation);
2709 .plug_leaks(placeholder_map, snapshot, obligations)
2715 ///////////////////////////////////////////////////////////////////////////
2718 // Confirmation unifies the output type parameters of the trait
2719 // with the values found in the obligation, possibly yielding a
2720 // type error. See the [rustc guide] for more details.
2723 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
2725 fn confirm_candidate(
2727 obligation: &TraitObligation<'tcx>,
2728 candidate: SelectionCandidate<'tcx>,
2729 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2730 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2733 BuiltinCandidate { has_nested } => {
2734 let data = self.confirm_builtin_candidate(obligation, has_nested);
2735 Ok(VtableBuiltin(data))
2738 ParamCandidate(param) => {
2739 let obligations = self.confirm_param_candidate(obligation, param);
2740 Ok(VtableParam(obligations))
2743 ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
2748 AutoImplCandidate(trait_def_id) => {
2749 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2750 Ok(VtableAutoImpl(data))
2753 ProjectionCandidate => {
2754 self.confirm_projection_candidate(obligation);
2755 Ok(VtableParam(Vec::new()))
2758 ClosureCandidate => {
2759 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2760 Ok(VtableClosure(vtable_closure))
2763 GeneratorCandidate => {
2764 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2765 Ok(VtableGenerator(vtable_generator))
2768 FnPointerCandidate => {
2769 let data = self.confirm_fn_pointer_candidate(obligation)?;
2770 Ok(VtableFnPointer(data))
2773 TraitAliasCandidate(alias_def_id) => {
2774 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2775 Ok(VtableTraitAlias(data))
2778 ObjectCandidate => {
2779 let data = self.confirm_object_candidate(obligation);
2780 Ok(VtableObject(data))
2783 BuiltinObjectCandidate => {
2784 // This indicates something like `(Trait+Send) :
2785 // Send`. In this case, we know that this holds
2786 // because that's what the object type is telling us,
2787 // and there's really no additional obligations to
2788 // prove and no types in particular to unify etc.
2789 Ok(VtableParam(Vec::new()))
2792 BuiltinUnsizeCandidate => {
2793 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2794 Ok(VtableBuiltin(data))
2799 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2800 self.in_snapshot(|this, snapshot| {
2802 this.match_projection_obligation_against_definition_bounds(obligation, snapshot);
2807 fn confirm_param_candidate(
2809 obligation: &TraitObligation<'tcx>,
2810 param: ty::PolyTraitRef<'tcx>,
2811 ) -> Vec<PredicateObligation<'tcx>> {
2812 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2814 // During evaluation, we already checked that this
2815 // where-clause trait-ref could be unified with the obligation
2816 // trait-ref. Repeat that unification now without any
2817 // transactional boundary; it should not fail.
2818 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2819 Ok(obligations) => obligations,
2822 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2830 fn confirm_builtin_candidate(
2832 obligation: &TraitObligation<'tcx>,
2834 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2836 "confirm_builtin_candidate({:?}, {:?})",
2837 obligation, has_nested
2840 let lang_items = self.tcx().lang_items();
2841 let obligations = if has_nested {
2842 let trait_def = obligation.predicate.def_id();
2843 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2844 self.sized_conditions(obligation)
2845 } else if Some(trait_def) == lang_items.copy_trait() {
2846 self.copy_clone_conditions(obligation)
2847 } else if Some(trait_def) == lang_items.clone_trait() {
2848 self.copy_clone_conditions(obligation)
2850 bug!("unexpected builtin trait {:?}", trait_def)
2852 let nested = match conditions {
2853 BuiltinImplConditions::Where(nested) => nested,
2855 "obligation {:?} had matched a builtin impl but now doesn't",
2860 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2861 self.collect_predicates_for_types(
2862 obligation.param_env,
2864 obligation.recursion_depth + 1,
2872 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2875 nested: obligations,
2879 /// This handles the case where a `auto trait Foo` impl is being used.
2880 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2882 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2883 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2884 fn confirm_auto_impl_candidate(
2886 obligation: &TraitObligation<'tcx>,
2887 trait_def_id: DefId,
2888 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2890 "confirm_auto_impl_candidate({:?}, {:?})",
2891 obligation, trait_def_id
2894 let types = obligation.predicate.map_bound(|inner| {
2895 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2896 self.constituent_types_for_ty(self_ty)
2898 self.vtable_auto_impl(obligation, trait_def_id, types)
2901 /// See `confirm_auto_impl_candidate`.
2902 fn vtable_auto_impl(
2904 obligation: &TraitObligation<'tcx>,
2905 trait_def_id: DefId,
2906 nested: ty::Binder<Vec<Ty<'tcx>>>,
2907 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2908 debug!("vtable_auto_impl: nested={:?}", nested);
2910 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2911 let mut obligations = self.collect_predicates_for_types(
2912 obligation.param_env,
2914 obligation.recursion_depth + 1,
2919 let trait_obligations: Vec<PredicateObligation<'_>> = self.in_snapshot(|this, snapshot| {
2920 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2921 let (trait_ref, placeholder_map) = this.infcx()
2922 .replace_bound_vars_with_placeholders(&poly_trait_ref);
2923 let cause = obligation.derived_cause(ImplDerivedObligation);
2924 this.impl_or_trait_obligations(
2926 obligation.recursion_depth + 1,
2927 obligation.param_env,
2935 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
2936 // predicate as usual. It won't have any effect since auto traits are coinductive.
2937 obligations.extend(trait_obligations);
2939 debug!("vtable_auto_impl: obligations={:?}", obligations);
2941 VtableAutoImplData {
2943 nested: obligations,
2947 fn confirm_impl_candidate(
2949 obligation: &TraitObligation<'tcx>,
2951 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2952 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
2954 // First, create the substitutions by matching the impl again,
2955 // this time not in a probe.
2956 self.in_snapshot(|this, snapshot| {
2957 let (substs, placeholder_map) = this.rematch_impl(impl_def_id, obligation, snapshot);
2958 debug!("confirm_impl_candidate: substs={:?}", substs);
2959 let cause = obligation.derived_cause(ImplDerivedObligation);
2964 obligation.recursion_depth + 1,
2965 obligation.param_env,
2975 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2976 cause: ObligationCause<'tcx>,
2977 recursion_depth: usize,
2978 param_env: ty::ParamEnv<'tcx>,
2979 placeholder_map: infer::PlaceholderMap<'tcx>,
2980 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
2981 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2983 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, placeholder_map={:?})",
2984 impl_def_id, substs, recursion_depth, placeholder_map
2987 let mut impl_obligations = self.impl_or_trait_obligations(
2998 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2999 impl_def_id, impl_obligations
3002 // Because of RFC447, the impl-trait-ref and obligations
3003 // are sufficient to determine the impl substs, without
3004 // relying on projections in the impl-trait-ref.
3006 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
3007 impl_obligations.append(&mut substs.obligations);
3011 substs: substs.value,
3012 nested: impl_obligations,
3016 fn confirm_object_candidate(
3018 obligation: &TraitObligation<'tcx>,
3019 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
3020 debug!("confirm_object_candidate({:?})", obligation);
3022 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
3023 // probably flatten the binder from the obligation and the binder
3024 // from the object. Have to try to make a broken test case that
3026 let self_ty = self.infcx
3027 .shallow_resolve(*obligation.self_ty().skip_binder());
3028 let poly_trait_ref = match self_ty.sty {
3029 ty::Dynamic(ref data, ..) => data.principal().with_self_ty(self.tcx(), self_ty),
3030 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
3033 let mut upcast_trait_ref = None;
3034 let mut nested = vec![];
3038 let tcx = self.tcx();
3040 // We want to find the first supertrait in the list of
3041 // supertraits that we can unify with, and do that
3042 // unification. We know that there is exactly one in the list
3043 // where we can unify because otherwise select would have
3044 // reported an ambiguity. (When we do find a match, also
3045 // record it for later.)
3046 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
3047 |&t| match self.commit_if_ok(|this, _| this.match_poly_trait_ref(obligation, t)) {
3048 Ok(obligations) => {
3049 upcast_trait_ref = Some(t);
3050 nested.extend(obligations);
3057 // Additionally, for each of the nonmatching predicates that
3058 // we pass over, we sum up the set of number of vtable
3059 // entries, so that we can compute the offset for the selected
3061 vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
3065 upcast_trait_ref: upcast_trait_ref.unwrap(),
3071 fn confirm_fn_pointer_candidate(
3073 obligation: &TraitObligation<'tcx>,
3074 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3075 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3077 // OK to skip binder; it is reintroduced below
3078 let self_ty = self.infcx
3079 .shallow_resolve(*obligation.self_ty().skip_binder());
3080 let sig = self_ty.fn_sig(self.tcx());
3081 let trait_ref = self.tcx()
3082 .closure_trait_ref_and_return_type(
3083 obligation.predicate.def_id(),
3086 util::TupleArgumentsFlag::Yes,
3088 .map_bound(|(trait_ref, _)| trait_ref);
3093 } = project::normalize_with_depth(
3095 obligation.param_env,
3096 obligation.cause.clone(),
3097 obligation.recursion_depth + 1,
3101 self.confirm_poly_trait_refs(
3102 obligation.cause.clone(),
3103 obligation.param_env,
3104 obligation.predicate.to_poly_trait_ref(),
3107 Ok(VtableFnPointerData {
3109 nested: obligations,
3113 fn confirm_trait_alias_candidate(
3115 obligation: &TraitObligation<'tcx>,
3116 alias_def_id: DefId,
3117 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3119 "confirm_trait_alias_candidate({:?}, {:?})",
3120 obligation, alias_def_id
3123 self.in_snapshot(|this, snapshot| {
3124 let (predicate, placeholder_map) = this.infcx()
3125 .replace_bound_vars_with_placeholders(&obligation.predicate);
3126 let trait_ref = predicate.trait_ref;
3127 let trait_def_id = trait_ref.def_id;
3128 let substs = trait_ref.substs;
3130 let trait_obligations = this.impl_or_trait_obligations(
3131 obligation.cause.clone(),
3132 obligation.recursion_depth,
3133 obligation.param_env,
3141 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3142 trait_def_id, trait_obligations
3145 VtableTraitAliasData {
3148 nested: trait_obligations,
3153 fn confirm_generator_candidate(
3155 obligation: &TraitObligation<'tcx>,
3156 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3157 // OK to skip binder because the substs on generator types never
3158 // touch bound regions, they just capture the in-scope
3159 // type/region parameters
3160 let self_ty = self.infcx
3161 .shallow_resolve(obligation.self_ty().skip_binder());
3162 let (generator_def_id, substs) = match self_ty.sty {
3163 ty::Generator(id, substs, _) => (id, substs),
3164 _ => bug!("closure candidate for non-closure {:?}", obligation),
3168 "confirm_generator_candidate({:?},{:?},{:?})",
3169 obligation, generator_def_id, substs
3172 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3176 } = normalize_with_depth(
3178 obligation.param_env,
3179 obligation.cause.clone(),
3180 obligation.recursion_depth + 1,
3185 "confirm_generator_candidate(generator_def_id={:?}, \
3186 trait_ref={:?}, obligations={:?})",
3187 generator_def_id, trait_ref, obligations
3190 obligations.extend(self.confirm_poly_trait_refs(
3191 obligation.cause.clone(),
3192 obligation.param_env,
3193 obligation.predicate.to_poly_trait_ref(),
3197 Ok(VtableGeneratorData {
3198 generator_def_id: generator_def_id,
3199 substs: substs.clone(),
3200 nested: obligations,
3204 fn confirm_closure_candidate(
3206 obligation: &TraitObligation<'tcx>,
3207 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3208 debug!("confirm_closure_candidate({:?})", obligation);
3210 let kind = self.tcx()
3212 .fn_trait_kind(obligation.predicate.def_id())
3213 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3215 // OK to skip binder because the substs on closure types never
3216 // touch bound regions, they just capture the in-scope
3217 // type/region parameters
3218 let self_ty = self.infcx
3219 .shallow_resolve(obligation.self_ty().skip_binder());
3220 let (closure_def_id, substs) = match self_ty.sty {
3221 ty::Closure(id, substs) => (id, substs),
3222 _ => bug!("closure candidate for non-closure {:?}", obligation),
3225 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3229 } = normalize_with_depth(
3231 obligation.param_env,
3232 obligation.cause.clone(),
3233 obligation.recursion_depth + 1,
3238 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3239 closure_def_id, trait_ref, obligations
3242 obligations.extend(self.confirm_poly_trait_refs(
3243 obligation.cause.clone(),
3244 obligation.param_env,
3245 obligation.predicate.to_poly_trait_ref(),
3249 obligations.push(Obligation::new(
3250 obligation.cause.clone(),
3251 obligation.param_env,
3252 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3255 Ok(VtableClosureData {
3257 substs: substs.clone(),
3258 nested: obligations,
3262 /// In the case of closure types and fn pointers,
3263 /// we currently treat the input type parameters on the trait as
3264 /// outputs. This means that when we have a match we have only
3265 /// considered the self type, so we have to go back and make sure
3266 /// to relate the argument types too. This is kind of wrong, but
3267 /// since we control the full set of impls, also not that wrong,
3268 /// and it DOES yield better error messages (since we don't report
3269 /// errors as if there is no applicable impl, but rather report
3270 /// errors are about mismatched argument types.
3272 /// Here is an example. Imagine we have a closure expression
3273 /// and we desugared it so that the type of the expression is
3274 /// `Closure`, and `Closure` expects an int as argument. Then it
3275 /// is "as if" the compiler generated this impl:
3277 /// impl Fn(int) for Closure { ... }
3279 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3280 /// we have matched the self-type `Closure`. At this point we'll
3281 /// compare the `int` to `usize` and generate an error.
3283 /// Note that this checking occurs *after* the impl has selected,
3284 /// because these output type parameters should not affect the
3285 /// selection of the impl. Therefore, if there is a mismatch, we
3286 /// report an error to the user.
3287 fn confirm_poly_trait_refs(
3289 obligation_cause: ObligationCause<'tcx>,
3290 obligation_param_env: ty::ParamEnv<'tcx>,
3291 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3292 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3293 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3294 let obligation_trait_ref = obligation_trait_ref.clone();
3296 .at(&obligation_cause, obligation_param_env)
3297 .sup(obligation_trait_ref, expected_trait_ref)
3298 .map(|InferOk { obligations, .. }| obligations)
3299 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3302 fn confirm_builtin_unsize_candidate(
3304 obligation: &TraitObligation<'tcx>,
3305 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3306 let tcx = self.tcx();
3308 // assemble_candidates_for_unsizing should ensure there are no late bound
3309 // regions here. See the comment there for more details.
3310 let source = self.infcx
3311 .shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3312 let target = obligation
3318 let target = self.infcx.shallow_resolve(target);
3321 "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
3325 let mut nested = vec![];
3326 match (&source.sty, &target.sty) {
3327 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3328 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3329 // See assemble_candidates_for_unsizing for more info.
3330 let existential_predicates = data_a.map_bound(|data_a| {
3331 let iter = iter::once(ty::ExistentialPredicate::Trait(data_a.principal()))
3334 .projection_bounds()
3335 .map(|x| ty::ExistentialPredicate::Projection(x)),
3340 .map(ty::ExistentialPredicate::AutoTrait),
3342 tcx.mk_existential_predicates(iter)
3344 let new_trait = tcx.mk_dynamic(existential_predicates, r_b);
3345 let InferOk { obligations, .. } = self.infcx
3346 .at(&obligation.cause, obligation.param_env)
3347 .eq(target, new_trait)
3348 .map_err(|_| Unimplemented)?;
3349 nested.extend(obligations);
3351 // Register one obligation for 'a: 'b.
3352 let cause = ObligationCause::new(
3353 obligation.cause.span,
3354 obligation.cause.body_id,
3355 ObjectCastObligation(target),
3357 let outlives = ty::OutlivesPredicate(r_a, r_b);
3358 nested.push(Obligation::with_depth(
3360 obligation.recursion_depth + 1,
3361 obligation.param_env,
3362 ty::Binder::bind(outlives).to_predicate(),
3367 (_, &ty::Dynamic(ref data, r)) => {
3368 let mut object_dids = data.auto_traits()
3369 .chain(iter::once(data.principal().def_id()));
3370 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3371 return Err(TraitNotObjectSafe(did));
3374 let cause = ObligationCause::new(
3375 obligation.cause.span,
3376 obligation.cause.body_id,
3377 ObjectCastObligation(target),
3380 let predicate_to_obligation = |predicate| {
3381 Obligation::with_depth(
3383 obligation.recursion_depth + 1,
3384 obligation.param_env,
3389 // Create obligations:
3390 // - Casting T to Trait
3391 // - For all the various builtin bounds attached to the object cast. (In other
3392 // words, if the object type is Foo+Send, this would create an obligation for the
3394 // - Projection predicates
3397 .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
3400 // We can only make objects from sized types.
3401 let tr = ty::TraitRef {
3402 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
3403 substs: tcx.mk_substs_trait(source, &[]),
3405 nested.push(predicate_to_obligation(tr.to_predicate()));
3407 // If the type is `Foo+'a`, ensures that the type
3408 // being cast to `Foo+'a` outlives `'a`:
3409 let outlives = ty::OutlivesPredicate(source, r);
3410 nested.push(predicate_to_obligation(
3411 ty::Binder::dummy(outlives).to_predicate(),
3416 (&ty::Array(a, _), &ty::Slice(b)) => {
3417 let InferOk { obligations, .. } = self.infcx
3418 .at(&obligation.cause, obligation.param_env)
3420 .map_err(|_| Unimplemented)?;
3421 nested.extend(obligations);
3424 // Struct<T> -> Struct<U>.
3425 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3426 let fields = def.all_fields()
3427 .map(|f| tcx.type_of(f.did))
3428 .collect::<Vec<_>>();
3430 // The last field of the structure has to exist and contain type parameters.
3431 let field = if let Some(&field) = fields.last() {
3434 return Err(Unimplemented);
3436 let mut ty_params = GrowableBitSet::new_empty();
3437 let mut found = false;
3438 for ty in field.walk() {
3439 if let ty::Param(p) = ty.sty {
3440 ty_params.insert(p.idx as usize);
3445 return Err(Unimplemented);
3448 // Replace type parameters used in unsizing with
3449 // Error and ensure they do not affect any other fields.
3450 // This could be checked after type collection for any struct
3451 // with a potentially unsized trailing field.
3452 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3453 if ty_params.contains(i) {
3454 tcx.types.err.into()
3459 let substs = tcx.mk_substs(params);
3460 for &ty in fields.split_last().unwrap().1 {
3461 if ty.subst(tcx, substs).references_error() {
3462 return Err(Unimplemented);
3466 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3467 let inner_source = field.subst(tcx, substs_a);
3468 let inner_target = field.subst(tcx, substs_b);
3470 // Check that the source struct with the target's
3471 // unsized parameters is equal to the target.
3472 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3473 if ty_params.contains(i) {
3474 substs_b.type_at(i).into()
3479 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3480 let InferOk { obligations, .. } = self.infcx
3481 .at(&obligation.cause, obligation.param_env)
3482 .eq(target, new_struct)
3483 .map_err(|_| Unimplemented)?;
3484 nested.extend(obligations);
3486 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3487 nested.push(tcx.predicate_for_trait_def(
3488 obligation.param_env,
3489 obligation.cause.clone(),
3490 obligation.predicate.def_id(),
3491 obligation.recursion_depth + 1,
3493 &[inner_target.into()],
3497 // (.., T) -> (.., U).
3498 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3499 assert_eq!(tys_a.len(), tys_b.len());
3501 // The last field of the tuple has to exist.
3502 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3505 return Err(Unimplemented);
3507 let &b_last = tys_b.last().unwrap();
3509 // Check that the source tuple with the target's
3510 // last element is equal to the target.
3511 let new_tuple = tcx.mk_tup(a_mid.iter().cloned().chain(iter::once(b_last)));
3512 let InferOk { obligations, .. } = self.infcx
3513 .at(&obligation.cause, obligation.param_env)
3514 .eq(target, new_tuple)
3515 .map_err(|_| Unimplemented)?;
3516 nested.extend(obligations);
3518 // Construct the nested T: Unsize<U> predicate.
3519 nested.push(tcx.predicate_for_trait_def(
3520 obligation.param_env,
3521 obligation.cause.clone(),
3522 obligation.predicate.def_id(),
3523 obligation.recursion_depth + 1,
3532 Ok(VtableBuiltinData { nested })
3535 ///////////////////////////////////////////////////////////////////////////
3538 // Matching is a common path used for both evaluation and
3539 // confirmation. It basically unifies types that appear in impls
3540 // and traits. This does affect the surrounding environment;
3541 // therefore, when used during evaluation, match routines must be
3542 // run inside of a `probe()` so that their side-effects are
3548 obligation: &TraitObligation<'tcx>,
3549 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3551 Normalized<'tcx, &'tcx Substs<'tcx>>,
3552 infer::PlaceholderMap<'tcx>,
3554 match self.match_impl(impl_def_id, obligation, snapshot) {
3555 Ok((substs, placeholder_map)) => (substs, placeholder_map),
3558 "Impl {:?} was matchable against {:?} but now is not",
3569 obligation: &TraitObligation<'tcx>,
3570 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3573 Normalized<'tcx, &'tcx Substs<'tcx>>,
3574 infer::PlaceholderMap<'tcx>,
3578 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3580 // Before we create the substitutions and everything, first
3581 // consider a "quick reject". This avoids creating more types
3582 // and so forth that we need to.
3583 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3587 let (skol_obligation, placeholder_map) = self.infcx()
3588 .replace_bound_vars_with_placeholders(&obligation.predicate);
3589 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3591 let impl_substs = self.infcx
3592 .fresh_substs_for_item(obligation.cause.span, impl_def_id);
3594 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3597 value: impl_trait_ref,
3598 obligations: mut nested_obligations,
3599 } = project::normalize_with_depth(
3601 obligation.param_env,
3602 obligation.cause.clone(),
3603 obligation.recursion_depth + 1,
3608 "match_impl(impl_def_id={:?}, obligation={:?}, \
3609 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3610 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3613 let InferOk { obligations, .. } = self.infcx
3614 .at(&obligation.cause, obligation.param_env)
3615 .eq(skol_obligation_trait_ref, impl_trait_ref)
3616 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3617 nested_obligations.extend(obligations);
3621 .leak_check(false, obligation.cause.span, &placeholder_map, snapshot)
3623 debug!("match_impl: failed leak check due to `{}`", e);
3627 debug!("match_impl: success impl_substs={:?}", impl_substs);
3631 obligations: nested_obligations,
3637 fn fast_reject_trait_refs(
3639 obligation: &TraitObligation<'_>,
3640 impl_trait_ref: &ty::TraitRef<'_>,
3642 // We can avoid creating type variables and doing the full
3643 // substitution if we find that any of the input types, when
3644 // simplified, do not match.
3650 .zip(impl_trait_ref.input_types())
3651 .any(|(obligation_ty, impl_ty)| {
3652 let simplified_obligation_ty =
3653 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3654 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3656 simplified_obligation_ty.is_some()
3657 && simplified_impl_ty.is_some()
3658 && simplified_obligation_ty != simplified_impl_ty
3662 /// Normalize `where_clause_trait_ref` and try to match it against
3663 /// `obligation`. If successful, return any predicates that
3664 /// result from the normalization. Normalization is necessary
3665 /// because where-clauses are stored in the parameter environment
3667 fn match_where_clause_trait_ref(
3669 obligation: &TraitObligation<'tcx>,
3670 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3671 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3672 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3675 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3676 /// obligation is satisfied.
3677 fn match_poly_trait_ref(
3679 obligation: &TraitObligation<'tcx>,
3680 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3681 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3683 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3684 obligation, poly_trait_ref
3688 .at(&obligation.cause, obligation.param_env)
3689 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3690 .map(|InferOk { obligations, .. }| obligations)
3694 ///////////////////////////////////////////////////////////////////////////
3697 fn match_fresh_trait_refs(
3699 previous: &ty::PolyTraitRef<'tcx>,
3700 current: &ty::PolyTraitRef<'tcx>,
3702 let mut matcher = ty::_match::Match::new(self.tcx());
3703 matcher.relate(previous, current).is_ok()
3706 fn push_stack<'o, 's: 'o>(
3708 previous_stack: TraitObligationStackList<'s, 'tcx>,
3709 obligation: &'o TraitObligation<'tcx>,
3710 ) -> TraitObligationStack<'o, 'tcx> {
3711 let fresh_trait_ref = obligation
3713 .to_poly_trait_ref()
3714 .fold_with(&mut self.freshener);
3716 TraitObligationStack {
3719 previous: previous_stack,
3723 fn closure_trait_ref_unnormalized(
3725 obligation: &TraitObligation<'tcx>,
3726 closure_def_id: DefId,
3727 substs: ty::ClosureSubsts<'tcx>,
3728 ) -> ty::PolyTraitRef<'tcx> {
3730 "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3731 obligation, closure_def_id, substs,
3733 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3736 "closure_trait_ref_unnormalized: closure_type = {:?}",
3740 // (1) Feels icky to skip the binder here, but OTOH we know
3741 // that the self-type is an unboxed closure type and hence is
3742 // in fact unparameterized (or at least does not reference any
3743 // regions bound in the obligation). Still probably some
3744 // refactoring could make this nicer.
3746 .closure_trait_ref_and_return_type(
3747 obligation.predicate.def_id(),
3748 obligation.predicate.skip_binder().self_ty(), // (1)
3750 util::TupleArgumentsFlag::No,
3752 .map_bound(|(trait_ref, _)| trait_ref)
3755 fn generator_trait_ref_unnormalized(
3757 obligation: &TraitObligation<'tcx>,
3758 closure_def_id: DefId,
3759 substs: ty::GeneratorSubsts<'tcx>,
3760 ) -> ty::PolyTraitRef<'tcx> {
3761 let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
3763 // (1) Feels icky to skip the binder here, but OTOH we know
3764 // that the self-type is an generator type and hence is
3765 // in fact unparameterized (or at least does not reference any
3766 // regions bound in the obligation). Still probably some
3767 // refactoring could make this nicer.
3770 .generator_trait_ref_and_outputs(
3771 obligation.predicate.def_id(),
3772 obligation.predicate.skip_binder().self_ty(), // (1)
3775 .map_bound(|(trait_ref, ..)| trait_ref)
3778 /// Returns the obligations that are implied by instantiating an
3779 /// impl or trait. The obligations are substituted and fully
3780 /// normalized. This is used when confirming an impl or default
3782 fn impl_or_trait_obligations(
3784 cause: ObligationCause<'tcx>,
3785 recursion_depth: usize,
3786 param_env: ty::ParamEnv<'tcx>,
3787 def_id: DefId, // of impl or trait
3788 substs: &Substs<'tcx>, // for impl or trait
3789 placeholder_map: infer::PlaceholderMap<'tcx>,
3790 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3791 ) -> Vec<PredicateObligation<'tcx>> {
3792 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3793 let tcx = self.tcx();
3795 // To allow for one-pass evaluation of the nested obligation,
3796 // each predicate must be preceded by the obligations required
3798 // for example, if we have:
3799 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3800 // the impl will have the following predicates:
3801 // <V as Iterator>::Item = U,
3802 // U: Iterator, U: Sized,
3803 // V: Iterator, V: Sized,
3804 // <U as Iterator>::Item: Copy
3805 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3806 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3807 // `$1: Copy`, so we must ensure the obligations are emitted in
3809 let predicates = tcx.predicates_of(def_id);
3810 assert_eq!(predicates.parent, None);
3811 let mut predicates: Vec<_> = predicates
3814 .flat_map(|(predicate, _)| {
3815 let predicate = normalize_with_depth(
3820 &predicate.subst(tcx, substs),
3822 predicate.obligations.into_iter().chain(Some(Obligation {
3823 cause: cause.clone(),
3826 predicate: predicate.value,
3831 // We are performing deduplication here to avoid exponential blowups
3832 // (#38528) from happening, but the real cause of the duplication is
3833 // unknown. What we know is that the deduplication avoids exponential
3834 // amount of predicates being propagated when processing deeply nested
3837 // This code is hot enough that it's worth avoiding the allocation
3838 // required for the FxHashSet when possible. Special-casing lengths 0,
3839 // 1 and 2 covers roughly 75--80% of the cases.
3840 if predicates.len() <= 1 {
3841 // No possibility of duplicates.
3842 } else if predicates.len() == 2 {
3843 // Only two elements. Drop the second if they are equal.
3844 if predicates[0] == predicates[1] {
3845 predicates.truncate(1);
3848 // Three or more elements. Use a general deduplication process.
3849 let mut seen = FxHashSet::default();
3850 predicates.retain(|i| seen.insert(i.clone()));
3853 .plug_leaks(placeholder_map, snapshot, predicates)
3857 impl<'tcx> TraitObligation<'tcx> {
3858 #[allow(unused_comparisons)]
3859 pub fn derived_cause(
3861 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3862 ) -> ObligationCause<'tcx> {
3864 * Creates a cause for obligations that are derived from
3865 * `obligation` by a recursive search (e.g., for a builtin
3866 * bound, or eventually a `auto trait Foo`). If `obligation`
3867 * is itself a derived obligation, this is just a clone, but
3868 * otherwise we create a "derived obligation" cause so as to
3869 * keep track of the original root obligation for error
3873 let obligation = self;
3875 // NOTE(flaper87): As of now, it keeps track of the whole error
3876 // chain. Ideally, we should have a way to configure this either
3877 // by using -Z verbose or just a CLI argument.
3878 if obligation.recursion_depth >= 0 {
3879 let derived_cause = DerivedObligationCause {
3880 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3881 parent_code: Rc::new(obligation.cause.code.clone()),
3883 let derived_code = variant(derived_cause);
3884 ObligationCause::new(
3885 obligation.cause.span,
3886 obligation.cause.body_id,
3890 obligation.cause.clone()
3895 impl<'tcx> SelectionCache<'tcx> {
3896 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3897 pub fn clear(&self) {
3898 *self.hashmap.borrow_mut() = Default::default();
3902 impl<'tcx> EvaluationCache<'tcx> {
3903 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3904 pub fn clear(&self) {
3905 *self.hashmap.borrow_mut() = Default::default();
3909 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
3910 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3911 TraitObligationStackList::with(self)
3914 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3919 #[derive(Copy, Clone)]
3920 struct TraitObligationStackList<'o, 'tcx: 'o> {
3921 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3924 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3925 fn empty() -> TraitObligationStackList<'o, 'tcx> {
3926 TraitObligationStackList { head: None }
3929 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3930 TraitObligationStackList { head: Some(r) }
3934 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
3935 type Item = &'o TraitObligationStack<'o, 'tcx>;
3937 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3948 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
3949 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3950 write!(f, "TraitObligationStack({:?})", self.obligation)
3954 #[derive(Clone, Eq, PartialEq)]
3955 pub struct WithDepNode<T> {
3956 dep_node: DepNodeIndex,
3960 impl<T: Clone> WithDepNode<T> {
3961 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3968 pub fn get(&self, tcx: TyCtxt<'_, '_, '_>) -> T {
3969 tcx.dep_graph.read_index(self.dep_node);
3970 self.cached_value.clone()