1 // ignore-tidy-filelength
3 //! Candidate selection. See the [rustc dev guide] for more information on how this works.
5 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
7 use self::EvaluationResult::*;
8 use self::SelectionCandidate::*;
10 use super::coherence::{self, Conflict};
12 use super::project::{normalize_with_depth, normalize_with_depth_to};
14 use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
16 use super::DerivedObligationCause;
18 use super::SelectionResult;
19 use super::TraitNotObjectSafe;
20 use super::TraitQueryMode;
21 use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
22 use super::{Normalized, ProjectionCacheKey};
23 use super::{ObjectCastObligation, Obligation};
24 use super::{ObligationCause, PredicateObligation, TraitObligation};
25 use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
27 VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
28 VtableObject, VtableParam, VtableTraitAlias,
31 VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
32 VtableGeneratorData, VtableImplData, VtableObjectData, VtableTraitAliasData,
35 use crate::infer::{CombinedSnapshot, InferCtxt, InferOk, PlaceholderMap, TypeFreshener};
36 use crate::traits::error_reporting::InferCtxtExt;
37 use crate::traits::project::ProjectionCacheKeyExt;
39 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
40 use rustc_data_structures::stack::ensure_sufficient_stack;
41 use rustc_errors::ErrorReported;
43 use rustc_hir::def_id::DefId;
44 use rustc_hir::lang_items;
45 use rustc_index::bit_set::GrowableBitSet;
46 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
47 use rustc_middle::mir::interpret::ErrorHandled;
48 use rustc_middle::ty::fast_reject;
49 use rustc_middle::ty::relate::TypeRelation;
50 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst, SubstsRef};
51 use rustc_middle::ty::{
52 self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
54 use rustc_span::symbol::sym;
55 use rustc_target::spec::abi::Abi;
57 use std::cell::{Cell, RefCell};
59 use std::fmt::{self, Display};
63 pub use rustc_middle::traits::select::*;
65 pub struct SelectionContext<'cx, 'tcx> {
66 infcx: &'cx InferCtxt<'cx, 'tcx>,
68 /// Freshener used specifically for entries on the obligation
69 /// stack. This ensures that all entries on the stack at one time
70 /// will have the same set of placeholder entries, which is
71 /// important for checking for trait bounds that recursively
72 /// require themselves.
73 freshener: TypeFreshener<'cx, 'tcx>,
75 /// If `true`, indicates that the evaluation should be conservative
76 /// and consider the possibility of types outside this crate.
77 /// This comes up primarily when resolving ambiguity. Imagine
78 /// there is some trait reference `$0: Bar` where `$0` is an
79 /// inference variable. If `intercrate` is true, then we can never
80 /// say for sure that this reference is not implemented, even if
81 /// there are *no impls at all for `Bar`*, because `$0` could be
82 /// bound to some type that in a downstream crate that implements
83 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
84 /// though, we set this to false, because we are only interested
85 /// in types that the user could actually have written --- in
86 /// other words, we consider `$0: Bar` to be unimplemented if
87 /// there is no type that the user could *actually name* that
88 /// would satisfy it. This avoids crippling inference, basically.
91 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
93 /// Controls whether or not to filter out negative impls when selecting.
94 /// This is used in librustdoc to distinguish between the lack of an impl
95 /// and a negative impl
96 allow_negative_impls: bool,
98 /// The mode that trait queries run in, which informs our error handling
99 /// policy. In essence, canonicalized queries need their errors propagated
100 /// rather than immediately reported because we do not have accurate spans.
101 query_mode: TraitQueryMode,
104 // A stack that walks back up the stack frame.
105 struct TraitObligationStack<'prev, 'tcx> {
106 obligation: &'prev TraitObligation<'tcx>,
108 /// The trait ref from `obligation` but "freshened" with the
109 /// selection-context's freshener. Used to check for recursion.
110 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
112 /// Starts out equal to `depth` -- if, during evaluation, we
113 /// encounter a cycle, then we will set this flag to the minimum
114 /// depth of that cycle for all participants in the cycle. These
115 /// participants will then forego caching their results. This is
116 /// not the most efficient solution, but it addresses #60010. The
117 /// problem we are trying to prevent:
119 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
120 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
121 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
123 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
124 /// is `EvaluatedToOk`; this is because they were only considered
125 /// ok on the premise that if `A: AutoTrait` held, but we indeed
126 /// encountered a problem (later on) with `A: AutoTrait. So we
127 /// currently set a flag on the stack node for `B: AutoTrait` (as
128 /// well as the second instance of `A: AutoTrait`) to suppress
131 /// This is a simple, targeted fix. A more-performant fix requires
132 /// deeper changes, but would permit more caching: we could
133 /// basically defer caching until we have fully evaluated the
134 /// tree, and then cache the entire tree at once. In any case, the
135 /// performance impact here shouldn't be so horrible: every time
136 /// this is hit, we do cache at least one trait, so we only
137 /// evaluate each member of a cycle up to N times, where N is the
138 /// length of the cycle. This means the performance impact is
139 /// bounded and we shouldn't have any terrible worst-cases.
140 reached_depth: Cell<usize>,
142 previous: TraitObligationStackList<'prev, 'tcx>,
144 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
147 /// The depth-first number of this node in the search graph -- a
148 /// pre-order index. Basically, a freshly incremented counter.
152 struct SelectionCandidateSet<'tcx> {
153 // A list of candidates that definitely apply to the current
154 // obligation (meaning: types unify).
155 vec: Vec<SelectionCandidate<'tcx>>,
157 // If `true`, then there were candidates that might or might
158 // not have applied, but we couldn't tell. This occurs when some
159 // of the input types are type variables, in which case there are
160 // various "builtin" rules that might or might not trigger.
164 #[derive(PartialEq, Eq, Debug, Clone)]
165 struct EvaluatedCandidate<'tcx> {
166 candidate: SelectionCandidate<'tcx>,
167 evaluation: EvaluationResult,
170 /// When does the builtin impl for `T: Trait` apply?
171 enum BuiltinImplConditions<'tcx> {
172 /// The impl is conditional on `T1, T2, ...: Trait`.
173 Where(ty::Binder<Vec<Ty<'tcx>>>),
174 /// There is no built-in impl. There may be some other
175 /// candidate (a where-clause or user-defined impl).
177 /// It is unknown whether there is an impl.
181 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
182 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
185 freshener: infcx.freshener(),
187 intercrate_ambiguity_causes: None,
188 allow_negative_impls: false,
189 query_mode: TraitQueryMode::Standard,
193 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
196 freshener: infcx.freshener(),
198 intercrate_ambiguity_causes: None,
199 allow_negative_impls: false,
200 query_mode: TraitQueryMode::Standard,
204 pub fn with_negative(
205 infcx: &'cx InferCtxt<'cx, 'tcx>,
206 allow_negative_impls: bool,
207 ) -> SelectionContext<'cx, 'tcx> {
208 debug!("with_negative({:?})", allow_negative_impls);
211 freshener: infcx.freshener(),
213 intercrate_ambiguity_causes: None,
214 allow_negative_impls,
215 query_mode: TraitQueryMode::Standard,
219 pub fn with_query_mode(
220 infcx: &'cx InferCtxt<'cx, 'tcx>,
221 query_mode: TraitQueryMode,
222 ) -> SelectionContext<'cx, 'tcx> {
223 debug!("with_query_mode({:?})", query_mode);
226 freshener: infcx.freshener(),
228 intercrate_ambiguity_causes: None,
229 allow_negative_impls: false,
234 /// Enables tracking of intercrate ambiguity causes. These are
235 /// used in coherence to give improved diagnostics. We don't do
236 /// this until we detect a coherence error because it can lead to
237 /// false overflow results (#47139) and because it costs
238 /// computation time.
239 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
240 assert!(self.intercrate);
241 assert!(self.intercrate_ambiguity_causes.is_none());
242 self.intercrate_ambiguity_causes = Some(vec![]);
243 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
246 /// Gets the intercrate ambiguity causes collected since tracking
247 /// was enabled and disables tracking at the same time. If
248 /// tracking is not enabled, just returns an empty vector.
249 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
250 assert!(self.intercrate);
251 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
254 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
258 pub fn tcx(&self) -> TyCtxt<'tcx> {
262 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
266 ///////////////////////////////////////////////////////////////////////////
269 // The selection phase tries to identify *how* an obligation will
270 // be resolved. For example, it will identify which impl or
271 // parameter bound is to be used. The process can be inconclusive
272 // if the self type in the obligation is not fully inferred. Selection
273 // can result in an error in one of two ways:
275 // 1. If no applicable impl or parameter bound can be found.
276 // 2. If the output type parameters in the obligation do not match
277 // those specified by the impl/bound. For example, if the obligation
278 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
279 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
281 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
282 /// type environment by performing unification.
285 obligation: &TraitObligation<'tcx>,
286 ) -> SelectionResult<'tcx, Selection<'tcx>> {
287 debug!("select({:?})", obligation);
288 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
290 let pec = &ProvisionalEvaluationCache::default();
291 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
293 let candidate = match self.candidate_from_obligation(&stack) {
294 Err(SelectionError::Overflow) => {
295 // In standard mode, overflow must have been caught and reported
297 assert!(self.query_mode == TraitQueryMode::Canonical);
298 return Err(SelectionError::Overflow);
306 Ok(Some(candidate)) => candidate,
309 match self.confirm_candidate(obligation, candidate) {
310 Err(SelectionError::Overflow) => {
311 assert!(self.query_mode == TraitQueryMode::Canonical);
312 Err(SelectionError::Overflow)
315 Ok(candidate) => Ok(Some(candidate)),
319 ///////////////////////////////////////////////////////////////////////////
322 // Tests whether an obligation can be selected or whether an impl
323 // can be applied to particular types. It skips the "confirmation"
324 // step and hence completely ignores output type parameters.
326 // The result is "true" if the obligation *may* hold and "false" if
327 // we can be sure it does not.
329 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
330 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
331 debug!("predicate_may_hold_fatal({:?})", obligation);
333 // This fatal query is a stopgap that should only be used in standard mode,
334 // where we do not expect overflow to be propagated.
335 assert!(self.query_mode == TraitQueryMode::Standard);
337 self.evaluate_root_obligation(obligation)
338 .expect("Overflow should be caught earlier in standard query mode")
342 /// Evaluates whether the obligation `obligation` can be satisfied
343 /// and returns an `EvaluationResult`. This is meant for the
345 pub fn evaluate_root_obligation(
347 obligation: &PredicateObligation<'tcx>,
348 ) -> Result<EvaluationResult, OverflowError> {
349 self.evaluation_probe(|this| {
350 this.evaluate_predicate_recursively(
351 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
359 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
360 ) -> Result<EvaluationResult, OverflowError> {
361 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
362 let result = op(self)?;
363 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
365 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
370 /// Evaluates the predicates in `predicates` recursively. Note that
371 /// this applies projections in the predicates, and therefore
372 /// is run within an inference probe.
373 fn evaluate_predicates_recursively<'o, I>(
375 stack: TraitObligationStackList<'o, 'tcx>,
377 ) -> Result<EvaluationResult, OverflowError>
379 I: IntoIterator<Item = PredicateObligation<'tcx>>,
381 let mut result = EvaluatedToOk;
382 for obligation in predicates {
383 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
384 debug!("evaluate_predicate_recursively({:?}) = {:?}", obligation, eval);
385 if let EvaluatedToErr = eval {
386 // fast-path - EvaluatedToErr is the top of the lattice,
387 // so we don't need to look on the other predicates.
388 return Ok(EvaluatedToErr);
390 result = cmp::max(result, eval);
396 fn evaluate_predicate_recursively<'o>(
398 previous_stack: TraitObligationStackList<'o, 'tcx>,
399 obligation: PredicateObligation<'tcx>,
400 ) -> Result<EvaluationResult, OverflowError> {
402 "evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
403 previous_stack.head(),
407 // `previous_stack` stores a `TraitObligatiom`, while `obligation` is
408 // a `PredicateObligation`. These are distinct types, so we can't
409 // use any `Option` combinator method that would force them to be
411 match previous_stack.head() {
412 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
413 None => self.check_recursion_limit(&obligation, &obligation)?,
416 match obligation.predicate {
417 ty::PredicateKind::Trait(ref t, _) => {
418 debug_assert!(!t.has_escaping_bound_vars());
419 let obligation = obligation.with(*t);
420 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
423 ty::PredicateKind::Subtype(ref p) => {
424 // Does this code ever run?
425 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
426 Some(Ok(InferOk { mut obligations, .. })) => {
427 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
428 self.evaluate_predicates_recursively(
430 obligations.into_iter(),
433 Some(Err(_)) => Ok(EvaluatedToErr),
434 None => Ok(EvaluatedToAmbig),
438 ty::PredicateKind::WellFormed(ty) => match wf::obligations(
440 obligation.param_env,
441 obligation.cause.body_id,
443 obligation.cause.span,
445 Some(mut obligations) => {
446 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
447 self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
449 None => Ok(EvaluatedToAmbig),
452 ty::PredicateKind::TypeOutlives(..) | ty::PredicateKind::RegionOutlives(..) => {
453 // We do not consider region relationships when evaluating trait matches.
454 Ok(EvaluatedToOkModuloRegions)
457 ty::PredicateKind::ObjectSafe(trait_def_id) => {
458 if self.tcx().is_object_safe(trait_def_id) {
465 ty::PredicateKind::Projection(ref data) => {
466 let project_obligation = obligation.with(*data);
467 match project::poly_project_and_unify_type(self, &project_obligation) {
468 Ok(Some(mut subobligations)) => {
469 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
470 let result = self.evaluate_predicates_recursively(
472 subobligations.into_iter(),
475 ProjectionCacheKey::from_poly_projection_predicate(self, data)
477 self.infcx.inner.borrow_mut().projection_cache().complete(key);
481 Ok(None) => Ok(EvaluatedToAmbig),
482 Err(_) => Ok(EvaluatedToErr),
486 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
487 match self.infcx.closure_kind(closure_substs) {
488 Some(closure_kind) => {
489 if closure_kind.extends(kind) {
495 None => Ok(EvaluatedToAmbig),
499 ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
500 match self.tcx().const_eval_resolve(
501 obligation.param_env,
507 Ok(_) => Ok(EvaluatedToOk),
508 Err(ErrorHandled::TooGeneric) => Ok(EvaluatedToAmbig),
509 Err(_) => Ok(EvaluatedToErr),
513 ty::Predicate::ConstEquate(c1, c2) => {
514 debug!("evaluate_predicate_recursively: equating consts c1={:?} c2={:?}", c1, c2);
516 let evaluate = |c: &'tcx ty::Const<'tcx>| {
517 if let ty::ConstKind::Unevaluated(def_id, substs, promoted) = c.val {
520 obligation.param_env,
524 Some(obligation.cause.span),
526 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
532 match (evaluate(c1), evaluate(c2)) {
533 (Ok(c1), Ok(c2)) => {
534 match self.infcx().at(&obligation.cause, obligation.param_env).eq(c1, c2) {
535 Ok(_) => Ok(EvaluatedToOk),
536 Err(_) => Ok(EvaluatedToErr),
539 (Err(ErrorHandled::Reported(ErrorReported)), _)
540 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
541 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => span_bug!(
542 obligation.cause.span(self.tcx()),
543 "ConstEquate: const_eval_resolve returned an unexpected error"
545 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
553 fn evaluate_trait_predicate_recursively<'o>(
555 previous_stack: TraitObligationStackList<'o, 'tcx>,
556 mut obligation: TraitObligation<'tcx>,
557 ) -> Result<EvaluationResult, OverflowError> {
558 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
561 && obligation.is_global()
562 && obligation.param_env.caller_bounds.iter().all(|bound| bound.needs_subst())
564 // If a param env has no global bounds, global obligations do not
565 // depend on its particular value in order to work, so we can clear
566 // out the param env and get better caching.
567 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
568 obligation.param_env = obligation.param_env.without_caller_bounds();
571 let stack = self.push_stack(previous_stack, &obligation);
572 let fresh_trait_ref = stack.fresh_trait_ref;
573 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
574 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
578 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
579 debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
580 stack.update_reached_depth(stack.cache().current_reached_depth());
584 // Check if this is a match for something already on the
585 // stack. If so, we don't want to insert the result into the
586 // main cache (it is cycle dependent) nor the provisional
587 // cache (which is meant for things that have completed but
588 // for a "backedge" -- this result *is* the backedge).
589 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
590 return Ok(cycle_result);
593 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
594 let result = result?;
596 if !result.must_apply_modulo_regions() {
597 stack.cache().on_failure(stack.dfn);
600 let reached_depth = stack.reached_depth.get();
601 if reached_depth >= stack.depth {
602 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
603 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
605 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
606 self.insert_evaluation_cache(
607 obligation.param_env,
610 provisional_result.max(result),
614 debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
616 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
617 is a cycle participant (at depth {}, reached depth {})",
618 fresh_trait_ref, stack.depth, reached_depth,
621 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
627 /// If there is any previous entry on the stack that precisely
628 /// matches this obligation, then we can assume that the
629 /// obligation is satisfied for now (still all other conditions
630 /// must be met of course). One obvious case this comes up is
631 /// marker traits like `Send`. Think of a linked list:
633 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
635 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
636 /// `Option<Box<List<T>>>` is `Send`, and in turn
637 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
640 /// Note that we do this comparison using the `fresh_trait_ref`
641 /// fields. Because these have all been freshened using
642 /// `self.freshener`, we can be sure that (a) this will not
643 /// affect the inferencer state and (b) that if we see two
644 /// fresh regions with the same index, they refer to the same
645 /// unbound type variable.
646 fn check_evaluation_cycle(
648 stack: &TraitObligationStack<'_, 'tcx>,
649 ) -> Option<EvaluationResult> {
650 if let Some(cycle_depth) = stack
652 .skip(1) // Skip top-most frame.
654 stack.obligation.param_env == prev.obligation.param_env
655 && stack.fresh_trait_ref == prev.fresh_trait_ref
657 .map(|stack| stack.depth)
660 "evaluate_stack({:?}) --> recursive at depth {}",
661 stack.fresh_trait_ref, cycle_depth,
664 // If we have a stack like `A B C D E A`, where the top of
665 // the stack is the final `A`, then this will iterate over
666 // `A, E, D, C, B` -- i.e., all the participants apart
667 // from the cycle head. We mark them as participating in a
668 // cycle. This suppresses caching for those nodes. See
669 // `in_cycle` field for more details.
670 stack.update_reached_depth(cycle_depth);
672 // Subtle: when checking for a coinductive cycle, we do
673 // not compare using the "freshened trait refs" (which
674 // have erased regions) but rather the fully explicit
675 // trait refs. This is important because it's only a cycle
676 // if the regions match exactly.
677 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
678 let cycle = cycle.map(|stack| {
679 ty::PredicateKind::Trait(stack.obligation.predicate, hir::Constness::NotConst)
681 if self.coinductive_match(cycle) {
682 debug!("evaluate_stack({:?}) --> recursive, coinductive", stack.fresh_trait_ref);
685 debug!("evaluate_stack({:?}) --> recursive, inductive", stack.fresh_trait_ref);
686 Some(EvaluatedToRecur)
693 fn evaluate_stack<'o>(
695 stack: &TraitObligationStack<'o, 'tcx>,
696 ) -> Result<EvaluationResult, OverflowError> {
697 // In intercrate mode, whenever any of the generics are unbound,
698 // there can always be an impl. Even if there are no impls in
699 // this crate, perhaps the type would be unified with
700 // something from another crate that does provide an impl.
702 // In intra mode, we must still be conservative. The reason is
703 // that we want to avoid cycles. Imagine an impl like:
705 // impl<T:Eq> Eq for Vec<T>
707 // and a trait reference like `$0 : Eq` where `$0` is an
708 // unbound variable. When we evaluate this trait-reference, we
709 // will unify `$0` with `Vec<$1>` (for some fresh variable
710 // `$1`), on the condition that `$1 : Eq`. We will then wind
711 // up with many candidates (since that are other `Eq` impls
712 // that apply) and try to winnow things down. This results in
713 // a recursive evaluation that `$1 : Eq` -- as you can
714 // imagine, this is just where we started. To avoid that, we
715 // check for unbound variables and return an ambiguous (hence possible)
716 // match if we've seen this trait before.
718 // This suffices to allow chains like `FnMut` implemented in
719 // terms of `Fn` etc, but we could probably make this more
721 let unbound_input_types =
722 stack.fresh_trait_ref.skip_binder().substs.types().any(|ty| ty.is_fresh());
723 // This check was an imperfect workaround for a bug in the old
724 // intercrate mode; it should be removed when that goes away.
725 if unbound_input_types && self.intercrate {
727 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
728 stack.fresh_trait_ref
730 // Heuristics: show the diagnostics when there are no candidates in crate.
731 if self.intercrate_ambiguity_causes.is_some() {
732 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
733 if let Ok(candidate_set) = self.assemble_candidates(stack) {
734 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
735 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
736 let self_ty = trait_ref.self_ty();
737 let cause = IntercrateAmbiguityCause::DownstreamCrate {
738 trait_desc: trait_ref.print_only_trait_path().to_string(),
739 self_desc: if self_ty.has_concrete_skeleton() {
740 Some(self_ty.to_string())
745 debug!("evaluate_stack: pushing cause = {:?}", cause);
746 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
750 return Ok(EvaluatedToAmbig);
752 if unbound_input_types
753 && stack.iter().skip(1).any(|prev| {
754 stack.obligation.param_env == prev.obligation.param_env
755 && self.match_fresh_trait_refs(
756 &stack.fresh_trait_ref,
757 &prev.fresh_trait_ref,
758 prev.obligation.param_env,
763 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
764 stack.fresh_trait_ref
766 return Ok(EvaluatedToUnknown);
769 match self.candidate_from_obligation(stack) {
770 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
771 Ok(None) => Ok(EvaluatedToAmbig),
772 Err(Overflow) => Err(OverflowError),
773 Err(..) => Ok(EvaluatedToErr),
777 /// For defaulted traits, we use a co-inductive strategy to solve, so
778 /// that recursion is ok. This routine returns `true` if the top of the
779 /// stack (`cycle[0]`):
781 /// - is a defaulted trait,
782 /// - it also appears in the backtrace at some position `X`,
783 /// - all the predicates at positions `X..` between `X` and the top are
784 /// also defaulted traits.
785 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
787 I: Iterator<Item = ty::Predicate<'tcx>>,
789 let mut cycle = cycle;
790 cycle.all(|predicate| self.coinductive_predicate(predicate))
793 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
794 let result = match predicate {
795 ty::PredicateKind::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()),
798 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
802 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
803 /// obligations are met. Returns whether `candidate` remains viable after this further
805 fn evaluate_candidate<'o>(
807 stack: &TraitObligationStack<'o, 'tcx>,
808 candidate: &SelectionCandidate<'tcx>,
809 ) -> Result<EvaluationResult, OverflowError> {
811 "evaluate_candidate: depth={} candidate={:?}",
812 stack.obligation.recursion_depth, candidate
814 let result = self.evaluation_probe(|this| {
815 let candidate = (*candidate).clone();
816 match this.confirm_candidate(stack.obligation, candidate) {
817 Ok(selection) => this.evaluate_predicates_recursively(
819 selection.nested_obligations().into_iter(),
821 Err(..) => Ok(EvaluatedToErr),
825 "evaluate_candidate: depth={} result={:?}",
826 stack.obligation.recursion_depth, result
831 fn check_evaluation_cache(
833 param_env: ty::ParamEnv<'tcx>,
834 trait_ref: ty::PolyTraitRef<'tcx>,
835 ) -> Option<EvaluationResult> {
836 let tcx = self.tcx();
837 if self.can_use_global_caches(param_env) {
838 let cache = tcx.evaluation_cache.hashmap.borrow();
839 if let Some(cached) = cache.get(¶m_env.and(trait_ref)) {
840 return Some(cached.get(tcx));
847 .get(¶m_env.and(trait_ref))
851 fn insert_evaluation_cache(
853 param_env: ty::ParamEnv<'tcx>,
854 trait_ref: ty::PolyTraitRef<'tcx>,
855 dep_node: DepNodeIndex,
856 result: EvaluationResult,
858 // Avoid caching results that depend on more than just the trait-ref
859 // - the stack can create recursion.
860 if result.is_stack_dependent() {
864 if self.can_use_global_caches(param_env) {
865 if !trait_ref.needs_infer() {
867 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
870 // This may overwrite the cache with the same value
871 // FIXME: Due to #50507 this overwrites the different values
872 // This should be changed to use HashMapExt::insert_same
873 // when that is fixed
878 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
883 debug!("insert_evaluation_cache(trait_ref={:?}, candidate={:?})", trait_ref, result,);
888 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
891 /// For various reasons, it's possible for a subobligation
892 /// to have a *lower* recursion_depth than the obligation used to create it.
893 /// Projection sub-obligations may be returned from the projection cache,
894 /// which results in obligations with an 'old' `recursion_depth`.
895 /// Additionally, methods like `wf::obligations` and
896 /// `InferCtxt.subtype_predicate` produce subobligations without
897 /// taking in a 'parent' depth, causing the generated subobligations
898 /// to have a `recursion_depth` of `0`.
900 /// To ensure that obligation_depth never decreasees, we force all subobligations
901 /// to have at least the depth of the original obligation.
902 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
907 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
910 /// Checks that the recursion limit has not been exceeded.
912 /// The weird return type of this function allows it to be used with the `try` (`?`)
913 /// operator within certain functions.
914 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
916 obligation: &Obligation<'tcx, T>,
917 error_obligation: &Obligation<'tcx, V>,
918 ) -> Result<(), OverflowError> {
919 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
920 if obligation.recursion_depth >= recursion_limit {
921 match self.query_mode {
922 TraitQueryMode::Standard => {
923 self.infcx().report_overflow_error(error_obligation, true);
925 TraitQueryMode::Canonical => {
926 return Err(OverflowError);
933 ///////////////////////////////////////////////////////////////////////////
934 // CANDIDATE ASSEMBLY
936 // The selection process begins by examining all in-scope impls,
937 // caller obligations, and so forth and assembling a list of
938 // candidates. See the [rustc dev guide] for more details.
940 // [rustc dev guide]:
941 // https://rustc-dev-guide.rust-lang.org/traits/resolution.html#candidate-assembly
943 fn candidate_from_obligation<'o>(
945 stack: &TraitObligationStack<'o, 'tcx>,
946 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
947 // Watch out for overflow. This intentionally bypasses (and does
948 // not update) the cache.
949 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
951 // Check the cache. Note that we freshen the trait-ref
952 // separately rather than using `stack.fresh_trait_ref` --
953 // this is because we want the unbound variables to be
954 // replaced with fresh types starting from index 0.
955 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
957 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
958 cache_fresh_trait_pred, stack
960 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
963 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
965 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
969 // If no match, compute result and insert into cache.
971 // FIXME(nikomatsakis) -- this cache is not taking into
972 // account cycles that may have occurred in forming the
973 // candidate. I don't know of any specific problems that
974 // result but it seems awfully suspicious.
975 let (candidate, dep_node) =
976 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
978 debug!("CACHE MISS: SELECT({:?})={:?}", cache_fresh_trait_pred, candidate);
979 self.insert_candidate_cache(
980 stack.obligation.param_env,
981 cache_fresh_trait_pred,
988 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
990 OP: FnOnce(&mut Self) -> R,
992 let (result, dep_node) =
993 self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || op(self));
994 self.tcx().dep_graph.read_index(dep_node);
998 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
999 fn filter_negative_and_reservation_impls(
1001 candidate: SelectionCandidate<'tcx>,
1002 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1003 if let ImplCandidate(def_id) = candidate {
1004 let tcx = self.tcx();
1005 match tcx.impl_polarity(def_id) {
1006 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1007 return Err(Unimplemented);
1009 ty::ImplPolarity::Reservation => {
1010 if let Some(intercrate_ambiguity_clauses) =
1011 &mut self.intercrate_ambiguity_causes
1013 let attrs = tcx.get_attrs(def_id);
1014 let attr = attr::find_by_name(&attrs, sym::rustc_reservation_impl);
1015 let value = attr.and_then(|a| a.value_str());
1016 if let Some(value) = value {
1018 "filter_negative_and_reservation_impls: \
1019 reservation impl ambiguity on {:?}",
1022 intercrate_ambiguity_clauses.push(
1023 IntercrateAmbiguityCause::ReservationImpl {
1024 message: value.to_string(),
1037 fn candidate_from_obligation_no_cache<'o>(
1039 stack: &TraitObligationStack<'o, 'tcx>,
1040 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1041 if stack.obligation.predicate.references_error() {
1042 // If we encounter a `Error`, we generally prefer the
1043 // most "optimistic" result in response -- that is, the
1044 // one least likely to report downstream errors. But
1045 // because this routine is shared by coherence and by
1046 // trait selection, there isn't an obvious "right" choice
1047 // here in that respect, so we opt to just return
1048 // ambiguity and let the upstream clients sort it out.
1052 if let Some(conflict) = self.is_knowable(stack) {
1053 debug!("coherence stage: not knowable");
1054 if self.intercrate_ambiguity_causes.is_some() {
1055 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1056 // Heuristics: show the diagnostics when there are no candidates in crate.
1057 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1058 let mut no_candidates_apply = true;
1060 let evaluated_candidates =
1061 candidate_set.vec.iter().map(|c| self.evaluate_candidate(stack, &c));
1063 for ec in evaluated_candidates {
1067 no_candidates_apply = false;
1071 Err(e) => return Err(e.into()),
1076 if !candidate_set.ambiguous && no_candidates_apply {
1077 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1078 let self_ty = trait_ref.self_ty();
1079 let trait_desc = trait_ref.print_only_trait_path().to_string();
1080 let self_desc = if self_ty.has_concrete_skeleton() {
1081 Some(self_ty.to_string())
1085 let cause = if let Conflict::Upstream = conflict {
1086 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1088 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1090 debug!("evaluate_stack: pushing cause = {:?}", cause);
1091 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1098 let candidate_set = self.assemble_candidates(stack)?;
1100 if candidate_set.ambiguous {
1101 debug!("candidate set contains ambig");
1105 let mut candidates = candidate_set.vec;
1107 debug!("assembled {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1109 // At this point, we know that each of the entries in the
1110 // candidate set is *individually* applicable. Now we have to
1111 // figure out if they contain mutual incompatibilities. This
1112 // frequently arises if we have an unconstrained input type --
1113 // for example, we are looking for `$0: Eq` where `$0` is some
1114 // unconstrained type variable. In that case, we'll get a
1115 // candidate which assumes $0 == int, one that assumes `$0 ==
1116 // usize`, etc. This spells an ambiguity.
1118 // If there is more than one candidate, first winnow them down
1119 // by considering extra conditions (nested obligations and so
1120 // forth). We don't winnow if there is exactly one
1121 // candidate. This is a relatively minor distinction but it
1122 // can lead to better inference and error-reporting. An
1123 // example would be if there was an impl:
1125 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1127 // and we were to see some code `foo.push_clone()` where `boo`
1128 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1129 // we were to winnow, we'd wind up with zero candidates.
1130 // Instead, we select the right impl now but report "`Bar` does
1131 // not implement `Clone`".
1132 if candidates.len() == 1 {
1133 return self.filter_negative_and_reservation_impls(candidates.pop().unwrap());
1136 // Winnow, but record the exact outcome of evaluation, which
1137 // is needed for specialization. Propagate overflow if it occurs.
1138 let mut candidates = candidates
1140 .map(|c| match self.evaluate_candidate(stack, &c) {
1141 Ok(eval) if eval.may_apply() => {
1142 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
1145 Err(OverflowError) => Err(Overflow),
1147 .flat_map(Result::transpose)
1148 .collect::<Result<Vec<_>, _>>()?;
1150 debug!("winnowed to {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1152 let needs_infer = stack.obligation.predicate.needs_infer();
1154 // If there are STILL multiple candidates, we can further
1155 // reduce the list by dropping duplicates -- including
1156 // resolving specializations.
1157 if candidates.len() > 1 {
1159 while i < candidates.len() {
1160 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1161 self.candidate_should_be_dropped_in_favor_of(
1168 debug!("Dropping candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1169 candidates.swap_remove(i);
1171 debug!("Retaining candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1174 // If there are *STILL* multiple candidates, give up
1175 // and report ambiguity.
1177 debug!("multiple matches, ambig");
1184 // If there are *NO* candidates, then there are no impls --
1185 // that we know of, anyway. Note that in the case where there
1186 // are unbound type variables within the obligation, it might
1187 // be the case that you could still satisfy the obligation
1188 // from another crate by instantiating the type variables with
1189 // a type from another crate that does have an impl. This case
1190 // is checked for in `evaluate_stack` (and hence users
1191 // who might care about this case, like coherence, should use
1193 if candidates.is_empty() {
1194 return Err(Unimplemented);
1197 // Just one candidate left.
1198 self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate)
1201 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1202 debug!("is_knowable(intercrate={:?})", self.intercrate);
1204 if !self.intercrate {
1208 let obligation = &stack.obligation;
1209 let predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1211 // Okay to skip binder because of the nature of the
1212 // trait-ref-is-knowable check, which does not care about
1214 let trait_ref = predicate.skip_binder().trait_ref;
1216 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1219 /// Returns `true` if the global caches can be used.
1220 /// Do note that if the type itself is not in the
1221 /// global tcx, the local caches will be used.
1222 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1223 // If there are any inference variables in the `ParamEnv`, then we
1224 // always use a cache local to this particular scope. Otherwise, we
1225 // switch to a global cache.
1226 if param_env.needs_infer() {
1230 // Avoid using the master cache during coherence and just rely
1231 // on the local cache. This effectively disables caching
1232 // during coherence. It is really just a simplification to
1233 // avoid us having to fear that coherence results "pollute"
1234 // the master cache. Since coherence executes pretty quickly,
1235 // it's not worth going to more trouble to increase the
1236 // hit-rate, I don't think.
1237 if self.intercrate {
1241 // Otherwise, we can use the global cache.
1245 fn check_candidate_cache(
1247 param_env: ty::ParamEnv<'tcx>,
1248 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1249 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1250 let tcx = self.tcx();
1251 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1252 if self.can_use_global_caches(param_env) {
1253 let cache = tcx.selection_cache.hashmap.borrow();
1254 if let Some(cached) = cache.get(¶m_env.and(*trait_ref)) {
1255 return Some(cached.get(tcx));
1262 .get(¶m_env.and(*trait_ref))
1263 .map(|v| v.get(tcx))
1266 /// Determines whether can we safely cache the result
1267 /// of selecting an obligation. This is almost always `true`,
1268 /// except when dealing with certain `ParamCandidate`s.
1270 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1271 /// since it was usually produced directly from a `DefId`. However,
1272 /// certain cases (currently only librustdoc's blanket impl finder),
1273 /// a `ParamEnv` may be explicitly constructed with inference types.
1274 /// When this is the case, we do *not* want to cache the resulting selection
1275 /// candidate. This is due to the fact that it might not always be possible
1276 /// to equate the obligation's trait ref and the candidate's trait ref,
1277 /// if more constraints end up getting added to an inference variable.
1279 /// Because of this, we always want to re-run the full selection
1280 /// process for our obligation the next time we see it, since
1281 /// we might end up picking a different `SelectionCandidate` (or none at all).
1282 fn can_cache_candidate(
1284 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1287 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1292 fn insert_candidate_cache(
1294 param_env: ty::ParamEnv<'tcx>,
1295 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1296 dep_node: DepNodeIndex,
1297 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1299 let tcx = self.tcx();
1300 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1302 if !self.can_cache_candidate(&candidate) {
1304 "insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1305 candidate is not cacheable",
1306 trait_ref, candidate
1311 if self.can_use_global_caches(param_env) {
1312 if let Err(Overflow) = candidate {
1313 // Don't cache overflow globally; we only produce this in certain modes.
1314 } else if !trait_ref.needs_infer() {
1315 if !candidate.needs_infer() {
1317 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1318 trait_ref, candidate,
1320 // This may overwrite the cache with the same value.
1324 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1331 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1332 trait_ref, candidate,
1338 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1341 fn assemble_candidates<'o>(
1343 stack: &TraitObligationStack<'o, 'tcx>,
1344 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1345 let TraitObligationStack { obligation, .. } = *stack;
1346 let obligation = &Obligation {
1347 param_env: obligation.param_env,
1348 cause: obligation.cause.clone(),
1349 recursion_depth: obligation.recursion_depth,
1350 predicate: self.infcx().resolve_vars_if_possible(&obligation.predicate),
1353 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1354 // Self is a type variable (e.g., `_: AsRef<str>`).
1356 // This is somewhat problematic, as the current scheme can't really
1357 // handle it turning to be a projection. This does end up as truly
1358 // ambiguous in most cases anyway.
1360 // Take the fast path out - this also improves
1361 // performance by preventing assemble_candidates_from_impls from
1362 // matching every impl for this trait.
1363 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1366 let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
1368 self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1370 // Other bounds. Consider both in-scope bounds from fn decl
1371 // and applicable impls. There is a certain set of precedence rules here.
1372 let def_id = obligation.predicate.def_id();
1373 let lang_items = self.tcx().lang_items();
1375 if lang_items.copy_trait() == Some(def_id) {
1376 debug!("obligation self ty is {:?}", obligation.predicate.skip_binder().self_ty());
1378 // User-defined copy impls are permitted, but only for
1379 // structs and enums.
1380 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1382 // For other types, we'll use the builtin rules.
1383 let copy_conditions = self.copy_clone_conditions(obligation);
1384 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1385 } else if lang_items.sized_trait() == Some(def_id) {
1386 // Sized is never implementable by end-users, it is
1387 // always automatically computed.
1388 let sized_conditions = self.sized_conditions(obligation);
1389 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1390 } else if lang_items.unsize_trait() == Some(def_id) {
1391 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1393 if lang_items.clone_trait() == Some(def_id) {
1394 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1395 // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone`
1396 // types have builtin support for `Clone`.
1397 let clone_conditions = self.copy_clone_conditions(obligation);
1398 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1401 self.assemble_generator_candidates(obligation, &mut candidates)?;
1402 self.assemble_closure_candidates(obligation, &mut candidates)?;
1403 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1404 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1405 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1408 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1409 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1410 // Auto implementations have lower priority, so we only
1411 // consider triggering a default if there is no other impl that can apply.
1412 if candidates.vec.is_empty() {
1413 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1415 debug!("candidate list size: {}", candidates.vec.len());
1419 fn assemble_candidates_from_projected_tys(
1421 obligation: &TraitObligation<'tcx>,
1422 candidates: &mut SelectionCandidateSet<'tcx>,
1424 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1426 // Before we go into the whole placeholder thing, just
1427 // quickly check if the self-type is a projection at all.
1428 match obligation.predicate.skip_binder().trait_ref.self_ty().kind {
1429 ty::Projection(_) | ty::Opaque(..) => {}
1430 ty::Infer(ty::TyVar(_)) => {
1432 obligation.cause.span,
1433 "Self=_ should have been handled by assemble_candidates"
1439 let result = self.infcx.probe(|snapshot| {
1440 self.match_projection_obligation_against_definition_bounds(obligation, snapshot)
1444 candidates.vec.push(ProjectionCandidate);
1448 fn match_projection_obligation_against_definition_bounds(
1450 obligation: &TraitObligation<'tcx>,
1451 snapshot: &CombinedSnapshot<'_, 'tcx>,
1453 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1454 let (placeholder_trait_predicate, placeholder_map) =
1455 self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
1457 "match_projection_obligation_against_definition_bounds: \
1458 placeholder_trait_predicate={:?}",
1459 placeholder_trait_predicate,
1462 let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().kind {
1463 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1464 ty::Opaque(def_id, substs) => (def_id, substs),
1467 obligation.cause.span,
1468 "match_projection_obligation_against_definition_bounds() called \
1469 but self-ty is not a projection: {:?}",
1470 placeholder_trait_predicate.trait_ref.self_ty()
1475 "match_projection_obligation_against_definition_bounds: \
1476 def_id={:?}, substs={:?}",
1480 let predicates_of = self.tcx().predicates_of(def_id);
1481 let bounds = predicates_of.instantiate(self.tcx(), substs);
1483 "match_projection_obligation_against_definition_bounds: \
1488 let elaborated_predicates =
1489 util::elaborate_predicates(self.tcx(), bounds.predicates.into_iter());
1490 let matching_bound = elaborated_predicates.filter_to_traits().find(|bound| {
1491 self.infcx.probe(|_| {
1492 self.match_projection(
1495 placeholder_trait_predicate.trait_ref,
1503 "match_projection_obligation_against_definition_bounds: \
1504 matching_bound={:?}",
1507 match matching_bound {
1510 // Repeat the successful match, if any, this time outside of a probe.
1511 let result = self.match_projection(
1514 placeholder_trait_predicate.trait_ref,
1525 fn match_projection(
1527 obligation: &TraitObligation<'tcx>,
1528 trait_bound: ty::PolyTraitRef<'tcx>,
1529 placeholder_trait_ref: ty::TraitRef<'tcx>,
1530 placeholder_map: &PlaceholderMap<'tcx>,
1531 snapshot: &CombinedSnapshot<'_, 'tcx>,
1533 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1535 .at(&obligation.cause, obligation.param_env)
1536 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1538 && self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1541 /// Given an obligation like `<SomeTrait for T>`, searches the obligations that the caller
1542 /// supplied to find out whether it is listed among them.
1544 /// Never affects the inference environment.
1545 fn assemble_candidates_from_caller_bounds<'o>(
1547 stack: &TraitObligationStack<'o, 'tcx>,
1548 candidates: &mut SelectionCandidateSet<'tcx>,
1549 ) -> Result<(), SelectionError<'tcx>> {
1550 debug!("assemble_candidates_from_caller_bounds({:?})", stack.obligation);
1552 let all_bounds = stack
1557 .filter_map(|o| o.to_opt_poly_trait_ref());
1559 // Micro-optimization: filter out predicates relating to different traits.
1560 let matching_bounds =
1561 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1563 // Keep only those bounds which may apply, and propagate overflow if it occurs.
1564 let mut param_candidates = vec![];
1565 for bound in matching_bounds {
1566 let wc = self.evaluate_where_clause(stack, bound)?;
1568 param_candidates.push(ParamCandidate(bound));
1572 candidates.vec.extend(param_candidates);
1577 fn evaluate_where_clause<'o>(
1579 stack: &TraitObligationStack<'o, 'tcx>,
1580 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1581 ) -> Result<EvaluationResult, OverflowError> {
1582 self.evaluation_probe(|this| {
1583 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1584 Ok(obligations) => {
1585 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1587 Err(()) => Ok(EvaluatedToErr),
1592 fn assemble_generator_candidates(
1594 obligation: &TraitObligation<'tcx>,
1595 candidates: &mut SelectionCandidateSet<'tcx>,
1596 ) -> Result<(), SelectionError<'tcx>> {
1597 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1601 // Okay to skip binder because the substs on generator types never
1602 // touch bound regions, they just capture the in-scope
1603 // type/region parameters.
1604 let self_ty = *obligation.self_ty().skip_binder();
1605 match self_ty.kind {
1606 ty::Generator(..) => {
1608 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1612 candidates.vec.push(GeneratorCandidate);
1614 ty::Infer(ty::TyVar(_)) => {
1615 debug!("assemble_generator_candidates: ambiguous self-type");
1616 candidates.ambiguous = true;
1624 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1625 /// FnMut<..>` where `X` is a closure type.
1627 /// Note: the type parameters on a closure candidate are modeled as *output* type
1628 /// parameters and hence do not affect whether this trait is a match or not. They will be
1629 /// unified during the confirmation step.
1630 fn assemble_closure_candidates(
1632 obligation: &TraitObligation<'tcx>,
1633 candidates: &mut SelectionCandidateSet<'tcx>,
1634 ) -> Result<(), SelectionError<'tcx>> {
1635 let kind = match self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) {
1642 // Okay to skip binder because the substs on closure types never
1643 // touch bound regions, they just capture the in-scope
1644 // type/region parameters
1645 match obligation.self_ty().skip_binder().kind {
1646 ty::Closure(_, closure_substs) => {
1647 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}", kind, obligation);
1648 match self.infcx.closure_kind(closure_substs) {
1649 Some(closure_kind) => {
1650 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1651 if closure_kind.extends(kind) {
1652 candidates.vec.push(ClosureCandidate);
1656 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1657 candidates.vec.push(ClosureCandidate);
1661 ty::Infer(ty::TyVar(_)) => {
1662 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1663 candidates.ambiguous = true;
1671 /// Implements one of the `Fn()` family for a fn pointer.
1672 fn assemble_fn_pointer_candidates(
1674 obligation: &TraitObligation<'tcx>,
1675 candidates: &mut SelectionCandidateSet<'tcx>,
1676 ) -> Result<(), SelectionError<'tcx>> {
1677 // We provide impl of all fn traits for fn pointers.
1678 if self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()).is_none() {
1682 // Okay to skip binder because what we are inspecting doesn't involve bound regions.
1683 let self_ty = *obligation.self_ty().skip_binder();
1684 match self_ty.kind {
1685 ty::Infer(ty::TyVar(_)) => {
1686 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1687 candidates.ambiguous = true; // Could wind up being a fn() type.
1689 // Provide an impl, but only for suitable `fn` pointers.
1690 ty::FnDef(..) | ty::FnPtr(_) => {
1692 unsafety: hir::Unsafety::Normal,
1696 } = self_ty.fn_sig(self.tcx()).skip_binder()
1698 candidates.vec.push(FnPointerCandidate);
1707 /// Searches for impls that might apply to `obligation`.
1708 fn assemble_candidates_from_impls(
1710 obligation: &TraitObligation<'tcx>,
1711 candidates: &mut SelectionCandidateSet<'tcx>,
1712 ) -> Result<(), SelectionError<'tcx>> {
1713 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1715 self.tcx().for_each_relevant_impl(
1716 obligation.predicate.def_id(),
1717 obligation.predicate.skip_binder().trait_ref.self_ty(),
1719 self.infcx.probe(|snapshot| {
1720 if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot) {
1721 candidates.vec.push(ImplCandidate(impl_def_id));
1730 fn assemble_candidates_from_auto_impls(
1732 obligation: &TraitObligation<'tcx>,
1733 candidates: &mut SelectionCandidateSet<'tcx>,
1734 ) -> Result<(), SelectionError<'tcx>> {
1735 // Okay to skip binder here because the tests we do below do not involve bound regions.
1736 let self_ty = *obligation.self_ty().skip_binder();
1737 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
1739 let def_id = obligation.predicate.def_id();
1741 if self.tcx().trait_is_auto(def_id) {
1742 match self_ty.kind {
1743 ty::Dynamic(..) => {
1744 // For object types, we don't know what the closed
1745 // over types are. This means we conservatively
1746 // say nothing; a candidate may be added by
1747 // `assemble_candidates_from_object_ty`.
1749 ty::Foreign(..) => {
1750 // Since the contents of foreign types is unknown,
1751 // we don't add any `..` impl. Default traits could
1752 // still be provided by a manual implementation for
1753 // this trait and type.
1755 ty::Param(..) | ty::Projection(..) => {
1756 // In these cases, we don't know what the actual
1757 // type is. Therefore, we cannot break it down
1758 // into its constituent types. So we don't
1759 // consider the `..` impl but instead just add no
1760 // candidates: this means that typeck will only
1761 // succeed if there is another reason to believe
1762 // that this obligation holds. That could be a
1763 // where-clause or, in the case of an object type,
1764 // it could be that the object type lists the
1765 // trait (e.g., `Foo+Send : Send`). See
1766 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1767 // for an example of a test case that exercises
1770 ty::Infer(ty::TyVar(_)) => {
1771 // The auto impl might apply; we don't know.
1772 candidates.ambiguous = true;
1774 ty::Generator(_, _, movability)
1775 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
1778 hir::Movability::Static => {
1779 // Immovable generators are never `Unpin`, so
1780 // suppress the normal auto-impl candidate for it.
1782 hir::Movability::Movable => {
1783 // Movable generators are always `Unpin`, so add an
1784 // unconditional builtin candidate.
1785 candidates.vec.push(BuiltinCandidate { has_nested: false });
1790 _ => candidates.vec.push(AutoImplCandidate(def_id)),
1797 /// Searches for impls that might apply to `obligation`.
1798 fn assemble_candidates_from_object_ty(
1800 obligation: &TraitObligation<'tcx>,
1801 candidates: &mut SelectionCandidateSet<'tcx>,
1804 "assemble_candidates_from_object_ty(self_ty={:?})",
1805 obligation.self_ty().skip_binder()
1808 self.infcx.probe(|_snapshot| {
1809 // The code below doesn't care about regions, and the
1810 // self-ty here doesn't escape this probe, so just erase
1812 let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
1813 let poly_trait_ref = match self_ty.kind {
1814 ty::Dynamic(ref data, ..) => {
1815 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1817 "assemble_candidates_from_object_ty: matched builtin bound, \
1820 candidates.vec.push(BuiltinObjectCandidate);
1824 if let Some(principal) = data.principal() {
1825 if !self.infcx.tcx.features().object_safe_for_dispatch {
1826 principal.with_self_ty(self.tcx(), self_ty)
1827 } else if self.tcx().is_object_safe(principal.def_id()) {
1828 principal.with_self_ty(self.tcx(), self_ty)
1833 // Only auto trait bounds exist.
1837 ty::Infer(ty::TyVar(_)) => {
1838 debug!("assemble_candidates_from_object_ty: ambiguous");
1839 candidates.ambiguous = true; // could wind up being an object type
1845 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}", poly_trait_ref);
1847 // Count only those upcast versions that match the trait-ref
1848 // we are looking for. Specifically, do not only check for the
1849 // correct trait, but also the correct type parameters.
1850 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1851 // but `Foo` is declared as `trait Foo: Bar<u32>`.
1852 let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
1853 .filter(|upcast_trait_ref| {
1855 .probe(|_| self.match_poly_trait_ref(obligation, *upcast_trait_ref).is_ok())
1859 if upcast_trait_refs > 1 {
1860 // Can be upcast in many ways; need more type information.
1861 candidates.ambiguous = true;
1862 } else if upcast_trait_refs == 1 {
1863 candidates.vec.push(ObjectCandidate);
1868 /// Searches for unsizing that might apply to `obligation`.
1869 fn assemble_candidates_for_unsizing(
1871 obligation: &TraitObligation<'tcx>,
1872 candidates: &mut SelectionCandidateSet<'tcx>,
1874 // We currently never consider higher-ranked obligations e.g.
1875 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1876 // because they are a priori invalid, and we could potentially add support
1877 // for them later, it's just that there isn't really a strong need for it.
1878 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1879 // impl, and those are generally applied to concrete types.
1881 // That said, one might try to write a fn with a where clause like
1882 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1883 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1884 // Still, you'd be more likely to write that where clause as
1886 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1887 // obligation above. Should be possible to extend this in the future.
1888 let source = match obligation.self_ty().no_bound_vars() {
1891 // Don't add any candidates if there are bound regions.
1895 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1897 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})", source, target);
1899 let may_apply = match (&source.kind, &target.kind) {
1900 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1901 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
1902 // Upcasts permit two things:
1904 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
1905 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
1907 // Note that neither of these changes requires any
1908 // change at runtime. Eventually this will be
1911 // We always upcast when we can because of reason
1912 // #2 (region bounds).
1913 data_a.principal_def_id() == data_b.principal_def_id()
1916 // All of a's auto traits need to be in b's auto traits.
1917 .all(|b| data_a.auto_traits().any(|a| a == b))
1921 (_, &ty::Dynamic(..)) => true,
1923 // Ambiguous handling is below `T` -> `Trait`, because inference
1924 // variables can still implement `Unsize<Trait>` and nested
1925 // obligations will have the final say (likely deferred).
1926 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
1927 debug!("assemble_candidates_for_unsizing: ambiguous");
1928 candidates.ambiguous = true;
1932 // `[T; n]` -> `[T]`
1933 (&ty::Array(..), &ty::Slice(_)) => true,
1935 // `Struct<T>` -> `Struct<U>`
1936 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
1937 def_id_a == def_id_b
1940 // `(.., T)` -> `(.., U)`
1941 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
1947 candidates.vec.push(BuiltinUnsizeCandidate);
1951 fn assemble_candidates_for_trait_alias(
1953 obligation: &TraitObligation<'tcx>,
1954 candidates: &mut SelectionCandidateSet<'tcx>,
1955 ) -> Result<(), SelectionError<'tcx>> {
1956 // Okay to skip binder here because the tests we do below do not involve bound regions.
1957 let self_ty = *obligation.self_ty().skip_binder();
1958 debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
1960 let def_id = obligation.predicate.def_id();
1962 if self.tcx().is_trait_alias(def_id) {
1963 candidates.vec.push(TraitAliasCandidate(def_id));
1969 ///////////////////////////////////////////////////////////////////////////
1972 // Winnowing is the process of attempting to resolve ambiguity by
1973 // probing further. During the winnowing process, we unify all
1974 // type variables and then we also attempt to evaluate recursive
1975 // bounds to see if they are satisfied.
1977 /// Returns `true` if `victim` should be dropped in favor of
1978 /// `other`. Generally speaking we will drop duplicate
1979 /// candidates and prefer where-clause candidates.
1981 /// See the comment for "SelectionCandidate" for more details.
1982 fn candidate_should_be_dropped_in_favor_of(
1984 victim: &EvaluatedCandidate<'tcx>,
1985 other: &EvaluatedCandidate<'tcx>,
1988 if victim.candidate == other.candidate {
1992 // Check if a bound would previously have been removed when normalizing
1993 // the param_env so that it can be given the lowest priority. See
1994 // #50825 for the motivation for this.
1996 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
1998 match other.candidate {
1999 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2000 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2001 // lifetime of a variable.
2002 BuiltinCandidate { has_nested: false } => true,
2003 ParamCandidate(ref cand) => match victim.candidate {
2004 AutoImplCandidate(..) => {
2006 "default implementations shouldn't be recorded \
2007 when there are other valid candidates"
2010 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2011 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2012 // lifetime of a variable.
2013 BuiltinCandidate { has_nested: false } => false,
2016 | GeneratorCandidate
2017 | FnPointerCandidate
2018 | BuiltinObjectCandidate
2019 | BuiltinUnsizeCandidate
2020 | BuiltinCandidate { .. }
2021 | TraitAliasCandidate(..) => {
2022 // Global bounds from the where clause should be ignored
2023 // here (see issue #50825). Otherwise, we have a where
2024 // clause so don't go around looking for impls.
2027 ObjectCandidate | ProjectionCandidate => {
2028 // Arbitrarily give param candidates priority
2029 // over projection and object candidates.
2032 ParamCandidate(..) => false,
2034 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2035 AutoImplCandidate(..) => {
2037 "default implementations shouldn't be recorded \
2038 when there are other valid candidates"
2041 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2042 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2043 // lifetime of a variable.
2044 BuiltinCandidate { has_nested: false } => false,
2047 | GeneratorCandidate
2048 | FnPointerCandidate
2049 | BuiltinObjectCandidate
2050 | BuiltinUnsizeCandidate
2051 | BuiltinCandidate { .. }
2052 | TraitAliasCandidate(..) => true,
2053 ObjectCandidate | ProjectionCandidate => {
2054 // Arbitrarily give param candidates priority
2055 // over projection and object candidates.
2058 ParamCandidate(ref cand) => is_global(cand),
2060 ImplCandidate(other_def) => {
2061 // See if we can toss out `victim` based on specialization.
2062 // This requires us to know *for sure* that the `other` impl applies
2063 // i.e., `EvaluatedToOk`.
2064 if other.evaluation.must_apply_modulo_regions() {
2065 match victim.candidate {
2066 ImplCandidate(victim_def) => {
2067 let tcx = self.tcx();
2068 if tcx.specializes((other_def, victim_def)) {
2071 return match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
2072 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
2073 // Subtle: If the predicate we are evaluating has inference
2074 // variables, do *not* allow discarding candidates due to
2075 // marker trait impls.
2077 // Without this restriction, we could end up accidentally
2078 // constrainting inference variables based on an arbitrarily
2079 // chosen trait impl.
2081 // Imagine we have the following code:
2084 // #[marker] trait MyTrait {}
2085 // impl MyTrait for u8 {}
2086 // impl MyTrait for bool {}
2089 // And we are evaluating the predicate `<_#0t as MyTrait>`.
2091 // During selection, we will end up with one candidate for each
2092 // impl of `MyTrait`. If we were to discard one impl in favor
2093 // of the other, we would be left with one candidate, causing
2094 // us to "successfully" select the predicate, unifying
2095 // _#0t with (for example) `u8`.
2097 // However, we have no reason to believe that this unification
2098 // is correct - we've essentially just picked an arbitrary
2099 // *possibility* for _#0t, and required that this be the *only*
2102 // Eventually, we will either:
2103 // 1) Unify all inference variables in the predicate through
2104 // some other means (e.g. type-checking of a function). We will
2105 // then be in a position to drop marker trait candidates
2106 // without constraining inference variables (since there are
2107 // none left to constrin)
2108 // 2) Be left with some unconstrained inference variables. We
2109 // will then correctly report an inference error, since the
2110 // existence of multiple marker trait impls tells us nothing
2111 // about which one should actually apply.
2118 ParamCandidate(ref cand) => {
2119 // Prefer the impl to a global where clause candidate.
2120 return is_global(cand);
2129 | GeneratorCandidate
2130 | FnPointerCandidate
2131 | BuiltinObjectCandidate
2132 | BuiltinUnsizeCandidate
2133 | BuiltinCandidate { has_nested: true } => {
2134 match victim.candidate {
2135 ParamCandidate(ref cand) => {
2136 // Prefer these to a global where-clause bound
2137 // (see issue #50825).
2138 is_global(cand) && other.evaluation.must_apply_modulo_regions()
2147 ///////////////////////////////////////////////////////////////////////////
2150 // These cover the traits that are built-in to the language
2151 // itself: `Copy`, `Clone` and `Sized`.
2153 fn assemble_builtin_bound_candidates(
2155 conditions: BuiltinImplConditions<'tcx>,
2156 candidates: &mut SelectionCandidateSet<'tcx>,
2157 ) -> Result<(), SelectionError<'tcx>> {
2159 BuiltinImplConditions::Where(nested) => {
2160 debug!("builtin_bound: nested={:?}", nested);
2163 .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
2165 BuiltinImplConditions::None => {}
2166 BuiltinImplConditions::Ambiguous => {
2167 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2168 candidates.ambiguous = true;
2175 fn sized_conditions(
2177 obligation: &TraitObligation<'tcx>,
2178 ) -> BuiltinImplConditions<'tcx> {
2179 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2181 // NOTE: binder moved to (*)
2182 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2184 match self_ty.kind {
2185 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2196 | ty::GeneratorWitness(..)
2201 // safe for everything
2202 Where(ty::Binder::dummy(Vec::new()))
2205 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2208 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2211 ty::Adt(def, substs) => {
2212 let sized_crit = def.sized_constraint(self.tcx());
2213 // (*) binder moved here
2214 Where(ty::Binder::bind(
2215 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect(),
2219 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2220 ty::Infer(ty::TyVar(_)) => Ambiguous,
2224 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2225 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2230 fn copy_clone_conditions(
2232 obligation: &TraitObligation<'tcx>,
2233 ) -> BuiltinImplConditions<'tcx> {
2234 // NOTE: binder moved to (*)
2235 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2237 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2239 match self_ty.kind {
2240 ty::Infer(ty::IntVar(_))
2241 | ty::Infer(ty::FloatVar(_))
2244 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2253 | ty::Ref(_, _, hir::Mutability::Not) => {
2254 // Implementations provided in libcore
2262 | ty::GeneratorWitness(..)
2264 | ty::Ref(_, _, hir::Mutability::Mut) => None,
2266 ty::Array(element_ty, _) => {
2267 // (*) binder moved here
2268 Where(ty::Binder::bind(vec![element_ty]))
2272 // (*) binder moved here
2273 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2276 ty::Closure(_, substs) => {
2277 // (*) binder moved here
2278 Where(ty::Binder::bind(substs.as_closure().upvar_tys().collect()))
2281 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2282 // Fallback to whatever user-defined impls exist in this case.
2286 ty::Infer(ty::TyVar(_)) => {
2287 // Unbound type variable. Might or might not have
2288 // applicable impls and so forth, depending on what
2289 // those type variables wind up being bound to.
2295 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2296 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2301 /// For default impls, we need to break apart a type into its
2302 /// "constituent types" -- meaning, the types that it contains.
2304 /// Here are some (simple) examples:
2307 /// (i32, u32) -> [i32, u32]
2308 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2309 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2310 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2312 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2322 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2324 | ty::Char => Vec::new(),
2330 | ty::Projection(..)
2332 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2333 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2336 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2340 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2342 ty::Tuple(ref tys) => {
2343 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2344 tys.iter().map(|k| k.expect_ty()).collect()
2347 ty::Closure(_, ref substs) => substs.as_closure().upvar_tys().collect(),
2349 ty::Generator(_, ref substs, _) => {
2350 let witness = substs.as_generator().witness();
2351 substs.as_generator().upvar_tys().chain(iter::once(witness)).collect()
2354 ty::GeneratorWitness(types) => {
2355 // This is sound because no regions in the witness can refer to
2356 // the binder outside the witness. So we'll effectivly reuse
2357 // the implicit binder around the witness.
2358 types.skip_binder().to_vec()
2361 // For `PhantomData<T>`, we pass `T`.
2362 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2364 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2366 ty::Opaque(def_id, substs) => {
2367 // We can resolve the `impl Trait` to its concrete type,
2368 // which enforces a DAG between the functions requiring
2369 // the auto trait bounds in question.
2370 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2375 fn collect_predicates_for_types(
2377 param_env: ty::ParamEnv<'tcx>,
2378 cause: ObligationCause<'tcx>,
2379 recursion_depth: usize,
2380 trait_def_id: DefId,
2381 types: ty::Binder<Vec<Ty<'tcx>>>,
2382 ) -> Vec<PredicateObligation<'tcx>> {
2383 // Because the types were potentially derived from
2384 // higher-ranked obligations they may reference late-bound
2385 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2386 // yield a type like `for<'a> &'a int`. In general, we
2387 // maintain the invariant that we never manipulate bound
2388 // regions, so we have to process these bound regions somehow.
2390 // The strategy is to:
2392 // 1. Instantiate those regions to placeholder regions (e.g.,
2393 // `for<'a> &'a int` becomes `&0 int`.
2394 // 2. Produce something like `&'0 int : Copy`
2395 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2402 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2404 self.infcx.commit_unconditionally(|_| {
2405 let (skol_ty, _) = self.infcx.replace_bound_vars_with_placeholders(&ty);
2406 let Normalized { value: normalized_ty, mut obligations } =
2407 ensure_sufficient_stack(|| {
2408 project::normalize_with_depth(
2416 let skol_obligation = predicate_for_trait_def(
2425 obligations.push(skol_obligation);
2432 ///////////////////////////////////////////////////////////////////////////
2435 // Confirmation unifies the output type parameters of the trait
2436 // with the values found in the obligation, possibly yielding a
2437 // type error. See the [rustc dev guide] for more details.
2439 // [rustc dev guide]:
2440 // https://rustc-dev-guide.rust-lang.org/traits/resolution.html#confirmation
2442 fn confirm_candidate(
2444 obligation: &TraitObligation<'tcx>,
2445 candidate: SelectionCandidate<'tcx>,
2446 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2447 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2450 BuiltinCandidate { has_nested } => {
2451 let data = self.confirm_builtin_candidate(obligation, has_nested);
2452 Ok(VtableBuiltin(data))
2455 ParamCandidate(param) => {
2456 let obligations = self.confirm_param_candidate(obligation, param);
2457 Ok(VtableParam(obligations))
2460 ImplCandidate(impl_def_id) => {
2461 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2464 AutoImplCandidate(trait_def_id) => {
2465 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2466 Ok(VtableAutoImpl(data))
2469 ProjectionCandidate => {
2470 self.confirm_projection_candidate(obligation);
2471 Ok(VtableParam(Vec::new()))
2474 ClosureCandidate => {
2475 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2476 Ok(VtableClosure(vtable_closure))
2479 GeneratorCandidate => {
2480 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2481 Ok(VtableGenerator(vtable_generator))
2484 FnPointerCandidate => {
2485 let data = self.confirm_fn_pointer_candidate(obligation)?;
2486 Ok(VtableFnPointer(data))
2489 TraitAliasCandidate(alias_def_id) => {
2490 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2491 Ok(VtableTraitAlias(data))
2494 ObjectCandidate => {
2495 let data = self.confirm_object_candidate(obligation);
2496 Ok(VtableObject(data))
2499 BuiltinObjectCandidate => {
2500 // This indicates something like `Trait + Send: Send`. In this case, we know that
2501 // this holds because that's what the object type is telling us, and there's really
2502 // no additional obligations to prove and no types in particular to unify, etc.
2503 Ok(VtableParam(Vec::new()))
2506 BuiltinUnsizeCandidate => {
2507 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2508 Ok(VtableBuiltin(data))
2513 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2514 self.infcx.commit_unconditionally(|snapshot| {
2516 self.match_projection_obligation_against_definition_bounds(obligation, snapshot);
2521 fn confirm_param_candidate(
2523 obligation: &TraitObligation<'tcx>,
2524 param: ty::PolyTraitRef<'tcx>,
2525 ) -> Vec<PredicateObligation<'tcx>> {
2526 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2528 // During evaluation, we already checked that this
2529 // where-clause trait-ref could be unified with the obligation
2530 // trait-ref. Repeat that unification now without any
2531 // transactional boundary; it should not fail.
2532 match self.match_where_clause_trait_ref(obligation, param) {
2533 Ok(obligations) => obligations,
2536 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2544 fn confirm_builtin_candidate(
2546 obligation: &TraitObligation<'tcx>,
2548 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2549 debug!("confirm_builtin_candidate({:?}, {:?})", obligation, has_nested);
2551 let lang_items = self.tcx().lang_items();
2552 let obligations = if has_nested {
2553 let trait_def = obligation.predicate.def_id();
2554 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2555 self.sized_conditions(obligation)
2556 } else if Some(trait_def) == lang_items.copy_trait() {
2557 self.copy_clone_conditions(obligation)
2558 } else if Some(trait_def) == lang_items.clone_trait() {
2559 self.copy_clone_conditions(obligation)
2561 bug!("unexpected builtin trait {:?}", trait_def)
2563 let nested = match conditions {
2564 BuiltinImplConditions::Where(nested) => nested,
2565 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation),
2568 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2569 ensure_sufficient_stack(|| {
2570 self.collect_predicates_for_types(
2571 obligation.param_env,
2573 obligation.recursion_depth + 1,
2582 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2584 VtableBuiltinData { nested: obligations }
2587 /// This handles the case where a `auto trait Foo` impl is being used.
2588 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2590 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2591 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2592 fn confirm_auto_impl_candidate(
2594 obligation: &TraitObligation<'tcx>,
2595 trait_def_id: DefId,
2596 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2597 debug!("confirm_auto_impl_candidate({:?}, {:?})", obligation, trait_def_id);
2599 let types = obligation.predicate.map_bound(|inner| {
2600 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2601 self.constituent_types_for_ty(self_ty)
2603 self.vtable_auto_impl(obligation, trait_def_id, types)
2606 /// See `confirm_auto_impl_candidate`.
2607 fn vtable_auto_impl(
2609 obligation: &TraitObligation<'tcx>,
2610 trait_def_id: DefId,
2611 nested: ty::Binder<Vec<Ty<'tcx>>>,
2612 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2613 debug!("vtable_auto_impl: nested={:?}", nested);
2614 ensure_sufficient_stack(|| {
2615 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2616 let mut obligations = self.collect_predicates_for_types(
2617 obligation.param_env,
2619 obligation.recursion_depth + 1,
2624 let trait_obligations: Vec<PredicateObligation<'_>> =
2625 self.infcx.commit_unconditionally(|_| {
2626 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2627 let (trait_ref, _) =
2628 self.infcx.replace_bound_vars_with_placeholders(&poly_trait_ref);
2629 let cause = obligation.derived_cause(ImplDerivedObligation);
2630 self.impl_or_trait_obligations(
2632 obligation.recursion_depth + 1,
2633 obligation.param_env,
2639 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
2640 // predicate as usual. It won't have any effect since auto traits are coinductive.
2641 obligations.extend(trait_obligations);
2643 debug!("vtable_auto_impl: obligations={:?}", obligations);
2645 VtableAutoImplData { trait_def_id, nested: obligations }
2649 fn confirm_impl_candidate(
2651 obligation: &TraitObligation<'tcx>,
2653 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2654 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
2656 // First, create the substitutions by matching the impl again,
2657 // this time not in a probe.
2658 self.infcx.commit_unconditionally(|snapshot| {
2659 let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
2660 debug!("confirm_impl_candidate: substs={:?}", substs);
2661 let cause = obligation.derived_cause(ImplDerivedObligation);
2662 ensure_sufficient_stack(|| {
2667 obligation.recursion_depth + 1,
2668 obligation.param_env,
2677 mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
2678 cause: ObligationCause<'tcx>,
2679 recursion_depth: usize,
2680 param_env: ty::ParamEnv<'tcx>,
2681 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2683 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
2684 impl_def_id, substs, recursion_depth,
2687 let mut impl_obligations = self.impl_or_trait_obligations(
2696 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2697 impl_def_id, impl_obligations
2700 // Because of RFC447, the impl-trait-ref and obligations
2701 // are sufficient to determine the impl substs, without
2702 // relying on projections in the impl-trait-ref.
2704 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2705 impl_obligations.append(&mut substs.obligations);
2707 VtableImplData { impl_def_id, substs: substs.value, nested: impl_obligations }
2710 fn confirm_object_candidate(
2712 obligation: &TraitObligation<'tcx>,
2713 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
2714 debug!("confirm_object_candidate({:?})", obligation);
2716 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
2717 // probably flatten the binder from the obligation and the binder
2718 // from the object. Have to try to make a broken test case that
2720 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2721 let poly_trait_ref = match self_ty.kind {
2722 ty::Dynamic(ref data, ..) => data
2724 .unwrap_or_else(|| {
2725 span_bug!(obligation.cause.span, "object candidate with no principal")
2727 .with_self_ty(self.tcx(), self_ty),
2728 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
2731 let mut upcast_trait_ref = None;
2732 let mut nested = vec![];
2736 let tcx = self.tcx();
2738 // We want to find the first supertrait in the list of
2739 // supertraits that we can unify with, and do that
2740 // unification. We know that there is exactly one in the list
2741 // where we can unify, because otherwise select would have
2742 // reported an ambiguity. (When we do find a match, also
2743 // record it for later.)
2744 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(|&t| {
2745 match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
2746 Ok(obligations) => {
2747 upcast_trait_ref = Some(t);
2748 nested.extend(obligations);
2755 // Additionally, for each of the non-matching predicates that
2756 // we pass over, we sum up the set of number of vtable
2757 // entries, so that we can compute the offset for the selected
2759 vtable_base = nonmatching.map(|t| super::util::count_own_vtable_entries(tcx, t)).sum();
2762 VtableObjectData { upcast_trait_ref: upcast_trait_ref.unwrap(), vtable_base, nested }
2765 fn confirm_fn_pointer_candidate(
2767 obligation: &TraitObligation<'tcx>,
2768 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2769 debug!("confirm_fn_pointer_candidate({:?})", obligation);
2771 // Okay to skip binder; it is reintroduced below.
2772 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2773 let sig = self_ty.fn_sig(self.tcx());
2774 let trait_ref = closure_trait_ref_and_return_type(
2776 obligation.predicate.def_id(),
2779 util::TupleArgumentsFlag::Yes,
2781 .map_bound(|(trait_ref, _)| trait_ref);
2783 let Normalized { value: trait_ref, obligations } = ensure_sufficient_stack(|| {
2784 project::normalize_with_depth(
2786 obligation.param_env,
2787 obligation.cause.clone(),
2788 obligation.recursion_depth + 1,
2793 self.confirm_poly_trait_refs(
2794 obligation.cause.clone(),
2795 obligation.param_env,
2796 obligation.predicate.to_poly_trait_ref(),
2799 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2802 fn confirm_trait_alias_candidate(
2804 obligation: &TraitObligation<'tcx>,
2805 alias_def_id: DefId,
2806 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
2807 debug!("confirm_trait_alias_candidate({:?}, {:?})", obligation, alias_def_id);
2809 self.infcx.commit_unconditionally(|_| {
2810 let (predicate, _) =
2811 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
2812 let trait_ref = predicate.trait_ref;
2813 let trait_def_id = trait_ref.def_id;
2814 let substs = trait_ref.substs;
2816 let trait_obligations = self.impl_or_trait_obligations(
2817 obligation.cause.clone(),
2818 obligation.recursion_depth,
2819 obligation.param_env,
2825 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
2826 trait_def_id, trait_obligations
2829 VtableTraitAliasData { alias_def_id, substs, nested: trait_obligations }
2833 fn confirm_generator_candidate(
2835 obligation: &TraitObligation<'tcx>,
2836 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2837 // Okay to skip binder because the substs on generator types never
2838 // touch bound regions, they just capture the in-scope
2839 // type/region parameters.
2840 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2841 let (generator_def_id, substs) = match self_ty.kind {
2842 ty::Generator(id, substs, _) => (id, substs),
2843 _ => bug!("closure candidate for non-closure {:?}", obligation),
2846 debug!("confirm_generator_candidate({:?},{:?},{:?})", obligation, generator_def_id, substs);
2848 let trait_ref = self.generator_trait_ref_unnormalized(obligation, substs);
2849 let Normalized { value: trait_ref, mut obligations } = ensure_sufficient_stack(|| {
2850 normalize_with_depth(
2852 obligation.param_env,
2853 obligation.cause.clone(),
2854 obligation.recursion_depth + 1,
2860 "confirm_generator_candidate(generator_def_id={:?}, \
2861 trait_ref={:?}, obligations={:?})",
2862 generator_def_id, trait_ref, obligations
2865 obligations.extend(self.confirm_poly_trait_refs(
2866 obligation.cause.clone(),
2867 obligation.param_env,
2868 obligation.predicate.to_poly_trait_ref(),
2872 Ok(VtableGeneratorData { generator_def_id, substs, nested: obligations })
2875 fn confirm_closure_candidate(
2877 obligation: &TraitObligation<'tcx>,
2878 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2879 debug!("confirm_closure_candidate({:?})", obligation);
2883 .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
2884 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
2886 // Okay to skip binder because the substs on closure types never
2887 // touch bound regions, they just capture the in-scope
2888 // type/region parameters.
2889 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2890 let (closure_def_id, substs) = match self_ty.kind {
2891 ty::Closure(id, substs) => (id, substs),
2892 _ => bug!("closure candidate for non-closure {:?}", obligation),
2895 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
2896 let Normalized { value: trait_ref, mut obligations } = ensure_sufficient_stack(|| {
2897 normalize_with_depth(
2899 obligation.param_env,
2900 obligation.cause.clone(),
2901 obligation.recursion_depth + 1,
2907 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2908 closure_def_id, trait_ref, obligations
2911 obligations.extend(self.confirm_poly_trait_refs(
2912 obligation.cause.clone(),
2913 obligation.param_env,
2914 obligation.predicate.to_poly_trait_ref(),
2920 if !self.tcx().sess.opts.debugging_opts.chalk {
2921 obligations.push(Obligation::new(
2922 obligation.cause.clone(),
2923 obligation.param_env,
2924 ty::PredicateKind::ClosureKind(closure_def_id, substs, kind),
2928 Ok(VtableClosureData { closure_def_id, substs, nested: obligations })
2931 /// In the case of closure types and fn pointers,
2932 /// we currently treat the input type parameters on the trait as
2933 /// outputs. This means that when we have a match we have only
2934 /// considered the self type, so we have to go back and make sure
2935 /// to relate the argument types too. This is kind of wrong, but
2936 /// since we control the full set of impls, also not that wrong,
2937 /// and it DOES yield better error messages (since we don't report
2938 /// errors as if there is no applicable impl, but rather report
2939 /// errors are about mismatched argument types.
2941 /// Here is an example. Imagine we have a closure expression
2942 /// and we desugared it so that the type of the expression is
2943 /// `Closure`, and `Closure` expects an int as argument. Then it
2944 /// is "as if" the compiler generated this impl:
2946 /// impl Fn(int) for Closure { ... }
2948 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2949 /// we have matched the self type `Closure`. At this point we'll
2950 /// compare the `int` to `usize` and generate an error.
2952 /// Note that this checking occurs *after* the impl has selected,
2953 /// because these output type parameters should not affect the
2954 /// selection of the impl. Therefore, if there is a mismatch, we
2955 /// report an error to the user.
2956 fn confirm_poly_trait_refs(
2958 obligation_cause: ObligationCause<'tcx>,
2959 obligation_param_env: ty::ParamEnv<'tcx>,
2960 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2961 expected_trait_ref: ty::PolyTraitRef<'tcx>,
2962 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2964 .at(&obligation_cause, obligation_param_env)
2965 .sup(obligation_trait_ref, expected_trait_ref)
2966 .map(|InferOk { obligations, .. }| obligations)
2967 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2970 fn confirm_builtin_unsize_candidate(
2972 obligation: &TraitObligation<'tcx>,
2973 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2974 let tcx = self.tcx();
2976 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
2977 // regions here. See the comment there for more details.
2978 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
2979 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2980 let target = self.infcx.shallow_resolve(target);
2982 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})", source, target);
2984 let mut nested = vec![];
2985 match (&source.kind, &target.kind) {
2986 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2987 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
2988 // See `assemble_candidates_for_unsizing` for more info.
2989 let existential_predicates = data_a.map_bound(|data_a| {
2992 .map(ty::ExistentialPredicate::Trait)
2994 .chain(data_a.projection_bounds().map(ty::ExistentialPredicate::Projection))
2995 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2996 tcx.mk_existential_predicates(iter)
2998 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
3000 // Require that the traits involved in this upcast are **equal**;
3001 // only the **lifetime bound** is changed.
3003 // FIXME: This condition is arguably too strong -- it would
3004 // suffice for the source trait to be a *subtype* of the target
3005 // trait. In particular, changing from something like
3006 // `for<'a, 'b> Foo<'a, 'b>` to `for<'a> Foo<'a, 'a>` should be
3007 // permitted. And, indeed, in the in commit
3008 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3009 // condition was loosened. However, when the leak check was
3010 // added back, using subtype here actually guides the coercion
3011 // code in such a way that it accepts `old-lub-glb-object.rs`.
3012 // This is probably a good thing, but I've modified this to `.eq`
3013 // because I want to continue rejecting that test (as we have
3014 // done for quite some time) before we are firmly comfortable
3015 // with what our behavior should be there. -nikomatsakis
3016 let InferOk { obligations, .. } = self
3018 .at(&obligation.cause, obligation.param_env)
3019 .eq(target, source_trait) // FIXME -- see below
3020 .map_err(|_| Unimplemented)?;
3021 nested.extend(obligations);
3023 // Register one obligation for 'a: 'b.
3024 let cause = ObligationCause::new(
3025 obligation.cause.span,
3026 obligation.cause.body_id,
3027 ObjectCastObligation(target),
3029 let outlives = ty::OutlivesPredicate(r_a, r_b);
3030 nested.push(Obligation::with_depth(
3032 obligation.recursion_depth + 1,
3033 obligation.param_env,
3034 ty::Binder::bind(outlives).to_predicate(),
3039 (_, &ty::Dynamic(ref data, r)) => {
3040 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
3041 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3042 return Err(TraitNotObjectSafe(did));
3045 let cause = ObligationCause::new(
3046 obligation.cause.span,
3047 obligation.cause.body_id,
3048 ObjectCastObligation(target),
3051 let predicate_to_obligation = |predicate| {
3052 Obligation::with_depth(
3054 obligation.recursion_depth + 1,
3055 obligation.param_env,
3060 // Create obligations:
3061 // - Casting `T` to `Trait`
3062 // - For all the various builtin bounds attached to the object cast. (In other
3063 // words, if the object type is `Foo + Send`, this would create an obligation for
3064 // the `Send` check.)
3065 // - Projection predicates
3067 data.iter().map(|predicate| {
3068 predicate_to_obligation(predicate.with_self_ty(tcx, source))
3072 // We can only make objects from sized types.
3073 let tr = ty::TraitRef::new(
3074 tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
3075 tcx.mk_substs_trait(source, &[]),
3077 nested.push(predicate_to_obligation(tr.without_const().to_predicate()));
3079 // If the type is `Foo + 'a`, ensure that the type
3080 // being cast to `Foo + 'a` outlives `'a`:
3081 let outlives = ty::OutlivesPredicate(source, r);
3082 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate()));
3085 // `[T; n]` -> `[T]`
3086 (&ty::Array(a, _), &ty::Slice(b)) => {
3087 let InferOk { obligations, .. } = self
3089 .at(&obligation.cause, obligation.param_env)
3091 .map_err(|_| Unimplemented)?;
3092 nested.extend(obligations);
3095 // `Struct<T>` -> `Struct<U>`
3096 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3097 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
3098 GenericArgKind::Type(ty) => match ty.kind {
3099 ty::Param(p) => Some(p.index),
3103 // Lifetimes aren't allowed to change during unsizing.
3104 GenericArgKind::Lifetime(_) => None,
3106 GenericArgKind::Const(ct) => match ct.val {
3107 ty::ConstKind::Param(p) => Some(p.index),
3112 // The last field of the structure has to exist and contain type/const parameters.
3113 let (tail_field, prefix_fields) =
3114 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
3115 let tail_field_ty = tcx.type_of(tail_field.did);
3117 let mut unsizing_params = GrowableBitSet::new_empty();
3118 let mut found = false;
3119 for arg in tail_field_ty.walk() {
3120 if let Some(i) = maybe_unsizing_param_idx(arg) {
3121 unsizing_params.insert(i);
3126 return Err(Unimplemented);
3129 // Ensure none of the other fields mention the parameters used
3131 // FIXME(eddyb) cache this (including computing `unsizing_params`)
3132 // by putting it in a query; it would only need the `DefId` as it
3133 // looks at declared field types, not anything substituted.
3134 for field in prefix_fields {
3135 for arg in tcx.type_of(field.did).walk() {
3136 if let Some(i) = maybe_unsizing_param_idx(arg) {
3137 if unsizing_params.contains(i) {
3138 return Err(Unimplemented);
3144 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`.
3145 let source_tail = tail_field_ty.subst(tcx, substs_a);
3146 let target_tail = tail_field_ty.subst(tcx, substs_b);
3148 // Check that the source struct with the target's
3149 // unsizing parameters is equal to the target.
3150 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, &k)| {
3151 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
3153 let new_struct = tcx.mk_adt(def, substs);
3154 let InferOk { obligations, .. } = self
3156 .at(&obligation.cause, obligation.param_env)
3157 .eq(target, new_struct)
3158 .map_err(|_| Unimplemented)?;
3159 nested.extend(obligations);
3161 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
3162 nested.push(predicate_for_trait_def(
3164 obligation.param_env,
3165 obligation.cause.clone(),
3166 obligation.predicate.def_id(),
3167 obligation.recursion_depth + 1,
3169 &[target_tail.into()],
3173 // `(.., T)` -> `(.., U)`
3174 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3175 assert_eq!(tys_a.len(), tys_b.len());
3177 // The last field of the tuple has to exist.
3178 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3181 return Err(Unimplemented);
3183 let &b_last = tys_b.last().unwrap();
3185 // Check that the source tuple with the target's
3186 // last element is equal to the target.
3187 let new_tuple = tcx.mk_tup(
3188 a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3190 let InferOk { obligations, .. } = self
3192 .at(&obligation.cause, obligation.param_env)
3193 .eq(target, new_tuple)
3194 .map_err(|_| Unimplemented)?;
3195 nested.extend(obligations);
3197 // Construct the nested `T: Unsize<U>` predicate.
3198 nested.push(ensure_sufficient_stack(|| {
3199 predicate_for_trait_def(
3201 obligation.param_env,
3202 obligation.cause.clone(),
3203 obligation.predicate.def_id(),
3204 obligation.recursion_depth + 1,
3214 Ok(VtableBuiltinData { nested })
3217 ///////////////////////////////////////////////////////////////////////////
3220 // Matching is a common path used for both evaluation and
3221 // confirmation. It basically unifies types that appear in impls
3222 // and traits. This does affect the surrounding environment;
3223 // therefore, when used during evaluation, match routines must be
3224 // run inside of a `probe()` so that their side-effects are
3230 obligation: &TraitObligation<'tcx>,
3231 snapshot: &CombinedSnapshot<'_, 'tcx>,
3232 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3233 match self.match_impl(impl_def_id, obligation, snapshot) {
3234 Ok(substs) => substs,
3237 "Impl {:?} was matchable against {:?} but now is not",
3248 obligation: &TraitObligation<'tcx>,
3249 snapshot: &CombinedSnapshot<'_, 'tcx>,
3250 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3251 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3253 // Before we create the substitutions and everything, first
3254 // consider a "quick reject". This avoids creating more types
3255 // and so forth that we need to.
3256 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3260 let (skol_obligation, placeholder_map) =
3261 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
3262 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3264 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
3266 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3268 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
3269 ensure_sufficient_stack(|| {
3270 project::normalize_with_depth(
3272 obligation.param_env,
3273 obligation.cause.clone(),
3274 obligation.recursion_depth + 1,
3280 "match_impl(impl_def_id={:?}, obligation={:?}, \
3281 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3282 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3285 let InferOk { obligations, .. } = self
3287 .at(&obligation.cause, obligation.param_env)
3288 .eq(skol_obligation_trait_ref, impl_trait_ref)
3289 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3290 nested_obligations.extend(obligations);
3292 if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3293 debug!("match_impl: failed leak check due to `{}`", e);
3298 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
3300 debug!("match_impl: reservation impls only apply in intercrate mode");
3304 debug!("match_impl: success impl_substs={:?}", impl_substs);
3305 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
3308 fn fast_reject_trait_refs(
3310 obligation: &TraitObligation<'_>,
3311 impl_trait_ref: &ty::TraitRef<'_>,
3313 // We can avoid creating type variables and doing the full
3314 // substitution if we find that any of the input types, when
3315 // simplified, do not match.
3317 obligation.predicate.skip_binder().trait_ref.substs.iter().zip(impl_trait_ref.substs).any(
3318 |(obligation_arg, impl_arg)| {
3319 match (obligation_arg.unpack(), impl_arg.unpack()) {
3320 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
3321 let simplified_obligation_ty =
3322 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3323 let simplified_impl_ty =
3324 fast_reject::simplify_type(self.tcx(), impl_ty, false);
3326 simplified_obligation_ty.is_some()
3327 && simplified_impl_ty.is_some()
3328 && simplified_obligation_ty != simplified_impl_ty
3330 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
3331 // Lifetimes can never cause a rejection.
3334 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
3335 // Conservatively ignore consts (i.e. assume they might
3336 // unify later) until we have `fast_reject` support for
3337 // them (if we'll ever need it, even).
3340 _ => unreachable!(),
3346 /// Normalize `where_clause_trait_ref` and try to match it against
3347 /// `obligation`. If successful, return any predicates that
3348 /// result from the normalization. Normalization is necessary
3349 /// because where-clauses are stored in the parameter environment
3351 fn match_where_clause_trait_ref(
3353 obligation: &TraitObligation<'tcx>,
3354 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3355 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3356 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3359 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3360 /// obligation is satisfied.
3361 fn match_poly_trait_ref(
3363 obligation: &TraitObligation<'tcx>,
3364 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3365 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3367 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3368 obligation, poly_trait_ref
3372 .at(&obligation.cause, obligation.param_env)
3373 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3374 .map(|InferOk { obligations, .. }| obligations)
3378 ///////////////////////////////////////////////////////////////////////////
3381 fn match_fresh_trait_refs(
3383 previous: &ty::PolyTraitRef<'tcx>,
3384 current: &ty::PolyTraitRef<'tcx>,
3385 param_env: ty::ParamEnv<'tcx>,
3387 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
3388 matcher.relate(previous, current).is_ok()
3393 previous_stack: TraitObligationStackList<'o, 'tcx>,
3394 obligation: &'o TraitObligation<'tcx>,
3395 ) -> TraitObligationStack<'o, 'tcx> {
3396 let fresh_trait_ref =
3397 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3399 let dfn = previous_stack.cache.next_dfn();
3400 let depth = previous_stack.depth() + 1;
3401 TraitObligationStack {
3404 reached_depth: Cell::new(depth),
3405 previous: previous_stack,
3411 fn closure_trait_ref_unnormalized(
3413 obligation: &TraitObligation<'tcx>,
3414 substs: SubstsRef<'tcx>,
3415 ) -> ty::PolyTraitRef<'tcx> {
3416 debug!("closure_trait_ref_unnormalized(obligation={:?}, substs={:?})", obligation, substs);
3417 let closure_sig = substs.as_closure().sig();
3419 debug!("closure_trait_ref_unnormalized: closure_sig = {:?}", closure_sig);
3421 // (1) Feels icky to skip the binder here, but OTOH we know
3422 // that the self-type is an unboxed closure type and hence is
3423 // in fact unparameterized (or at least does not reference any
3424 // regions bound in the obligation). Still probably some
3425 // refactoring could make this nicer.
3426 closure_trait_ref_and_return_type(
3428 obligation.predicate.def_id(),
3429 obligation.predicate.skip_binder().self_ty(), // (1)
3431 util::TupleArgumentsFlag::No,
3433 .map_bound(|(trait_ref, _)| trait_ref)
3436 fn generator_trait_ref_unnormalized(
3438 obligation: &TraitObligation<'tcx>,
3439 substs: SubstsRef<'tcx>,
3440 ) -> ty::PolyTraitRef<'tcx> {
3441 let gen_sig = substs.as_generator().poly_sig();
3443 // (1) Feels icky to skip the binder here, but OTOH we know
3444 // that the self-type is an generator type and hence is
3445 // in fact unparameterized (or at least does not reference any
3446 // regions bound in the obligation). Still probably some
3447 // refactoring could make this nicer.
3449 super::util::generator_trait_ref_and_outputs(
3451 obligation.predicate.def_id(),
3452 obligation.predicate.skip_binder().self_ty(), // (1)
3455 .map_bound(|(trait_ref, ..)| trait_ref)
3458 /// Returns the obligations that are implied by instantiating an
3459 /// impl or trait. The obligations are substituted and fully
3460 /// normalized. This is used when confirming an impl or default
3462 fn impl_or_trait_obligations(
3464 cause: ObligationCause<'tcx>,
3465 recursion_depth: usize,
3466 param_env: ty::ParamEnv<'tcx>,
3467 def_id: DefId, // of impl or trait
3468 substs: SubstsRef<'tcx>, // for impl or trait
3469 ) -> Vec<PredicateObligation<'tcx>> {
3470 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3471 let tcx = self.tcx();
3473 // To allow for one-pass evaluation of the nested obligation,
3474 // each predicate must be preceded by the obligations required
3476 // for example, if we have:
3477 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
3478 // the impl will have the following predicates:
3479 // <V as Iterator>::Item = U,
3480 // U: Iterator, U: Sized,
3481 // V: Iterator, V: Sized,
3482 // <U as Iterator>::Item: Copy
3483 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3484 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3485 // `$1: Copy`, so we must ensure the obligations are emitted in
3487 let predicates = tcx.predicates_of(def_id);
3488 assert_eq!(predicates.parent, None);
3489 let mut obligations = Vec::with_capacity(predicates.predicates.len());
3490 for (predicate, _) in predicates.predicates {
3491 let predicate = normalize_with_depth_to(
3496 &predicate.subst(tcx, substs),
3499 obligations.push(Obligation {
3500 cause: cause.clone(),
3507 // We are performing deduplication here to avoid exponential blowups
3508 // (#38528) from happening, but the real cause of the duplication is
3509 // unknown. What we know is that the deduplication avoids exponential
3510 // amount of predicates being propagated when processing deeply nested
3513 // This code is hot enough that it's worth avoiding the allocation
3514 // required for the FxHashSet when possible. Special-casing lengths 0,
3515 // 1 and 2 covers roughly 75-80% of the cases.
3516 if obligations.len() <= 1 {
3517 // No possibility of duplicates.
3518 } else if obligations.len() == 2 {
3519 // Only two elements. Drop the second if they are equal.
3520 if obligations[0] == obligations[1] {
3521 obligations.truncate(1);
3524 // Three or more elements. Use a general deduplication process.
3525 let mut seen = FxHashSet::default();
3526 obligations.retain(|i| seen.insert(i.clone()));
3533 trait TraitObligationExt<'tcx> {
3536 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3537 ) -> ObligationCause<'tcx>;
3540 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
3541 #[allow(unused_comparisons)]
3544 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3545 ) -> ObligationCause<'tcx> {
3547 * Creates a cause for obligations that are derived from
3548 * `obligation` by a recursive search (e.g., for a builtin
3549 * bound, or eventually a `auto trait Foo`). If `obligation`
3550 * is itself a derived obligation, this is just a clone, but
3551 * otherwise we create a "derived obligation" cause so as to
3552 * keep track of the original root obligation for error
3556 let obligation = self;
3558 // NOTE(flaper87): As of now, it keeps track of the whole error
3559 // chain. Ideally, we should have a way to configure this either
3560 // by using -Z verbose or just a CLI argument.
3561 let derived_cause = DerivedObligationCause {
3562 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3563 parent_code: Rc::new(obligation.cause.code.clone()),
3565 let derived_code = variant(derived_cause);
3566 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3570 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
3571 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3572 TraitObligationStackList::with(self)
3575 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
3579 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3583 /// Indicates that attempting to evaluate this stack entry
3584 /// required accessing something from the stack at depth `reached_depth`.
3585 fn update_reached_depth(&self, reached_depth: usize) {
3587 self.depth > reached_depth,
3588 "invoked `update_reached_depth` with something under this stack: \
3589 self.depth={} reached_depth={}",
3593 debug!("update_reached_depth(reached_depth={})", reached_depth);
3595 while reached_depth < p.depth {
3596 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
3597 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
3598 p = p.previous.head.unwrap();
3603 /// The "provisional evaluation cache" is used to store intermediate cache results
3604 /// when solving auto traits. Auto traits are unusual in that they can support
3605 /// cycles. So, for example, a "proof tree" like this would be ok:
3607 /// - `Foo<T>: Send` :-
3608 /// - `Bar<T>: Send` :-
3609 /// - `Foo<T>: Send` -- cycle, but ok
3610 /// - `Baz<T>: Send`
3612 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
3613 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
3614 /// For non-auto traits, this cycle would be an error, but for auto traits (because
3615 /// they are coinductive) it is considered ok.
3617 /// However, there is a complication: at the point where we have
3618 /// "proven" `Bar<T>: Send`, we have in fact only proven it
3619 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
3620 /// *under the assumption* that `Foo<T>: Send`. But what if we later
3621 /// find out this assumption is wrong? Specifically, we could
3622 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
3623 /// `Bar<T>: Send` didn't turn out to be true.
3625 /// In Issue #60010, we found a bug in rustc where it would cache
3626 /// these intermediate results. This was fixed in #60444 by disabling
3627 /// *all* caching for things involved in a cycle -- in our example,
3628 /// that would mean we don't cache that `Bar<T>: Send`. But this led
3629 /// to large slowdowns.
3631 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
3632 /// first requires proving `Bar<T>: Send` (which is true:
3634 /// - `Foo<T>: Send` :-
3635 /// - `Bar<T>: Send` :-
3636 /// - `Foo<T>: Send` -- cycle, but ok
3637 /// - `Baz<T>: Send`
3638 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
3639 /// - `*const T: Send` -- but what if we later encounter an error?
3641 /// The *provisional evaluation cache* resolves this issue. It stores
3642 /// cache results that we've proven but which were involved in a cycle
3643 /// in some way. We track the minimal stack depth (i.e., the
3644 /// farthest from the top of the stack) that we are dependent on.
3645 /// The idea is that the cache results within are all valid -- so long as
3646 /// none of the nodes in between the current node and the node at that minimum
3647 /// depth result in an error (in which case the cached results are just thrown away).
3649 /// During evaluation, we consult this provisional cache and rely on
3650 /// it. Accessing a cached value is considered equivalent to accessing
3651 /// a result at `reached_depth`, so it marks the *current* solution as
3652 /// provisional as well. If an error is encountered, we toss out any
3653 /// provisional results added from the subtree that encountered the
3654 /// error. When we pop the node at `reached_depth` from the stack, we
3655 /// can commit all the things that remain in the provisional cache.
3656 struct ProvisionalEvaluationCache<'tcx> {
3657 /// next "depth first number" to issue -- just a counter
3660 /// Stores the "coldest" depth (bottom of stack) reached by any of
3661 /// the evaluation entries. The idea here is that all things in the provisional
3662 /// cache are always dependent on *something* that is colder in the stack:
3663 /// therefore, if we add a new entry that is dependent on something *colder still*,
3664 /// we have to modify the depth for all entries at once.
3668 /// Imagine we have a stack `A B C D E` (with `E` being the top of
3669 /// the stack). We cache something with depth 2, which means that
3670 /// it was dependent on C. Then we pop E but go on and process a
3671 /// new node F: A B C D F. Now F adds something to the cache with
3672 /// depth 1, meaning it is dependent on B. Our original cache
3673 /// entry is also dependent on B, because there is a path from E
3674 /// to C and then from C to F and from F to B.
3675 reached_depth: Cell<usize>,
3677 /// Map from cache key to the provisionally evaluated thing.
3678 /// The cache entries contain the result but also the DFN in which they
3679 /// were added. The DFN is used to clear out values on failure.
3681 /// Imagine we have a stack like:
3683 /// - `A B C` and we add a cache for the result of C (DFN 2)
3684 /// - Then we have a stack `A B D` where `D` has DFN 3
3685 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
3686 /// - `E` generates various cache entries which have cyclic dependices on `B`
3687 /// - `A B D E F` and so forth
3688 /// - the DFN of `F` for example would be 5
3689 /// - then we determine that `E` is in error -- we will then clear
3690 /// all cache values whose DFN is >= 4 -- in this case, that
3691 /// means the cached value for `F`.
3692 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
3695 /// A cache value for the provisional cache: contains the depth-first
3696 /// number (DFN) and result.
3697 #[derive(Copy, Clone, Debug)]
3698 struct ProvisionalEvaluation {
3700 result: EvaluationResult,
3703 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
3704 fn default() -> Self {
3705 Self { dfn: Cell::new(0), reached_depth: Cell::new(usize::MAX), map: Default::default() }
3709 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
3710 /// Get the next DFN in sequence (basically a counter).
3711 fn next_dfn(&self) -> usize {
3712 let result = self.dfn.get();
3713 self.dfn.set(result + 1);
3717 /// Check the provisional cache for any result for
3718 /// `fresh_trait_ref`. If there is a hit, then you must consider
3719 /// it an access to the stack slots at depth
3720 /// `self.current_reached_depth()` and above.
3721 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
3723 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
3725 self.map.borrow().get(&fresh_trait_ref),
3726 self.reached_depth.get(),
3728 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
3731 /// Current value of the `reached_depth` counter -- all the
3732 /// provisional cache entries are dependent on the item at this
3734 fn current_reached_depth(&self) -> usize {
3735 self.reached_depth.get()
3738 /// Insert a provisional result into the cache. The result came
3739 /// from the node with the given DFN. It accessed a minimum depth
3740 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
3741 /// and resulted in `result`.
3742 fn insert_provisional(
3745 reached_depth: usize,
3746 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
3747 result: EvaluationResult,
3750 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
3751 from_dfn, reached_depth, fresh_trait_ref, result,
3753 let r_d = self.reached_depth.get();
3754 self.reached_depth.set(r_d.min(reached_depth));
3756 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
3758 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
3761 /// Invoked when the node with dfn `dfn` does not get a successful
3762 /// result. This will clear out any provisional cache entries
3763 /// that were added since `dfn` was created. This is because the
3764 /// provisional entries are things which must assume that the
3765 /// things on the stack at the time of their creation succeeded --
3766 /// since the failing node is presently at the top of the stack,
3767 /// these provisional entries must either depend on it or some
3769 fn on_failure(&self, dfn: usize) {
3770 debug!("on_failure(dfn={:?})", dfn,);
3771 self.map.borrow_mut().retain(|key, eval| {
3772 if !eval.from_dfn >= dfn {
3773 debug!("on_failure: removing {:?}", key);
3781 /// Invoked when the node at depth `depth` completed without
3782 /// depending on anything higher in the stack (if that completion
3783 /// was a failure, then `on_failure` should have been invoked
3784 /// already). The callback `op` will be invoked for each
3785 /// provisional entry that we can now confirm.
3789 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
3791 debug!("on_completion(depth={}, reached_depth={})", depth, self.reached_depth.get(),);
3793 if self.reached_depth.get() < depth {
3794 debug!("on_completion: did not yet reach depth to complete");
3798 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
3799 debug!("on_completion: fresh_trait_ref={:?} eval={:?}", fresh_trait_ref, eval,);
3801 op(fresh_trait_ref, eval.result);
3804 self.reached_depth.set(usize::MAX);
3808 #[derive(Copy, Clone)]
3809 struct TraitObligationStackList<'o, 'tcx> {
3810 cache: &'o ProvisionalEvaluationCache<'tcx>,
3811 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3814 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3815 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3816 TraitObligationStackList { cache, head: None }
3819 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3820 TraitObligationStackList { cache: r.cache(), head: Some(r) }
3823 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3827 fn depth(&self) -> usize {
3828 if let Some(head) = self.head { head.depth } else { 0 }
3832 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
3833 type Item = &'o TraitObligationStack<'o, 'tcx>;
3835 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3846 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
3847 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3848 write!(f, "TraitObligationStack({:?})", self.obligation)