1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See [rustc guide] for more info on how this works.
13 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#selection
15 use self::EvaluationResult::*;
16 use self::SelectionCandidate::*;
18 use super::coherence::{self, Conflict};
20 use super::project::{normalize_with_depth, Normalized, ProjectionCacheKey};
22 use super::DerivedObligationCause;
24 use super::SelectionResult;
25 use super::TraitNotObjectSafe;
26 use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
27 use super::{IntercrateMode, TraitQueryMode};
28 use super::{ObjectCastObligation, Obligation};
29 use super::{ObligationCause, PredicateObligation, TraitObligation};
30 use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
32 VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
33 VtableObject, VtableParam,
36 VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
37 VtableGeneratorData, VtableImplData, VtableObjectData,
40 use dep_graph::{DepKind, DepNodeIndex};
41 use hir::def_id::DefId;
43 use infer::{InferCtxt, InferOk, TypeFreshener};
44 use middle::lang_items;
45 use mir::interpret::GlobalId;
47 use ty::relate::TypeRelation;
48 use ty::subst::{Subst, Substs};
49 use ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
52 use rustc_data_structures::bit_set::GrowableBitSet;
53 use rustc_data_structures::sync::Lock;
54 use rustc_target::spec::abi::Abi;
60 use util::nodemap::{FxHashMap, FxHashSet};
62 pub struct SelectionContext<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> {
63 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
65 /// Freshener used specifically for entries on the obligation
66 /// stack. This ensures that all entries on the stack at one time
67 /// will have the same set of placeholder entries, which is
68 /// important for checking for trait bounds that recursively
69 /// require themselves.
70 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
72 /// If true, indicates that the evaluation should be conservative
73 /// and consider the possibility of types outside this crate.
74 /// This comes up primarily when resolving ambiguity. Imagine
75 /// there is some trait reference `$0 : Bar` where `$0` is an
76 /// inference variable. If `intercrate` is true, then we can never
77 /// say for sure that this reference is not implemented, even if
78 /// there are *no impls at all for `Bar`*, because `$0` could be
79 /// bound to some type that in a downstream crate that implements
80 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
81 /// though, we set this to false, because we are only interested
82 /// in types that the user could actually have written --- in
83 /// other words, we consider `$0 : Bar` to be unimplemented if
84 /// there is no type that the user could *actually name* that
85 /// would satisfy it. This avoids crippling inference, basically.
86 intercrate: Option<IntercrateMode>,
88 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
90 /// Controls whether or not to filter out negative impls when selecting.
91 /// This is used in librustdoc to distinguish between the lack of an impl
92 /// and a negative impl
93 allow_negative_impls: bool,
95 /// The mode that trait queries run in, which informs our error handling
96 /// policy. In essence, canonicalized queries need their errors propagated
97 /// rather than immediately reported because we do not have accurate spans.
98 query_mode: TraitQueryMode,
101 #[derive(Clone, Debug)]
102 pub enum IntercrateAmbiguityCause {
105 self_desc: Option<String>,
107 UpstreamCrateUpdate {
109 self_desc: Option<String>,
113 impl IntercrateAmbiguityCause {
114 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
115 /// See #23980 for details.
116 pub fn add_intercrate_ambiguity_hint<'a, 'tcx>(
118 err: &mut ::errors::DiagnosticBuilder<'_>,
120 err.note(&self.intercrate_ambiguity_hint());
123 pub fn intercrate_ambiguity_hint(&self) -> String {
125 &IntercrateAmbiguityCause::DownstreamCrate {
129 let self_desc = if let &Some(ref ty) = self_desc {
130 format!(" for type `{}`", ty)
135 "downstream crates may implement trait `{}`{}",
136 trait_desc, self_desc
139 &IntercrateAmbiguityCause::UpstreamCrateUpdate {
143 let self_desc = if let &Some(ref ty) = self_desc {
144 format!(" for type `{}`", ty)
149 "upstream crates may add new impl of trait `{}`{} \
151 trait_desc, self_desc
158 // A stack that walks back up the stack frame.
159 struct TraitObligationStack<'prev, 'tcx: 'prev> {
160 obligation: &'prev TraitObligation<'tcx>,
162 /// Trait ref from `obligation` but "freshened" with the
163 /// selection-context's freshener. Used to check for recursion.
164 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
166 previous: TraitObligationStackList<'prev, 'tcx>,
169 #[derive(Clone, Default)]
170 pub struct SelectionCache<'tcx> {
172 FxHashMap<ty::TraitRef<'tcx>, WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
176 /// The selection process begins by considering all impls, where
177 /// clauses, and so forth that might resolve an obligation. Sometimes
178 /// we'll be able to say definitively that (e.g.) an impl does not
179 /// apply to the obligation: perhaps it is defined for `usize` but the
180 /// obligation is for `int`. In that case, we drop the impl out of the
181 /// list. But the other cases are considered *candidates*.
183 /// For selection to succeed, there must be exactly one matching
184 /// candidate. If the obligation is fully known, this is guaranteed
185 /// by coherence. However, if the obligation contains type parameters
186 /// or variables, there may be multiple such impls.
188 /// It is not a real problem if multiple matching impls exist because
189 /// of type variables - it just means the obligation isn't sufficiently
190 /// elaborated. In that case we report an ambiguity, and the caller can
191 /// try again after more type information has been gathered or report a
192 /// "type annotations required" error.
194 /// However, with type parameters, this can be a real problem - type
195 /// parameters don't unify with regular types, but they *can* unify
196 /// with variables from blanket impls, and (unless we know its bounds
197 /// will always be satisfied) picking the blanket impl will be wrong
198 /// for at least *some* substitutions. To make this concrete, if we have
200 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
201 /// impl<T: fmt::Debug> AsDebug for T {
203 /// fn debug(self) -> fmt::Debug { self }
205 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
207 /// we can't just use the impl to resolve the <T as AsDebug> obligation
208 /// - a type from another crate (that doesn't implement fmt::Debug) could
209 /// implement AsDebug.
211 /// Because where-clauses match the type exactly, multiple clauses can
212 /// only match if there are unresolved variables, and we can mostly just
213 /// report this ambiguity in that case. This is still a problem - we can't
214 /// *do anything* with ambiguities that involve only regions. This is issue
217 /// If a single where-clause matches and there are no inference
218 /// variables left, then it definitely matches and we can just select
221 /// In fact, we even select the where-clause when the obligation contains
222 /// inference variables. The can lead to inference making "leaps of logic",
223 /// for example in this situation:
225 /// pub trait Foo<T> { fn foo(&self) -> T; }
226 /// impl<T> Foo<()> for T { fn foo(&self) { } }
227 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
229 /// pub fn foo<T>(t: T) where T: Foo<bool> {
230 /// println!("{:?}", <T as Foo<_>>::foo(&t));
232 /// fn main() { foo(false); }
234 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
235 /// impl and the where-clause. We select the where-clause and unify $0=bool,
236 /// so the program prints "false". However, if the where-clause is omitted,
237 /// the blanket impl is selected, we unify $0=(), and the program prints
240 /// Exactly the same issues apply to projection and object candidates, except
241 /// that we can have both a projection candidate and a where-clause candidate
242 /// for the same obligation. In that case either would do (except that
243 /// different "leaps of logic" would occur if inference variables are
244 /// present), and we just pick the where-clause. This is, for example,
245 /// required for associated types to work in default impls, as the bounds
246 /// are visible both as projection bounds and as where-clauses from the
247 /// parameter environment.
248 #[derive(PartialEq, Eq, Debug, Clone)]
249 enum SelectionCandidate<'tcx> {
250 /// If has_nested is false, there are no *further* obligations
254 ParamCandidate(ty::PolyTraitRef<'tcx>),
255 ImplCandidate(DefId),
256 AutoImplCandidate(DefId),
258 /// This is a trait matching with a projected type as `Self`, and
259 /// we found an applicable bound in the trait definition.
262 /// Implementation of a `Fn`-family trait by one of the anonymous types
263 /// generated for a `||` expression.
266 /// Implementation of a `Generator` trait by one of the anonymous types
267 /// generated for a generator.
270 /// Implementation of a `Fn`-family trait by one of the anonymous
271 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
276 BuiltinObjectCandidate,
278 BuiltinUnsizeCandidate,
281 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
282 type Lifted = SelectionCandidate<'tcx>;
283 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
285 BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
286 ImplCandidate(def_id) => ImplCandidate(def_id),
287 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
288 ProjectionCandidate => ProjectionCandidate,
289 FnPointerCandidate => FnPointerCandidate,
290 ObjectCandidate => ObjectCandidate,
291 BuiltinObjectCandidate => BuiltinObjectCandidate,
292 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
293 ClosureCandidate => ClosureCandidate,
294 GeneratorCandidate => GeneratorCandidate,
296 ParamCandidate(ref trait_ref) => {
297 return tcx.lift(trait_ref).map(ParamCandidate);
303 struct SelectionCandidateSet<'tcx> {
304 // a list of candidates that definitely apply to the current
305 // obligation (meaning: types unify).
306 vec: Vec<SelectionCandidate<'tcx>>,
308 // if this is true, then there were candidates that might or might
309 // not have applied, but we couldn't tell. This occurs when some
310 // of the input types are type variables, in which case there are
311 // various "builtin" rules that might or might not trigger.
315 #[derive(PartialEq, Eq, Debug, Clone)]
316 struct EvaluatedCandidate<'tcx> {
317 candidate: SelectionCandidate<'tcx>,
318 evaluation: EvaluationResult,
321 /// When does the builtin impl for `T: Trait` apply?
322 enum BuiltinImplConditions<'tcx> {
323 /// The impl is conditional on T1,T2,.. : Trait
324 Where(ty::Binder<Vec<Ty<'tcx>>>),
325 /// There is no built-in impl. There may be some other
326 /// candidate (a where-clause or user-defined impl).
328 /// It is unknown whether there is an impl.
332 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
333 /// The result of trait evaluation. The order is important
334 /// here as the evaluation of a list is the maximum of the
337 /// The evaluation results are ordered:
338 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
339 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
340 /// - the "union" of evaluation results is equal to their maximum -
341 /// all the "potential success" candidates can potentially succeed,
342 /// so they are no-ops when unioned with a definite error, and within
343 /// the categories it's easy to see that the unions are correct.
344 pub enum EvaluationResult {
345 /// Evaluation successful
347 /// Evaluation is known to be ambiguous - it *might* hold for some
348 /// assignment of inference variables, but it might not.
350 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
351 /// know whether this obligation holds or not - it is the result we
352 /// would get with an empty stack, and therefore is cacheable.
354 /// Evaluation failed because of recursion involving inference
355 /// variables. We are somewhat imprecise there, so we don't actually
356 /// know the real result.
358 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
360 /// Evaluation failed because we encountered an obligation we are already
361 /// trying to prove on this branch.
363 /// We know this branch can't be a part of a minimal proof-tree for
364 /// the "root" of our cycle, because then we could cut out the recursion
365 /// and maintain a valid proof tree. However, this does not mean
366 /// that all the obligations on this branch do not hold - it's possible
367 /// that we entered this branch "speculatively", and that there
368 /// might be some other way to prove this obligation that does not
369 /// go through this cycle - so we can't cache this as a failure.
371 /// For example, suppose we have this:
373 /// ```rust,ignore (pseudo-Rust)
374 /// pub trait Trait { fn xyz(); }
375 /// // This impl is "useless", but we can still have
376 /// // an `impl Trait for SomeUnsizedType` somewhere.
377 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
379 /// pub fn foo<T: Trait + ?Sized>() {
380 /// <T as Trait>::xyz();
384 /// When checking `foo`, we have to prove `T: Trait`. This basically
385 /// translates into this:
388 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
391 /// When we try to prove it, we first go the first option, which
392 /// recurses. This shows us that the impl is "useless" - it won't
393 /// tell us that `T: Trait` unless it already implemented `Trait`
394 /// by some other means. However, that does not prevent `T: Trait`
395 /// does not hold, because of the bound (which can indeed be satisfied
396 /// by `SomeUnsizedType` from another crate).
398 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
399 /// ought to convert it to an `EvaluatedToErr`, because we know
400 /// there definitely isn't a proof tree for that obligation. Not
401 /// doing so is still sound - there isn't any proof tree, so the
402 /// branch still can't be a part of a minimal one - but does not
403 /// re-enable caching.
405 /// Evaluation failed
409 impl EvaluationResult {
410 pub fn may_apply(self) -> bool {
412 EvaluatedToOk | EvaluatedToAmbig | EvaluatedToUnknown => true,
414 EvaluatedToErr | EvaluatedToRecur => false,
418 fn is_stack_dependent(self) -> bool {
420 EvaluatedToUnknown | EvaluatedToRecur => true,
422 EvaluatedToOk | EvaluatedToAmbig | EvaluatedToErr => false,
427 impl_stable_hash_for!(enum self::EvaluationResult {
435 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
436 /// Indicates that trait evaluation caused overflow.
437 pub struct OverflowError;
439 impl_stable_hash_for!(struct OverflowError {});
441 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
442 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
443 SelectionError::Overflow
447 #[derive(Clone, Default)]
448 pub struct EvaluationCache<'tcx> {
449 hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>,
452 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
453 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
456 freshener: infcx.freshener(),
458 intercrate_ambiguity_causes: None,
459 allow_negative_impls: false,
460 query_mode: TraitQueryMode::Standard,
465 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
466 mode: IntercrateMode,
467 ) -> SelectionContext<'cx, 'gcx, 'tcx> {
468 debug!("intercrate({:?})", mode);
471 freshener: infcx.freshener(),
472 intercrate: Some(mode),
473 intercrate_ambiguity_causes: None,
474 allow_negative_impls: false,
475 query_mode: TraitQueryMode::Standard,
479 pub fn with_negative(
480 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
481 allow_negative_impls: bool,
482 ) -> SelectionContext<'cx, 'gcx, 'tcx> {
483 debug!("with_negative({:?})", allow_negative_impls);
486 freshener: infcx.freshener(),
488 intercrate_ambiguity_causes: None,
489 allow_negative_impls,
490 query_mode: TraitQueryMode::Standard,
494 pub fn with_query_mode(
495 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
496 query_mode: TraitQueryMode,
497 ) -> SelectionContext<'cx, 'gcx, 'tcx> {
498 debug!("with_query_mode({:?})", query_mode);
501 freshener: infcx.freshener(),
503 intercrate_ambiguity_causes: None,
504 allow_negative_impls: false,
509 /// Enables tracking of intercrate ambiguity causes. These are
510 /// used in coherence to give improved diagnostics. We don't do
511 /// this until we detect a coherence error because it can lead to
512 /// false overflow results (#47139) and because it costs
513 /// computation time.
514 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
515 assert!(self.intercrate.is_some());
516 assert!(self.intercrate_ambiguity_causes.is_none());
517 self.intercrate_ambiguity_causes = Some(vec![]);
518 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
521 /// Gets the intercrate ambiguity causes collected since tracking
522 /// was enabled and disables tracking at the same time. If
523 /// tracking is not enabled, just returns an empty vector.
524 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
525 assert!(self.intercrate.is_some());
526 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
529 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
533 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
537 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
541 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
543 fn in_snapshot<R, F>(&mut self, f: F) -> R
545 F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R,
547 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
550 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
552 fn probe<R, F>(&mut self, f: F) -> R
554 F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R,
556 self.infcx.probe(|snapshot| f(self, snapshot))
559 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
560 /// the transaction fails and s.t. old obligations are retained.
561 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E>
563 F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> Result<T, E>,
565 self.infcx.commit_if_ok(|snapshot| f(self, snapshot))
568 ///////////////////////////////////////////////////////////////////////////
571 // The selection phase tries to identify *how* an obligation will
572 // be resolved. For example, it will identify which impl or
573 // parameter bound is to be used. The process can be inconclusive
574 // if the self type in the obligation is not fully inferred. Selection
575 // can result in an error in one of two ways:
577 // 1. If no applicable impl or parameter bound can be found.
578 // 2. If the output type parameters in the obligation do not match
579 // those specified by the impl/bound. For example, if the obligation
580 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
581 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
583 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
584 /// type environment by performing unification.
587 obligation: &TraitObligation<'tcx>,
588 ) -> SelectionResult<'tcx, Selection<'tcx>> {
589 debug!("select({:?})", obligation);
590 debug_assert!(!obligation.predicate.has_escaping_regions());
592 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
594 let candidate = match self.candidate_from_obligation(&stack) {
595 Err(SelectionError::Overflow) => {
596 // In standard mode, overflow must have been caught and reported
598 assert!(self.query_mode == TraitQueryMode::Canonical);
599 return Err(SelectionError::Overflow);
607 Ok(Some(candidate)) => candidate,
610 match self.confirm_candidate(obligation, candidate) {
611 Err(SelectionError::Overflow) => {
612 assert!(self.query_mode == TraitQueryMode::Canonical);
613 Err(SelectionError::Overflow)
616 Ok(candidate) => Ok(Some(candidate)),
620 ///////////////////////////////////////////////////////////////////////////
623 // Tests whether an obligation can be selected or whether an impl
624 // can be applied to particular types. It skips the "confirmation"
625 // step and hence completely ignores output type parameters.
627 // The result is "true" if the obligation *may* hold and "false" if
628 // we can be sure it does not.
630 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
631 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
632 debug!("predicate_may_hold_fatal({:?})", obligation);
634 // This fatal query is a stopgap that should only be used in standard mode,
635 // where we do not expect overflow to be propagated.
636 assert!(self.query_mode == TraitQueryMode::Standard);
638 self.evaluate_obligation_recursively(obligation)
639 .expect("Overflow should be caught earlier in standard query mode")
643 /// Evaluates whether the obligation `obligation` can be satisfied and returns
644 /// an `EvaluationResult`.
645 pub fn evaluate_obligation_recursively(
647 obligation: &PredicateObligation<'tcx>,
648 ) -> Result<EvaluationResult, OverflowError> {
649 self.probe(|this, _| {
650 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
654 /// Evaluates the predicates in `predicates` recursively. Note that
655 /// this applies projections in the predicates, and therefore
656 /// is run within an inference probe.
657 fn evaluate_predicates_recursively<'a, 'o, I>(
659 stack: TraitObligationStackList<'o, 'tcx>,
661 ) -> Result<EvaluationResult, OverflowError>
663 I: IntoIterator<Item = &'a PredicateObligation<'tcx>>,
666 let mut result = EvaluatedToOk;
667 for obligation in predicates {
668 let eval = self.evaluate_predicate_recursively(stack, obligation)?;
670 "evaluate_predicate_recursively({:?}) = {:?}",
673 if let EvaluatedToErr = eval {
674 // fast-path - EvaluatedToErr is the top of the lattice,
675 // so we don't need to look on the other predicates.
676 return Ok(EvaluatedToErr);
678 result = cmp::max(result, eval);
684 fn evaluate_predicate_recursively<'o>(
686 previous_stack: TraitObligationStackList<'o, 'tcx>,
687 obligation: &PredicateObligation<'tcx>,
688 ) -> Result<EvaluationResult, OverflowError> {
689 debug!("evaluate_predicate_recursively({:?})", obligation);
691 match obligation.predicate {
692 ty::Predicate::Trait(ref t) => {
693 debug_assert!(!t.has_escaping_regions());
694 let obligation = obligation.with(t.clone());
695 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
698 ty::Predicate::Subtype(ref p) => {
699 // does this code ever run?
701 .subtype_predicate(&obligation.cause, obligation.param_env, p)
703 Some(Ok(InferOk { obligations, .. })) => {
704 self.evaluate_predicates_recursively(previous_stack, &obligations)
706 Some(Err(_)) => Ok(EvaluatedToErr),
707 None => Ok(EvaluatedToAmbig),
711 ty::Predicate::WellFormed(ty) => match ty::wf::obligations(
713 obligation.param_env,
714 obligation.cause.body_id,
716 obligation.cause.span,
718 Some(obligations) => {
719 self.evaluate_predicates_recursively(previous_stack, obligations.iter())
721 None => Ok(EvaluatedToAmbig),
724 ty::Predicate::TypeOutlives(ref binder) => {
725 assert!(!binder.has_escaping_regions());
726 // Check if the type has higher-ranked regions.
727 if binder.skip_binder().0.has_escaping_regions() {
728 // If so, this obligation is an error (for now). Eventually we should be
729 // able to support additional cases here, like `for<'a> &'a str: 'a`.
731 // NOTE: this hack is implemented in both trait fulfillment and
732 // evaluation. If you fix it in one place, make sure you fix it
735 // We don't want to allow this sort of reasoning in intercrate
736 // mode, for backwards-compatibility reasons.
737 if self.intercrate.is_some() {
743 // If the type has no late bound regions, then if we assign all
744 // the inference variables in it to be 'static, then the type
745 // will be 'static itself.
747 // Therefore, `staticize(T): 'a` holds for any `'a`, so this
748 // obligation is fulfilled. Because evaluation works with
749 // staticized types (yes I know this is involved with #21974),
750 // we are 100% OK here.
755 ty::Predicate::RegionOutlives(ref binder) => {
756 let ty::OutlivesPredicate(r_a, r_b) = binder.skip_binder();
759 // for<'a> 'a: 'a. OK
761 } else if **r_a == ty::ReStatic {
762 // 'static: 'x always holds.
764 // This special case is handled somewhat inconsistently - if we
765 // have an inference variable that is supposed to be equal to
766 // `'static`, then we don't allow it to be equated to an LBR,
767 // but if we have a literal `'static`, then we *do*.
769 // This is actually consistent with how our region inference works.
771 // It would appear that this sort of inconsistency would
772 // cause "instability" problems with evaluation caching. However,
773 // evaluation caching is only for trait predicates, and when
774 // trait predicates create nested obligations, they contain
775 // inference variables for all the regions in the trait - the
776 // only way this codepath can be reached from trait predicate
777 // evaluation is when the user typed an explicit `where 'static: 'a`
778 // lifetime bound (in which case we want to return EvaluatedToOk).
780 // If we ever want to handle inference variables that might be
781 // equatable with ReStatic, we need to make sure we are not confused by
782 // technically-allowed-by-RFC-447-but-probably-should-not-be
785 // impl<'a, 's, T> X<'s> for T where T: Debug + 'a, 'a: 's
788 } else if r_a.is_late_bound() || r_b.is_late_bound() {
789 // There is no current way to prove `for<'a> 'a: 'x`
790 // unless `'a = 'x`, because there are no bounds involving
793 // It might be possible to prove `for<'a> 'x: 'a` by forcing `'x`
794 // to be `'static`. However, this is not currently done by type
795 // inference unless `'x` is literally ReStatic. See the comment
798 // We don't want to allow this sort of reasoning in intercrate
799 // mode, for backwards-compatibility reasons.
800 if self.intercrate.is_some() {
806 // Relating 2 inference variable regions. These will
807 // always hold if our query is "staticized".
812 ty::Predicate::ObjectSafe(trait_def_id) => {
813 if self.tcx().is_object_safe(trait_def_id) {
820 ty::Predicate::Projection(ref data) => {
821 let project_obligation = obligation.with(data.clone());
822 match project::poly_project_and_unify_type(self, &project_obligation) {
823 Ok(Some(subobligations)) => {
824 let result = self.evaluate_predicates_recursively(
826 subobligations.iter(),
829 ProjectionCacheKey::from_poly_projection_predicate(self, data)
831 self.infcx.projection_cache.borrow_mut().complete(key);
835 Ok(None) => Ok(EvaluatedToAmbig),
836 Err(_) => Ok(EvaluatedToErr),
840 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
841 match self.infcx.closure_kind(closure_def_id, closure_substs) {
842 Some(closure_kind) => {
843 if closure_kind.extends(kind) {
849 None => Ok(EvaluatedToAmbig),
853 ty::Predicate::ConstEvaluatable(def_id, substs) => {
854 let tcx = self.tcx();
855 match tcx.lift_to_global(&(obligation.param_env, substs)) {
856 Some((param_env, substs)) => {
858 ty::Instance::resolve(tcx.global_tcx(), param_env, def_id, substs);
859 if let Some(instance) = instance {
864 match self.tcx().const_eval(param_env.and(cid)) {
865 Ok(_) => Ok(EvaluatedToOk),
866 Err(_) => Ok(EvaluatedToErr),
873 // Inference variables still left in param_env or substs.
881 fn evaluate_trait_predicate_recursively<'o>(
883 previous_stack: TraitObligationStackList<'o, 'tcx>,
884 mut obligation: TraitObligation<'tcx>,
885 ) -> Result<EvaluationResult, OverflowError> {
886 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
888 if self.intercrate.is_none() && obligation.is_global()
893 .all(|bound| bound.needs_subst())
895 // If a param env has no global bounds, global obligations do not
896 // depend on its particular value in order to work, so we can clear
897 // out the param env and get better caching.
899 "evaluate_trait_predicate_recursively({:?}) - in global",
902 obligation.param_env = obligation.param_env.without_caller_bounds();
905 let stack = self.push_stack(previous_stack, &obligation);
906 let fresh_trait_ref = stack.fresh_trait_ref;
907 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
908 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
912 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
913 let result = result?;
915 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
916 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
921 fn evaluate_stack<'o>(
923 stack: &TraitObligationStack<'o, 'tcx>,
924 ) -> Result<EvaluationResult, OverflowError> {
925 // In intercrate mode, whenever any of the types are unbound,
926 // there can always be an impl. Even if there are no impls in
927 // this crate, perhaps the type would be unified with
928 // something from another crate that does provide an impl.
930 // In intra mode, we must still be conservative. The reason is
931 // that we want to avoid cycles. Imagine an impl like:
933 // impl<T:Eq> Eq for Vec<T>
935 // and a trait reference like `$0 : Eq` where `$0` is an
936 // unbound variable. When we evaluate this trait-reference, we
937 // will unify `$0` with `Vec<$1>` (for some fresh variable
938 // `$1`), on the condition that `$1 : Eq`. We will then wind
939 // up with many candidates (since that are other `Eq` impls
940 // that apply) and try to winnow things down. This results in
941 // a recursive evaluation that `$1 : Eq` -- as you can
942 // imagine, this is just where we started. To avoid that, we
943 // check for unbound variables and return an ambiguous (hence possible)
944 // match if we've seen this trait before.
946 // This suffices to allow chains like `FnMut` implemented in
947 // terms of `Fn` etc, but we could probably make this more
949 let unbound_input_types = stack
953 .any(|ty| ty.is_fresh());
954 // this check was an imperfect workaround for a bug n the old
955 // intercrate mode, it should be removed when that goes away.
956 if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
958 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
959 stack.fresh_trait_ref
961 // Heuristics: show the diagnostics when there are no candidates in crate.
962 if self.intercrate_ambiguity_causes.is_some() {
963 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
964 if let Ok(candidate_set) = self.assemble_candidates(stack) {
965 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
966 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
967 let self_ty = trait_ref.self_ty();
968 let cause = IntercrateAmbiguityCause::DownstreamCrate {
969 trait_desc: trait_ref.to_string(),
970 self_desc: if self_ty.has_concrete_skeleton() {
971 Some(self_ty.to_string())
976 debug!("evaluate_stack: pushing cause = {:?}", cause);
977 self.intercrate_ambiguity_causes
984 return Ok(EvaluatedToAmbig);
986 if unbound_input_types && stack.iter().skip(1).any(|prev| {
987 stack.obligation.param_env == prev.obligation.param_env
988 && self.match_fresh_trait_refs(&stack.fresh_trait_ref, &prev.fresh_trait_ref)
991 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
992 stack.fresh_trait_ref
994 return Ok(EvaluatedToUnknown);
997 // If there is any previous entry on the stack that precisely
998 // matches this obligation, then we can assume that the
999 // obligation is satisfied for now (still all other conditions
1000 // must be met of course). One obvious case this comes up is
1001 // marker traits like `Send`. Think of a linked list:
1003 // struct List<T> { data: T, next: Option<Box<List<T>>> }
1005 // `Box<List<T>>` will be `Send` if `T` is `Send` and
1006 // `Option<Box<List<T>>>` is `Send`, and in turn
1007 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
1010 // Note that we do this comparison using the `fresh_trait_ref`
1011 // fields. Because these have all been freshened using
1012 // `self.freshener`, we can be sure that (a) this will not
1013 // affect the inferencer state and (b) that if we see two
1014 // fresh regions with the same index, they refer to the same
1015 // unbound type variable.
1016 if let Some(rec_index) = stack.iter()
1017 .skip(1) // skip top-most frame
1018 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
1019 stack.fresh_trait_ref == prev.fresh_trait_ref)
1021 debug!("evaluate_stack({:?}) --> recursive", stack.fresh_trait_ref);
1023 let cycle = stack.iter().skip(1).take(rec_index + 1);
1024 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
1025 if self.coinductive_match(cycle) {
1027 "evaluate_stack({:?}) --> recursive, coinductive",
1028 stack.fresh_trait_ref
1030 return Ok(EvaluatedToOk);
1033 "evaluate_stack({:?}) --> recursive, inductive",
1034 stack.fresh_trait_ref
1036 return Ok(EvaluatedToRecur);
1040 match self.candidate_from_obligation(stack) {
1041 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1042 Ok(None) => Ok(EvaluatedToAmbig),
1043 Err(Overflow) => Err(OverflowError),
1044 Err(..) => Ok(EvaluatedToErr),
1048 /// For defaulted traits, we use a co-inductive strategy to solve, so
1049 /// that recursion is ok. This routine returns true if the top of the
1050 /// stack (`cycle[0]`):
1052 /// - is a defaulted trait, and
1053 /// - it also appears in the backtrace at some position `X`; and,
1054 /// - all the predicates at positions `X..` between `X` an the top are
1055 /// also defaulted traits.
1056 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1058 I: Iterator<Item = ty::Predicate<'tcx>>,
1060 let mut cycle = cycle;
1061 cycle.all(|predicate| self.coinductive_predicate(predicate))
1064 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1065 let result = match predicate {
1066 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1069 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1073 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1074 /// obligations are met. Returns true if `candidate` remains viable after this further
1076 fn evaluate_candidate<'o>(
1078 stack: &TraitObligationStack<'o, 'tcx>,
1079 candidate: &SelectionCandidate<'tcx>,
1080 ) -> Result<EvaluationResult, OverflowError> {
1082 "evaluate_candidate: depth={} candidate={:?}",
1083 stack.obligation.recursion_depth, candidate
1085 let result = self.probe(|this, _| {
1086 let candidate = (*candidate).clone();
1087 match this.confirm_candidate(stack.obligation, candidate) {
1088 Ok(selection) => this.evaluate_predicates_recursively(
1090 selection.nested_obligations().iter(),
1092 Err(..) => Ok(EvaluatedToErr),
1096 "evaluate_candidate: depth={} result={:?}",
1097 stack.obligation.recursion_depth, result
1102 fn check_evaluation_cache(
1104 param_env: ty::ParamEnv<'tcx>,
1105 trait_ref: ty::PolyTraitRef<'tcx>,
1106 ) -> Option<EvaluationResult> {
1107 let tcx = self.tcx();
1108 if self.can_use_global_caches(param_env) {
1109 let cache = tcx.evaluation_cache.hashmap.borrow();
1110 if let Some(cached) = cache.get(&trait_ref) {
1111 return Some(cached.get(tcx));
1119 .map(|v| v.get(tcx))
1122 fn insert_evaluation_cache(
1124 param_env: ty::ParamEnv<'tcx>,
1125 trait_ref: ty::PolyTraitRef<'tcx>,
1126 dep_node: DepNodeIndex,
1127 result: EvaluationResult,
1129 // Avoid caching results that depend on more than just the trait-ref
1130 // - the stack can create recursion.
1131 if result.is_stack_dependent() {
1135 if self.can_use_global_caches(param_env) {
1136 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
1138 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1141 // This may overwrite the cache with the same value
1142 // FIXME: Due to #50507 this overwrites the different values
1143 // This should be changed to use HashMapExt::insert_same
1144 // when that is fixed
1149 .insert(trait_ref, WithDepNode::new(dep_node, result));
1155 "insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
1162 .insert(trait_ref, WithDepNode::new(dep_node, result));
1165 ///////////////////////////////////////////////////////////////////////////
1166 // CANDIDATE ASSEMBLY
1168 // The selection process begins by examining all in-scope impls,
1169 // caller obligations, and so forth and assembling a list of
1170 // candidates. See [rustc guide] for more details.
1173 // https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1175 fn candidate_from_obligation<'o>(
1177 stack: &TraitObligationStack<'o, 'tcx>,
1178 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1179 // Watch out for overflow. This intentionally bypasses (and does
1180 // not update) the cache.
1181 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1182 if stack.obligation.recursion_depth >= recursion_limit {
1183 match self.query_mode {
1184 TraitQueryMode::Standard => {
1185 self.infcx().report_overflow_error(&stack.obligation, true);
1187 TraitQueryMode::Canonical => {
1188 return Err(Overflow);
1193 // Check the cache. Note that we freshen the trait-ref
1194 // separately rather than using `stack.fresh_trait_ref` --
1195 // this is because we want the unbound variables to be
1196 // replaced with fresh types starting from index 0.
1197 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1199 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1200 cache_fresh_trait_pred, stack
1202 debug_assert!(!stack.obligation.predicate.has_escaping_regions());
1205 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1207 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1211 // If no match, compute result and insert into cache.
1212 let (candidate, dep_node) =
1213 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1216 "CACHE MISS: SELECT({:?})={:?}",
1217 cache_fresh_trait_pred, candidate
1219 self.insert_candidate_cache(
1220 stack.obligation.param_env,
1221 cache_fresh_trait_pred,
1228 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1230 OP: FnOnce(&mut Self) -> R,
1232 let (result, dep_node) = self.tcx()
1234 .with_anon_task(DepKind::TraitSelect, || op(self));
1235 self.tcx().dep_graph.read_index(dep_node);
1239 // Treat negative impls as unimplemented
1240 fn filter_negative_impls(
1242 candidate: SelectionCandidate<'tcx>,
1243 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1244 if let ImplCandidate(def_id) = candidate {
1245 if !self.allow_negative_impls
1246 && self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative
1248 return Err(Unimplemented);
1254 fn candidate_from_obligation_no_cache<'o>(
1256 stack: &TraitObligationStack<'o, 'tcx>,
1257 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1258 if stack.obligation.predicate.references_error() {
1259 // If we encounter a `Error`, we generally prefer the
1260 // most "optimistic" result in response -- that is, the
1261 // one least likely to report downstream errors. But
1262 // because this routine is shared by coherence and by
1263 // trait selection, there isn't an obvious "right" choice
1264 // here in that respect, so we opt to just return
1265 // ambiguity and let the upstream clients sort it out.
1269 if let Some(conflict) = self.is_knowable(stack) {
1270 debug!("coherence stage: not knowable");
1271 if self.intercrate_ambiguity_causes.is_some() {
1272 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1273 // Heuristics: show the diagnostics when there are no candidates in crate.
1274 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1275 let mut no_candidates_apply = true;
1277 let evaluated_candidates = candidate_set
1280 .map(|c| self.evaluate_candidate(stack, &c));
1282 for ec in evaluated_candidates {
1286 no_candidates_apply = false;
1290 Err(e) => return Err(e.into()),
1295 if !candidate_set.ambiguous && no_candidates_apply {
1296 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1297 let self_ty = trait_ref.self_ty();
1298 let trait_desc = trait_ref.to_string();
1299 let self_desc = if self_ty.has_concrete_skeleton() {
1300 Some(self_ty.to_string())
1304 let cause = if let Conflict::Upstream = conflict {
1305 IntercrateAmbiguityCause::UpstreamCrateUpdate {
1310 IntercrateAmbiguityCause::DownstreamCrate {
1315 debug!("evaluate_stack: pushing cause = {:?}", cause);
1316 self.intercrate_ambiguity_causes
1326 let candidate_set = self.assemble_candidates(stack)?;
1328 if candidate_set.ambiguous {
1329 debug!("candidate set contains ambig");
1333 let mut candidates = candidate_set.vec;
1336 "assembled {} candidates for {:?}: {:?}",
1342 // At this point, we know that each of the entries in the
1343 // candidate set is *individually* applicable. Now we have to
1344 // figure out if they contain mutual incompatibilities. This
1345 // frequently arises if we have an unconstrained input type --
1346 // for example, we are looking for $0:Eq where $0 is some
1347 // unconstrained type variable. In that case, we'll get a
1348 // candidate which assumes $0 == int, one that assumes $0 ==
1349 // usize, etc. This spells an ambiguity.
1351 // If there is more than one candidate, first winnow them down
1352 // by considering extra conditions (nested obligations and so
1353 // forth). We don't winnow if there is exactly one
1354 // candidate. This is a relatively minor distinction but it
1355 // can lead to better inference and error-reporting. An
1356 // example would be if there was an impl:
1358 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1360 // and we were to see some code `foo.push_clone()` where `boo`
1361 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1362 // we were to winnow, we'd wind up with zero candidates.
1363 // Instead, we select the right impl now but report `Bar does
1364 // not implement Clone`.
1365 if candidates.len() == 1 {
1366 return self.filter_negative_impls(candidates.pop().unwrap());
1369 // Winnow, but record the exact outcome of evaluation, which
1370 // is needed for specialization. Propagate overflow if it occurs.
1371 let mut candidates = candidates.into_iter()
1372 .map(|c| match self.evaluate_candidate(stack, &c) {
1373 Ok(eval) if eval.may_apply() => Ok(Some(EvaluatedCandidate {
1378 Err(OverflowError) => Err(Overflow),
1380 .flat_map(Result::transpose)
1381 .collect::<Result<Vec<_>, _>>()?;
1384 "winnowed to {} candidates for {:?}: {:?}",
1390 // If there are STILL multiple candidates, we can further
1391 // reduce the list by dropping duplicates -- including
1392 // resolving specializations.
1393 if candidates.len() > 1 {
1395 while i < candidates.len() {
1396 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1397 self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1401 "Dropping candidate #{}/{}: {:?}",
1406 candidates.swap_remove(i);
1409 "Retaining candidate #{}/{}: {:?}",
1416 // If there are *STILL* multiple candidates, give up
1417 // and report ambiguity.
1419 debug!("multiple matches, ambig");
1426 // If there are *NO* candidates, then there are no impls --
1427 // that we know of, anyway. Note that in the case where there
1428 // are unbound type variables within the obligation, it might
1429 // be the case that you could still satisfy the obligation
1430 // from another crate by instantiating the type variables with
1431 // a type from another crate that does have an impl. This case
1432 // is checked for in `evaluate_stack` (and hence users
1433 // who might care about this case, like coherence, should use
1435 if candidates.is_empty() {
1436 return Err(Unimplemented);
1439 // Just one candidate left.
1440 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1443 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1444 debug!("is_knowable(intercrate={:?})", self.intercrate);
1446 if !self.intercrate.is_some() {
1450 let obligation = &stack.obligation;
1451 let predicate = self.infcx()
1452 .resolve_type_vars_if_possible(&obligation.predicate);
1454 // ok to skip binder because of the nature of the
1455 // trait-ref-is-knowable check, which does not care about
1457 let trait_ref = predicate.skip_binder().trait_ref;
1459 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1461 Some(Conflict::Downstream {
1462 used_to_be_broken: true,
1464 Some(IntercrateMode::Issue43355),
1465 ) = (result, self.intercrate)
1467 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1474 /// Returns true if the global caches can be used.
1475 /// Do note that if the type itself is not in the
1476 /// global tcx, the local caches will be used.
1477 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1478 // If there are any where-clauses in scope, then we always use
1479 // a cache local to this particular scope. Otherwise, we
1480 // switch to a global cache. We used to try and draw
1481 // finer-grained distinctions, but that led to a serious of
1482 // annoying and weird bugs like #22019 and #18290. This simple
1483 // rule seems to be pretty clearly safe and also still retains
1484 // a very high hit rate (~95% when compiling rustc).
1485 if !param_env.caller_bounds.is_empty() {
1489 // Avoid using the master cache during coherence and just rely
1490 // on the local cache. This effectively disables caching
1491 // during coherence. It is really just a simplification to
1492 // avoid us having to fear that coherence results "pollute"
1493 // the master cache. Since coherence executes pretty quickly,
1494 // it's not worth going to more trouble to increase the
1495 // hit-rate I don't think.
1496 if self.intercrate.is_some() {
1500 // Otherwise, we can use the global cache.
1504 fn check_candidate_cache(
1506 param_env: ty::ParamEnv<'tcx>,
1507 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1508 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1509 let tcx = self.tcx();
1510 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1511 if self.can_use_global_caches(param_env) {
1512 let cache = tcx.selection_cache.hashmap.borrow();
1513 if let Some(cached) = cache.get(&trait_ref) {
1514 return Some(cached.get(tcx));
1522 .map(|v| v.get(tcx))
1525 fn insert_candidate_cache(
1527 param_env: ty::ParamEnv<'tcx>,
1528 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1529 dep_node: DepNodeIndex,
1530 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1532 let tcx = self.tcx();
1533 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1534 if self.can_use_global_caches(param_env) {
1535 if let Err(Overflow) = candidate {
1536 // Don't cache overflow globally; we only produce this
1537 // in certain modes.
1538 } else if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1539 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1541 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1542 trait_ref, candidate,
1544 // This may overwrite the cache with the same value
1548 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1555 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1556 trait_ref, candidate,
1562 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1565 fn assemble_candidates<'o>(
1567 stack: &TraitObligationStack<'o, 'tcx>,
1568 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1569 let TraitObligationStack { obligation, .. } = *stack;
1570 let ref obligation = Obligation {
1571 param_env: obligation.param_env,
1572 cause: obligation.cause.clone(),
1573 recursion_depth: obligation.recursion_depth,
1574 predicate: self.infcx()
1575 .resolve_type_vars_if_possible(&obligation.predicate),
1578 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1579 // Self is a type variable (e.g. `_: AsRef<str>`).
1581 // This is somewhat problematic, as the current scheme can't really
1582 // handle it turning to be a projection. This does end up as truly
1583 // ambiguous in most cases anyway.
1585 // Take the fast path out - this also improves
1586 // performance by preventing assemble_candidates_from_impls from
1587 // matching every impl for this trait.
1588 return Ok(SelectionCandidateSet {
1594 let mut candidates = SelectionCandidateSet {
1599 // Other bounds. Consider both in-scope bounds from fn decl
1600 // and applicable impls. There is a certain set of precedence rules here.
1601 let def_id = obligation.predicate.def_id();
1602 let lang_items = self.tcx().lang_items();
1604 if lang_items.copy_trait() == Some(def_id) {
1606 "obligation self ty is {:?}",
1607 obligation.predicate.skip_binder().self_ty()
1610 // User-defined copy impls are permitted, but only for
1611 // structs and enums.
1612 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1614 // For other types, we'll use the builtin rules.
1615 let copy_conditions = self.copy_clone_conditions(obligation);
1616 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1617 } else if lang_items.sized_trait() == Some(def_id) {
1618 // Sized is never implementable by end-users, it is
1619 // always automatically computed.
1620 let sized_conditions = self.sized_conditions(obligation);
1621 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1622 } else if lang_items.unsize_trait() == Some(def_id) {
1623 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1625 if lang_items.clone_trait() == Some(def_id) {
1626 // Same builtin conditions as `Copy`, i.e. every type which has builtin support
1627 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1628 // types have builtin support for `Clone`.
1629 let clone_conditions = self.copy_clone_conditions(obligation);
1630 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1633 self.assemble_generator_candidates(obligation, &mut candidates)?;
1634 self.assemble_closure_candidates(obligation, &mut candidates)?;
1635 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1636 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1637 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1640 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1641 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1642 // Auto implementations have lower priority, so we only
1643 // consider triggering a default if there is no other impl that can apply.
1644 if candidates.vec.is_empty() {
1645 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1647 debug!("candidate list size: {}", candidates.vec.len());
1651 fn assemble_candidates_from_projected_tys(
1653 obligation: &TraitObligation<'tcx>,
1654 candidates: &mut SelectionCandidateSet<'tcx>,
1656 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1658 // before we go into the whole placeholder thing, just
1659 // quickly check if the self-type is a projection at all.
1660 match obligation.predicate.skip_binder().trait_ref.self_ty().sty {
1661 ty::Projection(_) | ty::Opaque(..) => {}
1662 ty::Infer(ty::TyVar(_)) => {
1664 obligation.cause.span,
1665 "Self=_ should have been handled by assemble_candidates"
1671 let result = self.probe(|this, snapshot| {
1672 this.match_projection_obligation_against_definition_bounds(obligation, snapshot)
1676 candidates.vec.push(ProjectionCandidate);
1680 fn match_projection_obligation_against_definition_bounds(
1682 obligation: &TraitObligation<'tcx>,
1683 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
1685 let poly_trait_predicate = self.infcx()
1686 .resolve_type_vars_if_possible(&obligation.predicate);
1687 let (skol_trait_predicate, placeholder_map) = self.infcx()
1688 .replace_late_bound_regions_with_placeholders(&poly_trait_predicate);
1690 "match_projection_obligation_against_definition_bounds: \
1691 skol_trait_predicate={:?} placeholder_map={:?}",
1692 skol_trait_predicate, placeholder_map
1695 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1696 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1697 ty::Opaque(def_id, substs) => (def_id, substs),
1700 obligation.cause.span,
1701 "match_projection_obligation_against_definition_bounds() called \
1702 but self-ty is not a projection: {:?}",
1703 skol_trait_predicate.trait_ref.self_ty()
1708 "match_projection_obligation_against_definition_bounds: \
1709 def_id={:?}, substs={:?}",
1713 let predicates_of = self.tcx().predicates_of(def_id);
1714 let bounds = predicates_of.instantiate(self.tcx(), substs);
1716 "match_projection_obligation_against_definition_bounds: \
1721 let matching_bound = util::elaborate_predicates(self.tcx(), bounds.predicates)
1724 self.probe(|this, _| {
1725 this.match_projection(
1728 skol_trait_predicate.trait_ref.clone(),
1736 "match_projection_obligation_against_definition_bounds: \
1737 matching_bound={:?}",
1740 match matching_bound {
1743 // Repeat the successful match, if any, this time outside of a probe.
1744 let result = self.match_projection(
1747 skol_trait_predicate.trait_ref.clone(),
1752 self.infcx.pop_placeholders(placeholder_map, snapshot);
1760 fn match_projection(
1762 obligation: &TraitObligation<'tcx>,
1763 trait_bound: ty::PolyTraitRef<'tcx>,
1764 skol_trait_ref: ty::TraitRef<'tcx>,
1765 placeholder_map: &infer::PlaceholderMap<'tcx>,
1766 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
1768 debug_assert!(!skol_trait_ref.has_escaping_regions());
1770 .at(&obligation.cause, obligation.param_env)
1771 .sup(ty::Binder::dummy(skol_trait_ref), trait_bound)
1778 .leak_check(false, obligation.cause.span, placeholder_map, snapshot)
1782 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1783 /// supplied to find out whether it is listed among them.
1785 /// Never affects inference environment.
1786 fn assemble_candidates_from_caller_bounds<'o>(
1788 stack: &TraitObligationStack<'o, 'tcx>,
1789 candidates: &mut SelectionCandidateSet<'tcx>,
1790 ) -> Result<(), SelectionError<'tcx>> {
1792 "assemble_candidates_from_caller_bounds({:?})",
1796 let all_bounds = stack
1801 .filter_map(|o| o.to_opt_poly_trait_ref());
1803 // micro-optimization: filter out predicates relating to different
1805 let matching_bounds =
1806 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1808 // keep only those bounds which may apply, and propagate overflow if it occurs
1809 let mut param_candidates = vec![];
1810 for bound in matching_bounds {
1811 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1813 param_candidates.push(ParamCandidate(bound));
1817 candidates.vec.extend(param_candidates);
1822 fn evaluate_where_clause<'o>(
1824 stack: &TraitObligationStack<'o, 'tcx>,
1825 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1826 ) -> Result<EvaluationResult, OverflowError> {
1827 self.probe(move |this, _| {
1828 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1829 Ok(obligations) => {
1830 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1832 Err(()) => Ok(EvaluatedToErr),
1837 fn assemble_generator_candidates(
1839 obligation: &TraitObligation<'tcx>,
1840 candidates: &mut SelectionCandidateSet<'tcx>,
1841 ) -> Result<(), SelectionError<'tcx>> {
1842 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1846 // ok to skip binder because the substs on generator types never
1847 // touch bound regions, they just capture the in-scope
1848 // type/region parameters
1849 let self_ty = *obligation.self_ty().skip_binder();
1851 ty::Generator(..) => {
1853 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1857 candidates.vec.push(GeneratorCandidate);
1859 ty::Infer(ty::TyVar(_)) => {
1860 debug!("assemble_generator_candidates: ambiguous self-type");
1861 candidates.ambiguous = true;
1869 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1870 /// FnMut<..>` where `X` is a closure type.
1872 /// Note: the type parameters on a closure candidate are modeled as *output* type
1873 /// parameters and hence do not affect whether this trait is a match or not. They will be
1874 /// unified during the confirmation step.
1875 fn assemble_closure_candidates(
1877 obligation: &TraitObligation<'tcx>,
1878 candidates: &mut SelectionCandidateSet<'tcx>,
1879 ) -> Result<(), SelectionError<'tcx>> {
1880 let kind = match self.tcx()
1882 .fn_trait_kind(obligation.predicate.def_id())
1890 // ok to skip binder because the substs on closure types never
1891 // touch bound regions, they just capture the in-scope
1892 // type/region parameters
1893 match obligation.self_ty().skip_binder().sty {
1894 ty::Closure(closure_def_id, closure_substs) => {
1896 "assemble_unboxed_candidates: kind={:?} obligation={:?}",
1899 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1900 Some(closure_kind) => {
1902 "assemble_unboxed_candidates: closure_kind = {:?}",
1905 if closure_kind.extends(kind) {
1906 candidates.vec.push(ClosureCandidate);
1910 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1911 candidates.vec.push(ClosureCandidate);
1915 ty::Infer(ty::TyVar(_)) => {
1916 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1917 candidates.ambiguous = true;
1925 /// Implement one of the `Fn()` family for a fn pointer.
1926 fn assemble_fn_pointer_candidates(
1928 obligation: &TraitObligation<'tcx>,
1929 candidates: &mut SelectionCandidateSet<'tcx>,
1930 ) -> Result<(), SelectionError<'tcx>> {
1931 // We provide impl of all fn traits for fn pointers.
1934 .fn_trait_kind(obligation.predicate.def_id())
1940 // ok to skip binder because what we are inspecting doesn't involve bound regions
1941 let self_ty = *obligation.self_ty().skip_binder();
1943 ty::Infer(ty::TyVar(_)) => {
1944 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1945 candidates.ambiguous = true; // could wind up being a fn() type
1947 // provide an impl, but only for suitable `fn` pointers
1948 ty::FnDef(..) | ty::FnPtr(_) => {
1950 unsafety: hir::Unsafety::Normal,
1954 } = self_ty.fn_sig(self.tcx()).skip_binder()
1956 candidates.vec.push(FnPointerCandidate);
1965 /// Search for impls that might apply to `obligation`.
1966 fn assemble_candidates_from_impls(
1968 obligation: &TraitObligation<'tcx>,
1969 candidates: &mut SelectionCandidateSet<'tcx>,
1970 ) -> Result<(), SelectionError<'tcx>> {
1972 "assemble_candidates_from_impls(obligation={:?})",
1976 self.tcx().for_each_relevant_impl(
1977 obligation.predicate.def_id(),
1978 obligation.predicate.skip_binder().trait_ref.self_ty(),
1980 self.probe(|this, snapshot| {
1981 if let Ok(placeholder_map) = this.match_impl(impl_def_id, obligation, snapshot)
1983 candidates.vec.push(ImplCandidate(impl_def_id));
1985 // NB: we can safely drop the placeholder map
1986 // since we are in a probe.
1987 mem::drop(placeholder_map);
1996 fn assemble_candidates_from_auto_impls(
1998 obligation: &TraitObligation<'tcx>,
1999 candidates: &mut SelectionCandidateSet<'tcx>,
2000 ) -> Result<(), SelectionError<'tcx>> {
2001 // OK to skip binder here because the tests we do below do not involve bound regions
2002 let self_ty = *obligation.self_ty().skip_binder();
2003 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2005 let def_id = obligation.predicate.def_id();
2007 if self.tcx().trait_is_auto(def_id) {
2009 ty::Dynamic(..) => {
2010 // For object types, we don't know what the closed
2011 // over types are. This means we conservatively
2012 // say nothing; a candidate may be added by
2013 // `assemble_candidates_from_object_ty`.
2015 ty::Foreign(..) => {
2016 // Since the contents of foreign types is unknown,
2017 // we don't add any `..` impl. Default traits could
2018 // still be provided by a manual implementation for
2019 // this trait and type.
2021 ty::Param(..) | ty::Projection(..) => {
2022 // In these cases, we don't know what the actual
2023 // type is. Therefore, we cannot break it down
2024 // into its constituent types. So we don't
2025 // consider the `..` impl but instead just add no
2026 // candidates: this means that typeck will only
2027 // succeed if there is another reason to believe
2028 // that this obligation holds. That could be a
2029 // where-clause or, in the case of an object type,
2030 // it could be that the object type lists the
2031 // trait (e.g. `Foo+Send : Send`). See
2032 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2033 // for an example of a test case that exercises
2036 ty::Infer(ty::TyVar(_)) => {
2037 // the auto impl might apply, we don't know
2038 candidates.ambiguous = true;
2040 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2047 /// Search for impls that might apply to `obligation`.
2048 fn assemble_candidates_from_object_ty(
2050 obligation: &TraitObligation<'tcx>,
2051 candidates: &mut SelectionCandidateSet<'tcx>,
2054 "assemble_candidates_from_object_ty(self_ty={:?})",
2055 obligation.self_ty().skip_binder()
2058 // Object-safety candidates are only applicable to object-safe
2059 // traits. Including this check is useful because it helps
2060 // inference in cases of traits like `BorrowFrom`, which are
2061 // not object-safe, and which rely on being able to infer the
2062 // self-type from one of the other inputs. Without this check,
2063 // these cases wind up being considered ambiguous due to a
2064 // (spurious) ambiguity introduced here.
2065 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
2066 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
2070 self.probe(|this, _snapshot| {
2071 // the code below doesn't care about regions, and the
2072 // self-ty here doesn't escape this probe, so just erase
2074 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
2075 let poly_trait_ref = match self_ty.sty {
2076 ty::Dynamic(ref data, ..) => {
2077 if data.auto_traits()
2078 .any(|did| did == obligation.predicate.def_id())
2081 "assemble_candidates_from_object_ty: matched builtin bound, \
2084 candidates.vec.push(BuiltinObjectCandidate);
2088 data.principal().with_self_ty(this.tcx(), self_ty)
2090 ty::Infer(ty::TyVar(_)) => {
2091 debug!("assemble_candidates_from_object_ty: ambiguous");
2092 candidates.ambiguous = true; // could wind up being an object type
2099 "assemble_candidates_from_object_ty: poly_trait_ref={:?}",
2103 // Count only those upcast versions that match the trait-ref
2104 // we are looking for. Specifically, do not only check for the
2105 // correct trait, but also the correct type parameters.
2106 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2107 // but `Foo` is declared as `trait Foo : Bar<u32>`.
2108 let upcast_trait_refs = util::supertraits(this.tcx(), poly_trait_ref)
2109 .filter(|upcast_trait_ref| {
2110 this.probe(|this, _| {
2111 let upcast_trait_ref = upcast_trait_ref.clone();
2112 this.match_poly_trait_ref(obligation, upcast_trait_ref)
2118 if upcast_trait_refs > 1 {
2119 // can be upcast in many ways; need more type information
2120 candidates.ambiguous = true;
2121 } else if upcast_trait_refs == 1 {
2122 candidates.vec.push(ObjectCandidate);
2127 /// Search for unsizing that might apply to `obligation`.
2128 fn assemble_candidates_for_unsizing(
2130 obligation: &TraitObligation<'tcx>,
2131 candidates: &mut SelectionCandidateSet<'tcx>,
2133 // We currently never consider higher-ranked obligations e.g.
2134 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2135 // because they are a priori invalid, and we could potentially add support
2136 // for them later, it's just that there isn't really a strong need for it.
2137 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2138 // impl, and those are generally applied to concrete types.
2140 // That said, one might try to write a fn with a where clause like
2141 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2142 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2143 // Still, you'd be more likely to write that where clause as
2145 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2146 // obligation above. Should be possible to extend this in the future.
2147 let source = match obligation.self_ty().no_late_bound_regions() {
2150 // Don't add any candidates if there are bound regions.
2154 let target = obligation
2162 "assemble_candidates_for_unsizing(source={:?}, target={:?})",
2166 let may_apply = match (&source.sty, &target.sty) {
2167 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2168 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2169 // Upcasts permit two things:
2171 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
2172 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
2174 // Note that neither of these changes requires any
2175 // change at runtime. Eventually this will be
2178 // We always upcast when we can because of reason
2179 // #2 (region bounds).
2180 data_a.principal().def_id() == data_b.principal().def_id()
2181 && data_b.auto_traits()
2182 // All of a's auto traits need to be in b's auto traits.
2183 .all(|b| data_a.auto_traits().any(|a| a == b))
2187 (_, &ty::Dynamic(..)) => true,
2189 // Ambiguous handling is below T -> Trait, because inference
2190 // variables can still implement Unsize<Trait> and nested
2191 // obligations will have the final say (likely deferred).
2192 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2193 debug!("assemble_candidates_for_unsizing: ambiguous");
2194 candidates.ambiguous = true;
2199 (&ty::Array(..), &ty::Slice(_)) => true,
2201 // Struct<T> -> Struct<U>.
2202 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2203 def_id_a == def_id_b
2206 // (.., T) -> (.., U).
2207 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2213 candidates.vec.push(BuiltinUnsizeCandidate);
2217 ///////////////////////////////////////////////////////////////////////////
2220 // Winnowing is the process of attempting to resolve ambiguity by
2221 // probing further. During the winnowing process, we unify all
2222 // type variables and then we also attempt to evaluate recursive
2223 // bounds to see if they are satisfied.
2225 /// Returns true if `victim` should be dropped in favor of
2226 /// `other`. Generally speaking we will drop duplicate
2227 /// candidates and prefer where-clause candidates.
2229 /// See the comment for "SelectionCandidate" for more details.
2230 fn candidate_should_be_dropped_in_favor_of<'o>(
2232 victim: &EvaluatedCandidate<'tcx>,
2233 other: &EvaluatedCandidate<'tcx>,
2235 if victim.candidate == other.candidate {
2239 // Check if a bound would previously have been removed when normalizing
2240 // the param_env so that it can be given the lowest priority. See
2241 // #50825 for the motivation for this.
2243 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2245 match other.candidate {
2246 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2247 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2248 // lifetime of a variable.
2249 BuiltinCandidate { has_nested: false } => true,
2250 ParamCandidate(ref cand) => match victim.candidate {
2251 AutoImplCandidate(..) => {
2253 "default implementations shouldn't be recorded \
2254 when there are other valid candidates"
2257 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2258 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2259 // lifetime of a variable.
2260 BuiltinCandidate { has_nested: false } => false,
2263 | GeneratorCandidate
2264 | FnPointerCandidate
2265 | BuiltinObjectCandidate
2266 | BuiltinUnsizeCandidate
2267 | BuiltinCandidate { .. } => {
2268 // Global bounds from the where clause should be ignored
2269 // here (see issue #50825). Otherwise, we have a where
2270 // clause so don't go around looking for impls.
2273 ObjectCandidate | ProjectionCandidate => {
2274 // Arbitrarily give param candidates priority
2275 // over projection and object candidates.
2278 ParamCandidate(..) => false,
2280 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2281 AutoImplCandidate(..) => {
2283 "default implementations shouldn't be recorded \
2284 when there are other valid candidates"
2287 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2288 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2289 // lifetime of a variable.
2290 BuiltinCandidate { has_nested: false } => false,
2293 | GeneratorCandidate
2294 | FnPointerCandidate
2295 | BuiltinObjectCandidate
2296 | BuiltinUnsizeCandidate
2297 | BuiltinCandidate { .. } => true,
2298 ObjectCandidate | ProjectionCandidate => {
2299 // Arbitrarily give param candidates priority
2300 // over projection and object candidates.
2303 ParamCandidate(ref cand) => is_global(cand),
2305 ImplCandidate(other_def) => {
2306 // See if we can toss out `victim` based on specialization.
2307 // This requires us to know *for sure* that the `other` impl applies
2308 // i.e. EvaluatedToOk:
2309 if other.evaluation == EvaluatedToOk {
2310 match victim.candidate {
2311 ImplCandidate(victim_def) => {
2312 let tcx = self.tcx().global_tcx();
2313 return tcx.specializes((other_def, victim_def))
2314 || tcx.impls_are_allowed_to_overlap(other_def, victim_def);
2316 ParamCandidate(ref cand) => {
2317 // Prefer the impl to a global where clause candidate.
2318 return is_global(cand);
2327 | GeneratorCandidate
2328 | FnPointerCandidate
2329 | BuiltinObjectCandidate
2330 | BuiltinUnsizeCandidate
2331 | BuiltinCandidate { has_nested: true } => {
2332 match victim.candidate {
2333 ParamCandidate(ref cand) => {
2334 // Prefer these to a global where-clause bound
2335 // (see issue #50825)
2336 is_global(cand) && other.evaluation == EvaluatedToOk
2345 ///////////////////////////////////////////////////////////////////////////
2348 // These cover the traits that are built-in to the language
2349 // itself: `Copy`, `Clone` and `Sized`.
2351 fn assemble_builtin_bound_candidates<'o>(
2353 conditions: BuiltinImplConditions<'tcx>,
2354 candidates: &mut SelectionCandidateSet<'tcx>,
2355 ) -> Result<(), SelectionError<'tcx>> {
2357 BuiltinImplConditions::Where(nested) => {
2358 debug!("builtin_bound: nested={:?}", nested);
2359 candidates.vec.push(BuiltinCandidate {
2360 has_nested: nested.skip_binder().len() > 0,
2363 BuiltinImplConditions::None => {}
2364 BuiltinImplConditions::Ambiguous => {
2365 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2366 candidates.ambiguous = true;
2373 fn sized_conditions(
2375 obligation: &TraitObligation<'tcx>,
2376 ) -> BuiltinImplConditions<'tcx> {
2377 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2379 // NOTE: binder moved to (*)
2380 let self_ty = self.infcx
2381 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2384 ty::Infer(ty::IntVar(_))
2385 | ty::Infer(ty::FloatVar(_))
2396 | ty::GeneratorWitness(..)
2401 // safe for everything
2402 Where(ty::Binder::dummy(Vec::new()))
2405 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2407 ty::Tuple(tys) => Where(ty::Binder::bind(tys.last().into_iter().cloned().collect())),
2409 ty::Adt(def, substs) => {
2410 let sized_crit = def.sized_constraint(self.tcx());
2411 // (*) binder moved here
2412 Where(ty::Binder::bind(
2415 .map(|ty| ty.subst(self.tcx(), substs))
2420 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2421 ty::Infer(ty::TyVar(_)) => Ambiguous,
2423 ty::UnnormalizedProjection(..)
2424 | ty::Infer(ty::CanonicalTy(_))
2425 | ty::Infer(ty::FreshTy(_))
2426 | ty::Infer(ty::FreshIntTy(_))
2427 | ty::Infer(ty::FreshFloatTy(_)) => {
2429 "asked to assemble builtin bounds of unexpected type: {:?}",
2436 fn copy_clone_conditions(
2438 obligation: &TraitObligation<'tcx>,
2439 ) -> BuiltinImplConditions<'tcx> {
2440 // NOTE: binder moved to (*)
2441 let self_ty = self.infcx
2442 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2444 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2447 ty::Infer(ty::IntVar(_))
2448 | ty::Infer(ty::FloatVar(_))
2451 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2460 | ty::Ref(_, _, hir::MutImmutable) => {
2461 // Implementations provided in libcore
2469 | ty::GeneratorWitness(..)
2471 | ty::Ref(_, _, hir::MutMutable) => None,
2473 ty::Array(element_ty, _) => {
2474 // (*) binder moved here
2475 Where(ty::Binder::bind(vec![element_ty]))
2479 // (*) binder moved here
2480 Where(ty::Binder::bind(tys.to_vec()))
2483 ty::Closure(def_id, substs) => {
2484 let trait_id = obligation.predicate.def_id();
2485 let is_copy_trait = Some(trait_id) == self.tcx().lang_items().copy_trait();
2486 let is_clone_trait = Some(trait_id) == self.tcx().lang_items().clone_trait();
2487 if is_copy_trait || is_clone_trait {
2488 Where(ty::Binder::bind(
2489 substs.upvar_tys(def_id, self.tcx()).collect(),
2496 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2497 // Fallback to whatever user-defined impls exist in this case.
2501 ty::Infer(ty::TyVar(_)) => {
2502 // Unbound type variable. Might or might not have
2503 // applicable impls and so forth, depending on what
2504 // those type variables wind up being bound to.
2508 ty::UnnormalizedProjection(..)
2509 | ty::Infer(ty::CanonicalTy(_))
2510 | ty::Infer(ty::FreshTy(_))
2511 | ty::Infer(ty::FreshIntTy(_))
2512 | ty::Infer(ty::FreshFloatTy(_)) => {
2514 "asked to assemble builtin bounds of unexpected type: {:?}",
2521 /// For default impls, we need to break apart a type into its
2522 /// "constituent types" -- meaning, the types that it contains.
2524 /// Here are some (simple) examples:
2527 /// (i32, u32) -> [i32, u32]
2528 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2529 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2530 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2532 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2542 | ty::Infer(ty::IntVar(_))
2543 | ty::Infer(ty::FloatVar(_))
2545 | ty::Char => Vec::new(),
2547 ty::UnnormalizedProjection(..)
2551 | ty::Projection(..)
2552 | ty::Infer(ty::CanonicalTy(_))
2553 | ty::Infer(ty::TyVar(_))
2554 | ty::Infer(ty::FreshTy(_))
2555 | ty::Infer(ty::FreshIntTy(_))
2556 | ty::Infer(ty::FreshFloatTy(_)) => {
2558 "asked to assemble constituent types of unexpected type: {:?}",
2563 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2567 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2569 ty::Tuple(ref tys) => {
2570 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2574 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(),
2576 ty::Generator(def_id, ref substs, _) => {
2577 let witness = substs.witness(def_id, self.tcx());
2579 .upvar_tys(def_id, self.tcx())
2580 .chain(iter::once(witness))
2584 ty::GeneratorWitness(types) => {
2585 // This is sound because no regions in the witness can refer to
2586 // the binder outside the witness. So we'll effectivly reuse
2587 // the implicit binder around the witness.
2588 types.skip_binder().to_vec()
2591 // for `PhantomData<T>`, we pass `T`
2592 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2594 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2596 ty::Opaque(def_id, substs) => {
2597 // We can resolve the `impl Trait` to its concrete type,
2598 // which enforces a DAG between the functions requiring
2599 // the auto trait bounds in question.
2600 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2605 fn collect_predicates_for_types(
2607 param_env: ty::ParamEnv<'tcx>,
2608 cause: ObligationCause<'tcx>,
2609 recursion_depth: usize,
2610 trait_def_id: DefId,
2611 types: ty::Binder<Vec<Ty<'tcx>>>,
2612 ) -> Vec<PredicateObligation<'tcx>> {
2613 // Because the types were potentially derived from
2614 // higher-ranked obligations they may reference late-bound
2615 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2616 // yield a type like `for<'a> &'a int`. In general, we
2617 // maintain the invariant that we never manipulate bound
2618 // regions, so we have to process these bound regions somehow.
2620 // The strategy is to:
2622 // 1. Instantiate those regions to placeholder regions (e.g.,
2623 // `for<'a> &'a int` becomes `&0 int`.
2624 // 2. Produce something like `&'0 int : Copy`
2625 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2632 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2634 self.in_snapshot(|this, snapshot| {
2635 let (skol_ty, placeholder_map) = this.infcx()
2636 .replace_late_bound_regions_with_placeholders(&ty);
2638 value: normalized_ty,
2640 } = project::normalize_with_depth(
2647 let skol_obligation = this.tcx().predicate_for_trait_def(
2655 obligations.push(skol_obligation);
2657 .plug_leaks(placeholder_map, snapshot, obligations)
2663 ///////////////////////////////////////////////////////////////////////////
2666 // Confirmation unifies the output type parameters of the trait
2667 // with the values found in the obligation, possibly yielding a
2668 // type error. See [rustc guide] for more details.
2671 // https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#confirmation
2673 fn confirm_candidate(
2675 obligation: &TraitObligation<'tcx>,
2676 candidate: SelectionCandidate<'tcx>,
2677 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2678 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2681 BuiltinCandidate { has_nested } => {
2682 let data = self.confirm_builtin_candidate(obligation, has_nested);
2683 Ok(VtableBuiltin(data))
2686 ParamCandidate(param) => {
2687 let obligations = self.confirm_param_candidate(obligation, param);
2688 Ok(VtableParam(obligations))
2691 AutoImplCandidate(trait_def_id) => {
2692 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2693 Ok(VtableAutoImpl(data))
2696 ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
2701 ClosureCandidate => {
2702 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2703 Ok(VtableClosure(vtable_closure))
2706 GeneratorCandidate => {
2707 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2708 Ok(VtableGenerator(vtable_generator))
2711 BuiltinObjectCandidate => {
2712 // This indicates something like `(Trait+Send) :
2713 // Send`. In this case, we know that this holds
2714 // because that's what the object type is telling us,
2715 // and there's really no additional obligations to
2716 // prove and no types in particular to unify etc.
2717 Ok(VtableParam(Vec::new()))
2720 ObjectCandidate => {
2721 let data = self.confirm_object_candidate(obligation);
2722 Ok(VtableObject(data))
2725 FnPointerCandidate => {
2726 let data = self.confirm_fn_pointer_candidate(obligation)?;
2727 Ok(VtableFnPointer(data))
2730 ProjectionCandidate => {
2731 self.confirm_projection_candidate(obligation);
2732 Ok(VtableParam(Vec::new()))
2735 BuiltinUnsizeCandidate => {
2736 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2737 Ok(VtableBuiltin(data))
2742 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2743 self.in_snapshot(|this, snapshot| {
2745 this.match_projection_obligation_against_definition_bounds(obligation, snapshot);
2750 fn confirm_param_candidate(
2752 obligation: &TraitObligation<'tcx>,
2753 param: ty::PolyTraitRef<'tcx>,
2754 ) -> Vec<PredicateObligation<'tcx>> {
2755 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2757 // During evaluation, we already checked that this
2758 // where-clause trait-ref could be unified with the obligation
2759 // trait-ref. Repeat that unification now without any
2760 // transactional boundary; it should not fail.
2761 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2762 Ok(obligations) => obligations,
2765 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2773 fn confirm_builtin_candidate(
2775 obligation: &TraitObligation<'tcx>,
2777 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2779 "confirm_builtin_candidate({:?}, {:?})",
2780 obligation, has_nested
2783 let lang_items = self.tcx().lang_items();
2784 let obligations = if has_nested {
2785 let trait_def = obligation.predicate.def_id();
2786 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2787 self.sized_conditions(obligation)
2788 } else if Some(trait_def) == lang_items.copy_trait() {
2789 self.copy_clone_conditions(obligation)
2790 } else if Some(trait_def) == lang_items.clone_trait() {
2791 self.copy_clone_conditions(obligation)
2793 bug!("unexpected builtin trait {:?}", trait_def)
2795 let nested = match conditions {
2796 BuiltinImplConditions::Where(nested) => nested,
2798 "obligation {:?} had matched a builtin impl but now doesn't",
2803 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2804 self.collect_predicates_for_types(
2805 obligation.param_env,
2807 obligation.recursion_depth + 1,
2815 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2818 nested: obligations,
2822 /// This handles the case where a `auto trait Foo` impl is being used.
2823 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2825 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2826 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2827 fn confirm_auto_impl_candidate(
2829 obligation: &TraitObligation<'tcx>,
2830 trait_def_id: DefId,
2831 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2833 "confirm_auto_impl_candidate({:?}, {:?})",
2834 obligation, trait_def_id
2837 let types = obligation.predicate.map_bound(|inner| {
2838 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2839 self.constituent_types_for_ty(self_ty)
2841 self.vtable_auto_impl(obligation, trait_def_id, types)
2844 /// See `confirm_auto_impl_candidate`
2845 fn vtable_auto_impl(
2847 obligation: &TraitObligation<'tcx>,
2848 trait_def_id: DefId,
2849 nested: ty::Binder<Vec<Ty<'tcx>>>,
2850 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2851 debug!("vtable_auto_impl: nested={:?}", nested);
2853 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2854 let mut obligations = self.collect_predicates_for_types(
2855 obligation.param_env,
2857 obligation.recursion_depth + 1,
2862 let trait_obligations: Vec<PredicateObligation<'_>> = self.in_snapshot(|this, snapshot| {
2863 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2864 let (trait_ref, placeholder_map) = this.infcx()
2865 .replace_late_bound_regions_with_placeholders(&poly_trait_ref);
2866 let cause = obligation.derived_cause(ImplDerivedObligation);
2867 this.impl_or_trait_obligations(
2869 obligation.recursion_depth + 1,
2870 obligation.param_env,
2878 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
2879 // predicate as usual. It won't have any effect since auto traits are coinductive.
2880 obligations.extend(trait_obligations);
2882 debug!("vtable_auto_impl: obligations={:?}", obligations);
2884 VtableAutoImplData {
2886 nested: obligations,
2890 fn confirm_impl_candidate(
2892 obligation: &TraitObligation<'tcx>,
2894 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2895 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
2897 // First, create the substitutions by matching the impl again,
2898 // this time not in a probe.
2899 self.in_snapshot(|this, snapshot| {
2900 let (substs, placeholder_map) = this.rematch_impl(impl_def_id, obligation, snapshot);
2901 debug!("confirm_impl_candidate substs={:?}", substs);
2902 let cause = obligation.derived_cause(ImplDerivedObligation);
2907 obligation.recursion_depth + 1,
2908 obligation.param_env,
2918 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2919 cause: ObligationCause<'tcx>,
2920 recursion_depth: usize,
2921 param_env: ty::ParamEnv<'tcx>,
2922 placeholder_map: infer::PlaceholderMap<'tcx>,
2923 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
2924 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2926 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, placeholder_map={:?})",
2927 impl_def_id, substs, recursion_depth, placeholder_map
2930 let mut impl_obligations = self.impl_or_trait_obligations(
2941 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2942 impl_def_id, impl_obligations
2945 // Because of RFC447, the impl-trait-ref and obligations
2946 // are sufficient to determine the impl substs, without
2947 // relying on projections in the impl-trait-ref.
2949 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2950 impl_obligations.append(&mut substs.obligations);
2954 substs: substs.value,
2955 nested: impl_obligations,
2959 fn confirm_object_candidate(
2961 obligation: &TraitObligation<'tcx>,
2962 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
2963 debug!("confirm_object_candidate({:?})", obligation);
2965 // FIXME skipping binder here seems wrong -- we should
2966 // probably flatten the binder from the obligation and the
2967 // binder from the object. Have to try to make a broken test
2968 // case that results. -nmatsakis
2969 let self_ty = self.infcx
2970 .shallow_resolve(*obligation.self_ty().skip_binder());
2971 let poly_trait_ref = match self_ty.sty {
2972 ty::Dynamic(ref data, ..) => {
2973 data.principal().with_self_ty(self.tcx(), self_ty)
2975 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
2978 let mut upcast_trait_ref = None;
2979 let mut nested = vec![];
2983 let tcx = self.tcx();
2985 // We want to find the first supertrait in the list of
2986 // supertraits that we can unify with, and do that
2987 // unification. We know that there is exactly one in the list
2988 // where we can unify because otherwise select would have
2989 // reported an ambiguity. (When we do find a match, also
2990 // record it for later.)
2991 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
2992 |&t| match self.commit_if_ok(|this, _| this.match_poly_trait_ref(obligation, t)) {
2993 Ok(obligations) => {
2994 upcast_trait_ref = Some(t);
2995 nested.extend(obligations);
3002 // Additionally, for each of the nonmatching predicates that
3003 // we pass over, we sum up the set of number of vtable
3004 // entries, so that we can compute the offset for the selected
3006 vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
3010 upcast_trait_ref: upcast_trait_ref.unwrap(),
3016 fn confirm_fn_pointer_candidate(
3018 obligation: &TraitObligation<'tcx>,
3019 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3020 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3022 // ok to skip binder; it is reintroduced below
3023 let self_ty = self.infcx
3024 .shallow_resolve(*obligation.self_ty().skip_binder());
3025 let sig = self_ty.fn_sig(self.tcx());
3026 let trait_ref = self.tcx()
3027 .closure_trait_ref_and_return_type(
3028 obligation.predicate.def_id(),
3031 util::TupleArgumentsFlag::Yes,
3033 .map_bound(|(trait_ref, _)| trait_ref);
3038 } = project::normalize_with_depth(
3040 obligation.param_env,
3041 obligation.cause.clone(),
3042 obligation.recursion_depth + 1,
3046 self.confirm_poly_trait_refs(
3047 obligation.cause.clone(),
3048 obligation.param_env,
3049 obligation.predicate.to_poly_trait_ref(),
3052 Ok(VtableFnPointerData {
3054 nested: obligations,
3058 fn confirm_generator_candidate(
3060 obligation: &TraitObligation<'tcx>,
3061 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3062 // ok to skip binder because the substs on generator types never
3063 // touch bound regions, they just capture the in-scope
3064 // type/region parameters
3065 let self_ty = self.infcx
3066 .shallow_resolve(obligation.self_ty().skip_binder());
3067 let (generator_def_id, substs) = match self_ty.sty {
3068 ty::Generator(id, substs, _) => (id, substs),
3069 _ => bug!("closure candidate for non-closure {:?}", obligation),
3073 "confirm_generator_candidate({:?},{:?},{:?})",
3074 obligation, generator_def_id, substs
3077 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3081 } = normalize_with_depth(
3083 obligation.param_env,
3084 obligation.cause.clone(),
3085 obligation.recursion_depth + 1,
3090 "confirm_generator_candidate(generator_def_id={:?}, \
3091 trait_ref={:?}, obligations={:?})",
3092 generator_def_id, trait_ref, obligations
3095 obligations.extend(self.confirm_poly_trait_refs(
3096 obligation.cause.clone(),
3097 obligation.param_env,
3098 obligation.predicate.to_poly_trait_ref(),
3102 Ok(VtableGeneratorData {
3103 generator_def_id: generator_def_id,
3104 substs: substs.clone(),
3105 nested: obligations,
3109 fn confirm_closure_candidate(
3111 obligation: &TraitObligation<'tcx>,
3112 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3113 debug!("confirm_closure_candidate({:?})", obligation);
3115 let kind = self.tcx()
3117 .fn_trait_kind(obligation.predicate.def_id())
3118 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3120 // ok to skip binder because the substs on closure types never
3121 // touch bound regions, they just capture the in-scope
3122 // type/region parameters
3123 let self_ty = self.infcx
3124 .shallow_resolve(obligation.self_ty().skip_binder());
3125 let (closure_def_id, substs) = match self_ty.sty {
3126 ty::Closure(id, substs) => (id, substs),
3127 _ => bug!("closure candidate for non-closure {:?}", obligation),
3130 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3134 } = normalize_with_depth(
3136 obligation.param_env,
3137 obligation.cause.clone(),
3138 obligation.recursion_depth + 1,
3143 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3144 closure_def_id, trait_ref, obligations
3147 obligations.extend(self.confirm_poly_trait_refs(
3148 obligation.cause.clone(),
3149 obligation.param_env,
3150 obligation.predicate.to_poly_trait_ref(),
3154 obligations.push(Obligation::new(
3155 obligation.cause.clone(),
3156 obligation.param_env,
3157 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3160 Ok(VtableClosureData {
3162 substs: substs.clone(),
3163 nested: obligations,
3167 /// In the case of closure types and fn pointers,
3168 /// we currently treat the input type parameters on the trait as
3169 /// outputs. This means that when we have a match we have only
3170 /// considered the self type, so we have to go back and make sure
3171 /// to relate the argument types too. This is kind of wrong, but
3172 /// since we control the full set of impls, also not that wrong,
3173 /// and it DOES yield better error messages (since we don't report
3174 /// errors as if there is no applicable impl, but rather report
3175 /// errors are about mismatched argument types.
3177 /// Here is an example. Imagine we have a closure expression
3178 /// and we desugared it so that the type of the expression is
3179 /// `Closure`, and `Closure` expects an int as argument. Then it
3180 /// is "as if" the compiler generated this impl:
3182 /// impl Fn(int) for Closure { ... }
3184 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3185 /// we have matched the self-type `Closure`. At this point we'll
3186 /// compare the `int` to `usize` and generate an error.
3188 /// Note that this checking occurs *after* the impl has selected,
3189 /// because these output type parameters should not affect the
3190 /// selection of the impl. Therefore, if there is a mismatch, we
3191 /// report an error to the user.
3192 fn confirm_poly_trait_refs(
3194 obligation_cause: ObligationCause<'tcx>,
3195 obligation_param_env: ty::ParamEnv<'tcx>,
3196 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3197 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3198 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3199 let obligation_trait_ref = obligation_trait_ref.clone();
3201 .at(&obligation_cause, obligation_param_env)
3202 .sup(obligation_trait_ref, expected_trait_ref)
3203 .map(|InferOk { obligations, .. }| obligations)
3204 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3207 fn confirm_builtin_unsize_candidate(
3209 obligation: &TraitObligation<'tcx>,
3210 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3211 let tcx = self.tcx();
3213 // assemble_candidates_for_unsizing should ensure there are no late bound
3214 // regions here. See the comment there for more details.
3215 let source = self.infcx
3216 .shallow_resolve(obligation.self_ty().no_late_bound_regions().unwrap());
3217 let target = obligation
3223 let target = self.infcx.shallow_resolve(target);
3226 "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
3230 let mut nested = vec![];
3231 match (&source.sty, &target.sty) {
3232 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3233 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3234 // See assemble_candidates_for_unsizing for more info.
3235 let existential_predicates = data_a.map_bound(|data_a| {
3236 let iter = iter::once(ty::ExistentialPredicate::Trait(data_a.principal()))
3239 .projection_bounds()
3240 .map(|x| ty::ExistentialPredicate::Projection(x)),
3245 .map(ty::ExistentialPredicate::AutoTrait),
3247 tcx.mk_existential_predicates(iter)
3249 let new_trait = tcx.mk_dynamic(existential_predicates, r_b);
3250 let InferOk { obligations, .. } = self.infcx
3251 .at(&obligation.cause, obligation.param_env)
3252 .eq(target, new_trait)
3253 .map_err(|_| Unimplemented)?;
3254 nested.extend(obligations);
3256 // Register one obligation for 'a: 'b.
3257 let cause = ObligationCause::new(
3258 obligation.cause.span,
3259 obligation.cause.body_id,
3260 ObjectCastObligation(target),
3262 let outlives = ty::OutlivesPredicate(r_a, r_b);
3263 nested.push(Obligation::with_depth(
3265 obligation.recursion_depth + 1,
3266 obligation.param_env,
3267 ty::Binder::bind(outlives).to_predicate(),
3272 (_, &ty::Dynamic(ref data, r)) => {
3273 let mut object_dids = data.auto_traits()
3274 .chain(iter::once(data.principal().def_id()));
3275 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3276 return Err(TraitNotObjectSafe(did));
3279 let cause = ObligationCause::new(
3280 obligation.cause.span,
3281 obligation.cause.body_id,
3282 ObjectCastObligation(target),
3285 let predicate_to_obligation = |predicate| {
3286 Obligation::with_depth(
3288 obligation.recursion_depth + 1,
3289 obligation.param_env,
3294 // Create obligations:
3295 // - Casting T to Trait
3296 // - For all the various builtin bounds attached to the object cast. (In other
3297 // words, if the object type is Foo+Send, this would create an obligation for the
3299 // - Projection predicates
3302 .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
3305 // We can only make objects from sized types.
3306 let tr = ty::TraitRef {
3307 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
3308 substs: tcx.mk_substs_trait(source, &[]),
3310 nested.push(predicate_to_obligation(tr.to_predicate()));
3312 // If the type is `Foo+'a`, ensures that the type
3313 // being cast to `Foo+'a` outlives `'a`:
3314 let outlives = ty::OutlivesPredicate(source, r);
3315 nested.push(predicate_to_obligation(
3316 ty::Binder::dummy(outlives).to_predicate(),
3321 (&ty::Array(a, _), &ty::Slice(b)) => {
3322 let InferOk { obligations, .. } = self.infcx
3323 .at(&obligation.cause, obligation.param_env)
3325 .map_err(|_| Unimplemented)?;
3326 nested.extend(obligations);
3329 // Struct<T> -> Struct<U>.
3330 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3331 let fields = def.all_fields()
3332 .map(|f| tcx.type_of(f.did))
3333 .collect::<Vec<_>>();
3335 // The last field of the structure has to exist and contain type parameters.
3336 let field = if let Some(&field) = fields.last() {
3339 return Err(Unimplemented);
3341 let mut ty_params = GrowableBitSet::new_empty();
3342 let mut found = false;
3343 for ty in field.walk() {
3344 if let ty::Param(p) = ty.sty {
3345 ty_params.insert(p.idx as usize);
3350 return Err(Unimplemented);
3353 // Replace type parameters used in unsizing with
3354 // Error and ensure they do not affect any other fields.
3355 // This could be checked after type collection for any struct
3356 // with a potentially unsized trailing field.
3357 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3358 if ty_params.contains(i) {
3359 tcx.types.err.into()
3364 let substs = tcx.mk_substs(params);
3365 for &ty in fields.split_last().unwrap().1 {
3366 if ty.subst(tcx, substs).references_error() {
3367 return Err(Unimplemented);
3371 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3372 let inner_source = field.subst(tcx, substs_a);
3373 let inner_target = field.subst(tcx, substs_b);
3375 // Check that the source struct with the target's
3376 // unsized parameters is equal to the target.
3377 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3378 if ty_params.contains(i) {
3379 substs_b.type_at(i).into()
3384 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3385 let InferOk { obligations, .. } = self.infcx
3386 .at(&obligation.cause, obligation.param_env)
3387 .eq(target, new_struct)
3388 .map_err(|_| Unimplemented)?;
3389 nested.extend(obligations);
3391 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3392 nested.push(tcx.predicate_for_trait_def(
3393 obligation.param_env,
3394 obligation.cause.clone(),
3395 obligation.predicate.def_id(),
3396 obligation.recursion_depth + 1,
3398 &[inner_target.into()],
3402 // (.., T) -> (.., U).
3403 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3404 assert_eq!(tys_a.len(), tys_b.len());
3406 // The last field of the tuple has to exist.
3407 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3410 return Err(Unimplemented);
3412 let &b_last = tys_b.last().unwrap();
3414 // Check that the source tuple with the target's
3415 // last element is equal to the target.
3416 let new_tuple = tcx.mk_tup(a_mid.iter().cloned().chain(iter::once(b_last)));
3417 let InferOk { obligations, .. } = self.infcx
3418 .at(&obligation.cause, obligation.param_env)
3419 .eq(target, new_tuple)
3420 .map_err(|_| Unimplemented)?;
3421 nested.extend(obligations);
3423 // Construct the nested T: Unsize<U> predicate.
3424 nested.push(tcx.predicate_for_trait_def(
3425 obligation.param_env,
3426 obligation.cause.clone(),
3427 obligation.predicate.def_id(),
3428 obligation.recursion_depth + 1,
3437 Ok(VtableBuiltinData { nested: nested })
3440 ///////////////////////////////////////////////////////////////////////////
3443 // Matching is a common path used for both evaluation and
3444 // confirmation. It basically unifies types that appear in impls
3445 // and traits. This does affect the surrounding environment;
3446 // therefore, when used during evaluation, match routines must be
3447 // run inside of a `probe()` so that their side-effects are
3453 obligation: &TraitObligation<'tcx>,
3454 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3456 Normalized<'tcx, &'tcx Substs<'tcx>>,
3457 infer::PlaceholderMap<'tcx>,
3459 match self.match_impl(impl_def_id, obligation, snapshot) {
3460 Ok((substs, placeholder_map)) => (substs, placeholder_map),
3463 "Impl {:?} was matchable against {:?} but now is not",
3474 obligation: &TraitObligation<'tcx>,
3475 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3478 Normalized<'tcx, &'tcx Substs<'tcx>>,
3479 infer::PlaceholderMap<'tcx>,
3483 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3485 // Before we create the substitutions and everything, first
3486 // consider a "quick reject". This avoids creating more types
3487 // and so forth that we need to.
3488 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3492 let (skol_obligation, placeholder_map) = self.infcx()
3493 .replace_late_bound_regions_with_placeholders(&obligation.predicate);
3494 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3496 let impl_substs = self.infcx
3497 .fresh_substs_for_item(obligation.cause.span, impl_def_id);
3499 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3502 value: impl_trait_ref,
3503 obligations: mut nested_obligations,
3504 } = project::normalize_with_depth(
3506 obligation.param_env,
3507 obligation.cause.clone(),
3508 obligation.recursion_depth + 1,
3513 "match_impl(impl_def_id={:?}, obligation={:?}, \
3514 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3515 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3518 let InferOk { obligations, .. } = self.infcx
3519 .at(&obligation.cause, obligation.param_env)
3520 .eq(skol_obligation_trait_ref, impl_trait_ref)
3521 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3522 nested_obligations.extend(obligations);
3526 .leak_check(false, obligation.cause.span, &placeholder_map, snapshot)
3528 debug!("match_impl: failed leak check due to `{}`", e);
3532 debug!("match_impl: success impl_substs={:?}", impl_substs);
3536 obligations: nested_obligations,
3542 fn fast_reject_trait_refs(
3544 obligation: &TraitObligation<'_>,
3545 impl_trait_ref: &ty::TraitRef<'_>,
3547 // We can avoid creating type variables and doing the full
3548 // substitution if we find that any of the input types, when
3549 // simplified, do not match.
3555 .zip(impl_trait_ref.input_types())
3556 .any(|(obligation_ty, impl_ty)| {
3557 let simplified_obligation_ty =
3558 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3559 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3561 simplified_obligation_ty.is_some()
3562 && simplified_impl_ty.is_some()
3563 && simplified_obligation_ty != simplified_impl_ty
3567 /// Normalize `where_clause_trait_ref` and try to match it against
3568 /// `obligation`. If successful, return any predicates that
3569 /// result from the normalization. Normalization is necessary
3570 /// because where-clauses are stored in the parameter environment
3572 fn match_where_clause_trait_ref(
3574 obligation: &TraitObligation<'tcx>,
3575 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3576 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3577 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3580 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3581 /// obligation is satisfied.
3582 fn match_poly_trait_ref(
3584 obligation: &TraitObligation<'tcx>,
3585 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3586 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3588 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3589 obligation, poly_trait_ref
3593 .at(&obligation.cause, obligation.param_env)
3594 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3595 .map(|InferOk { obligations, .. }| obligations)
3599 ///////////////////////////////////////////////////////////////////////////
3602 fn match_fresh_trait_refs(
3604 previous: &ty::PolyTraitRef<'tcx>,
3605 current: &ty::PolyTraitRef<'tcx>,
3607 let mut matcher = ty::_match::Match::new(self.tcx());
3608 matcher.relate(previous, current).is_ok()
3611 fn push_stack<'o, 's: 'o>(
3613 previous_stack: TraitObligationStackList<'s, 'tcx>,
3614 obligation: &'o TraitObligation<'tcx>,
3615 ) -> TraitObligationStack<'o, 'tcx> {
3616 let fresh_trait_ref = obligation
3618 .to_poly_trait_ref()
3619 .fold_with(&mut self.freshener);
3621 TraitObligationStack {
3624 previous: previous_stack,
3628 fn closure_trait_ref_unnormalized(
3630 obligation: &TraitObligation<'tcx>,
3631 closure_def_id: DefId,
3632 substs: ty::ClosureSubsts<'tcx>,
3633 ) -> ty::PolyTraitRef<'tcx> {
3634 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3636 // (1) Feels icky to skip the binder here, but OTOH we know
3637 // that the self-type is an unboxed closure type and hence is
3638 // in fact unparameterized (or at least does not reference any
3639 // regions bound in the obligation). Still probably some
3640 // refactoring could make this nicer.
3642 .closure_trait_ref_and_return_type(
3643 obligation.predicate.def_id(),
3644 obligation.predicate.skip_binder().self_ty(), // (1)
3646 util::TupleArgumentsFlag::No,
3648 .map_bound(|(trait_ref, _)| trait_ref)
3651 fn generator_trait_ref_unnormalized(
3653 obligation: &TraitObligation<'tcx>,
3654 closure_def_id: DefId,
3655 substs: ty::GeneratorSubsts<'tcx>,
3656 ) -> ty::PolyTraitRef<'tcx> {
3657 let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
3659 // (1) Feels icky to skip the binder here, but OTOH we know
3660 // that the self-type is an generator type and hence is
3661 // in fact unparameterized (or at least does not reference any
3662 // regions bound in the obligation). Still probably some
3663 // refactoring could make this nicer.
3666 .generator_trait_ref_and_outputs(
3667 obligation.predicate.def_id(),
3668 obligation.predicate.skip_binder().self_ty(), // (1)
3671 .map_bound(|(trait_ref, ..)| trait_ref)
3674 /// Returns the obligations that are implied by instantiating an
3675 /// impl or trait. The obligations are substituted and fully
3676 /// normalized. This is used when confirming an impl or default
3678 fn impl_or_trait_obligations(
3680 cause: ObligationCause<'tcx>,
3681 recursion_depth: usize,
3682 param_env: ty::ParamEnv<'tcx>,
3683 def_id: DefId, // of impl or trait
3684 substs: &Substs<'tcx>, // for impl or trait
3685 placeholder_map: infer::PlaceholderMap<'tcx>,
3686 snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
3687 ) -> Vec<PredicateObligation<'tcx>> {
3688 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3689 let tcx = self.tcx();
3691 // To allow for one-pass evaluation of the nested obligation,
3692 // each predicate must be preceded by the obligations required
3694 // for example, if we have:
3695 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3696 // the impl will have the following predicates:
3697 // <V as Iterator>::Item = U,
3698 // U: Iterator, U: Sized,
3699 // V: Iterator, V: Sized,
3700 // <U as Iterator>::Item: Copy
3701 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3702 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3703 // `$1: Copy`, so we must ensure the obligations are emitted in
3705 let predicates = tcx.predicates_of(def_id);
3706 assert_eq!(predicates.parent, None);
3707 let mut predicates: Vec<_> = predicates
3710 .flat_map(|(predicate, _)| {
3711 let predicate = normalize_with_depth(
3716 &predicate.subst(tcx, substs),
3718 predicate.obligations.into_iter().chain(Some(Obligation {
3719 cause: cause.clone(),
3722 predicate: predicate.value,
3727 // We are performing deduplication here to avoid exponential blowups
3728 // (#38528) from happening, but the real cause of the duplication is
3729 // unknown. What we know is that the deduplication avoids exponential
3730 // amount of predicates being propagated when processing deeply nested
3733 // This code is hot enough that it's worth avoiding the allocation
3734 // required for the FxHashSet when possible. Special-casing lengths 0,
3735 // 1 and 2 covers roughly 75--80% of the cases.
3736 if predicates.len() <= 1 {
3737 // No possibility of duplicates.
3738 } else if predicates.len() == 2 {
3739 // Only two elements. Drop the second if they are equal.
3740 if predicates[0] == predicates[1] {
3741 predicates.truncate(1);
3744 // Three or more elements. Use a general deduplication process.
3745 let mut seen = FxHashSet::default();
3746 predicates.retain(|i| seen.insert(i.clone()));
3749 .plug_leaks(placeholder_map, snapshot, predicates)
3753 impl<'tcx> TraitObligation<'tcx> {
3754 #[allow(unused_comparisons)]
3755 pub fn derived_cause(
3757 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3758 ) -> ObligationCause<'tcx> {
3760 * Creates a cause for obligations that are derived from
3761 * `obligation` by a recursive search (e.g., for a builtin
3762 * bound, or eventually a `auto trait Foo`). If `obligation`
3763 * is itself a derived obligation, this is just a clone, but
3764 * otherwise we create a "derived obligation" cause so as to
3765 * keep track of the original root obligation for error
3769 let obligation = self;
3771 // NOTE(flaper87): As of now, it keeps track of the whole error
3772 // chain. Ideally, we should have a way to configure this either
3773 // by using -Z verbose or just a CLI argument.
3774 if obligation.recursion_depth >= 0 {
3775 let derived_cause = DerivedObligationCause {
3776 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3777 parent_code: Rc::new(obligation.cause.code.clone()),
3779 let derived_code = variant(derived_cause);
3780 ObligationCause::new(
3781 obligation.cause.span,
3782 obligation.cause.body_id,
3786 obligation.cause.clone()
3791 impl<'tcx> SelectionCache<'tcx> {
3792 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3793 pub fn clear(&self) {
3794 *self.hashmap.borrow_mut() = Default::default();
3798 impl<'tcx> EvaluationCache<'tcx> {
3799 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3800 pub fn clear(&self) {
3801 *self.hashmap.borrow_mut() = Default::default();
3805 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
3806 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3807 TraitObligationStackList::with(self)
3810 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3815 #[derive(Copy, Clone)]
3816 struct TraitObligationStackList<'o, 'tcx: 'o> {
3817 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3820 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3821 fn empty() -> TraitObligationStackList<'o, 'tcx> {
3822 TraitObligationStackList { head: None }
3825 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3826 TraitObligationStackList { head: Some(r) }
3830 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
3831 type Item = &'o TraitObligationStack<'o, 'tcx>;
3833 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3844 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
3845 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3846 write!(f, "TraitObligationStack({:?})", self.obligation)
3850 #[derive(Clone, Eq, PartialEq)]
3851 pub struct WithDepNode<T> {
3852 dep_node: DepNodeIndex,
3856 impl<T: Clone> WithDepNode<T> {
3857 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3864 pub fn get(&self, tcx: TyCtxt<'_, '_, '_>) -> T {
3865 tcx.dep_graph.read_index(self.dep_node);
3866 self.cached_value.clone()