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