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::infer::{CombinedSnapshot, InferCtxt, InferOk, PlaceholderMap, TypeFreshener};
34 use crate::middle::lang_items;
35 use crate::ty::fast_reject;
36 use crate::ty::relate::TypeRelation;
37 use crate::ty::subst::{Subst, SubstsRef};
38 use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
39 use rustc_hir::def_id::DefId;
41 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
42 use rustc_data_structures::sync::Lock;
44 use rustc_index::bit_set::GrowableBitSet;
45 use rustc_span::symbol::sym;
46 use rustc_target::spec::abi::Abi;
47 use std::cell::{Cell, RefCell};
49 use std::fmt::{self, Display};
54 pub struct SelectionContext<'cx, 'tcx> {
55 infcx: &'cx InferCtxt<'cx, 'tcx>,
57 /// Freshener used specifically for entries on the obligation
58 /// stack. This ensures that all entries on the stack at one time
59 /// will have the same set of placeholder entries, which is
60 /// important for checking for trait bounds that recursively
61 /// require themselves.
62 freshener: TypeFreshener<'cx, 'tcx>,
64 /// If `true`, indicates that the evaluation should be conservative
65 /// and consider the possibility of types outside this crate.
66 /// This comes up primarily when resolving ambiguity. Imagine
67 /// there is some trait reference `$0: Bar` where `$0` is an
68 /// inference variable. If `intercrate` is true, then we can never
69 /// say for sure that this reference is not implemented, even if
70 /// there are *no impls at all for `Bar`*, because `$0` could be
71 /// bound to some type that in a downstream crate that implements
72 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
73 /// though, we set this to false, because we are only interested
74 /// in types that the user could actually have written --- in
75 /// other words, we consider `$0: Bar` to be unimplemented if
76 /// there is no type that the user could *actually name* that
77 /// would satisfy it. This avoids crippling inference, basically.
78 intercrate: Option<IntercrateMode>,
80 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
82 /// Controls whether or not to filter out negative impls when selecting.
83 /// This is used in librustdoc to distinguish between the lack of an impl
84 /// and a negative impl
85 allow_negative_impls: bool,
87 /// The mode that trait queries run in, which informs our error handling
88 /// policy. In essence, canonicalized queries need their errors propagated
89 /// rather than immediately reported because we do not have accurate spans.
90 query_mode: TraitQueryMode,
93 #[derive(Clone, Debug)]
94 pub enum IntercrateAmbiguityCause {
95 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
96 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
97 ReservationImpl { message: String },
100 impl IntercrateAmbiguityCause {
101 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
102 /// See #23980 for details.
103 pub fn add_intercrate_ambiguity_hint(&self, err: &mut errors::DiagnosticBuilder<'_>) {
104 err.note(&self.intercrate_ambiguity_hint());
107 pub fn intercrate_ambiguity_hint(&self) -> String {
109 &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
110 let self_desc = if let &Some(ref ty) = self_desc {
111 format!(" for type `{}`", ty)
115 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
117 &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
118 let self_desc = if let &Some(ref ty) = self_desc {
119 format!(" for type `{}`", ty)
124 "upstream crates may add a new impl of trait `{}`{} \
126 trait_desc, self_desc
129 &IntercrateAmbiguityCause::ReservationImpl { ref message } => message.clone(),
134 // A stack that walks back up the stack frame.
135 struct TraitObligationStack<'prev, 'tcx> {
136 obligation: &'prev TraitObligation<'tcx>,
138 /// The trait ref from `obligation` but "freshened" with the
139 /// selection-context's freshener. Used to check for recursion.
140 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
142 /// Starts out equal to `depth` -- if, during evaluation, we
143 /// encounter a cycle, then we will set this flag to the minimum
144 /// depth of that cycle for all participants in the cycle. These
145 /// participants will then forego caching their results. This is
146 /// not the most efficient solution, but it addresses #60010. The
147 /// problem we are trying to prevent:
149 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
150 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
151 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
153 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
154 /// is `EvaluatedToOk`; this is because they were only considered
155 /// ok on the premise that if `A: AutoTrait` held, but we indeed
156 /// encountered a problem (later on) with `A: AutoTrait. So we
157 /// currently set a flag on the stack node for `B: AutoTrait` (as
158 /// well as the second instance of `A: AutoTrait`) to suppress
161 /// This is a simple, targeted fix. A more-performant fix requires
162 /// deeper changes, but would permit more caching: we could
163 /// basically defer caching until we have fully evaluated the
164 /// tree, and then cache the entire tree at once. In any case, the
165 /// performance impact here shouldn't be so horrible: every time
166 /// this is hit, we do cache at least one trait, so we only
167 /// evaluate each member of a cycle up to N times, where N is the
168 /// length of the cycle. This means the performance impact is
169 /// bounded and we shouldn't have any terrible worst-cases.
170 reached_depth: Cell<usize>,
172 previous: TraitObligationStackList<'prev, 'tcx>,
174 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
177 /// The depth-first number of this node in the search graph -- a
178 /// pre-order index. Basically, a freshly incremented counter.
182 #[derive(Clone, Default)]
183 pub struct SelectionCache<'tcx> {
186 ty::ParamEnvAnd<'tcx, ty::TraitRef<'tcx>>,
187 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>,
192 /// The selection process begins by considering all impls, where
193 /// clauses, and so forth that might resolve an obligation. Sometimes
194 /// we'll be able to say definitively that (e.g.) an impl does not
195 /// apply to the obligation: perhaps it is defined for `usize` but the
196 /// obligation is for `int`. In that case, we drop the impl out of the
197 /// list. But the other cases are considered *candidates*.
199 /// For selection to succeed, there must be exactly one matching
200 /// candidate. If the obligation is fully known, this is guaranteed
201 /// by coherence. However, if the obligation contains type parameters
202 /// or variables, there may be multiple such impls.
204 /// It is not a real problem if multiple matching impls exist because
205 /// of type variables - it just means the obligation isn't sufficiently
206 /// elaborated. In that case we report an ambiguity, and the caller can
207 /// try again after more type information has been gathered or report a
208 /// "type annotations needed" error.
210 /// However, with type parameters, this can be a real problem - type
211 /// parameters don't unify with regular types, but they *can* unify
212 /// with variables from blanket impls, and (unless we know its bounds
213 /// will always be satisfied) picking the blanket impl will be wrong
214 /// for at least *some* substitutions. To make this concrete, if we have
216 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
217 /// impl<T: fmt::Debug> AsDebug for T {
219 /// fn debug(self) -> fmt::Debug { self }
221 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
223 /// we can't just use the impl to resolve the `<T as AsDebug>` obligation
224 /// -- a type from another crate (that doesn't implement `fmt::Debug`) could
225 /// implement `AsDebug`.
227 /// Because where-clauses match the type exactly, multiple clauses can
228 /// only match if there are unresolved variables, and we can mostly just
229 /// report this ambiguity in that case. This is still a problem - we can't
230 /// *do anything* with ambiguities that involve only regions. This is issue
233 /// If a single where-clause matches and there are no inference
234 /// variables left, then it definitely matches and we can just select
237 /// In fact, we even select the where-clause when the obligation contains
238 /// inference variables. The can lead to inference making "leaps of logic",
239 /// for example in this situation:
241 /// pub trait Foo<T> { fn foo(&self) -> T; }
242 /// impl<T> Foo<()> for T { fn foo(&self) { } }
243 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
245 /// pub fn foo<T>(t: T) where T: Foo<bool> {
246 /// println!("{:?}", <T as Foo<_>>::foo(&t));
248 /// fn main() { foo(false); }
250 /// Here the obligation `<T as Foo<$0>>` can be matched by both the blanket
251 /// impl and the where-clause. We select the where-clause and unify `$0=bool`,
252 /// so the program prints "false". However, if the where-clause is omitted,
253 /// the blanket impl is selected, we unify `$0=()`, and the program prints
256 /// Exactly the same issues apply to projection and object candidates, except
257 /// that we can have both a projection candidate and a where-clause candidate
258 /// for the same obligation. In that case either would do (except that
259 /// different "leaps of logic" would occur if inference variables are
260 /// present), and we just pick the where-clause. This is, for example,
261 /// required for associated types to work in default impls, as the bounds
262 /// are visible both as projection bounds and as where-clauses from the
263 /// parameter environment.
264 #[derive(PartialEq, Eq, Debug, Clone, TypeFoldable)]
265 enum SelectionCandidate<'tcx> {
267 /// `false` if there are no *further* obligations.
270 ParamCandidate(ty::PolyTraitRef<'tcx>),
271 ImplCandidate(DefId),
272 AutoImplCandidate(DefId),
274 /// This is a trait matching with a projected type as `Self`, and
275 /// we found an applicable bound in the trait definition.
278 /// Implementation of a `Fn`-family trait by one of the anonymous types
279 /// generated for a `||` expression.
282 /// Implementation of a `Generator` trait by one of the anonymous types
283 /// generated for a generator.
286 /// Implementation of a `Fn`-family trait by one of the anonymous
287 /// types generated for a fn pointer type (e.g., `fn(int) -> int`)
290 TraitAliasCandidate(DefId),
294 BuiltinObjectCandidate,
296 BuiltinUnsizeCandidate,
299 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
300 type Lifted = SelectionCandidate<'tcx>;
301 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
303 BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
304 ImplCandidate(def_id) => ImplCandidate(def_id),
305 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
306 ProjectionCandidate => ProjectionCandidate,
307 ClosureCandidate => ClosureCandidate,
308 GeneratorCandidate => GeneratorCandidate,
309 FnPointerCandidate => FnPointerCandidate,
310 TraitAliasCandidate(def_id) => TraitAliasCandidate(def_id),
311 ObjectCandidate => ObjectCandidate,
312 BuiltinObjectCandidate => BuiltinObjectCandidate,
313 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
315 ParamCandidate(ref trait_ref) => {
316 return tcx.lift(trait_ref).map(ParamCandidate);
322 struct SelectionCandidateSet<'tcx> {
323 // A list of candidates that definitely apply to the current
324 // obligation (meaning: types unify).
325 vec: Vec<SelectionCandidate<'tcx>>,
327 // If `true`, then there were candidates that might or might
328 // not have applied, but we couldn't tell. This occurs when some
329 // of the input types are type variables, in which case there are
330 // various "builtin" rules that might or might not trigger.
334 #[derive(PartialEq, Eq, Debug, Clone)]
335 struct EvaluatedCandidate<'tcx> {
336 candidate: SelectionCandidate<'tcx>,
337 evaluation: EvaluationResult,
340 /// When does the builtin impl for `T: Trait` apply?
341 enum BuiltinImplConditions<'tcx> {
342 /// The impl is conditional on `T1, T2, ...: Trait`.
343 Where(ty::Binder<Vec<Ty<'tcx>>>),
344 /// There is no built-in impl. There may be some other
345 /// candidate (a where-clause or user-defined impl).
347 /// It is unknown whether there is an impl.
351 /// The result of trait evaluation. The order is important
352 /// here as the evaluation of a list is the maximum of the
355 /// The evaluation results are ordered:
356 /// - `EvaluatedToOk` implies `EvaluatedToOkModuloRegions`
357 /// implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
358 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
359 /// - the "union" of evaluation results is equal to their maximum -
360 /// all the "potential success" candidates can potentially succeed,
361 /// so they are noops when unioned with a definite error, and within
362 /// the categories it's easy to see that the unions are correct.
363 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, HashStable)]
364 pub enum EvaluationResult {
365 /// Evaluation successful.
367 /// Evaluation successful, but there were unevaluated region obligations.
368 EvaluatedToOkModuloRegions,
369 /// Evaluation is known to be ambiguous -- it *might* hold for some
370 /// assignment of inference variables, but it might not.
372 /// While this has the same meaning as `EvaluatedToUnknown` -- we can't
373 /// know whether this obligation holds or not -- it is the result we
374 /// would get with an empty stack, and therefore is cacheable.
376 /// Evaluation failed because of recursion involving inference
377 /// variables. We are somewhat imprecise there, so we don't actually
378 /// know the real result.
380 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
382 /// Evaluation failed because we encountered an obligation we are already
383 /// trying to prove on this branch.
385 /// We know this branch can't be a part of a minimal proof-tree for
386 /// the "root" of our cycle, because then we could cut out the recursion
387 /// and maintain a valid proof tree. However, this does not mean
388 /// that all the obligations on this branch do not hold -- it's possible
389 /// that we entered this branch "speculatively", and that there
390 /// might be some other way to prove this obligation that does not
391 /// go through this cycle -- so we can't cache this as a failure.
393 /// For example, suppose we have this:
395 /// ```rust,ignore (pseudo-Rust)
396 /// pub trait Trait { fn xyz(); }
397 /// // This impl is "useless", but we can still have
398 /// // an `impl Trait for SomeUnsizedType` somewhere.
399 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
401 /// pub fn foo<T: Trait + ?Sized>() {
402 /// <T as Trait>::xyz();
406 /// When checking `foo`, we have to prove `T: Trait`. This basically
407 /// translates into this:
410 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
413 /// When we try to prove it, we first go the first option, which
414 /// recurses. This shows us that the impl is "useless" -- it won't
415 /// tell us that `T: Trait` unless it already implemented `Trait`
416 /// by some other means. However, that does not prevent `T: Trait`
417 /// does not hold, because of the bound (which can indeed be satisfied
418 /// by `SomeUnsizedType` from another crate).
420 // FIXME: when an `EvaluatedToRecur` goes past its parent root, we
421 // ought to convert it to an `EvaluatedToErr`, because we know
422 // there definitely isn't a proof tree for that obligation. Not
423 // doing so is still sound -- there isn't any proof tree, so the
424 // branch still can't be a part of a minimal one -- but does not re-enable caching.
426 /// Evaluation failed.
430 impl EvaluationResult {
431 /// Returns `true` if this evaluation result is known to apply, even
432 /// considering outlives constraints.
433 pub fn must_apply_considering_regions(self) -> bool {
434 self == EvaluatedToOk
437 /// Returns `true` if this evaluation result is known to apply, ignoring
438 /// outlives constraints.
439 pub fn must_apply_modulo_regions(self) -> bool {
440 self <= EvaluatedToOkModuloRegions
443 pub fn may_apply(self) -> bool {
445 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToUnknown => {
449 EvaluatedToErr | EvaluatedToRecur => false,
453 fn is_stack_dependent(self) -> bool {
455 EvaluatedToUnknown | EvaluatedToRecur => true,
457 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToErr => false,
462 /// Indicates that trait evaluation caused overflow.
463 #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable)]
464 pub struct OverflowError;
466 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
467 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
468 SelectionError::Overflow
472 #[derive(Clone, Default)]
473 pub struct EvaluationCache<'tcx> {
475 FxHashMap<ty::ParamEnvAnd<'tcx, ty::PolyTraitRef<'tcx>>, WithDepNode<EvaluationResult>>,
479 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
480 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
483 freshener: infcx.freshener(),
485 intercrate_ambiguity_causes: None,
486 allow_negative_impls: false,
487 query_mode: TraitQueryMode::Standard,
492 infcx: &'cx InferCtxt<'cx, 'tcx>,
493 mode: IntercrateMode,
494 ) -> SelectionContext<'cx, 'tcx> {
495 debug!("intercrate({:?})", mode);
498 freshener: infcx.freshener(),
499 intercrate: Some(mode),
500 intercrate_ambiguity_causes: None,
501 allow_negative_impls: false,
502 query_mode: TraitQueryMode::Standard,
506 pub fn with_negative(
507 infcx: &'cx InferCtxt<'cx, 'tcx>,
508 allow_negative_impls: bool,
509 ) -> SelectionContext<'cx, 'tcx> {
510 debug!("with_negative({:?})", allow_negative_impls);
513 freshener: infcx.freshener(),
515 intercrate_ambiguity_causes: None,
516 allow_negative_impls,
517 query_mode: TraitQueryMode::Standard,
521 pub fn with_query_mode(
522 infcx: &'cx InferCtxt<'cx, 'tcx>,
523 query_mode: TraitQueryMode,
524 ) -> SelectionContext<'cx, 'tcx> {
525 debug!("with_query_mode({:?})", query_mode);
528 freshener: infcx.freshener(),
530 intercrate_ambiguity_causes: None,
531 allow_negative_impls: false,
536 /// Enables tracking of intercrate ambiguity causes. These are
537 /// used in coherence to give improved diagnostics. We don't do
538 /// this until we detect a coherence error because it can lead to
539 /// false overflow results (#47139) and because it costs
540 /// computation time.
541 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
542 assert!(self.intercrate.is_some());
543 assert!(self.intercrate_ambiguity_causes.is_none());
544 self.intercrate_ambiguity_causes = Some(vec![]);
545 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
548 /// Gets the intercrate ambiguity causes collected since tracking
549 /// was enabled and disables tracking at the same time. If
550 /// tracking is not enabled, just returns an empty vector.
551 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
552 assert!(self.intercrate.is_some());
553 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
556 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
560 pub fn tcx(&self) -> TyCtxt<'tcx> {
564 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
568 ///////////////////////////////////////////////////////////////////////////
571 // The selection phase tries to identify *how* an obligation will
572 // be resolved. For example, it will identify which impl or
573 // parameter bound is to be used. The process can be inconclusive
574 // if the self type in the obligation is not fully inferred. Selection
575 // can result in an error in one of two ways:
577 // 1. If no applicable impl or parameter bound can be found.
578 // 2. If the output type parameters in the obligation do not match
579 // those specified by the impl/bound. For example, if the obligation
580 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
581 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
583 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
584 /// type environment by performing unification.
587 obligation: &TraitObligation<'tcx>,
588 ) -> SelectionResult<'tcx, Selection<'tcx>> {
589 debug!("select({:?})", obligation);
590 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
592 let pec = &ProvisionalEvaluationCache::default();
593 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
595 let candidate = match self.candidate_from_obligation(&stack) {
596 Err(SelectionError::Overflow) => {
597 // In standard mode, overflow must have been caught and reported
599 assert!(self.query_mode == TraitQueryMode::Canonical);
600 return Err(SelectionError::Overflow);
608 Ok(Some(candidate)) => candidate,
611 match self.confirm_candidate(obligation, candidate) {
612 Err(SelectionError::Overflow) => {
613 assert!(self.query_mode == TraitQueryMode::Canonical);
614 Err(SelectionError::Overflow)
617 Ok(candidate) => Ok(Some(candidate)),
621 ///////////////////////////////////////////////////////////////////////////
624 // Tests whether an obligation can be selected or whether an impl
625 // can be applied to particular types. It skips the "confirmation"
626 // step and hence completely ignores output type parameters.
628 // The result is "true" if the obligation *may* hold and "false" if
629 // we can be sure it does not.
631 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
632 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
633 debug!("predicate_may_hold_fatal({:?})", obligation);
635 // This fatal query is a stopgap that should only be used in standard mode,
636 // where we do not expect overflow to be propagated.
637 assert!(self.query_mode == TraitQueryMode::Standard);
639 self.evaluate_root_obligation(obligation)
640 .expect("Overflow should be caught earlier in standard query mode")
644 /// Evaluates whether the obligation `obligation` can be satisfied
645 /// and returns an `EvaluationResult`. This is meant for the
647 pub fn evaluate_root_obligation(
649 obligation: &PredicateObligation<'tcx>,
650 ) -> Result<EvaluationResult, OverflowError> {
651 self.evaluation_probe(|this| {
652 this.evaluate_predicate_recursively(
653 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
661 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
662 ) -> Result<EvaluationResult, OverflowError> {
663 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
664 let result = op(self)?;
665 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
667 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
672 /// Evaluates the predicates in `predicates` recursively. Note that
673 /// this applies projections in the predicates, and therefore
674 /// is run within an inference probe.
675 fn evaluate_predicates_recursively<'o, I>(
677 stack: TraitObligationStackList<'o, 'tcx>,
679 ) -> Result<EvaluationResult, OverflowError>
681 I: IntoIterator<Item = PredicateObligation<'tcx>>,
683 let mut result = EvaluatedToOk;
684 for obligation in predicates {
685 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
686 debug!("evaluate_predicate_recursively({:?}) = {:?}", obligation, eval);
687 if let EvaluatedToErr = eval {
688 // fast-path - EvaluatedToErr is the top of the lattice,
689 // so we don't need to look on the other predicates.
690 return Ok(EvaluatedToErr);
692 result = cmp::max(result, eval);
698 fn evaluate_predicate_recursively<'o>(
700 previous_stack: TraitObligationStackList<'o, 'tcx>,
701 obligation: PredicateObligation<'tcx>,
702 ) -> Result<EvaluationResult, OverflowError> {
704 "evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
705 previous_stack.head(),
709 // `previous_stack` stores a `TraitObligatiom`, while `obligation` is
710 // a `PredicateObligation`. These are distinct types, so we can't
711 // use any `Option` combinator method that would force them to be
713 match previous_stack.head() {
714 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
715 None => self.check_recursion_limit(&obligation, &obligation)?,
718 match obligation.predicate {
719 ty::Predicate::Trait(ref t) => {
720 debug_assert!(!t.has_escaping_bound_vars());
721 let obligation = obligation.with(t.clone());
722 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
725 ty::Predicate::Subtype(ref p) => {
726 // Does this code ever run?
727 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
728 Some(Ok(InferOk { mut obligations, .. })) => {
729 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
730 self.evaluate_predicates_recursively(
732 obligations.into_iter(),
735 Some(Err(_)) => Ok(EvaluatedToErr),
736 None => Ok(EvaluatedToAmbig),
740 ty::Predicate::WellFormed(ty) => match ty::wf::obligations(
742 obligation.param_env,
743 obligation.cause.body_id,
745 obligation.cause.span,
747 Some(mut obligations) => {
748 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
749 self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
751 None => Ok(EvaluatedToAmbig),
754 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
755 // We do not consider region relationships when evaluating trait matches.
756 Ok(EvaluatedToOkModuloRegions)
759 ty::Predicate::ObjectSafe(trait_def_id) => {
760 if self.tcx().is_object_safe(trait_def_id) {
767 ty::Predicate::Projection(ref data) => {
768 let project_obligation = obligation.with(data.clone());
769 match project::poly_project_and_unify_type(self, &project_obligation) {
770 Ok(Some(mut subobligations)) => {
771 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
772 let result = self.evaluate_predicates_recursively(
774 subobligations.into_iter(),
777 ProjectionCacheKey::from_poly_projection_predicate(self, data)
779 self.infcx.projection_cache.borrow_mut().complete(key);
783 Ok(None) => Ok(EvaluatedToAmbig),
784 Err(_) => Ok(EvaluatedToErr),
788 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
789 match self.infcx.closure_kind(closure_def_id, closure_substs) {
790 Some(closure_kind) => {
791 if closure_kind.extends(kind) {
797 None => Ok(EvaluatedToAmbig),
801 ty::Predicate::ConstEvaluatable(def_id, substs) => {
802 if !(obligation.param_env, substs).has_local_value() {
803 match self.tcx().const_eval_resolve(obligation.param_env, def_id, substs, None)
805 Ok(_) => Ok(EvaluatedToOk),
806 Err(_) => Ok(EvaluatedToErr),
809 // Inference variables still left in param_env or substs.
816 fn evaluate_trait_predicate_recursively<'o>(
818 previous_stack: TraitObligationStackList<'o, 'tcx>,
819 mut obligation: TraitObligation<'tcx>,
820 ) -> Result<EvaluationResult, OverflowError> {
821 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
823 if self.intercrate.is_none()
824 && obligation.is_global()
825 && obligation.param_env.caller_bounds.iter().all(|bound| bound.needs_subst())
827 // If a param env has no global bounds, global obligations do not
828 // depend on its particular value in order to work, so we can clear
829 // out the param env and get better caching.
830 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
831 obligation.param_env = obligation.param_env.without_caller_bounds();
834 let stack = self.push_stack(previous_stack, &obligation);
835 let fresh_trait_ref = stack.fresh_trait_ref;
836 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
837 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
841 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
842 debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
843 stack.update_reached_depth(stack.cache().current_reached_depth());
847 // Check if this is a match for something already on the
848 // stack. If so, we don't want to insert the result into the
849 // main cache (it is cycle dependent) nor the provisional
850 // cache (which is meant for things that have completed but
851 // for a "backedge" -- this result *is* the backedge).
852 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
853 return Ok(cycle_result);
856 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
857 let result = result?;
859 if !result.must_apply_modulo_regions() {
860 stack.cache().on_failure(stack.dfn);
863 let reached_depth = stack.reached_depth.get();
864 if reached_depth >= stack.depth {
865 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
866 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
868 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
869 self.insert_evaluation_cache(
870 obligation.param_env,
873 provisional_result.max(result),
877 debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
879 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
880 is a cycle participant (at depth {}, reached depth {})",
881 fresh_trait_ref, stack.depth, reached_depth,
884 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
890 /// If there is any previous entry on the stack that precisely
891 /// matches this obligation, then we can assume that the
892 /// obligation is satisfied for now (still all other conditions
893 /// must be met of course). One obvious case this comes up is
894 /// marker traits like `Send`. Think of a linked list:
896 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
898 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
899 /// `Option<Box<List<T>>>` is `Send`, and in turn
900 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
903 /// Note that we do this comparison using the `fresh_trait_ref`
904 /// fields. Because these have all been freshened using
905 /// `self.freshener`, we can be sure that (a) this will not
906 /// affect the inferencer state and (b) that if we see two
907 /// fresh regions with the same index, they refer to the same
908 /// unbound type variable.
909 fn check_evaluation_cycle(
911 stack: &TraitObligationStack<'_, 'tcx>,
912 ) -> Option<EvaluationResult> {
913 if let Some(cycle_depth) = stack
915 .skip(1) // Skip top-most frame.
917 stack.obligation.param_env == prev.obligation.param_env
918 && stack.fresh_trait_ref == prev.fresh_trait_ref
920 .map(|stack| stack.depth)
923 "evaluate_stack({:?}) --> recursive at depth {}",
924 stack.fresh_trait_ref, cycle_depth,
927 // If we have a stack like `A B C D E A`, where the top of
928 // the stack is the final `A`, then this will iterate over
929 // `A, E, D, C, B` -- i.e., all the participants apart
930 // from the cycle head. We mark them as participating in a
931 // cycle. This suppresses caching for those nodes. See
932 // `in_cycle` field for more details.
933 stack.update_reached_depth(cycle_depth);
935 // Subtle: when checking for a coinductive cycle, we do
936 // not compare using the "freshened trait refs" (which
937 // have erased regions) but rather the fully explicit
938 // trait refs. This is important because it's only a cycle
939 // if the regions match exactly.
940 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
941 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
942 if self.coinductive_match(cycle) {
943 debug!("evaluate_stack({:?}) --> recursive, coinductive", stack.fresh_trait_ref);
946 debug!("evaluate_stack({:?}) --> recursive, inductive", stack.fresh_trait_ref);
947 Some(EvaluatedToRecur)
954 fn evaluate_stack<'o>(
956 stack: &TraitObligationStack<'o, 'tcx>,
957 ) -> Result<EvaluationResult, OverflowError> {
958 // In intercrate mode, whenever any of the types are unbound,
959 // there can always be an impl. Even if there are no impls in
960 // this crate, perhaps the type would be unified with
961 // something from another crate that does provide an impl.
963 // In intra mode, we must still be conservative. The reason is
964 // that we want to avoid cycles. Imagine an impl like:
966 // impl<T:Eq> Eq for Vec<T>
968 // and a trait reference like `$0 : Eq` where `$0` is an
969 // unbound variable. When we evaluate this trait-reference, we
970 // will unify `$0` with `Vec<$1>` (for some fresh variable
971 // `$1`), on the condition that `$1 : Eq`. We will then wind
972 // up with many candidates (since that are other `Eq` impls
973 // that apply) and try to winnow things down. This results in
974 // a recursive evaluation that `$1 : Eq` -- as you can
975 // imagine, this is just where we started. To avoid that, we
976 // check for unbound variables and return an ambiguous (hence possible)
977 // match if we've seen this trait before.
979 // This suffices to allow chains like `FnMut` implemented in
980 // terms of `Fn` etc, but we could probably make this more
982 let unbound_input_types =
983 stack.fresh_trait_ref.skip_binder().input_types().any(|ty| ty.is_fresh());
984 // This check was an imperfect workaround for a bug in the old
985 // intercrate mode; it should be removed when that goes away.
986 if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
988 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
989 stack.fresh_trait_ref
991 // Heuristics: show the diagnostics when there are no candidates in crate.
992 if self.intercrate_ambiguity_causes.is_some() {
993 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
994 if let Ok(candidate_set) = self.assemble_candidates(stack) {
995 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
996 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
997 let self_ty = trait_ref.self_ty();
998 let cause = IntercrateAmbiguityCause::DownstreamCrate {
999 trait_desc: trait_ref.print_only_trait_path().to_string(),
1000 self_desc: if self_ty.has_concrete_skeleton() {
1001 Some(self_ty.to_string())
1006 debug!("evaluate_stack: pushing cause = {:?}", cause);
1007 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1011 return Ok(EvaluatedToAmbig);
1013 if unbound_input_types
1014 && stack.iter().skip(1).any(|prev| {
1015 stack.obligation.param_env == prev.obligation.param_env
1016 && self.match_fresh_trait_refs(
1017 &stack.fresh_trait_ref,
1018 &prev.fresh_trait_ref,
1019 prev.obligation.param_env,
1024 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
1025 stack.fresh_trait_ref
1027 return Ok(EvaluatedToUnknown);
1030 match self.candidate_from_obligation(stack) {
1031 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1032 Ok(None) => Ok(EvaluatedToAmbig),
1033 Err(Overflow) => Err(OverflowError),
1034 Err(..) => Ok(EvaluatedToErr),
1038 /// For defaulted traits, we use a co-inductive strategy to solve, so
1039 /// that recursion is ok. This routine returns `true` if the top of the
1040 /// stack (`cycle[0]`):
1042 /// - is a defaulted trait,
1043 /// - it also appears in the backtrace at some position `X`,
1044 /// - all the predicates at positions `X..` between `X` and the top are
1045 /// also defaulted traits.
1046 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1048 I: Iterator<Item = ty::Predicate<'tcx>>,
1050 let mut cycle = cycle;
1051 cycle.all(|predicate| self.coinductive_predicate(predicate))
1054 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1055 let result = match predicate {
1056 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1059 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1063 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1064 /// obligations are met. Returns whether `candidate` remains viable after this further
1066 fn evaluate_candidate<'o>(
1068 stack: &TraitObligationStack<'o, 'tcx>,
1069 candidate: &SelectionCandidate<'tcx>,
1070 ) -> Result<EvaluationResult, OverflowError> {
1072 "evaluate_candidate: depth={} candidate={:?}",
1073 stack.obligation.recursion_depth, candidate
1075 let result = self.evaluation_probe(|this| {
1076 let candidate = (*candidate).clone();
1077 match this.confirm_candidate(stack.obligation, candidate) {
1078 Ok(selection) => this.evaluate_predicates_recursively(
1080 selection.nested_obligations().into_iter(),
1082 Err(..) => Ok(EvaluatedToErr),
1086 "evaluate_candidate: depth={} result={:?}",
1087 stack.obligation.recursion_depth, result
1092 fn check_evaluation_cache(
1094 param_env: ty::ParamEnv<'tcx>,
1095 trait_ref: ty::PolyTraitRef<'tcx>,
1096 ) -> Option<EvaluationResult> {
1097 let tcx = self.tcx();
1098 if self.can_use_global_caches(param_env) {
1099 let cache = tcx.evaluation_cache.hashmap.borrow();
1100 if let Some(cached) = cache.get(¶m_env.and(trait_ref)) {
1101 return Some(cached.get(tcx));
1108 .get(¶m_env.and(trait_ref))
1109 .map(|v| v.get(tcx))
1112 fn insert_evaluation_cache(
1114 param_env: ty::ParamEnv<'tcx>,
1115 trait_ref: ty::PolyTraitRef<'tcx>,
1116 dep_node: DepNodeIndex,
1117 result: EvaluationResult,
1119 // Avoid caching results that depend on more than just the trait-ref
1120 // - the stack can create recursion.
1121 if result.is_stack_dependent() {
1125 if self.can_use_global_caches(param_env) {
1126 if !trait_ref.has_local_value() {
1128 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1131 // This may overwrite the cache with the same value
1132 // FIXME: Due to #50507 this overwrites the different values
1133 // This should be changed to use HashMapExt::insert_same
1134 // when that is fixed
1139 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
1144 debug!("insert_evaluation_cache(trait_ref={:?}, candidate={:?})", trait_ref, result,);
1149 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
1152 /// For various reasons, it's possible for a subobligation
1153 /// to have a *lower* recursion_depth than the obligation used to create it.
1154 /// Projection sub-obligations may be returned from the projection cache,
1155 /// which results in obligations with an 'old' `recursion_depth`.
1156 /// Additionally, methods like `ty::wf::obligations` and
1157 /// `InferCtxt.subtype_predicate` produce subobligations without
1158 /// taking in a 'parent' depth, causing the generated subobligations
1159 /// to have a `recursion_depth` of `0`.
1161 /// To ensure that obligation_depth never decreasees, we force all subobligations
1162 /// to have at least the depth of the original obligation.
1163 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1168 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1171 /// Checks that the recursion limit has not been exceeded.
1173 /// The weird return type of this function allows it to be used with the `try` (`?`)
1174 /// operator within certain functions.
1175 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1177 obligation: &Obligation<'tcx, T>,
1178 error_obligation: &Obligation<'tcx, V>,
1179 ) -> Result<(), OverflowError> {
1180 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1181 if obligation.recursion_depth >= recursion_limit {
1182 match self.query_mode {
1183 TraitQueryMode::Standard => {
1184 self.infcx().report_overflow_error(error_obligation, true);
1186 TraitQueryMode::Canonical => {
1187 return Err(OverflowError);
1194 ///////////////////////////////////////////////////////////////////////////
1195 // CANDIDATE ASSEMBLY
1197 // The selection process begins by examining all in-scope impls,
1198 // caller obligations, and so forth and assembling a list of
1199 // candidates. See the [rustc guide] for more details.
1202 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1204 fn candidate_from_obligation<'o>(
1206 stack: &TraitObligationStack<'o, 'tcx>,
1207 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1208 // Watch out for overflow. This intentionally bypasses (and does
1209 // not update) the cache.
1210 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
1212 // Check the cache. Note that we freshen the trait-ref
1213 // separately rather than using `stack.fresh_trait_ref` --
1214 // this is because we want the unbound variables to be
1215 // replaced with fresh types starting from index 0.
1216 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1218 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1219 cache_fresh_trait_pred, stack
1221 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
1224 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1226 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1230 // If no match, compute result and insert into cache.
1232 // FIXME(nikomatsakis) -- this cache is not taking into
1233 // account cycles that may have occurred in forming the
1234 // candidate. I don't know of any specific problems that
1235 // result but it seems awfully suspicious.
1236 let (candidate, dep_node) =
1237 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1239 debug!("CACHE MISS: SELECT({:?})={:?}", cache_fresh_trait_pred, candidate);
1240 self.insert_candidate_cache(
1241 stack.obligation.param_env,
1242 cache_fresh_trait_pred,
1249 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1251 OP: FnOnce(&mut Self) -> R,
1253 let (result, dep_node) =
1254 self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || op(self));
1255 self.tcx().dep_graph.read_index(dep_node);
1259 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1260 fn filter_negative_and_reservation_impls(
1262 candidate: SelectionCandidate<'tcx>,
1263 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1264 if let ImplCandidate(def_id) = candidate {
1265 let tcx = self.tcx();
1266 match tcx.impl_polarity(def_id) {
1267 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1268 return Err(Unimplemented);
1270 ty::ImplPolarity::Reservation => {
1271 if let Some(intercrate_ambiguity_clauses) =
1272 &mut self.intercrate_ambiguity_causes
1274 let attrs = tcx.get_attrs(def_id);
1275 let attr = attr::find_by_name(&attrs, sym::rustc_reservation_impl);
1276 let value = attr.and_then(|a| a.value_str());
1277 if let Some(value) = value {
1279 "filter_negative_and_reservation_impls: \
1280 reservation impl ambiguity on {:?}",
1283 intercrate_ambiguity_clauses.push(
1284 IntercrateAmbiguityCause::ReservationImpl {
1285 message: value.to_string(),
1298 fn candidate_from_obligation_no_cache<'o>(
1300 stack: &TraitObligationStack<'o, 'tcx>,
1301 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1302 if stack.obligation.predicate.references_error() {
1303 // If we encounter a `Error`, we generally prefer the
1304 // most "optimistic" result in response -- that is, the
1305 // one least likely to report downstream errors. But
1306 // because this routine is shared by coherence and by
1307 // trait selection, there isn't an obvious "right" choice
1308 // here in that respect, so we opt to just return
1309 // ambiguity and let the upstream clients sort it out.
1313 if let Some(conflict) = self.is_knowable(stack) {
1314 debug!("coherence stage: not knowable");
1315 if self.intercrate_ambiguity_causes.is_some() {
1316 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1317 // Heuristics: show the diagnostics when there are no candidates in crate.
1318 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1319 let mut no_candidates_apply = true;
1321 let evaluated_candidates =
1322 candidate_set.vec.iter().map(|c| self.evaluate_candidate(stack, &c));
1324 for ec in evaluated_candidates {
1328 no_candidates_apply = false;
1332 Err(e) => return Err(e.into()),
1337 if !candidate_set.ambiguous && no_candidates_apply {
1338 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1339 let self_ty = trait_ref.self_ty();
1340 let trait_desc = trait_ref.print_only_trait_path().to_string();
1341 let self_desc = if self_ty.has_concrete_skeleton() {
1342 Some(self_ty.to_string())
1346 let cause = if let Conflict::Upstream = conflict {
1347 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1349 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1351 debug!("evaluate_stack: pushing cause = {:?}", cause);
1352 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1359 let candidate_set = self.assemble_candidates(stack)?;
1361 if candidate_set.ambiguous {
1362 debug!("candidate set contains ambig");
1366 let mut candidates = candidate_set.vec;
1368 debug!("assembled {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1370 // At this point, we know that each of the entries in the
1371 // candidate set is *individually* applicable. Now we have to
1372 // figure out if they contain mutual incompatibilities. This
1373 // frequently arises if we have an unconstrained input type --
1374 // for example, we are looking for `$0: Eq` where `$0` is some
1375 // unconstrained type variable. In that case, we'll get a
1376 // candidate which assumes $0 == int, one that assumes `$0 ==
1377 // usize`, etc. This spells an ambiguity.
1379 // If there is more than one candidate, first winnow them down
1380 // by considering extra conditions (nested obligations and so
1381 // forth). We don't winnow if there is exactly one
1382 // candidate. This is a relatively minor distinction but it
1383 // can lead to better inference and error-reporting. An
1384 // example would be if there was an impl:
1386 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1388 // and we were to see some code `foo.push_clone()` where `boo`
1389 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1390 // we were to winnow, we'd wind up with zero candidates.
1391 // Instead, we select the right impl now but report "`Bar` does
1392 // not implement `Clone`".
1393 if candidates.len() == 1 {
1394 return self.filter_negative_and_reservation_impls(candidates.pop().unwrap());
1397 // Winnow, but record the exact outcome of evaluation, which
1398 // is needed for specialization. Propagate overflow if it occurs.
1399 let mut candidates = candidates
1401 .map(|c| match self.evaluate_candidate(stack, &c) {
1402 Ok(eval) if eval.may_apply() => {
1403 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
1406 Err(OverflowError) => Err(Overflow),
1408 .flat_map(Result::transpose)
1409 .collect::<Result<Vec<_>, _>>()?;
1411 debug!("winnowed to {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1413 // If there are STILL multiple candidates, we can further
1414 // reduce the list by dropping duplicates -- including
1415 // resolving specializations.
1416 if candidates.len() > 1 {
1418 while i < candidates.len() {
1419 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1420 self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1423 debug!("Dropping candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1424 candidates.swap_remove(i);
1426 debug!("Retaining candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1429 // If there are *STILL* multiple candidates, give up
1430 // and report ambiguity.
1432 debug!("multiple matches, ambig");
1439 // If there are *NO* candidates, then there are no impls --
1440 // that we know of, anyway. Note that in the case where there
1441 // are unbound type variables within the obligation, it might
1442 // be the case that you could still satisfy the obligation
1443 // from another crate by instantiating the type variables with
1444 // a type from another crate that does have an impl. This case
1445 // is checked for in `evaluate_stack` (and hence users
1446 // who might care about this case, like coherence, should use
1448 if candidates.is_empty() {
1449 return Err(Unimplemented);
1452 // Just one candidate left.
1453 self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate)
1456 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1457 debug!("is_knowable(intercrate={:?})", self.intercrate);
1459 if !self.intercrate.is_some() {
1463 let obligation = &stack.obligation;
1464 let predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1466 // Okay to skip binder because of the nature of the
1467 // trait-ref-is-knowable check, which does not care about
1469 let trait_ref = predicate.skip_binder().trait_ref;
1471 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1473 Some(Conflict::Downstream { used_to_be_broken: true }),
1474 Some(IntercrateMode::Issue43355),
1475 ) = (result, self.intercrate)
1477 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1484 /// Returns `true` if the global caches can be used.
1485 /// Do note that if the type itself is not in the
1486 /// global tcx, the local caches will be used.
1487 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1488 // If there are any e.g. inference variables in the `ParamEnv`, then we
1489 // always use a cache local to this particular scope. Otherwise, we
1490 // switch to a global cache.
1491 if param_env.has_local_value() {
1495 // Avoid using the master cache during coherence and just rely
1496 // on the local cache. This effectively disables caching
1497 // during coherence. It is really just a simplification to
1498 // avoid us having to fear that coherence results "pollute"
1499 // the master cache. Since coherence executes pretty quickly,
1500 // it's not worth going to more trouble to increase the
1501 // hit-rate, I don't think.
1502 if self.intercrate.is_some() {
1506 // Otherwise, we can use the global cache.
1510 fn check_candidate_cache(
1512 param_env: ty::ParamEnv<'tcx>,
1513 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1514 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1515 let tcx = self.tcx();
1516 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1517 if self.can_use_global_caches(param_env) {
1518 let cache = tcx.selection_cache.hashmap.borrow();
1519 if let Some(cached) = cache.get(¶m_env.and(*trait_ref)) {
1520 return Some(cached.get(tcx));
1527 .get(¶m_env.and(*trait_ref))
1528 .map(|v| v.get(tcx))
1531 /// Determines whether can we safely cache the result
1532 /// of selecting an obligation. This is almost always `true`,
1533 /// except when dealing with certain `ParamCandidate`s.
1535 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1536 /// since it was usually produced directly from a `DefId`. However,
1537 /// certain cases (currently only librustdoc's blanket impl finder),
1538 /// a `ParamEnv` may be explicitly constructed with inference types.
1539 /// When this is the case, we do *not* want to cache the resulting selection
1540 /// candidate. This is due to the fact that it might not always be possible
1541 /// to equate the obligation's trait ref and the candidate's trait ref,
1542 /// if more constraints end up getting added to an inference variable.
1544 /// Because of this, we always want to re-run the full selection
1545 /// process for our obligation the next time we see it, since
1546 /// we might end up picking a different `SelectionCandidate` (or none at all).
1547 fn can_cache_candidate(
1549 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1552 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => {
1553 !trait_ref.skip_binder().input_types().any(|t| t.walk().any(|t_| t_.is_ty_infer()))
1559 fn insert_candidate_cache(
1561 param_env: ty::ParamEnv<'tcx>,
1562 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1563 dep_node: DepNodeIndex,
1564 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1566 let tcx = self.tcx();
1567 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1569 if !self.can_cache_candidate(&candidate) {
1571 "insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1572 candidate is not cacheable",
1573 trait_ref, candidate
1578 if self.can_use_global_caches(param_env) {
1579 if let Err(Overflow) = candidate {
1580 // Don't cache overflow globally; we only produce this in certain modes.
1581 } else if !trait_ref.has_local_value() {
1582 if !candidate.has_local_value() {
1584 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1585 trait_ref, candidate,
1587 // This may overwrite the cache with the same value.
1591 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1598 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1599 trait_ref, candidate,
1605 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1608 fn assemble_candidates<'o>(
1610 stack: &TraitObligationStack<'o, 'tcx>,
1611 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1612 let TraitObligationStack { obligation, .. } = *stack;
1613 let ref obligation = Obligation {
1614 param_env: obligation.param_env,
1615 cause: obligation.cause.clone(),
1616 recursion_depth: obligation.recursion_depth,
1617 predicate: self.infcx().resolve_vars_if_possible(&obligation.predicate),
1620 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1621 // Self is a type variable (e.g., `_: AsRef<str>`).
1623 // This is somewhat problematic, as the current scheme can't really
1624 // handle it turning to be a projection. This does end up as truly
1625 // ambiguous in most cases anyway.
1627 // Take the fast path out - this also improves
1628 // performance by preventing assemble_candidates_from_impls from
1629 // matching every impl for this trait.
1630 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1633 let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
1635 self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1637 // Other bounds. Consider both in-scope bounds from fn decl
1638 // and applicable impls. There is a certain set of precedence rules here.
1639 let def_id = obligation.predicate.def_id();
1640 let lang_items = self.tcx().lang_items();
1642 if lang_items.copy_trait() == Some(def_id) {
1643 debug!("obligation self ty is {:?}", obligation.predicate.skip_binder().self_ty());
1645 // User-defined copy impls are permitted, but only for
1646 // structs and enums.
1647 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1649 // For other types, we'll use the builtin rules.
1650 let copy_conditions = self.copy_clone_conditions(obligation);
1651 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1652 } else if lang_items.sized_trait() == Some(def_id) {
1653 // Sized is never implementable by end-users, it is
1654 // always automatically computed.
1655 let sized_conditions = self.sized_conditions(obligation);
1656 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1657 } else if lang_items.unsize_trait() == Some(def_id) {
1658 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1660 if lang_items.clone_trait() == Some(def_id) {
1661 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1662 // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone`
1663 // types have builtin support for `Clone`.
1664 let clone_conditions = self.copy_clone_conditions(obligation);
1665 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1668 self.assemble_generator_candidates(obligation, &mut candidates)?;
1669 self.assemble_closure_candidates(obligation, &mut candidates)?;
1670 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1671 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1672 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1675 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1676 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1677 // Auto implementations have lower priority, so we only
1678 // consider triggering a default if there is no other impl that can apply.
1679 if candidates.vec.is_empty() {
1680 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1682 debug!("candidate list size: {}", candidates.vec.len());
1686 fn assemble_candidates_from_projected_tys(
1688 obligation: &TraitObligation<'tcx>,
1689 candidates: &mut SelectionCandidateSet<'tcx>,
1691 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1693 // Before we go into the whole placeholder thing, just
1694 // quickly check if the self-type is a projection at all.
1695 match obligation.predicate.skip_binder().trait_ref.self_ty().kind {
1696 ty::Projection(_) | ty::Opaque(..) => {}
1697 ty::Infer(ty::TyVar(_)) => {
1699 obligation.cause.span,
1700 "Self=_ should have been handled by assemble_candidates"
1706 let result = self.infcx.probe(|snapshot| {
1707 self.match_projection_obligation_against_definition_bounds(obligation, snapshot)
1711 candidates.vec.push(ProjectionCandidate);
1715 fn match_projection_obligation_against_definition_bounds(
1717 obligation: &TraitObligation<'tcx>,
1718 snapshot: &CombinedSnapshot<'_, 'tcx>,
1720 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1721 let (placeholder_trait_predicate, placeholder_map) =
1722 self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
1724 "match_projection_obligation_against_definition_bounds: \
1725 placeholder_trait_predicate={:?}",
1726 placeholder_trait_predicate,
1729 let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().kind {
1730 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1731 ty::Opaque(def_id, substs) => (def_id, substs),
1734 obligation.cause.span,
1735 "match_projection_obligation_against_definition_bounds() called \
1736 but self-ty is not a projection: {:?}",
1737 placeholder_trait_predicate.trait_ref.self_ty()
1742 "match_projection_obligation_against_definition_bounds: \
1743 def_id={:?}, substs={:?}",
1747 let predicates_of = self.tcx().predicates_of(def_id);
1748 let bounds = predicates_of.instantiate(self.tcx(), substs);
1750 "match_projection_obligation_against_definition_bounds: \
1755 let elaborated_predicates = util::elaborate_predicates(self.tcx(), bounds.predicates);
1756 let matching_bound = elaborated_predicates.filter_to_traits().find(|bound| {
1757 self.infcx.probe(|_| {
1758 self.match_projection(
1761 placeholder_trait_predicate.trait_ref.clone(),
1769 "match_projection_obligation_against_definition_bounds: \
1770 matching_bound={:?}",
1773 match matching_bound {
1776 // Repeat the successful match, if any, this time outside of a probe.
1777 let result = self.match_projection(
1780 placeholder_trait_predicate.trait_ref.clone(),
1791 fn match_projection(
1793 obligation: &TraitObligation<'tcx>,
1794 trait_bound: ty::PolyTraitRef<'tcx>,
1795 placeholder_trait_ref: ty::TraitRef<'tcx>,
1796 placeholder_map: &PlaceholderMap<'tcx>,
1797 snapshot: &CombinedSnapshot<'_, 'tcx>,
1799 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1801 .at(&obligation.cause, obligation.param_env)
1802 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1804 && self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1807 /// Given an obligation like `<SomeTrait for T>`, searches the obligations that the caller
1808 /// supplied to find out whether it is listed among them.
1810 /// Never affects the inference environment.
1811 fn assemble_candidates_from_caller_bounds<'o>(
1813 stack: &TraitObligationStack<'o, 'tcx>,
1814 candidates: &mut SelectionCandidateSet<'tcx>,
1815 ) -> Result<(), SelectionError<'tcx>> {
1816 debug!("assemble_candidates_from_caller_bounds({:?})", stack.obligation);
1818 let all_bounds = stack
1823 .filter_map(|o| o.to_opt_poly_trait_ref());
1825 // Micro-optimization: filter out predicates relating to different traits.
1826 let matching_bounds =
1827 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1829 // Keep only those bounds which may apply, and propagate overflow if it occurs.
1830 let mut param_candidates = vec![];
1831 for bound in matching_bounds {
1832 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1834 param_candidates.push(ParamCandidate(bound));
1838 candidates.vec.extend(param_candidates);
1843 fn evaluate_where_clause<'o>(
1845 stack: &TraitObligationStack<'o, 'tcx>,
1846 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1847 ) -> Result<EvaluationResult, OverflowError> {
1848 self.evaluation_probe(|this| {
1849 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1850 Ok(obligations) => {
1851 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1853 Err(()) => Ok(EvaluatedToErr),
1858 fn assemble_generator_candidates(
1860 obligation: &TraitObligation<'tcx>,
1861 candidates: &mut SelectionCandidateSet<'tcx>,
1862 ) -> Result<(), SelectionError<'tcx>> {
1863 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1867 // Okay to skip binder because the substs on generator types never
1868 // touch bound regions, they just capture the in-scope
1869 // type/region parameters.
1870 let self_ty = *obligation.self_ty().skip_binder();
1871 match self_ty.kind {
1872 ty::Generator(..) => {
1874 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1878 candidates.vec.push(GeneratorCandidate);
1880 ty::Infer(ty::TyVar(_)) => {
1881 debug!("assemble_generator_candidates: ambiguous self-type");
1882 candidates.ambiguous = true;
1890 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1891 /// FnMut<..>` where `X` is a closure type.
1893 /// Note: the type parameters on a closure candidate are modeled as *output* type
1894 /// parameters and hence do not affect whether this trait is a match or not. They will be
1895 /// unified during the confirmation step.
1896 fn assemble_closure_candidates(
1898 obligation: &TraitObligation<'tcx>,
1899 candidates: &mut SelectionCandidateSet<'tcx>,
1900 ) -> Result<(), SelectionError<'tcx>> {
1901 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()) {
1908 // Okay to skip binder because the substs on closure types never
1909 // touch bound regions, they just capture the in-scope
1910 // type/region parameters
1911 match obligation.self_ty().skip_binder().kind {
1912 ty::Closure(closure_def_id, closure_substs) => {
1913 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}", kind, obligation);
1914 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1915 Some(closure_kind) => {
1916 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1917 if closure_kind.extends(kind) {
1918 candidates.vec.push(ClosureCandidate);
1922 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1923 candidates.vec.push(ClosureCandidate);
1927 ty::Infer(ty::TyVar(_)) => {
1928 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1929 candidates.ambiguous = true;
1937 /// Implements one of the `Fn()` family for a fn pointer.
1938 fn assemble_fn_pointer_candidates(
1940 obligation: &TraitObligation<'tcx>,
1941 candidates: &mut SelectionCandidateSet<'tcx>,
1942 ) -> Result<(), SelectionError<'tcx>> {
1943 // We provide impl of all fn traits for fn pointers.
1944 if self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()).is_none() {
1948 // Okay to skip binder because what we are inspecting doesn't involve bound regions.
1949 let self_ty = *obligation.self_ty().skip_binder();
1950 match self_ty.kind {
1951 ty::Infer(ty::TyVar(_)) => {
1952 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1953 candidates.ambiguous = true; // Could wind up being a fn() type.
1955 // Provide an impl, but only for suitable `fn` pointers.
1956 ty::FnDef(..) | ty::FnPtr(_) => {
1958 unsafety: hir::Unsafety::Normal,
1962 } = self_ty.fn_sig(self.tcx()).skip_binder()
1964 candidates.vec.push(FnPointerCandidate);
1973 /// Searches for impls that might apply to `obligation`.
1974 fn assemble_candidates_from_impls(
1976 obligation: &TraitObligation<'tcx>,
1977 candidates: &mut SelectionCandidateSet<'tcx>,
1978 ) -> Result<(), SelectionError<'tcx>> {
1979 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1981 self.tcx().for_each_relevant_impl(
1982 obligation.predicate.def_id(),
1983 obligation.predicate.skip_binder().trait_ref.self_ty(),
1985 self.infcx.probe(|snapshot| {
1986 if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot) {
1987 candidates.vec.push(ImplCandidate(impl_def_id));
1996 fn assemble_candidates_from_auto_impls(
1998 obligation: &TraitObligation<'tcx>,
1999 candidates: &mut SelectionCandidateSet<'tcx>,
2000 ) -> Result<(), SelectionError<'tcx>> {
2001 // Okay to skip binder here because the tests we do below do not involve bound regions.
2002 let self_ty = *obligation.self_ty().skip_binder();
2003 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2005 let def_id = obligation.predicate.def_id();
2007 if self.tcx().trait_is_auto(def_id) {
2008 match self_ty.kind {
2009 ty::Dynamic(..) => {
2010 // For object types, we don't know what the closed
2011 // over types are. This means we conservatively
2012 // say nothing; a candidate may be added by
2013 // `assemble_candidates_from_object_ty`.
2015 ty::Foreign(..) => {
2016 // Since the contents of foreign types is unknown,
2017 // we don't add any `..` impl. Default traits could
2018 // still be provided by a manual implementation for
2019 // this trait and type.
2021 ty::Param(..) | ty::Projection(..) => {
2022 // In these cases, we don't know what the actual
2023 // type is. Therefore, we cannot break it down
2024 // into its constituent types. So we don't
2025 // consider the `..` impl but instead just add no
2026 // candidates: this means that typeck will only
2027 // succeed if there is another reason to believe
2028 // that this obligation holds. That could be a
2029 // where-clause or, in the case of an object type,
2030 // it could be that the object type lists the
2031 // trait (e.g., `Foo+Send : Send`). See
2032 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2033 // for an example of a test case that exercises
2036 ty::Infer(ty::TyVar(_)) => {
2037 // The auto impl might apply; we don't know.
2038 candidates.ambiguous = true;
2040 ty::Generator(_, _, movability)
2041 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
2044 hir::Movability::Static => {
2045 // Immovable generators are never `Unpin`, so
2046 // suppress the normal auto-impl candidate for it.
2048 hir::Movability::Movable => {
2049 // Movable generators are always `Unpin`, so add an
2050 // unconditional builtin candidate.
2051 candidates.vec.push(BuiltinCandidate { has_nested: false });
2056 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2063 /// Searches for impls that might apply to `obligation`.
2064 fn assemble_candidates_from_object_ty(
2066 obligation: &TraitObligation<'tcx>,
2067 candidates: &mut SelectionCandidateSet<'tcx>,
2070 "assemble_candidates_from_object_ty(self_ty={:?})",
2071 obligation.self_ty().skip_binder()
2074 self.infcx.probe(|_snapshot| {
2075 // The code below doesn't care about regions, and the
2076 // self-ty here doesn't escape this probe, so just erase
2078 let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
2079 let poly_trait_ref = match self_ty.kind {
2080 ty::Dynamic(ref data, ..) => {
2081 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
2083 "assemble_candidates_from_object_ty: matched builtin bound, \
2086 candidates.vec.push(BuiltinObjectCandidate);
2090 if let Some(principal) = data.principal() {
2091 if !self.infcx.tcx.features().object_safe_for_dispatch {
2092 principal.with_self_ty(self.tcx(), self_ty)
2093 } else if self.tcx().is_object_safe(principal.def_id()) {
2094 principal.with_self_ty(self.tcx(), self_ty)
2099 // Only auto trait bounds exist.
2103 ty::Infer(ty::TyVar(_)) => {
2104 debug!("assemble_candidates_from_object_ty: ambiguous");
2105 candidates.ambiguous = true; // could wind up being an object type
2111 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}", poly_trait_ref);
2113 // Count only those upcast versions that match the trait-ref
2114 // we are looking for. Specifically, do not only check for the
2115 // correct trait, but also the correct type parameters.
2116 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2117 // but `Foo` is declared as `trait Foo: Bar<u32>`.
2118 let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
2119 .filter(|upcast_trait_ref| {
2120 self.infcx.probe(|_| {
2121 let upcast_trait_ref = upcast_trait_ref.clone();
2122 self.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
2127 if upcast_trait_refs > 1 {
2128 // Can be upcast in many ways; need more type information.
2129 candidates.ambiguous = true;
2130 } else if upcast_trait_refs == 1 {
2131 candidates.vec.push(ObjectCandidate);
2136 /// Searches for unsizing that might apply to `obligation`.
2137 fn assemble_candidates_for_unsizing(
2139 obligation: &TraitObligation<'tcx>,
2140 candidates: &mut SelectionCandidateSet<'tcx>,
2142 // We currently never consider higher-ranked obligations e.g.
2143 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2144 // because they are a priori invalid, and we could potentially add support
2145 // for them later, it's just that there isn't really a strong need for it.
2146 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2147 // impl, and those are generally applied to concrete types.
2149 // That said, one might try to write a fn with a where clause like
2150 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2151 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2152 // Still, you'd be more likely to write that where clause as
2154 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2155 // obligation above. Should be possible to extend this in the future.
2156 let source = match obligation.self_ty().no_bound_vars() {
2159 // Don't add any candidates if there are bound regions.
2163 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2165 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})", source, target);
2167 let may_apply = match (&source.kind, &target.kind) {
2168 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2169 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2170 // Upcasts permit two things:
2172 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
2173 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
2175 // Note that neither of these changes requires any
2176 // change at runtime. Eventually this will be
2179 // We always upcast when we can because of reason
2180 // #2 (region bounds).
2181 data_a.principal_def_id() == data_b.principal_def_id()
2184 // All of a's auto traits need to be in b's auto traits.
2185 .all(|b| data_a.auto_traits().any(|a| a == b))
2189 (_, &ty::Dynamic(..)) => true,
2191 // Ambiguous handling is below `T` -> `Trait`, because inference
2192 // variables can still implement `Unsize<Trait>` and nested
2193 // obligations will have the final say (likely deferred).
2194 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2195 debug!("assemble_candidates_for_unsizing: ambiguous");
2196 candidates.ambiguous = true;
2200 // `[T; n]` -> `[T]`
2201 (&ty::Array(..), &ty::Slice(_)) => true,
2203 // `Struct<T>` -> `Struct<U>`
2204 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2205 def_id_a == def_id_b
2208 // `(.., T)` -> `(.., U)`
2209 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2215 candidates.vec.push(BuiltinUnsizeCandidate);
2219 fn assemble_candidates_for_trait_alias(
2221 obligation: &TraitObligation<'tcx>,
2222 candidates: &mut SelectionCandidateSet<'tcx>,
2223 ) -> Result<(), SelectionError<'tcx>> {
2224 // Okay to skip binder here because the tests we do below do not involve bound regions.
2225 let self_ty = *obligation.self_ty().skip_binder();
2226 debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
2228 let def_id = obligation.predicate.def_id();
2230 if self.tcx().is_trait_alias(def_id) {
2231 candidates.vec.push(TraitAliasCandidate(def_id.clone()));
2237 ///////////////////////////////////////////////////////////////////////////
2240 // Winnowing is the process of attempting to resolve ambiguity by
2241 // probing further. During the winnowing process, we unify all
2242 // type variables and then we also attempt to evaluate recursive
2243 // bounds to see if they are satisfied.
2245 /// Returns `true` if `victim` should be dropped in favor of
2246 /// `other`. Generally speaking we will drop duplicate
2247 /// candidates and prefer where-clause candidates.
2249 /// See the comment for "SelectionCandidate" for more details.
2250 fn candidate_should_be_dropped_in_favor_of(
2252 victim: &EvaluatedCandidate<'tcx>,
2253 other: &EvaluatedCandidate<'tcx>,
2255 if victim.candidate == other.candidate {
2259 // Check if a bound would previously have been removed when normalizing
2260 // the param_env so that it can be given the lowest priority. See
2261 // #50825 for the motivation for this.
2263 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2265 match other.candidate {
2266 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2267 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2268 // lifetime of a variable.
2269 BuiltinCandidate { has_nested: false } => true,
2270 ParamCandidate(ref cand) => match victim.candidate {
2271 AutoImplCandidate(..) => {
2273 "default implementations shouldn't be recorded \
2274 when there are other valid candidates"
2277 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2278 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2279 // lifetime of a variable.
2280 BuiltinCandidate { has_nested: false } => false,
2283 | GeneratorCandidate
2284 | FnPointerCandidate
2285 | BuiltinObjectCandidate
2286 | BuiltinUnsizeCandidate
2287 | BuiltinCandidate { .. }
2288 | TraitAliasCandidate(..) => {
2289 // Global bounds from the where clause should be ignored
2290 // here (see issue #50825). Otherwise, we have a where
2291 // clause so don't go around looking for impls.
2294 ObjectCandidate | ProjectionCandidate => {
2295 // Arbitrarily give param candidates priority
2296 // over projection and object candidates.
2299 ParamCandidate(..) => false,
2301 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2302 AutoImplCandidate(..) => {
2304 "default implementations shouldn't be recorded \
2305 when there are other valid candidates"
2308 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2309 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2310 // lifetime of a variable.
2311 BuiltinCandidate { has_nested: false } => false,
2314 | GeneratorCandidate
2315 | FnPointerCandidate
2316 | BuiltinObjectCandidate
2317 | BuiltinUnsizeCandidate
2318 | BuiltinCandidate { .. }
2319 | TraitAliasCandidate(..) => true,
2320 ObjectCandidate | ProjectionCandidate => {
2321 // Arbitrarily give param candidates priority
2322 // over projection and object candidates.
2325 ParamCandidate(ref cand) => is_global(cand),
2327 ImplCandidate(other_def) => {
2328 // See if we can toss out `victim` based on specialization.
2329 // This requires us to know *for sure* that the `other` impl applies
2330 // i.e., `EvaluatedToOk`.
2331 if other.evaluation.must_apply_modulo_regions() {
2332 match victim.candidate {
2333 ImplCandidate(victim_def) => {
2334 let tcx = self.tcx();
2335 return tcx.specializes((other_def, victim_def))
2337 .impls_are_allowed_to_overlap(other_def, victim_def)
2340 ParamCandidate(ref cand) => {
2341 // Prefer the impl to a global where clause candidate.
2342 return is_global(cand);
2351 | GeneratorCandidate
2352 | FnPointerCandidate
2353 | BuiltinObjectCandidate
2354 | BuiltinUnsizeCandidate
2355 | BuiltinCandidate { has_nested: true } => {
2356 match victim.candidate {
2357 ParamCandidate(ref cand) => {
2358 // Prefer these to a global where-clause bound
2359 // (see issue #50825).
2360 is_global(cand) && other.evaluation.must_apply_modulo_regions()
2369 ///////////////////////////////////////////////////////////////////////////
2372 // These cover the traits that are built-in to the language
2373 // itself: `Copy`, `Clone` and `Sized`.
2375 fn assemble_builtin_bound_candidates(
2377 conditions: BuiltinImplConditions<'tcx>,
2378 candidates: &mut SelectionCandidateSet<'tcx>,
2379 ) -> Result<(), SelectionError<'tcx>> {
2381 BuiltinImplConditions::Where(nested) => {
2382 debug!("builtin_bound: nested={:?}", nested);
2385 .push(BuiltinCandidate { has_nested: nested.skip_binder().len() > 0 });
2387 BuiltinImplConditions::None => {}
2388 BuiltinImplConditions::Ambiguous => {
2389 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2390 candidates.ambiguous = true;
2397 fn sized_conditions(
2399 obligation: &TraitObligation<'tcx>,
2400 ) -> BuiltinImplConditions<'tcx> {
2401 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2403 // NOTE: binder moved to (*)
2404 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2406 match self_ty.kind {
2407 ty::Infer(ty::IntVar(_))
2408 | ty::Infer(ty::FloatVar(_))
2419 | ty::GeneratorWitness(..)
2424 // safe for everything
2425 Where(ty::Binder::dummy(Vec::new()))
2428 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2431 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2434 ty::Adt(def, substs) => {
2435 let sized_crit = def.sized_constraint(self.tcx());
2436 // (*) binder moved here
2437 Where(ty::Binder::bind(
2438 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect(),
2442 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2443 ty::Infer(ty::TyVar(_)) => Ambiguous,
2445 ty::UnnormalizedProjection(..)
2446 | ty::Placeholder(..)
2448 | ty::Infer(ty::FreshTy(_))
2449 | ty::Infer(ty::FreshIntTy(_))
2450 | ty::Infer(ty::FreshFloatTy(_)) => {
2451 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2456 fn copy_clone_conditions(
2458 obligation: &TraitObligation<'tcx>,
2459 ) -> BuiltinImplConditions<'tcx> {
2460 // NOTE: binder moved to (*)
2461 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2463 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2465 match self_ty.kind {
2466 ty::Infer(ty::IntVar(_))
2467 | ty::Infer(ty::FloatVar(_))
2470 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2479 | ty::Ref(_, _, hir::Mutability::Not) => {
2480 // Implementations provided in libcore
2488 | ty::GeneratorWitness(..)
2490 | ty::Ref(_, _, hir::Mutability::Mut) => None,
2492 ty::Array(element_ty, _) => {
2493 // (*) binder moved here
2494 Where(ty::Binder::bind(vec![element_ty]))
2498 // (*) binder moved here
2499 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2502 ty::Closure(def_id, substs) => {
2503 // (*) binder moved here
2504 Where(ty::Binder::bind(substs.as_closure().upvar_tys(def_id, self.tcx()).collect()))
2507 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2508 // Fallback to whatever user-defined impls exist in this case.
2512 ty::Infer(ty::TyVar(_)) => {
2513 // Unbound type variable. Might or might not have
2514 // applicable impls and so forth, depending on what
2515 // those type variables wind up being bound to.
2519 ty::UnnormalizedProjection(..)
2520 | ty::Placeholder(..)
2522 | ty::Infer(ty::FreshTy(_))
2523 | ty::Infer(ty::FreshIntTy(_))
2524 | ty::Infer(ty::FreshFloatTy(_)) => {
2525 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2530 /// For default impls, we need to break apart a type into its
2531 /// "constituent types" -- meaning, the types that it contains.
2533 /// Here are some (simple) examples:
2536 /// (i32, u32) -> [i32, u32]
2537 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2538 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2539 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2541 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2551 | ty::Infer(ty::IntVar(_))
2552 | ty::Infer(ty::FloatVar(_))
2554 | ty::Char => Vec::new(),
2556 ty::UnnormalizedProjection(..)
2557 | ty::Placeholder(..)
2561 | ty::Projection(..)
2563 | ty::Infer(ty::TyVar(_))
2564 | ty::Infer(ty::FreshTy(_))
2565 | ty::Infer(ty::FreshIntTy(_))
2566 | ty::Infer(ty::FreshFloatTy(_)) => {
2567 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2570 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2574 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2576 ty::Tuple(ref tys) => {
2577 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2578 tys.iter().map(|k| k.expect_ty()).collect()
2581 ty::Closure(def_id, ref substs) => {
2582 substs.as_closure().upvar_tys(def_id, self.tcx()).collect()
2585 ty::Generator(def_id, ref substs, _) => {
2586 let witness = substs.as_generator().witness(def_id, self.tcx());
2589 .upvar_tys(def_id, self.tcx())
2590 .chain(iter::once(witness))
2594 ty::GeneratorWitness(types) => {
2595 // This is sound because no regions in the witness can refer to
2596 // the binder outside the witness. So we'll effectivly reuse
2597 // the implicit binder around the witness.
2598 types.skip_binder().to_vec()
2601 // For `PhantomData<T>`, we pass `T`.
2602 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2604 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2606 ty::Opaque(def_id, substs) => {
2607 // We can resolve the `impl Trait` to its concrete type,
2608 // which enforces a DAG between the functions requiring
2609 // the auto trait bounds in question.
2610 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2615 fn collect_predicates_for_types(
2617 param_env: ty::ParamEnv<'tcx>,
2618 cause: ObligationCause<'tcx>,
2619 recursion_depth: usize,
2620 trait_def_id: DefId,
2621 types: ty::Binder<Vec<Ty<'tcx>>>,
2622 ) -> Vec<PredicateObligation<'tcx>> {
2623 // Because the types were potentially derived from
2624 // higher-ranked obligations they may reference late-bound
2625 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2626 // yield a type like `for<'a> &'a int`. In general, we
2627 // maintain the invariant that we never manipulate bound
2628 // regions, so we have to process these bound regions somehow.
2630 // The strategy is to:
2632 // 1. Instantiate those regions to placeholder regions (e.g.,
2633 // `for<'a> &'a int` becomes `&0 int`.
2634 // 2. Produce something like `&'0 int : Copy`
2635 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2642 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2644 self.infcx.commit_unconditionally(|_| {
2645 let (skol_ty, _) = self.infcx.replace_bound_vars_with_placeholders(&ty);
2646 let Normalized { value: normalized_ty, mut obligations } =
2647 project::normalize_with_depth(
2654 let skol_obligation = self.tcx().predicate_for_trait_def(
2662 obligations.push(skol_obligation);
2669 ///////////////////////////////////////////////////////////////////////////
2672 // Confirmation unifies the output type parameters of the trait
2673 // with the values found in the obligation, possibly yielding a
2674 // type error. See the [rustc guide] for more details.
2677 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
2679 fn confirm_candidate(
2681 obligation: &TraitObligation<'tcx>,
2682 candidate: SelectionCandidate<'tcx>,
2683 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2684 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2687 BuiltinCandidate { has_nested } => {
2688 let data = self.confirm_builtin_candidate(obligation, has_nested);
2689 Ok(VtableBuiltin(data))
2692 ParamCandidate(param) => {
2693 let obligations = self.confirm_param_candidate(obligation, param);
2694 Ok(VtableParam(obligations))
2697 ImplCandidate(impl_def_id) => {
2698 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2701 AutoImplCandidate(trait_def_id) => {
2702 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2703 Ok(VtableAutoImpl(data))
2706 ProjectionCandidate => {
2707 self.confirm_projection_candidate(obligation);
2708 Ok(VtableParam(Vec::new()))
2711 ClosureCandidate => {
2712 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2713 Ok(VtableClosure(vtable_closure))
2716 GeneratorCandidate => {
2717 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2718 Ok(VtableGenerator(vtable_generator))
2721 FnPointerCandidate => {
2722 let data = self.confirm_fn_pointer_candidate(obligation)?;
2723 Ok(VtableFnPointer(data))
2726 TraitAliasCandidate(alias_def_id) => {
2727 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2728 Ok(VtableTraitAlias(data))
2731 ObjectCandidate => {
2732 let data = self.confirm_object_candidate(obligation);
2733 Ok(VtableObject(data))
2736 BuiltinObjectCandidate => {
2737 // This indicates something like `Trait + Send: Send`. In this case, we know that
2738 // this holds because that's what the object type is telling us, and there's really
2739 // no additional obligations to prove and no types in particular to unify, etc.
2740 Ok(VtableParam(Vec::new()))
2743 BuiltinUnsizeCandidate => {
2744 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2745 Ok(VtableBuiltin(data))
2750 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2751 self.infcx.commit_unconditionally(|snapshot| {
2753 self.match_projection_obligation_against_definition_bounds(obligation, snapshot);
2758 fn confirm_param_candidate(
2760 obligation: &TraitObligation<'tcx>,
2761 param: ty::PolyTraitRef<'tcx>,
2762 ) -> Vec<PredicateObligation<'tcx>> {
2763 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2765 // During evaluation, we already checked that this
2766 // where-clause trait-ref could be unified with the obligation
2767 // trait-ref. Repeat that unification now without any
2768 // transactional boundary; it should not fail.
2769 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2770 Ok(obligations) => obligations,
2773 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2781 fn confirm_builtin_candidate(
2783 obligation: &TraitObligation<'tcx>,
2785 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2786 debug!("confirm_builtin_candidate({:?}, {:?})", obligation, has_nested);
2788 let lang_items = self.tcx().lang_items();
2789 let obligations = if has_nested {
2790 let trait_def = obligation.predicate.def_id();
2791 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2792 self.sized_conditions(obligation)
2793 } else if Some(trait_def) == lang_items.copy_trait() {
2794 self.copy_clone_conditions(obligation)
2795 } else if Some(trait_def) == lang_items.clone_trait() {
2796 self.copy_clone_conditions(obligation)
2798 bug!("unexpected builtin trait {:?}", trait_def)
2800 let nested = match conditions {
2801 BuiltinImplConditions::Where(nested) => nested,
2802 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation),
2805 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2806 self.collect_predicates_for_types(
2807 obligation.param_env,
2809 obligation.recursion_depth + 1,
2817 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2819 VtableBuiltinData { nested: obligations }
2822 /// This handles the case where a `auto trait Foo` impl is being used.
2823 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2825 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2826 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2827 fn confirm_auto_impl_candidate(
2829 obligation: &TraitObligation<'tcx>,
2830 trait_def_id: DefId,
2831 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2832 debug!("confirm_auto_impl_candidate({:?}, {:?})", obligation, trait_def_id);
2834 let types = obligation.predicate.map_bound(|inner| {
2835 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2836 self.constituent_types_for_ty(self_ty)
2838 self.vtable_auto_impl(obligation, trait_def_id, types)
2841 /// See `confirm_auto_impl_candidate`.
2842 fn vtable_auto_impl(
2844 obligation: &TraitObligation<'tcx>,
2845 trait_def_id: DefId,
2846 nested: ty::Binder<Vec<Ty<'tcx>>>,
2847 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2848 debug!("vtable_auto_impl: nested={:?}", nested);
2850 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2851 let mut obligations = self.collect_predicates_for_types(
2852 obligation.param_env,
2854 obligation.recursion_depth + 1,
2859 let trait_obligations: Vec<PredicateObligation<'_>> =
2860 self.infcx.commit_unconditionally(|_| {
2861 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2862 let (trait_ref, _) =
2863 self.infcx.replace_bound_vars_with_placeholders(&poly_trait_ref);
2864 let cause = obligation.derived_cause(ImplDerivedObligation);
2865 self.impl_or_trait_obligations(
2867 obligation.recursion_depth + 1,
2868 obligation.param_env,
2874 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
2875 // predicate as usual. It won't have any effect since auto traits are coinductive.
2876 obligations.extend(trait_obligations);
2878 debug!("vtable_auto_impl: obligations={:?}", obligations);
2880 VtableAutoImplData { trait_def_id, nested: obligations }
2883 fn confirm_impl_candidate(
2885 obligation: &TraitObligation<'tcx>,
2887 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2888 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
2890 // First, create the substitutions by matching the impl again,
2891 // this time not in a probe.
2892 self.infcx.commit_unconditionally(|snapshot| {
2893 let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
2894 debug!("confirm_impl_candidate: substs={:?}", substs);
2895 let cause = obligation.derived_cause(ImplDerivedObligation);
2900 obligation.recursion_depth + 1,
2901 obligation.param_env,
2909 mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
2910 cause: ObligationCause<'tcx>,
2911 recursion_depth: usize,
2912 param_env: ty::ParamEnv<'tcx>,
2913 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2915 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
2916 impl_def_id, substs, recursion_depth,
2919 let mut impl_obligations = self.impl_or_trait_obligations(
2928 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2929 impl_def_id, impl_obligations
2932 // Because of RFC447, the impl-trait-ref and obligations
2933 // are sufficient to determine the impl substs, without
2934 // relying on projections in the impl-trait-ref.
2936 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2937 impl_obligations.append(&mut substs.obligations);
2939 VtableImplData { impl_def_id, substs: substs.value, nested: impl_obligations }
2942 fn confirm_object_candidate(
2944 obligation: &TraitObligation<'tcx>,
2945 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
2946 debug!("confirm_object_candidate({:?})", obligation);
2948 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
2949 // probably flatten the binder from the obligation and the binder
2950 // from the object. Have to try to make a broken test case that
2952 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2953 let poly_trait_ref = match self_ty.kind {
2954 ty::Dynamic(ref data, ..) => data
2956 .unwrap_or_else(|| {
2957 span_bug!(obligation.cause.span, "object candidate with no principal")
2959 .with_self_ty(self.tcx(), self_ty),
2960 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
2963 let mut upcast_trait_ref = None;
2964 let mut nested = vec![];
2968 let tcx = self.tcx();
2970 // We want to find the first supertrait in the list of
2971 // supertraits that we can unify with, and do that
2972 // unification. We know that there is exactly one in the list
2973 // where we can unify, because otherwise select would have
2974 // reported an ambiguity. (When we do find a match, also
2975 // record it for later.)
2976 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(|&t| {
2977 match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
2978 Ok(obligations) => {
2979 upcast_trait_ref = Some(t);
2980 nested.extend(obligations);
2987 // Additionally, for each of the non-matching predicates that
2988 // we pass over, we sum up the set of number of vtable
2989 // entries, so that we can compute the offset for the selected
2991 vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
2994 VtableObjectData { upcast_trait_ref: upcast_trait_ref.unwrap(), vtable_base, nested }
2997 fn confirm_fn_pointer_candidate(
2999 obligation: &TraitObligation<'tcx>,
3000 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3001 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3003 // Okay to skip binder; it is reintroduced below.
3004 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3005 let sig = self_ty.fn_sig(self.tcx());
3006 let trait_ref = self
3008 .closure_trait_ref_and_return_type(
3009 obligation.predicate.def_id(),
3012 util::TupleArgumentsFlag::Yes,
3014 .map_bound(|(trait_ref, _)| trait_ref);
3016 let Normalized { value: trait_ref, obligations } = project::normalize_with_depth(
3018 obligation.param_env,
3019 obligation.cause.clone(),
3020 obligation.recursion_depth + 1,
3024 self.confirm_poly_trait_refs(
3025 obligation.cause.clone(),
3026 obligation.param_env,
3027 obligation.predicate.to_poly_trait_ref(),
3030 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
3033 fn confirm_trait_alias_candidate(
3035 obligation: &TraitObligation<'tcx>,
3036 alias_def_id: DefId,
3037 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3038 debug!("confirm_trait_alias_candidate({:?}, {:?})", obligation, alias_def_id);
3040 self.infcx.commit_unconditionally(|_| {
3041 let (predicate, _) =
3042 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
3043 let trait_ref = predicate.trait_ref;
3044 let trait_def_id = trait_ref.def_id;
3045 let substs = trait_ref.substs;
3047 let trait_obligations = self.impl_or_trait_obligations(
3048 obligation.cause.clone(),
3049 obligation.recursion_depth,
3050 obligation.param_env,
3056 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3057 trait_def_id, trait_obligations
3060 VtableTraitAliasData { alias_def_id, substs: substs, nested: trait_obligations }
3064 fn confirm_generator_candidate(
3066 obligation: &TraitObligation<'tcx>,
3067 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3068 // Okay to skip binder because the substs on generator types never
3069 // touch bound regions, they just capture the in-scope
3070 // type/region parameters.
3071 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3072 let (generator_def_id, substs) = match self_ty.kind {
3073 ty::Generator(id, substs, _) => (id, substs),
3074 _ => bug!("closure candidate for non-closure {:?}", obligation),
3077 debug!("confirm_generator_candidate({:?},{:?},{:?})", obligation, generator_def_id, substs);
3079 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3080 let Normalized { value: trait_ref, mut obligations } = normalize_with_depth(
3082 obligation.param_env,
3083 obligation.cause.clone(),
3084 obligation.recursion_depth + 1,
3089 "confirm_generator_candidate(generator_def_id={:?}, \
3090 trait_ref={:?}, obligations={:?})",
3091 generator_def_id, trait_ref, obligations
3094 obligations.extend(self.confirm_poly_trait_refs(
3095 obligation.cause.clone(),
3096 obligation.param_env,
3097 obligation.predicate.to_poly_trait_ref(),
3101 Ok(VtableGeneratorData { generator_def_id, substs, nested: obligations })
3104 fn confirm_closure_candidate(
3106 obligation: &TraitObligation<'tcx>,
3107 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3108 debug!("confirm_closure_candidate({:?})", obligation);
3113 .fn_trait_kind(obligation.predicate.def_id())
3114 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3116 // Okay to skip binder because the substs on closure types never
3117 // touch bound regions, they just capture the in-scope
3118 // type/region parameters.
3119 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3120 let (closure_def_id, substs) = match self_ty.kind {
3121 ty::Closure(id, substs) => (id, substs),
3122 _ => bug!("closure candidate for non-closure {:?}", obligation),
3125 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3126 let Normalized { value: trait_ref, mut obligations } = normalize_with_depth(
3128 obligation.param_env,
3129 obligation.cause.clone(),
3130 obligation.recursion_depth + 1,
3135 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3136 closure_def_id, trait_ref, obligations
3139 obligations.extend(self.confirm_poly_trait_refs(
3140 obligation.cause.clone(),
3141 obligation.param_env,
3142 obligation.predicate.to_poly_trait_ref(),
3148 if !self.tcx().sess.opts.debugging_opts.chalk {
3149 obligations.push(Obligation::new(
3150 obligation.cause.clone(),
3151 obligation.param_env,
3152 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3156 Ok(VtableClosureData { closure_def_id, substs: substs, nested: obligations })
3159 /// In the case of closure types and fn pointers,
3160 /// we currently treat the input type parameters on the trait as
3161 /// outputs. This means that when we have a match we have only
3162 /// considered the self type, so we have to go back and make sure
3163 /// to relate the argument types too. This is kind of wrong, but
3164 /// since we control the full set of impls, also not that wrong,
3165 /// and it DOES yield better error messages (since we don't report
3166 /// errors as if there is no applicable impl, but rather report
3167 /// errors are about mismatched argument types.
3169 /// Here is an example. Imagine we have a closure expression
3170 /// and we desugared it so that the type of the expression is
3171 /// `Closure`, and `Closure` expects an int as argument. Then it
3172 /// is "as if" the compiler generated this impl:
3174 /// impl Fn(int) for Closure { ... }
3176 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3177 /// we have matched the self type `Closure`. At this point we'll
3178 /// compare the `int` to `usize` and generate an error.
3180 /// Note that this checking occurs *after* the impl has selected,
3181 /// because these output type parameters should not affect the
3182 /// selection of the impl. Therefore, if there is a mismatch, we
3183 /// report an error to the user.
3184 fn confirm_poly_trait_refs(
3186 obligation_cause: ObligationCause<'tcx>,
3187 obligation_param_env: ty::ParamEnv<'tcx>,
3188 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3189 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3190 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3191 let obligation_trait_ref = obligation_trait_ref.clone();
3193 .at(&obligation_cause, obligation_param_env)
3194 .sup(obligation_trait_ref, expected_trait_ref)
3195 .map(|InferOk { obligations, .. }| obligations)
3196 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3199 fn confirm_builtin_unsize_candidate(
3201 obligation: &TraitObligation<'tcx>,
3202 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3203 let tcx = self.tcx();
3205 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
3206 // regions here. See the comment there for more details.
3207 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3208 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
3209 let target = self.infcx.shallow_resolve(target);
3211 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})", source, target);
3213 let mut nested = vec![];
3214 match (&source.kind, &target.kind) {
3215 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3216 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3217 // See `assemble_candidates_for_unsizing` for more info.
3218 let existential_predicates = data_a.map_bound(|data_a| {
3221 .map(|x| ty::ExistentialPredicate::Trait(x))
3225 .projection_bounds()
3226 .map(|x| ty::ExistentialPredicate::Projection(x)),
3228 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
3229 tcx.mk_existential_predicates(iter)
3231 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
3233 // Require that the traits involved in this upcast are **equal**;
3234 // only the **lifetime bound** is changed.
3236 // FIXME: This condition is arguably too strong -- it would
3237 // suffice for the source trait to be a *subtype* of the target
3238 // trait. In particular, changing from something like
3239 // `for<'a, 'b> Foo<'a, 'b>` to `for<'a> Foo<'a, 'a>` should be
3240 // permitted. And, indeed, in the in commit
3241 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3242 // condition was loosened. However, when the leak check was
3243 // added back, using subtype here actually guides the coercion
3244 // code in such a way that it accepts `old-lub-glb-object.rs`.
3245 // This is probably a good thing, but I've modified this to `.eq`
3246 // because I want to continue rejecting that test (as we have
3247 // done for quite some time) before we are firmly comfortable
3248 // with what our behavior should be there. -nikomatsakis
3249 let InferOk { obligations, .. } = self
3251 .at(&obligation.cause, obligation.param_env)
3252 .eq(target, source_trait) // FIXME -- see below
3253 .map_err(|_| Unimplemented)?;
3254 nested.extend(obligations);
3256 // Register one obligation for 'a: 'b.
3257 let cause = ObligationCause::new(
3258 obligation.cause.span,
3259 obligation.cause.body_id,
3260 ObjectCastObligation(target),
3262 let outlives = ty::OutlivesPredicate(r_a, r_b);
3263 nested.push(Obligation::with_depth(
3265 obligation.recursion_depth + 1,
3266 obligation.param_env,
3267 ty::Binder::bind(outlives).to_predicate(),
3272 (_, &ty::Dynamic(ref data, r)) => {
3273 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
3274 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3275 return Err(TraitNotObjectSafe(did));
3278 let cause = ObligationCause::new(
3279 obligation.cause.span,
3280 obligation.cause.body_id,
3281 ObjectCastObligation(target),
3284 let predicate_to_obligation = |predicate| {
3285 Obligation::with_depth(
3287 obligation.recursion_depth + 1,
3288 obligation.param_env,
3293 // Create obligations:
3294 // - Casting `T` to `Trait`
3295 // - For all the various builtin bounds attached to the object cast. (In other
3296 // words, if the object type is `Foo + Send`, this would create an obligation for
3297 // the `Send` check.)
3298 // - Projection predicates
3300 data.iter().map(|predicate| {
3301 predicate_to_obligation(predicate.with_self_ty(tcx, source))
3305 // We can only make objects from sized types.
3306 let tr = ty::TraitRef::new(
3307 tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
3308 tcx.mk_substs_trait(source, &[]),
3310 nested.push(predicate_to_obligation(tr.to_predicate()));
3312 // If the type is `Foo + 'a`, ensure that the type
3313 // being cast to `Foo + 'a` outlives `'a`:
3314 let outlives = ty::OutlivesPredicate(source, r);
3315 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate()));
3318 // `[T; n]` -> `[T]`
3319 (&ty::Array(a, _), &ty::Slice(b)) => {
3320 let InferOk { obligations, .. } = self
3322 .at(&obligation.cause, obligation.param_env)
3324 .map_err(|_| Unimplemented)?;
3325 nested.extend(obligations);
3328 // `Struct<T>` -> `Struct<U>`
3329 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3331 def.all_fields().map(|field| tcx.type_of(field.did)).collect::<Vec<_>>();
3333 // The last field of the structure has to exist and contain type parameters.
3334 let field = if let Some(&field) = fields.last() {
3337 return Err(Unimplemented);
3339 let mut ty_params = GrowableBitSet::new_empty();
3340 let mut found = false;
3341 for ty in field.walk() {
3342 if let ty::Param(p) = ty.kind {
3343 ty_params.insert(p.index as usize);
3348 return Err(Unimplemented);
3351 // Replace type parameters used in unsizing with
3352 // Error and ensure they do not affect any other fields.
3353 // This could be checked after type collection for any struct
3354 // with a potentially unsized trailing field.
3355 let params = substs_a
3358 .map(|(i, &k)| if ty_params.contains(i) { tcx.types.err.into() } else { k });
3359 let substs = tcx.mk_substs(params);
3360 for &ty in fields.split_last().unwrap().1 {
3361 if ty.subst(tcx, substs).references_error() {
3362 return Err(Unimplemented);
3366 // Extract `Field<T>` and `Field<U>` from `Struct<T>` and `Struct<U>`.
3367 let inner_source = field.subst(tcx, substs_a);
3368 let inner_target = field.subst(tcx, substs_b);
3370 // Check that the source struct with the target's
3371 // unsized parameters is equal to the target.
3372 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3373 if ty_params.contains(i) { substs_b.type_at(i).into() } else { k }
3375 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3376 let InferOk { obligations, .. } = self
3378 .at(&obligation.cause, obligation.param_env)
3379 .eq(target, new_struct)
3380 .map_err(|_| Unimplemented)?;
3381 nested.extend(obligations);
3383 // Construct the nested `Field<T>: Unsize<Field<U>>` predicate.
3384 nested.push(tcx.predicate_for_trait_def(
3385 obligation.param_env,
3386 obligation.cause.clone(),
3387 obligation.predicate.def_id(),
3388 obligation.recursion_depth + 1,
3390 &[inner_target.into()],
3394 // `(.., T)` -> `(.., U)`
3395 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3396 assert_eq!(tys_a.len(), tys_b.len());
3398 // The last field of the tuple has to exist.
3399 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3402 return Err(Unimplemented);
3404 let &b_last = tys_b.last().unwrap();
3406 // Check that the source tuple with the target's
3407 // last element is equal to the target.
3408 let new_tuple = tcx.mk_tup(
3409 a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3411 let InferOk { obligations, .. } = self
3413 .at(&obligation.cause, obligation.param_env)
3414 .eq(target, new_tuple)
3415 .map_err(|_| Unimplemented)?;
3416 nested.extend(obligations);
3418 // Construct the nested `T: Unsize<U>` predicate.
3419 nested.push(tcx.predicate_for_trait_def(
3420 obligation.param_env,
3421 obligation.cause.clone(),
3422 obligation.predicate.def_id(),
3423 obligation.recursion_depth + 1,
3432 Ok(VtableBuiltinData { nested })
3435 ///////////////////////////////////////////////////////////////////////////
3438 // Matching is a common path used for both evaluation and
3439 // confirmation. It basically unifies types that appear in impls
3440 // and traits. This does affect the surrounding environment;
3441 // therefore, when used during evaluation, match routines must be
3442 // run inside of a `probe()` so that their side-effects are
3448 obligation: &TraitObligation<'tcx>,
3449 snapshot: &CombinedSnapshot<'_, 'tcx>,
3450 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3451 match self.match_impl(impl_def_id, obligation, snapshot) {
3452 Ok(substs) => substs,
3455 "Impl {:?} was matchable against {:?} but now is not",
3466 obligation: &TraitObligation<'tcx>,
3467 snapshot: &CombinedSnapshot<'_, 'tcx>,
3468 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3469 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3471 // Before we create the substitutions and everything, first
3472 // consider a "quick reject". This avoids creating more types
3473 // and so forth that we need to.
3474 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3478 let (skol_obligation, placeholder_map) =
3479 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
3480 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3482 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
3484 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3486 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
3487 project::normalize_with_depth(
3489 obligation.param_env,
3490 obligation.cause.clone(),
3491 obligation.recursion_depth + 1,
3496 "match_impl(impl_def_id={:?}, obligation={:?}, \
3497 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3498 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3501 let InferOk { obligations, .. } = self
3503 .at(&obligation.cause, obligation.param_env)
3504 .eq(skol_obligation_trait_ref, impl_trait_ref)
3505 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3506 nested_obligations.extend(obligations);
3508 if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3509 debug!("match_impl: failed leak check due to `{}`", e);
3513 if self.intercrate.is_none()
3514 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
3516 debug!("match_impl: reservation impls only apply in intercrate mode");
3520 debug!("match_impl: success impl_substs={:?}", impl_substs);
3521 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
3524 fn fast_reject_trait_refs(
3526 obligation: &TraitObligation<'_>,
3527 impl_trait_ref: &ty::TraitRef<'_>,
3529 // We can avoid creating type variables and doing the full
3530 // substitution if we find that any of the input types, when
3531 // simplified, do not match.
3533 obligation.predicate.skip_binder().input_types().zip(impl_trait_ref.input_types()).any(
3534 |(obligation_ty, impl_ty)| {
3535 let simplified_obligation_ty =
3536 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3537 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3539 simplified_obligation_ty.is_some()
3540 && simplified_impl_ty.is_some()
3541 && simplified_obligation_ty != simplified_impl_ty
3546 /// Normalize `where_clause_trait_ref` and try to match it against
3547 /// `obligation`. If successful, return any predicates that
3548 /// result from the normalization. Normalization is necessary
3549 /// because where-clauses are stored in the parameter environment
3551 fn match_where_clause_trait_ref(
3553 obligation: &TraitObligation<'tcx>,
3554 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3555 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3556 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3559 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3560 /// obligation is satisfied.
3561 fn match_poly_trait_ref(
3563 obligation: &TraitObligation<'tcx>,
3564 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3565 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3567 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3568 obligation, poly_trait_ref
3572 .at(&obligation.cause, obligation.param_env)
3573 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3574 .map(|InferOk { obligations, .. }| obligations)
3578 ///////////////////////////////////////////////////////////////////////////
3581 fn match_fresh_trait_refs(
3583 previous: &ty::PolyTraitRef<'tcx>,
3584 current: &ty::PolyTraitRef<'tcx>,
3585 param_env: ty::ParamEnv<'tcx>,
3587 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
3588 matcher.relate(previous, current).is_ok()
3593 previous_stack: TraitObligationStackList<'o, 'tcx>,
3594 obligation: &'o TraitObligation<'tcx>,
3595 ) -> TraitObligationStack<'o, 'tcx> {
3596 let fresh_trait_ref =
3597 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3599 let dfn = previous_stack.cache.next_dfn();
3600 let depth = previous_stack.depth() + 1;
3601 TraitObligationStack {
3604 reached_depth: Cell::new(depth),
3605 previous: previous_stack,
3611 fn closure_trait_ref_unnormalized(
3613 obligation: &TraitObligation<'tcx>,
3614 closure_def_id: DefId,
3615 substs: SubstsRef<'tcx>,
3616 ) -> ty::PolyTraitRef<'tcx> {
3618 "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3619 obligation, closure_def_id, substs,
3621 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3623 debug!("closure_trait_ref_unnormalized: closure_type = {:?}", closure_type);
3625 // (1) Feels icky to skip the binder here, but OTOH we know
3626 // that the self-type is an unboxed closure type and hence is
3627 // in fact unparameterized (or at least does not reference any
3628 // regions bound in the obligation). Still probably some
3629 // refactoring could make this nicer.
3631 .closure_trait_ref_and_return_type(
3632 obligation.predicate.def_id(),
3633 obligation.predicate.skip_binder().self_ty(), // (1)
3635 util::TupleArgumentsFlag::No,
3637 .map_bound(|(trait_ref, _)| trait_ref)
3640 fn generator_trait_ref_unnormalized(
3642 obligation: &TraitObligation<'tcx>,
3643 closure_def_id: DefId,
3644 substs: SubstsRef<'tcx>,
3645 ) -> ty::PolyTraitRef<'tcx> {
3646 let gen_sig = substs.as_generator().poly_sig(closure_def_id, self.tcx());
3648 // (1) Feels icky to skip the binder here, but OTOH we know
3649 // that the self-type is an generator type and hence is
3650 // in fact unparameterized (or at least does not reference any
3651 // regions bound in the obligation). Still probably some
3652 // refactoring could make this nicer.
3655 .generator_trait_ref_and_outputs(
3656 obligation.predicate.def_id(),
3657 obligation.predicate.skip_binder().self_ty(), // (1)
3660 .map_bound(|(trait_ref, ..)| trait_ref)
3663 /// Returns the obligations that are implied by instantiating an
3664 /// impl or trait. The obligations are substituted and fully
3665 /// normalized. This is used when confirming an impl or default
3667 fn impl_or_trait_obligations(
3669 cause: ObligationCause<'tcx>,
3670 recursion_depth: usize,
3671 param_env: ty::ParamEnv<'tcx>,
3672 def_id: DefId, // of impl or trait
3673 substs: SubstsRef<'tcx>, // for impl or trait
3674 ) -> Vec<PredicateObligation<'tcx>> {
3675 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3676 let tcx = self.tcx();
3678 // To allow for one-pass evaluation of the nested obligation,
3679 // each predicate must be preceded by the obligations required
3681 // for example, if we have:
3682 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
3683 // the impl will have the following predicates:
3684 // <V as Iterator>::Item = U,
3685 // U: Iterator, U: Sized,
3686 // V: Iterator, V: Sized,
3687 // <U as Iterator>::Item: Copy
3688 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3689 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3690 // `$1: Copy`, so we must ensure the obligations are emitted in
3692 let predicates = tcx.predicates_of(def_id);
3693 assert_eq!(predicates.parent, None);
3694 let mut predicates: Vec<_> = predicates
3697 .flat_map(|(predicate, _)| {
3698 let predicate = normalize_with_depth(
3703 &predicate.subst(tcx, substs),
3705 predicate.obligations.into_iter().chain(Some(Obligation {
3706 cause: cause.clone(),
3709 predicate: predicate.value,
3714 // We are performing deduplication here to avoid exponential blowups
3715 // (#38528) from happening, but the real cause of the duplication is
3716 // unknown. What we know is that the deduplication avoids exponential
3717 // amount of predicates being propagated when processing deeply nested
3720 // This code is hot enough that it's worth avoiding the allocation
3721 // required for the FxHashSet when possible. Special-casing lengths 0,
3722 // 1 and 2 covers roughly 75-80% of the cases.
3723 if predicates.len() <= 1 {
3724 // No possibility of duplicates.
3725 } else if predicates.len() == 2 {
3726 // Only two elements. Drop the second if they are equal.
3727 if predicates[0] == predicates[1] {
3728 predicates.truncate(1);
3731 // Three or more elements. Use a general deduplication process.
3732 let mut seen = FxHashSet::default();
3733 predicates.retain(|i| seen.insert(i.clone()));
3740 impl<'tcx> TraitObligation<'tcx> {
3741 #[allow(unused_comparisons)]
3742 pub fn derived_cause(
3744 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3745 ) -> ObligationCause<'tcx> {
3747 * Creates a cause for obligations that are derived from
3748 * `obligation` by a recursive search (e.g., for a builtin
3749 * bound, or eventually a `auto trait Foo`). If `obligation`
3750 * is itself a derived obligation, this is just a clone, but
3751 * otherwise we create a "derived obligation" cause so as to
3752 * keep track of the original root obligation for error
3756 let obligation = self;
3758 // NOTE(flaper87): As of now, it keeps track of the whole error
3759 // chain. Ideally, we should have a way to configure this either
3760 // by using -Z verbose or just a CLI argument.
3761 if obligation.recursion_depth >= 0 {
3762 let derived_cause = DerivedObligationCause {
3763 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3764 parent_code: Rc::new(obligation.cause.code.clone()),
3766 let derived_code = variant(derived_cause);
3767 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3769 obligation.cause.clone()
3774 impl<'tcx> SelectionCache<'tcx> {
3775 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3776 pub fn clear(&self) {
3777 *self.hashmap.borrow_mut() = Default::default();
3781 impl<'tcx> EvaluationCache<'tcx> {
3782 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3783 pub fn clear(&self) {
3784 *self.hashmap.borrow_mut() = Default::default();
3788 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
3789 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3790 TraitObligationStackList::with(self)
3793 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
3797 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3801 /// Indicates that attempting to evaluate this stack entry
3802 /// required accessing something from the stack at depth `reached_depth`.
3803 fn update_reached_depth(&self, reached_depth: usize) {
3805 self.depth > reached_depth,
3806 "invoked `update_reached_depth` with something under this stack: \
3807 self.depth={} reached_depth={}",
3811 debug!("update_reached_depth(reached_depth={})", reached_depth);
3813 while reached_depth < p.depth {
3814 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
3815 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
3816 p = p.previous.head.unwrap();
3821 /// The "provisional evaluation cache" is used to store intermediate cache results
3822 /// when solving auto traits. Auto traits are unusual in that they can support
3823 /// cycles. So, for example, a "proof tree" like this would be ok:
3825 /// - `Foo<T>: Send` :-
3826 /// - `Bar<T>: Send` :-
3827 /// - `Foo<T>: Send` -- cycle, but ok
3828 /// - `Baz<T>: Send`
3830 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
3831 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
3832 /// For non-auto traits, this cycle would be an error, but for auto traits (because
3833 /// they are coinductive) it is considered ok.
3835 /// However, there is a complication: at the point where we have
3836 /// "proven" `Bar<T>: Send`, we have in fact only proven it
3837 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
3838 /// *under the assumption* that `Foo<T>: Send`. But what if we later
3839 /// find out this assumption is wrong? Specifically, we could
3840 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
3841 /// `Bar<T>: Send` didn't turn out to be true.
3843 /// In Issue #60010, we found a bug in rustc where it would cache
3844 /// these intermediate results. This was fixed in #60444 by disabling
3845 /// *all* caching for things involved in a cycle -- in our example,
3846 /// that would mean we don't cache that `Bar<T>: Send`. But this led
3847 /// to large slowdowns.
3849 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
3850 /// first requires proving `Bar<T>: Send` (which is true:
3852 /// - `Foo<T>: Send` :-
3853 /// - `Bar<T>: Send` :-
3854 /// - `Foo<T>: Send` -- cycle, but ok
3855 /// - `Baz<T>: Send`
3856 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
3857 /// - `*const T: Send` -- but what if we later encounter an error?
3859 /// The *provisional evaluation cache* resolves this issue. It stores
3860 /// cache results that we've proven but which were involved in a cycle
3861 /// in some way. We track the minimal stack depth (i.e., the
3862 /// farthest from the top of the stack) that we are dependent on.
3863 /// The idea is that the cache results within are all valid -- so long as
3864 /// none of the nodes in between the current node and the node at that minimum
3865 /// depth result in an error (in which case the cached results are just thrown away).
3867 /// During evaluation, we consult this provisional cache and rely on
3868 /// it. Accessing a cached value is considered equivalent to accessing
3869 /// a result at `reached_depth`, so it marks the *current* solution as
3870 /// provisional as well. If an error is encountered, we toss out any
3871 /// provisional results added from the subtree that encountered the
3872 /// error. When we pop the node at `reached_depth` from the stack, we
3873 /// can commit all the things that remain in the provisional cache.
3874 struct ProvisionalEvaluationCache<'tcx> {
3875 /// next "depth first number" to issue -- just a counter
3878 /// Stores the "coldest" depth (bottom of stack) reached by any of
3879 /// the evaluation entries. The idea here is that all things in the provisional
3880 /// cache are always dependent on *something* that is colder in the stack:
3881 /// therefore, if we add a new entry that is dependent on something *colder still*,
3882 /// we have to modify the depth for all entries at once.
3886 /// Imagine we have a stack `A B C D E` (with `E` being the top of
3887 /// the stack). We cache something with depth 2, which means that
3888 /// it was dependent on C. Then we pop E but go on and process a
3889 /// new node F: A B C D F. Now F adds something to the cache with
3890 /// depth 1, meaning it is dependent on B. Our original cache
3891 /// entry is also dependent on B, because there is a path from E
3892 /// to C and then from C to F and from F to B.
3893 reached_depth: Cell<usize>,
3895 /// Map from cache key to the provisionally evaluated thing.
3896 /// The cache entries contain the result but also the DFN in which they
3897 /// were added. The DFN is used to clear out values on failure.
3899 /// Imagine we have a stack like:
3901 /// - `A B C` and we add a cache for the result of C (DFN 2)
3902 /// - Then we have a stack `A B D` where `D` has DFN 3
3903 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
3904 /// - `E` generates various cache entries which have cyclic dependices on `B`
3905 /// - `A B D E F` and so forth
3906 /// - the DFN of `F` for example would be 5
3907 /// - then we determine that `E` is in error -- we will then clear
3908 /// all cache values whose DFN is >= 4 -- in this case, that
3909 /// means the cached value for `F`.
3910 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
3913 /// A cache value for the provisional cache: contains the depth-first
3914 /// number (DFN) and result.
3915 #[derive(Copy, Clone, Debug)]
3916 struct ProvisionalEvaluation {
3918 result: EvaluationResult,
3921 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
3922 fn default() -> Self {
3925 reached_depth: Cell::new(std::usize::MAX),
3926 map: Default::default(),
3931 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
3932 /// Get the next DFN in sequence (basically a counter).
3933 fn next_dfn(&self) -> usize {
3934 let result = self.dfn.get();
3935 self.dfn.set(result + 1);
3939 /// Check the provisional cache for any result for
3940 /// `fresh_trait_ref`. If there is a hit, then you must consider
3941 /// it an access to the stack slots at depth
3942 /// `self.current_reached_depth()` and above.
3943 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
3945 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
3947 self.map.borrow().get(&fresh_trait_ref),
3948 self.reached_depth.get(),
3950 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
3953 /// Current value of the `reached_depth` counter -- all the
3954 /// provisional cache entries are dependent on the item at this
3956 fn current_reached_depth(&self) -> usize {
3957 self.reached_depth.get()
3960 /// Insert a provisional result into the cache. The result came
3961 /// from the node with the given DFN. It accessed a minimum depth
3962 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
3963 /// and resulted in `result`.
3964 fn insert_provisional(
3967 reached_depth: usize,
3968 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
3969 result: EvaluationResult,
3972 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
3973 from_dfn, reached_depth, fresh_trait_ref, result,
3975 let r_d = self.reached_depth.get();
3976 self.reached_depth.set(r_d.min(reached_depth));
3978 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
3980 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
3983 /// Invoked when the node with dfn `dfn` does not get a successful
3984 /// result. This will clear out any provisional cache entries
3985 /// that were added since `dfn` was created. This is because the
3986 /// provisional entries are things which must assume that the
3987 /// things on the stack at the time of their creation succeeded --
3988 /// since the failing node is presently at the top of the stack,
3989 /// these provisional entries must either depend on it or some
3991 fn on_failure(&self, dfn: usize) {
3992 debug!("on_failure(dfn={:?})", dfn,);
3993 self.map.borrow_mut().retain(|key, eval| {
3994 if !eval.from_dfn >= dfn {
3995 debug!("on_failure: removing {:?}", key);
4003 /// Invoked when the node at depth `depth` completed without
4004 /// depending on anything higher in the stack (if that completion
4005 /// was a failure, then `on_failure` should have been invoked
4006 /// already). The callback `op` will be invoked for each
4007 /// provisional entry that we can now confirm.
4011 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
4013 debug!("on_completion(depth={}, reached_depth={})", depth, self.reached_depth.get(),);
4015 if self.reached_depth.get() < depth {
4016 debug!("on_completion: did not yet reach depth to complete");
4020 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
4021 debug!("on_completion: fresh_trait_ref={:?} eval={:?}", fresh_trait_ref, eval,);
4023 op(fresh_trait_ref, eval.result);
4026 self.reached_depth.set(std::usize::MAX);
4030 #[derive(Copy, Clone)]
4031 struct TraitObligationStackList<'o, 'tcx> {
4032 cache: &'o ProvisionalEvaluationCache<'tcx>,
4033 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
4036 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
4037 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4038 TraitObligationStackList { cache, head: None }
4041 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4042 TraitObligationStackList { cache: r.cache(), head: Some(r) }
4045 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4049 fn depth(&self) -> usize {
4050 if let Some(head) = self.head { head.depth } else { 0 }
4054 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
4055 type Item = &'o TraitObligationStack<'o, 'tcx>;
4057 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4068 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
4069 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4070 write!(f, "TraitObligationStack({:?})", self.obligation)
4074 #[derive(Clone, Eq, PartialEq)]
4075 pub struct WithDepNode<T> {
4076 dep_node: DepNodeIndex,
4080 impl<T: Clone> WithDepNode<T> {
4081 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
4082 WithDepNode { dep_node, cached_value }
4085 pub fn get(&self, tcx: TyCtxt<'_>) -> T {
4086 tcx.dep_graph.read_index(self.dep_node);
4087 self.cached_value.clone()