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