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