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