1 // ignore-tidy-filelength
3 //! Candidate selection. See the [rustc guide] for more information on how this works.
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html#selection
7 use self::EvaluationResult::*;
8 use self::SelectionCandidate::*;
10 use super::coherence::{self, Conflict};
12 use super::project::{normalize_with_depth, Normalized, ProjectionCacheKey};
14 use super::DerivedObligationCause;
16 use super::SelectionResult;
17 use super::TraitNotObjectSafe;
18 use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
19 use super::{IntercrateMode, TraitQueryMode};
20 use super::{ObjectCastObligation, Obligation};
21 use super::{ObligationCause, PredicateObligation, TraitObligation};
22 use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
24 VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
25 VtableObject, VtableParam, VtableTraitAlias,
28 VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
29 VtableGeneratorData, VtableImplData, VtableObjectData, VtableTraitAliasData,
32 use crate::dep_graph::{DepKind, DepNodeIndex};
33 use crate::hir::def_id::DefId;
34 use crate::infer::{CombinedSnapshot, InferCtxt, InferOk, PlaceholderMap, TypeFreshener};
35 use crate::middle::lang_items;
36 use crate::mir::interpret::GlobalId;
37 use crate::ty::fast_reject;
38 use crate::ty::relate::TypeRelation;
39 use crate::ty::subst::{Subst, SubstsRef};
40 use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
43 use rustc_index::bit_set::GrowableBitSet;
44 use rustc_data_structures::sync::Lock;
45 use rustc_target::spec::abi::Abi;
47 use syntax::symbol::sym;
48 use std::cell::{Cell, RefCell};
50 use std::fmt::{self, Display};
53 use crate::util::nodemap::{FxHashMap, FxHashSet};
55 pub struct SelectionContext<'cx, 'tcx> {
56 infcx: &'cx InferCtxt<'cx, 'tcx>,
58 /// Freshener used specifically for entries on the obligation
59 /// stack. This ensures that all entries on the stack at one time
60 /// will have the same set of placeholder entries, which is
61 /// important for checking for trait bounds that recursively
62 /// require themselves.
63 freshener: TypeFreshener<'cx, 'tcx>,
65 /// If `true`, indicates that the evaluation should be conservative
66 /// and consider the possibility of types outside this crate.
67 /// This comes up primarily when resolving ambiguity. Imagine
68 /// there is some trait reference `$0: Bar` where `$0` is an
69 /// inference variable. If `intercrate` is true, then we can never
70 /// say for sure that this reference is not implemented, even if
71 /// there are *no impls at all for `Bar`*, because `$0` could be
72 /// bound to some type that in a downstream crate that implements
73 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
74 /// though, we set this to false, because we are only interested
75 /// in types that the user could actually have written --- in
76 /// other words, we consider `$0: Bar` to be unimplemented if
77 /// there is no type that the user could *actually name* that
78 /// would satisfy it. This avoids crippling inference, basically.
79 intercrate: Option<IntercrateMode>,
81 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
83 /// Controls whether or not to filter out negative impls when selecting.
84 /// This is used in librustdoc to distinguish between the lack of an impl
85 /// and a negative impl
86 allow_negative_impls: bool,
88 /// The mode that trait queries run in, which informs our error handling
89 /// policy. In essence, canonicalized queries need their errors propagated
90 /// rather than immediately reported because we do not have accurate spans.
91 query_mode: TraitQueryMode,
94 #[derive(Clone, Debug)]
95 pub enum IntercrateAmbiguityCause {
98 self_desc: Option<String>,
100 UpstreamCrateUpdate {
102 self_desc: Option<String>,
109 impl IntercrateAmbiguityCause {
110 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
111 /// See #23980 for details.
112 pub fn add_intercrate_ambiguity_hint(&self, err: &mut errors::DiagnosticBuilder<'_>) {
113 err.note(&self.intercrate_ambiguity_hint());
116 pub fn intercrate_ambiguity_hint(&self) -> String {
118 &IntercrateAmbiguityCause::DownstreamCrate {
122 let self_desc = if let &Some(ref ty) = self_desc {
123 format!(" for type `{}`", ty)
128 "downstream crates may implement trait `{}`{}",
129 trait_desc, self_desc
132 &IntercrateAmbiguityCause::UpstreamCrateUpdate {
136 let self_desc = if let &Some(ref ty) = self_desc {
137 format!(" for type `{}`", ty)
142 "upstream crates may add a new impl of trait `{}`{} \
144 trait_desc, self_desc
147 &IntercrateAmbiguityCause::ReservationImpl {
156 // A stack that walks back up the stack frame.
157 struct TraitObligationStack<'prev, 'tcx> {
158 obligation: &'prev TraitObligation<'tcx>,
160 /// Trait ref from `obligation` but "freshened" with the
161 /// selection-context's freshener. Used to check for recursion.
162 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
164 /// Starts out equal to `depth` -- if, during evaluation, we
165 /// encounter a cycle, then we will set this flag to the minimum
166 /// depth of that cycle for all participants in the cycle. These
167 /// participants will then forego caching their results. This is
168 /// not the most efficient solution, but it addresses #60010. The
169 /// problem we are trying to prevent:
171 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
172 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
173 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
175 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
176 /// is `EvaluatedToOk`; this is because they were only considered
177 /// ok on the premise that if `A: AutoTrait` held, but we indeed
178 /// encountered a problem (later on) with `A: AutoTrait. So we
179 /// currently set a flag on the stack node for `B: AutoTrait` (as
180 /// well as the second instance of `A: AutoTrait`) to suppress
183 /// This is a simple, targeted fix. A more-performant fix requires
184 /// deeper changes, but would permit more caching: we could
185 /// basically defer caching until we have fully evaluated the
186 /// tree, and then cache the entire tree at once. In any case, the
187 /// performance impact here shouldn't be so horrible: every time
188 /// this is hit, we do cache at least one trait, so we only
189 /// evaluate each member of a cycle up to N times, where N is the
190 /// length of the cycle. This means the performance impact is
191 /// bounded and we shouldn't have any terrible worst-cases.
192 reached_depth: Cell<usize>,
194 previous: TraitObligationStackList<'prev, 'tcx>,
196 /// Number of parent frames plus one -- so the topmost frame has depth 1.
199 /// Depth-first number of this node in the search graph -- a
200 /// pre-order index. Basically a freshly incremented counter.
204 #[derive(Clone, Default)]
205 pub struct SelectionCache<'tcx> {
207 FxHashMap<ty::TraitRef<'tcx>, WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
211 /// The selection process begins by considering all impls, where
212 /// clauses, and so forth that might resolve an obligation. Sometimes
213 /// we'll be able to say definitively that (e.g.) an impl does not
214 /// apply to the obligation: perhaps it is defined for `usize` but the
215 /// obligation is for `int`. In that case, we drop the impl out of the
216 /// list. But the other cases are considered *candidates*.
218 /// For selection to succeed, there must be exactly one matching
219 /// candidate. If the obligation is fully known, this is guaranteed
220 /// by coherence. However, if the obligation contains type parameters
221 /// or variables, there may be multiple such impls.
223 /// It is not a real problem if multiple matching impls exist because
224 /// of type variables - it just means the obligation isn't sufficiently
225 /// elaborated. In that case we report an ambiguity, and the caller can
226 /// try again after more type information has been gathered or report a
227 /// "type annotations needed" error.
229 /// However, with type parameters, this can be a real problem - type
230 /// parameters don't unify with regular types, but they *can* unify
231 /// with variables from blanket impls, and (unless we know its bounds
232 /// will always be satisfied) picking the blanket impl will be wrong
233 /// for at least *some* substitutions. To make this concrete, if we have
235 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
236 /// impl<T: fmt::Debug> AsDebug for T {
238 /// fn debug(self) -> fmt::Debug { self }
240 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
242 /// we can't just use the impl to resolve the <T as AsDebug> obligation
243 /// - a type from another crate (that doesn't implement fmt::Debug) could
244 /// implement AsDebug.
246 /// Because where-clauses match the type exactly, multiple clauses can
247 /// only match if there are unresolved variables, and we can mostly just
248 /// report this ambiguity in that case. This is still a problem - we can't
249 /// *do anything* with ambiguities that involve only regions. This is issue
252 /// If a single where-clause matches and there are no inference
253 /// variables left, then it definitely matches and we can just select
256 /// In fact, we even select the where-clause when the obligation contains
257 /// inference variables. The can lead to inference making "leaps of logic",
258 /// for example in this situation:
260 /// pub trait Foo<T> { fn foo(&self) -> T; }
261 /// impl<T> Foo<()> for T { fn foo(&self) { } }
262 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
264 /// pub fn foo<T>(t: T) where T: Foo<bool> {
265 /// println!("{:?}", <T as Foo<_>>::foo(&t));
267 /// fn main() { foo(false); }
269 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
270 /// impl and the where-clause. We select the where-clause and unify $0=bool,
271 /// so the program prints "false". However, if the where-clause is omitted,
272 /// the blanket impl is selected, we unify $0=(), and the program prints
275 /// Exactly the same issues apply to projection and object candidates, except
276 /// that we can have both a projection candidate and a where-clause candidate
277 /// for the same obligation. In that case either would do (except that
278 /// different "leaps of logic" would occur if inference variables are
279 /// present), and we just pick the where-clause. This is, for example,
280 /// required for associated types to work in default impls, as the bounds
281 /// are visible both as projection bounds and as where-clauses from the
282 /// parameter environment.
283 #[derive(PartialEq, Eq, Debug, Clone, TypeFoldable)]
284 enum SelectionCandidate<'tcx> {
285 /// If has_nested is false, there are no *further* obligations
289 ParamCandidate(ty::PolyTraitRef<'tcx>),
290 ImplCandidate(DefId),
291 AutoImplCandidate(DefId),
293 /// This is a trait matching with a projected type as `Self`, and
294 /// we found an applicable bound in the trait definition.
297 /// Implementation of a `Fn`-family trait by one of the anonymous types
298 /// generated for a `||` expression.
301 /// Implementation of a `Generator` trait by one of the anonymous types
302 /// generated for a generator.
305 /// Implementation of a `Fn`-family trait by one of the anonymous
306 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
309 TraitAliasCandidate(DefId),
313 BuiltinObjectCandidate,
315 BuiltinUnsizeCandidate,
318 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
319 type Lifted = SelectionCandidate<'tcx>;
320 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
322 BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
323 ImplCandidate(def_id) => ImplCandidate(def_id),
324 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
325 ProjectionCandidate => ProjectionCandidate,
326 ClosureCandidate => ClosureCandidate,
327 GeneratorCandidate => GeneratorCandidate,
328 FnPointerCandidate => FnPointerCandidate,
329 TraitAliasCandidate(def_id) => TraitAliasCandidate(def_id),
330 ObjectCandidate => ObjectCandidate,
331 BuiltinObjectCandidate => BuiltinObjectCandidate,
332 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
334 ParamCandidate(ref trait_ref) => {
335 return tcx.lift(trait_ref).map(ParamCandidate);
341 struct SelectionCandidateSet<'tcx> {
342 // a list of candidates that definitely apply to the current
343 // obligation (meaning: types unify).
344 vec: Vec<SelectionCandidate<'tcx>>,
346 // if this is true, then there were candidates that might or might
347 // not have applied, but we couldn't tell. This occurs when some
348 // of the input types are type variables, in which case there are
349 // various "builtin" rules that might or might not trigger.
353 #[derive(PartialEq, Eq, Debug, Clone)]
354 struct EvaluatedCandidate<'tcx> {
355 candidate: SelectionCandidate<'tcx>,
356 evaluation: EvaluationResult,
359 /// When does the builtin impl for `T: Trait` apply?
360 enum BuiltinImplConditions<'tcx> {
361 /// The impl is conditional on T1,T2,.. : Trait
362 Where(ty::Binder<Vec<Ty<'tcx>>>),
363 /// There is no built-in impl. There may be some other
364 /// candidate (a where-clause or user-defined impl).
366 /// It is unknown whether there is an impl.
370 /// The result of trait evaluation. The order is important
371 /// here as the evaluation of a list is the maximum of the
374 /// The evaluation results are ordered:
375 /// - `EvaluatedToOk` implies `EvaluatedToOkModuloRegions`
376 /// implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
377 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
378 /// - the "union" of evaluation results is equal to their maximum -
379 /// all the "potential success" candidates can potentially succeed,
380 /// so they are noops when unioned with a definite error, and within
381 /// the categories it's easy to see that the unions are correct.
382 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, HashStable)]
383 pub enum EvaluationResult {
384 /// Evaluation successful
386 /// Evaluation successful, but there were unevaluated region obligations
387 EvaluatedToOkModuloRegions,
388 /// Evaluation is known to be ambiguous - it *might* hold for some
389 /// assignment of inference variables, but it might not.
391 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
392 /// know whether this obligation holds or not - it is the result we
393 /// would get with an empty stack, and therefore is cacheable.
395 /// Evaluation failed because of recursion involving inference
396 /// variables. We are somewhat imprecise there, so we don't actually
397 /// know the real result.
399 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
401 /// Evaluation failed because we encountered an obligation we are already
402 /// trying to prove on this branch.
404 /// We know this branch can't be a part of a minimal proof-tree for
405 /// the "root" of our cycle, because then we could cut out the recursion
406 /// and maintain a valid proof tree. However, this does not mean
407 /// that all the obligations on this branch do not hold - it's possible
408 /// that we entered this branch "speculatively", and that there
409 /// might be some other way to prove this obligation that does not
410 /// go through this cycle - so we can't cache this as a failure.
412 /// For example, suppose we have this:
414 /// ```rust,ignore (pseudo-Rust)
415 /// pub trait Trait { fn xyz(); }
416 /// // This impl is "useless", but we can still have
417 /// // an `impl Trait for SomeUnsizedType` somewhere.
418 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
420 /// pub fn foo<T: Trait + ?Sized>() {
421 /// <T as Trait>::xyz();
425 /// When checking `foo`, we have to prove `T: Trait`. This basically
426 /// translates into this:
429 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
432 /// When we try to prove it, we first go the first option, which
433 /// recurses. This shows us that the impl is "useless" -- it won't
434 /// tell us that `T: Trait` unless it already implemented `Trait`
435 /// by some other means. However, that does not prevent `T: Trait`
436 /// does not hold, because of the bound (which can indeed be satisfied
437 /// by `SomeUnsizedType` from another crate).
439 // FIXME: when an `EvaluatedToRecur` goes past its parent root, we
440 // ought to convert it to an `EvaluatedToErr`, because we know
441 // there definitely isn't a proof tree for that obligation. Not
442 // doing so is still sound -- there isn't any proof tree, so the
443 // branch still can't be a part of a minimal one -- but does not re-enable caching.
445 /// Evaluation failed.
449 impl EvaluationResult {
450 /// Returns `true` if this evaluation result is known to apply, even
451 /// considering outlives constraints.
452 pub fn must_apply_considering_regions(self) -> bool {
453 self == EvaluatedToOk
456 /// Returns `true` if this evaluation result is known to apply, ignoring
457 /// outlives constraints.
458 pub fn must_apply_modulo_regions(self) -> bool {
459 self <= EvaluatedToOkModuloRegions
462 pub fn may_apply(self) -> bool {
464 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToUnknown => {
468 EvaluatedToErr | EvaluatedToRecur => false,
472 fn is_stack_dependent(self) -> bool {
474 EvaluatedToUnknown | EvaluatedToRecur => true,
476 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToErr => false,
481 /// Indicates that trait evaluation caused overflow.
482 #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable)]
483 pub struct OverflowError;
485 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
486 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
487 SelectionError::Overflow
491 #[derive(Clone, Default)]
492 pub struct EvaluationCache<'tcx> {
493 hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>,
496 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
497 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
500 freshener: infcx.freshener(),
502 intercrate_ambiguity_causes: None,
503 allow_negative_impls: false,
504 query_mode: TraitQueryMode::Standard,
509 infcx: &'cx InferCtxt<'cx, 'tcx>,
510 mode: IntercrateMode,
511 ) -> SelectionContext<'cx, 'tcx> {
512 debug!("intercrate({:?})", mode);
515 freshener: infcx.freshener(),
516 intercrate: Some(mode),
517 intercrate_ambiguity_causes: None,
518 allow_negative_impls: false,
519 query_mode: TraitQueryMode::Standard,
523 pub fn with_negative(
524 infcx: &'cx InferCtxt<'cx, 'tcx>,
525 allow_negative_impls: bool,
526 ) -> SelectionContext<'cx, 'tcx> {
527 debug!("with_negative({:?})", allow_negative_impls);
530 freshener: infcx.freshener(),
532 intercrate_ambiguity_causes: None,
533 allow_negative_impls,
534 query_mode: TraitQueryMode::Standard,
538 pub fn with_query_mode(
539 infcx: &'cx InferCtxt<'cx, 'tcx>,
540 query_mode: TraitQueryMode,
541 ) -> SelectionContext<'cx, 'tcx> {
542 debug!("with_query_mode({:?})", query_mode);
545 freshener: infcx.freshener(),
547 intercrate_ambiguity_causes: None,
548 allow_negative_impls: false,
553 /// Enables tracking of intercrate ambiguity causes. These are
554 /// used in coherence to give improved diagnostics. We don't do
555 /// this until we detect a coherence error because it can lead to
556 /// false overflow results (#47139) and because it costs
557 /// computation time.
558 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
559 assert!(self.intercrate.is_some());
560 assert!(self.intercrate_ambiguity_causes.is_none());
561 self.intercrate_ambiguity_causes = Some(vec![]);
562 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
565 /// Gets the intercrate ambiguity causes collected since tracking
566 /// was enabled and disables tracking at the same time. If
567 /// tracking is not enabled, just returns an empty vector.
568 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
569 assert!(self.intercrate.is_some());
570 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
573 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
577 pub fn tcx(&self) -> TyCtxt<'tcx> {
581 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
585 ///////////////////////////////////////////////////////////////////////////
588 // The selection phase tries to identify *how* an obligation will
589 // be resolved. For example, it will identify which impl or
590 // parameter bound is to be used. The process can be inconclusive
591 // if the self type in the obligation is not fully inferred. Selection
592 // can result in an error in one of two ways:
594 // 1. If no applicable impl or parameter bound can be found.
595 // 2. If the output type parameters in the obligation do not match
596 // those specified by the impl/bound. For example, if the obligation
597 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
598 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
600 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
601 /// type environment by performing unification.
604 obligation: &TraitObligation<'tcx>,
605 ) -> SelectionResult<'tcx, Selection<'tcx>> {
606 debug!("select({:?})", obligation);
607 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
609 let pec = &ProvisionalEvaluationCache::default();
610 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
612 let candidate = match self.candidate_from_obligation(&stack) {
613 Err(SelectionError::Overflow) => {
614 // In standard mode, overflow must have been caught and reported
616 assert!(self.query_mode == TraitQueryMode::Canonical);
617 return Err(SelectionError::Overflow);
625 Ok(Some(candidate)) => candidate,
628 match self.confirm_candidate(obligation, candidate) {
629 Err(SelectionError::Overflow) => {
630 assert!(self.query_mode == TraitQueryMode::Canonical);
631 Err(SelectionError::Overflow)
634 Ok(candidate) => Ok(Some(candidate)),
638 ///////////////////////////////////////////////////////////////////////////
641 // Tests whether an obligation can be selected or whether an impl
642 // can be applied to particular types. It skips the "confirmation"
643 // step and hence completely ignores output type parameters.
645 // The result is "true" if the obligation *may* hold and "false" if
646 // we can be sure it does not.
648 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
649 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
650 debug!("predicate_may_hold_fatal({:?})", obligation);
652 // This fatal query is a stopgap that should only be used in standard mode,
653 // where we do not expect overflow to be propagated.
654 assert!(self.query_mode == TraitQueryMode::Standard);
656 self.evaluate_root_obligation(obligation)
657 .expect("Overflow should be caught earlier in standard query mode")
661 /// Evaluates whether the obligation `obligation` can be satisfied
662 /// and returns an `EvaluationResult`. This is meant for the
664 pub fn evaluate_root_obligation(
666 obligation: &PredicateObligation<'tcx>,
667 ) -> Result<EvaluationResult, OverflowError> {
668 self.evaluation_probe(|this| {
669 this.evaluate_predicate_recursively(
670 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
678 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
679 ) -> Result<EvaluationResult, OverflowError> {
680 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
681 let result = op(self)?;
682 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
684 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
689 /// Evaluates the predicates in `predicates` recursively. Note that
690 /// this applies projections in the predicates, and therefore
691 /// is run within an inference probe.
692 fn evaluate_predicates_recursively<'o, I>(
694 stack: TraitObligationStackList<'o, 'tcx>,
696 ) -> Result<EvaluationResult, OverflowError>
698 I: IntoIterator<Item = PredicateObligation<'tcx>>,
700 let mut result = EvaluatedToOk;
701 for obligation in predicates {
702 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
704 "evaluate_predicate_recursively({:?}) = {:?}",
707 if let EvaluatedToErr = eval {
708 // fast-path - EvaluatedToErr is the top of the lattice,
709 // so we don't need to look on the other predicates.
710 return Ok(EvaluatedToErr);
712 result = cmp::max(result, eval);
718 fn evaluate_predicate_recursively<'o>(
720 previous_stack: TraitObligationStackList<'o, 'tcx>,
721 obligation: PredicateObligation<'tcx>,
722 ) -> Result<EvaluationResult, OverflowError> {
723 debug!("evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
724 previous_stack.head(), obligation);
726 // Previous_stack stores a TraitObligatiom, while 'obligation' is
727 // a PredicateObligation. These are distinct types, so we can't
728 // use any Option combinator method that would force them to be
730 match previous_stack.head() {
731 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
732 None => self.check_recursion_limit(&obligation, &obligation)?
735 match obligation.predicate {
736 ty::Predicate::Trait(ref t) => {
737 debug_assert!(!t.has_escaping_bound_vars());
738 let obligation = obligation.with(t.clone());
739 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
742 ty::Predicate::Subtype(ref p) => {
743 // does this code ever run?
745 .subtype_predicate(&obligation.cause, obligation.param_env, p)
747 Some(Ok(InferOk { mut obligations, .. })) => {
748 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
749 self.evaluate_predicates_recursively(previous_stack,obligations.into_iter())
751 Some(Err(_)) => Ok(EvaluatedToErr),
752 None => Ok(EvaluatedToAmbig),
756 ty::Predicate::WellFormed(ty) => match ty::wf::obligations(
758 obligation.param_env,
759 obligation.cause.body_id,
761 obligation.cause.span,
763 Some(mut obligations) => {
764 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
765 self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
767 None => Ok(EvaluatedToAmbig),
770 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
771 // we do not consider region relationships when
772 // evaluating trait matches
773 Ok(EvaluatedToOkModuloRegions)
776 ty::Predicate::ObjectSafe(trait_def_id) => {
777 if self.tcx().is_object_safe(trait_def_id) {
784 ty::Predicate::Projection(ref data) => {
785 let project_obligation = obligation.with(data.clone());
786 match project::poly_project_and_unify_type(self, &project_obligation) {
787 Ok(Some(mut subobligations)) => {
788 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
789 let result = self.evaluate_predicates_recursively(
791 subobligations.into_iter(),
794 ProjectionCacheKey::from_poly_projection_predicate(self, data)
796 self.infcx.projection_cache.borrow_mut().complete(key);
800 Ok(None) => Ok(EvaluatedToAmbig),
801 Err(_) => Ok(EvaluatedToErr),
805 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
806 match self.infcx.closure_kind(closure_def_id, closure_substs) {
807 Some(closure_kind) => {
808 if closure_kind.extends(kind) {
814 None => Ok(EvaluatedToAmbig),
818 ty::Predicate::ConstEvaluatable(def_id, substs) => {
819 let tcx = self.tcx();
820 if !(obligation.param_env, substs).has_local_value() {
821 let param_env = obligation.param_env;
823 ty::Instance::resolve(tcx, param_env, def_id, substs);
824 if let Some(instance) = instance {
829 match self.tcx().const_eval(param_env.and(cid)) {
830 Ok(_) => Ok(EvaluatedToOk),
831 Err(_) => Ok(EvaluatedToErr),
837 // Inference variables still left in param_env or substs.
844 fn evaluate_trait_predicate_recursively<'o>(
846 previous_stack: TraitObligationStackList<'o, 'tcx>,
847 mut obligation: TraitObligation<'tcx>,
848 ) -> Result<EvaluationResult, OverflowError> {
849 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
851 if self.intercrate.is_none() && obligation.is_global()
856 .all(|bound| bound.needs_subst())
858 // If a param env has no global bounds, global obligations do not
859 // depend on its particular value in order to work, so we can clear
860 // out the param env and get better caching.
862 "evaluate_trait_predicate_recursively({:?}) - in global",
865 obligation.param_env = obligation.param_env.without_caller_bounds();
868 let stack = self.push_stack(previous_stack, &obligation);
869 let fresh_trait_ref = stack.fresh_trait_ref;
870 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
871 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
875 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
876 debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
877 stack.update_reached_depth(stack.cache().current_reached_depth());
881 // Check if this is a match for something already on the
882 // stack. If so, we don't want to insert the result into the
883 // main cache (it is cycle dependent) nor the provisional
884 // cache (which is meant for things that have completed but
885 // for a "backedge" -- this result *is* the backedge).
886 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
887 return Ok(cycle_result);
890 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
891 let result = result?;
893 if !result.must_apply_modulo_regions() {
894 stack.cache().on_failure(stack.dfn);
897 let reached_depth = stack.reached_depth.get();
898 if reached_depth >= stack.depth {
899 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
900 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
902 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
903 self.insert_evaluation_cache(
904 obligation.param_env,
907 provisional_result.max(result),
911 debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
913 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
914 is a cycle participant (at depth {}, reached depth {})",
920 stack.cache().insert_provisional(
932 /// If there is any previous entry on the stack that precisely
933 /// matches this obligation, then we can assume that the
934 /// obligation is satisfied for now (still all other conditions
935 /// must be met of course). One obvious case this comes up is
936 /// marker traits like `Send`. Think of a linked list:
938 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
940 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
941 /// `Option<Box<List<T>>>` is `Send`, and in turn
942 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
945 /// Note that we do this comparison using the `fresh_trait_ref`
946 /// fields. Because these have all been freshened using
947 /// `self.freshener`, we can be sure that (a) this will not
948 /// affect the inferencer state and (b) that if we see two
949 /// fresh regions with the same index, they refer to the same
950 /// unbound type variable.
951 fn check_evaluation_cycle(
953 stack: &TraitObligationStack<'_, 'tcx>,
954 ) -> Option<EvaluationResult> {
955 if let Some(cycle_depth) = stack.iter()
956 .skip(1) // skip top-most frame
957 .find(|prev| stack.obligation.param_env == prev.obligation.param_env &&
958 stack.fresh_trait_ref == prev.fresh_trait_ref)
959 .map(|stack| stack.depth)
962 "evaluate_stack({:?}) --> recursive at depth {}",
963 stack.fresh_trait_ref,
967 // If we have a stack like `A B C D E A`, where the top of
968 // the stack is the final `A`, then this will iterate over
969 // `A, E, D, C, B` -- i.e., all the participants apart
970 // from the cycle head. We mark them as participating in a
971 // cycle. This suppresses caching for those nodes. See
972 // `in_cycle` field for more details.
973 stack.update_reached_depth(cycle_depth);
975 // Subtle: when checking for a coinductive cycle, we do
976 // not compare using the "freshened trait refs" (which
977 // have erased regions) but rather the fully explicit
978 // trait refs. This is important because it's only a cycle
979 // if the regions match exactly.
980 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
981 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
982 if self.coinductive_match(cycle) {
984 "evaluate_stack({:?}) --> recursive, coinductive",
985 stack.fresh_trait_ref
990 "evaluate_stack({:?}) --> recursive, inductive",
991 stack.fresh_trait_ref
993 Some(EvaluatedToRecur)
1000 fn evaluate_stack<'o>(
1002 stack: &TraitObligationStack<'o, 'tcx>,
1003 ) -> Result<EvaluationResult, OverflowError> {
1004 // In intercrate mode, whenever any of the types are unbound,
1005 // there can always be an impl. Even if there are no impls in
1006 // this crate, perhaps the type would be unified with
1007 // something from another crate that does provide an impl.
1009 // In intra mode, we must still be conservative. The reason is
1010 // that we want to avoid cycles. Imagine an impl like:
1012 // impl<T:Eq> Eq for Vec<T>
1014 // and a trait reference like `$0 : Eq` where `$0` is an
1015 // unbound variable. When we evaluate this trait-reference, we
1016 // will unify `$0` with `Vec<$1>` (for some fresh variable
1017 // `$1`), on the condition that `$1 : Eq`. We will then wind
1018 // up with many candidates (since that are other `Eq` impls
1019 // that apply) and try to winnow things down. This results in
1020 // a recursive evaluation that `$1 : Eq` -- as you can
1021 // imagine, this is just where we started. To avoid that, we
1022 // check for unbound variables and return an ambiguous (hence possible)
1023 // match if we've seen this trait before.
1025 // This suffices to allow chains like `FnMut` implemented in
1026 // terms of `Fn` etc, but we could probably make this more
1028 let unbound_input_types = stack
1032 .any(|ty| ty.is_fresh());
1033 // this check was an imperfect workaround for a bug n the old
1034 // intercrate mode, it should be removed when that goes away.
1035 if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
1037 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
1038 stack.fresh_trait_ref
1040 // Heuristics: show the diagnostics when there are no candidates in crate.
1041 if self.intercrate_ambiguity_causes.is_some() {
1042 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1043 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1044 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
1045 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1046 let self_ty = trait_ref.self_ty();
1047 let cause = IntercrateAmbiguityCause::DownstreamCrate {
1048 trait_desc: trait_ref.to_string(),
1049 self_desc: if self_ty.has_concrete_skeleton() {
1050 Some(self_ty.to_string())
1055 debug!("evaluate_stack: pushing cause = {:?}", cause);
1056 self.intercrate_ambiguity_causes
1063 return Ok(EvaluatedToAmbig);
1065 if unbound_input_types && stack.iter().skip(1).any(|prev| {
1066 stack.obligation.param_env == prev.obligation.param_env
1067 && self.match_fresh_trait_refs(
1068 &stack.fresh_trait_ref, &prev.fresh_trait_ref, prev.obligation.param_env)
1071 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
1072 stack.fresh_trait_ref
1074 return Ok(EvaluatedToUnknown);
1077 match self.candidate_from_obligation(stack) {
1078 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1079 Ok(None) => Ok(EvaluatedToAmbig),
1080 Err(Overflow) => Err(OverflowError),
1081 Err(..) => Ok(EvaluatedToErr),
1085 /// For defaulted traits, we use a co-inductive strategy to solve, so
1086 /// that recursion is ok. This routine returns true if the top of the
1087 /// stack (`cycle[0]`):
1089 /// - is a defaulted trait,
1090 /// - it also appears in the backtrace at some position `X`,
1091 /// - all the predicates at positions `X..` between `X` and the top are
1092 /// also defaulted traits.
1093 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1095 I: Iterator<Item = ty::Predicate<'tcx>>,
1097 let mut cycle = cycle;
1098 cycle.all(|predicate| self.coinductive_predicate(predicate))
1101 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1102 let result = match predicate {
1103 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1106 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1110 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1111 /// obligations are met. Returns whether `candidate` remains viable after this further
1113 fn evaluate_candidate<'o>(
1115 stack: &TraitObligationStack<'o, 'tcx>,
1116 candidate: &SelectionCandidate<'tcx>,
1117 ) -> Result<EvaluationResult, OverflowError> {
1119 "evaluate_candidate: depth={} candidate={:?}",
1120 stack.obligation.recursion_depth, candidate
1122 let result = self.evaluation_probe(|this| {
1123 let candidate = (*candidate).clone();
1124 match this.confirm_candidate(stack.obligation, candidate) {
1125 Ok(selection) => this.evaluate_predicates_recursively(
1127 selection.nested_obligations().into_iter()
1129 Err(..) => Ok(EvaluatedToErr),
1133 "evaluate_candidate: depth={} result={:?}",
1134 stack.obligation.recursion_depth, result
1139 fn check_evaluation_cache(
1141 param_env: ty::ParamEnv<'tcx>,
1142 trait_ref: ty::PolyTraitRef<'tcx>,
1143 ) -> Option<EvaluationResult> {
1144 let tcx = self.tcx();
1145 if self.can_use_global_caches(param_env) {
1146 let cache = tcx.evaluation_cache.hashmap.borrow();
1147 if let Some(cached) = cache.get(&trait_ref) {
1148 return Some(cached.get(tcx));
1156 .map(|v| v.get(tcx))
1159 fn insert_evaluation_cache(
1161 param_env: ty::ParamEnv<'tcx>,
1162 trait_ref: ty::PolyTraitRef<'tcx>,
1163 dep_node: DepNodeIndex,
1164 result: EvaluationResult,
1166 // Avoid caching results that depend on more than just the trait-ref
1167 // - the stack can create recursion.
1168 if result.is_stack_dependent() {
1172 if self.can_use_global_caches(param_env) {
1173 if !trait_ref.has_local_value() {
1175 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1178 // This may overwrite the cache with the same value
1179 // FIXME: Due to #50507 this overwrites the different values
1180 // This should be changed to use HashMapExt::insert_same
1181 // when that is fixed
1186 .insert(trait_ref, WithDepNode::new(dep_node, result));
1192 "insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
1199 .insert(trait_ref, WithDepNode::new(dep_node, result));
1202 // For various reasons, it's possible for a subobligation
1203 // to have a *lower* recursion_depth than the obligation used to create it.
1204 // Projection sub-obligations may be returned from the projection cache,
1205 // which results in obligations with an 'old' recursion_depth.
1206 // Additionally, methods like ty::wf::obligations and
1207 // InferCtxt.subtype_predicate produce subobligations without
1208 // taking in a 'parent' depth, causing the generated subobligations
1209 // to have a recursion_depth of 0
1211 // To ensure that obligation_depth never decreasees, we force all subobligations
1212 // to have at least the depth of the original obligation.
1213 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(&self, it: I,
1215 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1218 // Check that the recursion limit has not been exceeded.
1220 // The weird return type of this function allows it to be used with the 'try' (?)
1221 // operator within certain functions
1222 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1224 obligation: &Obligation<'tcx, T>,
1225 error_obligation: &Obligation<'tcx, V>
1226 ) -> Result<(), OverflowError> {
1227 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1228 if obligation.recursion_depth >= recursion_limit {
1229 match self.query_mode {
1230 TraitQueryMode::Standard => {
1231 self.infcx().report_overflow_error(error_obligation, true);
1233 TraitQueryMode::Canonical => {
1234 return Err(OverflowError);
1241 ///////////////////////////////////////////////////////////////////////////
1242 // CANDIDATE ASSEMBLY
1244 // The selection process begins by examining all in-scope impls,
1245 // caller obligations, and so forth and assembling a list of
1246 // candidates. See the [rustc guide] for more details.
1249 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1251 fn candidate_from_obligation<'o>(
1253 stack: &TraitObligationStack<'o, 'tcx>,
1254 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1255 // Watch out for overflow. This intentionally bypasses (and does
1256 // not update) the cache.
1257 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
1260 // Check the cache. Note that we freshen the trait-ref
1261 // separately rather than using `stack.fresh_trait_ref` --
1262 // this is because we want the unbound variables to be
1263 // replaced with fresh types starting from index 0.
1264 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1266 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1267 cache_fresh_trait_pred, stack
1269 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
1272 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1274 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1278 // If no match, compute result and insert into cache.
1280 // FIXME(nikomatsakis) -- this cache is not taking into
1281 // account cycles that may have occurred in forming the
1282 // candidate. I don't know of any specific problems that
1283 // result but it seems awfully suspicious.
1284 let (candidate, dep_node) =
1285 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1288 "CACHE MISS: SELECT({:?})={:?}",
1289 cache_fresh_trait_pred, candidate
1291 self.insert_candidate_cache(
1292 stack.obligation.param_env,
1293 cache_fresh_trait_pred,
1300 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1302 OP: FnOnce(&mut Self) -> R,
1304 let (result, dep_node) = self.tcx()
1306 .with_anon_task(DepKind::TraitSelect, || op(self));
1307 self.tcx().dep_graph.read_index(dep_node);
1311 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1312 fn filter_negative_and_reservation_impls(
1314 candidate: SelectionCandidate<'tcx>,
1315 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1316 if let ImplCandidate(def_id) = candidate {
1317 let tcx = self.tcx();
1318 match tcx.impl_polarity(def_id) {
1319 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1320 return Err(Unimplemented);
1322 ty::ImplPolarity::Reservation => {
1323 if let Some(intercrate_ambiguity_clauses)
1324 = &mut self.intercrate_ambiguity_causes
1326 let attrs = tcx.get_attrs(def_id);
1327 let attr = attr::find_by_name(&attrs, sym::rustc_reservation_impl);
1328 let value = attr.and_then(|a| a.value_str());
1329 if let Some(value) = value {
1330 debug!("filter_negative_and_reservation_impls: \
1331 reservation impl ambiguity on {:?}", def_id);
1332 intercrate_ambiguity_clauses.push(
1333 IntercrateAmbiguityCause::ReservationImpl {
1334 message: value.to_string()
1347 fn candidate_from_obligation_no_cache<'o>(
1349 stack: &TraitObligationStack<'o, 'tcx>,
1350 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1351 if stack.obligation.predicate.references_error() {
1352 // If we encounter a `Error`, we generally prefer the
1353 // most "optimistic" result in response -- that is, the
1354 // one least likely to report downstream errors. But
1355 // because this routine is shared by coherence and by
1356 // trait selection, there isn't an obvious "right" choice
1357 // here in that respect, so we opt to just return
1358 // ambiguity and let the upstream clients sort it out.
1362 if let Some(conflict) = self.is_knowable(stack) {
1363 debug!("coherence stage: not knowable");
1364 if self.intercrate_ambiguity_causes.is_some() {
1365 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1366 // Heuristics: show the diagnostics when there are no candidates in crate.
1367 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1368 let mut no_candidates_apply = true;
1370 let evaluated_candidates = candidate_set
1373 .map(|c| self.evaluate_candidate(stack, &c));
1375 for ec in evaluated_candidates {
1379 no_candidates_apply = false;
1383 Err(e) => return Err(e.into()),
1388 if !candidate_set.ambiguous && no_candidates_apply {
1389 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1390 let self_ty = trait_ref.self_ty();
1391 let trait_desc = trait_ref.to_string();
1392 let self_desc = if self_ty.has_concrete_skeleton() {
1393 Some(self_ty.to_string())
1397 let cause = if let Conflict::Upstream = conflict {
1398 IntercrateAmbiguityCause::UpstreamCrateUpdate {
1403 IntercrateAmbiguityCause::DownstreamCrate {
1408 debug!("evaluate_stack: pushing cause = {:?}", cause);
1409 self.intercrate_ambiguity_causes
1419 let candidate_set = self.assemble_candidates(stack)?;
1421 if candidate_set.ambiguous {
1422 debug!("candidate set contains ambig");
1426 let mut candidates = candidate_set.vec;
1429 "assembled {} candidates for {:?}: {:?}",
1435 // At this point, we know that each of the entries in the
1436 // candidate set is *individually* applicable. Now we have to
1437 // figure out if they contain mutual incompatibilities. This
1438 // frequently arises if we have an unconstrained input type --
1439 // for example, we are looking for $0:Eq where $0 is some
1440 // unconstrained type variable. In that case, we'll get a
1441 // candidate which assumes $0 == int, one that assumes $0 ==
1442 // usize, etc. This spells an ambiguity.
1444 // If there is more than one candidate, first winnow them down
1445 // by considering extra conditions (nested obligations and so
1446 // forth). We don't winnow if there is exactly one
1447 // candidate. This is a relatively minor distinction but it
1448 // can lead to better inference and error-reporting. An
1449 // example would be if there was an impl:
1451 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1453 // and we were to see some code `foo.push_clone()` where `boo`
1454 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1455 // we were to winnow, we'd wind up with zero candidates.
1456 // Instead, we select the right impl now but report `Bar does
1457 // not implement Clone`.
1458 if candidates.len() == 1 {
1459 return self.filter_negative_and_reservation_impls(candidates.pop().unwrap());
1462 // Winnow, but record the exact outcome of evaluation, which
1463 // is needed for specialization. Propagate overflow if it occurs.
1464 let mut candidates = candidates
1466 .map(|c| match self.evaluate_candidate(stack, &c) {
1467 Ok(eval) if eval.may_apply() => Ok(Some(EvaluatedCandidate {
1472 Err(OverflowError) => Err(Overflow),
1474 .flat_map(Result::transpose)
1475 .collect::<Result<Vec<_>, _>>()?;
1478 "winnowed to {} candidates for {:?}: {:?}",
1484 // If there are STILL multiple candidates, we can further
1485 // reduce the list by dropping duplicates -- including
1486 // resolving specializations.
1487 if candidates.len() > 1 {
1489 while i < candidates.len() {
1490 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1491 self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1495 "Dropping candidate #{}/{}: {:?}",
1500 candidates.swap_remove(i);
1503 "Retaining candidate #{}/{}: {:?}",
1510 // If there are *STILL* multiple candidates, give up
1511 // and report ambiguity.
1513 debug!("multiple matches, ambig");
1520 // If there are *NO* candidates, then there are no impls --
1521 // that we know of, anyway. Note that in the case where there
1522 // are unbound type variables within the obligation, it might
1523 // be the case that you could still satisfy the obligation
1524 // from another crate by instantiating the type variables with
1525 // a type from another crate that does have an impl. This case
1526 // is checked for in `evaluate_stack` (and hence users
1527 // who might care about this case, like coherence, should use
1529 if candidates.is_empty() {
1530 return Err(Unimplemented);
1533 // Just one candidate left.
1534 self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate)
1537 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1538 debug!("is_knowable(intercrate={:?})", self.intercrate);
1540 if !self.intercrate.is_some() {
1544 let obligation = &stack.obligation;
1545 let predicate = self.infcx()
1546 .resolve_vars_if_possible(&obligation.predicate);
1548 // Okay to skip binder because of the nature of the
1549 // trait-ref-is-knowable check, which does not care about
1551 let trait_ref = predicate.skip_binder().trait_ref;
1553 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1555 Some(Conflict::Downstream {
1556 used_to_be_broken: true,
1558 Some(IntercrateMode::Issue43355),
1559 ) = (result, self.intercrate)
1561 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1568 /// Returns `true` if the global caches can be used.
1569 /// Do note that if the type itself is not in the
1570 /// global tcx, the local caches will be used.
1571 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1572 // If there are any where-clauses in scope, then we always use
1573 // a cache local to this particular scope. Otherwise, we
1574 // switch to a global cache. We used to try and draw
1575 // finer-grained distinctions, but that led to a serious of
1576 // annoying and weird bugs like #22019 and #18290. This simple
1577 // rule seems to be pretty clearly safe and also still retains
1578 // a very high hit rate (~95% when compiling rustc).
1579 if !param_env.caller_bounds.is_empty() {
1583 // Avoid using the master cache during coherence and just rely
1584 // on the local cache. This effectively disables caching
1585 // during coherence. It is really just a simplification to
1586 // avoid us having to fear that coherence results "pollute"
1587 // the master cache. Since coherence executes pretty quickly,
1588 // it's not worth going to more trouble to increase the
1589 // hit-rate I don't think.
1590 if self.intercrate.is_some() {
1594 // Otherwise, we can use the global cache.
1598 fn check_candidate_cache(
1600 param_env: ty::ParamEnv<'tcx>,
1601 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1602 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1603 let tcx = self.tcx();
1604 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1605 if self.can_use_global_caches(param_env) {
1606 let cache = tcx.selection_cache.hashmap.borrow();
1607 if let Some(cached) = cache.get(&trait_ref) {
1608 return Some(cached.get(tcx));
1616 .map(|v| v.get(tcx))
1619 /// Determines whether can we safely cache the result
1620 /// of selecting an obligation. This is almost always 'true',
1621 /// except when dealing with certain ParamCandidates.
1623 /// Ordinarily, a ParamCandidate will contain no inference variables,
1624 /// since it was usually produced directly from a DefId. However,
1625 /// certain cases (currently only librustdoc's blanket impl finder),
1626 /// a ParamEnv may be explicitly constructed with inference types.
1627 /// When this is the case, we do *not* want to cache the resulting selection
1628 /// candidate. This is due to the fact that it might not always be possible
1629 /// to equate the obligation's trait ref and the candidate's trait ref,
1630 /// if more constraints end up getting added to an inference variable.
1632 /// Because of this, we always want to re-run the full selection
1633 /// process for our obligation the next time we see it, since
1634 /// we might end up picking a different SelectionCandidate (or none at all)
1635 fn can_cache_candidate(&self,
1636 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>
1639 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => {
1640 !trait_ref.skip_binder().input_types().any(|t| t.walk().any(|t_| t_.is_ty_infer()))
1646 fn insert_candidate_cache(
1648 param_env: ty::ParamEnv<'tcx>,
1649 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1650 dep_node: DepNodeIndex,
1651 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1653 let tcx = self.tcx();
1654 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1656 if !self.can_cache_candidate(&candidate) {
1657 debug!("insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1658 candidate is not cacheable", trait_ref, candidate);
1663 if self.can_use_global_caches(param_env) {
1664 if let Err(Overflow) = candidate {
1665 // Don't cache overflow globally; we only produce this
1666 // in certain modes.
1667 } else if !trait_ref.has_local_value() {
1668 if !candidate.has_local_value() {
1670 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1671 trait_ref, candidate,
1673 // This may overwrite the cache with the same value
1677 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1684 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1685 trait_ref, candidate,
1691 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1694 fn assemble_candidates<'o>(
1696 stack: &TraitObligationStack<'o, 'tcx>,
1697 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1698 let TraitObligationStack { obligation, .. } = *stack;
1699 let ref obligation = Obligation {
1700 param_env: obligation.param_env,
1701 cause: obligation.cause.clone(),
1702 recursion_depth: obligation.recursion_depth,
1703 predicate: self.infcx()
1704 .resolve_vars_if_possible(&obligation.predicate),
1707 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1708 // Self is a type variable (e.g., `_: AsRef<str>`).
1710 // This is somewhat problematic, as the current scheme can't really
1711 // handle it turning to be a projection. This does end up as truly
1712 // ambiguous in most cases anyway.
1714 // Take the fast path out - this also improves
1715 // performance by preventing assemble_candidates_from_impls from
1716 // matching every impl for this trait.
1717 return Ok(SelectionCandidateSet {
1723 let mut candidates = SelectionCandidateSet {
1728 self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1730 // Other bounds. Consider both in-scope bounds from fn decl
1731 // and applicable impls. There is a certain set of precedence rules here.
1732 let def_id = obligation.predicate.def_id();
1733 let lang_items = self.tcx().lang_items();
1735 if lang_items.copy_trait() == Some(def_id) {
1737 "obligation self ty is {:?}",
1738 obligation.predicate.skip_binder().self_ty()
1741 // User-defined copy impls are permitted, but only for
1742 // structs and enums.
1743 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1745 // For other types, we'll use the builtin rules.
1746 let copy_conditions = self.copy_clone_conditions(obligation);
1747 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1748 } else if lang_items.sized_trait() == Some(def_id) {
1749 // Sized is never implementable by end-users, it is
1750 // always automatically computed.
1751 let sized_conditions = self.sized_conditions(obligation);
1752 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1753 } else if lang_items.unsize_trait() == Some(def_id) {
1754 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1756 if lang_items.clone_trait() == Some(def_id) {
1757 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1758 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1759 // types have builtin support for `Clone`.
1760 let clone_conditions = self.copy_clone_conditions(obligation);
1761 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1764 self.assemble_generator_candidates(obligation, &mut candidates)?;
1765 self.assemble_closure_candidates(obligation, &mut candidates)?;
1766 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1767 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1768 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1771 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1772 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1773 // Auto implementations have lower priority, so we only
1774 // consider triggering a default if there is no other impl that can apply.
1775 if candidates.vec.is_empty() {
1776 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1778 debug!("candidate list size: {}", candidates.vec.len());
1782 fn assemble_candidates_from_projected_tys(
1784 obligation: &TraitObligation<'tcx>,
1785 candidates: &mut SelectionCandidateSet<'tcx>,
1787 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1789 // before we go into the whole placeholder thing, just
1790 // quickly check if the self-type is a projection at all.
1791 match obligation.predicate.skip_binder().trait_ref.self_ty().kind {
1792 ty::Projection(_) | ty::Opaque(..) => {}
1793 ty::Infer(ty::TyVar(_)) => {
1795 obligation.cause.span,
1796 "Self=_ should have been handled by assemble_candidates"
1802 let result = self.infcx.probe(|snapshot| {
1803 self.match_projection_obligation_against_definition_bounds(
1810 candidates.vec.push(ProjectionCandidate);
1814 fn match_projection_obligation_against_definition_bounds(
1816 obligation: &TraitObligation<'tcx>,
1817 snapshot: &CombinedSnapshot<'_, 'tcx>,
1819 let poly_trait_predicate = self.infcx()
1820 .resolve_vars_if_possible(&obligation.predicate);
1821 let (placeholder_trait_predicate, placeholder_map) = self.infcx()
1822 .replace_bound_vars_with_placeholders(&poly_trait_predicate);
1824 "match_projection_obligation_against_definition_bounds: \
1825 placeholder_trait_predicate={:?}",
1826 placeholder_trait_predicate,
1829 let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().kind {
1830 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1831 ty::Opaque(def_id, substs) => (def_id, substs),
1834 obligation.cause.span,
1835 "match_projection_obligation_against_definition_bounds() called \
1836 but self-ty is not a projection: {:?}",
1837 placeholder_trait_predicate.trait_ref.self_ty()
1842 "match_projection_obligation_against_definition_bounds: \
1843 def_id={:?}, substs={:?}",
1847 let predicates_of = self.tcx().predicates_of(def_id);
1848 let bounds = predicates_of.instantiate(self.tcx(), substs);
1850 "match_projection_obligation_against_definition_bounds: \
1855 let elaborated_predicates = util::elaborate_predicates(self.tcx(), bounds.predicates);
1856 let matching_bound = elaborated_predicates
1859 self.infcx.probe(|_| {
1860 self.match_projection(
1863 placeholder_trait_predicate.trait_ref.clone(),
1871 "match_projection_obligation_against_definition_bounds: \
1872 matching_bound={:?}",
1875 match matching_bound {
1878 // Repeat the successful match, if any, this time outside of a probe.
1879 let result = self.match_projection(
1882 placeholder_trait_predicate.trait_ref.clone(),
1893 fn match_projection(
1895 obligation: &TraitObligation<'tcx>,
1896 trait_bound: ty::PolyTraitRef<'tcx>,
1897 placeholder_trait_ref: ty::TraitRef<'tcx>,
1898 placeholder_map: &PlaceholderMap<'tcx>,
1899 snapshot: &CombinedSnapshot<'_, 'tcx>,
1901 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1903 .at(&obligation.cause, obligation.param_env)
1904 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1907 self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1910 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1911 /// supplied to find out whether it is listed among them.
1913 /// Never affects inference environment.
1914 fn assemble_candidates_from_caller_bounds<'o>(
1916 stack: &TraitObligationStack<'o, 'tcx>,
1917 candidates: &mut SelectionCandidateSet<'tcx>,
1918 ) -> Result<(), SelectionError<'tcx>> {
1920 "assemble_candidates_from_caller_bounds({:?})",
1924 let all_bounds = stack
1929 .filter_map(|o| o.to_opt_poly_trait_ref());
1931 // Micro-optimization: filter out predicates relating to different traits.
1932 let matching_bounds =
1933 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1935 // Keep only those bounds which may apply, and propagate overflow if it occurs.
1936 let mut param_candidates = vec![];
1937 for bound in matching_bounds {
1938 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1940 param_candidates.push(ParamCandidate(bound));
1944 candidates.vec.extend(param_candidates);
1949 fn evaluate_where_clause<'o>(
1951 stack: &TraitObligationStack<'o, 'tcx>,
1952 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1953 ) -> Result<EvaluationResult, OverflowError> {
1954 self.evaluation_probe(|this| {
1955 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1956 Ok(obligations) => {
1957 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1959 Err(()) => Ok(EvaluatedToErr),
1964 fn assemble_generator_candidates(
1966 obligation: &TraitObligation<'tcx>,
1967 candidates: &mut SelectionCandidateSet<'tcx>,
1968 ) -> Result<(), SelectionError<'tcx>> {
1969 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1973 // Okay to skip binder because the substs on generator types never
1974 // touch bound regions, they just capture the in-scope
1975 // type/region parameters.
1976 let self_ty = *obligation.self_ty().skip_binder();
1977 match self_ty.kind {
1978 ty::Generator(..) => {
1980 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1984 candidates.vec.push(GeneratorCandidate);
1986 ty::Infer(ty::TyVar(_)) => {
1987 debug!("assemble_generator_candidates: ambiguous self-type");
1988 candidates.ambiguous = true;
1996 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1997 /// FnMut<..>` where `X` is a closure type.
1999 /// Note: the type parameters on a closure candidate are modeled as *output* type
2000 /// parameters and hence do not affect whether this trait is a match or not. They will be
2001 /// unified during the confirmation step.
2002 fn assemble_closure_candidates(
2004 obligation: &TraitObligation<'tcx>,
2005 candidates: &mut SelectionCandidateSet<'tcx>,
2006 ) -> Result<(), SelectionError<'tcx>> {
2007 let kind = match self.tcx()
2009 .fn_trait_kind(obligation.predicate.def_id())
2017 // Okay to skip binder because the substs on closure types never
2018 // touch bound regions, they just capture the in-scope
2019 // type/region parameters
2020 match obligation.self_ty().skip_binder().kind {
2021 ty::Closure(closure_def_id, closure_substs) => {
2023 "assemble_unboxed_candidates: kind={:?} obligation={:?}",
2026 match self.infcx.closure_kind(
2030 Some(closure_kind) => {
2032 "assemble_unboxed_candidates: closure_kind = {:?}",
2035 if closure_kind.extends(kind) {
2036 candidates.vec.push(ClosureCandidate);
2040 debug!("assemble_unboxed_candidates: closure_kind not yet known");
2041 candidates.vec.push(ClosureCandidate);
2045 ty::Infer(ty::TyVar(_)) => {
2046 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
2047 candidates.ambiguous = true;
2055 /// Implement one of the `Fn()` family for a fn pointer.
2056 fn assemble_fn_pointer_candidates(
2058 obligation: &TraitObligation<'tcx>,
2059 candidates: &mut SelectionCandidateSet<'tcx>,
2060 ) -> Result<(), SelectionError<'tcx>> {
2061 // We provide impl of all fn traits for fn pointers.
2064 .fn_trait_kind(obligation.predicate.def_id())
2070 // Okay to skip binder because what we are inspecting doesn't involve bound regions
2071 let self_ty = *obligation.self_ty().skip_binder();
2072 match self_ty.kind {
2073 ty::Infer(ty::TyVar(_)) => {
2074 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
2075 candidates.ambiguous = true; // could wind up being a fn() type
2077 // provide an impl, but only for suitable `fn` pointers
2078 ty::FnDef(..) | ty::FnPtr(_) => {
2080 unsafety: hir::Unsafety::Normal,
2084 } = self_ty.fn_sig(self.tcx()).skip_binder()
2086 candidates.vec.push(FnPointerCandidate);
2095 /// Search for impls that might apply to `obligation`.
2096 fn assemble_candidates_from_impls(
2098 obligation: &TraitObligation<'tcx>,
2099 candidates: &mut SelectionCandidateSet<'tcx>,
2100 ) -> Result<(), SelectionError<'tcx>> {
2102 "assemble_candidates_from_impls(obligation={:?})",
2106 self.tcx().for_each_relevant_impl(
2107 obligation.predicate.def_id(),
2108 obligation.predicate.skip_binder().trait_ref.self_ty(),
2110 self.infcx.probe(|snapshot| {
2111 if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot)
2113 candidates.vec.push(ImplCandidate(impl_def_id));
2122 fn assemble_candidates_from_auto_impls(
2124 obligation: &TraitObligation<'tcx>,
2125 candidates: &mut SelectionCandidateSet<'tcx>,
2126 ) -> Result<(), SelectionError<'tcx>> {
2127 // Okay to skip binder here because the tests we do below do not involve bound regions.
2128 let self_ty = *obligation.self_ty().skip_binder();
2129 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2131 let def_id = obligation.predicate.def_id();
2133 if self.tcx().trait_is_auto(def_id) {
2134 match self_ty.kind {
2135 ty::Dynamic(..) => {
2136 // For object types, we don't know what the closed
2137 // over types are. This means we conservatively
2138 // say nothing; a candidate may be added by
2139 // `assemble_candidates_from_object_ty`.
2141 ty::Foreign(..) => {
2142 // Since the contents of foreign types is unknown,
2143 // we don't add any `..` impl. Default traits could
2144 // still be provided by a manual implementation for
2145 // this trait and type.
2147 ty::Param(..) | ty::Projection(..) => {
2148 // In these cases, we don't know what the actual
2149 // type is. Therefore, we cannot break it down
2150 // into its constituent types. So we don't
2151 // consider the `..` impl but instead just add no
2152 // candidates: this means that typeck will only
2153 // succeed if there is another reason to believe
2154 // that this obligation holds. That could be a
2155 // where-clause or, in the case of an object type,
2156 // it could be that the object type lists the
2157 // trait (e.g., `Foo+Send : Send`). See
2158 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2159 // for an example of a test case that exercises
2162 ty::Infer(ty::TyVar(_)) => {
2163 // the auto impl might apply, we don't know
2164 candidates.ambiguous = true;
2166 ty::Generator(_, _, movability)
2167 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
2170 hir::Movability::Static => {
2171 // Immovable generators are never `Unpin`, so
2172 // suppress the normal auto-impl candidate for it.
2174 hir::Movability::Movable => {
2175 // Movable generators are always `Unpin`, so add an
2176 // unconditional builtin candidate.
2177 candidates.vec.push(BuiltinCandidate {
2184 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2191 /// Search for impls that might apply to `obligation`.
2192 fn assemble_candidates_from_object_ty(
2194 obligation: &TraitObligation<'tcx>,
2195 candidates: &mut SelectionCandidateSet<'tcx>,
2198 "assemble_candidates_from_object_ty(self_ty={:?})",
2199 obligation.self_ty().skip_binder()
2202 self.infcx.probe(|_snapshot| {
2203 // The code below doesn't care about regions, and the
2204 // self-ty here doesn't escape this probe, so just erase
2206 let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
2207 let poly_trait_ref = match self_ty.kind {
2208 ty::Dynamic(ref data, ..) => {
2209 if data.auto_traits()
2210 .any(|did| did == obligation.predicate.def_id())
2213 "assemble_candidates_from_object_ty: matched builtin bound, \
2216 candidates.vec.push(BuiltinObjectCandidate);
2220 if let Some(principal) = data.principal() {
2221 if !self.infcx.tcx.features().object_safe_for_dispatch {
2222 principal.with_self_ty(self.tcx(), self_ty)
2223 } else if self.tcx().is_object_safe(principal.def_id()) {
2224 principal.with_self_ty(self.tcx(), self_ty)
2229 // Only auto-trait bounds exist.
2233 ty::Infer(ty::TyVar(_)) => {
2234 debug!("assemble_candidates_from_object_ty: ambiguous");
2235 candidates.ambiguous = true; // could wind up being an object type
2242 "assemble_candidates_from_object_ty: poly_trait_ref={:?}",
2246 // Count only those upcast versions that match the trait-ref
2247 // we are looking for. Specifically, do not only check for the
2248 // correct trait, but also the correct type parameters.
2249 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2250 // but `Foo` is declared as `trait Foo : Bar<u32>`.
2251 let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
2252 .filter(|upcast_trait_ref| {
2253 self.infcx.probe(|_| {
2254 let upcast_trait_ref = upcast_trait_ref.clone();
2255 self.match_poly_trait_ref(obligation, upcast_trait_ref)
2261 if upcast_trait_refs > 1 {
2262 // Can be upcast in many ways; need more type information.
2263 candidates.ambiguous = true;
2264 } else if upcast_trait_refs == 1 {
2265 candidates.vec.push(ObjectCandidate);
2270 /// Search for unsizing that might apply to `obligation`.
2271 fn assemble_candidates_for_unsizing(
2273 obligation: &TraitObligation<'tcx>,
2274 candidates: &mut SelectionCandidateSet<'tcx>,
2276 // We currently never consider higher-ranked obligations e.g.
2277 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2278 // because they are a priori invalid, and we could potentially add support
2279 // for them later, it's just that there isn't really a strong need for it.
2280 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2281 // impl, and those are generally applied to concrete types.
2283 // That said, one might try to write a fn with a where clause like
2284 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2285 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2286 // Still, you'd be more likely to write that where clause as
2288 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2289 // obligation above. Should be possible to extend this in the future.
2290 let source = match obligation.self_ty().no_bound_vars() {
2293 // Don't add any candidates if there are bound regions.
2297 let target = obligation
2305 "assemble_candidates_for_unsizing(source={:?}, target={:?})",
2309 let may_apply = match (&source.kind, &target.kind) {
2310 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2311 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2312 // Upcasts permit two things:
2314 // 1. Dropping builtin bounds, e.g., `Foo+Send` to `Foo`
2315 // 2. Tightening the region bound, e.g., `Foo+'a` to `Foo+'b` if `'a : 'b`
2317 // Note that neither of these changes requires any
2318 // change at runtime. Eventually this will be
2321 // We always upcast when we can because of reason
2322 // #2 (region bounds).
2323 data_a.principal_def_id() == data_b.principal_def_id()
2324 && data_b.auto_traits()
2325 // All of a's auto traits need to be in b's auto traits.
2326 .all(|b| data_a.auto_traits().any(|a| a == b))
2330 (_, &ty::Dynamic(..)) => true,
2332 // Ambiguous handling is below T -> Trait, because inference
2333 // variables can still implement Unsize<Trait> and nested
2334 // obligations will have the final say (likely deferred).
2335 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2336 debug!("assemble_candidates_for_unsizing: ambiguous");
2337 candidates.ambiguous = true;
2342 (&ty::Array(..), &ty::Slice(_)) => true,
2344 // Struct<T> -> Struct<U>.
2345 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2346 def_id_a == def_id_b
2349 // (.., T) -> (.., U).
2350 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2356 candidates.vec.push(BuiltinUnsizeCandidate);
2360 fn assemble_candidates_for_trait_alias(
2362 obligation: &TraitObligation<'tcx>,
2363 candidates: &mut SelectionCandidateSet<'tcx>,
2364 ) -> Result<(), SelectionError<'tcx>> {
2365 // Okay to skip binder here because the tests we do below do not involve bound regions.
2366 let self_ty = *obligation.self_ty().skip_binder();
2367 debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
2369 let def_id = obligation.predicate.def_id();
2371 if self.tcx().is_trait_alias(def_id) {
2372 candidates.vec.push(TraitAliasCandidate(def_id.clone()));
2378 ///////////////////////////////////////////////////////////////////////////
2381 // Winnowing is the process of attempting to resolve ambiguity by
2382 // probing further. During the winnowing process, we unify all
2383 // type variables and then we also attempt to evaluate recursive
2384 // bounds to see if they are satisfied.
2386 /// Returns `true` if `victim` should be dropped in favor of
2387 /// `other`. Generally speaking we will drop duplicate
2388 /// candidates and prefer where-clause candidates.
2390 /// See the comment for "SelectionCandidate" for more details.
2391 fn candidate_should_be_dropped_in_favor_of(
2393 victim: &EvaluatedCandidate<'tcx>,
2394 other: &EvaluatedCandidate<'tcx>,
2396 if victim.candidate == other.candidate {
2400 // Check if a bound would previously have been removed when normalizing
2401 // the param_env so that it can be given the lowest priority. See
2402 // #50825 for the motivation for this.
2404 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2406 match other.candidate {
2407 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2408 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2409 // lifetime of a variable.
2410 BuiltinCandidate { has_nested: false } => true,
2411 ParamCandidate(ref cand) => match victim.candidate {
2412 AutoImplCandidate(..) => {
2414 "default implementations shouldn't be recorded \
2415 when there are other valid candidates"
2418 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2419 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2420 // lifetime of a variable.
2421 BuiltinCandidate { has_nested: false } => false,
2424 | GeneratorCandidate
2425 | FnPointerCandidate
2426 | BuiltinObjectCandidate
2427 | BuiltinUnsizeCandidate
2428 | BuiltinCandidate { .. }
2429 | TraitAliasCandidate(..) => {
2430 // Global bounds from the where clause should be ignored
2431 // here (see issue #50825). Otherwise, we have a where
2432 // clause so don't go around looking for impls.
2435 ObjectCandidate | ProjectionCandidate => {
2436 // Arbitrarily give param candidates priority
2437 // over projection and object candidates.
2440 ParamCandidate(..) => false,
2442 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2443 AutoImplCandidate(..) => {
2445 "default implementations shouldn't be recorded \
2446 when there are other valid candidates"
2449 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2450 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2451 // lifetime of a variable.
2452 BuiltinCandidate { has_nested: false } => false,
2455 | GeneratorCandidate
2456 | FnPointerCandidate
2457 | BuiltinObjectCandidate
2458 | BuiltinUnsizeCandidate
2459 | BuiltinCandidate { .. }
2460 | TraitAliasCandidate(..) => true,
2461 ObjectCandidate | ProjectionCandidate => {
2462 // Arbitrarily give param candidates priority
2463 // over projection and object candidates.
2466 ParamCandidate(ref cand) => is_global(cand),
2468 ImplCandidate(other_def) => {
2469 // See if we can toss out `victim` based on specialization.
2470 // This requires us to know *for sure* that the `other` impl applies
2471 // i.e., EvaluatedToOk:
2472 if other.evaluation.must_apply_modulo_regions() {
2473 match victim.candidate {
2474 ImplCandidate(victim_def) => {
2475 let tcx = self.tcx();
2476 return tcx.specializes((other_def, victim_def))
2477 || tcx.impls_are_allowed_to_overlap(
2478 other_def, victim_def).is_some();
2480 ParamCandidate(ref cand) => {
2481 // Prefer the impl to a global where clause candidate.
2482 return is_global(cand);
2491 | GeneratorCandidate
2492 | FnPointerCandidate
2493 | BuiltinObjectCandidate
2494 | BuiltinUnsizeCandidate
2495 | BuiltinCandidate { has_nested: true } => {
2496 match victim.candidate {
2497 ParamCandidate(ref cand) => {
2498 // Prefer these to a global where-clause bound
2499 // (see issue #50825)
2500 is_global(cand) && other.evaluation.must_apply_modulo_regions()
2509 ///////////////////////////////////////////////////////////////////////////
2512 // These cover the traits that are built-in to the language
2513 // itself: `Copy`, `Clone` and `Sized`.
2515 fn assemble_builtin_bound_candidates(
2517 conditions: BuiltinImplConditions<'tcx>,
2518 candidates: &mut SelectionCandidateSet<'tcx>,
2519 ) -> Result<(), SelectionError<'tcx>> {
2521 BuiltinImplConditions::Where(nested) => {
2522 debug!("builtin_bound: nested={:?}", nested);
2523 candidates.vec.push(BuiltinCandidate {
2524 has_nested: nested.skip_binder().len() > 0,
2527 BuiltinImplConditions::None => {}
2528 BuiltinImplConditions::Ambiguous => {
2529 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2530 candidates.ambiguous = true;
2537 fn sized_conditions(
2539 obligation: &TraitObligation<'tcx>,
2540 ) -> BuiltinImplConditions<'tcx> {
2541 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2543 // NOTE: binder moved to (*)
2544 let self_ty = self.infcx
2545 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2547 match self_ty.kind {
2548 ty::Infer(ty::IntVar(_))
2549 | ty::Infer(ty::FloatVar(_))
2560 | ty::GeneratorWitness(..)
2565 // safe for everything
2566 Where(ty::Binder::dummy(Vec::new()))
2569 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2572 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2575 ty::Adt(def, substs) => {
2576 let sized_crit = def.sized_constraint(self.tcx());
2577 // (*) binder moved here
2578 Where(ty::Binder::bind(
2581 .map(|ty| ty.subst(self.tcx(), substs))
2586 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2587 ty::Infer(ty::TyVar(_)) => Ambiguous,
2589 ty::UnnormalizedProjection(..)
2590 | ty::Placeholder(..)
2592 | ty::Infer(ty::FreshTy(_))
2593 | ty::Infer(ty::FreshIntTy(_))
2594 | ty::Infer(ty::FreshFloatTy(_)) => {
2596 "asked to assemble builtin bounds of unexpected type: {:?}",
2603 fn copy_clone_conditions(
2605 obligation: &TraitObligation<'tcx>,
2606 ) -> BuiltinImplConditions<'tcx> {
2607 // NOTE: binder moved to (*)
2608 let self_ty = self.infcx
2609 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2611 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2613 match self_ty.kind {
2614 ty::Infer(ty::IntVar(_))
2615 | ty::Infer(ty::FloatVar(_))
2618 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2627 | ty::Ref(_, _, hir::Mutability::Immutable) => {
2628 // Implementations provided in libcore
2636 | ty::GeneratorWitness(..)
2638 | ty::Ref(_, _, hir::Mutability::Mutable) => None,
2640 ty::Array(element_ty, _) => {
2641 // (*) binder moved here
2642 Where(ty::Binder::bind(vec![element_ty]))
2646 // (*) binder moved here
2647 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2650 ty::Closure(def_id, substs) => {
2651 // (*) binder moved here
2652 Where(ty::Binder::bind(
2653 substs.as_closure().upvar_tys(def_id, self.tcx()).collect(),
2657 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2658 // Fallback to whatever user-defined impls exist in this case.
2662 ty::Infer(ty::TyVar(_)) => {
2663 // Unbound type variable. Might or might not have
2664 // applicable impls and so forth, depending on what
2665 // those type variables wind up being bound to.
2669 ty::UnnormalizedProjection(..)
2670 | ty::Placeholder(..)
2672 | ty::Infer(ty::FreshTy(_))
2673 | ty::Infer(ty::FreshIntTy(_))
2674 | ty::Infer(ty::FreshFloatTy(_)) => {
2676 "asked to assemble builtin bounds of unexpected type: {:?}",
2683 /// For default impls, we need to break apart a type into its
2684 /// "constituent types" -- meaning, the types that it contains.
2686 /// Here are some (simple) examples:
2689 /// (i32, u32) -> [i32, u32]
2690 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2691 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2692 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2694 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2704 | ty::Infer(ty::IntVar(_))
2705 | ty::Infer(ty::FloatVar(_))
2707 | ty::Char => Vec::new(),
2709 ty::UnnormalizedProjection(..)
2710 | ty::Placeholder(..)
2714 | ty::Projection(..)
2716 | ty::Infer(ty::TyVar(_))
2717 | ty::Infer(ty::FreshTy(_))
2718 | ty::Infer(ty::FreshIntTy(_))
2719 | ty::Infer(ty::FreshFloatTy(_)) => {
2721 "asked to assemble constituent types of unexpected type: {:?}",
2726 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2730 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2732 ty::Tuple(ref tys) => {
2733 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2734 tys.iter().map(|k| k.expect_ty()).collect()
2737 ty::Closure(def_id, ref substs) => substs.as_closure()
2738 .upvar_tys(def_id, self.tcx())
2741 ty::Generator(def_id, ref substs, _) => {
2742 let witness = substs.as_generator().witness(def_id, self.tcx());
2745 .upvar_tys(def_id, self.tcx())
2746 .chain(iter::once(witness))
2750 ty::GeneratorWitness(types) => {
2751 // This is sound because no regions in the witness can refer to
2752 // the binder outside the witness. So we'll effectivly reuse
2753 // the implicit binder around the witness.
2754 types.skip_binder().to_vec()
2757 // for `PhantomData<T>`, we pass `T`
2758 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2760 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2762 ty::Opaque(def_id, substs) => {
2763 // We can resolve the `impl Trait` to its concrete type,
2764 // which enforces a DAG between the functions requiring
2765 // the auto trait bounds in question.
2766 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2771 fn collect_predicates_for_types(
2773 param_env: ty::ParamEnv<'tcx>,
2774 cause: ObligationCause<'tcx>,
2775 recursion_depth: usize,
2776 trait_def_id: DefId,
2777 types: ty::Binder<Vec<Ty<'tcx>>>,
2778 ) -> Vec<PredicateObligation<'tcx>> {
2779 // Because the types were potentially derived from
2780 // higher-ranked obligations they may reference late-bound
2781 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2782 // yield a type like `for<'a> &'a int`. In general, we
2783 // maintain the invariant that we never manipulate bound
2784 // regions, so we have to process these bound regions somehow.
2786 // The strategy is to:
2788 // 1. Instantiate those regions to placeholder regions (e.g.,
2789 // `for<'a> &'a int` becomes `&0 int`.
2790 // 2. Produce something like `&'0 int : Copy`
2791 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2798 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2800 self.infcx.commit_unconditionally(|_| {
2801 let (skol_ty, _) = self.infcx
2802 .replace_bound_vars_with_placeholders(&ty);
2804 value: normalized_ty,
2806 } = project::normalize_with_depth(
2813 let skol_obligation = self.tcx().predicate_for_trait_def(
2821 obligations.push(skol_obligation);
2828 ///////////////////////////////////////////////////////////////////////////
2831 // Confirmation unifies the output type parameters of the trait
2832 // with the values found in the obligation, possibly yielding a
2833 // type error. See the [rustc guide] for more details.
2836 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
2838 fn confirm_candidate(
2840 obligation: &TraitObligation<'tcx>,
2841 candidate: SelectionCandidate<'tcx>,
2842 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2843 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2846 BuiltinCandidate { has_nested } => {
2847 let data = self.confirm_builtin_candidate(obligation, has_nested);
2848 Ok(VtableBuiltin(data))
2851 ParamCandidate(param) => {
2852 let obligations = self.confirm_param_candidate(obligation, param);
2853 Ok(VtableParam(obligations))
2856 ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
2861 AutoImplCandidate(trait_def_id) => {
2862 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2863 Ok(VtableAutoImpl(data))
2866 ProjectionCandidate => {
2867 self.confirm_projection_candidate(obligation);
2868 Ok(VtableParam(Vec::new()))
2871 ClosureCandidate => {
2872 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2873 Ok(VtableClosure(vtable_closure))
2876 GeneratorCandidate => {
2877 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2878 Ok(VtableGenerator(vtable_generator))
2881 FnPointerCandidate => {
2882 let data = self.confirm_fn_pointer_candidate(obligation)?;
2883 Ok(VtableFnPointer(data))
2886 TraitAliasCandidate(alias_def_id) => {
2887 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2888 Ok(VtableTraitAlias(data))
2891 ObjectCandidate => {
2892 let data = self.confirm_object_candidate(obligation);
2893 Ok(VtableObject(data))
2896 BuiltinObjectCandidate => {
2897 // This indicates something like `(Trait+Send) :
2898 // Send`. In this case, we know that this holds
2899 // because that's what the object type is telling us,
2900 // and there's really no additional obligations to
2901 // prove and no types in particular to unify etc.
2902 Ok(VtableParam(Vec::new()))
2905 BuiltinUnsizeCandidate => {
2906 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2907 Ok(VtableBuiltin(data))
2912 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2913 self.infcx.commit_unconditionally(|snapshot| {
2915 self.match_projection_obligation_against_definition_bounds(
2923 fn confirm_param_candidate(
2925 obligation: &TraitObligation<'tcx>,
2926 param: ty::PolyTraitRef<'tcx>,
2927 ) -> Vec<PredicateObligation<'tcx>> {
2928 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2930 // During evaluation, we already checked that this
2931 // where-clause trait-ref could be unified with the obligation
2932 // trait-ref. Repeat that unification now without any
2933 // transactional boundary; it should not fail.
2934 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2935 Ok(obligations) => obligations,
2938 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2946 fn confirm_builtin_candidate(
2948 obligation: &TraitObligation<'tcx>,
2950 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2952 "confirm_builtin_candidate({:?}, {:?})",
2953 obligation, has_nested
2956 let lang_items = self.tcx().lang_items();
2957 let obligations = if has_nested {
2958 let trait_def = obligation.predicate.def_id();
2959 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2960 self.sized_conditions(obligation)
2961 } else if Some(trait_def) == lang_items.copy_trait() {
2962 self.copy_clone_conditions(obligation)
2963 } else if Some(trait_def) == lang_items.clone_trait() {
2964 self.copy_clone_conditions(obligation)
2966 bug!("unexpected builtin trait {:?}", trait_def)
2968 let nested = match conditions {
2969 BuiltinImplConditions::Where(nested) => nested,
2971 "obligation {:?} had matched a builtin impl but now doesn't",
2976 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2977 self.collect_predicates_for_types(
2978 obligation.param_env,
2980 obligation.recursion_depth + 1,
2988 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2991 nested: obligations,
2995 /// This handles the case where a `auto trait Foo` impl is being used.
2996 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2998 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2999 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
3000 fn confirm_auto_impl_candidate(
3002 obligation: &TraitObligation<'tcx>,
3003 trait_def_id: DefId,
3004 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
3006 "confirm_auto_impl_candidate({:?}, {:?})",
3007 obligation, trait_def_id
3010 let types = obligation.predicate.map_bound(|inner| {
3011 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
3012 self.constituent_types_for_ty(self_ty)
3014 self.vtable_auto_impl(obligation, trait_def_id, types)
3017 /// See `confirm_auto_impl_candidate`.
3018 fn vtable_auto_impl(
3020 obligation: &TraitObligation<'tcx>,
3021 trait_def_id: DefId,
3022 nested: ty::Binder<Vec<Ty<'tcx>>>,
3023 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
3024 debug!("vtable_auto_impl: nested={:?}", nested);
3026 let cause = obligation.derived_cause(BuiltinDerivedObligation);
3027 let mut obligations = self.collect_predicates_for_types(
3028 obligation.param_env,
3030 obligation.recursion_depth + 1,
3035 let trait_obligations: Vec<PredicateObligation<'_>> =
3036 self.infcx.commit_unconditionally(|_| {
3037 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
3038 let (trait_ref, _) = self.infcx
3039 .replace_bound_vars_with_placeholders(&poly_trait_ref);
3040 let cause = obligation.derived_cause(ImplDerivedObligation);
3041 self.impl_or_trait_obligations(
3043 obligation.recursion_depth + 1,
3044 obligation.param_env,
3050 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
3051 // predicate as usual. It won't have any effect since auto traits are coinductive.
3052 obligations.extend(trait_obligations);
3054 debug!("vtable_auto_impl: obligations={:?}", obligations);
3056 VtableAutoImplData {
3058 nested: obligations,
3062 fn confirm_impl_candidate(
3064 obligation: &TraitObligation<'tcx>,
3066 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3067 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
3069 // First, create the substitutions by matching the impl again,
3070 // this time not in a probe.
3071 self.infcx.commit_unconditionally(|snapshot| {
3072 let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
3073 debug!("confirm_impl_candidate: substs={:?}", substs);
3074 let cause = obligation.derived_cause(ImplDerivedObligation);
3079 obligation.recursion_depth + 1,
3080 obligation.param_env,
3088 mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
3089 cause: ObligationCause<'tcx>,
3090 recursion_depth: usize,
3091 param_env: ty::ParamEnv<'tcx>,
3092 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3094 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
3095 impl_def_id, substs, recursion_depth,
3098 let mut impl_obligations = self.impl_or_trait_obligations(
3107 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
3108 impl_def_id, impl_obligations
3111 // Because of RFC447, the impl-trait-ref and obligations
3112 // are sufficient to determine the impl substs, without
3113 // relying on projections in the impl-trait-ref.
3115 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
3116 impl_obligations.append(&mut substs.obligations);
3120 substs: substs.value,
3121 nested: impl_obligations,
3125 fn confirm_object_candidate(
3127 obligation: &TraitObligation<'tcx>,
3128 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
3129 debug!("confirm_object_candidate({:?})", obligation);
3131 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
3132 // probably flatten the binder from the obligation and the binder
3133 // from the object. Have to try to make a broken test case that
3135 let self_ty = self.infcx
3136 .shallow_resolve(*obligation.self_ty().skip_binder());
3137 let poly_trait_ref = match self_ty.kind {
3138 ty::Dynamic(ref data, ..) =>
3139 data.principal().unwrap_or_else(|| {
3140 span_bug!(obligation.cause.span, "object candidate with no principal")
3141 }).with_self_ty(self.tcx(), self_ty),
3142 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
3145 let mut upcast_trait_ref = None;
3146 let mut nested = vec![];
3150 let tcx = self.tcx();
3152 // We want to find the first supertrait in the list of
3153 // supertraits that we can unify with, and do that
3154 // unification. We know that there is exactly one in the list
3155 // where we can unify because otherwise select would have
3156 // reported an ambiguity. (When we do find a match, also
3157 // record it for later.)
3158 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
3159 |&t| match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
3160 Ok(obligations) => {
3161 upcast_trait_ref = Some(t);
3162 nested.extend(obligations);
3169 // Additionally, for each of the nonmatching predicates that
3170 // we pass over, we sum up the set of number of vtable
3171 // entries, so that we can compute the offset for the selected
3173 vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
3177 upcast_trait_ref: upcast_trait_ref.unwrap(),
3183 fn confirm_fn_pointer_candidate(
3185 obligation: &TraitObligation<'tcx>,
3186 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3187 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3189 // Okay to skip binder; it is reintroduced below.
3190 let self_ty = self.infcx
3191 .shallow_resolve(*obligation.self_ty().skip_binder());
3192 let sig = self_ty.fn_sig(self.tcx());
3193 let trait_ref = self.tcx()
3194 .closure_trait_ref_and_return_type(
3195 obligation.predicate.def_id(),
3198 util::TupleArgumentsFlag::Yes,
3200 .map_bound(|(trait_ref, _)| trait_ref);
3205 } = project::normalize_with_depth(
3207 obligation.param_env,
3208 obligation.cause.clone(),
3209 obligation.recursion_depth + 1,
3213 self.confirm_poly_trait_refs(
3214 obligation.cause.clone(),
3215 obligation.param_env,
3216 obligation.predicate.to_poly_trait_ref(),
3219 Ok(VtableFnPointerData {
3221 nested: obligations,
3225 fn confirm_trait_alias_candidate(
3227 obligation: &TraitObligation<'tcx>,
3228 alias_def_id: DefId,
3229 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3231 "confirm_trait_alias_candidate({:?}, {:?})",
3232 obligation, alias_def_id
3235 self.infcx.commit_unconditionally(|_| {
3236 let (predicate, _) = self.infcx()
3237 .replace_bound_vars_with_placeholders(&obligation.predicate);
3238 let trait_ref = predicate.trait_ref;
3239 let trait_def_id = trait_ref.def_id;
3240 let substs = trait_ref.substs;
3242 let trait_obligations = self.impl_or_trait_obligations(
3243 obligation.cause.clone(),
3244 obligation.recursion_depth,
3245 obligation.param_env,
3251 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3252 trait_def_id, trait_obligations
3255 VtableTraitAliasData {
3258 nested: trait_obligations,
3263 fn confirm_generator_candidate(
3265 obligation: &TraitObligation<'tcx>,
3266 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3267 // Okay to skip binder because the substs on generator types never
3268 // touch bound regions, they just capture the in-scope
3269 // type/region parameters.
3270 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3271 let (generator_def_id, substs) = match self_ty.kind {
3272 ty::Generator(id, substs, _) => (id, substs),
3273 _ => bug!("closure candidate for non-closure {:?}", obligation),
3277 "confirm_generator_candidate({:?},{:?},{:?})",
3278 obligation, generator_def_id, substs
3281 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3285 } = normalize_with_depth(
3287 obligation.param_env,
3288 obligation.cause.clone(),
3289 obligation.recursion_depth + 1,
3294 "confirm_generator_candidate(generator_def_id={:?}, \
3295 trait_ref={:?}, obligations={:?})",
3296 generator_def_id, trait_ref, obligations
3299 obligations.extend(self.confirm_poly_trait_refs(
3300 obligation.cause.clone(),
3301 obligation.param_env,
3302 obligation.predicate.to_poly_trait_ref(),
3306 Ok(VtableGeneratorData {
3309 nested: obligations,
3313 fn confirm_closure_candidate(
3315 obligation: &TraitObligation<'tcx>,
3316 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3317 debug!("confirm_closure_candidate({:?})", obligation);
3319 let kind = self.tcx()
3321 .fn_trait_kind(obligation.predicate.def_id())
3322 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3324 // Okay to skip binder because the substs on closure types never
3325 // touch bound regions, they just capture the in-scope
3326 // type/region parameters.
3327 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3328 let (closure_def_id, substs) = match self_ty.kind {
3329 ty::Closure(id, substs) => (id, substs),
3330 _ => bug!("closure candidate for non-closure {:?}", obligation),
3333 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3337 } = normalize_with_depth(
3339 obligation.param_env,
3340 obligation.cause.clone(),
3341 obligation.recursion_depth + 1,
3346 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3347 closure_def_id, trait_ref, obligations
3350 obligations.extend(self.confirm_poly_trait_refs(
3351 obligation.cause.clone(),
3352 obligation.param_env,
3353 obligation.predicate.to_poly_trait_ref(),
3359 if !self.tcx().sess.opts.debugging_opts.chalk {
3360 obligations.push(Obligation::new(
3361 obligation.cause.clone(),
3362 obligation.param_env,
3363 ty::Predicate::ClosureKind(
3371 Ok(VtableClosureData {
3374 nested: obligations,
3378 /// In the case of closure types and fn pointers,
3379 /// we currently treat the input type parameters on the trait as
3380 /// outputs. This means that when we have a match we have only
3381 /// considered the self type, so we have to go back and make sure
3382 /// to relate the argument types too. This is kind of wrong, but
3383 /// since we control the full set of impls, also not that wrong,
3384 /// and it DOES yield better error messages (since we don't report
3385 /// errors as if there is no applicable impl, but rather report
3386 /// errors are about mismatched argument types.
3388 /// Here is an example. Imagine we have a closure expression
3389 /// and we desugared it so that the type of the expression is
3390 /// `Closure`, and `Closure` expects an int as argument. Then it
3391 /// is "as if" the compiler generated this impl:
3393 /// impl Fn(int) for Closure { ... }
3395 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3396 /// we have matched the self type `Closure`. At this point we'll
3397 /// compare the `int` to `usize` and generate an error.
3399 /// Note that this checking occurs *after* the impl has selected,
3400 /// because these output type parameters should not affect the
3401 /// selection of the impl. Therefore, if there is a mismatch, we
3402 /// report an error to the user.
3403 fn confirm_poly_trait_refs(
3405 obligation_cause: ObligationCause<'tcx>,
3406 obligation_param_env: ty::ParamEnv<'tcx>,
3407 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3408 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3409 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3410 let obligation_trait_ref = obligation_trait_ref.clone();
3412 .at(&obligation_cause, obligation_param_env)
3413 .sup(obligation_trait_ref, expected_trait_ref)
3414 .map(|InferOk { obligations, .. }| obligations)
3415 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3418 fn confirm_builtin_unsize_candidate(
3420 obligation: &TraitObligation<'tcx>,
3421 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3422 let tcx = self.tcx();
3424 // assemble_candidates_for_unsizing should ensure there are no late bound
3425 // regions here. See the comment there for more details.
3426 let source = self.infcx
3427 .shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3428 let target = obligation
3434 let target = self.infcx.shallow_resolve(target);
3437 "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
3441 let mut nested = vec![];
3442 match (&source.kind, &target.kind) {
3443 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3444 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3445 // See assemble_candidates_for_unsizing for more info.
3446 let existential_predicates = data_a.map_bound(|data_a| {
3448 data_a.principal().map(|x| ty::ExistentialPredicate::Trait(x))
3451 .projection_bounds()
3452 .map(|x| ty::ExistentialPredicate::Projection(x)),
3457 .map(ty::ExistentialPredicate::AutoTrait),
3459 tcx.mk_existential_predicates(iter)
3461 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
3463 // Require that the traits involved in this upcast are **equal**;
3464 // only the **lifetime bound** is changed.
3466 // FIXME: This condition is arguably too strong -- it
3467 // would suffice for the source trait to be a
3468 // *subtype* of the target trait. In particular
3469 // changing from something like `for<'a, 'b> Foo<'a,
3470 // 'b>` to `for<'a> Foo<'a, 'a>` should be
3471 // permitted. And, indeed, in the in commit
3472 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3473 // condition was loosened. However, when the leak check was added
3474 // back, using subtype here actually guies the coercion code in
3475 // such a way that it accepts `old-lub-glb-object.rs`. This is probably
3476 // a good thing, but I've modified this to `.eq` because I want
3477 // to continue rejecting that test (as we have done for quite some time)
3478 // before we are firmly comfortable with what our behavior
3479 // should be there. -nikomatsakis
3480 let InferOk { obligations, .. } = self.infcx
3481 .at(&obligation.cause, obligation.param_env)
3482 .eq(target, source_trait) // FIXME -- see below
3483 .map_err(|_| Unimplemented)?;
3484 nested.extend(obligations);
3486 // Register one obligation for 'a: 'b.
3487 let cause = ObligationCause::new(
3488 obligation.cause.span,
3489 obligation.cause.body_id,
3490 ObjectCastObligation(target),
3492 let outlives = ty::OutlivesPredicate(r_a, r_b);
3493 nested.push(Obligation::with_depth(
3495 obligation.recursion_depth + 1,
3496 obligation.param_env,
3497 ty::Binder::bind(outlives).to_predicate(),
3502 (_, &ty::Dynamic(ref data, r)) => {
3503 let mut object_dids = data.auto_traits()
3504 .chain(data.principal_def_id());
3505 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3506 return Err(TraitNotObjectSafe(did));
3509 let cause = ObligationCause::new(
3510 obligation.cause.span,
3511 obligation.cause.body_id,
3512 ObjectCastObligation(target),
3515 let predicate_to_obligation = |predicate| {
3516 Obligation::with_depth(
3518 obligation.recursion_depth + 1,
3519 obligation.param_env,
3524 // Create obligations:
3525 // - Casting T to Trait
3526 // - For all the various builtin bounds attached to the object cast. (In other
3527 // words, if the object type is Foo+Send, this would create an obligation for the
3529 // - Projection predicates
3532 .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
3535 // We can only make objects from sized types.
3536 let tr = ty::TraitRef {
3537 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
3538 substs: tcx.mk_substs_trait(source, &[]),
3540 nested.push(predicate_to_obligation(tr.to_predicate()));
3542 // If the type is `Foo+'a`, ensures that the type
3543 // being cast to `Foo+'a` outlives `'a`:
3544 let outlives = ty::OutlivesPredicate(source, r);
3545 nested.push(predicate_to_obligation(
3546 ty::Binder::dummy(outlives).to_predicate(),
3551 (&ty::Array(a, _), &ty::Slice(b)) => {
3552 let InferOk { obligations, .. } = self.infcx
3553 .at(&obligation.cause, obligation.param_env)
3555 .map_err(|_| Unimplemented)?;
3556 nested.extend(obligations);
3559 // Struct<T> -> Struct<U>.
3560 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3561 let fields = def.all_fields()
3562 .map(|f| tcx.type_of(f.did))
3563 .collect::<Vec<_>>();
3565 // The last field of the structure has to exist and contain type parameters.
3566 let field = if let Some(&field) = fields.last() {
3569 return Err(Unimplemented);
3571 let mut ty_params = GrowableBitSet::new_empty();
3572 let mut found = false;
3573 for ty in field.walk() {
3574 if let ty::Param(p) = ty.kind {
3575 ty_params.insert(p.index as usize);
3580 return Err(Unimplemented);
3583 // Replace type parameters used in unsizing with
3584 // Error and ensure they do not affect any other fields.
3585 // This could be checked after type collection for any struct
3586 // with a potentially unsized trailing field.
3587 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3588 if ty_params.contains(i) {
3589 tcx.types.err.into()
3594 let substs = tcx.mk_substs(params);
3595 for &ty in fields.split_last().unwrap().1 {
3596 if ty.subst(tcx, substs).references_error() {
3597 return Err(Unimplemented);
3601 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3602 let inner_source = field.subst(tcx, substs_a);
3603 let inner_target = field.subst(tcx, substs_b);
3605 // Check that the source struct with the target's
3606 // unsized parameters is equal to the target.
3607 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3608 if ty_params.contains(i) {
3609 substs_b.type_at(i).into()
3614 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3615 let InferOk { obligations, .. } = self.infcx
3616 .at(&obligation.cause, obligation.param_env)
3617 .eq(target, new_struct)
3618 .map_err(|_| Unimplemented)?;
3619 nested.extend(obligations);
3621 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3622 nested.push(tcx.predicate_for_trait_def(
3623 obligation.param_env,
3624 obligation.cause.clone(),
3625 obligation.predicate.def_id(),
3626 obligation.recursion_depth + 1,
3628 &[inner_target.into()],
3632 // (.., T) -> (.., U).
3633 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3634 assert_eq!(tys_a.len(), tys_b.len());
3636 // The last field of the tuple has to exist.
3637 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3640 return Err(Unimplemented);
3642 let &b_last = tys_b.last().unwrap();
3644 // Check that the source tuple with the target's
3645 // last element is equal to the target.
3646 let new_tuple = tcx.mk_tup(
3647 a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3649 let InferOk { obligations, .. } = self.infcx
3650 .at(&obligation.cause, obligation.param_env)
3651 .eq(target, new_tuple)
3652 .map_err(|_| Unimplemented)?;
3653 nested.extend(obligations);
3655 // Construct the nested T: Unsize<U> predicate.
3656 nested.push(tcx.predicate_for_trait_def(
3657 obligation.param_env,
3658 obligation.cause.clone(),
3659 obligation.predicate.def_id(),
3660 obligation.recursion_depth + 1,
3669 Ok(VtableBuiltinData { nested })
3672 ///////////////////////////////////////////////////////////////////////////
3675 // Matching is a common path used for both evaluation and
3676 // confirmation. It basically unifies types that appear in impls
3677 // and traits. This does affect the surrounding environment;
3678 // therefore, when used during evaluation, match routines must be
3679 // run inside of a `probe()` so that their side-effects are
3685 obligation: &TraitObligation<'tcx>,
3686 snapshot: &CombinedSnapshot<'_, 'tcx>,
3687 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3688 match self.match_impl(impl_def_id, obligation, snapshot) {
3689 Ok(substs) => substs,
3692 "Impl {:?} was matchable against {:?} but now is not",
3703 obligation: &TraitObligation<'tcx>,
3704 snapshot: &CombinedSnapshot<'_, 'tcx>,
3705 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3706 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3708 // Before we create the substitutions and everything, first
3709 // consider a "quick reject". This avoids creating more types
3710 // and so forth that we need to.
3711 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3715 let (skol_obligation, placeholder_map) = self.infcx()
3716 .replace_bound_vars_with_placeholders(&obligation.predicate);
3717 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3719 let impl_substs = self.infcx
3720 .fresh_substs_for_item(obligation.cause.span, impl_def_id);
3722 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3725 value: impl_trait_ref,
3726 obligations: mut nested_obligations,
3727 } = project::normalize_with_depth(
3729 obligation.param_env,
3730 obligation.cause.clone(),
3731 obligation.recursion_depth + 1,
3736 "match_impl(impl_def_id={:?}, obligation={:?}, \
3737 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3738 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3741 let InferOk { obligations, .. } = self.infcx
3742 .at(&obligation.cause, obligation.param_env)
3743 .eq(skol_obligation_trait_ref, impl_trait_ref)
3744 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3745 nested_obligations.extend(obligations);
3747 if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3748 debug!("match_impl: failed leak check due to `{}`", e);
3752 if self.intercrate.is_none()
3753 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
3755 debug!("match_impl: reservation impls only apply in intercrate mode");
3759 debug!("match_impl: success impl_substs={:?}", impl_substs);
3762 obligations: nested_obligations,
3766 fn fast_reject_trait_refs(
3768 obligation: &TraitObligation<'_>,
3769 impl_trait_ref: &ty::TraitRef<'_>,
3771 // We can avoid creating type variables and doing the full
3772 // substitution if we find that any of the input types, when
3773 // simplified, do not match.
3779 .zip(impl_trait_ref.input_types())
3780 .any(|(obligation_ty, impl_ty)| {
3781 let simplified_obligation_ty =
3782 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3783 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3785 simplified_obligation_ty.is_some()
3786 && simplified_impl_ty.is_some()
3787 && simplified_obligation_ty != simplified_impl_ty
3791 /// Normalize `where_clause_trait_ref` and try to match it against
3792 /// `obligation`. If successful, return any predicates that
3793 /// result from the normalization. Normalization is necessary
3794 /// because where-clauses are stored in the parameter environment
3796 fn match_where_clause_trait_ref(
3798 obligation: &TraitObligation<'tcx>,
3799 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3800 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3801 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3804 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3805 /// obligation is satisfied.
3806 fn match_poly_trait_ref(
3808 obligation: &TraitObligation<'tcx>,
3809 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3810 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3812 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3813 obligation, poly_trait_ref
3817 .at(&obligation.cause, obligation.param_env)
3818 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3819 .map(|InferOk { obligations, .. }| obligations)
3823 ///////////////////////////////////////////////////////////////////////////
3826 fn match_fresh_trait_refs(
3828 previous: &ty::PolyTraitRef<'tcx>,
3829 current: &ty::PolyTraitRef<'tcx>,
3830 param_env: ty::ParamEnv<'tcx>,
3832 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
3833 matcher.relate(previous, current).is_ok()
3838 previous_stack: TraitObligationStackList<'o, 'tcx>,
3839 obligation: &'o TraitObligation<'tcx>,
3840 ) -> TraitObligationStack<'o, 'tcx> {
3841 let fresh_trait_ref = obligation
3843 .to_poly_trait_ref()
3844 .fold_with(&mut self.freshener);
3846 let dfn = previous_stack.cache.next_dfn();
3847 let depth = previous_stack.depth() + 1;
3848 TraitObligationStack {
3851 reached_depth: Cell::new(depth),
3852 previous: previous_stack,
3858 fn closure_trait_ref_unnormalized(
3860 obligation: &TraitObligation<'tcx>,
3861 closure_def_id: DefId,
3862 substs: SubstsRef<'tcx>,
3863 ) -> ty::PolyTraitRef<'tcx> {
3865 "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3866 obligation, closure_def_id, substs,
3868 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3871 "closure_trait_ref_unnormalized: closure_type = {:?}",
3875 // (1) Feels icky to skip the binder here, but OTOH we know
3876 // that the self-type is an unboxed closure type and hence is
3877 // in fact unparameterized (or at least does not reference any
3878 // regions bound in the obligation). Still probably some
3879 // refactoring could make this nicer.
3881 .closure_trait_ref_and_return_type(
3882 obligation.predicate.def_id(),
3883 obligation.predicate.skip_binder().self_ty(), // (1)
3885 util::TupleArgumentsFlag::No,
3887 .map_bound(|(trait_ref, _)| trait_ref)
3890 fn generator_trait_ref_unnormalized(
3892 obligation: &TraitObligation<'tcx>,
3893 closure_def_id: DefId,
3894 substs: SubstsRef<'tcx>,
3895 ) -> ty::PolyTraitRef<'tcx> {
3896 let gen_sig = substs.as_generator().poly_sig(closure_def_id, self.tcx());
3898 // (1) Feels icky to skip the binder here, but OTOH we know
3899 // that the self-type is an generator type and hence is
3900 // in fact unparameterized (or at least does not reference any
3901 // regions bound in the obligation). Still probably some
3902 // refactoring could make this nicer.
3905 .generator_trait_ref_and_outputs(
3906 obligation.predicate.def_id(),
3907 obligation.predicate.skip_binder().self_ty(), // (1)
3910 .map_bound(|(trait_ref, ..)| trait_ref)
3913 /// Returns the obligations that are implied by instantiating an
3914 /// impl or trait. The obligations are substituted and fully
3915 /// normalized. This is used when confirming an impl or default
3917 fn impl_or_trait_obligations(
3919 cause: ObligationCause<'tcx>,
3920 recursion_depth: usize,
3921 param_env: ty::ParamEnv<'tcx>,
3922 def_id: DefId, // of impl or trait
3923 substs: SubstsRef<'tcx>, // for impl or trait
3924 ) -> Vec<PredicateObligation<'tcx>> {
3925 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3926 let tcx = self.tcx();
3928 // To allow for one-pass evaluation of the nested obligation,
3929 // each predicate must be preceded by the obligations required
3931 // for example, if we have:
3932 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
3933 // the impl will have the following predicates:
3934 // <V as Iterator>::Item = U,
3935 // U: Iterator, U: Sized,
3936 // V: Iterator, V: Sized,
3937 // <U as Iterator>::Item: Copy
3938 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3939 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3940 // `$1: Copy`, so we must ensure the obligations are emitted in
3942 let predicates = tcx.predicates_of(def_id);
3943 assert_eq!(predicates.parent, None);
3944 let mut predicates: Vec<_> = predicates
3947 .flat_map(|(predicate, _)| {
3948 let predicate = normalize_with_depth(
3953 &predicate.subst(tcx, substs),
3955 predicate.obligations.into_iter().chain(Some(Obligation {
3956 cause: cause.clone(),
3959 predicate: predicate.value,
3964 // We are performing deduplication here to avoid exponential blowups
3965 // (#38528) from happening, but the real cause of the duplication is
3966 // unknown. What we know is that the deduplication avoids exponential
3967 // amount of predicates being propagated when processing deeply nested
3970 // This code is hot enough that it's worth avoiding the allocation
3971 // required for the FxHashSet when possible. Special-casing lengths 0,
3972 // 1 and 2 covers roughly 75--80% of the cases.
3973 if predicates.len() <= 1 {
3974 // No possibility of duplicates.
3975 } else if predicates.len() == 2 {
3976 // Only two elements. Drop the second if they are equal.
3977 if predicates[0] == predicates[1] {
3978 predicates.truncate(1);
3981 // Three or more elements. Use a general deduplication process.
3982 let mut seen = FxHashSet::default();
3983 predicates.retain(|i| seen.insert(i.clone()));
3990 impl<'tcx> TraitObligation<'tcx> {
3991 #[allow(unused_comparisons)]
3992 pub fn derived_cause(
3994 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3995 ) -> ObligationCause<'tcx> {
3997 * Creates a cause for obligations that are derived from
3998 * `obligation` by a recursive search (e.g., for a builtin
3999 * bound, or eventually a `auto trait Foo`). If `obligation`
4000 * is itself a derived obligation, this is just a clone, but
4001 * otherwise we create a "derived obligation" cause so as to
4002 * keep track of the original root obligation for error
4006 let obligation = self;
4008 // NOTE(flaper87): As of now, it keeps track of the whole error
4009 // chain. Ideally, we should have a way to configure this either
4010 // by using -Z verbose or just a CLI argument.
4011 if obligation.recursion_depth >= 0 {
4012 let derived_cause = DerivedObligationCause {
4013 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
4014 parent_code: Rc::new(obligation.cause.code.clone()),
4016 let derived_code = variant(derived_cause);
4017 ObligationCause::new(
4018 obligation.cause.span,
4019 obligation.cause.body_id,
4023 obligation.cause.clone()
4028 impl<'tcx> SelectionCache<'tcx> {
4029 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4030 pub fn clear(&self) {
4031 *self.hashmap.borrow_mut() = Default::default();
4035 impl<'tcx> EvaluationCache<'tcx> {
4036 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4037 pub fn clear(&self) {
4038 *self.hashmap.borrow_mut() = Default::default();
4042 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
4043 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4044 TraitObligationStackList::with(self)
4047 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
4051 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4055 /// Indicates that attempting to evaluate this stack entry
4056 /// required accessing something from the stack at depth `reached_depth`.
4057 fn update_reached_depth(&self, reached_depth: usize) {
4059 self.depth > reached_depth,
4060 "invoked `update_reached_depth` with something under this stack: \
4061 self.depth={} reached_depth={}",
4065 debug!("update_reached_depth(reached_depth={})", reached_depth);
4067 while reached_depth < p.depth {
4068 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
4069 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
4070 p = p.previous.head.unwrap();
4075 /// The "provisional evaluation cache" is used to store intermediate cache results
4076 /// when solving auto traits. Auto traits are unusual in that they can support
4077 /// cycles. So, for example, a "proof tree" like this would be ok:
4079 /// - `Foo<T>: Send` :-
4080 /// - `Bar<T>: Send` :-
4081 /// - `Foo<T>: Send` -- cycle, but ok
4082 /// - `Baz<T>: Send`
4084 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
4085 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
4086 /// For non-auto traits, this cycle would be an error, but for auto traits (because
4087 /// they are coinductive) it is considered ok.
4089 /// However, there is a complication: at the point where we have
4090 /// "proven" `Bar<T>: Send`, we have in fact only proven it
4091 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
4092 /// *under the assumption* that `Foo<T>: Send`. But what if we later
4093 /// find out this assumption is wrong? Specifically, we could
4094 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
4095 /// `Bar<T>: Send` didn't turn out to be true.
4097 /// In Issue #60010, we found a bug in rustc where it would cache
4098 /// these intermediate results. This was fixed in #60444 by disabling
4099 /// *all* caching for things involved in a cycle -- in our example,
4100 /// that would mean we don't cache that `Bar<T>: Send`. But this led
4101 /// to large slowdowns.
4103 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
4104 /// first requires proving `Bar<T>: Send` (which is true:
4106 /// - `Foo<T>: Send` :-
4107 /// - `Bar<T>: Send` :-
4108 /// - `Foo<T>: Send` -- cycle, but ok
4109 /// - `Baz<T>: Send`
4110 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
4111 /// - `*const T: Send` -- but what if we later encounter an error?
4113 /// The *provisional evaluation cache* resolves this issue. It stores
4114 /// cache results that we've proven but which were involved in a cycle
4115 /// in some way. We track the minimal stack depth (i.e., the
4116 /// farthest from the top of the stack) that we are dependent on.
4117 /// The idea is that the cache results within are all valid -- so long as
4118 /// none of the nodes in between the current node and the node at that minimum
4119 /// depth result in an error (in which case the cached results are just thrown away).
4121 /// During evaluation, we consult this provisional cache and rely on
4122 /// it. Accessing a cached value is considered equivalent to accessing
4123 /// a result at `reached_depth`, so it marks the *current* solution as
4124 /// provisional as well. If an error is encountered, we toss out any
4125 /// provisional results added from the subtree that encountered the
4126 /// error. When we pop the node at `reached_depth` from the stack, we
4127 /// can commit all the things that remain in the provisional cache.
4128 struct ProvisionalEvaluationCache<'tcx> {
4129 /// next "depth first number" to issue -- just a counter
4132 /// Stores the "coldest" depth (bottom of stack) reached by any of
4133 /// the evaluation entries. The idea here is that all things in the provisional
4134 /// cache are always dependent on *something* that is colder in the stack:
4135 /// therefore, if we add a new entry that is dependent on something *colder still*,
4136 /// we have to modify the depth for all entries at once.
4140 /// Imagine we have a stack `A B C D E` (with `E` being the top of
4141 /// the stack). We cache something with depth 2, which means that
4142 /// it was dependent on C. Then we pop E but go on and process a
4143 /// new node F: A B C D F. Now F adds something to the cache with
4144 /// depth 1, meaning it is dependent on B. Our original cache
4145 /// entry is also dependent on B, because there is a path from E
4146 /// to C and then from C to F and from F to B.
4147 reached_depth: Cell<usize>,
4149 /// Map from cache key to the provisionally evaluated thing.
4150 /// The cache entries contain the result but also the DFN in which they
4151 /// were added. The DFN is used to clear out values on failure.
4153 /// Imagine we have a stack like:
4155 /// - `A B C` and we add a cache for the result of C (DFN 2)
4156 /// - Then we have a stack `A B D` where `D` has DFN 3
4157 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
4158 /// - `E` generates various cache entries which have cyclic dependices on `B`
4159 /// - `A B D E F` and so forth
4160 /// - the DFN of `F` for example would be 5
4161 /// - then we determine that `E` is in error -- we will then clear
4162 /// all cache values whose DFN is >= 4 -- in this case, that
4163 /// means the cached value for `F`.
4164 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
4167 /// A cache value for the provisional cache: contains the depth-first
4168 /// number (DFN) and result.
4169 #[derive(Copy, Clone, Debug)]
4170 struct ProvisionalEvaluation {
4172 result: EvaluationResult,
4175 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
4176 fn default() -> Self {
4179 reached_depth: Cell::new(std::usize::MAX),
4180 map: Default::default(),
4185 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
4186 /// Get the next DFN in sequence (basically a counter).
4187 fn next_dfn(&self) -> usize {
4188 let result = self.dfn.get();
4189 self.dfn.set(result + 1);
4193 /// Check the provisional cache for any result for
4194 /// `fresh_trait_ref`. If there is a hit, then you must consider
4195 /// it an access to the stack slots at depth
4196 /// `self.current_reached_depth()` and above.
4197 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
4199 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
4201 self.map.borrow().get(&fresh_trait_ref),
4202 self.reached_depth.get(),
4204 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
4207 /// Current value of the `reached_depth` counter -- all the
4208 /// provisional cache entries are dependent on the item at this
4210 fn current_reached_depth(&self) -> usize {
4211 self.reached_depth.get()
4214 /// Insert a provisional result into the cache. The result came
4215 /// from the node with the given DFN. It accessed a minimum depth
4216 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
4217 /// and resulted in `result`.
4218 fn insert_provisional(
4221 reached_depth: usize,
4222 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
4223 result: EvaluationResult,
4226 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
4232 let r_d = self.reached_depth.get();
4233 self.reached_depth.set(r_d.min(reached_depth));
4235 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
4237 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
4240 /// Invoked when the node with dfn `dfn` does not get a successful
4241 /// result. This will clear out any provisional cache entries
4242 /// that were added since `dfn` was created. This is because the
4243 /// provisional entries are things which must assume that the
4244 /// things on the stack at the time of their creation succeeded --
4245 /// since the failing node is presently at the top of the stack,
4246 /// these provisional entries must either depend on it or some
4248 fn on_failure(&self, dfn: usize) {
4250 "on_failure(dfn={:?})",
4253 self.map.borrow_mut().retain(|key, eval| {
4254 if !eval.from_dfn >= dfn {
4255 debug!("on_failure: removing {:?}", key);
4263 /// Invoked when the node at depth `depth` completed without
4264 /// depending on anything higher in the stack (if that completion
4265 /// was a failure, then `on_failure` should have been invoked
4266 /// already). The callback `op` will be invoked for each
4267 /// provisional entry that we can now confirm.
4271 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
4274 "on_completion(depth={}, reached_depth={})",
4276 self.reached_depth.get(),
4279 if self.reached_depth.get() < depth {
4280 debug!("on_completion: did not yet reach depth to complete");
4284 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
4286 "on_completion: fresh_trait_ref={:?} eval={:?}",
4291 op(fresh_trait_ref, eval.result);
4294 self.reached_depth.set(std::usize::MAX);
4298 #[derive(Copy, Clone)]
4299 struct TraitObligationStackList<'o, 'tcx> {
4300 cache: &'o ProvisionalEvaluationCache<'tcx>,
4301 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
4304 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
4305 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4306 TraitObligationStackList { cache, head: None }
4309 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4310 TraitObligationStackList { cache: r.cache(), head: Some(r) }
4313 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4317 fn depth(&self) -> usize {
4318 if let Some(head) = self.head {
4326 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
4327 type Item = &'o TraitObligationStack<'o, 'tcx>;
4329 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4340 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
4341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4342 write!(f, "TraitObligationStack({:?})", self.obligation)
4346 #[derive(Clone, Eq, PartialEq)]
4347 pub struct WithDepNode<T> {
4348 dep_node: DepNodeIndex,
4352 impl<T: Clone> WithDepNode<T> {
4353 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
4360 pub fn get(&self, tcx: TyCtxt<'_>) -> T {
4361 tcx.dep_graph.read_index(self.dep_node);
4362 self.cached_value.clone()