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