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