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