]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/select/mod.rs
Rollup merge of #88851 - fee1-dead:dup-bound, r=oli-obk
[rust.git] / compiler / rustc_trait_selection / src / traits / select / mod.rs
1 //! Candidate selection. See the [rustc dev guide] for more information on how this works.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
4
5 use self::EvaluationResult::*;
6 use self::SelectionCandidate::*;
7
8 use super::coherence::{self, Conflict};
9 use super::const_evaluatable;
10 use super::project;
11 use super::project::normalize_with_depth_to;
12 use super::project::ProjectionTyObligation;
13 use super::util;
14 use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
15 use super::wf;
16 use super::DerivedObligationCause;
17 use super::Obligation;
18 use super::ObligationCauseCode;
19 use super::Selection;
20 use super::SelectionResult;
21 use super::TraitQueryMode;
22 use super::{Normalized, ProjectionCacheKey};
23 use super::{ObligationCause, PredicateObligation, TraitObligation};
24 use super::{Overflow, SelectionError, Unimplemented};
25
26 use crate::infer::{InferCtxt, InferOk, TypeFreshener};
27 use crate::traits::error_reporting::InferCtxtExt;
28 use crate::traits::project::ProjectionCacheKeyExt;
29 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_errors::ErrorReported;
33 use rustc_hir as hir;
34 use rustc_hir::def_id::DefId;
35 use rustc_infer::infer::LateBoundRegionConversionTime;
36 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
37 use rustc_middle::mir::interpret::ErrorHandled;
38 use rustc_middle::thir::abstract_const::NotConstEvaluatable;
39 use rustc_middle::ty::fast_reject;
40 use rustc_middle::ty::print::with_no_trimmed_paths;
41 use rustc_middle::ty::relate::TypeRelation;
42 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
43 use rustc_middle::ty::WithConstness;
44 use rustc_middle::ty::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
45 use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable};
46 use rustc_span::symbol::sym;
47
48 use std::cell::{Cell, RefCell};
49 use std::cmp;
50 use std::fmt::{self, Display};
51 use std::iter;
52
53 pub use rustc_middle::traits::select::*;
54
55 mod candidate_assembly;
56 mod confirmation;
57
58 #[derive(Clone, Debug)]
59 pub enum IntercrateAmbiguityCause {
60     DownstreamCrate { trait_desc: String, self_desc: Option<String> },
61     UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
62     ReservationImpl { message: String },
63 }
64
65 impl IntercrateAmbiguityCause {
66     /// Emits notes when the overlap is caused by complex intercrate ambiguities.
67     /// See #23980 for details.
68     pub fn add_intercrate_ambiguity_hint(&self, err: &mut rustc_errors::DiagnosticBuilder<'_>) {
69         err.note(&self.intercrate_ambiguity_hint());
70     }
71
72     pub fn intercrate_ambiguity_hint(&self) -> String {
73         match self {
74             IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
75                 let self_desc = if let Some(ty) = self_desc {
76                     format!(" for type `{}`", ty)
77                 } else {
78                     String::new()
79                 };
80                 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
81             }
82             IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
83                 let self_desc = if let Some(ty) = self_desc {
84                     format!(" for type `{}`", ty)
85                 } else {
86                     String::new()
87                 };
88                 format!(
89                     "upstream crates may add a new impl of trait `{}`{} \
90                      in future versions",
91                     trait_desc, self_desc
92                 )
93             }
94             IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
95         }
96     }
97 }
98
99 pub struct SelectionContext<'cx, 'tcx> {
100     infcx: &'cx InferCtxt<'cx, 'tcx>,
101
102     /// Freshener used specifically for entries on the obligation
103     /// stack. This ensures that all entries on the stack at one time
104     /// will have the same set of placeholder entries, which is
105     /// important for checking for trait bounds that recursively
106     /// require themselves.
107     freshener: TypeFreshener<'cx, 'tcx>,
108
109     /// If `true`, indicates that the evaluation should be conservative
110     /// and consider the possibility of types outside this crate.
111     /// This comes up primarily when resolving ambiguity. Imagine
112     /// there is some trait reference `$0: Bar` where `$0` is an
113     /// inference variable. If `intercrate` is true, then we can never
114     /// say for sure that this reference is not implemented, even if
115     /// there are *no impls at all for `Bar`*, because `$0` could be
116     /// bound to some type that in a downstream crate that implements
117     /// `Bar`. This is the suitable mode for coherence. Elsewhere,
118     /// though, we set this to false, because we are only interested
119     /// in types that the user could actually have written --- in
120     /// other words, we consider `$0: Bar` to be unimplemented if
121     /// there is no type that the user could *actually name* that
122     /// would satisfy it. This avoids crippling inference, basically.
123     intercrate: bool,
124
125     intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
126
127     /// Controls whether or not to filter out negative impls when selecting.
128     /// This is used in librustdoc to distinguish between the lack of an impl
129     /// and a negative impl
130     allow_negative_impls: bool,
131
132     /// Are we in a const context that needs `~const` bounds to be const?
133     is_in_const_context: bool,
134
135     /// The mode that trait queries run in, which informs our error handling
136     /// policy. In essence, canonicalized queries need their errors propagated
137     /// rather than immediately reported because we do not have accurate spans.
138     query_mode: TraitQueryMode,
139 }
140
141 // A stack that walks back up the stack frame.
142 struct TraitObligationStack<'prev, 'tcx> {
143     obligation: &'prev TraitObligation<'tcx>,
144
145     /// The trait ref from `obligation` but "freshened" with the
146     /// selection-context's freshener. Used to check for recursion.
147     fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
148
149     /// Starts out equal to `depth` -- if, during evaluation, we
150     /// encounter a cycle, then we will set this flag to the minimum
151     /// depth of that cycle for all participants in the cycle. These
152     /// participants will then forego caching their results. This is
153     /// not the most efficient solution, but it addresses #60010. The
154     /// problem we are trying to prevent:
155     ///
156     /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
157     /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
158     /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
159     ///
160     /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
161     /// is `EvaluatedToOk`; this is because they were only considered
162     /// ok on the premise that if `A: AutoTrait` held, but we indeed
163     /// encountered a problem (later on) with `A: AutoTrait. So we
164     /// currently set a flag on the stack node for `B: AutoTrait` (as
165     /// well as the second instance of `A: AutoTrait`) to suppress
166     /// caching.
167     ///
168     /// This is a simple, targeted fix. A more-performant fix requires
169     /// deeper changes, but would permit more caching: we could
170     /// basically defer caching until we have fully evaluated the
171     /// tree, and then cache the entire tree at once. In any case, the
172     /// performance impact here shouldn't be so horrible: every time
173     /// this is hit, we do cache at least one trait, so we only
174     /// evaluate each member of a cycle up to N times, where N is the
175     /// length of the cycle. This means the performance impact is
176     /// bounded and we shouldn't have any terrible worst-cases.
177     reached_depth: Cell<usize>,
178
179     previous: TraitObligationStackList<'prev, 'tcx>,
180
181     /// The number of parent frames plus one (thus, the topmost frame has depth 1).
182     depth: usize,
183
184     /// The depth-first number of this node in the search graph -- a
185     /// pre-order index. Basically, a freshly incremented counter.
186     dfn: usize,
187 }
188
189 struct SelectionCandidateSet<'tcx> {
190     // A list of candidates that definitely apply to the current
191     // obligation (meaning: types unify).
192     vec: Vec<SelectionCandidate<'tcx>>,
193
194     // If `true`, then there were candidates that might or might
195     // not have applied, but we couldn't tell. This occurs when some
196     // of the input types are type variables, in which case there are
197     // various "builtin" rules that might or might not trigger.
198     ambiguous: bool,
199 }
200
201 #[derive(PartialEq, Eq, Debug, Clone)]
202 struct EvaluatedCandidate<'tcx> {
203     candidate: SelectionCandidate<'tcx>,
204     evaluation: EvaluationResult,
205 }
206
207 /// When does the builtin impl for `T: Trait` apply?
208 enum BuiltinImplConditions<'tcx> {
209     /// The impl is conditional on `T1, T2, ...: Trait`.
210     Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
211     /// There is no built-in impl. There may be some other
212     /// candidate (a where-clause or user-defined impl).
213     None,
214     /// It is unknown whether there is an impl.
215     Ambiguous,
216 }
217
218 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
219     pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
220         SelectionContext {
221             infcx,
222             freshener: infcx.freshener_keep_static(),
223             intercrate: false,
224             intercrate_ambiguity_causes: None,
225             allow_negative_impls: false,
226             is_in_const_context: false,
227             query_mode: TraitQueryMode::Standard,
228         }
229     }
230
231     pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
232         SelectionContext {
233             infcx,
234             freshener: infcx.freshener_keep_static(),
235             intercrate: true,
236             intercrate_ambiguity_causes: None,
237             allow_negative_impls: false,
238             is_in_const_context: false,
239             query_mode: TraitQueryMode::Standard,
240         }
241     }
242
243     pub fn with_negative(
244         infcx: &'cx InferCtxt<'cx, 'tcx>,
245         allow_negative_impls: bool,
246     ) -> SelectionContext<'cx, 'tcx> {
247         debug!(?allow_negative_impls, "with_negative");
248         SelectionContext {
249             infcx,
250             freshener: infcx.freshener_keep_static(),
251             intercrate: false,
252             intercrate_ambiguity_causes: None,
253             allow_negative_impls,
254             is_in_const_context: false,
255             query_mode: TraitQueryMode::Standard,
256         }
257     }
258
259     pub fn with_query_mode(
260         infcx: &'cx InferCtxt<'cx, 'tcx>,
261         query_mode: TraitQueryMode,
262     ) -> SelectionContext<'cx, 'tcx> {
263         debug!(?query_mode, "with_query_mode");
264         SelectionContext {
265             infcx,
266             freshener: infcx.freshener_keep_static(),
267             intercrate: false,
268             intercrate_ambiguity_causes: None,
269             allow_negative_impls: false,
270             is_in_const_context: false,
271             query_mode,
272         }
273     }
274
275     pub fn with_constness(
276         infcx: &'cx InferCtxt<'cx, 'tcx>,
277         constness: hir::Constness,
278     ) -> SelectionContext<'cx, 'tcx> {
279         SelectionContext {
280             infcx,
281             freshener: infcx.freshener_keep_static(),
282             intercrate: false,
283             intercrate_ambiguity_causes: None,
284             allow_negative_impls: false,
285             is_in_const_context: matches!(constness, hir::Constness::Const),
286             query_mode: TraitQueryMode::Standard,
287         }
288     }
289
290     /// Enables tracking of intercrate ambiguity causes. These are
291     /// used in coherence to give improved diagnostics. We don't do
292     /// this until we detect a coherence error because it can lead to
293     /// false overflow results (#47139) and because it costs
294     /// computation time.
295     pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
296         assert!(self.intercrate);
297         assert!(self.intercrate_ambiguity_causes.is_none());
298         self.intercrate_ambiguity_causes = Some(vec![]);
299         debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
300     }
301
302     /// Gets the intercrate ambiguity causes collected since tracking
303     /// was enabled and disables tracking at the same time. If
304     /// tracking is not enabled, just returns an empty vector.
305     pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
306         assert!(self.intercrate);
307         self.intercrate_ambiguity_causes.take().unwrap_or_default()
308     }
309
310     pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
311         self.infcx
312     }
313
314     pub fn tcx(&self) -> TyCtxt<'tcx> {
315         self.infcx.tcx
316     }
317
318     /// Returns `true` if the trait predicate is considerd `const` to this selection context.
319     pub fn is_trait_predicate_const(&self, pred: ty::TraitPredicate<'_>) -> bool {
320         match pred.constness {
321             ty::BoundConstness::ConstIfConst if self.is_in_const_context => true,
322             _ => false,
323         }
324     }
325
326     /// Returns `true` if the predicate is considered `const` to
327     /// this selection context.
328     pub fn is_predicate_const(&self, pred: ty::Predicate<'_>) -> bool {
329         match pred.kind().skip_binder() {
330             ty::PredicateKind::Trait(pred) => self.is_trait_predicate_const(pred),
331             _ => false,
332         }
333     }
334
335     ///////////////////////////////////////////////////////////////////////////
336     // Selection
337     //
338     // The selection phase tries to identify *how* an obligation will
339     // be resolved. For example, it will identify which impl or
340     // parameter bound is to be used. The process can be inconclusive
341     // if the self type in the obligation is not fully inferred. Selection
342     // can result in an error in one of two ways:
343     //
344     // 1. If no applicable impl or parameter bound can be found.
345     // 2. If the output type parameters in the obligation do not match
346     //    those specified by the impl/bound. For example, if the obligation
347     //    is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
348     //    `impl<T> Iterable<T> for Vec<T>`, than an error would result.
349
350     /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
351     /// type environment by performing unification.
352     #[instrument(level = "debug", skip(self))]
353     pub fn select(
354         &mut self,
355         obligation: &TraitObligation<'tcx>,
356     ) -> SelectionResult<'tcx, Selection<'tcx>> {
357         debug_assert!(!obligation.predicate.has_escaping_bound_vars());
358
359         let pec = &ProvisionalEvaluationCache::default();
360         let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
361
362         let candidate = match self.candidate_from_obligation(&stack) {
363             Err(SelectionError::Overflow) => {
364                 // In standard mode, overflow must have been caught and reported
365                 // earlier.
366                 assert!(self.query_mode == TraitQueryMode::Canonical);
367                 return Err(SelectionError::Overflow);
368             }
369             Err(e) => {
370                 return Err(e);
371             }
372             Ok(None) => {
373                 return Ok(None);
374             }
375             Ok(Some(candidate)) => candidate,
376         };
377
378         match self.confirm_candidate(obligation, candidate) {
379             Err(SelectionError::Overflow) => {
380                 assert!(self.query_mode == TraitQueryMode::Canonical);
381                 Err(SelectionError::Overflow)
382             }
383             Err(e) => Err(e),
384             Ok(candidate) => {
385                 debug!(?candidate);
386                 Ok(Some(candidate))
387             }
388         }
389     }
390
391     ///////////////////////////////////////////////////////////////////////////
392     // EVALUATION
393     //
394     // Tests whether an obligation can be selected or whether an impl
395     // can be applied to particular types. It skips the "confirmation"
396     // step and hence completely ignores output type parameters.
397     //
398     // The result is "true" if the obligation *may* hold and "false" if
399     // we can be sure it does not.
400
401     /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
402     pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
403         debug!(?obligation, "predicate_may_hold_fatal");
404
405         // This fatal query is a stopgap that should only be used in standard mode,
406         // where we do not expect overflow to be propagated.
407         assert!(self.query_mode == TraitQueryMode::Standard);
408
409         self.evaluate_root_obligation(obligation)
410             .expect("Overflow should be caught earlier in standard query mode")
411             .may_apply()
412     }
413
414     /// Evaluates whether the obligation `obligation` can be satisfied
415     /// and returns an `EvaluationResult`. This is meant for the
416     /// *initial* call.
417     pub fn evaluate_root_obligation(
418         &mut self,
419         obligation: &PredicateObligation<'tcx>,
420     ) -> Result<EvaluationResult, OverflowError> {
421         self.evaluation_probe(|this| {
422             this.evaluate_predicate_recursively(
423                 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
424                 obligation.clone(),
425             )
426         })
427     }
428
429     fn evaluation_probe(
430         &mut self,
431         op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
432     ) -> Result<EvaluationResult, OverflowError> {
433         self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
434             let result = op(self)?;
435
436             match self.infcx.leak_check(true, snapshot) {
437                 Ok(()) => {}
438                 Err(_) => return Ok(EvaluatedToErr),
439             }
440
441             match self.infcx.region_constraints_added_in_snapshot(snapshot) {
442                 None => Ok(result),
443                 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
444             }
445         })
446     }
447
448     /// Evaluates the predicates in `predicates` recursively. Note that
449     /// this applies projections in the predicates, and therefore
450     /// is run within an inference probe.
451     fn evaluate_predicates_recursively<'o, I>(
452         &mut self,
453         stack: TraitObligationStackList<'o, 'tcx>,
454         predicates: I,
455     ) -> Result<EvaluationResult, OverflowError>
456     where
457         I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
458     {
459         let mut result = EvaluatedToOk;
460         debug!(?predicates, "evaluate_predicates_recursively");
461         for obligation in predicates {
462             let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
463             if let EvaluatedToErr = eval {
464                 // fast-path - EvaluatedToErr is the top of the lattice,
465                 // so we don't need to look on the other predicates.
466                 return Ok(EvaluatedToErr);
467             } else {
468                 result = cmp::max(result, eval);
469             }
470         }
471         Ok(result)
472     }
473
474     #[instrument(
475         level = "debug",
476         skip(self, previous_stack),
477         fields(previous_stack = ?previous_stack.head())
478     )]
479     fn evaluate_predicate_recursively<'o>(
480         &mut self,
481         previous_stack: TraitObligationStackList<'o, 'tcx>,
482         obligation: PredicateObligation<'tcx>,
483     ) -> Result<EvaluationResult, OverflowError> {
484         // `previous_stack` stores a `TraitObligation`, while `obligation` is
485         // a `PredicateObligation`. These are distinct types, so we can't
486         // use any `Option` combinator method that would force them to be
487         // the same.
488         match previous_stack.head() {
489             Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
490             None => self.check_recursion_limit(&obligation, &obligation)?,
491         }
492
493         let result = ensure_sufficient_stack(|| {
494             let bound_predicate = obligation.predicate.kind();
495             match bound_predicate.skip_binder() {
496                 ty::PredicateKind::Trait(t) => {
497                     let t = bound_predicate.rebind(t);
498                     debug_assert!(!t.has_escaping_bound_vars());
499                     let obligation = obligation.with(t);
500                     self.evaluate_trait_predicate_recursively(previous_stack, obligation)
501                 }
502
503                 ty::PredicateKind::Subtype(p) => {
504                     let p = bound_predicate.rebind(p);
505                     // Does this code ever run?
506                     match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
507                         Some(Ok(InferOk { mut obligations, .. })) => {
508                             self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
509                             self.evaluate_predicates_recursively(
510                                 previous_stack,
511                                 obligations.into_iter(),
512                             )
513                         }
514                         Some(Err(_)) => Ok(EvaluatedToErr),
515                         None => Ok(EvaluatedToAmbig),
516                     }
517                 }
518
519                 ty::PredicateKind::Coerce(p) => {
520                     let p = bound_predicate.rebind(p);
521                     // Does this code ever run?
522                     match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
523                         Some(Ok(InferOk { mut obligations, .. })) => {
524                             self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
525                             self.evaluate_predicates_recursively(
526                                 previous_stack,
527                                 obligations.into_iter(),
528                             )
529                         }
530                         Some(Err(_)) => Ok(EvaluatedToErr),
531                         None => Ok(EvaluatedToAmbig),
532                     }
533                 }
534
535                 ty::PredicateKind::WellFormed(arg) => match wf::obligations(
536                     self.infcx,
537                     obligation.param_env,
538                     obligation.cause.body_id,
539                     obligation.recursion_depth + 1,
540                     arg,
541                     obligation.cause.span,
542                 ) {
543                     Some(mut obligations) => {
544                         self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
545                         self.evaluate_predicates_recursively(previous_stack, obligations)
546                     }
547                     None => Ok(EvaluatedToAmbig),
548                 },
549
550                 ty::PredicateKind::TypeOutlives(pred) => {
551                     if pred.0.is_known_global() {
552                         Ok(EvaluatedToOk)
553                     } else {
554                         Ok(EvaluatedToOkModuloRegions)
555                     }
556                 }
557
558                 ty::PredicateKind::RegionOutlives(..) => {
559                     // We do not consider region relationships when evaluating trait matches.
560                     Ok(EvaluatedToOkModuloRegions)
561                 }
562
563                 ty::PredicateKind::ObjectSafe(trait_def_id) => {
564                     if self.tcx().is_object_safe(trait_def_id) {
565                         Ok(EvaluatedToOk)
566                     } else {
567                         Ok(EvaluatedToErr)
568                     }
569                 }
570
571                 ty::PredicateKind::Projection(data) => {
572                     let data = bound_predicate.rebind(data);
573                     let project_obligation = obligation.with(data);
574                     match project::poly_project_and_unify_type(self, &project_obligation) {
575                         Ok(Ok(Some(mut subobligations))) => {
576                             self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
577                             let result = self
578                                 .evaluate_predicates_recursively(previous_stack, subobligations);
579                             if let Some(key) =
580                                 ProjectionCacheKey::from_poly_projection_predicate(self, data)
581                             {
582                                 self.infcx.inner.borrow_mut().projection_cache().complete(key);
583                             }
584                             result
585                         }
586                         Ok(Ok(None)) => Ok(EvaluatedToAmbig),
587                         Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur),
588                         Err(_) => Ok(EvaluatedToErr),
589                     }
590                 }
591
592                 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
593                     match self.infcx.closure_kind(closure_substs) {
594                         Some(closure_kind) => {
595                             if closure_kind.extends(kind) {
596                                 Ok(EvaluatedToOk)
597                             } else {
598                                 Ok(EvaluatedToErr)
599                             }
600                         }
601                         None => Ok(EvaluatedToAmbig),
602                     }
603                 }
604
605                 ty::PredicateKind::ConstEvaluatable(uv) => {
606                     match const_evaluatable::is_const_evaluatable(
607                         self.infcx,
608                         uv,
609                         obligation.param_env,
610                         obligation.cause.span,
611                     ) {
612                         Ok(()) => Ok(EvaluatedToOk),
613                         Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
614                         Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
615                         Err(_) => Ok(EvaluatedToErr),
616                     }
617                 }
618
619                 ty::PredicateKind::ConstEquate(c1, c2) => {
620                     debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
621
622                     if self.tcx().features().generic_const_exprs {
623                         // FIXME: we probably should only try to unify abstract constants
624                         // if the constants depend on generic parameters.
625                         //
626                         // Let's just see where this breaks :shrug:
627                         if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
628                             (c1.val, c2.val)
629                         {
630                             if self.infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
631                                 return Ok(EvaluatedToOk);
632                             }
633                         }
634                     }
635
636                     let evaluate = |c: &'tcx ty::Const<'tcx>| {
637                         if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
638                             self.infcx
639                                 .const_eval_resolve(
640                                     obligation.param_env,
641                                     unevaluated,
642                                     Some(obligation.cause.span),
643                                 )
644                                 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
645                         } else {
646                             Ok(c)
647                         }
648                     };
649
650                     match (evaluate(c1), evaluate(c2)) {
651                         (Ok(c1), Ok(c2)) => {
652                             match self
653                                 .infcx()
654                                 .at(&obligation.cause, obligation.param_env)
655                                 .eq(c1, c2)
656                             {
657                                 Ok(_) => Ok(EvaluatedToOk),
658                                 Err(_) => Ok(EvaluatedToErr),
659                             }
660                         }
661                         (Err(ErrorHandled::Reported(ErrorReported)), _)
662                         | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
663                         (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
664                             span_bug!(
665                                 obligation.cause.span(self.tcx()),
666                                 "ConstEquate: const_eval_resolve returned an unexpected error"
667                             )
668                         }
669                         (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
670                             if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
671                                 Ok(EvaluatedToAmbig)
672                             } else {
673                                 // Two different constants using generic parameters ~> error.
674                                 Ok(EvaluatedToErr)
675                             }
676                         }
677                     }
678                 }
679                 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
680                     bug!("TypeWellFormedFromEnv is only used for chalk")
681                 }
682             }
683         });
684
685         debug!("finished: {:?} from {:?}", result, obligation);
686
687         result
688     }
689
690     fn evaluate_trait_predicate_recursively<'o>(
691         &mut self,
692         previous_stack: TraitObligationStackList<'o, 'tcx>,
693         mut obligation: TraitObligation<'tcx>,
694     ) -> Result<EvaluationResult, OverflowError> {
695         debug!(?obligation, "evaluate_trait_predicate_recursively");
696
697         if !self.intercrate
698             && obligation.is_global(self.tcx())
699             && obligation
700                 .param_env
701                 .caller_bounds()
702                 .iter()
703                 .all(|bound| bound.definitely_needs_subst(self.tcx()))
704         {
705             // If a param env has no global bounds, global obligations do not
706             // depend on its particular value in order to work, so we can clear
707             // out the param env and get better caching.
708             debug!("evaluate_trait_predicate_recursively - in global");
709             obligation.param_env = obligation.param_env.without_caller_bounds();
710         }
711
712         let stack = self.push_stack(previous_stack, &obligation);
713         let fresh_trait_ref = stack.fresh_trait_ref;
714
715         debug!(?fresh_trait_ref);
716
717         if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
718             debug!(?result, "CACHE HIT");
719             return Ok(result);
720         }
721
722         if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
723             debug!(?result, "PROVISIONAL CACHE HIT");
724             stack.update_reached_depth(result.reached_depth);
725             return Ok(result.result);
726         }
727
728         // Check if this is a match for something already on the
729         // stack. If so, we don't want to insert the result into the
730         // main cache (it is cycle dependent) nor the provisional
731         // cache (which is meant for things that have completed but
732         // for a "backedge" -- this result *is* the backedge).
733         if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
734             return Ok(cycle_result);
735         }
736
737         let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
738         let result = result?;
739
740         if !result.must_apply_modulo_regions() {
741             stack.cache().on_failure(stack.dfn);
742         }
743
744         let reached_depth = stack.reached_depth.get();
745         if reached_depth >= stack.depth {
746             debug!(?result, "CACHE MISS");
747             self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
748
749             stack.cache().on_completion(stack.dfn, |fresh_trait_ref, provisional_result| {
750                 self.insert_evaluation_cache(
751                     obligation.param_env,
752                     fresh_trait_ref,
753                     dep_node,
754                     provisional_result.max(result),
755                 );
756             });
757         } else {
758             debug!(?result, "PROVISIONAL");
759             debug!(
760                 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
761                  is a cycle participant (at depth {}, reached depth {})",
762                 fresh_trait_ref, stack.depth, reached_depth,
763             );
764
765             stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
766         }
767
768         Ok(result)
769     }
770
771     /// If there is any previous entry on the stack that precisely
772     /// matches this obligation, then we can assume that the
773     /// obligation is satisfied for now (still all other conditions
774     /// must be met of course). One obvious case this comes up is
775     /// marker traits like `Send`. Think of a linked list:
776     ///
777     ///    struct List<T> { data: T, next: Option<Box<List<T>>> }
778     ///
779     /// `Box<List<T>>` will be `Send` if `T` is `Send` and
780     /// `Option<Box<List<T>>>` is `Send`, and in turn
781     /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
782     /// `Send`.
783     ///
784     /// Note that we do this comparison using the `fresh_trait_ref`
785     /// fields. Because these have all been freshened using
786     /// `self.freshener`, we can be sure that (a) this will not
787     /// affect the inferencer state and (b) that if we see two
788     /// fresh regions with the same index, they refer to the same
789     /// unbound type variable.
790     fn check_evaluation_cycle(
791         &mut self,
792         stack: &TraitObligationStack<'_, 'tcx>,
793     ) -> Option<EvaluationResult> {
794         if let Some(cycle_depth) = stack
795             .iter()
796             .skip(1) // Skip top-most frame.
797             .find(|prev| {
798                 stack.obligation.param_env == prev.obligation.param_env
799                     && stack.fresh_trait_ref == prev.fresh_trait_ref
800             })
801             .map(|stack| stack.depth)
802         {
803             debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
804
805             // If we have a stack like `A B C D E A`, where the top of
806             // the stack is the final `A`, then this will iterate over
807             // `A, E, D, C, B` -- i.e., all the participants apart
808             // from the cycle head. We mark them as participating in a
809             // cycle. This suppresses caching for those nodes. See
810             // `in_cycle` field for more details.
811             stack.update_reached_depth(cycle_depth);
812
813             // Subtle: when checking for a coinductive cycle, we do
814             // not compare using the "freshened trait refs" (which
815             // have erased regions) but rather the fully explicit
816             // trait refs. This is important because it's only a cycle
817             // if the regions match exactly.
818             let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
819             let tcx = self.tcx();
820             let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
821             if self.coinductive_match(cycle) {
822                 debug!("evaluate_stack --> recursive, coinductive");
823                 Some(EvaluatedToOk)
824             } else {
825                 debug!("evaluate_stack --> recursive, inductive");
826                 Some(EvaluatedToRecur)
827             }
828         } else {
829             None
830         }
831     }
832
833     fn evaluate_stack<'o>(
834         &mut self,
835         stack: &TraitObligationStack<'o, 'tcx>,
836     ) -> Result<EvaluationResult, OverflowError> {
837         // In intercrate mode, whenever any of the generics are unbound,
838         // there can always be an impl. Even if there are no impls in
839         // this crate, perhaps the type would be unified with
840         // something from another crate that does provide an impl.
841         //
842         // In intra mode, we must still be conservative. The reason is
843         // that we want to avoid cycles. Imagine an impl like:
844         //
845         //     impl<T:Eq> Eq for Vec<T>
846         //
847         // and a trait reference like `$0 : Eq` where `$0` is an
848         // unbound variable. When we evaluate this trait-reference, we
849         // will unify `$0` with `Vec<$1>` (for some fresh variable
850         // `$1`), on the condition that `$1 : Eq`. We will then wind
851         // up with many candidates (since that are other `Eq` impls
852         // that apply) and try to winnow things down. This results in
853         // a recursive evaluation that `$1 : Eq` -- as you can
854         // imagine, this is just where we started. To avoid that, we
855         // check for unbound variables and return an ambiguous (hence possible)
856         // match if we've seen this trait before.
857         //
858         // This suffices to allow chains like `FnMut` implemented in
859         // terms of `Fn` etc, but we could probably make this more
860         // precise still.
861         let unbound_input_types =
862             stack.fresh_trait_ref.value.skip_binder().substs.types().any(|ty| ty.is_fresh());
863         // This check was an imperfect workaround for a bug in the old
864         // intercrate mode; it should be removed when that goes away.
865         if unbound_input_types && self.intercrate {
866             debug!("evaluate_stack --> unbound argument, intercrate -->  ambiguous",);
867             // Heuristics: show the diagnostics when there are no candidates in crate.
868             if self.intercrate_ambiguity_causes.is_some() {
869                 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
870                 if let Ok(candidate_set) = self.assemble_candidates(stack) {
871                     if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
872                         let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
873                         let self_ty = trait_ref.self_ty();
874                         let cause =
875                             with_no_trimmed_paths(|| IntercrateAmbiguityCause::DownstreamCrate {
876                                 trait_desc: trait_ref.print_only_trait_path().to_string(),
877                                 self_desc: if self_ty.has_concrete_skeleton() {
878                                     Some(self_ty.to_string())
879                                 } else {
880                                     None
881                                 },
882                             });
883
884                         debug!(?cause, "evaluate_stack: pushing cause");
885                         self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
886                     }
887                 }
888             }
889             return Ok(EvaluatedToAmbig);
890         }
891         if unbound_input_types
892             && stack.iter().skip(1).any(|prev| {
893                 stack.obligation.param_env == prev.obligation.param_env
894                     && self.match_fresh_trait_refs(
895                         stack.fresh_trait_ref,
896                         prev.fresh_trait_ref,
897                         prev.obligation.param_env,
898                     )
899             })
900         {
901             debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
902             return Ok(EvaluatedToUnknown);
903         }
904
905         match self.candidate_from_obligation(stack) {
906             Ok(Some(c)) => self.evaluate_candidate(stack, &c),
907             Ok(None) => Ok(EvaluatedToAmbig),
908             Err(Overflow) => Err(OverflowError),
909             Err(..) => Ok(EvaluatedToErr),
910         }
911     }
912
913     /// For defaulted traits, we use a co-inductive strategy to solve, so
914     /// that recursion is ok. This routine returns `true` if the top of the
915     /// stack (`cycle[0]`):
916     ///
917     /// - is a defaulted trait,
918     /// - it also appears in the backtrace at some position `X`,
919     /// - all the predicates at positions `X..` between `X` and the top are
920     ///   also defaulted traits.
921     pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
922     where
923         I: Iterator<Item = ty::Predicate<'tcx>>,
924     {
925         cycle.all(|predicate| self.coinductive_predicate(predicate))
926     }
927
928     fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
929         let result = match predicate.kind().skip_binder() {
930             ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
931             _ => false,
932         };
933         debug!(?predicate, ?result, "coinductive_predicate");
934         result
935     }
936
937     /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
938     /// obligations are met. Returns whether `candidate` remains viable after this further
939     /// scrutiny.
940     #[instrument(
941         level = "debug",
942         skip(self, stack),
943         fields(depth = stack.obligation.recursion_depth)
944     )]
945     fn evaluate_candidate<'o>(
946         &mut self,
947         stack: &TraitObligationStack<'o, 'tcx>,
948         candidate: &SelectionCandidate<'tcx>,
949     ) -> Result<EvaluationResult, OverflowError> {
950         let mut result = self.evaluation_probe(|this| {
951             let candidate = (*candidate).clone();
952             match this.confirm_candidate(stack.obligation, candidate) {
953                 Ok(selection) => {
954                     debug!(?selection);
955                     this.evaluate_predicates_recursively(
956                         stack.list(),
957                         selection.nested_obligations().into_iter(),
958                     )
959                 }
960                 Err(..) => Ok(EvaluatedToErr),
961             }
962         })?;
963
964         // If we erased any lifetimes, then we want to use
965         // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
966         // as your final result. The result will be cached using
967         // the freshened trait predicate as a key, so we need
968         // our result to be correct by *any* choice of original lifetimes,
969         // not just the lifetime choice for this particular (non-erased)
970         // predicate.
971         // See issue #80691
972         if stack.fresh_trait_ref.has_erased_regions() {
973             result = result.max(EvaluatedToOkModuloRegions);
974         }
975
976         debug!(?result);
977         Ok(result)
978     }
979
980     fn check_evaluation_cache(
981         &self,
982         param_env: ty::ParamEnv<'tcx>,
983         trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
984     ) -> Option<EvaluationResult> {
985         let tcx = self.tcx();
986         if self.can_use_global_caches(param_env) {
987             if let Some(res) = tcx.evaluation_cache.get(&param_env.and(trait_ref), tcx) {
988                 return Some(res);
989             }
990         }
991         self.infcx.evaluation_cache.get(&param_env.and(trait_ref), tcx)
992     }
993
994     fn insert_evaluation_cache(
995         &mut self,
996         param_env: ty::ParamEnv<'tcx>,
997         trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
998         dep_node: DepNodeIndex,
999         result: EvaluationResult,
1000     ) {
1001         // Avoid caching results that depend on more than just the trait-ref
1002         // - the stack can create recursion.
1003         if result.is_stack_dependent() {
1004             return;
1005         }
1006
1007         if self.can_use_global_caches(param_env) {
1008             if !trait_ref.needs_infer() {
1009                 debug!(?trait_ref, ?result, "insert_evaluation_cache global");
1010                 // This may overwrite the cache with the same value
1011                 // FIXME: Due to #50507 this overwrites the different values
1012                 // This should be changed to use HashMapExt::insert_same
1013                 // when that is fixed
1014                 self.tcx().evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
1015                 return;
1016             }
1017         }
1018
1019         debug!(?trait_ref, ?result, "insert_evaluation_cache");
1020         self.infcx.evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
1021     }
1022
1023     /// For various reasons, it's possible for a subobligation
1024     /// to have a *lower* recursion_depth than the obligation used to create it.
1025     /// Projection sub-obligations may be returned from the projection cache,
1026     /// which results in obligations with an 'old' `recursion_depth`.
1027     /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1028     /// subobligations without taking in a 'parent' depth, causing the
1029     /// generated subobligations to have a `recursion_depth` of `0`.
1030     ///
1031     /// To ensure that obligation_depth never decreases, we force all subobligations
1032     /// to have at least the depth of the original obligation.
1033     fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1034         &self,
1035         it: I,
1036         min_depth: usize,
1037     ) {
1038         it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1039     }
1040
1041     /// Checks that the recursion limit has not been exceeded.
1042     ///
1043     /// The weird return type of this function allows it to be used with the `try` (`?`)
1044     /// operator within certain functions.
1045     fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1046         &self,
1047         obligation: &Obligation<'tcx, T>,
1048         error_obligation: &Obligation<'tcx, V>,
1049     ) -> Result<(), OverflowError> {
1050         if !self.infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
1051             match self.query_mode {
1052                 TraitQueryMode::Standard => {
1053                     self.infcx().report_overflow_error(error_obligation, true);
1054                 }
1055                 TraitQueryMode::Canonical => {
1056                     return Err(OverflowError);
1057                 }
1058             }
1059         }
1060         Ok(())
1061     }
1062
1063     fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1064     where
1065         OP: FnOnce(&mut Self) -> R,
1066     {
1067         let (result, dep_node) =
1068             self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1069         self.tcx().dep_graph.read_index(dep_node);
1070         (result, dep_node)
1071     }
1072
1073     #[instrument(level = "debug", skip(self))]
1074     fn filter_impls(
1075         &mut self,
1076         candidate: SelectionCandidate<'tcx>,
1077         obligation: &TraitObligation<'tcx>,
1078     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1079         let tcx = self.tcx();
1080         // Respect const trait obligations
1081         if self.is_trait_predicate_const(obligation.predicate.skip_binder()) {
1082             if Some(obligation.predicate.skip_binder().trait_ref.def_id)
1083                 != tcx.lang_items().sized_trait()
1084             // const Sized bounds are skipped
1085             {
1086                 match candidate {
1087                     // const impl
1088                     ImplCandidate(def_id)
1089                         if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1090                     // const param
1091                     ParamCandidate(ty::ConstnessAnd {
1092                         constness: ty::BoundConstness::ConstIfConst,
1093                         ..
1094                     }) => {}
1095                     // auto trait impl
1096                     AutoImplCandidate(..) => {}
1097                     // generator, this will raise error in other places
1098                     // or ignore error with const_async_blocks feature
1099                     GeneratorCandidate => {}
1100                     _ => {
1101                         // reject all other types of candidates
1102                         return Err(Unimplemented);
1103                     }
1104                 }
1105             }
1106         }
1107         // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1108         if let ImplCandidate(def_id) = candidate {
1109             match tcx.impl_polarity(def_id) {
1110                 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1111                     return Err(Unimplemented);
1112                 }
1113                 ty::ImplPolarity::Reservation => {
1114                     if let Some(intercrate_ambiguity_clauses) =
1115                         &mut self.intercrate_ambiguity_causes
1116                     {
1117                         let attrs = tcx.get_attrs(def_id);
1118                         let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1119                         let value = attr.and_then(|a| a.value_str());
1120                         if let Some(value) = value {
1121                             debug!(
1122                                 "filter_impls: \
1123                                  reservation impl ambiguity on {:?}",
1124                                 def_id
1125                             );
1126                             intercrate_ambiguity_clauses.push(
1127                                 IntercrateAmbiguityCause::ReservationImpl {
1128                                     message: value.to_string(),
1129                                 },
1130                             );
1131                         }
1132                     }
1133                     return Ok(None);
1134                 }
1135                 _ => {}
1136             };
1137         }
1138         Ok(Some(candidate))
1139     }
1140
1141     fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1142         debug!("is_knowable(intercrate={:?})", self.intercrate);
1143
1144         if !self.intercrate {
1145             return None;
1146         }
1147
1148         let obligation = &stack.obligation;
1149         let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1150
1151         // Okay to skip binder because of the nature of the
1152         // trait-ref-is-knowable check, which does not care about
1153         // bound regions.
1154         let trait_ref = predicate.skip_binder().trait_ref;
1155
1156         coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1157     }
1158
1159     /// Returns `true` if the global caches can be used.
1160     fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1161         // If there are any inference variables in the `ParamEnv`, then we
1162         // always use a cache local to this particular scope. Otherwise, we
1163         // switch to a global cache.
1164         if param_env.needs_infer() {
1165             return false;
1166         }
1167
1168         // Avoid using the master cache during coherence and just rely
1169         // on the local cache. This effectively disables caching
1170         // during coherence. It is really just a simplification to
1171         // avoid us having to fear that coherence results "pollute"
1172         // the master cache. Since coherence executes pretty quickly,
1173         // it's not worth going to more trouble to increase the
1174         // hit-rate, I don't think.
1175         if self.intercrate {
1176             return false;
1177         }
1178
1179         // Otherwise, we can use the global cache.
1180         true
1181     }
1182
1183     fn check_candidate_cache(
1184         &mut self,
1185         param_env: ty::ParamEnv<'tcx>,
1186         cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1187     ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1188         let tcx = self.tcx();
1189         let pred = &cache_fresh_trait_pred.skip_binder();
1190         let trait_ref = pred.trait_ref;
1191         if self.can_use_global_caches(param_env) {
1192             if let Some(res) = tcx
1193                 .selection_cache
1194                 .get(&param_env.and(trait_ref).with_constness(pred.constness), tcx)
1195             {
1196                 return Some(res);
1197             }
1198         }
1199         self.infcx
1200             .selection_cache
1201             .get(&param_env.and(trait_ref).with_constness(pred.constness), tcx)
1202     }
1203
1204     /// Determines whether can we safely cache the result
1205     /// of selecting an obligation. This is almost always `true`,
1206     /// except when dealing with certain `ParamCandidate`s.
1207     ///
1208     /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1209     /// since it was usually produced directly from a `DefId`. However,
1210     /// certain cases (currently only librustdoc's blanket impl finder),
1211     /// a `ParamEnv` may be explicitly constructed with inference types.
1212     /// When this is the case, we do *not* want to cache the resulting selection
1213     /// candidate. This is due to the fact that it might not always be possible
1214     /// to equate the obligation's trait ref and the candidate's trait ref,
1215     /// if more constraints end up getting added to an inference variable.
1216     ///
1217     /// Because of this, we always want to re-run the full selection
1218     /// process for our obligation the next time we see it, since
1219     /// we might end up picking a different `SelectionCandidate` (or none at all).
1220     fn can_cache_candidate(
1221         &self,
1222         result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1223     ) -> bool {
1224         match result {
1225             Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1226             _ => true,
1227         }
1228     }
1229
1230     fn insert_candidate_cache(
1231         &mut self,
1232         param_env: ty::ParamEnv<'tcx>,
1233         cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1234         dep_node: DepNodeIndex,
1235         candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1236     ) {
1237         let tcx = self.tcx();
1238         let pred = cache_fresh_trait_pred.skip_binder();
1239         let trait_ref = pred.trait_ref;
1240
1241         if !self.can_cache_candidate(&candidate) {
1242             debug!(?trait_ref, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1243             return;
1244         }
1245
1246         if self.can_use_global_caches(param_env) {
1247             if let Err(Overflow) = candidate {
1248                 // Don't cache overflow globally; we only produce this in certain modes.
1249             } else if !trait_ref.needs_infer() {
1250                 if !candidate.needs_infer() {
1251                     debug!(?trait_ref, ?candidate, "insert_candidate_cache global");
1252                     // This may overwrite the cache with the same value.
1253                     tcx.selection_cache.insert(
1254                         param_env.and(trait_ref).with_constness(pred.constness),
1255                         dep_node,
1256                         candidate,
1257                     );
1258                     return;
1259                 }
1260             }
1261         }
1262
1263         debug!(?trait_ref, ?candidate, "insert_candidate_cache local");
1264         self.infcx.selection_cache.insert(
1265             param_env.and(trait_ref).with_constness(pred.constness),
1266             dep_node,
1267             candidate,
1268         );
1269     }
1270
1271     /// Matches a predicate against the bounds of its self type.
1272     ///
1273     /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1274     /// a projection, look at the bounds of `T::Bar`, see if we can find a
1275     /// `Baz` bound. We return indexes into the list returned by
1276     /// `tcx.item_bounds` for any applicable bounds.
1277     fn match_projection_obligation_against_definition_bounds(
1278         &mut self,
1279         obligation: &TraitObligation<'tcx>,
1280     ) -> smallvec::SmallVec<[usize; 2]> {
1281         let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1282         let placeholder_trait_predicate =
1283             self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1284         debug!(
1285             ?placeholder_trait_predicate,
1286             "match_projection_obligation_against_definition_bounds"
1287         );
1288
1289         let tcx = self.infcx.tcx;
1290         let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1291             ty::Projection(ref data) => (data.item_def_id, data.substs),
1292             ty::Opaque(def_id, substs) => (def_id, substs),
1293             _ => {
1294                 span_bug!(
1295                     obligation.cause.span,
1296                     "match_projection_obligation_against_definition_bounds() called \
1297                      but self-ty is not a projection: {:?}",
1298                     placeholder_trait_predicate.trait_ref.self_ty()
1299                 );
1300             }
1301         };
1302         let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1303
1304         // The bounds returned by `item_bounds` may contain duplicates after
1305         // normalization, so try to deduplicate when possible to avoid
1306         // unnecessary ambiguity.
1307         let mut distinct_normalized_bounds = FxHashSet::default();
1308
1309         let matching_bounds = bounds
1310             .iter()
1311             .enumerate()
1312             .filter_map(|(idx, bound)| {
1313                 let bound_predicate = bound.kind();
1314                 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1315                     let bound = bound_predicate.rebind(pred.trait_ref);
1316                     if self.infcx.probe(|_| {
1317                         match self.match_normalize_trait_ref(
1318                             obligation,
1319                             bound,
1320                             placeholder_trait_predicate.trait_ref,
1321                         ) {
1322                             Ok(None) => true,
1323                             Ok(Some(normalized_trait))
1324                                 if distinct_normalized_bounds.insert(normalized_trait) =>
1325                             {
1326                                 true
1327                             }
1328                             _ => false,
1329                         }
1330                     }) {
1331                         return Some(idx);
1332                     }
1333                 }
1334                 None
1335             })
1336             .collect();
1337
1338         debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
1339         matching_bounds
1340     }
1341
1342     /// Equates the trait in `obligation` with trait bound. If the two traits
1343     /// can be equated and the normalized trait bound doesn't contain inference
1344     /// variables or placeholders, the normalized bound is returned.
1345     fn match_normalize_trait_ref(
1346         &mut self,
1347         obligation: &TraitObligation<'tcx>,
1348         trait_bound: ty::PolyTraitRef<'tcx>,
1349         placeholder_trait_ref: ty::TraitRef<'tcx>,
1350     ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1351         debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1352         if placeholder_trait_ref.def_id != trait_bound.def_id() {
1353             // Avoid unnecessary normalization
1354             return Err(());
1355         }
1356
1357         let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1358             project::normalize_with_depth(
1359                 self,
1360                 obligation.param_env,
1361                 obligation.cause.clone(),
1362                 obligation.recursion_depth + 1,
1363                 trait_bound,
1364             )
1365         });
1366         self.infcx
1367             .at(&obligation.cause, obligation.param_env)
1368             .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1369             .map(|InferOk { obligations: _, value: () }| {
1370                 // This method is called within a probe, so we can't have
1371                 // inference variables and placeholders escape.
1372                 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1373                     Some(trait_bound)
1374                 } else {
1375                     None
1376                 }
1377             })
1378             .map_err(|_| ())
1379     }
1380
1381     fn evaluate_where_clause<'o>(
1382         &mut self,
1383         stack: &TraitObligationStack<'o, 'tcx>,
1384         where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1385     ) -> Result<EvaluationResult, OverflowError> {
1386         self.evaluation_probe(|this| {
1387             match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1388                 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1389                 Err(()) => Ok(EvaluatedToErr),
1390             }
1391         })
1392     }
1393
1394     pub(super) fn match_projection_projections(
1395         &mut self,
1396         obligation: &ProjectionTyObligation<'tcx>,
1397         env_predicate: PolyProjectionPredicate<'tcx>,
1398         potentially_unnormalized_candidates: bool,
1399     ) -> bool {
1400         let mut nested_obligations = Vec::new();
1401         let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1402             obligation.cause.span,
1403             LateBoundRegionConversionTime::HigherRankedType,
1404             env_predicate,
1405         );
1406         let infer_projection = if potentially_unnormalized_candidates {
1407             ensure_sufficient_stack(|| {
1408                 project::normalize_with_depth_to(
1409                     self,
1410                     obligation.param_env,
1411                     obligation.cause.clone(),
1412                     obligation.recursion_depth + 1,
1413                     infer_predicate.projection_ty,
1414                     &mut nested_obligations,
1415                 )
1416             })
1417         } else {
1418             infer_predicate.projection_ty
1419         };
1420
1421         self.infcx
1422             .at(&obligation.cause, obligation.param_env)
1423             .sup(obligation.predicate, infer_projection)
1424             .map_or(false, |InferOk { obligations, value: () }| {
1425                 self.evaluate_predicates_recursively(
1426                     TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1427                     nested_obligations.into_iter().chain(obligations),
1428                 )
1429                 .map_or(false, |res| res.may_apply())
1430             })
1431     }
1432
1433     ///////////////////////////////////////////////////////////////////////////
1434     // WINNOW
1435     //
1436     // Winnowing is the process of attempting to resolve ambiguity by
1437     // probing further. During the winnowing process, we unify all
1438     // type variables and then we also attempt to evaluate recursive
1439     // bounds to see if they are satisfied.
1440
1441     /// Returns `true` if `victim` should be dropped in favor of
1442     /// `other`. Generally speaking we will drop duplicate
1443     /// candidates and prefer where-clause candidates.
1444     ///
1445     /// See the comment for "SelectionCandidate" for more details.
1446     fn candidate_should_be_dropped_in_favor_of(
1447         &mut self,
1448         victim: &EvaluatedCandidate<'tcx>,
1449         other: &EvaluatedCandidate<'tcx>,
1450         needs_infer: bool,
1451     ) -> bool {
1452         if victim.candidate == other.candidate {
1453             return true;
1454         }
1455
1456         // Check if a bound would previously have been removed when normalizing
1457         // the param_env so that it can be given the lowest priority. See
1458         // #50825 for the motivation for this.
1459         let is_global =
1460             |cand: &ty::PolyTraitRef<'_>| cand.is_known_global() && !cand.has_late_bound_regions();
1461
1462         // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1463         // and `DiscriminantKindCandidate` to anything else.
1464         //
1465         // This is a fix for #53123 and prevents winnowing from accidentally extending the
1466         // lifetime of a variable.
1467         match (&other.candidate, &victim.candidate) {
1468             (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1469                 bug!(
1470                     "default implementations shouldn't be recorded \
1471                     when there are other valid candidates"
1472                 );
1473             }
1474
1475             // (*)
1476             (
1477                 BuiltinCandidate { has_nested: false }
1478                 | DiscriminantKindCandidate
1479                 | PointeeCandidate,
1480                 _,
1481             ) => true,
1482             (
1483                 _,
1484                 BuiltinCandidate { has_nested: false }
1485                 | DiscriminantKindCandidate
1486                 | PointeeCandidate,
1487             ) => false,
1488
1489             (ParamCandidate(other), ParamCandidate(victim)) => {
1490                 let same_except_bound_vars = other.value.skip_binder()
1491                     == victim.value.skip_binder()
1492                     && other.constness == victim.constness
1493                     && !other.value.skip_binder().has_escaping_bound_vars();
1494                 if same_except_bound_vars {
1495                     // See issue #84398. In short, we can generate multiple ParamCandidates which are
1496                     // the same except for unused bound vars. Just pick the one with the fewest bound vars
1497                     // or the current one if tied (they should both evaluate to the same answer). This is
1498                     // probably best characterized as a "hack", since we might prefer to just do our
1499                     // best to *not* create essentially duplicate candidates in the first place.
1500                     other.value.bound_vars().len() <= victim.value.bound_vars().len()
1501                 } else if other.value == victim.value
1502                     && victim.constness == ty::BoundConstness::NotConst
1503                 {
1504                     // Drop otherwise equivalent non-const candidates in favor of const candidates.
1505                     true
1506                 } else {
1507                     false
1508                 }
1509             }
1510
1511             // Global bounds from the where clause should be ignored
1512             // here (see issue #50825). Otherwise, we have a where
1513             // clause so don't go around looking for impls.
1514             // Arbitrarily give param candidates priority
1515             // over projection and object candidates.
1516             (
1517                 ParamCandidate(ref cand),
1518                 ImplCandidate(..)
1519                 | ClosureCandidate
1520                 | GeneratorCandidate
1521                 | FnPointerCandidate
1522                 | BuiltinObjectCandidate
1523                 | BuiltinUnsizeCandidate
1524                 | TraitUpcastingUnsizeCandidate(_)
1525                 | BuiltinCandidate { .. }
1526                 | TraitAliasCandidate(..)
1527                 | ObjectCandidate(_)
1528                 | ProjectionCandidate(_),
1529             ) => !is_global(&cand.value),
1530             (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1531                 // Prefer these to a global where-clause bound
1532                 // (see issue #50825).
1533                 is_global(&cand.value)
1534             }
1535             (
1536                 ImplCandidate(_)
1537                 | ClosureCandidate
1538                 | GeneratorCandidate
1539                 | FnPointerCandidate
1540                 | BuiltinObjectCandidate
1541                 | BuiltinUnsizeCandidate
1542                 | TraitUpcastingUnsizeCandidate(_)
1543                 | BuiltinCandidate { has_nested: true }
1544                 | TraitAliasCandidate(..),
1545                 ParamCandidate(ref cand),
1546             ) => {
1547                 // Prefer these to a global where-clause bound
1548                 // (see issue #50825).
1549                 is_global(&cand.value) && other.evaluation.must_apply_modulo_regions()
1550             }
1551
1552             (ProjectionCandidate(i), ProjectionCandidate(j))
1553             | (ObjectCandidate(i), ObjectCandidate(j)) => {
1554                 // Arbitrarily pick the lower numbered candidate for backwards
1555                 // compatibility reasons. Don't let this affect inference.
1556                 i < j && !needs_infer
1557             }
1558             (ObjectCandidate(_), ProjectionCandidate(_))
1559             | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1560                 bug!("Have both object and projection candidate")
1561             }
1562
1563             // Arbitrarily give projection and object candidates priority.
1564             (
1565                 ObjectCandidate(_) | ProjectionCandidate(_),
1566                 ImplCandidate(..)
1567                 | ClosureCandidate
1568                 | GeneratorCandidate
1569                 | FnPointerCandidate
1570                 | BuiltinObjectCandidate
1571                 | BuiltinUnsizeCandidate
1572                 | TraitUpcastingUnsizeCandidate(_)
1573                 | BuiltinCandidate { .. }
1574                 | TraitAliasCandidate(..),
1575             ) => true,
1576
1577             (
1578                 ImplCandidate(..)
1579                 | ClosureCandidate
1580                 | GeneratorCandidate
1581                 | FnPointerCandidate
1582                 | BuiltinObjectCandidate
1583                 | BuiltinUnsizeCandidate
1584                 | TraitUpcastingUnsizeCandidate(_)
1585                 | BuiltinCandidate { .. }
1586                 | TraitAliasCandidate(..),
1587                 ObjectCandidate(_) | ProjectionCandidate(_),
1588             ) => false,
1589
1590             (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1591                 // See if we can toss out `victim` based on specialization.
1592                 // This requires us to know *for sure* that the `other` impl applies
1593                 // i.e., `EvaluatedToOk`.
1594                 //
1595                 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1596                 // to me but is required for `std` to compile, so I didn't change it
1597                 // for now.
1598                 let tcx = self.tcx();
1599                 if other.evaluation.must_apply_modulo_regions() {
1600                     if tcx.specializes((other_def, victim_def)) {
1601                         return true;
1602                     }
1603                 }
1604
1605                 if other.evaluation.must_apply_considering_regions() {
1606                     match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1607                         Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1608                             // Subtle: If the predicate we are evaluating has inference
1609                             // variables, do *not* allow discarding candidates due to
1610                             // marker trait impls.
1611                             //
1612                             // Without this restriction, we could end up accidentally
1613                             // constrainting inference variables based on an arbitrarily
1614                             // chosen trait impl.
1615                             //
1616                             // Imagine we have the following code:
1617                             //
1618                             // ```rust
1619                             // #[marker] trait MyTrait {}
1620                             // impl MyTrait for u8 {}
1621                             // impl MyTrait for bool {}
1622                             // ```
1623                             //
1624                             // And we are evaluating the predicate `<_#0t as MyTrait>`.
1625                             //
1626                             // During selection, we will end up with one candidate for each
1627                             // impl of `MyTrait`. If we were to discard one impl in favor
1628                             // of the other, we would be left with one candidate, causing
1629                             // us to "successfully" select the predicate, unifying
1630                             // _#0t with (for example) `u8`.
1631                             //
1632                             // However, we have no reason to believe that this unification
1633                             // is correct - we've essentially just picked an arbitrary
1634                             // *possibility* for _#0t, and required that this be the *only*
1635                             // possibility.
1636                             //
1637                             // Eventually, we will either:
1638                             // 1) Unify all inference variables in the predicate through
1639                             // some other means (e.g. type-checking of a function). We will
1640                             // then be in a position to drop marker trait candidates
1641                             // without constraining inference variables (since there are
1642                             // none left to constrin)
1643                             // 2) Be left with some unconstrained inference variables. We
1644                             // will then correctly report an inference error, since the
1645                             // existence of multiple marker trait impls tells us nothing
1646                             // about which one should actually apply.
1647                             !needs_infer
1648                         }
1649                         Some(_) => true,
1650                         None => false,
1651                     }
1652                 } else {
1653                     false
1654                 }
1655             }
1656
1657             // Everything else is ambiguous
1658             (
1659                 ImplCandidate(_)
1660                 | ClosureCandidate
1661                 | GeneratorCandidate
1662                 | FnPointerCandidate
1663                 | BuiltinObjectCandidate
1664                 | BuiltinUnsizeCandidate
1665                 | TraitUpcastingUnsizeCandidate(_)
1666                 | BuiltinCandidate { has_nested: true }
1667                 | TraitAliasCandidate(..),
1668                 ImplCandidate(_)
1669                 | ClosureCandidate
1670                 | GeneratorCandidate
1671                 | FnPointerCandidate
1672                 | BuiltinObjectCandidate
1673                 | BuiltinUnsizeCandidate
1674                 | TraitUpcastingUnsizeCandidate(_)
1675                 | BuiltinCandidate { has_nested: true }
1676                 | TraitAliasCandidate(..),
1677             ) => false,
1678         }
1679     }
1680
1681     fn sized_conditions(
1682         &mut self,
1683         obligation: &TraitObligation<'tcx>,
1684     ) -> BuiltinImplConditions<'tcx> {
1685         use self::BuiltinImplConditions::{Ambiguous, None, Where};
1686
1687         // NOTE: binder moved to (*)
1688         let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1689
1690         match self_ty.kind() {
1691             ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1692             | ty::Uint(_)
1693             | ty::Int(_)
1694             | ty::Bool
1695             | ty::Float(_)
1696             | ty::FnDef(..)
1697             | ty::FnPtr(_)
1698             | ty::RawPtr(..)
1699             | ty::Char
1700             | ty::Ref(..)
1701             | ty::Generator(..)
1702             | ty::GeneratorWitness(..)
1703             | ty::Array(..)
1704             | ty::Closure(..)
1705             | ty::Never
1706             | ty::Error(_) => {
1707                 // safe for everything
1708                 Where(ty::Binder::dummy(Vec::new()))
1709             }
1710
1711             ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1712
1713             ty::Tuple(tys) => Where(
1714                 obligation
1715                     .predicate
1716                     .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1717             ),
1718
1719             ty::Adt(def, substs) => {
1720                 let sized_crit = def.sized_constraint(self.tcx());
1721                 // (*) binder moved here
1722                 Where(
1723                     obligation.predicate.rebind({
1724                         sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1725                     }),
1726                 )
1727             }
1728
1729             ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1730             ty::Infer(ty::TyVar(_)) => Ambiguous,
1731
1732             ty::Placeholder(..)
1733             | ty::Bound(..)
1734             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1735                 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1736             }
1737         }
1738     }
1739
1740     fn copy_clone_conditions(
1741         &mut self,
1742         obligation: &TraitObligation<'tcx>,
1743     ) -> BuiltinImplConditions<'tcx> {
1744         // NOTE: binder moved to (*)
1745         let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1746
1747         use self::BuiltinImplConditions::{Ambiguous, None, Where};
1748
1749         match *self_ty.kind() {
1750             ty::Infer(ty::IntVar(_))
1751             | ty::Infer(ty::FloatVar(_))
1752             | ty::FnDef(..)
1753             | ty::FnPtr(_)
1754             | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1755
1756             ty::Uint(_)
1757             | ty::Int(_)
1758             | ty::Bool
1759             | ty::Float(_)
1760             | ty::Char
1761             | ty::RawPtr(..)
1762             | ty::Never
1763             | ty::Ref(_, _, hir::Mutability::Not) => {
1764                 // Implementations provided in libcore
1765                 None
1766             }
1767
1768             ty::Dynamic(..)
1769             | ty::Str
1770             | ty::Slice(..)
1771             | ty::Generator(..)
1772             | ty::GeneratorWitness(..)
1773             | ty::Foreign(..)
1774             | ty::Ref(_, _, hir::Mutability::Mut) => None,
1775
1776             ty::Array(element_ty, _) => {
1777                 // (*) binder moved here
1778                 Where(obligation.predicate.rebind(vec![element_ty]))
1779             }
1780
1781             ty::Tuple(tys) => {
1782                 // (*) binder moved here
1783                 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
1784             }
1785
1786             ty::Closure(_, substs) => {
1787                 // (*) binder moved here
1788                 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1789                 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1790                     // Not yet resolved.
1791                     Ambiguous
1792                 } else {
1793                     Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1794                 }
1795             }
1796
1797             ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1798                 // Fallback to whatever user-defined impls exist in this case.
1799                 None
1800             }
1801
1802             ty::Infer(ty::TyVar(_)) => {
1803                 // Unbound type variable. Might or might not have
1804                 // applicable impls and so forth, depending on what
1805                 // those type variables wind up being bound to.
1806                 Ambiguous
1807             }
1808
1809             ty::Placeholder(..)
1810             | ty::Bound(..)
1811             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1812                 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1813             }
1814         }
1815     }
1816
1817     /// For default impls, we need to break apart a type into its
1818     /// "constituent types" -- meaning, the types that it contains.
1819     ///
1820     /// Here are some (simple) examples:
1821     ///
1822     /// ```
1823     /// (i32, u32) -> [i32, u32]
1824     /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1825     /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1826     /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1827     /// ```
1828     fn constituent_types_for_ty(
1829         &self,
1830         t: ty::Binder<'tcx, Ty<'tcx>>,
1831     ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1832         match *t.skip_binder().kind() {
1833             ty::Uint(_)
1834             | ty::Int(_)
1835             | ty::Bool
1836             | ty::Float(_)
1837             | ty::FnDef(..)
1838             | ty::FnPtr(_)
1839             | ty::Str
1840             | ty::Error(_)
1841             | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1842             | ty::Never
1843             | ty::Char => ty::Binder::dummy(Vec::new()),
1844
1845             ty::Placeholder(..)
1846             | ty::Dynamic(..)
1847             | ty::Param(..)
1848             | ty::Foreign(..)
1849             | ty::Projection(..)
1850             | ty::Bound(..)
1851             | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1852                 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1853             }
1854
1855             ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1856                 t.rebind(vec![element_ty])
1857             }
1858
1859             ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1860
1861             ty::Tuple(ref tys) => {
1862                 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1863                 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
1864             }
1865
1866             ty::Closure(_, ref substs) => {
1867                 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1868                 t.rebind(vec![ty])
1869             }
1870
1871             ty::Generator(_, ref substs, _) => {
1872                 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1873                 let witness = substs.as_generator().witness();
1874                 t.rebind(vec![ty].into_iter().chain(iter::once(witness)).collect())
1875             }
1876
1877             ty::GeneratorWitness(types) => {
1878                 debug_assert!(!types.has_escaping_bound_vars());
1879                 types.map_bound(|types| types.to_vec())
1880             }
1881
1882             // For `PhantomData<T>`, we pass `T`.
1883             ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1884
1885             ty::Adt(def, substs) => {
1886                 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
1887             }
1888
1889             ty::Opaque(def_id, substs) => {
1890                 // We can resolve the `impl Trait` to its concrete type,
1891                 // which enforces a DAG between the functions requiring
1892                 // the auto trait bounds in question.
1893                 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
1894             }
1895         }
1896     }
1897
1898     fn collect_predicates_for_types(
1899         &mut self,
1900         param_env: ty::ParamEnv<'tcx>,
1901         cause: ObligationCause<'tcx>,
1902         recursion_depth: usize,
1903         trait_def_id: DefId,
1904         types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
1905     ) -> Vec<PredicateObligation<'tcx>> {
1906         // Because the types were potentially derived from
1907         // higher-ranked obligations they may reference late-bound
1908         // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1909         // yield a type like `for<'a> &'a i32`. In general, we
1910         // maintain the invariant that we never manipulate bound
1911         // regions, so we have to process these bound regions somehow.
1912         //
1913         // The strategy is to:
1914         //
1915         // 1. Instantiate those regions to placeholder regions (e.g.,
1916         //    `for<'a> &'a i32` becomes `&0 i32`.
1917         // 2. Produce something like `&'0 i32 : Copy`
1918         // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1919
1920         types
1921             .as_ref()
1922             .skip_binder() // binder moved -\
1923             .iter()
1924             .flat_map(|ty| {
1925                 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/
1926
1927                 self.infcx.commit_unconditionally(|_| {
1928                     let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
1929                     let Normalized { value: normalized_ty, mut obligations } =
1930                         ensure_sufficient_stack(|| {
1931                             project::normalize_with_depth(
1932                                 self,
1933                                 param_env,
1934                                 cause.clone(),
1935                                 recursion_depth,
1936                                 placeholder_ty,
1937                             )
1938                         });
1939                     let placeholder_obligation = predicate_for_trait_def(
1940                         self.tcx(),
1941                         param_env,
1942                         cause.clone(),
1943                         trait_def_id,
1944                         recursion_depth,
1945                         normalized_ty,
1946                         &[],
1947                     );
1948                     obligations.push(placeholder_obligation);
1949                     obligations
1950                 })
1951             })
1952             .collect()
1953     }
1954
1955     ///////////////////////////////////////////////////////////////////////////
1956     // Matching
1957     //
1958     // Matching is a common path used for both evaluation and
1959     // confirmation.  It basically unifies types that appear in impls
1960     // and traits. This does affect the surrounding environment;
1961     // therefore, when used during evaluation, match routines must be
1962     // run inside of a `probe()` so that their side-effects are
1963     // contained.
1964
1965     fn rematch_impl(
1966         &mut self,
1967         impl_def_id: DefId,
1968         obligation: &TraitObligation<'tcx>,
1969     ) -> Normalized<'tcx, SubstsRef<'tcx>> {
1970         match self.match_impl(impl_def_id, obligation) {
1971             Ok(substs) => substs,
1972             Err(()) => {
1973                 bug!(
1974                     "Impl {:?} was matchable against {:?} but now is not",
1975                     impl_def_id,
1976                     obligation
1977                 );
1978             }
1979         }
1980     }
1981
1982     #[tracing::instrument(level = "debug", skip(self))]
1983     fn match_impl(
1984         &mut self,
1985         impl_def_id: DefId,
1986         obligation: &TraitObligation<'tcx>,
1987     ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
1988         let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
1989
1990         // Before we create the substitutions and everything, first
1991         // consider a "quick reject". This avoids creating more types
1992         // and so forth that we need to.
1993         if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
1994             return Err(());
1995         }
1996
1997         let placeholder_obligation =
1998             self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
1999         let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2000
2001         let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2002
2003         let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2004
2005         debug!(?impl_trait_ref);
2006
2007         let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2008             ensure_sufficient_stack(|| {
2009                 project::normalize_with_depth(
2010                     self,
2011                     obligation.param_env,
2012                     obligation.cause.clone(),
2013                     obligation.recursion_depth + 1,
2014                     impl_trait_ref,
2015                 )
2016             });
2017
2018         debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2019
2020         let cause = ObligationCause::new(
2021             obligation.cause.span,
2022             obligation.cause.body_id,
2023             ObligationCauseCode::MatchImpl(Lrc::new(obligation.cause.code.clone()), impl_def_id),
2024         );
2025
2026         let InferOk { obligations, .. } = self
2027             .infcx
2028             .at(&cause, obligation.param_env)
2029             .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2030             .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2031         nested_obligations.extend(obligations);
2032
2033         if !self.intercrate
2034             && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2035         {
2036             debug!("match_impl: reservation impls only apply in intercrate mode");
2037             return Err(());
2038         }
2039
2040         debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2041         Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2042     }
2043
2044     fn fast_reject_trait_refs(
2045         &mut self,
2046         obligation: &TraitObligation<'_>,
2047         impl_trait_ref: &ty::TraitRef<'_>,
2048     ) -> bool {
2049         // We can avoid creating type variables and doing the full
2050         // substitution if we find that any of the input types, when
2051         // simplified, do not match.
2052
2053         iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2054             |(obligation_arg, impl_arg)| {
2055                 match (obligation_arg.unpack(), impl_arg.unpack()) {
2056                     (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2057                         let simplified_obligation_ty =
2058                             fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2059                         let simplified_impl_ty =
2060                             fast_reject::simplify_type(self.tcx(), impl_ty, false);
2061
2062                         simplified_obligation_ty.is_some()
2063                             && simplified_impl_ty.is_some()
2064                             && simplified_obligation_ty != simplified_impl_ty
2065                     }
2066                     (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2067                         // Lifetimes can never cause a rejection.
2068                         false
2069                     }
2070                     (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2071                         // Conservatively ignore consts (i.e. assume they might
2072                         // unify later) until we have `fast_reject` support for
2073                         // them (if we'll ever need it, even).
2074                         false
2075                     }
2076                     _ => unreachable!(),
2077                 }
2078             },
2079         )
2080     }
2081
2082     /// Normalize `where_clause_trait_ref` and try to match it against
2083     /// `obligation`. If successful, return any predicates that
2084     /// result from the normalization.
2085     fn match_where_clause_trait_ref(
2086         &mut self,
2087         obligation: &TraitObligation<'tcx>,
2088         where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2089     ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2090         self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2091     }
2092
2093     /// Returns `Ok` if `poly_trait_ref` being true implies that the
2094     /// obligation is satisfied.
2095     fn match_poly_trait_ref(
2096         &mut self,
2097         obligation: &TraitObligation<'tcx>,
2098         poly_trait_ref: ty::PolyTraitRef<'tcx>,
2099     ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2100         debug!(?obligation, ?poly_trait_ref, "match_poly_trait_ref");
2101
2102         self.infcx
2103             .at(&obligation.cause, obligation.param_env)
2104             .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2105             .map(|InferOk { obligations, .. }| obligations)
2106             .map_err(|_| ())
2107     }
2108
2109     ///////////////////////////////////////////////////////////////////////////
2110     // Miscellany
2111
2112     fn match_fresh_trait_refs(
2113         &self,
2114         previous: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2115         current: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2116         param_env: ty::ParamEnv<'tcx>,
2117     ) -> bool {
2118         let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2119         matcher.relate(previous, current).is_ok()
2120     }
2121
2122     fn push_stack<'o>(
2123         &mut self,
2124         previous_stack: TraitObligationStackList<'o, 'tcx>,
2125         obligation: &'o TraitObligation<'tcx>,
2126     ) -> TraitObligationStack<'o, 'tcx> {
2127         let fresh_trait_ref = obligation
2128             .predicate
2129             .to_poly_trait_ref()
2130             .fold_with(&mut self.freshener)
2131             .with_constness(obligation.predicate.skip_binder().constness);
2132
2133         let dfn = previous_stack.cache.next_dfn();
2134         let depth = previous_stack.depth() + 1;
2135         TraitObligationStack {
2136             obligation,
2137             fresh_trait_ref,
2138             reached_depth: Cell::new(depth),
2139             previous: previous_stack,
2140             dfn,
2141             depth,
2142         }
2143     }
2144
2145     fn closure_trait_ref_unnormalized(
2146         &mut self,
2147         obligation: &TraitObligation<'tcx>,
2148         substs: SubstsRef<'tcx>,
2149     ) -> ty::PolyTraitRef<'tcx> {
2150         debug!(?obligation, ?substs, "closure_trait_ref_unnormalized");
2151         let closure_sig = substs.as_closure().sig();
2152
2153         debug!(?closure_sig);
2154
2155         // (1) Feels icky to skip the binder here, but OTOH we know
2156         // that the self-type is an unboxed closure type and hence is
2157         // in fact unparameterized (or at least does not reference any
2158         // regions bound in the obligation). Still probably some
2159         // refactoring could make this nicer.
2160         closure_trait_ref_and_return_type(
2161             self.tcx(),
2162             obligation.predicate.def_id(),
2163             obligation.predicate.skip_binder().self_ty(), // (1)
2164             closure_sig,
2165             util::TupleArgumentsFlag::No,
2166         )
2167         .map_bound(|(trait_ref, _)| trait_ref)
2168     }
2169
2170     fn generator_trait_ref_unnormalized(
2171         &mut self,
2172         obligation: &TraitObligation<'tcx>,
2173         substs: SubstsRef<'tcx>,
2174     ) -> ty::PolyTraitRef<'tcx> {
2175         let gen_sig = substs.as_generator().poly_sig();
2176
2177         // (1) Feels icky to skip the binder here, but OTOH we know
2178         // that the self-type is an generator type and hence is
2179         // in fact unparameterized (or at least does not reference any
2180         // regions bound in the obligation). Still probably some
2181         // refactoring could make this nicer.
2182
2183         super::util::generator_trait_ref_and_outputs(
2184             self.tcx(),
2185             obligation.predicate.def_id(),
2186             obligation.predicate.skip_binder().self_ty(), // (1)
2187             gen_sig,
2188         )
2189         .map_bound(|(trait_ref, ..)| trait_ref)
2190     }
2191
2192     /// Returns the obligations that are implied by instantiating an
2193     /// impl or trait. The obligations are substituted and fully
2194     /// normalized. This is used when confirming an impl or default
2195     /// impl.
2196     #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2197     fn impl_or_trait_obligations(
2198         &mut self,
2199         cause: ObligationCause<'tcx>,
2200         recursion_depth: usize,
2201         param_env: ty::ParamEnv<'tcx>,
2202         def_id: DefId,           // of impl or trait
2203         substs: SubstsRef<'tcx>, // for impl or trait
2204     ) -> Vec<PredicateObligation<'tcx>> {
2205         let tcx = self.tcx();
2206
2207         // To allow for one-pass evaluation of the nested obligation,
2208         // each predicate must be preceded by the obligations required
2209         // to normalize it.
2210         // for example, if we have:
2211         //    impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2212         // the impl will have the following predicates:
2213         //    <V as Iterator>::Item = U,
2214         //    U: Iterator, U: Sized,
2215         //    V: Iterator, V: Sized,
2216         //    <U as Iterator>::Item: Copy
2217         // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2218         // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2219         // `$1: Copy`, so we must ensure the obligations are emitted in
2220         // that order.
2221         let predicates = tcx.predicates_of(def_id);
2222         debug!(?predicates);
2223         assert_eq!(predicates.parent, None);
2224         let mut obligations = Vec::with_capacity(predicates.predicates.len());
2225         for (predicate, _) in predicates.predicates {
2226             debug!(?predicate);
2227             let predicate = normalize_with_depth_to(
2228                 self,
2229                 param_env,
2230                 cause.clone(),
2231                 recursion_depth,
2232                 predicate.subst(tcx, substs),
2233                 &mut obligations,
2234             );
2235             obligations.push(Obligation {
2236                 cause: cause.clone(),
2237                 recursion_depth,
2238                 param_env,
2239                 predicate,
2240             });
2241         }
2242
2243         // We are performing deduplication here to avoid exponential blowups
2244         // (#38528) from happening, but the real cause of the duplication is
2245         // unknown. What we know is that the deduplication avoids exponential
2246         // amount of predicates being propagated when processing deeply nested
2247         // types.
2248         //
2249         // This code is hot enough that it's worth avoiding the allocation
2250         // required for the FxHashSet when possible. Special-casing lengths 0,
2251         // 1 and 2 covers roughly 75-80% of the cases.
2252         if obligations.len() <= 1 {
2253             // No possibility of duplicates.
2254         } else if obligations.len() == 2 {
2255             // Only two elements. Drop the second if they are equal.
2256             if obligations[0] == obligations[1] {
2257                 obligations.truncate(1);
2258             }
2259         } else {
2260             // Three or more elements. Use a general deduplication process.
2261             let mut seen = FxHashSet::default();
2262             obligations.retain(|i| seen.insert(i.clone()));
2263         }
2264
2265         obligations
2266     }
2267 }
2268
2269 trait TraitObligationExt<'tcx> {
2270     fn derived_cause(
2271         &self,
2272         variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2273     ) -> ObligationCause<'tcx>;
2274 }
2275
2276 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2277     fn derived_cause(
2278         &self,
2279         variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2280     ) -> ObligationCause<'tcx> {
2281         /*!
2282          * Creates a cause for obligations that are derived from
2283          * `obligation` by a recursive search (e.g., for a builtin
2284          * bound, or eventually a `auto trait Foo`). If `obligation`
2285          * is itself a derived obligation, this is just a clone, but
2286          * otherwise we create a "derived obligation" cause so as to
2287          * keep track of the original root obligation for error
2288          * reporting.
2289          */
2290
2291         let obligation = self;
2292
2293         // NOTE(flaper87): As of now, it keeps track of the whole error
2294         // chain. Ideally, we should have a way to configure this either
2295         // by using -Z verbose or just a CLI argument.
2296         let derived_cause = DerivedObligationCause {
2297             parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2298             parent_code: Lrc::new(obligation.cause.code.clone()),
2299         };
2300         let derived_code = variant(derived_cause);
2301         ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2302     }
2303 }
2304
2305 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2306     fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2307         TraitObligationStackList::with(self)
2308     }
2309
2310     fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2311         self.previous.cache
2312     }
2313
2314     fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2315         self.list()
2316     }
2317
2318     /// Indicates that attempting to evaluate this stack entry
2319     /// required accessing something from the stack at depth `reached_depth`.
2320     fn update_reached_depth(&self, reached_depth: usize) {
2321         assert!(
2322             self.depth >= reached_depth,
2323             "invoked `update_reached_depth` with something under this stack: \
2324              self.depth={} reached_depth={}",
2325             self.depth,
2326             reached_depth,
2327         );
2328         debug!(reached_depth, "update_reached_depth");
2329         let mut p = self;
2330         while reached_depth < p.depth {
2331             debug!(?p.fresh_trait_ref, "update_reached_depth: marking as cycle participant");
2332             p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2333             p = p.previous.head.unwrap();
2334         }
2335     }
2336 }
2337
2338 /// The "provisional evaluation cache" is used to store intermediate cache results
2339 /// when solving auto traits. Auto traits are unusual in that they can support
2340 /// cycles. So, for example, a "proof tree" like this would be ok:
2341 ///
2342 /// - `Foo<T>: Send` :-
2343 ///   - `Bar<T>: Send` :-
2344 ///     - `Foo<T>: Send` -- cycle, but ok
2345 ///   - `Baz<T>: Send`
2346 ///
2347 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2348 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2349 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2350 /// they are coinductive) it is considered ok.
2351 ///
2352 /// However, there is a complication: at the point where we have
2353 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2354 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2355 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2356 /// find out this assumption is wrong?  Specifically, we could
2357 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2358 /// `Bar<T>: Send` didn't turn out to be true.
2359 ///
2360 /// In Issue #60010, we found a bug in rustc where it would cache
2361 /// these intermediate results. This was fixed in #60444 by disabling
2362 /// *all* caching for things involved in a cycle -- in our example,
2363 /// that would mean we don't cache that `Bar<T>: Send`.  But this led
2364 /// to large slowdowns.
2365 ///
2366 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2367 /// first requires proving `Bar<T>: Send` (which is true:
2368 ///
2369 /// - `Foo<T>: Send` :-
2370 ///   - `Bar<T>: Send` :-
2371 ///     - `Foo<T>: Send` -- cycle, but ok
2372 ///   - `Baz<T>: Send`
2373 ///     - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2374 ///     - `*const T: Send` -- but what if we later encounter an error?
2375 ///
2376 /// The *provisional evaluation cache* resolves this issue. It stores
2377 /// cache results that we've proven but which were involved in a cycle
2378 /// in some way. We track the minimal stack depth (i.e., the
2379 /// farthest from the top of the stack) that we are dependent on.
2380 /// The idea is that the cache results within are all valid -- so long as
2381 /// none of the nodes in between the current node and the node at that minimum
2382 /// depth result in an error (in which case the cached results are just thrown away).
2383 ///
2384 /// During evaluation, we consult this provisional cache and rely on
2385 /// it. Accessing a cached value is considered equivalent to accessing
2386 /// a result at `reached_depth`, so it marks the *current* solution as
2387 /// provisional as well. If an error is encountered, we toss out any
2388 /// provisional results added from the subtree that encountered the
2389 /// error.  When we pop the node at `reached_depth` from the stack, we
2390 /// can commit all the things that remain in the provisional cache.
2391 struct ProvisionalEvaluationCache<'tcx> {
2392     /// next "depth first number" to issue -- just a counter
2393     dfn: Cell<usize>,
2394
2395     /// Map from cache key to the provisionally evaluated thing.
2396     /// The cache entries contain the result but also the DFN in which they
2397     /// were added. The DFN is used to clear out values on failure.
2398     ///
2399     /// Imagine we have a stack like:
2400     ///
2401     /// - `A B C` and we add a cache for the result of C (DFN 2)
2402     /// - Then we have a stack `A B D` where `D` has DFN 3
2403     /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2404     /// - `E` generates various cache entries which have cyclic dependices on `B`
2405     ///   - `A B D E F` and so forth
2406     ///   - the DFN of `F` for example would be 5
2407     /// - then we determine that `E` is in error -- we will then clear
2408     ///   all cache values whose DFN is >= 4 -- in this case, that
2409     ///   means the cached value for `F`.
2410     map: RefCell<FxHashMap<ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, ProvisionalEvaluation>>,
2411 }
2412
2413 /// A cache value for the provisional cache: contains the depth-first
2414 /// number (DFN) and result.
2415 #[derive(Copy, Clone, Debug)]
2416 struct ProvisionalEvaluation {
2417     from_dfn: usize,
2418     reached_depth: usize,
2419     result: EvaluationResult,
2420 }
2421
2422 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2423     fn default() -> Self {
2424         Self { dfn: Cell::new(0), map: Default::default() }
2425     }
2426 }
2427
2428 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2429     /// Get the next DFN in sequence (basically a counter).
2430     fn next_dfn(&self) -> usize {
2431         let result = self.dfn.get();
2432         self.dfn.set(result + 1);
2433         result
2434     }
2435
2436     /// Check the provisional cache for any result for
2437     /// `fresh_trait_ref`. If there is a hit, then you must consider
2438     /// it an access to the stack slots at depth
2439     /// `reached_depth` (from the returned value).
2440     fn get_provisional(
2441         &self,
2442         fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2443     ) -> Option<ProvisionalEvaluation> {
2444         debug!(
2445             ?fresh_trait_ref,
2446             "get_provisional = {:#?}",
2447             self.map.borrow().get(&fresh_trait_ref),
2448         );
2449         Some(*self.map.borrow().get(&fresh_trait_ref)?)
2450     }
2451
2452     /// Insert a provisional result into the cache. The result came
2453     /// from the node with the given DFN. It accessed a minimum depth
2454     /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2455     /// and resulted in `result`.
2456     fn insert_provisional(
2457         &self,
2458         from_dfn: usize,
2459         reached_depth: usize,
2460         fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2461         result: EvaluationResult,
2462     ) {
2463         debug!(?from_dfn, ?fresh_trait_ref, ?result, "insert_provisional");
2464
2465         let mut map = self.map.borrow_mut();
2466
2467         // Subtle: when we complete working on the DFN `from_dfn`, anything
2468         // that remains in the provisional cache must be dependent on some older
2469         // stack entry than `from_dfn`. We have to update their depth with our transitive
2470         // depth in that case or else it would be referring to some popped note.
2471         //
2472         // Example:
2473         // A (reached depth 0)
2474         //   ...
2475         //      B // depth 1 -- reached depth = 0
2476         //          C // depth 2 -- reached depth = 1 (should be 0)
2477         //              B
2478         //          A // depth 0
2479         //   D (reached depth 1)
2480         //      C (cache -- reached depth = 2)
2481         for (_k, v) in &mut *map {
2482             if v.from_dfn >= from_dfn {
2483                 v.reached_depth = reached_depth.min(v.reached_depth);
2484             }
2485         }
2486
2487         map.insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, reached_depth, result });
2488     }
2489
2490     /// Invoked when the node with dfn `dfn` does not get a successful
2491     /// result.  This will clear out any provisional cache entries
2492     /// that were added since `dfn` was created. This is because the
2493     /// provisional entries are things which must assume that the
2494     /// things on the stack at the time of their creation succeeded --
2495     /// since the failing node is presently at the top of the stack,
2496     /// these provisional entries must either depend on it or some
2497     /// ancestor of it.
2498     fn on_failure(&self, dfn: usize) {
2499         debug!(?dfn, "on_failure");
2500         self.map.borrow_mut().retain(|key, eval| {
2501             if !eval.from_dfn >= dfn {
2502                 debug!("on_failure: removing {:?}", key);
2503                 false
2504             } else {
2505                 true
2506             }
2507         });
2508     }
2509
2510     /// Invoked when the node at depth `depth` completed without
2511     /// depending on anything higher in the stack (if that completion
2512     /// was a failure, then `on_failure` should have been invoked
2513     /// already). The callback `op` will be invoked for each
2514     /// provisional entry that we can now confirm.
2515     ///
2516     /// Note that we may still have provisional cache items remaining
2517     /// in the cache when this is done. For example, if there is a
2518     /// cycle:
2519     ///
2520     /// * A depends on...
2521     ///     * B depends on A
2522     ///     * C depends on...
2523     ///         * D depends on C
2524     ///     * ...
2525     ///
2526     /// Then as we complete the C node we will have a provisional cache
2527     /// with results for A, B, C, and D. This method would clear out
2528     /// the C and D results, but leave A and B provisional.
2529     ///
2530     /// This is determined based on the DFN: we remove any provisional
2531     /// results created since `dfn` started (e.g., in our example, dfn
2532     /// would be 2, representing the C node, and hence we would
2533     /// remove the result for D, which has DFN 3, but not the results for
2534     /// A and B, which have DFNs 0 and 1 respectively).
2535     fn on_completion(
2536         &self,
2537         dfn: usize,
2538         mut op: impl FnMut(ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, EvaluationResult),
2539     ) {
2540         debug!(?dfn, "on_completion");
2541
2542         for (fresh_trait_ref, eval) in
2543             self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2544         {
2545             debug!(?fresh_trait_ref, ?eval, "on_completion");
2546
2547             op(fresh_trait_ref, eval.result);
2548         }
2549     }
2550 }
2551
2552 #[derive(Copy, Clone)]
2553 struct TraitObligationStackList<'o, 'tcx> {
2554     cache: &'o ProvisionalEvaluationCache<'tcx>,
2555     head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2556 }
2557
2558 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2559     fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2560         TraitObligationStackList { cache, head: None }
2561     }
2562
2563     fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2564         TraitObligationStackList { cache: r.cache(), head: Some(r) }
2565     }
2566
2567     fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2568         self.head
2569     }
2570
2571     fn depth(&self) -> usize {
2572         if let Some(head) = self.head { head.depth } else { 0 }
2573     }
2574 }
2575
2576 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2577     type Item = &'o TraitObligationStack<'o, 'tcx>;
2578
2579     fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2580         let o = self.head?;
2581         *self = o.previous;
2582         Some(o)
2583     }
2584 }
2585
2586 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2587     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2588         write!(f, "TraitObligationStack({:?})", self.obligation)
2589     }
2590 }