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,
36 VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
37 VtableGeneratorData, VtableImplData, VtableObjectData,
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>,
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`)
276 BuiltinObjectCandidate,
278 BuiltinUnsizeCandidate,
281 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
282 type Lifted = SelectionCandidate<'tcx>;
283 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
285 BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
286 ImplCandidate(def_id) => ImplCandidate(def_id),
287 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
288 ProjectionCandidate => ProjectionCandidate,
289 FnPointerCandidate => FnPointerCandidate,
290 ObjectCandidate => ObjectCandidate,
291 BuiltinObjectCandidate => BuiltinObjectCandidate,
292 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
293 ClosureCandidate => ClosureCandidate,
294 GeneratorCandidate => GeneratorCandidate,
296 ParamCandidate(ref trait_ref) => {
297 return tcx.lift(trait_ref).map(ParamCandidate);
303 struct SelectionCandidateSet<'tcx> {
304 // a list of candidates that definitely apply to the current
305 // obligation (meaning: types unify).
306 vec: Vec<SelectionCandidate<'tcx>>,
308 // if this is true, then there were candidates that might or might
309 // not have applied, but we couldn't tell. This occurs when some
310 // of the input types are type variables, in which case there are
311 // various "builtin" rules that might or might not trigger.
315 #[derive(PartialEq, Eq, Debug, Clone)]
316 struct EvaluatedCandidate<'tcx> {
317 candidate: SelectionCandidate<'tcx>,
318 evaluation: EvaluationResult,
321 /// When does the builtin impl for `T: Trait` apply?
322 enum BuiltinImplConditions<'tcx> {
323 /// The impl is conditional on T1,T2,.. : Trait
324 Where(ty::Binder<Vec<Ty<'tcx>>>),
325 /// There is no built-in impl. There may be some other
326 /// candidate (a where-clause or user-defined impl).
328 /// It is unknown whether there is an impl.
332 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
333 /// The result of trait evaluation. The order is important
334 /// here as the evaluation of a list is the maximum of the
337 /// The evaluation results are ordered:
338 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
339 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
340 /// - the "union" of evaluation results is equal to their maximum -
341 /// all the "potential success" candidates can potentially succeed,
342 /// so they are no-ops when unioned with a definite error, and within
343 /// the categories it's easy to see that the unions are correct.
344 pub enum EvaluationResult {
345 /// Evaluation successful
347 /// Evaluation is known to be ambiguous - it *might* hold for some
348 /// assignment of inference variables, but it might not.
350 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
351 /// know whether this obligation holds or not - it is the result we
352 /// would get with an empty stack, and therefore is cacheable.
354 /// Evaluation failed because of recursion involving inference
355 /// variables. We are somewhat imprecise there, so we don't actually
356 /// know the real result.
358 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
360 /// Evaluation failed because we encountered an obligation we are already
361 /// trying to prove on this branch.
363 /// We know this branch can't be a part of a minimal proof-tree for
364 /// the "root" of our cycle, because then we could cut out the recursion
365 /// and maintain a valid proof tree. However, this does not mean
366 /// that all the obligations on this branch do not hold - it's possible
367 /// that we entered this branch "speculatively", and that there
368 /// might be some other way to prove this obligation that does not
369 /// go through this cycle - so we can't cache this as a failure.
371 /// For example, suppose we have this:
373 /// ```rust,ignore (pseudo-Rust)
374 /// pub trait Trait { fn xyz(); }
375 /// // This impl is "useless", but we can still have
376 /// // an `impl Trait for SomeUnsizedType` somewhere.
377 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
379 /// pub fn foo<T: Trait + ?Sized>() {
380 /// <T as Trait>::xyz();
384 /// When checking `foo`, we have to prove `T: Trait`. This basically
385 /// translates into this:
388 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
391 /// When we try to prove it, we first go the first option, which
392 /// recurses. This shows us that the impl is "useless" - it won't
393 /// tell us that `T: Trait` unless it already implemented `Trait`
394 /// by some other means. However, that does not prevent `T: Trait`
395 /// does not hold, because of the bound (which can indeed be satisfied
396 /// by `SomeUnsizedType` from another crate).
398 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
399 /// ought to convert it to an `EvaluatedToErr`, because we know
400 /// there definitely isn't a proof tree for that obligation. Not
401 /// doing so is still sound - there isn't any proof tree, so the
402 /// branch still can't be a part of a minimal one - but does not
403 /// re-enable caching.
405 /// Evaluation failed
409 impl EvaluationResult {
410 pub fn may_apply(self) -> bool {
412 EvaluatedToOk | EvaluatedToAmbig | EvaluatedToUnknown => true,
414 EvaluatedToErr | EvaluatedToRecur => false,
418 fn is_stack_dependent(self) -> bool {
420 EvaluatedToUnknown | EvaluatedToRecur => true,
422 EvaluatedToOk | EvaluatedToAmbig | EvaluatedToErr => false,
427 impl_stable_hash_for!(enum self::EvaluationResult {
435 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
436 /// Indicates that trait evaluation caused overflow.
437 pub struct OverflowError;
439 impl_stable_hash_for!(struct OverflowError {});
441 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
442 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
443 SelectionError::Overflow
448 pub struct EvaluationCache<'tcx> {
449 hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>,
452 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
453 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
456 freshener: infcx.freshener(),
458 intercrate_ambiguity_causes: None,
459 allow_negative_impls: false,
460 query_mode: TraitQueryMode::Standard,
465 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
466 mode: IntercrateMode,
467 ) -> SelectionContext<'cx, 'gcx, 'tcx> {
468 debug!("intercrate({:?})", mode);
471 freshener: infcx.freshener(),
472 intercrate: Some(mode),
473 intercrate_ambiguity_causes: None,
474 allow_negative_impls: false,
475 query_mode: TraitQueryMode::Standard,
479 pub fn with_negative(
480 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
481 allow_negative_impls: bool,
482 ) -> SelectionContext<'cx, 'gcx, 'tcx> {
483 debug!("with_negative({:?})", allow_negative_impls);
486 freshener: infcx.freshener(),
488 intercrate_ambiguity_causes: None,
489 allow_negative_impls,
490 query_mode: TraitQueryMode::Standard,
494 pub fn with_query_mode(
495 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
496 query_mode: TraitQueryMode,
497 ) -> SelectionContext<'cx, 'gcx, 'tcx> {
498 debug!("with_query_mode({:?})", query_mode);
501 freshener: infcx.freshener(),
503 intercrate_ambiguity_causes: None,
504 allow_negative_impls: false,
509 /// Enables tracking of intercrate ambiguity causes. These are
510 /// used in coherence to give improved diagnostics. We don't do
511 /// this until we detect a coherence error because it can lead to
512 /// false overflow results (#47139) and because it costs
513 /// computation time.
514 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
515 assert!(self.intercrate.is_some());
516 assert!(self.intercrate_ambiguity_causes.is_none());
517 self.intercrate_ambiguity_causes = Some(vec![]);
518 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
521 /// Gets the intercrate ambiguity causes collected since tracking
522 /// was enabled and disables tracking at the same time. If
523 /// tracking is not enabled, just returns an empty vector.
524 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
525 assert!(self.intercrate.is_some());
526 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
529 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
533 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
537 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
541 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
543 fn in_snapshot<R, F>(&mut self, f: F) -> R
545 F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R,
547 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
550 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
552 fn probe<R, F>(&mut self, f: F) -> R
554 F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R,
556 self.infcx.probe(|snapshot| f(self, snapshot))
559 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
560 /// the transaction fails and s.t. old obligations are retained.
561 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E>
563 F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> Result<T, E>,
565 self.infcx.commit_if_ok(|snapshot| f(self, snapshot))
568 ///////////////////////////////////////////////////////////////////////////
571 // The selection phase tries to identify *how* an obligation will
572 // be resolved. For example, it will identify which impl or
573 // parameter bound is to be used. The process can be inconclusive
574 // if the self type in the obligation is not fully inferred. Selection
575 // can result in an error in one of two ways:
577 // 1. If no applicable impl or parameter bound can be found.
578 // 2. If the output type parameters in the obligation do not match
579 // those specified by the impl/bound. For example, if the obligation
580 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
581 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
583 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
584 /// type environment by performing unification.
587 obligation: &TraitObligation<'tcx>,
588 ) -> SelectionResult<'tcx, Selection<'tcx>> {
589 debug!("select({:?})", obligation);
590 debug_assert!(!obligation.predicate.has_escaping_regions());
592 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
594 let candidate = match self.candidate_from_obligation(&stack) {
595 Err(SelectionError::Overflow) => {
596 // In standard mode, overflow must have been caught and reported
598 assert!(self.query_mode == TraitQueryMode::Canonical);
599 return Err(SelectionError::Overflow);
607 Ok(Some(candidate)) => candidate,
610 match self.confirm_candidate(obligation, candidate) {
611 Err(SelectionError::Overflow) => {
612 assert!(self.query_mode == TraitQueryMode::Canonical);
613 Err(SelectionError::Overflow)
616 Ok(candidate) => Ok(Some(candidate)),
620 ///////////////////////////////////////////////////////////////////////////
623 // Tests whether an obligation can be selected or whether an impl
624 // can be applied to particular types. It skips the "confirmation"
625 // step and hence completely ignores output type parameters.
627 // The result is "true" if the obligation *may* hold and "false" if
628 // we can be sure it does not.
630 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
631 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
632 debug!("predicate_may_hold_fatal({:?})", obligation);
634 // This fatal query is a stopgap that should only be used in standard mode,
635 // where we do not expect overflow to be propagated.
636 assert!(self.query_mode == TraitQueryMode::Standard);
638 self.evaluate_obligation_recursively(obligation)
639 .expect("Overflow should be caught earlier in standard query mode")
643 /// Evaluates whether the obligation `obligation` can be satisfied and returns
644 /// an `EvaluationResult`.
645 pub fn evaluate_obligation_recursively(
647 obligation: &PredicateObligation<'tcx>,
648 ) -> Result<EvaluationResult, OverflowError> {
649 self.probe(|this, _| {
650 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
654 /// Evaluates the predicates in `predicates` recursively. Note that
655 /// this applies projections in the predicates, and therefore
656 /// is run within an inference probe.
657 fn evaluate_predicates_recursively<'a, 'o, I>(
659 stack: TraitObligationStackList<'o, 'tcx>,
661 ) -> Result<EvaluationResult, OverflowError>
663 I: IntoIterator<Item = &'a PredicateObligation<'tcx>>,
666 let mut result = EvaluatedToOk;
667 for obligation in predicates {
668 let eval = self.evaluate_predicate_recursively(stack, obligation)?;
670 "evaluate_predicate_recursively({:?}) = {:?}",
673 if let EvaluatedToErr = eval {
674 // fast-path - EvaluatedToErr is the top of the lattice,
675 // so we don't need to look on the other predicates.
676 return Ok(EvaluatedToErr);
678 result = cmp::max(result, eval);
684 fn evaluate_predicate_recursively<'o>(
686 previous_stack: TraitObligationStackList<'o, 'tcx>,
687 obligation: &PredicateObligation<'tcx>,
688 ) -> Result<EvaluationResult, OverflowError> {
689 debug!("evaluate_predicate_recursively({:?})", obligation);
691 match obligation.predicate {
692 ty::Predicate::Trait(ref t) => {
693 debug_assert!(!t.has_escaping_regions());
694 let obligation = obligation.with(t.clone());
695 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
698 ty::Predicate::Subtype(ref p) => {
699 // does this code ever run?
701 .subtype_predicate(&obligation.cause, obligation.param_env, p)
703 Some(Ok(InferOk { obligations, .. })) => {
704 self.evaluate_predicates_recursively(previous_stack, &obligations)
706 Some(Err(_)) => Ok(EvaluatedToErr),
707 None => Ok(EvaluatedToAmbig),
711 ty::Predicate::WellFormed(ty) => match ty::wf::obligations(
713 obligation.param_env,
714 obligation.cause.body_id,
716 obligation.cause.span,
718 Some(obligations) => {
719 self.evaluate_predicates_recursively(previous_stack, obligations.iter())
721 None => Ok(EvaluatedToAmbig),
724 ty::Predicate::TypeOutlives(ref binder) => {
725 assert!(!binder.has_escaping_regions());
726 // Check if the type has higher-ranked regions.
727 if binder.skip_binder().0.has_escaping_regions() {
728 // If so, this obligation is an error (for now). Eventually we should be
729 // able to support additional cases here, like `for<'a> &'a str: 'a`.
731 // NOTE: this hack is implemented in both trait fulfillment and
732 // evaluation. If you fix it in one place, make sure you fix it
735 // We don't want to allow this sort of reasoning in intercrate
736 // mode, for backwards-compatibility reasons.
737 if self.intercrate.is_some() {
743 // If the type has no late bound regions, then if we assign all
744 // the inference variables in it to be 'static, then the type
745 // will be 'static itself.
747 // Therefore, `staticize(T): 'a` holds for any `'a`, so this
748 // obligation is fulfilled. Because evaluation works with
749 // staticized types (yes I know this is involved with #21974),
750 // we are 100% OK here.
755 ty::Predicate::RegionOutlives(ref binder) => {
756 let ty::OutlivesPredicate(r_a, r_b) = binder.skip_binder();
759 // for<'a> 'a: 'a. OK
761 } else if **r_a == ty::ReStatic {
762 // 'static: 'x always holds.
764 // This special case is handled somewhat inconsistently - if we
765 // have an inference variable that is supposed to be equal to
766 // `'static`, then we don't allow it to be equated to an LBR,
767 // but if we have a literal `'static`, then we *do*.
769 // This is actually consistent with how our region inference works.
771 // It would appear that this sort of inconsistency would
772 // cause "instability" problems with evaluation caching. However,
773 // evaluation caching is only for trait predicates, and when
774 // trait predicates create nested obligations, they contain
775 // inference variables for all the regions in the trait - the
776 // only way this codepath can be reached from trait predicate
777 // evaluation is when the user typed an explicit `where 'static: 'a`
778 // lifetime bound (in which case we want to return EvaluatedToOk).
780 // If we ever want to handle inference variables that might be
781 // equatable with ReStatic, we need to make sure we are not confused by
782 // technically-allowed-by-RFC-447-but-probably-should-not-be
785 // impl<'a, 's, T> X<'s> for T where T: Debug + 'a, 'a: 's
788 } else if r_a.is_late_bound() || r_b.is_late_bound() {
789 // There is no current way to prove `for<'a> 'a: 'x`
790 // unless `'a = 'x`, because there are no bounds involving
793 // It might be possible to prove `for<'a> 'x: 'a` by forcing `'x`
794 // to be `'static`. However, this is not currently done by type
795 // inference unless `'x` is literally ReStatic. See the comment
798 // We don't want to allow this sort of reasoning in intercrate
799 // mode, for backwards-compatibility reasons.
800 if self.intercrate.is_some() {
806 // Relating 2 inference variable regions. These will
807 // always hold if our query is "staticized".
812 ty::Predicate::ObjectSafe(trait_def_id) => {
813 if self.tcx().is_object_safe(trait_def_id) {
820 ty::Predicate::Projection(ref data) => {
821 let project_obligation = obligation.with(data.clone());
822 match project::poly_project_and_unify_type(self, &project_obligation) {
823 Ok(Some(subobligations)) => {
824 let result = self.evaluate_predicates_recursively(
826 subobligations.iter(),
829 ProjectionCacheKey::from_poly_projection_predicate(self, data)
831 self.infcx.projection_cache.borrow_mut().complete(key);
835 Ok(None) => Ok(EvaluatedToAmbig),
836 Err(_) => Ok(EvaluatedToErr),
840 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
841 match self.infcx.closure_kind(closure_def_id, closure_substs) {
842 Some(closure_kind) => {
843 if closure_kind.extends(kind) {
849 None => Ok(EvaluatedToAmbig),
853 ty::Predicate::ConstEvaluatable(def_id, substs) => {
854 let tcx = self.tcx();
855 match tcx.lift_to_global(&(obligation.param_env, substs)) {
856 Some((param_env, substs)) => {
858 ty::Instance::resolve(tcx.global_tcx(), param_env, def_id, substs);
859 if let Some(instance) = instance {
864 match self.tcx().const_eval(param_env.and(cid)) {
865 Ok(_) => Ok(EvaluatedToOk),
866 Err(_) => Ok(EvaluatedToErr),
873 // Inference variables still left in param_env or substs.
881 fn evaluate_trait_predicate_recursively<'o>(
883 previous_stack: TraitObligationStackList<'o, 'tcx>,
884 mut obligation: TraitObligation<'tcx>,
885 ) -> Result<EvaluationResult, OverflowError> {
886 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
888 if self.intercrate.is_none() && obligation.is_global()
893 .all(|bound| bound.needs_subst())
895 // If a param env has no global bounds, global obligations do not
896 // depend on its particular value in order to work, so we can clear
897 // out the param env and get better caching.
899 "evaluate_trait_predicate_recursively({:?}) - in global",
902 obligation.param_env = obligation.param_env.without_caller_bounds();
905 let stack = self.push_stack(previous_stack, &obligation);
906 let fresh_trait_ref = stack.fresh_trait_ref;
907 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
908 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
912 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
913 let result = result?;
915 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
916 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
921 fn evaluate_stack<'o>(
923 stack: &TraitObligationStack<'o, 'tcx>,
924 ) -> Result<EvaluationResult, OverflowError> {
925 // In intercrate mode, whenever any of the types are unbound,
926 // there can always be an impl. Even if there are no impls in
927 // this crate, perhaps the type would be unified with
928 // something from another crate that does provide an impl.
930 // In intra mode, we must still be conservative. The reason is
931 // that we want to avoid cycles. Imagine an impl like:
933 // impl<T:Eq> Eq for Vec<T>
935 // and a trait reference like `$0 : Eq` where `$0` is an
936 // unbound variable. When we evaluate this trait-reference, we
937 // will unify `$0` with `Vec<$1>` (for some fresh variable
938 // `$1`), on the condition that `$1 : Eq`. We will then wind
939 // up with many candidates (since that are other `Eq` impls
940 // that apply) and try to winnow things down. This results in
941 // a recursive evaluation that `$1 : Eq` -- as you can
942 // imagine, this is just where we started. To avoid that, we
943 // check for unbound variables and return an ambiguous (hence possible)
944 // match if we've seen this trait before.
946 // This suffices to allow chains like `FnMut` implemented in
947 // terms of `Fn` etc, but we could probably make this more
949 let unbound_input_types = stack
953 .any(|ty| ty.is_fresh());
954 // this check was an imperfect workaround for a bug n the old
955 // intercrate mode, it should be removed when that goes away.
956 if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
958 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
959 stack.fresh_trait_ref
961 // Heuristics: show the diagnostics when there are no candidates in crate.
962 if self.intercrate_ambiguity_causes.is_some() {
963 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
964 if let Ok(candidate_set) = self.assemble_candidates(stack) {
965 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
966 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
967 let self_ty = trait_ref.self_ty();
968 let cause = IntercrateAmbiguityCause::DownstreamCrate {
969 trait_desc: trait_ref.to_string(),
970 self_desc: if self_ty.has_concrete_skeleton() {
971 Some(self_ty.to_string())
976 debug!("evaluate_stack: pushing cause = {:?}", cause);
977 self.intercrate_ambiguity_causes
984 return Ok(EvaluatedToAmbig);
986 if unbound_input_types && stack.iter().skip(1).any(|prev| {
987 stack.obligation.param_env == prev.obligation.param_env
988 && self.match_fresh_trait_refs(&stack.fresh_trait_ref, &prev.fresh_trait_ref)
991 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
992 stack.fresh_trait_ref
994 return Ok(EvaluatedToUnknown);
997 // If there is any previous entry on the stack that precisely
998 // matches this obligation, then we can assume that the
999 // obligation is satisfied for now (still all other conditions
1000 // must be met of course). One obvious case this comes up is
1001 // marker traits like `Send`. Think of a linked list:
1003 // struct List<T> { data: T, next: Option<Box<List<T>>> }
1005 // `Box<List<T>>` will be `Send` if `T` is `Send` and
1006 // `Option<Box<List<T>>>` is `Send`, and in turn
1007 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
1010 // Note that we do this comparison using the `fresh_trait_ref`
1011 // fields. Because these have all been freshened using
1012 // `self.freshener`, we can be sure that (a) this will not
1013 // affect the inferencer state and (b) that if we see two
1014 // fresh regions with the same index, they refer to the same
1015 // unbound type variable.
1016 if let Some(rec_index) = stack.iter()
1017 .skip(1) // skip top-most frame
1018 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
1019 stack.fresh_trait_ref == prev.fresh_trait_ref)
1021 debug!("evaluate_stack({:?}) --> recursive", stack.fresh_trait_ref);
1023 let cycle = stack.iter().skip(1).take(rec_index + 1);
1024 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
1025 if self.coinductive_match(cycle) {
1027 "evaluate_stack({:?}) --> recursive, coinductive",
1028 stack.fresh_trait_ref
1030 return Ok(EvaluatedToOk);
1033 "evaluate_stack({:?}) --> recursive, inductive",
1034 stack.fresh_trait_ref
1036 return Ok(EvaluatedToRecur);
1040 match self.candidate_from_obligation(stack) {
1041 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1042 Ok(None) => Ok(EvaluatedToAmbig),
1043 Err(Overflow) => Err(OverflowError),
1044 Err(..) => Ok(EvaluatedToErr),
1048 /// For defaulted traits, we use a co-inductive strategy to solve, so
1049 /// that recursion is ok. This routine returns true if the top of the
1050 /// stack (`cycle[0]`):
1052 /// - is a defaulted trait, and
1053 /// - it also appears in the backtrace at some position `X`; and,
1054 /// - all the predicates at positions `X..` between `X` an the top are
1055 /// also defaulted traits.
1056 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1058 I: Iterator<Item = ty::Predicate<'tcx>>,
1060 let mut cycle = cycle;
1061 cycle.all(|predicate| self.coinductive_predicate(predicate))
1064 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1065 let result = match predicate {
1066 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1069 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1073 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1074 /// obligations are met. Returns true if `candidate` remains viable after this further
1076 fn evaluate_candidate<'o>(
1078 stack: &TraitObligationStack<'o, 'tcx>,
1079 candidate: &SelectionCandidate<'tcx>,
1080 ) -> Result<EvaluationResult, OverflowError> {
1082 "evaluate_candidate: depth={} candidate={:?}",
1083 stack.obligation.recursion_depth, candidate
1085 let result = self.probe(|this, _| {
1086 let candidate = (*candidate).clone();
1087 match this.confirm_candidate(stack.obligation, candidate) {
1088 Ok(selection) => this.evaluate_predicates_recursively(
1090 selection.nested_obligations().iter(),
1092 Err(..) => Ok(EvaluatedToErr),
1096 "evaluate_candidate: depth={} result={:?}",
1097 stack.obligation.recursion_depth, result
1102 fn check_evaluation_cache(
1104 param_env: ty::ParamEnv<'tcx>,
1105 trait_ref: ty::PolyTraitRef<'tcx>,
1106 ) -> Option<EvaluationResult> {
1107 let tcx = self.tcx();
1108 if self.can_use_global_caches(param_env) {
1109 let cache = tcx.evaluation_cache.hashmap.borrow();
1110 if let Some(cached) = cache.get(&trait_ref) {
1111 return Some(cached.get(tcx));
1119 .map(|v| v.get(tcx))
1122 fn insert_evaluation_cache(
1124 param_env: ty::ParamEnv<'tcx>,
1125 trait_ref: ty::PolyTraitRef<'tcx>,
1126 dep_node: DepNodeIndex,
1127 result: EvaluationResult,
1129 // Avoid caching results that depend on more than just the trait-ref
1130 // - the stack can create recursion.
1131 if result.is_stack_dependent() {
1135 if self.can_use_global_caches(param_env) {
1136 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1138 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1141 // This may overwrite the cache with the same value
1142 // FIXME: Due to #50507 this overwrites the different values
1143 // This should be changed to use HashMapExt::insert_same
1144 // when that is fixed
1149 .insert(trait_ref, WithDepNode::new(dep_node, result));
1155 "insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
1162 .insert(trait_ref, WithDepNode::new(dep_node, result));
1165 ///////////////////////////////////////////////////////////////////////////
1166 // CANDIDATE ASSEMBLY
1168 // The selection process begins by examining all in-scope impls,
1169 // caller obligations, and so forth and assembling a list of
1170 // candidates. See [rustc guide] for more details.
1173 // https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1175 fn candidate_from_obligation<'o>(
1177 stack: &TraitObligationStack<'o, 'tcx>,
1178 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1179 // Watch out for overflow. This intentionally bypasses (and does
1180 // not update) the cache.
1181 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1182 if stack.obligation.recursion_depth >= recursion_limit {
1183 match self.query_mode {
1184 TraitQueryMode::Standard => {
1185 self.infcx().report_overflow_error(&stack.obligation, true);
1187 TraitQueryMode::Canonical => {
1188 return Err(Overflow);
1193 // Check the cache. Note that we freshen the trait-ref
1194 // separately rather than using `stack.fresh_trait_ref` --
1195 // this is because we want the unbound variables to be
1196 // replaced with fresh types starting from index 0.
1197 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1199 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1200 cache_fresh_trait_pred, stack
1202 debug_assert!(!stack.obligation.predicate.has_escaping_regions());
1205 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1207 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1211 // If no match, compute result and insert into cache.
1212 let (candidate, dep_node) =
1213 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1216 "CACHE MISS: SELECT({:?})={:?}",
1217 cache_fresh_trait_pred, candidate
1219 self.insert_candidate_cache(
1220 stack.obligation.param_env,
1221 cache_fresh_trait_pred,
1228 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1230 OP: FnOnce(&mut Self) -> R,
1232 let (result, dep_node) = self.tcx()
1234 .with_anon_task(DepKind::TraitSelect, || op(self));
1235 self.tcx().dep_graph.read_index(dep_node);
1239 // Treat negative impls as unimplemented
1240 fn filter_negative_impls(
1242 candidate: SelectionCandidate<'tcx>,
1243 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1244 if let ImplCandidate(def_id) = candidate {
1245 if !self.allow_negative_impls
1246 && self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative
1248 return Err(Unimplemented);
1254 fn candidate_from_obligation_no_cache<'o>(
1256 stack: &TraitObligationStack<'o, 'tcx>,
1257 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1258 if stack.obligation.predicate.references_error() {
1259 // If we encounter a `Error`, we generally prefer the
1260 // most "optimistic" result in response -- that is, the
1261 // one least likely to report downstream errors. But
1262 // because this routine is shared by coherence and by
1263 // trait selection, there isn't an obvious "right" choice
1264 // here in that respect, so we opt to just return
1265 // ambiguity and let the upstream clients sort it out.
1269 if let Some(conflict) = self.is_knowable(stack) {
1270 debug!("coherence stage: not knowable");
1271 if self.intercrate_ambiguity_causes.is_some() {
1272 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1273 // Heuristics: show the diagnostics when there are no candidates in crate.
1274 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1275 let mut no_candidates_apply = true;
1277 let evaluated_candidates = candidate_set
1280 .map(|c| self.evaluate_candidate(stack, &c));
1282 for ec in evaluated_candidates {
1286 no_candidates_apply = false;
1290 Err(e) => return Err(e.into()),
1295 if !candidate_set.ambiguous && no_candidates_apply {
1296 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1297 let self_ty = trait_ref.self_ty();
1298 let trait_desc = trait_ref.to_string();
1299 let self_desc = if self_ty.has_concrete_skeleton() {
1300 Some(self_ty.to_string())
1304 let cause = if let Conflict::Upstream = conflict {
1305 IntercrateAmbiguityCause::UpstreamCrateUpdate {
1310 IntercrateAmbiguityCause::DownstreamCrate {
1315 debug!("evaluate_stack: pushing cause = {:?}", cause);
1316 self.intercrate_ambiguity_causes
1326 let candidate_set = self.assemble_candidates(stack)?;
1328 if candidate_set.ambiguous {
1329 debug!("candidate set contains ambig");
1333 let mut candidates = candidate_set.vec;
1336 "assembled {} candidates for {:?}: {:?}",
1342 // At this point, we know that each of the entries in the
1343 // candidate set is *individually* applicable. Now we have to
1344 // figure out if they contain mutual incompatibilities. This
1345 // frequently arises if we have an unconstrained input type --
1346 // for example, we are looking for $0:Eq where $0 is some
1347 // unconstrained type variable. In that case, we'll get a
1348 // candidate which assumes $0 == int, one that assumes $0 ==
1349 // usize, etc. This spells an ambiguity.
1351 // If there is more than one candidate, first winnow them down
1352 // by considering extra conditions (nested obligations and so
1353 // forth). We don't winnow if there is exactly one
1354 // candidate. This is a relatively minor distinction but it
1355 // can lead to better inference and error-reporting. An
1356 // example would be if there was an impl:
1358 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1360 // and we were to see some code `foo.push_clone()` where `boo`
1361 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1362 // we were to winnow, we'd wind up with zero candidates.
1363 // Instead, we select the right impl now but report `Bar does
1364 // not implement Clone`.
1365 if candidates.len() == 1 {
1366 return self.filter_negative_impls(candidates.pop().unwrap());
1369 // Winnow, but record the exact outcome of evaluation, which
1370 // is needed for specialization. Propagate overflow if it occurs.
1371 let candidates: Result<Vec<Option<EvaluatedCandidate<'_>>>, _> = candidates
1373 .map(|c| match self.evaluate_candidate(stack, &c) {
1374 Ok(eval) if eval.may_apply() => Ok(Some(EvaluatedCandidate {
1379 Err(OverflowError) => Err(Overflow),
1383 let mut candidates: Vec<EvaluatedCandidate<'_>> =
1384 candidates?.into_iter().filter_map(|c| c).collect();
1387 "winnowed to {} candidates for {:?}: {:?}",
1393 // If there are STILL multiple candidate, we can further
1394 // reduce the list by dropping duplicates -- including
1395 // resolving specializations.
1396 if candidates.len() > 1 {
1398 while i < candidates.len() {
1399 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1400 self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1404 "Dropping candidate #{}/{}: {:?}",
1409 candidates.swap_remove(i);
1412 "Retaining candidate #{}/{}: {:?}",
1419 // If there are *STILL* multiple candidates, give up
1420 // and report ambiguity.
1422 debug!("multiple matches, ambig");
1429 // If there are *NO* candidates, then there are no impls --
1430 // that we know of, anyway. Note that in the case where there
1431 // are unbound type variables within the obligation, it might
1432 // be the case that you could still satisfy the obligation
1433 // from another crate by instantiating the type variables with
1434 // a type from another crate that does have an impl. This case
1435 // is checked for in `evaluate_stack` (and hence users
1436 // who might care about this case, like coherence, should use
1438 if candidates.is_empty() {
1439 return Err(Unimplemented);
1442 // Just one candidate left.
1443 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1446 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1447 debug!("is_knowable(intercrate={:?})", self.intercrate);
1449 if !self.intercrate.is_some() {
1453 let obligation = &stack.obligation;
1454 let predicate = self.infcx()
1455 .resolve_type_vars_if_possible(&obligation.predicate);
1457 // ok to skip binder because of the nature of the
1458 // trait-ref-is-knowable check, which does not care about
1460 let trait_ref = predicate.skip_binder().trait_ref;
1462 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1464 Some(Conflict::Downstream {
1465 used_to_be_broken: true,
1467 Some(IntercrateMode::Issue43355),
1468 ) = (result, self.intercrate)
1470 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1477 /// Returns true if the global caches can be used.
1478 /// Do note that if the type itself is not in the
1479 /// global tcx, the local caches will be used.
1480 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1481 // If there are any where-clauses in scope, then we always use
1482 // a cache local to this particular scope. Otherwise, we
1483 // switch to a global cache. We used to try and draw
1484 // finer-grained distinctions, but that led to a serious of
1485 // annoying and weird bugs like #22019 and #18290. This simple
1486 // rule seems to be pretty clearly safe and also still retains
1487 // a very high hit rate (~95% when compiling rustc).
1488 if !param_env.caller_bounds.is_empty() {
1492 // Avoid using the master cache during coherence and just rely
1493 // on the local cache. This effectively disables caching
1494 // during coherence. It is really just a simplification to
1495 // avoid us having to fear that coherence results "pollute"
1496 // the master cache. Since coherence executes pretty quickly,
1497 // it's not worth going to more trouble to increase the
1498 // hit-rate I don't think.
1499 if self.intercrate.is_some() {
1503 // Otherwise, we can use the global cache.
1507 fn check_candidate_cache(
1509 param_env: ty::ParamEnv<'tcx>,
1510 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1511 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1512 let tcx = self.tcx();
1513 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1514 if self.can_use_global_caches(param_env) {
1515 let cache = tcx.selection_cache.hashmap.borrow();
1516 if let Some(cached) = cache.get(&trait_ref) {
1517 return Some(cached.get(tcx));
1525 .map(|v| v.get(tcx))
1528 fn insert_candidate_cache(
1530 param_env: ty::ParamEnv<'tcx>,
1531 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1532 dep_node: DepNodeIndex,
1533 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1535 let tcx = self.tcx();
1536 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1537 if self.can_use_global_caches(param_env) {
1538 if let Err(Overflow) = candidate {
1539 // Don't cache overflow globally; we only produce this
1540 // in certain modes.
1541 } else if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1542 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1544 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1545 trait_ref, candidate,
1547 // This may overwrite the cache with the same value
1551 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1558 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1559 trait_ref, candidate,
1565 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1568 fn assemble_candidates<'o>(
1570 stack: &TraitObligationStack<'o, 'tcx>,
1571 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1572 let TraitObligationStack { obligation, .. } = *stack;
1573 let ref obligation = Obligation {
1574 param_env: obligation.param_env,
1575 cause: obligation.cause.clone(),
1576 recursion_depth: obligation.recursion_depth,
1577 predicate: self.infcx()
1578 .resolve_type_vars_if_possible(&obligation.predicate),
1581 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1582 // Self is a type variable (e.g. `_: AsRef<str>`).
1584 // This is somewhat problematic, as the current scheme can't really
1585 // handle it turning to be a projection. This does end up as truly
1586 // ambiguous in most cases anyway.
1588 // Take the fast path out - this also improves
1589 // performance by preventing assemble_candidates_from_impls from
1590 // matching every impl for this trait.
1591 return Ok(SelectionCandidateSet {
1597 let mut candidates = SelectionCandidateSet {
1602 // Other bounds. Consider both in-scope bounds from fn decl
1603 // and applicable impls. There is a certain set of precedence rules here.
1604 let def_id = obligation.predicate.def_id();
1605 let lang_items = self.tcx().lang_items();
1607 if lang_items.copy_trait() == Some(def_id) {
1609 "obligation self ty is {:?}",
1610 obligation.predicate.skip_binder().self_ty()
1613 // User-defined copy impls are permitted, but only for
1614 // structs and enums.
1615 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1617 // For other types, we'll use the builtin rules.
1618 let copy_conditions = self.copy_clone_conditions(obligation);
1619 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1620 } else if lang_items.sized_trait() == Some(def_id) {
1621 // Sized is never implementable by end-users, it is
1622 // always automatically computed.
1623 let sized_conditions = self.sized_conditions(obligation);
1624 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1625 } else if lang_items.unsize_trait() == Some(def_id) {
1626 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1628 if lang_items.clone_trait() == Some(def_id) {
1629 // Same builtin conditions as `Copy`, i.e. every type which has builtin support
1630 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1631 // types have builtin support for `Clone`.
1632 let clone_conditions = self.copy_clone_conditions(obligation);
1633 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1636 self.assemble_generator_candidates(obligation, &mut candidates)?;
1637 self.assemble_closure_candidates(obligation, &mut candidates)?;
1638 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1639 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1640 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1643 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1644 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1645 // Auto implementations have lower priority, so we only
1646 // consider triggering a default if there is no other impl that can apply.
1647 if candidates.vec.is_empty() {
1648 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1650 debug!("candidate list size: {}", candidates.vec.len());
1654 fn assemble_candidates_from_projected_tys(
1656 obligation: &TraitObligation<'tcx>,
1657 candidates: &mut SelectionCandidateSet<'tcx>,
1659 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1661 // before we go into the whole skolemization thing, just
1662 // quickly check if the self-type is a projection at all.
1663 match obligation.predicate.skip_binder().trait_ref.self_ty().sty {
1664 ty::Projection(_) | ty::Opaque(..) => {}
1665 ty::Infer(ty::TyVar(_)) => {
1667 obligation.cause.span,
1668 "Self=_ should have been handled by assemble_candidates"
1674 let result = self.probe(|this, snapshot| {
1675 this.match_projection_obligation_against_definition_bounds(obligation, snapshot)
1679 candidates.vec.push(ProjectionCandidate);
1683 fn match_projection_obligation_against_definition_bounds(
1685 obligation: &TraitObligation<'tcx>,
1686 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
1688 let poly_trait_predicate = self.infcx()
1689 .resolve_type_vars_if_possible(&obligation.predicate);
1690 let (skol_trait_predicate, placeholder_map) = self.infcx()
1691 .replace_late_bound_regions_with_placeholders(&poly_trait_predicate);
1693 "match_projection_obligation_against_definition_bounds: \
1694 skol_trait_predicate={:?} placeholder_map={:?}",
1695 skol_trait_predicate, placeholder_map
1698 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1699 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1700 ty::Opaque(def_id, substs) => (def_id, substs),
1703 obligation.cause.span,
1704 "match_projection_obligation_against_definition_bounds() called \
1705 but self-ty is not a projection: {:?}",
1706 skol_trait_predicate.trait_ref.self_ty()
1711 "match_projection_obligation_against_definition_bounds: \
1712 def_id={:?}, substs={:?}",
1716 let predicates_of = self.tcx().predicates_of(def_id);
1717 let bounds = predicates_of.instantiate(self.tcx(), substs);
1719 "match_projection_obligation_against_definition_bounds: \
1724 let matching_bound = util::elaborate_predicates(self.tcx(), bounds.predicates)
1727 self.probe(|this, _| {
1728 this.match_projection(
1731 skol_trait_predicate.trait_ref.clone(),
1739 "match_projection_obligation_against_definition_bounds: \
1740 matching_bound={:?}",
1743 match matching_bound {
1746 // Repeat the successful match, if any, this time outside of a probe.
1747 let result = self.match_projection(
1750 skol_trait_predicate.trait_ref.clone(),
1755 self.infcx.pop_placeholders(placeholder_map, snapshot);
1763 fn match_projection(
1765 obligation: &TraitObligation<'tcx>,
1766 trait_bound: ty::PolyTraitRef<'tcx>,
1767 skol_trait_ref: ty::TraitRef<'tcx>,
1768 placeholder_map: &infer::PlaceholderMap<'tcx>,
1769 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
1771 debug_assert!(!skol_trait_ref.has_escaping_regions());
1773 .at(&obligation.cause, obligation.param_env)
1774 .sup(ty::Binder::dummy(skol_trait_ref), trait_bound)
1781 .leak_check(false, obligation.cause.span, placeholder_map, snapshot)
1785 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1786 /// supplied to find out whether it is listed among them.
1788 /// Never affects inference environment.
1789 fn assemble_candidates_from_caller_bounds<'o>(
1791 stack: &TraitObligationStack<'o, 'tcx>,
1792 candidates: &mut SelectionCandidateSet<'tcx>,
1793 ) -> Result<(), SelectionError<'tcx>> {
1795 "assemble_candidates_from_caller_bounds({:?})",
1799 let all_bounds = stack
1804 .filter_map(|o| o.to_opt_poly_trait_ref());
1806 // micro-optimization: filter out predicates relating to different
1808 let matching_bounds =
1809 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1811 // keep only those bounds which may apply, and propagate overflow if it occurs
1812 let mut param_candidates = vec![];
1813 for bound in matching_bounds {
1814 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1816 param_candidates.push(ParamCandidate(bound));
1820 candidates.vec.extend(param_candidates);
1825 fn evaluate_where_clause<'o>(
1827 stack: &TraitObligationStack<'o, 'tcx>,
1828 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1829 ) -> Result<EvaluationResult, OverflowError> {
1830 self.probe(move |this, _| {
1831 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1832 Ok(obligations) => {
1833 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1835 Err(()) => Ok(EvaluatedToErr),
1840 fn assemble_generator_candidates(
1842 obligation: &TraitObligation<'tcx>,
1843 candidates: &mut SelectionCandidateSet<'tcx>,
1844 ) -> Result<(), SelectionError<'tcx>> {
1845 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1849 // ok to skip binder because the substs on generator types never
1850 // touch bound regions, they just capture the in-scope
1851 // type/region parameters
1852 let self_ty = *obligation.self_ty().skip_binder();
1854 ty::Generator(..) => {
1856 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1860 candidates.vec.push(GeneratorCandidate);
1862 ty::Infer(ty::TyVar(_)) => {
1863 debug!("assemble_generator_candidates: ambiguous self-type");
1864 candidates.ambiguous = true;
1872 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1873 /// FnMut<..>` where `X` is a closure type.
1875 /// Note: the type parameters on a closure candidate are modeled as *output* type
1876 /// parameters and hence do not affect whether this trait is a match or not. They will be
1877 /// unified during the confirmation step.
1878 fn assemble_closure_candidates(
1880 obligation: &TraitObligation<'tcx>,
1881 candidates: &mut SelectionCandidateSet<'tcx>,
1882 ) -> Result<(), SelectionError<'tcx>> {
1883 let kind = match self.tcx()
1885 .fn_trait_kind(obligation.predicate.def_id())
1893 // ok to skip binder because the substs on closure types never
1894 // touch bound regions, they just capture the in-scope
1895 // type/region parameters
1896 match obligation.self_ty().skip_binder().sty {
1897 ty::Closure(closure_def_id, closure_substs) => {
1899 "assemble_unboxed_candidates: kind={:?} obligation={:?}",
1902 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1903 Some(closure_kind) => {
1905 "assemble_unboxed_candidates: closure_kind = {:?}",
1908 if closure_kind.extends(kind) {
1909 candidates.vec.push(ClosureCandidate);
1913 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1914 candidates.vec.push(ClosureCandidate);
1918 ty::Infer(ty::TyVar(_)) => {
1919 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1920 candidates.ambiguous = true;
1928 /// Implement one of the `Fn()` family for a fn pointer.
1929 fn assemble_fn_pointer_candidates(
1931 obligation: &TraitObligation<'tcx>,
1932 candidates: &mut SelectionCandidateSet<'tcx>,
1933 ) -> Result<(), SelectionError<'tcx>> {
1934 // We provide impl of all fn traits for fn pointers.
1937 .fn_trait_kind(obligation.predicate.def_id())
1943 // ok to skip binder because what we are inspecting doesn't involve bound regions
1944 let self_ty = *obligation.self_ty().skip_binder();
1946 ty::Infer(ty::TyVar(_)) => {
1947 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1948 candidates.ambiguous = true; // could wind up being a fn() type
1950 // provide an impl, but only for suitable `fn` pointers
1951 ty::FnDef(..) | ty::FnPtr(_) => {
1953 unsafety: hir::Unsafety::Normal,
1957 } = self_ty.fn_sig(self.tcx()).skip_binder()
1959 candidates.vec.push(FnPointerCandidate);
1968 /// Search for impls that might apply to `obligation`.
1969 fn assemble_candidates_from_impls(
1971 obligation: &TraitObligation<'tcx>,
1972 candidates: &mut SelectionCandidateSet<'tcx>,
1973 ) -> Result<(), SelectionError<'tcx>> {
1975 "assemble_candidates_from_impls(obligation={:?})",
1979 self.tcx().for_each_relevant_impl(
1980 obligation.predicate.def_id(),
1981 obligation.predicate.skip_binder().trait_ref.self_ty(),
1983 self.probe(|this, snapshot| {
1984 if let Ok(placeholder_map) = this.match_impl(impl_def_id, obligation, snapshot)
1986 candidates.vec.push(ImplCandidate(impl_def_id));
1988 // NB: we can safely drop the placeholder map
1989 // since we are in a probe.
1990 mem::drop(placeholder_map);
1999 fn assemble_candidates_from_auto_impls(
2001 obligation: &TraitObligation<'tcx>,
2002 candidates: &mut SelectionCandidateSet<'tcx>,
2003 ) -> Result<(), SelectionError<'tcx>> {
2004 // OK to skip binder here because the tests we do below do not involve bound regions
2005 let self_ty = *obligation.self_ty().skip_binder();
2006 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2008 let def_id = obligation.predicate.def_id();
2010 if self.tcx().trait_is_auto(def_id) {
2012 ty::Dynamic(..) => {
2013 // For object types, we don't know what the closed
2014 // over types are. This means we conservatively
2015 // say nothing; a candidate may be added by
2016 // `assemble_candidates_from_object_ty`.
2018 ty::Foreign(..) => {
2019 // Since the contents of foreign types is unknown,
2020 // we don't add any `..` impl. Default traits could
2021 // still be provided by a manual implementation for
2022 // this trait and type.
2024 ty::Param(..) | ty::Projection(..) => {
2025 // In these cases, we don't know what the actual
2026 // type is. Therefore, we cannot break it down
2027 // into its constituent types. So we don't
2028 // consider the `..` impl but instead just add no
2029 // candidates: this means that typeck will only
2030 // succeed if there is another reason to believe
2031 // that this obligation holds. That could be a
2032 // where-clause or, in the case of an object type,
2033 // it could be that the object type lists the
2034 // trait (e.g. `Foo+Send : Send`). See
2035 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2036 // for an example of a test case that exercises
2039 ty::Infer(ty::TyVar(_)) => {
2040 // the auto impl might apply, we don't know
2041 candidates.ambiguous = true;
2043 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2050 /// Search for impls that might apply to `obligation`.
2051 fn assemble_candidates_from_object_ty(
2053 obligation: &TraitObligation<'tcx>,
2054 candidates: &mut SelectionCandidateSet<'tcx>,
2057 "assemble_candidates_from_object_ty(self_ty={:?})",
2058 obligation.self_ty().skip_binder()
2061 // Object-safety candidates are only applicable to object-safe
2062 // traits. Including this check is useful because it helps
2063 // inference in cases of traits like `BorrowFrom`, which are
2064 // not object-safe, and which rely on being able to infer the
2065 // self-type from one of the other inputs. Without this check,
2066 // these cases wind up being considered ambiguous due to a
2067 // (spurious) ambiguity introduced here.
2068 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
2069 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
2073 self.probe(|this, _snapshot| {
2074 // the code below doesn't care about regions, and the
2075 // self-ty here doesn't escape this probe, so just erase
2077 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
2078 let poly_trait_ref = match self_ty.sty {
2079 ty::Dynamic(ref data, ..) => {
2080 if data.auto_traits()
2081 .any(|did| did == obligation.predicate.def_id())
2084 "assemble_candidates_from_object_ty: matched builtin bound, \
2087 candidates.vec.push(BuiltinObjectCandidate);
2091 match data.principal() {
2092 Some(p) => p.with_self_ty(this.tcx(), self_ty),
2096 ty::Infer(ty::TyVar(_)) => {
2097 debug!("assemble_candidates_from_object_ty: ambiguous");
2098 candidates.ambiguous = true; // could wind up being an object type
2105 "assemble_candidates_from_object_ty: poly_trait_ref={:?}",
2109 // Count only those upcast versions that match the trait-ref
2110 // we are looking for. Specifically, do not only check for the
2111 // correct trait, but also the correct type parameters.
2112 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2113 // but `Foo` is declared as `trait Foo : Bar<u32>`.
2114 let upcast_trait_refs = util::supertraits(this.tcx(), poly_trait_ref)
2115 .filter(|upcast_trait_ref| {
2116 this.probe(|this, _| {
2117 let upcast_trait_ref = upcast_trait_ref.clone();
2118 this.match_poly_trait_ref(obligation, upcast_trait_ref)
2124 if upcast_trait_refs > 1 {
2125 // can be upcast in many ways; need more type information
2126 candidates.ambiguous = true;
2127 } else if upcast_trait_refs == 1 {
2128 candidates.vec.push(ObjectCandidate);
2133 /// Search for unsizing that might apply to `obligation`.
2134 fn assemble_candidates_for_unsizing(
2136 obligation: &TraitObligation<'tcx>,
2137 candidates: &mut SelectionCandidateSet<'tcx>,
2139 // We currently never consider higher-ranked obligations e.g.
2140 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2141 // because they are a priori invalid, and we could potentially add support
2142 // for them later, it's just that there isn't really a strong need for it.
2143 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2144 // impl, and those are generally applied to concrete types.
2146 // That said, one might try to write a fn with a where clause like
2147 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2148 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2149 // Still, you'd be more likely to write that where clause as
2151 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2152 // obligation above. Should be possible to extend this in the future.
2153 let source = match obligation.self_ty().no_late_bound_regions() {
2156 // Don't add any candidates if there are bound regions.
2160 let target = obligation
2168 "assemble_candidates_for_unsizing(source={:?}, target={:?})",
2172 let may_apply = match (&source.sty, &target.sty) {
2173 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2174 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2175 // Upcasts permit two things:
2177 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
2178 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
2180 // Note that neither of these changes requires any
2181 // change at runtime. Eventually this will be
2184 // We always upcast when we can because of reason
2185 // #2 (region bounds).
2186 match (data_a.principal(), data_b.principal()) {
2187 (Some(a), Some(b)) => {
2188 a.def_id() == b.def_id()
2189 && data_b.auto_traits()
2190 // All of a's auto traits need to be in b's auto traits.
2191 .all(|b| data_a.auto_traits().any(|a| a == b))
2198 (_, &ty::Dynamic(..)) => true,
2200 // Ambiguous handling is below T -> Trait, because inference
2201 // variables can still implement Unsize<Trait> and nested
2202 // obligations will have the final say (likely deferred).
2203 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2204 debug!("assemble_candidates_for_unsizing: ambiguous");
2205 candidates.ambiguous = true;
2210 (&ty::Array(..), &ty::Slice(_)) => true,
2212 // Struct<T> -> Struct<U>.
2213 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2214 def_id_a == def_id_b
2217 // (.., T) -> (.., U).
2218 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2224 candidates.vec.push(BuiltinUnsizeCandidate);
2228 ///////////////////////////////////////////////////////////////////////////
2231 // Winnowing is the process of attempting to resolve ambiguity by
2232 // probing further. During the winnowing process, we unify all
2233 // type variables (ignoring skolemization) and then we also
2234 // attempt to evaluate recursive bounds to see if they are
2237 /// Returns true if `victim` should be dropped in favor of
2238 /// `other`. Generally speaking we will drop duplicate
2239 /// candidates and prefer where-clause candidates.
2241 /// See the comment for "SelectionCandidate" for more details.
2242 fn candidate_should_be_dropped_in_favor_of<'o>(
2244 victim: &EvaluatedCandidate<'tcx>,
2245 other: &EvaluatedCandidate<'tcx>,
2247 if victim.candidate == other.candidate {
2251 // Check if a bound would previously have been removed when normalizing
2252 // the param_env so that it can be given the lowest priority. See
2253 // #50825 for the motivation for this.
2255 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2257 match other.candidate {
2258 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2259 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2260 // lifetime of a variable.
2261 BuiltinCandidate { has_nested: false } => true,
2262 ParamCandidate(ref cand) => match victim.candidate {
2263 AutoImplCandidate(..) => {
2265 "default implementations shouldn't be recorded \
2266 when there are other valid candidates"
2269 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2270 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2271 // lifetime of a variable.
2272 BuiltinCandidate { has_nested: false } => false,
2275 | GeneratorCandidate
2276 | FnPointerCandidate
2277 | BuiltinObjectCandidate
2278 | BuiltinUnsizeCandidate
2279 | BuiltinCandidate { .. } => {
2280 // Global bounds from the where clause should be ignored
2281 // here (see issue #50825). Otherwise, we have a where
2282 // clause so don't go around looking for impls.
2285 ObjectCandidate | ProjectionCandidate => {
2286 // Arbitrarily give param candidates priority
2287 // over projection and object candidates.
2290 ParamCandidate(..) => false,
2292 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2293 AutoImplCandidate(..) => {
2295 "default implementations shouldn't be recorded \
2296 when there are other valid candidates"
2299 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2300 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2301 // lifetime of a variable.
2302 BuiltinCandidate { has_nested: false } => false,
2305 | GeneratorCandidate
2306 | FnPointerCandidate
2307 | BuiltinObjectCandidate
2308 | BuiltinUnsizeCandidate
2309 | BuiltinCandidate { .. } => true,
2310 ObjectCandidate | ProjectionCandidate => {
2311 // Arbitrarily give param candidates priority
2312 // over projection and object candidates.
2315 ParamCandidate(ref cand) => is_global(cand),
2317 ImplCandidate(other_def) => {
2318 // See if we can toss out `victim` based on specialization.
2319 // This requires us to know *for sure* that the `other` impl applies
2320 // i.e. EvaluatedToOk:
2321 if other.evaluation == EvaluatedToOk {
2322 match victim.candidate {
2323 ImplCandidate(victim_def) => {
2324 let tcx = self.tcx().global_tcx();
2325 return tcx.specializes((other_def, victim_def))
2326 || tcx.impls_are_allowed_to_overlap(other_def, victim_def);
2328 ParamCandidate(ref cand) => {
2329 // Prefer the impl to a global where clause candidate.
2330 return is_global(cand);
2339 | GeneratorCandidate
2340 | FnPointerCandidate
2341 | BuiltinObjectCandidate
2342 | BuiltinUnsizeCandidate
2343 | BuiltinCandidate { has_nested: true } => {
2344 match victim.candidate {
2345 ParamCandidate(ref cand) => {
2346 // Prefer these to a global where-clause bound
2347 // (see issue #50825)
2348 is_global(cand) && other.evaluation == EvaluatedToOk
2357 ///////////////////////////////////////////////////////////////////////////
2360 // These cover the traits that are built-in to the language
2361 // itself: `Copy`, `Clone` and `Sized`.
2363 fn assemble_builtin_bound_candidates<'o>(
2365 conditions: BuiltinImplConditions<'tcx>,
2366 candidates: &mut SelectionCandidateSet<'tcx>,
2367 ) -> Result<(), SelectionError<'tcx>> {
2369 BuiltinImplConditions::Where(nested) => {
2370 debug!("builtin_bound: nested={:?}", nested);
2371 candidates.vec.push(BuiltinCandidate {
2372 has_nested: nested.skip_binder().len() > 0,
2375 BuiltinImplConditions::None => {}
2376 BuiltinImplConditions::Ambiguous => {
2377 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2378 candidates.ambiguous = true;
2385 fn sized_conditions(
2387 obligation: &TraitObligation<'tcx>,
2388 ) -> BuiltinImplConditions<'tcx> {
2389 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2391 // NOTE: binder moved to (*)
2392 let self_ty = self.infcx
2393 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2396 ty::Infer(ty::IntVar(_))
2397 | ty::Infer(ty::FloatVar(_))
2408 | ty::GeneratorWitness(..)
2413 // safe for everything
2414 Where(ty::Binder::dummy(Vec::new()))
2417 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2419 ty::Tuple(tys) => Where(ty::Binder::bind(tys.last().into_iter().cloned().collect())),
2421 ty::Adt(def, substs) => {
2422 let sized_crit = def.sized_constraint(self.tcx());
2423 // (*) binder moved here
2424 Where(ty::Binder::bind(
2427 .map(|ty| ty.subst(self.tcx(), substs))
2432 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2433 ty::Infer(ty::TyVar(_)) => Ambiguous,
2435 ty::UnnormalizedProjection(..)
2436 | ty::Infer(ty::CanonicalTy(_))
2437 | ty::Infer(ty::FreshTy(_))
2438 | ty::Infer(ty::FreshIntTy(_))
2439 | ty::Infer(ty::FreshFloatTy(_)) => {
2441 "asked to assemble builtin bounds of unexpected type: {:?}",
2448 fn copy_clone_conditions(
2450 obligation: &TraitObligation<'tcx>,
2451 ) -> BuiltinImplConditions<'tcx> {
2452 // NOTE: binder moved to (*)
2453 let self_ty = self.infcx
2454 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2456 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2459 ty::Infer(ty::IntVar(_))
2460 | ty::Infer(ty::FloatVar(_))
2463 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2472 | ty::Ref(_, _, hir::MutImmutable) => {
2473 // Implementations provided in libcore
2481 | ty::GeneratorWitness(..)
2483 | ty::Ref(_, _, hir::MutMutable) => None,
2485 ty::Array(element_ty, _) => {
2486 // (*) binder moved here
2487 Where(ty::Binder::bind(vec![element_ty]))
2491 // (*) binder moved here
2492 Where(ty::Binder::bind(tys.to_vec()))
2495 ty::Closure(def_id, substs) => {
2496 let trait_id = obligation.predicate.def_id();
2497 let is_copy_trait = Some(trait_id) == self.tcx().lang_items().copy_trait();
2498 let is_clone_trait = Some(trait_id) == self.tcx().lang_items().clone_trait();
2499 if is_copy_trait || is_clone_trait {
2500 Where(ty::Binder::bind(
2501 substs.upvar_tys(def_id, self.tcx()).collect(),
2508 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2509 // Fallback to whatever user-defined impls exist in this case.
2513 ty::Infer(ty::TyVar(_)) => {
2514 // Unbound type variable. Might or might not have
2515 // applicable impls and so forth, depending on what
2516 // those type variables wind up being bound to.
2520 ty::UnnormalizedProjection(..)
2521 | ty::Infer(ty::CanonicalTy(_))
2522 | ty::Infer(ty::FreshTy(_))
2523 | ty::Infer(ty::FreshIntTy(_))
2524 | ty::Infer(ty::FreshFloatTy(_)) => {
2526 "asked to assemble builtin bounds of unexpected type: {:?}",
2533 /// For default impls, we need to break apart a type into its
2534 /// "constituent types" -- meaning, the types that it contains.
2536 /// Here are some (simple) examples:
2539 /// (i32, u32) -> [i32, u32]
2540 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2541 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2542 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2544 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2554 | ty::Infer(ty::IntVar(_))
2555 | ty::Infer(ty::FloatVar(_))
2557 | ty::Char => Vec::new(),
2559 ty::UnnormalizedProjection(..)
2563 | ty::Projection(..)
2564 | ty::Infer(ty::CanonicalTy(_))
2565 | ty::Infer(ty::TyVar(_))
2566 | ty::Infer(ty::FreshTy(_))
2567 | ty::Infer(ty::FreshIntTy(_))
2568 | ty::Infer(ty::FreshFloatTy(_)) => {
2570 "asked to assemble constituent types of unexpected type: {:?}",
2575 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2579 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2581 ty::Tuple(ref tys) => {
2582 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2586 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(),
2588 ty::Generator(def_id, ref substs, _) => {
2589 let witness = substs.witness(def_id, self.tcx());
2591 .upvar_tys(def_id, self.tcx())
2592 .chain(iter::once(witness))
2596 ty::GeneratorWitness(types) => {
2597 // This is sound because no regions in the witness can refer to
2598 // the binder outside the witness. So we'll effectivly reuse
2599 // the implicit binder around the witness.
2600 types.skip_binder().to_vec()
2603 // for `PhantomData<T>`, we pass `T`
2604 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2606 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2608 ty::Opaque(def_id, substs) => {
2609 // We can resolve the `impl Trait` to its concrete type,
2610 // which enforces a DAG between the functions requiring
2611 // the auto trait bounds in question.
2612 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2617 fn collect_predicates_for_types(
2619 param_env: ty::ParamEnv<'tcx>,
2620 cause: ObligationCause<'tcx>,
2621 recursion_depth: usize,
2622 trait_def_id: DefId,
2623 types: ty::Binder<Vec<Ty<'tcx>>>,
2624 ) -> Vec<PredicateObligation<'tcx>> {
2625 // Because the types were potentially derived from
2626 // higher-ranked obligations they may reference late-bound
2627 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2628 // yield a type like `for<'a> &'a int`. In general, we
2629 // maintain the invariant that we never manipulate bound
2630 // regions, so we have to process these bound regions somehow.
2632 // The strategy is to:
2634 // 1. Instantiate those regions to placeholder regions (e.g.,
2635 // `for<'a> &'a int` becomes `&0 int`.
2636 // 2. Produce something like `&'0 int : Copy`
2637 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2644 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2646 self.in_snapshot(|this, snapshot| {
2647 let (skol_ty, placeholder_map) = this.infcx()
2648 .replace_late_bound_regions_with_placeholders(&ty);
2650 value: normalized_ty,
2652 } = project::normalize_with_depth(
2659 let skol_obligation = this.tcx().predicate_for_trait_def(
2667 obligations.push(skol_obligation);
2669 .plug_leaks(placeholder_map, snapshot, obligations)
2675 ///////////////////////////////////////////////////////////////////////////
2678 // Confirmation unifies the output type parameters of the trait
2679 // with the values found in the obligation, possibly yielding a
2680 // type error. See [rustc guide] for more details.
2683 // https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#confirmation
2685 fn confirm_candidate(
2687 obligation: &TraitObligation<'tcx>,
2688 candidate: SelectionCandidate<'tcx>,
2689 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2690 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2693 BuiltinCandidate { has_nested } => {
2694 let data = self.confirm_builtin_candidate(obligation, has_nested);
2695 Ok(VtableBuiltin(data))
2698 ParamCandidate(param) => {
2699 let obligations = self.confirm_param_candidate(obligation, param);
2700 Ok(VtableParam(obligations))
2703 AutoImplCandidate(trait_def_id) => {
2704 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2705 Ok(VtableAutoImpl(data))
2708 ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
2713 ClosureCandidate => {
2714 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2715 Ok(VtableClosure(vtable_closure))
2718 GeneratorCandidate => {
2719 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2720 Ok(VtableGenerator(vtable_generator))
2723 BuiltinObjectCandidate => {
2724 // This indicates something like `(Trait+Send) :
2725 // Send`. In this case, we know that this holds
2726 // because that's what the object type is telling us,
2727 // and there's really no additional obligations to
2728 // prove and no types in particular to unify etc.
2729 Ok(VtableParam(Vec::new()))
2732 ObjectCandidate => {
2733 let data = self.confirm_object_candidate(obligation);
2734 Ok(VtableObject(data))
2737 FnPointerCandidate => {
2738 let data = self.confirm_fn_pointer_candidate(obligation)?;
2739 Ok(VtableFnPointer(data))
2742 ProjectionCandidate => {
2743 self.confirm_projection_candidate(obligation);
2744 Ok(VtableParam(Vec::new()))
2747 BuiltinUnsizeCandidate => {
2748 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2749 Ok(VtableBuiltin(data))
2754 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2755 self.in_snapshot(|this, snapshot| {
2757 this.match_projection_obligation_against_definition_bounds(obligation, snapshot);
2762 fn confirm_param_candidate(
2764 obligation: &TraitObligation<'tcx>,
2765 param: ty::PolyTraitRef<'tcx>,
2766 ) -> Vec<PredicateObligation<'tcx>> {
2767 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2769 // During evaluation, we already checked that this
2770 // where-clause trait-ref could be unified with the obligation
2771 // trait-ref. Repeat that unification now without any
2772 // transactional boundary; it should not fail.
2773 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2774 Ok(obligations) => obligations,
2777 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2785 fn confirm_builtin_candidate(
2787 obligation: &TraitObligation<'tcx>,
2789 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2791 "confirm_builtin_candidate({:?}, {:?})",
2792 obligation, has_nested
2795 let lang_items = self.tcx().lang_items();
2796 let obligations = if has_nested {
2797 let trait_def = obligation.predicate.def_id();
2798 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2799 self.sized_conditions(obligation)
2800 } else if Some(trait_def) == lang_items.copy_trait() {
2801 self.copy_clone_conditions(obligation)
2802 } else if Some(trait_def) == lang_items.clone_trait() {
2803 self.copy_clone_conditions(obligation)
2805 bug!("unexpected builtin trait {:?}", trait_def)
2807 let nested = match conditions {
2808 BuiltinImplConditions::Where(nested) => nested,
2810 "obligation {:?} had matched a builtin impl but now doesn't",
2815 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2816 self.collect_predicates_for_types(
2817 obligation.param_env,
2819 obligation.recursion_depth + 1,
2827 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2830 nested: obligations,
2834 /// This handles the case where a `auto trait Foo` impl is being used.
2835 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2837 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2838 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2839 fn confirm_auto_impl_candidate(
2841 obligation: &TraitObligation<'tcx>,
2842 trait_def_id: DefId,
2843 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2845 "confirm_auto_impl_candidate({:?}, {:?})",
2846 obligation, trait_def_id
2849 let types = obligation.predicate.map_bound(|inner| {
2850 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2851 self.constituent_types_for_ty(self_ty)
2853 self.vtable_auto_impl(obligation, trait_def_id, types)
2856 /// See `confirm_auto_impl_candidate`
2857 fn vtable_auto_impl(
2859 obligation: &TraitObligation<'tcx>,
2860 trait_def_id: DefId,
2861 nested: ty::Binder<Vec<Ty<'tcx>>>,
2862 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2863 debug!("vtable_auto_impl: nested={:?}", nested);
2865 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2866 let mut obligations = self.collect_predicates_for_types(
2867 obligation.param_env,
2869 obligation.recursion_depth + 1,
2874 let trait_obligations: Vec<PredicateObligation<'_>> = self.in_snapshot(|this, snapshot| {
2875 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2876 let (trait_ref, placeholder_map) = this.infcx()
2877 .replace_late_bound_regions_with_placeholders(&poly_trait_ref);
2878 let cause = obligation.derived_cause(ImplDerivedObligation);
2879 this.impl_or_trait_obligations(
2881 obligation.recursion_depth + 1,
2882 obligation.param_env,
2890 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
2891 // predicate as usual. It won't have any effect since auto traits are coinductive.
2892 obligations.extend(trait_obligations);
2894 debug!("vtable_auto_impl: obligations={:?}", obligations);
2896 VtableAutoImplData {
2898 nested: obligations,
2902 fn confirm_impl_candidate(
2904 obligation: &TraitObligation<'tcx>,
2906 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2907 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
2909 // First, create the substitutions by matching the impl again,
2910 // this time not in a probe.
2911 self.in_snapshot(|this, snapshot| {
2912 let (substs, placeholder_map) = this.rematch_impl(impl_def_id, obligation, snapshot);
2913 debug!("confirm_impl_candidate substs={:?}", substs);
2914 let cause = obligation.derived_cause(ImplDerivedObligation);
2919 obligation.recursion_depth + 1,
2920 obligation.param_env,
2930 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2931 cause: ObligationCause<'tcx>,
2932 recursion_depth: usize,
2933 param_env: ty::ParamEnv<'tcx>,
2934 placeholder_map: infer::PlaceholderMap<'tcx>,
2935 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
2936 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2938 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, placeholder_map={:?})",
2939 impl_def_id, substs, recursion_depth, placeholder_map
2942 let mut impl_obligations = self.impl_or_trait_obligations(
2953 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2954 impl_def_id, impl_obligations
2957 // Because of RFC447, the impl-trait-ref and obligations
2958 // are sufficient to determine the impl substs, without
2959 // relying on projections in the impl-trait-ref.
2961 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2962 impl_obligations.append(&mut substs.obligations);
2966 substs: substs.value,
2967 nested: impl_obligations,
2971 fn confirm_object_candidate(
2973 obligation: &TraitObligation<'tcx>,
2974 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
2975 debug!("confirm_object_candidate({:?})", obligation);
2977 // FIXME skipping binder here seems wrong -- we should
2978 // probably flatten the binder from the obligation and the
2979 // binder from the object. Have to try to make a broken test
2980 // case that results. -nmatsakis
2981 let self_ty = self.infcx
2982 .shallow_resolve(*obligation.self_ty().skip_binder());
2983 let poly_trait_ref = match self_ty.sty {
2984 ty::Dynamic(ref data, ..) => {
2985 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2987 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
2990 let mut upcast_trait_ref = None;
2991 let mut nested = vec![];
2995 let tcx = self.tcx();
2997 // We want to find the first supertrait in the list of
2998 // supertraits that we can unify with, and do that
2999 // unification. We know that there is exactly one in the list
3000 // where we can unify because otherwise select would have
3001 // reported an ambiguity. (When we do find a match, also
3002 // record it for later.)
3003 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
3004 |&t| match self.commit_if_ok(|this, _| this.match_poly_trait_ref(obligation, t)) {
3005 Ok(obligations) => {
3006 upcast_trait_ref = Some(t);
3007 nested.extend(obligations);
3014 // Additionally, for each of the nonmatching predicates that
3015 // we pass over, we sum up the set of number of vtable
3016 // entries, so that we can compute the offset for the selected
3018 vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
3022 upcast_trait_ref: upcast_trait_ref.unwrap(),
3028 fn confirm_fn_pointer_candidate(
3030 obligation: &TraitObligation<'tcx>,
3031 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3032 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3034 // ok to skip binder; it is reintroduced below
3035 let self_ty = self.infcx
3036 .shallow_resolve(*obligation.self_ty().skip_binder());
3037 let sig = self_ty.fn_sig(self.tcx());
3038 let trait_ref = self.tcx()
3039 .closure_trait_ref_and_return_type(
3040 obligation.predicate.def_id(),
3043 util::TupleArgumentsFlag::Yes,
3045 .map_bound(|(trait_ref, _)| trait_ref);
3050 } = project::normalize_with_depth(
3052 obligation.param_env,
3053 obligation.cause.clone(),
3054 obligation.recursion_depth + 1,
3058 self.confirm_poly_trait_refs(
3059 obligation.cause.clone(),
3060 obligation.param_env,
3061 obligation.predicate.to_poly_trait_ref(),
3064 Ok(VtableFnPointerData {
3066 nested: obligations,
3070 fn confirm_generator_candidate(
3072 obligation: &TraitObligation<'tcx>,
3073 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3074 // ok to skip binder because the substs on generator types never
3075 // touch bound regions, they just capture the in-scope
3076 // type/region parameters
3077 let self_ty = self.infcx
3078 .shallow_resolve(obligation.self_ty().skip_binder());
3079 let (generator_def_id, substs) = match self_ty.sty {
3080 ty::Generator(id, substs, _) => (id, substs),
3081 _ => bug!("closure candidate for non-closure {:?}", obligation),
3085 "confirm_generator_candidate({:?},{:?},{:?})",
3086 obligation, generator_def_id, substs
3089 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3093 } = normalize_with_depth(
3095 obligation.param_env,
3096 obligation.cause.clone(),
3097 obligation.recursion_depth + 1,
3102 "confirm_generator_candidate(generator_def_id={:?}, \
3103 trait_ref={:?}, obligations={:?})",
3104 generator_def_id, trait_ref, obligations
3107 obligations.extend(self.confirm_poly_trait_refs(
3108 obligation.cause.clone(),
3109 obligation.param_env,
3110 obligation.predicate.to_poly_trait_ref(),
3114 Ok(VtableGeneratorData {
3115 generator_def_id: generator_def_id,
3116 substs: substs.clone(),
3117 nested: obligations,
3121 fn confirm_closure_candidate(
3123 obligation: &TraitObligation<'tcx>,
3124 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3125 debug!("confirm_closure_candidate({:?})", obligation);
3127 let kind = self.tcx()
3129 .fn_trait_kind(obligation.predicate.def_id())
3130 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3132 // ok to skip binder because the substs on closure types never
3133 // touch bound regions, they just capture the in-scope
3134 // type/region parameters
3135 let self_ty = self.infcx
3136 .shallow_resolve(obligation.self_ty().skip_binder());
3137 let (closure_def_id, substs) = match self_ty.sty {
3138 ty::Closure(id, substs) => (id, substs),
3139 _ => bug!("closure candidate for non-closure {:?}", obligation),
3142 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3146 } = normalize_with_depth(
3148 obligation.param_env,
3149 obligation.cause.clone(),
3150 obligation.recursion_depth + 1,
3155 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3156 closure_def_id, trait_ref, obligations
3159 obligations.extend(self.confirm_poly_trait_refs(
3160 obligation.cause.clone(),
3161 obligation.param_env,
3162 obligation.predicate.to_poly_trait_ref(),
3166 obligations.push(Obligation::new(
3167 obligation.cause.clone(),
3168 obligation.param_env,
3169 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3172 Ok(VtableClosureData {
3174 substs: substs.clone(),
3175 nested: obligations,
3179 /// In the case of closure types and fn pointers,
3180 /// we currently treat the input type parameters on the trait as
3181 /// outputs. This means that when we have a match we have only
3182 /// considered the self type, so we have to go back and make sure
3183 /// to relate the argument types too. This is kind of wrong, but
3184 /// since we control the full set of impls, also not that wrong,
3185 /// and it DOES yield better error messages (since we don't report
3186 /// errors as if there is no applicable impl, but rather report
3187 /// errors are about mismatched argument types.
3189 /// Here is an example. Imagine we have a closure expression
3190 /// and we desugared it so that the type of the expression is
3191 /// `Closure`, and `Closure` expects an int as argument. Then it
3192 /// is "as if" the compiler generated this impl:
3194 /// impl Fn(int) for Closure { ... }
3196 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3197 /// we have matched the self-type `Closure`. At this point we'll
3198 /// compare the `int` to `usize` and generate an error.
3200 /// Note that this checking occurs *after* the impl has selected,
3201 /// because these output type parameters should not affect the
3202 /// selection of the impl. Therefore, if there is a mismatch, we
3203 /// report an error to the user.
3204 fn confirm_poly_trait_refs(
3206 obligation_cause: ObligationCause<'tcx>,
3207 obligation_param_env: ty::ParamEnv<'tcx>,
3208 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3209 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3210 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3211 let obligation_trait_ref = obligation_trait_ref.clone();
3213 .at(&obligation_cause, obligation_param_env)
3214 .sup(obligation_trait_ref, expected_trait_ref)
3215 .map(|InferOk { obligations, .. }| obligations)
3216 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3219 fn confirm_builtin_unsize_candidate(
3221 obligation: &TraitObligation<'tcx>,
3222 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3223 let tcx = self.tcx();
3225 // assemble_candidates_for_unsizing should ensure there are no late bound
3226 // regions here. See the comment there for more details.
3227 let source = self.infcx
3228 .shallow_resolve(obligation.self_ty().no_late_bound_regions().unwrap());
3229 let target = obligation
3235 let target = self.infcx.shallow_resolve(target);
3238 "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
3242 let mut nested = vec![];
3243 match (&source.sty, &target.sty) {
3244 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3245 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3246 // See assemble_candidates_for_unsizing for more info.
3247 let existential_predicates = data_a.map_bound(|data_a| {
3248 let principal = data_a.principal();
3249 let iter = principal
3251 .map(ty::ExistentialPredicate::Trait)
3254 .projection_bounds()
3255 .map(|x| ty::ExistentialPredicate::Projection(x)),
3260 .map(ty::ExistentialPredicate::AutoTrait),
3262 tcx.mk_existential_predicates(iter)
3264 let new_trait = tcx.mk_dynamic(existential_predicates, r_b);
3265 let InferOk { obligations, .. } = self.infcx
3266 .at(&obligation.cause, obligation.param_env)
3267 .eq(target, new_trait)
3268 .map_err(|_| Unimplemented)?;
3269 nested.extend(obligations);
3271 // Register one obligation for 'a: 'b.
3272 let cause = ObligationCause::new(
3273 obligation.cause.span,
3274 obligation.cause.body_id,
3275 ObjectCastObligation(target),
3277 let outlives = ty::OutlivesPredicate(r_a, r_b);
3278 nested.push(Obligation::with_depth(
3280 obligation.recursion_depth + 1,
3281 obligation.param_env,
3282 ty::Binder::bind(outlives).to_predicate(),
3287 (_, &ty::Dynamic(ref data, r)) => {
3288 let mut object_dids = data.auto_traits()
3289 .chain(data.principal().map(|p| p.def_id()));
3290 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3291 return Err(TraitNotObjectSafe(did));
3294 let cause = ObligationCause::new(
3295 obligation.cause.span,
3296 obligation.cause.body_id,
3297 ObjectCastObligation(target),
3300 let predicate_to_obligation = |predicate| {
3301 Obligation::with_depth(
3303 obligation.recursion_depth + 1,
3304 obligation.param_env,
3309 // Create obligations:
3310 // - Casting T to Trait
3311 // - For all the various builtin bounds attached to the object cast. (In other
3312 // words, if the object type is Foo+Send, this would create an obligation for the
3314 // - Projection predicates
3317 .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
3320 // We can only make objects from sized types.
3321 let tr = ty::TraitRef {
3322 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
3323 substs: tcx.mk_substs_trait(source, &[]),
3325 nested.push(predicate_to_obligation(tr.to_predicate()));
3327 // If the type is `Foo+'a`, ensures that the type
3328 // being cast to `Foo+'a` outlives `'a`:
3329 let outlives = ty::OutlivesPredicate(source, r);
3330 nested.push(predicate_to_obligation(
3331 ty::Binder::dummy(outlives).to_predicate(),
3336 (&ty::Array(a, _), &ty::Slice(b)) => {
3337 let InferOk { obligations, .. } = self.infcx
3338 .at(&obligation.cause, obligation.param_env)
3340 .map_err(|_| Unimplemented)?;
3341 nested.extend(obligations);
3344 // Struct<T> -> Struct<U>.
3345 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3346 let fields = def.all_fields()
3347 .map(|f| tcx.type_of(f.did))
3348 .collect::<Vec<_>>();
3350 // The last field of the structure has to exist and contain type parameters.
3351 let field = if let Some(&field) = fields.last() {
3354 return Err(Unimplemented);
3356 let mut ty_params = GrowableBitSet::new_empty();
3357 let mut found = false;
3358 for ty in field.walk() {
3359 if let ty::Param(p) = ty.sty {
3360 ty_params.insert(p.idx as usize);
3365 return Err(Unimplemented);
3368 // Replace type parameters used in unsizing with
3369 // Error and ensure they do not affect any other fields.
3370 // This could be checked after type collection for any struct
3371 // with a potentially unsized trailing field.
3372 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3373 if ty_params.contains(i) {
3374 tcx.types.err.into()
3379 let substs = tcx.mk_substs(params);
3380 for &ty in fields.split_last().unwrap().1 {
3381 if ty.subst(tcx, substs).references_error() {
3382 return Err(Unimplemented);
3386 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3387 let inner_source = field.subst(tcx, substs_a);
3388 let inner_target = field.subst(tcx, substs_b);
3390 // Check that the source struct with the target's
3391 // unsized parameters is equal to the target.
3392 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3393 if ty_params.contains(i) {
3394 substs_b.type_at(i).into()
3399 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3400 let InferOk { obligations, .. } = self.infcx
3401 .at(&obligation.cause, obligation.param_env)
3402 .eq(target, new_struct)
3403 .map_err(|_| Unimplemented)?;
3404 nested.extend(obligations);
3406 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3407 nested.push(tcx.predicate_for_trait_def(
3408 obligation.param_env,
3409 obligation.cause.clone(),
3410 obligation.predicate.def_id(),
3411 obligation.recursion_depth + 1,
3413 &[inner_target.into()],
3417 // (.., T) -> (.., U).
3418 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3419 assert_eq!(tys_a.len(), tys_b.len());
3421 // The last field of the tuple has to exist.
3422 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3425 return Err(Unimplemented);
3427 let &b_last = tys_b.last().unwrap();
3429 // Check that the source tuple with the target's
3430 // last element is equal to the target.
3431 let new_tuple = tcx.mk_tup(a_mid.iter().cloned().chain(iter::once(b_last)));
3432 let InferOk { obligations, .. } = self.infcx
3433 .at(&obligation.cause, obligation.param_env)
3434 .eq(target, new_tuple)
3435 .map_err(|_| Unimplemented)?;
3436 nested.extend(obligations);
3438 // Construct the nested T: Unsize<U> predicate.
3439 nested.push(tcx.predicate_for_trait_def(
3440 obligation.param_env,
3441 obligation.cause.clone(),
3442 obligation.predicate.def_id(),
3443 obligation.recursion_depth + 1,
3452 Ok(VtableBuiltinData { nested: nested })
3455 ///////////////////////////////////////////////////////////////////////////
3458 // Matching is a common path used for both evaluation and
3459 // confirmation. It basically unifies types that appear in impls
3460 // and traits. This does affect the surrounding environment;
3461 // therefore, when used during evaluation, match routines must be
3462 // run inside of a `probe()` so that their side-effects are
3468 obligation: &TraitObligation<'tcx>,
3469 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3471 Normalized<'tcx, &'tcx Substs<'tcx>>,
3472 infer::PlaceholderMap<'tcx>,
3474 match self.match_impl(impl_def_id, obligation, snapshot) {
3475 Ok((substs, placeholder_map)) => (substs, placeholder_map),
3478 "Impl {:?} was matchable against {:?} but now is not",
3489 obligation: &TraitObligation<'tcx>,
3490 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3493 Normalized<'tcx, &'tcx Substs<'tcx>>,
3494 infer::PlaceholderMap<'tcx>,
3498 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3500 // Before we create the substitutions and everything, first
3501 // consider a "quick reject". This avoids creating more types
3502 // and so forth that we need to.
3503 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3507 let (skol_obligation, placeholder_map) = self.infcx()
3508 .replace_late_bound_regions_with_placeholders(&obligation.predicate);
3509 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3511 let impl_substs = self.infcx
3512 .fresh_substs_for_item(obligation.cause.span, impl_def_id);
3514 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3517 value: impl_trait_ref,
3518 obligations: mut nested_obligations,
3519 } = project::normalize_with_depth(
3521 obligation.param_env,
3522 obligation.cause.clone(),
3523 obligation.recursion_depth + 1,
3528 "match_impl(impl_def_id={:?}, obligation={:?}, \
3529 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3530 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3533 let InferOk { obligations, .. } = self.infcx
3534 .at(&obligation.cause, obligation.param_env)
3535 .eq(skol_obligation_trait_ref, impl_trait_ref)
3536 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3537 nested_obligations.extend(obligations);
3541 .leak_check(false, obligation.cause.span, &placeholder_map, snapshot)
3543 debug!("match_impl: failed leak check due to `{}`", e);
3547 debug!("match_impl: success impl_substs={:?}", impl_substs);
3551 obligations: nested_obligations,
3557 fn fast_reject_trait_refs(
3559 obligation: &TraitObligation<'_>,
3560 impl_trait_ref: &ty::TraitRef<'_>,
3562 // We can avoid creating type variables and doing the full
3563 // substitution if we find that any of the input types, when
3564 // simplified, do not match.
3570 .zip(impl_trait_ref.input_types())
3571 .any(|(obligation_ty, impl_ty)| {
3572 let simplified_obligation_ty =
3573 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3574 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3576 simplified_obligation_ty.is_some()
3577 && simplified_impl_ty.is_some()
3578 && simplified_obligation_ty != simplified_impl_ty
3582 /// Normalize `where_clause_trait_ref` and try to match it against
3583 /// `obligation`. If successful, return any predicates that
3584 /// result from the normalization. Normalization is necessary
3585 /// because where-clauses are stored in the parameter environment
3587 fn match_where_clause_trait_ref(
3589 obligation: &TraitObligation<'tcx>,
3590 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3591 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3592 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3595 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3596 /// obligation is satisfied.
3597 fn match_poly_trait_ref(
3599 obligation: &TraitObligation<'tcx>,
3600 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3601 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3603 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3604 obligation, poly_trait_ref
3608 .at(&obligation.cause, obligation.param_env)
3609 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3610 .map(|InferOk { obligations, .. }| obligations)
3614 ///////////////////////////////////////////////////////////////////////////
3617 fn match_fresh_trait_refs(
3619 previous: &ty::PolyTraitRef<'tcx>,
3620 current: &ty::PolyTraitRef<'tcx>,
3622 let mut matcher = ty::_match::Match::new(self.tcx());
3623 matcher.relate(previous, current).is_ok()
3626 fn push_stack<'o, 's: 'o>(
3628 previous_stack: TraitObligationStackList<'s, 'tcx>,
3629 obligation: &'o TraitObligation<'tcx>,
3630 ) -> TraitObligationStack<'o, 'tcx> {
3631 let fresh_trait_ref = obligation
3633 .to_poly_trait_ref()
3634 .fold_with(&mut self.freshener);
3636 TraitObligationStack {
3639 previous: previous_stack,
3643 fn closure_trait_ref_unnormalized(
3645 obligation: &TraitObligation<'tcx>,
3646 closure_def_id: DefId,
3647 substs: ty::ClosureSubsts<'tcx>,
3648 ) -> ty::PolyTraitRef<'tcx> {
3649 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3651 // (1) Feels icky to skip the binder here, but OTOH we know
3652 // that the self-type is an unboxed closure type and hence is
3653 // in fact unparameterized (or at least does not reference any
3654 // regions bound in the obligation). Still probably some
3655 // refactoring could make this nicer.
3657 .closure_trait_ref_and_return_type(
3658 obligation.predicate.def_id(),
3659 obligation.predicate.skip_binder().self_ty(), // (1)
3661 util::TupleArgumentsFlag::No,
3663 .map_bound(|(trait_ref, _)| trait_ref)
3666 fn generator_trait_ref_unnormalized(
3668 obligation: &TraitObligation<'tcx>,
3669 closure_def_id: DefId,
3670 substs: ty::GeneratorSubsts<'tcx>,
3671 ) -> ty::PolyTraitRef<'tcx> {
3672 let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
3674 // (1) Feels icky to skip the binder here, but OTOH we know
3675 // that the self-type is an generator type and hence is
3676 // in fact unparameterized (or at least does not reference any
3677 // regions bound in the obligation). Still probably some
3678 // refactoring could make this nicer.
3681 .generator_trait_ref_and_outputs(
3682 obligation.predicate.def_id(),
3683 obligation.predicate.skip_binder().self_ty(), // (1)
3686 .map_bound(|(trait_ref, ..)| trait_ref)
3689 /// Returns the obligations that are implied by instantiating an
3690 /// impl or trait. The obligations are substituted and fully
3691 /// normalized. This is used when confirming an impl or default
3693 fn impl_or_trait_obligations(
3695 cause: ObligationCause<'tcx>,
3696 recursion_depth: usize,
3697 param_env: ty::ParamEnv<'tcx>,
3698 def_id: DefId, // of impl or trait
3699 substs: &Substs<'tcx>, // for impl or trait
3700 placeholder_map: infer::PlaceholderMap<'tcx>,
3701 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3702 ) -> Vec<PredicateObligation<'tcx>> {
3703 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3704 let tcx = self.tcx();
3706 // To allow for one-pass evaluation of the nested obligation,
3707 // each predicate must be preceded by the obligations required
3709 // for example, if we have:
3710 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3711 // the impl will have the following predicates:
3712 // <V as Iterator>::Item = U,
3713 // U: Iterator, U: Sized,
3714 // V: Iterator, V: Sized,
3715 // <U as Iterator>::Item: Copy
3716 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3717 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3718 // `$1: Copy`, so we must ensure the obligations are emitted in
3720 let predicates = tcx.predicates_of(def_id);
3721 assert_eq!(predicates.parent, None);
3722 let mut predicates: Vec<_> = predicates
3725 .flat_map(|(predicate, _)| {
3726 let predicate = normalize_with_depth(
3731 &predicate.subst(tcx, substs),
3733 predicate.obligations.into_iter().chain(Some(Obligation {
3734 cause: cause.clone(),
3737 predicate: predicate.value,
3742 // We are performing deduplication here to avoid exponential blowups
3743 // (#38528) from happening, but the real cause of the duplication is
3744 // unknown. What we know is that the deduplication avoids exponential
3745 // amount of predicates being propagated when processing deeply nested
3748 // This code is hot enough that it's worth avoiding the allocation
3749 // required for the FxHashSet when possible. Special-casing lengths 0,
3750 // 1 and 2 covers roughly 75--80% of the cases.
3751 if predicates.len() <= 1 {
3752 // No possibility of duplicates.
3753 } else if predicates.len() == 2 {
3754 // Only two elements. Drop the second if they are equal.
3755 if predicates[0] == predicates[1] {
3756 predicates.truncate(1);
3759 // Three or more elements. Use a general deduplication process.
3760 let mut seen = FxHashSet();
3761 predicates.retain(|i| seen.insert(i.clone()));
3764 .plug_leaks(placeholder_map, snapshot, predicates)
3768 impl<'tcx> TraitObligation<'tcx> {
3769 #[allow(unused_comparisons)]
3770 pub fn derived_cause(
3772 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3773 ) -> ObligationCause<'tcx> {
3775 * Creates a cause for obligations that are derived from
3776 * `obligation` by a recursive search (e.g., for a builtin
3777 * bound, or eventually a `auto trait Foo`). If `obligation`
3778 * is itself a derived obligation, this is just a clone, but
3779 * otherwise we create a "derived obligation" cause so as to
3780 * keep track of the original root obligation for error
3784 let obligation = self;
3786 // NOTE(flaper87): As of now, it keeps track of the whole error
3787 // chain. Ideally, we should have a way to configure this either
3788 // by using -Z verbose or just a CLI argument.
3789 if obligation.recursion_depth >= 0 {
3790 let derived_cause = DerivedObligationCause {
3791 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3792 parent_code: Rc::new(obligation.cause.code.clone()),
3794 let derived_code = variant(derived_cause);
3795 ObligationCause::new(
3796 obligation.cause.span,
3797 obligation.cause.body_id,
3801 obligation.cause.clone()
3806 impl<'tcx> SelectionCache<'tcx> {
3807 pub fn new() -> SelectionCache<'tcx> {
3809 hashmap: Lock::new(FxHashMap()),
3813 pub fn clear(&self) {
3814 *self.hashmap.borrow_mut() = FxHashMap()
3818 impl<'tcx> EvaluationCache<'tcx> {
3819 pub fn new() -> EvaluationCache<'tcx> {
3821 hashmap: Lock::new(FxHashMap()),
3825 pub fn clear(&self) {
3826 *self.hashmap.borrow_mut() = FxHashMap()
3830 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
3831 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3832 TraitObligationStackList::with(self)
3835 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3840 #[derive(Copy, Clone)]
3841 struct TraitObligationStackList<'o, 'tcx: 'o> {
3842 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3845 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3846 fn empty() -> TraitObligationStackList<'o, 'tcx> {
3847 TraitObligationStackList { head: None }
3850 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3851 TraitObligationStackList { head: Some(r) }
3855 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
3856 type Item = &'o TraitObligationStack<'o, 'tcx>;
3858 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3869 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
3870 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3871 write!(f, "TraitObligationStack({:?})", self.obligation)
3875 #[derive(Clone, Eq, PartialEq)]
3876 pub struct WithDepNode<T> {
3877 dep_node: DepNodeIndex,
3881 impl<T: Clone> WithDepNode<T> {
3882 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3889 pub fn get(&self, tcx: TyCtxt<'_, '_, '_>) -> T {
3890 tcx.dep_graph.read_index(self.dep_node);
3891 self.cached_value.clone()