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