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