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::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
16 use super::DerivedObligationCause;
18 use super::SelectionResult;
19 use super::TraitNotObjectSafe;
20 use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
21 use super::{IntercrateMode, TraitQueryMode};
22 use super::{ObjectCastObligation, Obligation};
23 use super::{ObligationCause, PredicateObligation, TraitObligation};
24 use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
26 VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
27 VtableObject, VtableParam, VtableTraitAlias,
30 VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
31 VtableGeneratorData, VtableImplData, VtableObjectData, VtableTraitAliasData,
34 use crate::dep_graph::{DepKind, DepNodeIndex};
35 use crate::infer::{CombinedSnapshot, InferCtxt, InferOk, PlaceholderMap, TypeFreshener};
36 use crate::middle::lang_items;
37 use crate::ty::fast_reject;
38 use crate::ty::relate::TypeRelation;
39 use crate::ty::subst::{Subst, SubstsRef};
40 use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
41 use rustc_hir::def_id::DefId;
43 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
44 use rustc_data_structures::sync::Lock;
46 use rustc_index::bit_set::GrowableBitSet;
47 use rustc_span::symbol::sym;
48 use rustc_target::spec::abi::Abi;
49 use std::cell::{Cell, RefCell};
51 use std::fmt::{self, Display};
56 pub struct SelectionContext<'cx, 'tcx> {
57 infcx: &'cx InferCtxt<'cx, 'tcx>,
59 /// Freshener used specifically for entries on the obligation
60 /// stack. This ensures that all entries on the stack at one time
61 /// will have the same set of placeholder entries, which is
62 /// important for checking for trait bounds that recursively
63 /// require themselves.
64 freshener: TypeFreshener<'cx, 'tcx>,
66 /// If `true`, indicates that the evaluation should be conservative
67 /// and consider the possibility of types outside this crate.
68 /// This comes up primarily when resolving ambiguity. Imagine
69 /// there is some trait reference `$0: Bar` where `$0` is an
70 /// inference variable. If `intercrate` is true, then we can never
71 /// say for sure that this reference is not implemented, even if
72 /// there are *no impls at all for `Bar`*, because `$0` could be
73 /// bound to some type that in a downstream crate that implements
74 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
75 /// though, we set this to false, because we are only interested
76 /// in types that the user could actually have written --- in
77 /// other words, we consider `$0: Bar` to be unimplemented if
78 /// there is no type that the user could *actually name* that
79 /// would satisfy it. This avoids crippling inference, basically.
80 intercrate: Option<IntercrateMode>,
82 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
84 /// Controls whether or not to filter out negative impls when selecting.
85 /// This is used in librustdoc to distinguish between the lack of an impl
86 /// and a negative impl
87 allow_negative_impls: bool,
89 /// The mode that trait queries run in, which informs our error handling
90 /// policy. In essence, canonicalized queries need their errors propagated
91 /// rather than immediately reported because we do not have accurate spans.
92 query_mode: TraitQueryMode,
95 #[derive(Clone, Debug)]
96 pub enum IntercrateAmbiguityCause {
97 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
98 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
99 ReservationImpl { message: String },
102 impl IntercrateAmbiguityCause {
103 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
104 /// See #23980 for details.
105 pub fn add_intercrate_ambiguity_hint(&self, err: &mut rustc_errors::DiagnosticBuilder<'_>) {
106 err.note(&self.intercrate_ambiguity_hint());
109 pub fn intercrate_ambiguity_hint(&self) -> String {
111 &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
112 let self_desc = if let &Some(ref ty) = self_desc {
113 format!(" for type `{}`", ty)
117 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
119 &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
120 let self_desc = if let &Some(ref ty) = self_desc {
121 format!(" for type `{}`", ty)
126 "upstream crates may add a new impl of trait `{}`{} \
128 trait_desc, self_desc
131 &IntercrateAmbiguityCause::ReservationImpl { ref message } => message.clone(),
136 // A stack that walks back up the stack frame.
137 struct TraitObligationStack<'prev, 'tcx> {
138 obligation: &'prev TraitObligation<'tcx>,
140 /// The trait ref from `obligation` but "freshened" with the
141 /// selection-context's freshener. Used to check for recursion.
142 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
144 /// Starts out equal to `depth` -- if, during evaluation, we
145 /// encounter a cycle, then we will set this flag to the minimum
146 /// depth of that cycle for all participants in the cycle. These
147 /// participants will then forego caching their results. This is
148 /// not the most efficient solution, but it addresses #60010. The
149 /// problem we are trying to prevent:
151 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
152 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
153 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
155 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
156 /// is `EvaluatedToOk`; this is because they were only considered
157 /// ok on the premise that if `A: AutoTrait` held, but we indeed
158 /// encountered a problem (later on) with `A: AutoTrait. So we
159 /// currently set a flag on the stack node for `B: AutoTrait` (as
160 /// well as the second instance of `A: AutoTrait`) to suppress
163 /// This is a simple, targeted fix. A more-performant fix requires
164 /// deeper changes, but would permit more caching: we could
165 /// basically defer caching until we have fully evaluated the
166 /// tree, and then cache the entire tree at once. In any case, the
167 /// performance impact here shouldn't be so horrible: every time
168 /// this is hit, we do cache at least one trait, so we only
169 /// evaluate each member of a cycle up to N times, where N is the
170 /// length of the cycle. This means the performance impact is
171 /// bounded and we shouldn't have any terrible worst-cases.
172 reached_depth: Cell<usize>,
174 previous: TraitObligationStackList<'prev, 'tcx>,
176 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
179 /// The depth-first number of this node in the search graph -- a
180 /// pre-order index. Basically, a freshly incremented counter.
184 #[derive(Clone, Default)]
185 pub struct SelectionCache<'tcx> {
188 ty::ParamEnvAnd<'tcx, ty::TraitRef<'tcx>>,
189 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>,
194 /// The selection process begins by considering all impls, where
195 /// clauses, and so forth that might resolve an obligation. Sometimes
196 /// we'll be able to say definitively that (e.g.) an impl does not
197 /// apply to the obligation: perhaps it is defined for `usize` but the
198 /// obligation is for `int`. In that case, we drop the impl out of the
199 /// list. But the other cases are considered *candidates*.
201 /// For selection to succeed, there must be exactly one matching
202 /// candidate. If the obligation is fully known, this is guaranteed
203 /// by coherence. However, if the obligation contains type parameters
204 /// or variables, there may be multiple such impls.
206 /// It is not a real problem if multiple matching impls exist because
207 /// of type variables - it just means the obligation isn't sufficiently
208 /// elaborated. In that case we report an ambiguity, and the caller can
209 /// try again after more type information has been gathered or report a
210 /// "type annotations needed" error.
212 /// However, with type parameters, this can be a real problem - type
213 /// parameters don't unify with regular types, but they *can* unify
214 /// with variables from blanket impls, and (unless we know its bounds
215 /// will always be satisfied) picking the blanket impl will be wrong
216 /// for at least *some* substitutions. To make this concrete, if we have
218 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
219 /// impl<T: fmt::Debug> AsDebug for T {
221 /// fn debug(self) -> fmt::Debug { self }
223 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
225 /// we can't just use the impl to resolve the `<T as AsDebug>` obligation
226 /// -- a type from another crate (that doesn't implement `fmt::Debug`) could
227 /// implement `AsDebug`.
229 /// Because where-clauses match the type exactly, multiple clauses can
230 /// only match if there are unresolved variables, and we can mostly just
231 /// report this ambiguity in that case. This is still a problem - we can't
232 /// *do anything* with ambiguities that involve only regions. This is issue
235 /// If a single where-clause matches and there are no inference
236 /// variables left, then it definitely matches and we can just select
239 /// In fact, we even select the where-clause when the obligation contains
240 /// inference variables. The can lead to inference making "leaps of logic",
241 /// for example in this situation:
243 /// pub trait Foo<T> { fn foo(&self) -> T; }
244 /// impl<T> Foo<()> for T { fn foo(&self) { } }
245 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
247 /// pub fn foo<T>(t: T) where T: Foo<bool> {
248 /// println!("{:?}", <T as Foo<_>>::foo(&t));
250 /// fn main() { foo(false); }
252 /// Here the obligation `<T as Foo<$0>>` can be matched by both the blanket
253 /// impl and the where-clause. We select the where-clause and unify `$0=bool`,
254 /// so the program prints "false". However, if the where-clause is omitted,
255 /// the blanket impl is selected, we unify `$0=()`, and the program prints
258 /// Exactly the same issues apply to projection and object candidates, except
259 /// that we can have both a projection candidate and a where-clause candidate
260 /// for the same obligation. In that case either would do (except that
261 /// different "leaps of logic" would occur if inference variables are
262 /// present), and we just pick the where-clause. This is, for example,
263 /// required for associated types to work in default impls, as the bounds
264 /// are visible both as projection bounds and as where-clauses from the
265 /// parameter environment.
266 #[derive(PartialEq, Eq, Debug, Clone, TypeFoldable)]
267 enum SelectionCandidate<'tcx> {
269 /// `false` if there are no *further* obligations.
272 ParamCandidate(ty::PolyTraitRef<'tcx>),
273 ImplCandidate(DefId),
274 AutoImplCandidate(DefId),
276 /// This is a trait matching with a projected type as `Self`, and
277 /// we found an applicable bound in the trait definition.
280 /// Implementation of a `Fn`-family trait by one of the anonymous types
281 /// generated for a `||` expression.
284 /// Implementation of a `Generator` trait by one of the anonymous types
285 /// generated for a generator.
288 /// Implementation of a `Fn`-family trait by one of the anonymous
289 /// types generated for a fn pointer type (e.g., `fn(int) -> int`)
292 TraitAliasCandidate(DefId),
296 BuiltinObjectCandidate,
298 BuiltinUnsizeCandidate,
301 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
302 type Lifted = SelectionCandidate<'tcx>;
303 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
305 BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
306 ImplCandidate(def_id) => ImplCandidate(def_id),
307 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
308 ProjectionCandidate => ProjectionCandidate,
309 ClosureCandidate => ClosureCandidate,
310 GeneratorCandidate => GeneratorCandidate,
311 FnPointerCandidate => FnPointerCandidate,
312 TraitAliasCandidate(def_id) => TraitAliasCandidate(def_id),
313 ObjectCandidate => ObjectCandidate,
314 BuiltinObjectCandidate => BuiltinObjectCandidate,
315 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
317 ParamCandidate(ref trait_ref) => {
318 return tcx.lift(trait_ref).map(ParamCandidate);
324 struct SelectionCandidateSet<'tcx> {
325 // A list of candidates that definitely apply to the current
326 // obligation (meaning: types unify).
327 vec: Vec<SelectionCandidate<'tcx>>,
329 // If `true`, then there were candidates that might or might
330 // not have applied, but we couldn't tell. This occurs when some
331 // of the input types are type variables, in which case there are
332 // various "builtin" rules that might or might not trigger.
336 #[derive(PartialEq, Eq, Debug, Clone)]
337 struct EvaluatedCandidate<'tcx> {
338 candidate: SelectionCandidate<'tcx>,
339 evaluation: EvaluationResult,
342 /// When does the builtin impl for `T: Trait` apply?
343 enum BuiltinImplConditions<'tcx> {
344 /// The impl is conditional on `T1, T2, ...: Trait`.
345 Where(ty::Binder<Vec<Ty<'tcx>>>),
346 /// There is no built-in impl. There may be some other
347 /// candidate (a where-clause or user-defined impl).
349 /// It is unknown whether there is an impl.
353 /// The result of trait evaluation. The order is important
354 /// here as the evaluation of a list is the maximum of the
357 /// The evaluation results are ordered:
358 /// - `EvaluatedToOk` implies `EvaluatedToOkModuloRegions`
359 /// implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
360 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
361 /// - the "union" of evaluation results is equal to their maximum -
362 /// all the "potential success" candidates can potentially succeed,
363 /// so they are noops when unioned with a definite error, and within
364 /// the categories it's easy to see that the unions are correct.
365 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, HashStable)]
366 pub enum EvaluationResult {
367 /// Evaluation successful.
369 /// Evaluation successful, but there were unevaluated region obligations.
370 EvaluatedToOkModuloRegions,
371 /// Evaluation is known to be ambiguous -- it *might* hold for some
372 /// assignment of inference variables, but it might not.
374 /// While this has the same meaning as `EvaluatedToUnknown` -- we can't
375 /// know whether this obligation holds or not -- it is the result we
376 /// would get with an empty stack, and therefore is cacheable.
378 /// Evaluation failed because of recursion involving inference
379 /// variables. We are somewhat imprecise there, so we don't actually
380 /// know the real result.
382 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
384 /// Evaluation failed because we encountered an obligation we are already
385 /// trying to prove on this branch.
387 /// We know this branch can't be a part of a minimal proof-tree for
388 /// the "root" of our cycle, because then we could cut out the recursion
389 /// and maintain a valid proof tree. However, this does not mean
390 /// that all the obligations on this branch do not hold -- it's possible
391 /// that we entered this branch "speculatively", and that there
392 /// might be some other way to prove this obligation that does not
393 /// go through this cycle -- so we can't cache this as a failure.
395 /// For example, suppose we have this:
397 /// ```rust,ignore (pseudo-Rust)
398 /// pub trait Trait { fn xyz(); }
399 /// // This impl is "useless", but we can still have
400 /// // an `impl Trait for SomeUnsizedType` somewhere.
401 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
403 /// pub fn foo<T: Trait + ?Sized>() {
404 /// <T as Trait>::xyz();
408 /// When checking `foo`, we have to prove `T: Trait`. This basically
409 /// translates into this:
412 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
415 /// When we try to prove it, we first go the first option, which
416 /// recurses. This shows us that the impl is "useless" -- it won't
417 /// tell us that `T: Trait` unless it already implemented `Trait`
418 /// by some other means. However, that does not prevent `T: Trait`
419 /// does not hold, because of the bound (which can indeed be satisfied
420 /// by `SomeUnsizedType` from another crate).
422 // FIXME: when an `EvaluatedToRecur` goes past its parent root, we
423 // ought to convert it to an `EvaluatedToErr`, because we know
424 // there definitely isn't a proof tree for that obligation. Not
425 // doing so is still sound -- there isn't any proof tree, so the
426 // branch still can't be a part of a minimal one -- but does not re-enable caching.
428 /// Evaluation failed.
432 impl EvaluationResult {
433 /// Returns `true` if this evaluation result is known to apply, even
434 /// considering outlives constraints.
435 pub fn must_apply_considering_regions(self) -> bool {
436 self == EvaluatedToOk
439 /// Returns `true` if this evaluation result is known to apply, ignoring
440 /// outlives constraints.
441 pub fn must_apply_modulo_regions(self) -> bool {
442 self <= EvaluatedToOkModuloRegions
445 pub fn may_apply(self) -> bool {
447 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToUnknown => {
451 EvaluatedToErr | EvaluatedToRecur => false,
455 fn is_stack_dependent(self) -> bool {
457 EvaluatedToUnknown | EvaluatedToRecur => true,
459 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToErr => false,
464 /// Indicates that trait evaluation caused overflow.
465 #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable)]
466 pub struct OverflowError;
468 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
469 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
470 SelectionError::Overflow
474 #[derive(Clone, Default)]
475 pub struct EvaluationCache<'tcx> {
477 FxHashMap<ty::ParamEnvAnd<'tcx, ty::PolyTraitRef<'tcx>>, WithDepNode<EvaluationResult>>,
481 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
482 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
485 freshener: infcx.freshener(),
487 intercrate_ambiguity_causes: None,
488 allow_negative_impls: false,
489 query_mode: TraitQueryMode::Standard,
494 infcx: &'cx InferCtxt<'cx, 'tcx>,
495 mode: IntercrateMode,
496 ) -> SelectionContext<'cx, 'tcx> {
497 debug!("intercrate({:?})", mode);
500 freshener: infcx.freshener(),
501 intercrate: Some(mode),
502 intercrate_ambiguity_causes: None,
503 allow_negative_impls: false,
504 query_mode: TraitQueryMode::Standard,
508 pub fn with_negative(
509 infcx: &'cx InferCtxt<'cx, 'tcx>,
510 allow_negative_impls: bool,
511 ) -> SelectionContext<'cx, 'tcx> {
512 debug!("with_negative({:?})", allow_negative_impls);
515 freshener: infcx.freshener(),
517 intercrate_ambiguity_causes: None,
518 allow_negative_impls,
519 query_mode: TraitQueryMode::Standard,
523 pub fn with_query_mode(
524 infcx: &'cx InferCtxt<'cx, 'tcx>,
525 query_mode: TraitQueryMode,
526 ) -> SelectionContext<'cx, 'tcx> {
527 debug!("with_query_mode({:?})", query_mode);
530 freshener: infcx.freshener(),
532 intercrate_ambiguity_causes: None,
533 allow_negative_impls: false,
538 /// Enables tracking of intercrate ambiguity causes. These are
539 /// used in coherence to give improved diagnostics. We don't do
540 /// this until we detect a coherence error because it can lead to
541 /// false overflow results (#47139) and because it costs
542 /// computation time.
543 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
544 assert!(self.intercrate.is_some());
545 assert!(self.intercrate_ambiguity_causes.is_none());
546 self.intercrate_ambiguity_causes = Some(vec![]);
547 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
550 /// Gets the intercrate ambiguity causes collected since tracking
551 /// was enabled and disables tracking at the same time. If
552 /// tracking is not enabled, just returns an empty vector.
553 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
554 assert!(self.intercrate.is_some());
555 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
558 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
562 pub fn tcx(&self) -> TyCtxt<'tcx> {
566 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
570 ///////////////////////////////////////////////////////////////////////////
573 // The selection phase tries to identify *how* an obligation will
574 // be resolved. For example, it will identify which impl or
575 // parameter bound is to be used. The process can be inconclusive
576 // if the self type in the obligation is not fully inferred. Selection
577 // can result in an error in one of two ways:
579 // 1. If no applicable impl or parameter bound can be found.
580 // 2. If the output type parameters in the obligation do not match
581 // those specified by the impl/bound. For example, if the obligation
582 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
583 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
585 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
586 /// type environment by performing unification.
589 obligation: &TraitObligation<'tcx>,
590 ) -> SelectionResult<'tcx, Selection<'tcx>> {
591 debug!("select({:?})", obligation);
592 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
594 let pec = &ProvisionalEvaluationCache::default();
595 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
597 let candidate = match self.candidate_from_obligation(&stack) {
598 Err(SelectionError::Overflow) => {
599 // In standard mode, overflow must have been caught and reported
601 assert!(self.query_mode == TraitQueryMode::Canonical);
602 return Err(SelectionError::Overflow);
610 Ok(Some(candidate)) => candidate,
613 match self.confirm_candidate(obligation, candidate) {
614 Err(SelectionError::Overflow) => {
615 assert!(self.query_mode == TraitQueryMode::Canonical);
616 Err(SelectionError::Overflow)
619 Ok(candidate) => Ok(Some(candidate)),
623 ///////////////////////////////////////////////////////////////////////////
626 // Tests whether an obligation can be selected or whether an impl
627 // can be applied to particular types. It skips the "confirmation"
628 // step and hence completely ignores output type parameters.
630 // The result is "true" if the obligation *may* hold and "false" if
631 // we can be sure it does not.
633 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
634 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
635 debug!("predicate_may_hold_fatal({:?})", obligation);
637 // This fatal query is a stopgap that should only be used in standard mode,
638 // where we do not expect overflow to be propagated.
639 assert!(self.query_mode == TraitQueryMode::Standard);
641 self.evaluate_root_obligation(obligation)
642 .expect("Overflow should be caught earlier in standard query mode")
646 /// Evaluates whether the obligation `obligation` can be satisfied
647 /// and returns an `EvaluationResult`. This is meant for the
649 pub fn evaluate_root_obligation(
651 obligation: &PredicateObligation<'tcx>,
652 ) -> Result<EvaluationResult, OverflowError> {
653 self.evaluation_probe(|this| {
654 this.evaluate_predicate_recursively(
655 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
663 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
664 ) -> Result<EvaluationResult, OverflowError> {
665 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
666 let result = op(self)?;
667 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
669 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
674 /// Evaluates the predicates in `predicates` recursively. Note that
675 /// this applies projections in the predicates, and therefore
676 /// is run within an inference probe.
677 fn evaluate_predicates_recursively<'o, I>(
679 stack: TraitObligationStackList<'o, 'tcx>,
681 ) -> Result<EvaluationResult, OverflowError>
683 I: IntoIterator<Item = PredicateObligation<'tcx>>,
685 let mut result = EvaluatedToOk;
686 for obligation in predicates {
687 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
688 debug!("evaluate_predicate_recursively({:?}) = {:?}", obligation, eval);
689 if let EvaluatedToErr = eval {
690 // fast-path - EvaluatedToErr is the top of the lattice,
691 // so we don't need to look on the other predicates.
692 return Ok(EvaluatedToErr);
694 result = cmp::max(result, eval);
700 fn evaluate_predicate_recursively<'o>(
702 previous_stack: TraitObligationStackList<'o, 'tcx>,
703 obligation: PredicateObligation<'tcx>,
704 ) -> Result<EvaluationResult, OverflowError> {
706 "evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
707 previous_stack.head(),
711 // `previous_stack` stores a `TraitObligatiom`, while `obligation` is
712 // a `PredicateObligation`. These are distinct types, so we can't
713 // use any `Option` combinator method that would force them to be
715 match previous_stack.head() {
716 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
717 None => self.check_recursion_limit(&obligation, &obligation)?,
720 match obligation.predicate {
721 ty::Predicate::Trait(ref t) => {
722 debug_assert!(!t.has_escaping_bound_vars());
723 let obligation = obligation.with(t.clone());
724 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
727 ty::Predicate::Subtype(ref p) => {
728 // Does this code ever run?
729 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
730 Some(Ok(InferOk { mut obligations, .. })) => {
731 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
732 self.evaluate_predicates_recursively(
734 obligations.into_iter(),
737 Some(Err(_)) => Ok(EvaluatedToErr),
738 None => Ok(EvaluatedToAmbig),
742 ty::Predicate::WellFormed(ty) => match wf::obligations(
744 obligation.param_env,
745 obligation.cause.body_id,
747 obligation.cause.span,
749 Some(mut obligations) => {
750 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
751 self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
753 None => Ok(EvaluatedToAmbig),
756 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
757 // We do not consider region relationships when evaluating trait matches.
758 Ok(EvaluatedToOkModuloRegions)
761 ty::Predicate::ObjectSafe(trait_def_id) => {
762 if self.tcx().is_object_safe(trait_def_id) {
769 ty::Predicate::Projection(ref data) => {
770 let project_obligation = obligation.with(data.clone());
771 match project::poly_project_and_unify_type(self, &project_obligation) {
772 Ok(Some(mut subobligations)) => {
773 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
774 let result = self.evaluate_predicates_recursively(
776 subobligations.into_iter(),
779 ProjectionCacheKey::from_poly_projection_predicate(self, data)
781 self.infcx.projection_cache.borrow_mut().complete(key);
785 Ok(None) => Ok(EvaluatedToAmbig),
786 Err(_) => Ok(EvaluatedToErr),
790 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
791 match self.infcx.closure_kind(closure_def_id, closure_substs) {
792 Some(closure_kind) => {
793 if closure_kind.extends(kind) {
799 None => Ok(EvaluatedToAmbig),
803 ty::Predicate::ConstEvaluatable(def_id, substs) => {
804 if !(obligation.param_env, substs).has_local_value() {
805 match self.tcx().const_eval_resolve(
806 obligation.param_env,
812 Ok(_) => Ok(EvaluatedToOk),
813 Err(_) => Ok(EvaluatedToErr),
816 // Inference variables still left in param_env or substs.
823 fn evaluate_trait_predicate_recursively<'o>(
825 previous_stack: TraitObligationStackList<'o, 'tcx>,
826 mut obligation: TraitObligation<'tcx>,
827 ) -> Result<EvaluationResult, OverflowError> {
828 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
830 if self.intercrate.is_none()
831 && obligation.is_global()
832 && obligation.param_env.caller_bounds.iter().all(|bound| bound.needs_subst())
834 // If a param env has no global bounds, global obligations do not
835 // depend on its particular value in order to work, so we can clear
836 // out the param env and get better caching.
837 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
838 obligation.param_env = obligation.param_env.without_caller_bounds();
841 let stack = self.push_stack(previous_stack, &obligation);
842 let fresh_trait_ref = stack.fresh_trait_ref;
843 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
844 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
848 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
849 debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
850 stack.update_reached_depth(stack.cache().current_reached_depth());
854 // Check if this is a match for something already on the
855 // stack. If so, we don't want to insert the result into the
856 // main cache (it is cycle dependent) nor the provisional
857 // cache (which is meant for things that have completed but
858 // for a "backedge" -- this result *is* the backedge).
859 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
860 return Ok(cycle_result);
863 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
864 let result = result?;
866 if !result.must_apply_modulo_regions() {
867 stack.cache().on_failure(stack.dfn);
870 let reached_depth = stack.reached_depth.get();
871 if reached_depth >= stack.depth {
872 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
873 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
875 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
876 self.insert_evaluation_cache(
877 obligation.param_env,
880 provisional_result.max(result),
884 debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
886 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
887 is a cycle participant (at depth {}, reached depth {})",
888 fresh_trait_ref, stack.depth, reached_depth,
891 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
897 /// If there is any previous entry on the stack that precisely
898 /// matches this obligation, then we can assume that the
899 /// obligation is satisfied for now (still all other conditions
900 /// must be met of course). One obvious case this comes up is
901 /// marker traits like `Send`. Think of a linked list:
903 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
905 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
906 /// `Option<Box<List<T>>>` is `Send`, and in turn
907 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
910 /// Note that we do this comparison using the `fresh_trait_ref`
911 /// fields. Because these have all been freshened using
912 /// `self.freshener`, we can be sure that (a) this will not
913 /// affect the inferencer state and (b) that if we see two
914 /// fresh regions with the same index, they refer to the same
915 /// unbound type variable.
916 fn check_evaluation_cycle(
918 stack: &TraitObligationStack<'_, 'tcx>,
919 ) -> Option<EvaluationResult> {
920 if let Some(cycle_depth) = stack
922 .skip(1) // Skip top-most frame.
924 stack.obligation.param_env == prev.obligation.param_env
925 && stack.fresh_trait_ref == prev.fresh_trait_ref
927 .map(|stack| stack.depth)
930 "evaluate_stack({:?}) --> recursive at depth {}",
931 stack.fresh_trait_ref, cycle_depth,
934 // If we have a stack like `A B C D E A`, where the top of
935 // the stack is the final `A`, then this will iterate over
936 // `A, E, D, C, B` -- i.e., all the participants apart
937 // from the cycle head. We mark them as participating in a
938 // cycle. This suppresses caching for those nodes. See
939 // `in_cycle` field for more details.
940 stack.update_reached_depth(cycle_depth);
942 // Subtle: when checking for a coinductive cycle, we do
943 // not compare using the "freshened trait refs" (which
944 // have erased regions) but rather the fully explicit
945 // trait refs. This is important because it's only a cycle
946 // if the regions match exactly.
947 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
948 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
949 if self.coinductive_match(cycle) {
950 debug!("evaluate_stack({:?}) --> recursive, coinductive", stack.fresh_trait_ref);
953 debug!("evaluate_stack({:?}) --> recursive, inductive", stack.fresh_trait_ref);
954 Some(EvaluatedToRecur)
961 fn evaluate_stack<'o>(
963 stack: &TraitObligationStack<'o, 'tcx>,
964 ) -> Result<EvaluationResult, OverflowError> {
965 // In intercrate mode, whenever any of the types are unbound,
966 // there can always be an impl. Even if there are no impls in
967 // this crate, perhaps the type would be unified with
968 // something from another crate that does provide an impl.
970 // In intra mode, we must still be conservative. The reason is
971 // that we want to avoid cycles. Imagine an impl like:
973 // impl<T:Eq> Eq for Vec<T>
975 // and a trait reference like `$0 : Eq` where `$0` is an
976 // unbound variable. When we evaluate this trait-reference, we
977 // will unify `$0` with `Vec<$1>` (for some fresh variable
978 // `$1`), on the condition that `$1 : Eq`. We will then wind
979 // up with many candidates (since that are other `Eq` impls
980 // that apply) and try to winnow things down. This results in
981 // a recursive evaluation that `$1 : Eq` -- as you can
982 // imagine, this is just where we started. To avoid that, we
983 // check for unbound variables and return an ambiguous (hence possible)
984 // match if we've seen this trait before.
986 // This suffices to allow chains like `FnMut` implemented in
987 // terms of `Fn` etc, but we could probably make this more
989 let unbound_input_types =
990 stack.fresh_trait_ref.skip_binder().input_types().any(|ty| ty.is_fresh());
991 // This check was an imperfect workaround for a bug in the old
992 // intercrate mode; it should be removed when that goes away.
993 if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
995 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
996 stack.fresh_trait_ref
998 // Heuristics: show the diagnostics when there are no candidates in crate.
999 if self.intercrate_ambiguity_causes.is_some() {
1000 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1001 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1002 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
1003 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1004 let self_ty = trait_ref.self_ty();
1005 let cause = IntercrateAmbiguityCause::DownstreamCrate {
1006 trait_desc: trait_ref.print_only_trait_path().to_string(),
1007 self_desc: if self_ty.has_concrete_skeleton() {
1008 Some(self_ty.to_string())
1013 debug!("evaluate_stack: pushing cause = {:?}", cause);
1014 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1018 return Ok(EvaluatedToAmbig);
1020 if unbound_input_types
1021 && stack.iter().skip(1).any(|prev| {
1022 stack.obligation.param_env == prev.obligation.param_env
1023 && self.match_fresh_trait_refs(
1024 &stack.fresh_trait_ref,
1025 &prev.fresh_trait_ref,
1026 prev.obligation.param_env,
1031 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
1032 stack.fresh_trait_ref
1034 return Ok(EvaluatedToUnknown);
1037 match self.candidate_from_obligation(stack) {
1038 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1039 Ok(None) => Ok(EvaluatedToAmbig),
1040 Err(Overflow) => Err(OverflowError),
1041 Err(..) => Ok(EvaluatedToErr),
1045 /// For defaulted traits, we use a co-inductive strategy to solve, so
1046 /// that recursion is ok. This routine returns `true` if the top of the
1047 /// stack (`cycle[0]`):
1049 /// - is a defaulted trait,
1050 /// - it also appears in the backtrace at some position `X`,
1051 /// - all the predicates at positions `X..` between `X` and the top are
1052 /// also defaulted traits.
1053 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1055 I: Iterator<Item = ty::Predicate<'tcx>>,
1057 let mut cycle = cycle;
1058 cycle.all(|predicate| self.coinductive_predicate(predicate))
1061 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1062 let result = match predicate {
1063 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1066 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1070 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1071 /// obligations are met. Returns whether `candidate` remains viable after this further
1073 fn evaluate_candidate<'o>(
1075 stack: &TraitObligationStack<'o, 'tcx>,
1076 candidate: &SelectionCandidate<'tcx>,
1077 ) -> Result<EvaluationResult, OverflowError> {
1079 "evaluate_candidate: depth={} candidate={:?}",
1080 stack.obligation.recursion_depth, candidate
1082 let result = self.evaluation_probe(|this| {
1083 let candidate = (*candidate).clone();
1084 match this.confirm_candidate(stack.obligation, candidate) {
1085 Ok(selection) => this.evaluate_predicates_recursively(
1087 selection.nested_obligations().into_iter(),
1089 Err(..) => Ok(EvaluatedToErr),
1093 "evaluate_candidate: depth={} result={:?}",
1094 stack.obligation.recursion_depth, result
1099 fn check_evaluation_cache(
1101 param_env: ty::ParamEnv<'tcx>,
1102 trait_ref: ty::PolyTraitRef<'tcx>,
1103 ) -> Option<EvaluationResult> {
1104 let tcx = self.tcx();
1105 if self.can_use_global_caches(param_env) {
1106 let cache = tcx.evaluation_cache.hashmap.borrow();
1107 if let Some(cached) = cache.get(¶m_env.and(trait_ref)) {
1108 return Some(cached.get(tcx));
1115 .get(¶m_env.and(trait_ref))
1116 .map(|v| v.get(tcx))
1119 fn insert_evaluation_cache(
1121 param_env: ty::ParamEnv<'tcx>,
1122 trait_ref: ty::PolyTraitRef<'tcx>,
1123 dep_node: DepNodeIndex,
1124 result: EvaluationResult,
1126 // Avoid caching results that depend on more than just the trait-ref
1127 // - the stack can create recursion.
1128 if result.is_stack_dependent() {
1132 if self.can_use_global_caches(param_env) {
1133 if !trait_ref.has_local_value() {
1135 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1138 // This may overwrite the cache with the same value
1139 // FIXME: Due to #50507 this overwrites the different values
1140 // This should be changed to use HashMapExt::insert_same
1141 // when that is fixed
1146 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
1151 debug!("insert_evaluation_cache(trait_ref={:?}, candidate={:?})", trait_ref, result,);
1156 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
1159 /// For various reasons, it's possible for a subobligation
1160 /// to have a *lower* recursion_depth than the obligation used to create it.
1161 /// Projection sub-obligations may be returned from the projection cache,
1162 /// which results in obligations with an 'old' `recursion_depth`.
1163 /// Additionally, methods like `wf::obligations` and
1164 /// `InferCtxt.subtype_predicate` produce subobligations without
1165 /// taking in a 'parent' depth, causing the generated subobligations
1166 /// to have a `recursion_depth` of `0`.
1168 /// To ensure that obligation_depth never decreasees, we force all subobligations
1169 /// to have at least the depth of the original obligation.
1170 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1175 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1178 /// Checks that the recursion limit has not been exceeded.
1180 /// The weird return type of this function allows it to be used with the `try` (`?`)
1181 /// operator within certain functions.
1182 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1184 obligation: &Obligation<'tcx, T>,
1185 error_obligation: &Obligation<'tcx, V>,
1186 ) -> Result<(), OverflowError> {
1187 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1188 if obligation.recursion_depth >= recursion_limit {
1189 match self.query_mode {
1190 TraitQueryMode::Standard => {
1191 self.infcx().report_overflow_error(error_obligation, true);
1193 TraitQueryMode::Canonical => {
1194 return Err(OverflowError);
1201 ///////////////////////////////////////////////////////////////////////////
1202 // CANDIDATE ASSEMBLY
1204 // The selection process begins by examining all in-scope impls,
1205 // caller obligations, and so forth and assembling a list of
1206 // candidates. See the [rustc guide] for more details.
1209 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1211 fn candidate_from_obligation<'o>(
1213 stack: &TraitObligationStack<'o, 'tcx>,
1214 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1215 // Watch out for overflow. This intentionally bypasses (and does
1216 // not update) the cache.
1217 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
1219 // Check the cache. Note that we freshen the trait-ref
1220 // separately rather than using `stack.fresh_trait_ref` --
1221 // this is because we want the unbound variables to be
1222 // replaced with fresh types starting from index 0.
1223 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1225 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1226 cache_fresh_trait_pred, stack
1228 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
1231 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1233 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1237 // If no match, compute result and insert into cache.
1239 // FIXME(nikomatsakis) -- this cache is not taking into
1240 // account cycles that may have occurred in forming the
1241 // candidate. I don't know of any specific problems that
1242 // result but it seems awfully suspicious.
1243 let (candidate, dep_node) =
1244 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1246 debug!("CACHE MISS: SELECT({:?})={:?}", cache_fresh_trait_pred, candidate);
1247 self.insert_candidate_cache(
1248 stack.obligation.param_env,
1249 cache_fresh_trait_pred,
1256 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1258 OP: FnOnce(&mut Self) -> R,
1260 let (result, dep_node) =
1261 self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || op(self));
1262 self.tcx().dep_graph.read_index(dep_node);
1266 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1267 fn filter_negative_and_reservation_impls(
1269 candidate: SelectionCandidate<'tcx>,
1270 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1271 if let ImplCandidate(def_id) = candidate {
1272 let tcx = self.tcx();
1273 match tcx.impl_polarity(def_id) {
1274 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1275 return Err(Unimplemented);
1277 ty::ImplPolarity::Reservation => {
1278 if let Some(intercrate_ambiguity_clauses) =
1279 &mut self.intercrate_ambiguity_causes
1281 let attrs = tcx.get_attrs(def_id);
1282 let attr = attr::find_by_name(&attrs, sym::rustc_reservation_impl);
1283 let value = attr.and_then(|a| a.value_str());
1284 if let Some(value) = value {
1286 "filter_negative_and_reservation_impls: \
1287 reservation impl ambiguity on {:?}",
1290 intercrate_ambiguity_clauses.push(
1291 IntercrateAmbiguityCause::ReservationImpl {
1292 message: value.to_string(),
1305 fn candidate_from_obligation_no_cache<'o>(
1307 stack: &TraitObligationStack<'o, 'tcx>,
1308 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1309 if stack.obligation.predicate.references_error() {
1310 // If we encounter a `Error`, we generally prefer the
1311 // most "optimistic" result in response -- that is, the
1312 // one least likely to report downstream errors. But
1313 // because this routine is shared by coherence and by
1314 // trait selection, there isn't an obvious "right" choice
1315 // here in that respect, so we opt to just return
1316 // ambiguity and let the upstream clients sort it out.
1320 if let Some(conflict) = self.is_knowable(stack) {
1321 debug!("coherence stage: not knowable");
1322 if self.intercrate_ambiguity_causes.is_some() {
1323 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1324 // Heuristics: show the diagnostics when there are no candidates in crate.
1325 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1326 let mut no_candidates_apply = true;
1328 let evaluated_candidates =
1329 candidate_set.vec.iter().map(|c| self.evaluate_candidate(stack, &c));
1331 for ec in evaluated_candidates {
1335 no_candidates_apply = false;
1339 Err(e) => return Err(e.into()),
1344 if !candidate_set.ambiguous && no_candidates_apply {
1345 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1346 let self_ty = trait_ref.self_ty();
1347 let trait_desc = trait_ref.print_only_trait_path().to_string();
1348 let self_desc = if self_ty.has_concrete_skeleton() {
1349 Some(self_ty.to_string())
1353 let cause = if let Conflict::Upstream = conflict {
1354 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1356 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1358 debug!("evaluate_stack: pushing cause = {:?}", cause);
1359 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1366 let candidate_set = self.assemble_candidates(stack)?;
1368 if candidate_set.ambiguous {
1369 debug!("candidate set contains ambig");
1373 let mut candidates = candidate_set.vec;
1375 debug!("assembled {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1377 // At this point, we know that each of the entries in the
1378 // candidate set is *individually* applicable. Now we have to
1379 // figure out if they contain mutual incompatibilities. This
1380 // frequently arises if we have an unconstrained input type --
1381 // for example, we are looking for `$0: Eq` where `$0` is some
1382 // unconstrained type variable. In that case, we'll get a
1383 // candidate which assumes $0 == int, one that assumes `$0 ==
1384 // usize`, etc. This spells an ambiguity.
1386 // If there is more than one candidate, first winnow them down
1387 // by considering extra conditions (nested obligations and so
1388 // forth). We don't winnow if there is exactly one
1389 // candidate. This is a relatively minor distinction but it
1390 // can lead to better inference and error-reporting. An
1391 // example would be if there was an impl:
1393 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1395 // and we were to see some code `foo.push_clone()` where `boo`
1396 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1397 // we were to winnow, we'd wind up with zero candidates.
1398 // Instead, we select the right impl now but report "`Bar` does
1399 // not implement `Clone`".
1400 if candidates.len() == 1 {
1401 return self.filter_negative_and_reservation_impls(candidates.pop().unwrap());
1404 // Winnow, but record the exact outcome of evaluation, which
1405 // is needed for specialization. Propagate overflow if it occurs.
1406 let mut candidates = candidates
1408 .map(|c| match self.evaluate_candidate(stack, &c) {
1409 Ok(eval) if eval.may_apply() => {
1410 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
1413 Err(OverflowError) => Err(Overflow),
1415 .flat_map(Result::transpose)
1416 .collect::<Result<Vec<_>, _>>()?;
1418 debug!("winnowed to {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1420 let needs_infer = stack.obligation.predicate.needs_infer();
1422 // If there are STILL multiple candidates, we can further
1423 // reduce the list by dropping duplicates -- including
1424 // resolving specializations.
1425 if candidates.len() > 1 {
1427 while i < candidates.len() {
1428 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1429 self.candidate_should_be_dropped_in_favor_of(
1436 debug!("Dropping candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1437 candidates.swap_remove(i);
1439 debug!("Retaining candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1442 // If there are *STILL* multiple candidates, give up
1443 // and report ambiguity.
1445 debug!("multiple matches, ambig");
1452 // If there are *NO* candidates, then there are no impls --
1453 // that we know of, anyway. Note that in the case where there
1454 // are unbound type variables within the obligation, it might
1455 // be the case that you could still satisfy the obligation
1456 // from another crate by instantiating the type variables with
1457 // a type from another crate that does have an impl. This case
1458 // is checked for in `evaluate_stack` (and hence users
1459 // who might care about this case, like coherence, should use
1461 if candidates.is_empty() {
1462 return Err(Unimplemented);
1465 // Just one candidate left.
1466 self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate)
1469 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1470 debug!("is_knowable(intercrate={:?})", self.intercrate);
1472 if !self.intercrate.is_some() {
1476 let obligation = &stack.obligation;
1477 let predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1479 // Okay to skip binder because of the nature of the
1480 // trait-ref-is-knowable check, which does not care about
1482 let trait_ref = predicate.skip_binder().trait_ref;
1484 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1486 Some(Conflict::Downstream { used_to_be_broken: true }),
1487 Some(IntercrateMode::Issue43355),
1488 ) = (result, self.intercrate)
1490 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1497 /// Returns `true` if the global caches can be used.
1498 /// Do note that if the type itself is not in the
1499 /// global tcx, the local caches will be used.
1500 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1501 // If there are any e.g. inference variables in the `ParamEnv`, then we
1502 // always use a cache local to this particular scope. Otherwise, we
1503 // switch to a global cache.
1504 if param_env.has_local_value() {
1508 // Avoid using the master cache during coherence and just rely
1509 // on the local cache. This effectively disables caching
1510 // during coherence. It is really just a simplification to
1511 // avoid us having to fear that coherence results "pollute"
1512 // the master cache. Since coherence executes pretty quickly,
1513 // it's not worth going to more trouble to increase the
1514 // hit-rate, I don't think.
1515 if self.intercrate.is_some() {
1519 // Otherwise, we can use the global cache.
1523 fn check_candidate_cache(
1525 param_env: ty::ParamEnv<'tcx>,
1526 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1527 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1528 let tcx = self.tcx();
1529 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1530 if self.can_use_global_caches(param_env) {
1531 let cache = tcx.selection_cache.hashmap.borrow();
1532 if let Some(cached) = cache.get(¶m_env.and(*trait_ref)) {
1533 return Some(cached.get(tcx));
1540 .get(¶m_env.and(*trait_ref))
1541 .map(|v| v.get(tcx))
1544 /// Determines whether can we safely cache the result
1545 /// of selecting an obligation. This is almost always `true`,
1546 /// except when dealing with certain `ParamCandidate`s.
1548 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1549 /// since it was usually produced directly from a `DefId`. However,
1550 /// certain cases (currently only librustdoc's blanket impl finder),
1551 /// a `ParamEnv` may be explicitly constructed with inference types.
1552 /// When this is the case, we do *not* want to cache the resulting selection
1553 /// candidate. This is due to the fact that it might not always be possible
1554 /// to equate the obligation's trait ref and the candidate's trait ref,
1555 /// if more constraints end up getting added to an inference variable.
1557 /// Because of this, we always want to re-run the full selection
1558 /// process for our obligation the next time we see it, since
1559 /// we might end up picking a different `SelectionCandidate` (or none at all).
1560 fn can_cache_candidate(
1562 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1565 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => {
1566 !trait_ref.skip_binder().input_types().any(|t| t.walk().any(|t_| t_.is_ty_infer()))
1572 fn insert_candidate_cache(
1574 param_env: ty::ParamEnv<'tcx>,
1575 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1576 dep_node: DepNodeIndex,
1577 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1579 let tcx = self.tcx();
1580 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1582 if !self.can_cache_candidate(&candidate) {
1584 "insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1585 candidate is not cacheable",
1586 trait_ref, candidate
1591 if self.can_use_global_caches(param_env) {
1592 if let Err(Overflow) = candidate {
1593 // Don't cache overflow globally; we only produce this in certain modes.
1594 } else if !trait_ref.has_local_value() {
1595 if !candidate.has_local_value() {
1597 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1598 trait_ref, candidate,
1600 // This may overwrite the cache with the same value.
1604 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1611 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1612 trait_ref, candidate,
1618 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1621 fn assemble_candidates<'o>(
1623 stack: &TraitObligationStack<'o, 'tcx>,
1624 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1625 let TraitObligationStack { obligation, .. } = *stack;
1626 let ref obligation = Obligation {
1627 param_env: obligation.param_env,
1628 cause: obligation.cause.clone(),
1629 recursion_depth: obligation.recursion_depth,
1630 predicate: self.infcx().resolve_vars_if_possible(&obligation.predicate),
1633 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1634 // Self is a type variable (e.g., `_: AsRef<str>`).
1636 // This is somewhat problematic, as the current scheme can't really
1637 // handle it turning to be a projection. This does end up as truly
1638 // ambiguous in most cases anyway.
1640 // Take the fast path out - this also improves
1641 // performance by preventing assemble_candidates_from_impls from
1642 // matching every impl for this trait.
1643 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1646 let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
1648 self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1650 // Other bounds. Consider both in-scope bounds from fn decl
1651 // and applicable impls. There is a certain set of precedence rules here.
1652 let def_id = obligation.predicate.def_id();
1653 let lang_items = self.tcx().lang_items();
1655 if lang_items.copy_trait() == Some(def_id) {
1656 debug!("obligation self ty is {:?}", obligation.predicate.skip_binder().self_ty());
1658 // User-defined copy impls are permitted, but only for
1659 // structs and enums.
1660 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1662 // For other types, we'll use the builtin rules.
1663 let copy_conditions = self.copy_clone_conditions(obligation);
1664 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1665 } else if lang_items.sized_trait() == Some(def_id) {
1666 // Sized is never implementable by end-users, it is
1667 // always automatically computed.
1668 let sized_conditions = self.sized_conditions(obligation);
1669 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1670 } else if lang_items.unsize_trait() == Some(def_id) {
1671 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1673 if lang_items.clone_trait() == Some(def_id) {
1674 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1675 // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone`
1676 // types have builtin support for `Clone`.
1677 let clone_conditions = self.copy_clone_conditions(obligation);
1678 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1681 self.assemble_generator_candidates(obligation, &mut candidates)?;
1682 self.assemble_closure_candidates(obligation, &mut candidates)?;
1683 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1684 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1685 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1688 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1689 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1690 // Auto implementations have lower priority, so we only
1691 // consider triggering a default if there is no other impl that can apply.
1692 if candidates.vec.is_empty() {
1693 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1695 debug!("candidate list size: {}", candidates.vec.len());
1699 fn assemble_candidates_from_projected_tys(
1701 obligation: &TraitObligation<'tcx>,
1702 candidates: &mut SelectionCandidateSet<'tcx>,
1704 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1706 // Before we go into the whole placeholder thing, just
1707 // quickly check if the self-type is a projection at all.
1708 match obligation.predicate.skip_binder().trait_ref.self_ty().kind {
1709 ty::Projection(_) | ty::Opaque(..) => {}
1710 ty::Infer(ty::TyVar(_)) => {
1712 obligation.cause.span,
1713 "Self=_ should have been handled by assemble_candidates"
1719 let result = self.infcx.probe(|snapshot| {
1720 self.match_projection_obligation_against_definition_bounds(obligation, snapshot)
1724 candidates.vec.push(ProjectionCandidate);
1728 fn match_projection_obligation_against_definition_bounds(
1730 obligation: &TraitObligation<'tcx>,
1731 snapshot: &CombinedSnapshot<'_, 'tcx>,
1733 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1734 let (placeholder_trait_predicate, placeholder_map) =
1735 self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
1737 "match_projection_obligation_against_definition_bounds: \
1738 placeholder_trait_predicate={:?}",
1739 placeholder_trait_predicate,
1742 let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().kind {
1743 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1744 ty::Opaque(def_id, substs) => (def_id, substs),
1747 obligation.cause.span,
1748 "match_projection_obligation_against_definition_bounds() called \
1749 but self-ty is not a projection: {:?}",
1750 placeholder_trait_predicate.trait_ref.self_ty()
1755 "match_projection_obligation_against_definition_bounds: \
1756 def_id={:?}, substs={:?}",
1760 let predicates_of = self.tcx().predicates_of(def_id);
1761 let bounds = predicates_of.instantiate(self.tcx(), substs);
1763 "match_projection_obligation_against_definition_bounds: \
1768 let elaborated_predicates = util::elaborate_predicates(self.tcx(), bounds.predicates);
1769 let matching_bound = elaborated_predicates.filter_to_traits().find(|bound| {
1770 self.infcx.probe(|_| {
1771 self.match_projection(
1774 placeholder_trait_predicate.trait_ref.clone(),
1782 "match_projection_obligation_against_definition_bounds: \
1783 matching_bound={:?}",
1786 match matching_bound {
1789 // Repeat the successful match, if any, this time outside of a probe.
1790 let result = self.match_projection(
1793 placeholder_trait_predicate.trait_ref.clone(),
1804 fn match_projection(
1806 obligation: &TraitObligation<'tcx>,
1807 trait_bound: ty::PolyTraitRef<'tcx>,
1808 placeholder_trait_ref: ty::TraitRef<'tcx>,
1809 placeholder_map: &PlaceholderMap<'tcx>,
1810 snapshot: &CombinedSnapshot<'_, 'tcx>,
1812 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1814 .at(&obligation.cause, obligation.param_env)
1815 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1817 && self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1820 /// Given an obligation like `<SomeTrait for T>`, searches the obligations that the caller
1821 /// supplied to find out whether it is listed among them.
1823 /// Never affects the inference environment.
1824 fn assemble_candidates_from_caller_bounds<'o>(
1826 stack: &TraitObligationStack<'o, 'tcx>,
1827 candidates: &mut SelectionCandidateSet<'tcx>,
1828 ) -> Result<(), SelectionError<'tcx>> {
1829 debug!("assemble_candidates_from_caller_bounds({:?})", stack.obligation);
1831 let all_bounds = stack
1836 .filter_map(|o| o.to_opt_poly_trait_ref());
1838 // Micro-optimization: filter out predicates relating to different traits.
1839 let matching_bounds =
1840 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1842 // Keep only those bounds which may apply, and propagate overflow if it occurs.
1843 let mut param_candidates = vec![];
1844 for bound in matching_bounds {
1845 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1847 param_candidates.push(ParamCandidate(bound));
1851 candidates.vec.extend(param_candidates);
1856 fn evaluate_where_clause<'o>(
1858 stack: &TraitObligationStack<'o, 'tcx>,
1859 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1860 ) -> Result<EvaluationResult, OverflowError> {
1861 self.evaluation_probe(|this| {
1862 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1863 Ok(obligations) => {
1864 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1866 Err(()) => Ok(EvaluatedToErr),
1871 fn assemble_generator_candidates(
1873 obligation: &TraitObligation<'tcx>,
1874 candidates: &mut SelectionCandidateSet<'tcx>,
1875 ) -> Result<(), SelectionError<'tcx>> {
1876 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1880 // Okay to skip binder because the substs on generator types never
1881 // touch bound regions, they just capture the in-scope
1882 // type/region parameters.
1883 let self_ty = *obligation.self_ty().skip_binder();
1884 match self_ty.kind {
1885 ty::Generator(..) => {
1887 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1891 candidates.vec.push(GeneratorCandidate);
1893 ty::Infer(ty::TyVar(_)) => {
1894 debug!("assemble_generator_candidates: ambiguous self-type");
1895 candidates.ambiguous = true;
1903 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1904 /// FnMut<..>` where `X` is a closure type.
1906 /// Note: the type parameters on a closure candidate are modeled as *output* type
1907 /// parameters and hence do not affect whether this trait is a match or not. They will be
1908 /// unified during the confirmation step.
1909 fn assemble_closure_candidates(
1911 obligation: &TraitObligation<'tcx>,
1912 candidates: &mut SelectionCandidateSet<'tcx>,
1913 ) -> Result<(), SelectionError<'tcx>> {
1914 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()) {
1921 // Okay to skip binder because the substs on closure types never
1922 // touch bound regions, they just capture the in-scope
1923 // type/region parameters
1924 match obligation.self_ty().skip_binder().kind {
1925 ty::Closure(closure_def_id, closure_substs) => {
1926 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}", kind, obligation);
1927 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1928 Some(closure_kind) => {
1929 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1930 if closure_kind.extends(kind) {
1931 candidates.vec.push(ClosureCandidate);
1935 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1936 candidates.vec.push(ClosureCandidate);
1940 ty::Infer(ty::TyVar(_)) => {
1941 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1942 candidates.ambiguous = true;
1950 /// Implements one of the `Fn()` family for a fn pointer.
1951 fn assemble_fn_pointer_candidates(
1953 obligation: &TraitObligation<'tcx>,
1954 candidates: &mut SelectionCandidateSet<'tcx>,
1955 ) -> Result<(), SelectionError<'tcx>> {
1956 // We provide impl of all fn traits for fn pointers.
1957 if self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()).is_none() {
1961 // Okay to skip binder because what we are inspecting doesn't involve bound regions.
1962 let self_ty = *obligation.self_ty().skip_binder();
1963 match self_ty.kind {
1964 ty::Infer(ty::TyVar(_)) => {
1965 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1966 candidates.ambiguous = true; // Could wind up being a fn() type.
1968 // Provide an impl, but only for suitable `fn` pointers.
1969 ty::FnDef(..) | ty::FnPtr(_) => {
1971 unsafety: hir::Unsafety::Normal,
1975 } = self_ty.fn_sig(self.tcx()).skip_binder()
1977 candidates.vec.push(FnPointerCandidate);
1986 /// Searches for impls that might apply to `obligation`.
1987 fn assemble_candidates_from_impls(
1989 obligation: &TraitObligation<'tcx>,
1990 candidates: &mut SelectionCandidateSet<'tcx>,
1991 ) -> Result<(), SelectionError<'tcx>> {
1992 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1994 self.tcx().for_each_relevant_impl(
1995 obligation.predicate.def_id(),
1996 obligation.predicate.skip_binder().trait_ref.self_ty(),
1998 self.infcx.probe(|snapshot| {
1999 if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot) {
2000 candidates.vec.push(ImplCandidate(impl_def_id));
2009 fn assemble_candidates_from_auto_impls(
2011 obligation: &TraitObligation<'tcx>,
2012 candidates: &mut SelectionCandidateSet<'tcx>,
2013 ) -> Result<(), SelectionError<'tcx>> {
2014 // Okay to skip binder here because the tests we do below do not involve bound regions.
2015 let self_ty = *obligation.self_ty().skip_binder();
2016 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2018 let def_id = obligation.predicate.def_id();
2020 if self.tcx().trait_is_auto(def_id) {
2021 match self_ty.kind {
2022 ty::Dynamic(..) => {
2023 // For object types, we don't know what the closed
2024 // over types are. This means we conservatively
2025 // say nothing; a candidate may be added by
2026 // `assemble_candidates_from_object_ty`.
2028 ty::Foreign(..) => {
2029 // Since the contents of foreign types is unknown,
2030 // we don't add any `..` impl. Default traits could
2031 // still be provided by a manual implementation for
2032 // this trait and type.
2034 ty::Param(..) | ty::Projection(..) => {
2035 // In these cases, we don't know what the actual
2036 // type is. Therefore, we cannot break it down
2037 // into its constituent types. So we don't
2038 // consider the `..` impl but instead just add no
2039 // candidates: this means that typeck will only
2040 // succeed if there is another reason to believe
2041 // that this obligation holds. That could be a
2042 // where-clause or, in the case of an object type,
2043 // it could be that the object type lists the
2044 // trait (e.g., `Foo+Send : Send`). See
2045 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2046 // for an example of a test case that exercises
2049 ty::Infer(ty::TyVar(_)) => {
2050 // The auto impl might apply; we don't know.
2051 candidates.ambiguous = true;
2053 ty::Generator(_, _, movability)
2054 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
2057 hir::Movability::Static => {
2058 // Immovable generators are never `Unpin`, so
2059 // suppress the normal auto-impl candidate for it.
2061 hir::Movability::Movable => {
2062 // Movable generators are always `Unpin`, so add an
2063 // unconditional builtin candidate.
2064 candidates.vec.push(BuiltinCandidate { has_nested: false });
2069 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2076 /// Searches for impls that might apply to `obligation`.
2077 fn assemble_candidates_from_object_ty(
2079 obligation: &TraitObligation<'tcx>,
2080 candidates: &mut SelectionCandidateSet<'tcx>,
2083 "assemble_candidates_from_object_ty(self_ty={:?})",
2084 obligation.self_ty().skip_binder()
2087 self.infcx.probe(|_snapshot| {
2088 // The code below doesn't care about regions, and the
2089 // self-ty here doesn't escape this probe, so just erase
2091 let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
2092 let poly_trait_ref = match self_ty.kind {
2093 ty::Dynamic(ref data, ..) => {
2094 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
2096 "assemble_candidates_from_object_ty: matched builtin bound, \
2099 candidates.vec.push(BuiltinObjectCandidate);
2103 if let Some(principal) = data.principal() {
2104 if !self.infcx.tcx.features().object_safe_for_dispatch {
2105 principal.with_self_ty(self.tcx(), self_ty)
2106 } else if self.tcx().is_object_safe(principal.def_id()) {
2107 principal.with_self_ty(self.tcx(), self_ty)
2112 // Only auto trait bounds exist.
2116 ty::Infer(ty::TyVar(_)) => {
2117 debug!("assemble_candidates_from_object_ty: ambiguous");
2118 candidates.ambiguous = true; // could wind up being an object type
2124 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}", poly_trait_ref);
2126 // Count only those upcast versions that match the trait-ref
2127 // we are looking for. Specifically, do not only check for the
2128 // correct trait, but also the correct type parameters.
2129 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2130 // but `Foo` is declared as `trait Foo: Bar<u32>`.
2131 let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
2132 .filter(|upcast_trait_ref| {
2133 self.infcx.probe(|_| {
2134 let upcast_trait_ref = upcast_trait_ref.clone();
2135 self.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
2140 if upcast_trait_refs > 1 {
2141 // Can be upcast in many ways; need more type information.
2142 candidates.ambiguous = true;
2143 } else if upcast_trait_refs == 1 {
2144 candidates.vec.push(ObjectCandidate);
2149 /// Searches for unsizing that might apply to `obligation`.
2150 fn assemble_candidates_for_unsizing(
2152 obligation: &TraitObligation<'tcx>,
2153 candidates: &mut SelectionCandidateSet<'tcx>,
2155 // We currently never consider higher-ranked obligations e.g.
2156 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2157 // because they are a priori invalid, and we could potentially add support
2158 // for them later, it's just that there isn't really a strong need for it.
2159 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2160 // impl, and those are generally applied to concrete types.
2162 // That said, one might try to write a fn with a where clause like
2163 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2164 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2165 // Still, you'd be more likely to write that where clause as
2167 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2168 // obligation above. Should be possible to extend this in the future.
2169 let source = match obligation.self_ty().no_bound_vars() {
2172 // Don't add any candidates if there are bound regions.
2176 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2178 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})", source, target);
2180 let may_apply = match (&source.kind, &target.kind) {
2181 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2182 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2183 // Upcasts permit two things:
2185 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
2186 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
2188 // Note that neither of these changes requires any
2189 // change at runtime. Eventually this will be
2192 // We always upcast when we can because of reason
2193 // #2 (region bounds).
2194 data_a.principal_def_id() == data_b.principal_def_id()
2197 // All of a's auto traits need to be in b's auto traits.
2198 .all(|b| data_a.auto_traits().any(|a| a == b))
2202 (_, &ty::Dynamic(..)) => true,
2204 // Ambiguous handling is below `T` -> `Trait`, because inference
2205 // variables can still implement `Unsize<Trait>` and nested
2206 // obligations will have the final say (likely deferred).
2207 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2208 debug!("assemble_candidates_for_unsizing: ambiguous");
2209 candidates.ambiguous = true;
2213 // `[T; n]` -> `[T]`
2214 (&ty::Array(..), &ty::Slice(_)) => true,
2216 // `Struct<T>` -> `Struct<U>`
2217 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2218 def_id_a == def_id_b
2221 // `(.., T)` -> `(.., U)`
2222 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2228 candidates.vec.push(BuiltinUnsizeCandidate);
2232 fn assemble_candidates_for_trait_alias(
2234 obligation: &TraitObligation<'tcx>,
2235 candidates: &mut SelectionCandidateSet<'tcx>,
2236 ) -> Result<(), SelectionError<'tcx>> {
2237 // Okay to skip binder here because the tests we do below do not involve bound regions.
2238 let self_ty = *obligation.self_ty().skip_binder();
2239 debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
2241 let def_id = obligation.predicate.def_id();
2243 if self.tcx().is_trait_alias(def_id) {
2244 candidates.vec.push(TraitAliasCandidate(def_id.clone()));
2250 ///////////////////////////////////////////////////////////////////////////
2253 // Winnowing is the process of attempting to resolve ambiguity by
2254 // probing further. During the winnowing process, we unify all
2255 // type variables and then we also attempt to evaluate recursive
2256 // bounds to see if they are satisfied.
2258 /// Returns `true` if `victim` should be dropped in favor of
2259 /// `other`. Generally speaking we will drop duplicate
2260 /// candidates and prefer where-clause candidates.
2262 /// See the comment for "SelectionCandidate" for more details.
2263 fn candidate_should_be_dropped_in_favor_of(
2265 victim: &EvaluatedCandidate<'tcx>,
2266 other: &EvaluatedCandidate<'tcx>,
2269 if victim.candidate == other.candidate {
2273 // Check if a bound would previously have been removed when normalizing
2274 // the param_env so that it can be given the lowest priority. See
2275 // #50825 for the motivation for this.
2277 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2279 match other.candidate {
2280 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2281 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2282 // lifetime of a variable.
2283 BuiltinCandidate { has_nested: false } => true,
2284 ParamCandidate(ref cand) => match victim.candidate {
2285 AutoImplCandidate(..) => {
2287 "default implementations shouldn't be recorded \
2288 when there are other valid candidates"
2291 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2292 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2293 // lifetime of a variable.
2294 BuiltinCandidate { has_nested: false } => false,
2297 | GeneratorCandidate
2298 | FnPointerCandidate
2299 | BuiltinObjectCandidate
2300 | BuiltinUnsizeCandidate
2301 | BuiltinCandidate { .. }
2302 | TraitAliasCandidate(..) => {
2303 // Global bounds from the where clause should be ignored
2304 // here (see issue #50825). Otherwise, we have a where
2305 // clause so don't go around looking for impls.
2308 ObjectCandidate | ProjectionCandidate => {
2309 // Arbitrarily give param candidates priority
2310 // over projection and object candidates.
2313 ParamCandidate(..) => false,
2315 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2316 AutoImplCandidate(..) => {
2318 "default implementations shouldn't be recorded \
2319 when there are other valid candidates"
2322 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2323 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2324 // lifetime of a variable.
2325 BuiltinCandidate { has_nested: false } => false,
2328 | GeneratorCandidate
2329 | FnPointerCandidate
2330 | BuiltinObjectCandidate
2331 | BuiltinUnsizeCandidate
2332 | BuiltinCandidate { .. }
2333 | TraitAliasCandidate(..) => true,
2334 ObjectCandidate | ProjectionCandidate => {
2335 // Arbitrarily give param candidates priority
2336 // over projection and object candidates.
2339 ParamCandidate(ref cand) => is_global(cand),
2341 ImplCandidate(other_def) => {
2342 // See if we can toss out `victim` based on specialization.
2343 // This requires us to know *for sure* that the `other` impl applies
2344 // i.e., `EvaluatedToOk`.
2345 if other.evaluation.must_apply_modulo_regions() {
2346 match victim.candidate {
2347 ImplCandidate(victim_def) => {
2348 let tcx = self.tcx();
2349 if tcx.specializes((other_def, victim_def)) {
2352 return match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
2353 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
2354 // Subtle: If the predicate we are evaluating has inference
2355 // variables, do *not* allow discarding candidates due to
2356 // marker trait impls.
2358 // Without this restriction, we could end up accidentally
2359 // constrainting inference variables based on an arbitrarily
2360 // chosen trait impl.
2362 // Imagine we have the following code:
2365 // #[marker] trait MyTrait {}
2366 // impl MyTrait for u8 {}
2367 // impl MyTrait for bool {}
2370 // And we are evaluating the predicate `<_#0t as MyTrait>`.
2372 // During selection, we will end up with one candidate for each
2373 // impl of `MyTrait`. If we were to discard one impl in favor
2374 // of the other, we would be left with one candidate, causing
2375 // us to "successfully" select the predicate, unifying
2376 // _#0t with (for example) `u8`.
2378 // However, we have no reason to believe that this unification
2379 // is correct - we've essentially just picked an arbitrary
2380 // *possibility* for _#0t, and required that this be the *only*
2383 // Eventually, we will either:
2384 // 1) Unify all inference variables in the predicate through
2385 // some other means (e.g. type-checking of a function). We will
2386 // then be in a position to drop marker trait candidates
2387 // without constraining inference variables (since there are
2388 // none left to constrin)
2389 // 2) Be left with some unconstrained inference variables. We
2390 // will then correctly report an inference error, since the
2391 // existence of multiple marker trait impls tells us nothing
2392 // about which one should actually apply.
2399 ParamCandidate(ref cand) => {
2400 // Prefer the impl to a global where clause candidate.
2401 return is_global(cand);
2410 | GeneratorCandidate
2411 | FnPointerCandidate
2412 | BuiltinObjectCandidate
2413 | BuiltinUnsizeCandidate
2414 | BuiltinCandidate { has_nested: true } => {
2415 match victim.candidate {
2416 ParamCandidate(ref cand) => {
2417 // Prefer these to a global where-clause bound
2418 // (see issue #50825).
2419 is_global(cand) && other.evaluation.must_apply_modulo_regions()
2428 ///////////////////////////////////////////////////////////////////////////
2431 // These cover the traits that are built-in to the language
2432 // itself: `Copy`, `Clone` and `Sized`.
2434 fn assemble_builtin_bound_candidates(
2436 conditions: BuiltinImplConditions<'tcx>,
2437 candidates: &mut SelectionCandidateSet<'tcx>,
2438 ) -> Result<(), SelectionError<'tcx>> {
2440 BuiltinImplConditions::Where(nested) => {
2441 debug!("builtin_bound: nested={:?}", nested);
2444 .push(BuiltinCandidate { has_nested: nested.skip_binder().len() > 0 });
2446 BuiltinImplConditions::None => {}
2447 BuiltinImplConditions::Ambiguous => {
2448 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2449 candidates.ambiguous = true;
2456 fn sized_conditions(
2458 obligation: &TraitObligation<'tcx>,
2459 ) -> BuiltinImplConditions<'tcx> {
2460 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2462 // NOTE: binder moved to (*)
2463 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2465 match self_ty.kind {
2466 ty::Infer(ty::IntVar(_))
2467 | ty::Infer(ty::FloatVar(_))
2478 | ty::GeneratorWitness(..)
2483 // safe for everything
2484 Where(ty::Binder::dummy(Vec::new()))
2487 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2490 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2493 ty::Adt(def, substs) => {
2494 let sized_crit = def.sized_constraint(self.tcx());
2495 // (*) binder moved here
2496 Where(ty::Binder::bind(
2497 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect(),
2501 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2502 ty::Infer(ty::TyVar(_)) => Ambiguous,
2504 ty::UnnormalizedProjection(..)
2505 | ty::Placeholder(..)
2507 | ty::Infer(ty::FreshTy(_))
2508 | ty::Infer(ty::FreshIntTy(_))
2509 | ty::Infer(ty::FreshFloatTy(_)) => {
2510 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2515 fn copy_clone_conditions(
2517 obligation: &TraitObligation<'tcx>,
2518 ) -> BuiltinImplConditions<'tcx> {
2519 // NOTE: binder moved to (*)
2520 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2522 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2524 match self_ty.kind {
2525 ty::Infer(ty::IntVar(_))
2526 | ty::Infer(ty::FloatVar(_))
2529 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2538 | ty::Ref(_, _, hir::Mutability::Not) => {
2539 // Implementations provided in libcore
2547 | ty::GeneratorWitness(..)
2549 | ty::Ref(_, _, hir::Mutability::Mut) => None,
2551 ty::Array(element_ty, _) => {
2552 // (*) binder moved here
2553 Where(ty::Binder::bind(vec![element_ty]))
2557 // (*) binder moved here
2558 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2561 ty::Closure(def_id, substs) => {
2562 // (*) binder moved here
2563 Where(ty::Binder::bind(substs.as_closure().upvar_tys(def_id, self.tcx()).collect()))
2566 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2567 // Fallback to whatever user-defined impls exist in this case.
2571 ty::Infer(ty::TyVar(_)) => {
2572 // Unbound type variable. Might or might not have
2573 // applicable impls and so forth, depending on what
2574 // those type variables wind up being bound to.
2578 ty::UnnormalizedProjection(..)
2579 | ty::Placeholder(..)
2581 | ty::Infer(ty::FreshTy(_))
2582 | ty::Infer(ty::FreshIntTy(_))
2583 | ty::Infer(ty::FreshFloatTy(_)) => {
2584 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2589 /// For default impls, we need to break apart a type into its
2590 /// "constituent types" -- meaning, the types that it contains.
2592 /// Here are some (simple) examples:
2595 /// (i32, u32) -> [i32, u32]
2596 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2597 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2598 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2600 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2610 | ty::Infer(ty::IntVar(_))
2611 | ty::Infer(ty::FloatVar(_))
2613 | ty::Char => Vec::new(),
2615 ty::UnnormalizedProjection(..)
2616 | ty::Placeholder(..)
2620 | ty::Projection(..)
2622 | ty::Infer(ty::TyVar(_))
2623 | ty::Infer(ty::FreshTy(_))
2624 | ty::Infer(ty::FreshIntTy(_))
2625 | ty::Infer(ty::FreshFloatTy(_)) => {
2626 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2629 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2633 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2635 ty::Tuple(ref tys) => {
2636 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2637 tys.iter().map(|k| k.expect_ty()).collect()
2640 ty::Closure(def_id, ref substs) => {
2641 substs.as_closure().upvar_tys(def_id, self.tcx()).collect()
2644 ty::Generator(def_id, ref substs, _) => {
2645 let witness = substs.as_generator().witness(def_id, self.tcx());
2648 .upvar_tys(def_id, self.tcx())
2649 .chain(iter::once(witness))
2653 ty::GeneratorWitness(types) => {
2654 // This is sound because no regions in the witness can refer to
2655 // the binder outside the witness. So we'll effectivly reuse
2656 // the implicit binder around the witness.
2657 types.skip_binder().to_vec()
2660 // For `PhantomData<T>`, we pass `T`.
2661 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2663 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2665 ty::Opaque(def_id, substs) => {
2666 // We can resolve the `impl Trait` to its concrete type,
2667 // which enforces a DAG between the functions requiring
2668 // the auto trait bounds in question.
2669 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2674 fn collect_predicates_for_types(
2676 param_env: ty::ParamEnv<'tcx>,
2677 cause: ObligationCause<'tcx>,
2678 recursion_depth: usize,
2679 trait_def_id: DefId,
2680 types: ty::Binder<Vec<Ty<'tcx>>>,
2681 ) -> Vec<PredicateObligation<'tcx>> {
2682 // Because the types were potentially derived from
2683 // higher-ranked obligations they may reference late-bound
2684 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2685 // yield a type like `for<'a> &'a int`. In general, we
2686 // maintain the invariant that we never manipulate bound
2687 // regions, so we have to process these bound regions somehow.
2689 // The strategy is to:
2691 // 1. Instantiate those regions to placeholder regions (e.g.,
2692 // `for<'a> &'a int` becomes `&0 int`.
2693 // 2. Produce something like `&'0 int : Copy`
2694 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2701 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2703 self.infcx.commit_unconditionally(|_| {
2704 let (skol_ty, _) = self.infcx.replace_bound_vars_with_placeholders(&ty);
2705 let Normalized { value: normalized_ty, mut obligations } =
2706 project::normalize_with_depth(
2713 let skol_obligation = predicate_for_trait_def(
2722 obligations.push(skol_obligation);
2729 ///////////////////////////////////////////////////////////////////////////
2732 // Confirmation unifies the output type parameters of the trait
2733 // with the values found in the obligation, possibly yielding a
2734 // type error. See the [rustc guide] for more details.
2737 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
2739 fn confirm_candidate(
2741 obligation: &TraitObligation<'tcx>,
2742 candidate: SelectionCandidate<'tcx>,
2743 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2744 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2747 BuiltinCandidate { has_nested } => {
2748 let data = self.confirm_builtin_candidate(obligation, has_nested);
2749 Ok(VtableBuiltin(data))
2752 ParamCandidate(param) => {
2753 let obligations = self.confirm_param_candidate(obligation, param);
2754 Ok(VtableParam(obligations))
2757 ImplCandidate(impl_def_id) => {
2758 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2761 AutoImplCandidate(trait_def_id) => {
2762 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2763 Ok(VtableAutoImpl(data))
2766 ProjectionCandidate => {
2767 self.confirm_projection_candidate(obligation);
2768 Ok(VtableParam(Vec::new()))
2771 ClosureCandidate => {
2772 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2773 Ok(VtableClosure(vtable_closure))
2776 GeneratorCandidate => {
2777 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2778 Ok(VtableGenerator(vtable_generator))
2781 FnPointerCandidate => {
2782 let data = self.confirm_fn_pointer_candidate(obligation)?;
2783 Ok(VtableFnPointer(data))
2786 TraitAliasCandidate(alias_def_id) => {
2787 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2788 Ok(VtableTraitAlias(data))
2791 ObjectCandidate => {
2792 let data = self.confirm_object_candidate(obligation);
2793 Ok(VtableObject(data))
2796 BuiltinObjectCandidate => {
2797 // This indicates something like `Trait + Send: Send`. In this case, we know that
2798 // this holds because that's what the object type is telling us, and there's really
2799 // no additional obligations to prove and no types in particular to unify, etc.
2800 Ok(VtableParam(Vec::new()))
2803 BuiltinUnsizeCandidate => {
2804 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2805 Ok(VtableBuiltin(data))
2810 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2811 self.infcx.commit_unconditionally(|snapshot| {
2813 self.match_projection_obligation_against_definition_bounds(obligation, snapshot);
2818 fn confirm_param_candidate(
2820 obligation: &TraitObligation<'tcx>,
2821 param: ty::PolyTraitRef<'tcx>,
2822 ) -> Vec<PredicateObligation<'tcx>> {
2823 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2825 // During evaluation, we already checked that this
2826 // where-clause trait-ref could be unified with the obligation
2827 // trait-ref. Repeat that unification now without any
2828 // transactional boundary; it should not fail.
2829 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2830 Ok(obligations) => obligations,
2833 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2841 fn confirm_builtin_candidate(
2843 obligation: &TraitObligation<'tcx>,
2845 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2846 debug!("confirm_builtin_candidate({:?}, {:?})", obligation, has_nested);
2848 let lang_items = self.tcx().lang_items();
2849 let obligations = if has_nested {
2850 let trait_def = obligation.predicate.def_id();
2851 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2852 self.sized_conditions(obligation)
2853 } else if Some(trait_def) == lang_items.copy_trait() {
2854 self.copy_clone_conditions(obligation)
2855 } else if Some(trait_def) == lang_items.clone_trait() {
2856 self.copy_clone_conditions(obligation)
2858 bug!("unexpected builtin trait {:?}", trait_def)
2860 let nested = match conditions {
2861 BuiltinImplConditions::Where(nested) => nested,
2862 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation),
2865 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2866 self.collect_predicates_for_types(
2867 obligation.param_env,
2869 obligation.recursion_depth + 1,
2877 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2879 VtableBuiltinData { nested: obligations }
2882 /// This handles the case where a `auto trait Foo` impl is being used.
2883 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2885 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2886 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2887 fn confirm_auto_impl_candidate(
2889 obligation: &TraitObligation<'tcx>,
2890 trait_def_id: DefId,
2891 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2892 debug!("confirm_auto_impl_candidate({:?}, {:?})", obligation, trait_def_id);
2894 let types = obligation.predicate.map_bound(|inner| {
2895 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2896 self.constituent_types_for_ty(self_ty)
2898 self.vtable_auto_impl(obligation, trait_def_id, types)
2901 /// See `confirm_auto_impl_candidate`.
2902 fn vtable_auto_impl(
2904 obligation: &TraitObligation<'tcx>,
2905 trait_def_id: DefId,
2906 nested: ty::Binder<Vec<Ty<'tcx>>>,
2907 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2908 debug!("vtable_auto_impl: nested={:?}", nested);
2910 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2911 let mut obligations = self.collect_predicates_for_types(
2912 obligation.param_env,
2914 obligation.recursion_depth + 1,
2919 let trait_obligations: Vec<PredicateObligation<'_>> =
2920 self.infcx.commit_unconditionally(|_| {
2921 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2922 let (trait_ref, _) =
2923 self.infcx.replace_bound_vars_with_placeholders(&poly_trait_ref);
2924 let cause = obligation.derived_cause(ImplDerivedObligation);
2925 self.impl_or_trait_obligations(
2927 obligation.recursion_depth + 1,
2928 obligation.param_env,
2934 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
2935 // predicate as usual. It won't have any effect since auto traits are coinductive.
2936 obligations.extend(trait_obligations);
2938 debug!("vtable_auto_impl: obligations={:?}", obligations);
2940 VtableAutoImplData { trait_def_id, nested: obligations }
2943 fn confirm_impl_candidate(
2945 obligation: &TraitObligation<'tcx>,
2947 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2948 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
2950 // First, create the substitutions by matching the impl again,
2951 // this time not in a probe.
2952 self.infcx.commit_unconditionally(|snapshot| {
2953 let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
2954 debug!("confirm_impl_candidate: substs={:?}", substs);
2955 let cause = obligation.derived_cause(ImplDerivedObligation);
2960 obligation.recursion_depth + 1,
2961 obligation.param_env,
2969 mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
2970 cause: ObligationCause<'tcx>,
2971 recursion_depth: usize,
2972 param_env: ty::ParamEnv<'tcx>,
2973 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2975 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
2976 impl_def_id, substs, recursion_depth,
2979 let mut impl_obligations = self.impl_or_trait_obligations(
2988 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2989 impl_def_id, impl_obligations
2992 // Because of RFC447, the impl-trait-ref and obligations
2993 // are sufficient to determine the impl substs, without
2994 // relying on projections in the impl-trait-ref.
2996 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2997 impl_obligations.append(&mut substs.obligations);
2999 VtableImplData { impl_def_id, substs: substs.value, nested: impl_obligations }
3002 fn confirm_object_candidate(
3004 obligation: &TraitObligation<'tcx>,
3005 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
3006 debug!("confirm_object_candidate({:?})", obligation);
3008 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
3009 // probably flatten the binder from the obligation and the binder
3010 // from the object. Have to try to make a broken test case that
3012 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3013 let poly_trait_ref = match self_ty.kind {
3014 ty::Dynamic(ref data, ..) => data
3016 .unwrap_or_else(|| {
3017 span_bug!(obligation.cause.span, "object candidate with no principal")
3019 .with_self_ty(self.tcx(), self_ty),
3020 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
3023 let mut upcast_trait_ref = None;
3024 let mut nested = vec![];
3028 let tcx = self.tcx();
3030 // We want to find the first supertrait in the list of
3031 // supertraits that we can unify with, and do that
3032 // unification. We know that there is exactly one in the list
3033 // where we can unify, because otherwise select would have
3034 // reported an ambiguity. (When we do find a match, also
3035 // record it for later.)
3036 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(|&t| {
3037 match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
3038 Ok(obligations) => {
3039 upcast_trait_ref = Some(t);
3040 nested.extend(obligations);
3047 // Additionally, for each of the non-matching predicates that
3048 // we pass over, we sum up the set of number of vtable
3049 // entries, so that we can compute the offset for the selected
3051 vtable_base = nonmatching.map(|t| super::util::count_own_vtable_entries(tcx, t)).sum();
3054 VtableObjectData { upcast_trait_ref: upcast_trait_ref.unwrap(), vtable_base, nested }
3057 fn confirm_fn_pointer_candidate(
3059 obligation: &TraitObligation<'tcx>,
3060 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3061 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3063 // Okay to skip binder; it is reintroduced below.
3064 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3065 let sig = self_ty.fn_sig(self.tcx());
3066 let trait_ref = closure_trait_ref_and_return_type(
3068 obligation.predicate.def_id(),
3071 util::TupleArgumentsFlag::Yes,
3073 .map_bound(|(trait_ref, _)| trait_ref);
3075 let Normalized { value: trait_ref, obligations } = project::normalize_with_depth(
3077 obligation.param_env,
3078 obligation.cause.clone(),
3079 obligation.recursion_depth + 1,
3083 self.confirm_poly_trait_refs(
3084 obligation.cause.clone(),
3085 obligation.param_env,
3086 obligation.predicate.to_poly_trait_ref(),
3089 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
3092 fn confirm_trait_alias_candidate(
3094 obligation: &TraitObligation<'tcx>,
3095 alias_def_id: DefId,
3096 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3097 debug!("confirm_trait_alias_candidate({:?}, {:?})", obligation, alias_def_id);
3099 self.infcx.commit_unconditionally(|_| {
3100 let (predicate, _) =
3101 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
3102 let trait_ref = predicate.trait_ref;
3103 let trait_def_id = trait_ref.def_id;
3104 let substs = trait_ref.substs;
3106 let trait_obligations = self.impl_or_trait_obligations(
3107 obligation.cause.clone(),
3108 obligation.recursion_depth,
3109 obligation.param_env,
3115 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3116 trait_def_id, trait_obligations
3119 VtableTraitAliasData { alias_def_id, substs: substs, nested: trait_obligations }
3123 fn confirm_generator_candidate(
3125 obligation: &TraitObligation<'tcx>,
3126 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3127 // Okay to skip binder because the substs on generator types never
3128 // touch bound regions, they just capture the in-scope
3129 // type/region parameters.
3130 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3131 let (generator_def_id, substs) = match self_ty.kind {
3132 ty::Generator(id, substs, _) => (id, substs),
3133 _ => bug!("closure candidate for non-closure {:?}", obligation),
3136 debug!("confirm_generator_candidate({:?},{:?},{:?})", obligation, generator_def_id, substs);
3138 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3139 let Normalized { value: trait_ref, mut obligations } = normalize_with_depth(
3141 obligation.param_env,
3142 obligation.cause.clone(),
3143 obligation.recursion_depth + 1,
3148 "confirm_generator_candidate(generator_def_id={:?}, \
3149 trait_ref={:?}, obligations={:?})",
3150 generator_def_id, trait_ref, obligations
3153 obligations.extend(self.confirm_poly_trait_refs(
3154 obligation.cause.clone(),
3155 obligation.param_env,
3156 obligation.predicate.to_poly_trait_ref(),
3160 Ok(VtableGeneratorData { generator_def_id, substs, nested: obligations })
3163 fn confirm_closure_candidate(
3165 obligation: &TraitObligation<'tcx>,
3166 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3167 debug!("confirm_closure_candidate({:?})", obligation);
3172 .fn_trait_kind(obligation.predicate.def_id())
3173 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3175 // Okay to skip binder because the substs on closure types never
3176 // touch bound regions, they just capture the in-scope
3177 // type/region parameters.
3178 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3179 let (closure_def_id, substs) = match self_ty.kind {
3180 ty::Closure(id, substs) => (id, substs),
3181 _ => bug!("closure candidate for non-closure {:?}", obligation),
3184 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3185 let Normalized { value: trait_ref, mut obligations } = normalize_with_depth(
3187 obligation.param_env,
3188 obligation.cause.clone(),
3189 obligation.recursion_depth + 1,
3194 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3195 closure_def_id, trait_ref, obligations
3198 obligations.extend(self.confirm_poly_trait_refs(
3199 obligation.cause.clone(),
3200 obligation.param_env,
3201 obligation.predicate.to_poly_trait_ref(),
3207 if !self.tcx().sess.opts.debugging_opts.chalk {
3208 obligations.push(Obligation::new(
3209 obligation.cause.clone(),
3210 obligation.param_env,
3211 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3215 Ok(VtableClosureData { closure_def_id, substs: substs, nested: obligations })
3218 /// In the case of closure types and fn pointers,
3219 /// we currently treat the input type parameters on the trait as
3220 /// outputs. This means that when we have a match we have only
3221 /// considered the self type, so we have to go back and make sure
3222 /// to relate the argument types too. This is kind of wrong, but
3223 /// since we control the full set of impls, also not that wrong,
3224 /// and it DOES yield better error messages (since we don't report
3225 /// errors as if there is no applicable impl, but rather report
3226 /// errors are about mismatched argument types.
3228 /// Here is an example. Imagine we have a closure expression
3229 /// and we desugared it so that the type of the expression is
3230 /// `Closure`, and `Closure` expects an int as argument. Then it
3231 /// is "as if" the compiler generated this impl:
3233 /// impl Fn(int) for Closure { ... }
3235 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3236 /// we have matched the self type `Closure`. At this point we'll
3237 /// compare the `int` to `usize` and generate an error.
3239 /// Note that this checking occurs *after* the impl has selected,
3240 /// because these output type parameters should not affect the
3241 /// selection of the impl. Therefore, if there is a mismatch, we
3242 /// report an error to the user.
3243 fn confirm_poly_trait_refs(
3245 obligation_cause: ObligationCause<'tcx>,
3246 obligation_param_env: ty::ParamEnv<'tcx>,
3247 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3248 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3249 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3250 let obligation_trait_ref = obligation_trait_ref.clone();
3252 .at(&obligation_cause, obligation_param_env)
3253 .sup(obligation_trait_ref, expected_trait_ref)
3254 .map(|InferOk { obligations, .. }| obligations)
3255 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3258 fn confirm_builtin_unsize_candidate(
3260 obligation: &TraitObligation<'tcx>,
3261 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3262 let tcx = self.tcx();
3264 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
3265 // regions here. See the comment there for more details.
3266 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3267 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
3268 let target = self.infcx.shallow_resolve(target);
3270 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})", source, target);
3272 let mut nested = vec![];
3273 match (&source.kind, &target.kind) {
3274 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3275 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3276 // See `assemble_candidates_for_unsizing` for more info.
3277 let existential_predicates = data_a.map_bound(|data_a| {
3280 .map(|x| ty::ExistentialPredicate::Trait(x))
3284 .projection_bounds()
3285 .map(|x| ty::ExistentialPredicate::Projection(x)),
3287 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
3288 tcx.mk_existential_predicates(iter)
3290 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
3292 // Require that the traits involved in this upcast are **equal**;
3293 // only the **lifetime bound** is changed.
3295 // FIXME: This condition is arguably too strong -- it would
3296 // suffice for the source trait to be a *subtype* of the target
3297 // trait. In particular, changing from something like
3298 // `for<'a, 'b> Foo<'a, 'b>` to `for<'a> Foo<'a, 'a>` should be
3299 // permitted. And, indeed, in the in commit
3300 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3301 // condition was loosened. However, when the leak check was
3302 // added back, using subtype here actually guides the coercion
3303 // code in such a way that it accepts `old-lub-glb-object.rs`.
3304 // This is probably a good thing, but I've modified this to `.eq`
3305 // because I want to continue rejecting that test (as we have
3306 // done for quite some time) before we are firmly comfortable
3307 // with what our behavior should be there. -nikomatsakis
3308 let InferOk { obligations, .. } = self
3310 .at(&obligation.cause, obligation.param_env)
3311 .eq(target, source_trait) // FIXME -- see below
3312 .map_err(|_| Unimplemented)?;
3313 nested.extend(obligations);
3315 // Register one obligation for 'a: 'b.
3316 let cause = ObligationCause::new(
3317 obligation.cause.span,
3318 obligation.cause.body_id,
3319 ObjectCastObligation(target),
3321 let outlives = ty::OutlivesPredicate(r_a, r_b);
3322 nested.push(Obligation::with_depth(
3324 obligation.recursion_depth + 1,
3325 obligation.param_env,
3326 ty::Binder::bind(outlives).to_predicate(),
3331 (_, &ty::Dynamic(ref data, r)) => {
3332 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
3333 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3334 return Err(TraitNotObjectSafe(did));
3337 let cause = ObligationCause::new(
3338 obligation.cause.span,
3339 obligation.cause.body_id,
3340 ObjectCastObligation(target),
3343 let predicate_to_obligation = |predicate| {
3344 Obligation::with_depth(
3346 obligation.recursion_depth + 1,
3347 obligation.param_env,
3352 // Create obligations:
3353 // - Casting `T` to `Trait`
3354 // - For all the various builtin bounds attached to the object cast. (In other
3355 // words, if the object type is `Foo + Send`, this would create an obligation for
3356 // the `Send` check.)
3357 // - Projection predicates
3359 data.iter().map(|predicate| {
3360 predicate_to_obligation(predicate.with_self_ty(tcx, source))
3364 // We can only make objects from sized types.
3365 let tr = ty::TraitRef::new(
3366 tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
3367 tcx.mk_substs_trait(source, &[]),
3369 nested.push(predicate_to_obligation(tr.to_predicate()));
3371 // If the type is `Foo + 'a`, ensure that the type
3372 // being cast to `Foo + 'a` outlives `'a`:
3373 let outlives = ty::OutlivesPredicate(source, r);
3374 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate()));
3377 // `[T; n]` -> `[T]`
3378 (&ty::Array(a, _), &ty::Slice(b)) => {
3379 let InferOk { obligations, .. } = self
3381 .at(&obligation.cause, obligation.param_env)
3383 .map_err(|_| Unimplemented)?;
3384 nested.extend(obligations);
3387 // `Struct<T>` -> `Struct<U>`
3388 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3390 def.all_fields().map(|field| tcx.type_of(field.did)).collect::<Vec<_>>();
3392 // The last field of the structure has to exist and contain type parameters.
3393 let field = if let Some(&field) = fields.last() {
3396 return Err(Unimplemented);
3398 let mut ty_params = GrowableBitSet::new_empty();
3399 let mut found = false;
3400 for ty in field.walk() {
3401 if let ty::Param(p) = ty.kind {
3402 ty_params.insert(p.index as usize);
3407 return Err(Unimplemented);
3410 // Replace type parameters used in unsizing with
3411 // Error and ensure they do not affect any other fields.
3412 // This could be checked after type collection for any struct
3413 // with a potentially unsized trailing field.
3414 let params = substs_a
3417 .map(|(i, &k)| if ty_params.contains(i) { tcx.types.err.into() } else { k });
3418 let substs = tcx.mk_substs(params);
3419 for &ty in fields.split_last().unwrap().1 {
3420 if ty.subst(tcx, substs).references_error() {
3421 return Err(Unimplemented);
3425 // Extract `Field<T>` and `Field<U>` from `Struct<T>` and `Struct<U>`.
3426 let inner_source = field.subst(tcx, substs_a);
3427 let inner_target = field.subst(tcx, substs_b);
3429 // Check that the source struct with the target's
3430 // unsized parameters is equal to the target.
3431 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3432 if ty_params.contains(i) { substs_b.type_at(i).into() } else { k }
3434 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3435 let InferOk { obligations, .. } = self
3437 .at(&obligation.cause, obligation.param_env)
3438 .eq(target, new_struct)
3439 .map_err(|_| Unimplemented)?;
3440 nested.extend(obligations);
3442 // Construct the nested `Field<T>: Unsize<Field<U>>` predicate.
3443 nested.push(predicate_for_trait_def(
3445 obligation.param_env,
3446 obligation.cause.clone(),
3447 obligation.predicate.def_id(),
3448 obligation.recursion_depth + 1,
3450 &[inner_target.into()],
3454 // `(.., T)` -> `(.., U)`
3455 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3456 assert_eq!(tys_a.len(), tys_b.len());
3458 // The last field of the tuple has to exist.
3459 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3462 return Err(Unimplemented);
3464 let &b_last = tys_b.last().unwrap();
3466 // Check that the source tuple with the target's
3467 // last element is equal to the target.
3468 let new_tuple = tcx.mk_tup(
3469 a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3471 let InferOk { obligations, .. } = self
3473 .at(&obligation.cause, obligation.param_env)
3474 .eq(target, new_tuple)
3475 .map_err(|_| Unimplemented)?;
3476 nested.extend(obligations);
3478 // Construct the nested `T: Unsize<U>` predicate.
3479 nested.push(predicate_for_trait_def(
3481 obligation.param_env,
3482 obligation.cause.clone(),
3483 obligation.predicate.def_id(),
3484 obligation.recursion_depth + 1,
3493 Ok(VtableBuiltinData { nested })
3496 ///////////////////////////////////////////////////////////////////////////
3499 // Matching is a common path used for both evaluation and
3500 // confirmation. It basically unifies types that appear in impls
3501 // and traits. This does affect the surrounding environment;
3502 // therefore, when used during evaluation, match routines must be
3503 // run inside of a `probe()` so that their side-effects are
3509 obligation: &TraitObligation<'tcx>,
3510 snapshot: &CombinedSnapshot<'_, 'tcx>,
3511 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3512 match self.match_impl(impl_def_id, obligation, snapshot) {
3513 Ok(substs) => substs,
3516 "Impl {:?} was matchable against {:?} but now is not",
3527 obligation: &TraitObligation<'tcx>,
3528 snapshot: &CombinedSnapshot<'_, 'tcx>,
3529 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3530 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3532 // Before we create the substitutions and everything, first
3533 // consider a "quick reject". This avoids creating more types
3534 // and so forth that we need to.
3535 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3539 let (skol_obligation, placeholder_map) =
3540 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
3541 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3543 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
3545 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3547 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
3548 project::normalize_with_depth(
3550 obligation.param_env,
3551 obligation.cause.clone(),
3552 obligation.recursion_depth + 1,
3557 "match_impl(impl_def_id={:?}, obligation={:?}, \
3558 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3559 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3562 let InferOk { obligations, .. } = self
3564 .at(&obligation.cause, obligation.param_env)
3565 .eq(skol_obligation_trait_ref, impl_trait_ref)
3566 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3567 nested_obligations.extend(obligations);
3569 if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3570 debug!("match_impl: failed leak check due to `{}`", e);
3574 if self.intercrate.is_none()
3575 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
3577 debug!("match_impl: reservation impls only apply in intercrate mode");
3581 debug!("match_impl: success impl_substs={:?}", impl_substs);
3582 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
3585 fn fast_reject_trait_refs(
3587 obligation: &TraitObligation<'_>,
3588 impl_trait_ref: &ty::TraitRef<'_>,
3590 // We can avoid creating type variables and doing the full
3591 // substitution if we find that any of the input types, when
3592 // simplified, do not match.
3594 obligation.predicate.skip_binder().input_types().zip(impl_trait_ref.input_types()).any(
3595 |(obligation_ty, impl_ty)| {
3596 let simplified_obligation_ty =
3597 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3598 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3600 simplified_obligation_ty.is_some()
3601 && simplified_impl_ty.is_some()
3602 && simplified_obligation_ty != simplified_impl_ty
3607 /// Normalize `where_clause_trait_ref` and try to match it against
3608 /// `obligation`. If successful, return any predicates that
3609 /// result from the normalization. Normalization is necessary
3610 /// because where-clauses are stored in the parameter environment
3612 fn match_where_clause_trait_ref(
3614 obligation: &TraitObligation<'tcx>,
3615 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3616 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3617 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3620 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3621 /// obligation is satisfied.
3622 fn match_poly_trait_ref(
3624 obligation: &TraitObligation<'tcx>,
3625 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3626 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3628 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3629 obligation, poly_trait_ref
3633 .at(&obligation.cause, obligation.param_env)
3634 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3635 .map(|InferOk { obligations, .. }| obligations)
3639 ///////////////////////////////////////////////////////////////////////////
3642 fn match_fresh_trait_refs(
3644 previous: &ty::PolyTraitRef<'tcx>,
3645 current: &ty::PolyTraitRef<'tcx>,
3646 param_env: ty::ParamEnv<'tcx>,
3648 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
3649 matcher.relate(previous, current).is_ok()
3654 previous_stack: TraitObligationStackList<'o, 'tcx>,
3655 obligation: &'o TraitObligation<'tcx>,
3656 ) -> TraitObligationStack<'o, 'tcx> {
3657 let fresh_trait_ref =
3658 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3660 let dfn = previous_stack.cache.next_dfn();
3661 let depth = previous_stack.depth() + 1;
3662 TraitObligationStack {
3665 reached_depth: Cell::new(depth),
3666 previous: previous_stack,
3672 fn closure_trait_ref_unnormalized(
3674 obligation: &TraitObligation<'tcx>,
3675 closure_def_id: DefId,
3676 substs: SubstsRef<'tcx>,
3677 ) -> ty::PolyTraitRef<'tcx> {
3679 "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3680 obligation, closure_def_id, substs,
3682 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3684 debug!("closure_trait_ref_unnormalized: closure_type = {:?}", closure_type);
3686 // (1) Feels icky to skip the binder here, but OTOH we know
3687 // that the self-type is an unboxed closure type and hence is
3688 // in fact unparameterized (or at least does not reference any
3689 // regions bound in the obligation). Still probably some
3690 // refactoring could make this nicer.
3691 closure_trait_ref_and_return_type(
3693 obligation.predicate.def_id(),
3694 obligation.predicate.skip_binder().self_ty(), // (1)
3696 util::TupleArgumentsFlag::No,
3698 .map_bound(|(trait_ref, _)| trait_ref)
3701 fn generator_trait_ref_unnormalized(
3703 obligation: &TraitObligation<'tcx>,
3704 closure_def_id: DefId,
3705 substs: SubstsRef<'tcx>,
3706 ) -> ty::PolyTraitRef<'tcx> {
3707 let gen_sig = substs.as_generator().poly_sig(closure_def_id, self.tcx());
3709 // (1) Feels icky to skip the binder here, but OTOH we know
3710 // that the self-type is an generator type and hence is
3711 // in fact unparameterized (or at least does not reference any
3712 // regions bound in the obligation). Still probably some
3713 // refactoring could make this nicer.
3715 super::util::generator_trait_ref_and_outputs(
3717 obligation.predicate.def_id(),
3718 obligation.predicate.skip_binder().self_ty(), // (1)
3721 .map_bound(|(trait_ref, ..)| trait_ref)
3724 /// Returns the obligations that are implied by instantiating an
3725 /// impl or trait. The obligations are substituted and fully
3726 /// normalized. This is used when confirming an impl or default
3728 fn impl_or_trait_obligations(
3730 cause: ObligationCause<'tcx>,
3731 recursion_depth: usize,
3732 param_env: ty::ParamEnv<'tcx>,
3733 def_id: DefId, // of impl or trait
3734 substs: SubstsRef<'tcx>, // for impl or trait
3735 ) -> Vec<PredicateObligation<'tcx>> {
3736 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3737 let tcx = self.tcx();
3739 // To allow for one-pass evaluation of the nested obligation,
3740 // each predicate must be preceded by the obligations required
3742 // for example, if we have:
3743 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
3744 // the impl will have the following predicates:
3745 // <V as Iterator>::Item = U,
3746 // U: Iterator, U: Sized,
3747 // V: Iterator, V: Sized,
3748 // <U as Iterator>::Item: Copy
3749 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3750 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3751 // `$1: Copy`, so we must ensure the obligations are emitted in
3753 let predicates = tcx.predicates_of(def_id);
3754 assert_eq!(predicates.parent, None);
3755 let mut predicates: Vec<_> = predicates
3758 .flat_map(|(predicate, _)| {
3759 let predicate = normalize_with_depth(
3764 &predicate.subst(tcx, substs),
3766 predicate.obligations.into_iter().chain(Some(Obligation {
3767 cause: cause.clone(),
3770 predicate: predicate.value,
3775 // We are performing deduplication here to avoid exponential blowups
3776 // (#38528) from happening, but the real cause of the duplication is
3777 // unknown. What we know is that the deduplication avoids exponential
3778 // amount of predicates being propagated when processing deeply nested
3781 // This code is hot enough that it's worth avoiding the allocation
3782 // required for the FxHashSet when possible. Special-casing lengths 0,
3783 // 1 and 2 covers roughly 75-80% of the cases.
3784 if predicates.len() <= 1 {
3785 // No possibility of duplicates.
3786 } else if predicates.len() == 2 {
3787 // Only two elements. Drop the second if they are equal.
3788 if predicates[0] == predicates[1] {
3789 predicates.truncate(1);
3792 // Three or more elements. Use a general deduplication process.
3793 let mut seen = FxHashSet::default();
3794 predicates.retain(|i| seen.insert(i.clone()));
3801 impl<'tcx> TraitObligation<'tcx> {
3802 #[allow(unused_comparisons)]
3803 pub fn derived_cause(
3805 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3806 ) -> ObligationCause<'tcx> {
3808 * Creates a cause for obligations that are derived from
3809 * `obligation` by a recursive search (e.g., for a builtin
3810 * bound, or eventually a `auto trait Foo`). If `obligation`
3811 * is itself a derived obligation, this is just a clone, but
3812 * otherwise we create a "derived obligation" cause so as to
3813 * keep track of the original root obligation for error
3817 let obligation = self;
3819 // NOTE(flaper87): As of now, it keeps track of the whole error
3820 // chain. Ideally, we should have a way to configure this either
3821 // by using -Z verbose or just a CLI argument.
3822 let derived_cause = DerivedObligationCause {
3823 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3824 parent_code: Rc::new(obligation.cause.code.clone()),
3826 let derived_code = variant(derived_cause);
3827 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3831 impl<'tcx> SelectionCache<'tcx> {
3832 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3833 pub fn clear(&self) {
3834 *self.hashmap.borrow_mut() = Default::default();
3838 impl<'tcx> EvaluationCache<'tcx> {
3839 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3840 pub fn clear(&self) {
3841 *self.hashmap.borrow_mut() = Default::default();
3845 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
3846 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3847 TraitObligationStackList::with(self)
3850 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
3854 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3858 /// Indicates that attempting to evaluate this stack entry
3859 /// required accessing something from the stack at depth `reached_depth`.
3860 fn update_reached_depth(&self, reached_depth: usize) {
3862 self.depth > reached_depth,
3863 "invoked `update_reached_depth` with something under this stack: \
3864 self.depth={} reached_depth={}",
3868 debug!("update_reached_depth(reached_depth={})", reached_depth);
3870 while reached_depth < p.depth {
3871 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
3872 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
3873 p = p.previous.head.unwrap();
3878 /// The "provisional evaluation cache" is used to store intermediate cache results
3879 /// when solving auto traits. Auto traits are unusual in that they can support
3880 /// cycles. So, for example, a "proof tree" like this would be ok:
3882 /// - `Foo<T>: Send` :-
3883 /// - `Bar<T>: Send` :-
3884 /// - `Foo<T>: Send` -- cycle, but ok
3885 /// - `Baz<T>: Send`
3887 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
3888 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
3889 /// For non-auto traits, this cycle would be an error, but for auto traits (because
3890 /// they are coinductive) it is considered ok.
3892 /// However, there is a complication: at the point where we have
3893 /// "proven" `Bar<T>: Send`, we have in fact only proven it
3894 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
3895 /// *under the assumption* that `Foo<T>: Send`. But what if we later
3896 /// find out this assumption is wrong? Specifically, we could
3897 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
3898 /// `Bar<T>: Send` didn't turn out to be true.
3900 /// In Issue #60010, we found a bug in rustc where it would cache
3901 /// these intermediate results. This was fixed in #60444 by disabling
3902 /// *all* caching for things involved in a cycle -- in our example,
3903 /// that would mean we don't cache that `Bar<T>: Send`. But this led
3904 /// to large slowdowns.
3906 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
3907 /// first requires proving `Bar<T>: Send` (which is true:
3909 /// - `Foo<T>: Send` :-
3910 /// - `Bar<T>: Send` :-
3911 /// - `Foo<T>: Send` -- cycle, but ok
3912 /// - `Baz<T>: Send`
3913 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
3914 /// - `*const T: Send` -- but what if we later encounter an error?
3916 /// The *provisional evaluation cache* resolves this issue. It stores
3917 /// cache results that we've proven but which were involved in a cycle
3918 /// in some way. We track the minimal stack depth (i.e., the
3919 /// farthest from the top of the stack) that we are dependent on.
3920 /// The idea is that the cache results within are all valid -- so long as
3921 /// none of the nodes in between the current node and the node at that minimum
3922 /// depth result in an error (in which case the cached results are just thrown away).
3924 /// During evaluation, we consult this provisional cache and rely on
3925 /// it. Accessing a cached value is considered equivalent to accessing
3926 /// a result at `reached_depth`, so it marks the *current* solution as
3927 /// provisional as well. If an error is encountered, we toss out any
3928 /// provisional results added from the subtree that encountered the
3929 /// error. When we pop the node at `reached_depth` from the stack, we
3930 /// can commit all the things that remain in the provisional cache.
3931 struct ProvisionalEvaluationCache<'tcx> {
3932 /// next "depth first number" to issue -- just a counter
3935 /// Stores the "coldest" depth (bottom of stack) reached by any of
3936 /// the evaluation entries. The idea here is that all things in the provisional
3937 /// cache are always dependent on *something* that is colder in the stack:
3938 /// therefore, if we add a new entry that is dependent on something *colder still*,
3939 /// we have to modify the depth for all entries at once.
3943 /// Imagine we have a stack `A B C D E` (with `E` being the top of
3944 /// the stack). We cache something with depth 2, which means that
3945 /// it was dependent on C. Then we pop E but go on and process a
3946 /// new node F: A B C D F. Now F adds something to the cache with
3947 /// depth 1, meaning it is dependent on B. Our original cache
3948 /// entry is also dependent on B, because there is a path from E
3949 /// to C and then from C to F and from F to B.
3950 reached_depth: Cell<usize>,
3952 /// Map from cache key to the provisionally evaluated thing.
3953 /// The cache entries contain the result but also the DFN in which they
3954 /// were added. The DFN is used to clear out values on failure.
3956 /// Imagine we have a stack like:
3958 /// - `A B C` and we add a cache for the result of C (DFN 2)
3959 /// - Then we have a stack `A B D` where `D` has DFN 3
3960 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
3961 /// - `E` generates various cache entries which have cyclic dependices on `B`
3962 /// - `A B D E F` and so forth
3963 /// - the DFN of `F` for example would be 5
3964 /// - then we determine that `E` is in error -- we will then clear
3965 /// all cache values whose DFN is >= 4 -- in this case, that
3966 /// means the cached value for `F`.
3967 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
3970 /// A cache value for the provisional cache: contains the depth-first
3971 /// number (DFN) and result.
3972 #[derive(Copy, Clone, Debug)]
3973 struct ProvisionalEvaluation {
3975 result: EvaluationResult,
3978 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
3979 fn default() -> Self {
3982 reached_depth: Cell::new(std::usize::MAX),
3983 map: Default::default(),
3988 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
3989 /// Get the next DFN in sequence (basically a counter).
3990 fn next_dfn(&self) -> usize {
3991 let result = self.dfn.get();
3992 self.dfn.set(result + 1);
3996 /// Check the provisional cache for any result for
3997 /// `fresh_trait_ref`. If there is a hit, then you must consider
3998 /// it an access to the stack slots at depth
3999 /// `self.current_reached_depth()` and above.
4000 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
4002 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
4004 self.map.borrow().get(&fresh_trait_ref),
4005 self.reached_depth.get(),
4007 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
4010 /// Current value of the `reached_depth` counter -- all the
4011 /// provisional cache entries are dependent on the item at this
4013 fn current_reached_depth(&self) -> usize {
4014 self.reached_depth.get()
4017 /// Insert a provisional result into the cache. The result came
4018 /// from the node with the given DFN. It accessed a minimum depth
4019 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
4020 /// and resulted in `result`.
4021 fn insert_provisional(
4024 reached_depth: usize,
4025 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
4026 result: EvaluationResult,
4029 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
4030 from_dfn, reached_depth, fresh_trait_ref, result,
4032 let r_d = self.reached_depth.get();
4033 self.reached_depth.set(r_d.min(reached_depth));
4035 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
4037 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
4040 /// Invoked when the node with dfn `dfn` does not get a successful
4041 /// result. This will clear out any provisional cache entries
4042 /// that were added since `dfn` was created. This is because the
4043 /// provisional entries are things which must assume that the
4044 /// things on the stack at the time of their creation succeeded --
4045 /// since the failing node is presently at the top of the stack,
4046 /// these provisional entries must either depend on it or some
4048 fn on_failure(&self, dfn: usize) {
4049 debug!("on_failure(dfn={:?})", dfn,);
4050 self.map.borrow_mut().retain(|key, eval| {
4051 if !eval.from_dfn >= dfn {
4052 debug!("on_failure: removing {:?}", key);
4060 /// Invoked when the node at depth `depth` completed without
4061 /// depending on anything higher in the stack (if that completion
4062 /// was a failure, then `on_failure` should have been invoked
4063 /// already). The callback `op` will be invoked for each
4064 /// provisional entry that we can now confirm.
4068 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
4070 debug!("on_completion(depth={}, reached_depth={})", depth, self.reached_depth.get(),);
4072 if self.reached_depth.get() < depth {
4073 debug!("on_completion: did not yet reach depth to complete");
4077 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
4078 debug!("on_completion: fresh_trait_ref={:?} eval={:?}", fresh_trait_ref, eval,);
4080 op(fresh_trait_ref, eval.result);
4083 self.reached_depth.set(std::usize::MAX);
4087 #[derive(Copy, Clone)]
4088 struct TraitObligationStackList<'o, 'tcx> {
4089 cache: &'o ProvisionalEvaluationCache<'tcx>,
4090 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
4093 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
4094 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4095 TraitObligationStackList { cache, head: None }
4098 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4099 TraitObligationStackList { cache: r.cache(), head: Some(r) }
4102 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4106 fn depth(&self) -> usize {
4107 if let Some(head) = self.head { head.depth } else { 0 }
4111 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
4112 type Item = &'o TraitObligationStack<'o, 'tcx>;
4114 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4125 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
4126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4127 write!(f, "TraitObligationStack({:?})", self.obligation)
4131 #[derive(Clone, Eq, PartialEq)]
4132 pub struct WithDepNode<T> {
4133 dep_node: DepNodeIndex,
4137 impl<T: Clone> WithDepNode<T> {
4138 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
4139 WithDepNode { dep_node, cached_value }
4142 pub fn get(&self, tcx: TyCtxt<'_>) -> T {
4143 tcx.dep_graph.read_index(self.dep_node);
4144 self.cached_value.clone()