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