1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See [rustc guide] for more info on how this works.
13 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#selection
15 use self::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 [rustc guide] for more details.
1176 // https://rust-lang-nursery.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_late_bound_regions_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 // NB: 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(..)
2474 | ty::Infer(ty::FreshTy(_))
2475 | ty::Infer(ty::FreshIntTy(_))
2476 | ty::Infer(ty::FreshFloatTy(_)) => {
2478 "asked to assemble builtin bounds of unexpected type: {:?}",
2485 fn copy_clone_conditions(
2487 obligation: &TraitObligation<'tcx>,
2488 ) -> BuiltinImplConditions<'tcx> {
2489 // NOTE: binder moved to (*)
2490 let self_ty = self.infcx
2491 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2493 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2496 ty::Infer(ty::IntVar(_))
2497 | ty::Infer(ty::FloatVar(_))
2500 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2509 | ty::Ref(_, _, hir::MutImmutable) => {
2510 // Implementations provided in libcore
2518 | ty::GeneratorWitness(..)
2520 | ty::Ref(_, _, hir::MutMutable) => None,
2522 ty::Array(element_ty, _) => {
2523 // (*) binder moved here
2524 Where(ty::Binder::bind(vec![element_ty]))
2528 // (*) binder moved here
2529 Where(ty::Binder::bind(tys.to_vec()))
2532 ty::Closure(def_id, substs) => {
2533 let trait_id = obligation.predicate.def_id();
2534 let is_copy_trait = Some(trait_id) == self.tcx().lang_items().copy_trait();
2535 let is_clone_trait = Some(trait_id) == self.tcx().lang_items().clone_trait();
2536 if is_copy_trait || is_clone_trait {
2537 Where(ty::Binder::bind(
2538 substs.upvar_tys(def_id, self.tcx()).collect(),
2545 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2546 // Fallback to whatever user-defined impls exist in this case.
2550 ty::Infer(ty::TyVar(_)) => {
2551 // Unbound type variable. Might or might not have
2552 // applicable impls and so forth, depending on what
2553 // those type variables wind up being bound to.
2557 ty::UnnormalizedProjection(..)
2559 | ty::Infer(ty::FreshTy(_))
2560 | ty::Infer(ty::FreshIntTy(_))
2561 | ty::Infer(ty::FreshFloatTy(_)) => {
2563 "asked to assemble builtin bounds of unexpected type: {:?}",
2570 /// For default impls, we need to break apart a type into its
2571 /// "constituent types" -- meaning, the types that it contains.
2573 /// Here are some (simple) examples:
2576 /// (i32, u32) -> [i32, u32]
2577 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2578 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2579 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2581 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2591 | ty::Infer(ty::IntVar(_))
2592 | ty::Infer(ty::FloatVar(_))
2594 | ty::Char => Vec::new(),
2596 ty::UnnormalizedProjection(..)
2600 | ty::Projection(..)
2602 | ty::Infer(ty::TyVar(_))
2603 | ty::Infer(ty::FreshTy(_))
2604 | ty::Infer(ty::FreshIntTy(_))
2605 | ty::Infer(ty::FreshFloatTy(_)) => {
2607 "asked to assemble constituent types of unexpected type: {:?}",
2612 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2616 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2618 ty::Tuple(ref tys) => {
2619 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2623 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(),
2625 ty::Generator(def_id, ref substs, _) => {
2626 let witness = substs.witness(def_id, self.tcx());
2628 .upvar_tys(def_id, self.tcx())
2629 .chain(iter::once(witness))
2633 ty::GeneratorWitness(types) => {
2634 // This is sound because no regions in the witness can refer to
2635 // the binder outside the witness. So we'll effectivly reuse
2636 // the implicit binder around the witness.
2637 types.skip_binder().to_vec()
2640 // for `PhantomData<T>`, we pass `T`
2641 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2643 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2645 ty::Opaque(def_id, substs) => {
2646 // We can resolve the `impl Trait` to its concrete type,
2647 // which enforces a DAG between the functions requiring
2648 // the auto trait bounds in question.
2649 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2654 fn collect_predicates_for_types(
2656 param_env: ty::ParamEnv<'tcx>,
2657 cause: ObligationCause<'tcx>,
2658 recursion_depth: usize,
2659 trait_def_id: DefId,
2660 types: ty::Binder<Vec<Ty<'tcx>>>,
2661 ) -> Vec<PredicateObligation<'tcx>> {
2662 // Because the types were potentially derived from
2663 // higher-ranked obligations they may reference late-bound
2664 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2665 // yield a type like `for<'a> &'a int`. In general, we
2666 // maintain the invariant that we never manipulate bound
2667 // regions, so we have to process these bound regions somehow.
2669 // The strategy is to:
2671 // 1. Instantiate those regions to placeholder regions (e.g.,
2672 // `for<'a> &'a int` becomes `&0 int`.
2673 // 2. Produce something like `&'0 int : Copy`
2674 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2681 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2683 self.in_snapshot(|this, snapshot| {
2684 let (skol_ty, placeholder_map) = this.infcx()
2685 .replace_late_bound_regions_with_placeholders(&ty);
2687 value: normalized_ty,
2689 } = project::normalize_with_depth(
2696 let skol_obligation = this.tcx().predicate_for_trait_def(
2704 obligations.push(skol_obligation);
2706 .plug_leaks(placeholder_map, snapshot, obligations)
2712 ///////////////////////////////////////////////////////////////////////////
2715 // Confirmation unifies the output type parameters of the trait
2716 // with the values found in the obligation, possibly yielding a
2717 // type error. See [rustc guide] for more details.
2720 // https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#confirmation
2722 fn confirm_candidate(
2724 obligation: &TraitObligation<'tcx>,
2725 candidate: SelectionCandidate<'tcx>,
2726 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2727 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2730 BuiltinCandidate { has_nested } => {
2731 let data = self.confirm_builtin_candidate(obligation, has_nested);
2732 Ok(VtableBuiltin(data))
2735 ParamCandidate(param) => {
2736 let obligations = self.confirm_param_candidate(obligation, param);
2737 Ok(VtableParam(obligations))
2740 ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
2745 AutoImplCandidate(trait_def_id) => {
2746 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2747 Ok(VtableAutoImpl(data))
2750 ProjectionCandidate => {
2751 self.confirm_projection_candidate(obligation);
2752 Ok(VtableParam(Vec::new()))
2755 ClosureCandidate => {
2756 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2757 Ok(VtableClosure(vtable_closure))
2760 GeneratorCandidate => {
2761 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2762 Ok(VtableGenerator(vtable_generator))
2765 FnPointerCandidate => {
2766 let data = self.confirm_fn_pointer_candidate(obligation)?;
2767 Ok(VtableFnPointer(data))
2770 TraitAliasCandidate(alias_def_id) => {
2771 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2772 Ok(VtableTraitAlias(data))
2775 ObjectCandidate => {
2776 let data = self.confirm_object_candidate(obligation);
2777 Ok(VtableObject(data))
2780 BuiltinObjectCandidate => {
2781 // This indicates something like `(Trait+Send) :
2782 // Send`. In this case, we know that this holds
2783 // because that's what the object type is telling us,
2784 // and there's really no additional obligations to
2785 // prove and no types in particular to unify etc.
2786 Ok(VtableParam(Vec::new()))
2789 BuiltinUnsizeCandidate => {
2790 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2791 Ok(VtableBuiltin(data))
2796 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2797 self.in_snapshot(|this, snapshot| {
2799 this.match_projection_obligation_against_definition_bounds(obligation, snapshot);
2804 fn confirm_param_candidate(
2806 obligation: &TraitObligation<'tcx>,
2807 param: ty::PolyTraitRef<'tcx>,
2808 ) -> Vec<PredicateObligation<'tcx>> {
2809 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2811 // During evaluation, we already checked that this
2812 // where-clause trait-ref could be unified with the obligation
2813 // trait-ref. Repeat that unification now without any
2814 // transactional boundary; it should not fail.
2815 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2816 Ok(obligations) => obligations,
2819 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2827 fn confirm_builtin_candidate(
2829 obligation: &TraitObligation<'tcx>,
2831 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2833 "confirm_builtin_candidate({:?}, {:?})",
2834 obligation, has_nested
2837 let lang_items = self.tcx().lang_items();
2838 let obligations = if has_nested {
2839 let trait_def = obligation.predicate.def_id();
2840 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2841 self.sized_conditions(obligation)
2842 } else if Some(trait_def) == lang_items.copy_trait() {
2843 self.copy_clone_conditions(obligation)
2844 } else if Some(trait_def) == lang_items.clone_trait() {
2845 self.copy_clone_conditions(obligation)
2847 bug!("unexpected builtin trait {:?}", trait_def)
2849 let nested = match conditions {
2850 BuiltinImplConditions::Where(nested) => nested,
2852 "obligation {:?} had matched a builtin impl but now doesn't",
2857 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2858 self.collect_predicates_for_types(
2859 obligation.param_env,
2861 obligation.recursion_depth + 1,
2869 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2872 nested: obligations,
2876 /// This handles the case where a `auto trait Foo` impl is being used.
2877 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2879 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2880 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2881 fn confirm_auto_impl_candidate(
2883 obligation: &TraitObligation<'tcx>,
2884 trait_def_id: DefId,
2885 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2887 "confirm_auto_impl_candidate({:?}, {:?})",
2888 obligation, trait_def_id
2891 let types = obligation.predicate.map_bound(|inner| {
2892 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2893 self.constituent_types_for_ty(self_ty)
2895 self.vtable_auto_impl(obligation, trait_def_id, types)
2898 /// See `confirm_auto_impl_candidate`.
2899 fn vtable_auto_impl(
2901 obligation: &TraitObligation<'tcx>,
2902 trait_def_id: DefId,
2903 nested: ty::Binder<Vec<Ty<'tcx>>>,
2904 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2905 debug!("vtable_auto_impl: nested={:?}", nested);
2907 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2908 let mut obligations = self.collect_predicates_for_types(
2909 obligation.param_env,
2911 obligation.recursion_depth + 1,
2916 let trait_obligations: Vec<PredicateObligation<'_>> = self.in_snapshot(|this, snapshot| {
2917 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2918 let (trait_ref, placeholder_map) = this.infcx()
2919 .replace_late_bound_regions_with_placeholders(&poly_trait_ref);
2920 let cause = obligation.derived_cause(ImplDerivedObligation);
2921 this.impl_or_trait_obligations(
2923 obligation.recursion_depth + 1,
2924 obligation.param_env,
2932 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
2933 // predicate as usual. It won't have any effect since auto traits are coinductive.
2934 obligations.extend(trait_obligations);
2936 debug!("vtable_auto_impl: obligations={:?}", obligations);
2938 VtableAutoImplData {
2940 nested: obligations,
2944 fn confirm_impl_candidate(
2946 obligation: &TraitObligation<'tcx>,
2948 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2949 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
2951 // First, create the substitutions by matching the impl again,
2952 // this time not in a probe.
2953 self.in_snapshot(|this, snapshot| {
2954 let (substs, placeholder_map) = this.rematch_impl(impl_def_id, obligation, snapshot);
2955 debug!("confirm_impl_candidate: substs={:?}", substs);
2956 let cause = obligation.derived_cause(ImplDerivedObligation);
2961 obligation.recursion_depth + 1,
2962 obligation.param_env,
2972 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2973 cause: ObligationCause<'tcx>,
2974 recursion_depth: usize,
2975 param_env: ty::ParamEnv<'tcx>,
2976 placeholder_map: infer::PlaceholderMap<'tcx>,
2977 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
2978 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2980 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, placeholder_map={:?})",
2981 impl_def_id, substs, recursion_depth, placeholder_map
2984 let mut impl_obligations = self.impl_or_trait_obligations(
2995 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2996 impl_def_id, impl_obligations
2999 // Because of RFC447, the impl-trait-ref and obligations
3000 // are sufficient to determine the impl substs, without
3001 // relying on projections in the impl-trait-ref.
3003 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
3004 impl_obligations.append(&mut substs.obligations);
3008 substs: substs.value,
3009 nested: impl_obligations,
3013 fn confirm_object_candidate(
3015 obligation: &TraitObligation<'tcx>,
3016 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
3017 debug!("confirm_object_candidate({:?})", obligation);
3019 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
3020 // probably flatten the binder from the obligation and the binder
3021 // from the object. Have to try to make a broken test case that
3023 let self_ty = self.infcx
3024 .shallow_resolve(*obligation.self_ty().skip_binder());
3025 let poly_trait_ref = match self_ty.sty {
3026 ty::Dynamic(ref data, ..) => data.principal().with_self_ty(self.tcx(), self_ty),
3027 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
3030 let mut upcast_trait_ref = None;
3031 let mut nested = vec![];
3035 let tcx = self.tcx();
3037 // We want to find the first supertrait in the list of
3038 // supertraits that we can unify with, and do that
3039 // unification. We know that there is exactly one in the list
3040 // where we can unify because otherwise select would have
3041 // reported an ambiguity. (When we do find a match, also
3042 // record it for later.)
3043 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
3044 |&t| match self.commit_if_ok(|this, _| this.match_poly_trait_ref(obligation, t)) {
3045 Ok(obligations) => {
3046 upcast_trait_ref = Some(t);
3047 nested.extend(obligations);
3054 // Additionally, for each of the nonmatching predicates that
3055 // we pass over, we sum up the set of number of vtable
3056 // entries, so that we can compute the offset for the selected
3058 vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
3062 upcast_trait_ref: upcast_trait_ref.unwrap(),
3068 fn confirm_fn_pointer_candidate(
3070 obligation: &TraitObligation<'tcx>,
3071 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3072 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3074 // OK to skip binder; it is reintroduced below
3075 let self_ty = self.infcx
3076 .shallow_resolve(*obligation.self_ty().skip_binder());
3077 let sig = self_ty.fn_sig(self.tcx());
3078 let trait_ref = self.tcx()
3079 .closure_trait_ref_and_return_type(
3080 obligation.predicate.def_id(),
3083 util::TupleArgumentsFlag::Yes,
3085 .map_bound(|(trait_ref, _)| trait_ref);
3090 } = project::normalize_with_depth(
3092 obligation.param_env,
3093 obligation.cause.clone(),
3094 obligation.recursion_depth + 1,
3098 self.confirm_poly_trait_refs(
3099 obligation.cause.clone(),
3100 obligation.param_env,
3101 obligation.predicate.to_poly_trait_ref(),
3104 Ok(VtableFnPointerData {
3106 nested: obligations,
3110 fn confirm_trait_alias_candidate(
3112 obligation: &TraitObligation<'tcx>,
3113 alias_def_id: DefId,
3114 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3116 "confirm_trait_alias_candidate({:?}, {:?})",
3117 obligation, alias_def_id
3120 self.in_snapshot(|this, snapshot| {
3121 let (predicate, placeholder_map) = this.infcx()
3122 .replace_late_bound_regions_with_placeholders(&obligation.predicate);
3123 let trait_ref = predicate.trait_ref;
3124 let trait_def_id = trait_ref.def_id;
3125 let substs = trait_ref.substs;
3127 let trait_obligations = this.impl_or_trait_obligations(
3128 obligation.cause.clone(),
3129 obligation.recursion_depth,
3130 obligation.param_env,
3138 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3139 trait_def_id, trait_obligations
3142 VtableTraitAliasData {
3145 nested: trait_obligations,
3150 fn confirm_generator_candidate(
3152 obligation: &TraitObligation<'tcx>,
3153 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3154 // OK to skip binder because the substs on generator types never
3155 // touch bound regions, they just capture the in-scope
3156 // type/region parameters
3157 let self_ty = self.infcx
3158 .shallow_resolve(obligation.self_ty().skip_binder());
3159 let (generator_def_id, substs) = match self_ty.sty {
3160 ty::Generator(id, substs, _) => (id, substs),
3161 _ => bug!("closure candidate for non-closure {:?}", obligation),
3165 "confirm_generator_candidate({:?},{:?},{:?})",
3166 obligation, generator_def_id, substs
3169 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3173 } = normalize_with_depth(
3175 obligation.param_env,
3176 obligation.cause.clone(),
3177 obligation.recursion_depth + 1,
3182 "confirm_generator_candidate(generator_def_id={:?}, \
3183 trait_ref={:?}, obligations={:?})",
3184 generator_def_id, trait_ref, obligations
3187 obligations.extend(self.confirm_poly_trait_refs(
3188 obligation.cause.clone(),
3189 obligation.param_env,
3190 obligation.predicate.to_poly_trait_ref(),
3194 Ok(VtableGeneratorData {
3195 generator_def_id: generator_def_id,
3196 substs: substs.clone(),
3197 nested: obligations,
3201 fn confirm_closure_candidate(
3203 obligation: &TraitObligation<'tcx>,
3204 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3205 debug!("confirm_closure_candidate({:?})", obligation);
3207 let kind = self.tcx()
3209 .fn_trait_kind(obligation.predicate.def_id())
3210 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3212 // OK to skip binder because the substs on closure types never
3213 // touch bound regions, they just capture the in-scope
3214 // type/region parameters
3215 let self_ty = self.infcx
3216 .shallow_resolve(obligation.self_ty().skip_binder());
3217 let (closure_def_id, substs) = match self_ty.sty {
3218 ty::Closure(id, substs) => (id, substs),
3219 _ => bug!("closure candidate for non-closure {:?}", obligation),
3222 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3226 } = normalize_with_depth(
3228 obligation.param_env,
3229 obligation.cause.clone(),
3230 obligation.recursion_depth + 1,
3235 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3236 closure_def_id, trait_ref, obligations
3239 obligations.extend(self.confirm_poly_trait_refs(
3240 obligation.cause.clone(),
3241 obligation.param_env,
3242 obligation.predicate.to_poly_trait_ref(),
3246 obligations.push(Obligation::new(
3247 obligation.cause.clone(),
3248 obligation.param_env,
3249 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3252 Ok(VtableClosureData {
3254 substs: substs.clone(),
3255 nested: obligations,
3259 /// In the case of closure types and fn pointers,
3260 /// we currently treat the input type parameters on the trait as
3261 /// outputs. This means that when we have a match we have only
3262 /// considered the self type, so we have to go back and make sure
3263 /// to relate the argument types too. This is kind of wrong, but
3264 /// since we control the full set of impls, also not that wrong,
3265 /// and it DOES yield better error messages (since we don't report
3266 /// errors as if there is no applicable impl, but rather report
3267 /// errors are about mismatched argument types.
3269 /// Here is an example. Imagine we have a closure expression
3270 /// and we desugared it so that the type of the expression is
3271 /// `Closure`, and `Closure` expects an int as argument. Then it
3272 /// is "as if" the compiler generated this impl:
3274 /// impl Fn(int) for Closure { ... }
3276 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3277 /// we have matched the self-type `Closure`. At this point we'll
3278 /// compare the `int` to `usize` and generate an error.
3280 /// Note that this checking occurs *after* the impl has selected,
3281 /// because these output type parameters should not affect the
3282 /// selection of the impl. Therefore, if there is a mismatch, we
3283 /// report an error to the user.
3284 fn confirm_poly_trait_refs(
3286 obligation_cause: ObligationCause<'tcx>,
3287 obligation_param_env: ty::ParamEnv<'tcx>,
3288 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3289 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3290 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3291 let obligation_trait_ref = obligation_trait_ref.clone();
3293 .at(&obligation_cause, obligation_param_env)
3294 .sup(obligation_trait_ref, expected_trait_ref)
3295 .map(|InferOk { obligations, .. }| obligations)
3296 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3299 fn confirm_builtin_unsize_candidate(
3301 obligation: &TraitObligation<'tcx>,
3302 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3303 let tcx = self.tcx();
3305 // assemble_candidates_for_unsizing should ensure there are no late bound
3306 // regions here. See the comment there for more details.
3307 let source = self.infcx
3308 .shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3309 let target = obligation
3315 let target = self.infcx.shallow_resolve(target);
3318 "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
3322 let mut nested = vec![];
3323 match (&source.sty, &target.sty) {
3324 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3325 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3326 // See assemble_candidates_for_unsizing for more info.
3327 let existential_predicates = data_a.map_bound(|data_a| {
3328 let iter = iter::once(ty::ExistentialPredicate::Trait(data_a.principal()))
3331 .projection_bounds()
3332 .map(|x| ty::ExistentialPredicate::Projection(x)),
3337 .map(ty::ExistentialPredicate::AutoTrait),
3339 tcx.mk_existential_predicates(iter)
3341 let new_trait = tcx.mk_dynamic(existential_predicates, r_b);
3342 let InferOk { obligations, .. } = self.infcx
3343 .at(&obligation.cause, obligation.param_env)
3344 .eq(target, new_trait)
3345 .map_err(|_| Unimplemented)?;
3346 nested.extend(obligations);
3348 // Register one obligation for 'a: 'b.
3349 let cause = ObligationCause::new(
3350 obligation.cause.span,
3351 obligation.cause.body_id,
3352 ObjectCastObligation(target),
3354 let outlives = ty::OutlivesPredicate(r_a, r_b);
3355 nested.push(Obligation::with_depth(
3357 obligation.recursion_depth + 1,
3358 obligation.param_env,
3359 ty::Binder::bind(outlives).to_predicate(),
3364 (_, &ty::Dynamic(ref data, r)) => {
3365 let mut object_dids = data.auto_traits()
3366 .chain(iter::once(data.principal().def_id()));
3367 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3368 return Err(TraitNotObjectSafe(did));
3371 let cause = ObligationCause::new(
3372 obligation.cause.span,
3373 obligation.cause.body_id,
3374 ObjectCastObligation(target),
3377 let predicate_to_obligation = |predicate| {
3378 Obligation::with_depth(
3380 obligation.recursion_depth + 1,
3381 obligation.param_env,
3386 // Create obligations:
3387 // - Casting T to Trait
3388 // - For all the various builtin bounds attached to the object cast. (In other
3389 // words, if the object type is Foo+Send, this would create an obligation for the
3391 // - Projection predicates
3394 .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
3397 // We can only make objects from sized types.
3398 let tr = ty::TraitRef {
3399 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
3400 substs: tcx.mk_substs_trait(source, &[]),
3402 nested.push(predicate_to_obligation(tr.to_predicate()));
3404 // If the type is `Foo+'a`, ensures that the type
3405 // being cast to `Foo+'a` outlives `'a`:
3406 let outlives = ty::OutlivesPredicate(source, r);
3407 nested.push(predicate_to_obligation(
3408 ty::Binder::dummy(outlives).to_predicate(),
3413 (&ty::Array(a, _), &ty::Slice(b)) => {
3414 let InferOk { obligations, .. } = self.infcx
3415 .at(&obligation.cause, obligation.param_env)
3417 .map_err(|_| Unimplemented)?;
3418 nested.extend(obligations);
3421 // Struct<T> -> Struct<U>.
3422 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3423 let fields = def.all_fields()
3424 .map(|f| tcx.type_of(f.did))
3425 .collect::<Vec<_>>();
3427 // The last field of the structure has to exist and contain type parameters.
3428 let field = if let Some(&field) = fields.last() {
3431 return Err(Unimplemented);
3433 let mut ty_params = GrowableBitSet::new_empty();
3434 let mut found = false;
3435 for ty in field.walk() {
3436 if let ty::Param(p) = ty.sty {
3437 ty_params.insert(p.idx as usize);
3442 return Err(Unimplemented);
3445 // Replace type parameters used in unsizing with
3446 // Error and ensure they do not affect any other fields.
3447 // This could be checked after type collection for any struct
3448 // with a potentially unsized trailing field.
3449 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3450 if ty_params.contains(i) {
3451 tcx.types.err.into()
3456 let substs = tcx.mk_substs(params);
3457 for &ty in fields.split_last().unwrap().1 {
3458 if ty.subst(tcx, substs).references_error() {
3459 return Err(Unimplemented);
3463 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3464 let inner_source = field.subst(tcx, substs_a);
3465 let inner_target = field.subst(tcx, substs_b);
3467 // Check that the source struct with the target's
3468 // unsized parameters is equal to the target.
3469 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3470 if ty_params.contains(i) {
3471 substs_b.type_at(i).into()
3476 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3477 let InferOk { obligations, .. } = self.infcx
3478 .at(&obligation.cause, obligation.param_env)
3479 .eq(target, new_struct)
3480 .map_err(|_| Unimplemented)?;
3481 nested.extend(obligations);
3483 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3484 nested.push(tcx.predicate_for_trait_def(
3485 obligation.param_env,
3486 obligation.cause.clone(),
3487 obligation.predicate.def_id(),
3488 obligation.recursion_depth + 1,
3490 &[inner_target.into()],
3494 // (.., T) -> (.., U).
3495 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3496 assert_eq!(tys_a.len(), tys_b.len());
3498 // The last field of the tuple has to exist.
3499 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3502 return Err(Unimplemented);
3504 let &b_last = tys_b.last().unwrap();
3506 // Check that the source tuple with the target's
3507 // last element is equal to the target.
3508 let new_tuple = tcx.mk_tup(a_mid.iter().cloned().chain(iter::once(b_last)));
3509 let InferOk { obligations, .. } = self.infcx
3510 .at(&obligation.cause, obligation.param_env)
3511 .eq(target, new_tuple)
3512 .map_err(|_| Unimplemented)?;
3513 nested.extend(obligations);
3515 // Construct the nested T: Unsize<U> predicate.
3516 nested.push(tcx.predicate_for_trait_def(
3517 obligation.param_env,
3518 obligation.cause.clone(),
3519 obligation.predicate.def_id(),
3520 obligation.recursion_depth + 1,
3529 Ok(VtableBuiltinData { nested })
3532 ///////////////////////////////////////////////////////////////////////////
3535 // Matching is a common path used for both evaluation and
3536 // confirmation. It basically unifies types that appear in impls
3537 // and traits. This does affect the surrounding environment;
3538 // therefore, when used during evaluation, match routines must be
3539 // run inside of a `probe()` so that their side-effects are
3545 obligation: &TraitObligation<'tcx>,
3546 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3548 Normalized<'tcx, &'tcx Substs<'tcx>>,
3549 infer::PlaceholderMap<'tcx>,
3551 match self.match_impl(impl_def_id, obligation, snapshot) {
3552 Ok((substs, placeholder_map)) => (substs, placeholder_map),
3555 "Impl {:?} was matchable against {:?} but now is not",
3566 obligation: &TraitObligation<'tcx>,
3567 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3570 Normalized<'tcx, &'tcx Substs<'tcx>>,
3571 infer::PlaceholderMap<'tcx>,
3575 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3577 // Before we create the substitutions and everything, first
3578 // consider a "quick reject". This avoids creating more types
3579 // and so forth that we need to.
3580 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3584 let (skol_obligation, placeholder_map) = self.infcx()
3585 .replace_late_bound_regions_with_placeholders(&obligation.predicate);
3586 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3588 let impl_substs = self.infcx
3589 .fresh_substs_for_item(obligation.cause.span, impl_def_id);
3591 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3594 value: impl_trait_ref,
3595 obligations: mut nested_obligations,
3596 } = project::normalize_with_depth(
3598 obligation.param_env,
3599 obligation.cause.clone(),
3600 obligation.recursion_depth + 1,
3605 "match_impl(impl_def_id={:?}, obligation={:?}, \
3606 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3607 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3610 let InferOk { obligations, .. } = self.infcx
3611 .at(&obligation.cause, obligation.param_env)
3612 .eq(skol_obligation_trait_ref, impl_trait_ref)
3613 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3614 nested_obligations.extend(obligations);
3618 .leak_check(false, obligation.cause.span, &placeholder_map, snapshot)
3620 debug!("match_impl: failed leak check due to `{}`", e);
3624 debug!("match_impl: success impl_substs={:?}", impl_substs);
3628 obligations: nested_obligations,
3634 fn fast_reject_trait_refs(
3636 obligation: &TraitObligation<'_>,
3637 impl_trait_ref: &ty::TraitRef<'_>,
3639 // We can avoid creating type variables and doing the full
3640 // substitution if we find that any of the input types, when
3641 // simplified, do not match.
3647 .zip(impl_trait_ref.input_types())
3648 .any(|(obligation_ty, impl_ty)| {
3649 let simplified_obligation_ty =
3650 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3651 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3653 simplified_obligation_ty.is_some()
3654 && simplified_impl_ty.is_some()
3655 && simplified_obligation_ty != simplified_impl_ty
3659 /// Normalize `where_clause_trait_ref` and try to match it against
3660 /// `obligation`. If successful, return any predicates that
3661 /// result from the normalization. Normalization is necessary
3662 /// because where-clauses are stored in the parameter environment
3664 fn match_where_clause_trait_ref(
3666 obligation: &TraitObligation<'tcx>,
3667 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3668 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3669 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3672 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3673 /// obligation is satisfied.
3674 fn match_poly_trait_ref(
3676 obligation: &TraitObligation<'tcx>,
3677 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3678 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3680 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3681 obligation, poly_trait_ref
3685 .at(&obligation.cause, obligation.param_env)
3686 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3687 .map(|InferOk { obligations, .. }| obligations)
3691 ///////////////////////////////////////////////////////////////////////////
3694 fn match_fresh_trait_refs(
3696 previous: &ty::PolyTraitRef<'tcx>,
3697 current: &ty::PolyTraitRef<'tcx>,
3699 let mut matcher = ty::_match::Match::new(self.tcx());
3700 matcher.relate(previous, current).is_ok()
3703 fn push_stack<'o, 's: 'o>(
3705 previous_stack: TraitObligationStackList<'s, 'tcx>,
3706 obligation: &'o TraitObligation<'tcx>,
3707 ) -> TraitObligationStack<'o, 'tcx> {
3708 let fresh_trait_ref = obligation
3710 .to_poly_trait_ref()
3711 .fold_with(&mut self.freshener);
3713 TraitObligationStack {
3716 previous: previous_stack,
3720 fn closure_trait_ref_unnormalized(
3722 obligation: &TraitObligation<'tcx>,
3723 closure_def_id: DefId,
3724 substs: ty::ClosureSubsts<'tcx>,
3725 ) -> ty::PolyTraitRef<'tcx> {
3727 "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3728 obligation, closure_def_id, substs,
3730 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3733 "closure_trait_ref_unnormalized: closure_type = {:?}",
3737 // (1) Feels icky to skip the binder here, but OTOH we know
3738 // that the self-type is an unboxed closure type and hence is
3739 // in fact unparameterized (or at least does not reference any
3740 // regions bound in the obligation). Still probably some
3741 // refactoring could make this nicer.
3743 .closure_trait_ref_and_return_type(
3744 obligation.predicate.def_id(),
3745 obligation.predicate.skip_binder().self_ty(), // (1)
3747 util::TupleArgumentsFlag::No,
3749 .map_bound(|(trait_ref, _)| trait_ref)
3752 fn generator_trait_ref_unnormalized(
3754 obligation: &TraitObligation<'tcx>,
3755 closure_def_id: DefId,
3756 substs: ty::GeneratorSubsts<'tcx>,
3757 ) -> ty::PolyTraitRef<'tcx> {
3758 let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
3760 // (1) Feels icky to skip the binder here, but OTOH we know
3761 // that the self-type is an generator type and hence is
3762 // in fact unparameterized (or at least does not reference any
3763 // regions bound in the obligation). Still probably some
3764 // refactoring could make this nicer.
3767 .generator_trait_ref_and_outputs(
3768 obligation.predicate.def_id(),
3769 obligation.predicate.skip_binder().self_ty(), // (1)
3772 .map_bound(|(trait_ref, ..)| trait_ref)
3775 /// Returns the obligations that are implied by instantiating an
3776 /// impl or trait. The obligations are substituted and fully
3777 /// normalized. This is used when confirming an impl or default
3779 fn impl_or_trait_obligations(
3781 cause: ObligationCause<'tcx>,
3782 recursion_depth: usize,
3783 param_env: ty::ParamEnv<'tcx>,
3784 def_id: DefId, // of impl or trait
3785 substs: &Substs<'tcx>, // for impl or trait
3786 placeholder_map: infer::PlaceholderMap<'tcx>,
3787 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3788 ) -> Vec<PredicateObligation<'tcx>> {
3789 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3790 let tcx = self.tcx();
3792 // To allow for one-pass evaluation of the nested obligation,
3793 // each predicate must be preceded by the obligations required
3795 // for example, if we have:
3796 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3797 // the impl will have the following predicates:
3798 // <V as Iterator>::Item = U,
3799 // U: Iterator, U: Sized,
3800 // V: Iterator, V: Sized,
3801 // <U as Iterator>::Item: Copy
3802 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3803 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3804 // `$1: Copy`, so we must ensure the obligations are emitted in
3806 let predicates = tcx.predicates_of(def_id);
3807 assert_eq!(predicates.parent, None);
3808 let mut predicates: Vec<_> = predicates
3811 .flat_map(|(predicate, _)| {
3812 let predicate = normalize_with_depth(
3817 &predicate.subst(tcx, substs),
3819 predicate.obligations.into_iter().chain(Some(Obligation {
3820 cause: cause.clone(),
3823 predicate: predicate.value,
3828 // We are performing deduplication here to avoid exponential blowups
3829 // (#38528) from happening, but the real cause of the duplication is
3830 // unknown. What we know is that the deduplication avoids exponential
3831 // amount of predicates being propagated when processing deeply nested
3834 // This code is hot enough that it's worth avoiding the allocation
3835 // required for the FxHashSet when possible. Special-casing lengths 0,
3836 // 1 and 2 covers roughly 75--80% of the cases.
3837 if predicates.len() <= 1 {
3838 // No possibility of duplicates.
3839 } else if predicates.len() == 2 {
3840 // Only two elements. Drop the second if they are equal.
3841 if predicates[0] == predicates[1] {
3842 predicates.truncate(1);
3845 // Three or more elements. Use a general deduplication process.
3846 let mut seen = FxHashSet::default();
3847 predicates.retain(|i| seen.insert(i.clone()));
3850 .plug_leaks(placeholder_map, snapshot, predicates)
3854 impl<'tcx> TraitObligation<'tcx> {
3855 #[allow(unused_comparisons)]
3856 pub fn derived_cause(
3858 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3859 ) -> ObligationCause<'tcx> {
3861 * Creates a cause for obligations that are derived from
3862 * `obligation` by a recursive search (e.g., for a builtin
3863 * bound, or eventually a `auto trait Foo`). If `obligation`
3864 * is itself a derived obligation, this is just a clone, but
3865 * otherwise we create a "derived obligation" cause so as to
3866 * keep track of the original root obligation for error
3870 let obligation = self;
3872 // NOTE(flaper87): As of now, it keeps track of the whole error
3873 // chain. Ideally, we should have a way to configure this either
3874 // by using -Z verbose or just a CLI argument.
3875 if obligation.recursion_depth >= 0 {
3876 let derived_cause = DerivedObligationCause {
3877 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3878 parent_code: Rc::new(obligation.cause.code.clone()),
3880 let derived_code = variant(derived_cause);
3881 ObligationCause::new(
3882 obligation.cause.span,
3883 obligation.cause.body_id,
3887 obligation.cause.clone()
3892 impl<'tcx> SelectionCache<'tcx> {
3893 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3894 pub fn clear(&self) {
3895 *self.hashmap.borrow_mut() = Default::default();
3899 impl<'tcx> EvaluationCache<'tcx> {
3900 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3901 pub fn clear(&self) {
3902 *self.hashmap.borrow_mut() = Default::default();
3906 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
3907 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3908 TraitObligationStackList::with(self)
3911 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3916 #[derive(Copy, Clone)]
3917 struct TraitObligationStackList<'o, 'tcx: 'o> {
3918 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3921 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3922 fn empty() -> TraitObligationStackList<'o, 'tcx> {
3923 TraitObligationStackList { head: None }
3926 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3927 TraitObligationStackList { head: Some(r) }
3931 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
3932 type Item = &'o TraitObligationStack<'o, 'tcx>;
3934 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3945 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
3946 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3947 write!(f, "TraitObligationStack({:?})", self.obligation)
3951 #[derive(Clone, Eq, PartialEq)]
3952 pub struct WithDepNode<T> {
3953 dep_node: DepNodeIndex,
3957 impl<T: Clone> WithDepNode<T> {
3958 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3965 pub fn get(&self, tcx: TyCtxt<'_, '_, '_>) -> T {
3966 tcx.dep_graph.read_index(self.dep_node);
3967 self.cached_value.clone()