]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/select/mod.rs
Auto merge of #90424 - matthiaskrgr:rollup-jezzu4f, r=matthiaskrgr
[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 = |cand: &ty::PolyTraitRef<'tcx>| {
1551             cand.is_global(self.infcx.tcx) && !cand.has_late_bound_regions()
1552         };
1553
1554         // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1555         // and `DiscriminantKindCandidate` to anything else.
1556         //
1557         // This is a fix for #53123 and prevents winnowing from accidentally extending the
1558         // lifetime of a variable.
1559         match (&other.candidate, &victim.candidate) {
1560             (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1561                 bug!(
1562                     "default implementations shouldn't be recorded \
1563                     when there are other valid candidates"
1564                 );
1565             }
1566
1567             // (*)
1568             (
1569                 BuiltinCandidate { has_nested: false }
1570                 | DiscriminantKindCandidate
1571                 | PointeeCandidate
1572                 | ConstDropCandidate,
1573                 _,
1574             ) => true,
1575             (
1576                 _,
1577                 BuiltinCandidate { has_nested: false }
1578                 | DiscriminantKindCandidate
1579                 | PointeeCandidate
1580                 | ConstDropCandidate,
1581             ) => false,
1582
1583             (
1584                 ParamCandidate((other, other_polarity)),
1585                 ParamCandidate((victim, victim_polarity)),
1586             ) => {
1587                 let same_except_bound_vars = other.value.skip_binder()
1588                     == victim.value.skip_binder()
1589                     && other.constness == victim.constness
1590                     && other_polarity == victim_polarity
1591                     && !other.value.skip_binder().has_escaping_bound_vars();
1592                 if same_except_bound_vars {
1593                     // See issue #84398. In short, we can generate multiple ParamCandidates which are
1594                     // the same except for unused bound vars. Just pick the one with the fewest bound vars
1595                     // or the current one if tied (they should both evaluate to the same answer). This is
1596                     // probably best characterized as a "hack", since we might prefer to just do our
1597                     // best to *not* create essentially duplicate candidates in the first place.
1598                     other.value.bound_vars().len() <= victim.value.bound_vars().len()
1599                 } else if other.value == victim.value
1600                     && victim.constness == ty::BoundConstness::NotConst
1601                     && other_polarity == victim_polarity
1602                 {
1603                     // Drop otherwise equivalent non-const candidates in favor of const candidates.
1604                     true
1605                 } else {
1606                     false
1607                 }
1608             }
1609
1610             // Drop otherwise equivalent non-const fn pointer candidates
1611             (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1612
1613             // Global bounds from the where clause should be ignored
1614             // here (see issue #50825). Otherwise, we have a where
1615             // clause so don't go around looking for impls.
1616             // Arbitrarily give param candidates priority
1617             // over projection and object candidates.
1618             (
1619                 ParamCandidate(ref cand),
1620                 ImplCandidate(..)
1621                 | ClosureCandidate
1622                 | GeneratorCandidate
1623                 | FnPointerCandidate { .. }
1624                 | BuiltinObjectCandidate
1625                 | BuiltinUnsizeCandidate
1626                 | TraitUpcastingUnsizeCandidate(_)
1627                 | BuiltinCandidate { .. }
1628                 | TraitAliasCandidate(..)
1629                 | ObjectCandidate(_)
1630                 | ProjectionCandidate(_),
1631             ) => !is_global(&cand.0.value),
1632             (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1633                 // Prefer these to a global where-clause bound
1634                 // (see issue #50825).
1635                 is_global(&cand.0.value)
1636             }
1637             (
1638                 ImplCandidate(_)
1639                 | ClosureCandidate
1640                 | GeneratorCandidate
1641                 | FnPointerCandidate { .. }
1642                 | BuiltinObjectCandidate
1643                 | BuiltinUnsizeCandidate
1644                 | TraitUpcastingUnsizeCandidate(_)
1645                 | BuiltinCandidate { has_nested: true }
1646                 | TraitAliasCandidate(..),
1647                 ParamCandidate(ref cand),
1648             ) => {
1649                 // Prefer these to a global where-clause bound
1650                 // (see issue #50825).
1651                 is_global(&cand.0.value) && other.evaluation.must_apply_modulo_regions()
1652             }
1653
1654             (ProjectionCandidate(i), ProjectionCandidate(j))
1655             | (ObjectCandidate(i), ObjectCandidate(j)) => {
1656                 // Arbitrarily pick the lower numbered candidate for backwards
1657                 // compatibility reasons. Don't let this affect inference.
1658                 i < j && !needs_infer
1659             }
1660             (ObjectCandidate(_), ProjectionCandidate(_))
1661             | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1662                 bug!("Have both object and projection candidate")
1663             }
1664
1665             // Arbitrarily give projection and object candidates priority.
1666             (
1667                 ObjectCandidate(_) | ProjectionCandidate(_),
1668                 ImplCandidate(..)
1669                 | ClosureCandidate
1670                 | GeneratorCandidate
1671                 | FnPointerCandidate { .. }
1672                 | BuiltinObjectCandidate
1673                 | BuiltinUnsizeCandidate
1674                 | TraitUpcastingUnsizeCandidate(_)
1675                 | BuiltinCandidate { .. }
1676                 | TraitAliasCandidate(..),
1677             ) => true,
1678
1679             (
1680                 ImplCandidate(..)
1681                 | ClosureCandidate
1682                 | GeneratorCandidate
1683                 | FnPointerCandidate { .. }
1684                 | BuiltinObjectCandidate
1685                 | BuiltinUnsizeCandidate
1686                 | TraitUpcastingUnsizeCandidate(_)
1687                 | BuiltinCandidate { .. }
1688                 | TraitAliasCandidate(..),
1689                 ObjectCandidate(_) | ProjectionCandidate(_),
1690             ) => false,
1691
1692             (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1693                 // See if we can toss out `victim` based on specialization.
1694                 // This requires us to know *for sure* that the `other` impl applies
1695                 // i.e., `EvaluatedToOk`.
1696                 //
1697                 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1698                 // to me but is required for `std` to compile, so I didn't change it
1699                 // for now.
1700                 let tcx = self.tcx();
1701                 if other.evaluation.must_apply_modulo_regions() {
1702                     if tcx.specializes((other_def, victim_def)) {
1703                         return true;
1704                     }
1705                 }
1706
1707                 if other.evaluation.must_apply_considering_regions() {
1708                     match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1709                         Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1710                             // Subtle: If the predicate we are evaluating has inference
1711                             // variables, do *not* allow discarding candidates due to
1712                             // marker trait impls.
1713                             //
1714                             // Without this restriction, we could end up accidentally
1715                             // constrainting inference variables based on an arbitrarily
1716                             // chosen trait impl.
1717                             //
1718                             // Imagine we have the following code:
1719                             //
1720                             // ```rust
1721                             // #[marker] trait MyTrait {}
1722                             // impl MyTrait for u8 {}
1723                             // impl MyTrait for bool {}
1724                             // ```
1725                             //
1726                             // And we are evaluating the predicate `<_#0t as MyTrait>`.
1727                             //
1728                             // During selection, we will end up with one candidate for each
1729                             // impl of `MyTrait`. If we were to discard one impl in favor
1730                             // of the other, we would be left with one candidate, causing
1731                             // us to "successfully" select the predicate, unifying
1732                             // _#0t with (for example) `u8`.
1733                             //
1734                             // However, we have no reason to believe that this unification
1735                             // is correct - we've essentially just picked an arbitrary
1736                             // *possibility* for _#0t, and required that this be the *only*
1737                             // possibility.
1738                             //
1739                             // Eventually, we will either:
1740                             // 1) Unify all inference variables in the predicate through
1741                             // some other means (e.g. type-checking of a function). We will
1742                             // then be in a position to drop marker trait candidates
1743                             // without constraining inference variables (since there are
1744                             // none left to constrin)
1745                             // 2) Be left with some unconstrained inference variables. We
1746                             // will then correctly report an inference error, since the
1747                             // existence of multiple marker trait impls tells us nothing
1748                             // about which one should actually apply.
1749                             !needs_infer
1750                         }
1751                         Some(_) => true,
1752                         None => false,
1753                     }
1754                 } else {
1755                     false
1756                 }
1757             }
1758
1759             // Everything else is ambiguous
1760             (
1761                 ImplCandidate(_)
1762                 | ClosureCandidate
1763                 | GeneratorCandidate
1764                 | FnPointerCandidate { .. }
1765                 | BuiltinObjectCandidate
1766                 | BuiltinUnsizeCandidate
1767                 | TraitUpcastingUnsizeCandidate(_)
1768                 | BuiltinCandidate { has_nested: true }
1769                 | TraitAliasCandidate(..),
1770                 ImplCandidate(_)
1771                 | ClosureCandidate
1772                 | GeneratorCandidate
1773                 | FnPointerCandidate { .. }
1774                 | BuiltinObjectCandidate
1775                 | BuiltinUnsizeCandidate
1776                 | TraitUpcastingUnsizeCandidate(_)
1777                 | BuiltinCandidate { has_nested: true }
1778                 | TraitAliasCandidate(..),
1779             ) => false,
1780         }
1781     }
1782
1783     fn sized_conditions(
1784         &mut self,
1785         obligation: &TraitObligation<'tcx>,
1786     ) -> BuiltinImplConditions<'tcx> {
1787         use self::BuiltinImplConditions::{Ambiguous, None, Where};
1788
1789         // NOTE: binder moved to (*)
1790         let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1791
1792         match self_ty.kind() {
1793             ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1794             | ty::Uint(_)
1795             | ty::Int(_)
1796             | ty::Bool
1797             | ty::Float(_)
1798             | ty::FnDef(..)
1799             | ty::FnPtr(_)
1800             | ty::RawPtr(..)
1801             | ty::Char
1802             | ty::Ref(..)
1803             | ty::Generator(..)
1804             | ty::GeneratorWitness(..)
1805             | ty::Array(..)
1806             | ty::Closure(..)
1807             | ty::Never
1808             | ty::Error(_) => {
1809                 // safe for everything
1810                 Where(ty::Binder::dummy(Vec::new()))
1811             }
1812
1813             ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1814
1815             ty::Tuple(tys) => Where(
1816                 obligation
1817                     .predicate
1818                     .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1819             ),
1820
1821             ty::Adt(def, substs) => {
1822                 let sized_crit = def.sized_constraint(self.tcx());
1823                 // (*) binder moved here
1824                 Where(
1825                     obligation.predicate.rebind({
1826                         sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1827                     }),
1828                 )
1829             }
1830
1831             ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1832             ty::Infer(ty::TyVar(_)) => Ambiguous,
1833
1834             ty::Placeholder(..)
1835             | ty::Bound(..)
1836             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1837                 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1838             }
1839         }
1840     }
1841
1842     fn copy_clone_conditions(
1843         &mut self,
1844         obligation: &TraitObligation<'tcx>,
1845     ) -> BuiltinImplConditions<'tcx> {
1846         // NOTE: binder moved to (*)
1847         let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1848
1849         use self::BuiltinImplConditions::{Ambiguous, None, Where};
1850
1851         match *self_ty.kind() {
1852             ty::Infer(ty::IntVar(_))
1853             | ty::Infer(ty::FloatVar(_))
1854             | ty::FnDef(..)
1855             | ty::FnPtr(_)
1856             | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1857
1858             ty::Uint(_)
1859             | ty::Int(_)
1860             | ty::Bool
1861             | ty::Float(_)
1862             | ty::Char
1863             | ty::RawPtr(..)
1864             | ty::Never
1865             | ty::Ref(_, _, hir::Mutability::Not) => {
1866                 // Implementations provided in libcore
1867                 None
1868             }
1869
1870             ty::Dynamic(..)
1871             | ty::Str
1872             | ty::Slice(..)
1873             | ty::Generator(..)
1874             | ty::GeneratorWitness(..)
1875             | ty::Foreign(..)
1876             | ty::Ref(_, _, hir::Mutability::Mut) => None,
1877
1878             ty::Array(element_ty, _) => {
1879                 // (*) binder moved here
1880                 Where(obligation.predicate.rebind(vec![element_ty]))
1881             }
1882
1883             ty::Tuple(tys) => {
1884                 // (*) binder moved here
1885                 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
1886             }
1887
1888             ty::Closure(_, substs) => {
1889                 // (*) binder moved here
1890                 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1891                 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1892                     // Not yet resolved.
1893                     Ambiguous
1894                 } else {
1895                     Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1896                 }
1897             }
1898
1899             ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1900                 // Fallback to whatever user-defined impls exist in this case.
1901                 None
1902             }
1903
1904             ty::Infer(ty::TyVar(_)) => {
1905                 // Unbound type variable. Might or might not have
1906                 // applicable impls and so forth, depending on what
1907                 // those type variables wind up being bound to.
1908                 Ambiguous
1909             }
1910
1911             ty::Placeholder(..)
1912             | ty::Bound(..)
1913             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1914                 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1915             }
1916         }
1917     }
1918
1919     /// For default impls, we need to break apart a type into its
1920     /// "constituent types" -- meaning, the types that it contains.
1921     ///
1922     /// Here are some (simple) examples:
1923     ///
1924     /// ```
1925     /// (i32, u32) -> [i32, u32]
1926     /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1927     /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1928     /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1929     /// ```
1930     fn constituent_types_for_ty(
1931         &self,
1932         t: ty::Binder<'tcx, Ty<'tcx>>,
1933     ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1934         match *t.skip_binder().kind() {
1935             ty::Uint(_)
1936             | ty::Int(_)
1937             | ty::Bool
1938             | ty::Float(_)
1939             | ty::FnDef(..)
1940             | ty::FnPtr(_)
1941             | ty::Str
1942             | ty::Error(_)
1943             | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1944             | ty::Never
1945             | ty::Char => ty::Binder::dummy(Vec::new()),
1946
1947             ty::Placeholder(..)
1948             | ty::Dynamic(..)
1949             | ty::Param(..)
1950             | ty::Foreign(..)
1951             | ty::Projection(..)
1952             | ty::Bound(..)
1953             | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1954                 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1955             }
1956
1957             ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1958                 t.rebind(vec![element_ty])
1959             }
1960
1961             ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1962
1963             ty::Tuple(ref tys) => {
1964                 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1965                 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
1966             }
1967
1968             ty::Closure(_, ref substs) => {
1969                 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1970                 t.rebind(vec![ty])
1971             }
1972
1973             ty::Generator(_, ref substs, _) => {
1974                 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1975                 let witness = substs.as_generator().witness();
1976                 t.rebind(vec![ty].into_iter().chain(iter::once(witness)).collect())
1977             }
1978
1979             ty::GeneratorWitness(types) => {
1980                 debug_assert!(!types.has_escaping_bound_vars());
1981                 types.map_bound(|types| types.to_vec())
1982             }
1983
1984             // For `PhantomData<T>`, we pass `T`.
1985             ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1986
1987             ty::Adt(def, substs) => {
1988                 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
1989             }
1990
1991             ty::Opaque(def_id, substs) => {
1992                 // We can resolve the `impl Trait` to its concrete type,
1993                 // which enforces a DAG between the functions requiring
1994                 // the auto trait bounds in question.
1995                 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
1996             }
1997         }
1998     }
1999
2000     fn collect_predicates_for_types(
2001         &mut self,
2002         param_env: ty::ParamEnv<'tcx>,
2003         cause: ObligationCause<'tcx>,
2004         recursion_depth: usize,
2005         trait_def_id: DefId,
2006         types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2007     ) -> Vec<PredicateObligation<'tcx>> {
2008         // Because the types were potentially derived from
2009         // higher-ranked obligations they may reference late-bound
2010         // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2011         // yield a type like `for<'a> &'a i32`. In general, we
2012         // maintain the invariant that we never manipulate bound
2013         // regions, so we have to process these bound regions somehow.
2014         //
2015         // The strategy is to:
2016         //
2017         // 1. Instantiate those regions to placeholder regions (e.g.,
2018         //    `for<'a> &'a i32` becomes `&0 i32`.
2019         // 2. Produce something like `&'0 i32 : Copy`
2020         // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2021
2022         types
2023             .as_ref()
2024             .skip_binder() // binder moved -\
2025             .iter()
2026             .flat_map(|ty| {
2027                 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/
2028
2029                 self.infcx.commit_unconditionally(|_| {
2030                     let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2031                     let Normalized { value: normalized_ty, mut obligations } =
2032                         ensure_sufficient_stack(|| {
2033                             project::normalize_with_depth(
2034                                 self,
2035                                 param_env,
2036                                 cause.clone(),
2037                                 recursion_depth,
2038                                 placeholder_ty,
2039                             )
2040                         });
2041                     let placeholder_obligation = predicate_for_trait_def(
2042                         self.tcx(),
2043                         param_env,
2044                         cause.clone(),
2045                         trait_def_id,
2046                         recursion_depth,
2047                         normalized_ty,
2048                         &[],
2049                     );
2050                     obligations.push(placeholder_obligation);
2051                     obligations
2052                 })
2053             })
2054             .collect()
2055     }
2056
2057     ///////////////////////////////////////////////////////////////////////////
2058     // Matching
2059     //
2060     // Matching is a common path used for both evaluation and
2061     // confirmation.  It basically unifies types that appear in impls
2062     // and traits. This does affect the surrounding environment;
2063     // therefore, when used during evaluation, match routines must be
2064     // run inside of a `probe()` so that their side-effects are
2065     // contained.
2066
2067     fn rematch_impl(
2068         &mut self,
2069         impl_def_id: DefId,
2070         obligation: &TraitObligation<'tcx>,
2071     ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2072         match self.match_impl(impl_def_id, obligation) {
2073             Ok(substs) => substs,
2074             Err(()) => {
2075                 bug!(
2076                     "Impl {:?} was matchable against {:?} but now is not",
2077                     impl_def_id,
2078                     obligation
2079                 );
2080             }
2081         }
2082     }
2083
2084     #[tracing::instrument(level = "debug", skip(self))]
2085     fn match_impl(
2086         &mut self,
2087         impl_def_id: DefId,
2088         obligation: &TraitObligation<'tcx>,
2089     ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2090         let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2091
2092         // Before we create the substitutions and everything, first
2093         // consider a "quick reject". This avoids creating more types
2094         // and so forth that we need to.
2095         if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2096             return Err(());
2097         }
2098
2099         let placeholder_obligation =
2100             self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2101         let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2102
2103         let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2104
2105         let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2106
2107         debug!(?impl_trait_ref);
2108
2109         let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2110             ensure_sufficient_stack(|| {
2111                 project::normalize_with_depth(
2112                     self,
2113                     obligation.param_env,
2114                     obligation.cause.clone(),
2115                     obligation.recursion_depth + 1,
2116                     impl_trait_ref,
2117                 )
2118             });
2119
2120         debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2121
2122         let cause = ObligationCause::new(
2123             obligation.cause.span,
2124             obligation.cause.body_id,
2125             ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2126         );
2127
2128         let InferOk { obligations, .. } = self
2129             .infcx
2130             .at(&cause, obligation.param_env)
2131             .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2132             .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2133         nested_obligations.extend(obligations);
2134
2135         if !self.intercrate
2136             && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2137         {
2138             debug!("match_impl: reservation impls only apply in intercrate mode");
2139             return Err(());
2140         }
2141
2142         debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2143         Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2144     }
2145
2146     fn fast_reject_trait_refs(
2147         &mut self,
2148         obligation: &TraitObligation<'_>,
2149         impl_trait_ref: &ty::TraitRef<'_>,
2150     ) -> bool {
2151         // We can avoid creating type variables and doing the full
2152         // substitution if we find that any of the input types, when
2153         // simplified, do not match.
2154
2155         iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2156             |(obligation_arg, impl_arg)| {
2157                 match (obligation_arg.unpack(), impl_arg.unpack()) {
2158                     (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2159                         let simplified_obligation_ty =
2160                             fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2161                         let simplified_impl_ty =
2162                             fast_reject::simplify_type(self.tcx(), impl_ty, false);
2163
2164                         simplified_obligation_ty.is_some()
2165                             && simplified_impl_ty.is_some()
2166                             && simplified_obligation_ty != simplified_impl_ty
2167                     }
2168                     (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2169                         // Lifetimes can never cause a rejection.
2170                         false
2171                     }
2172                     (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2173                         // Conservatively ignore consts (i.e. assume they might
2174                         // unify later) until we have `fast_reject` support for
2175                         // them (if we'll ever need it, even).
2176                         false
2177                     }
2178                     _ => unreachable!(),
2179                 }
2180             },
2181         )
2182     }
2183
2184     /// Normalize `where_clause_trait_ref` and try to match it against
2185     /// `obligation`. If successful, return any predicates that
2186     /// result from the normalization.
2187     fn match_where_clause_trait_ref(
2188         &mut self,
2189         obligation: &TraitObligation<'tcx>,
2190         where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2191     ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2192         self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2193     }
2194
2195     /// Returns `Ok` if `poly_trait_ref` being true implies that the
2196     /// obligation is satisfied.
2197     #[instrument(skip(self), level = "debug")]
2198     fn match_poly_trait_ref(
2199         &mut self,
2200         obligation: &TraitObligation<'tcx>,
2201         poly_trait_ref: ty::PolyTraitRef<'tcx>,
2202     ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2203         self.infcx
2204             .at(&obligation.cause, obligation.param_env)
2205             .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2206             .map(|InferOk { obligations, .. }| obligations)
2207             .map_err(|_| ())
2208     }
2209
2210     ///////////////////////////////////////////////////////////////////////////
2211     // Miscellany
2212
2213     fn match_fresh_trait_refs(
2214         &self,
2215         previous: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2216         current: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2217         param_env: ty::ParamEnv<'tcx>,
2218     ) -> bool {
2219         let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2220         matcher.relate(previous, current).is_ok()
2221     }
2222
2223     fn push_stack<'o>(
2224         &mut self,
2225         previous_stack: TraitObligationStackList<'o, 'tcx>,
2226         obligation: &'o TraitObligation<'tcx>,
2227     ) -> TraitObligationStack<'o, 'tcx> {
2228         let fresh_trait_ref = obligation
2229             .predicate
2230             .to_poly_trait_ref()
2231             .fold_with(&mut self.freshener)
2232             .with_constness(obligation.predicate.skip_binder().constness);
2233
2234         let dfn = previous_stack.cache.next_dfn();
2235         let depth = previous_stack.depth() + 1;
2236         TraitObligationStack {
2237             obligation,
2238             fresh_trait_ref,
2239             reached_depth: Cell::new(depth),
2240             previous: previous_stack,
2241             dfn,
2242             depth,
2243         }
2244     }
2245
2246     #[instrument(skip(self), level = "debug")]
2247     fn closure_trait_ref_unnormalized(
2248         &mut self,
2249         obligation: &TraitObligation<'tcx>,
2250         substs: SubstsRef<'tcx>,
2251     ) -> ty::PolyTraitRef<'tcx> {
2252         let closure_sig = substs.as_closure().sig();
2253
2254         debug!(?closure_sig);
2255
2256         // (1) Feels icky to skip the binder here, but OTOH we know
2257         // that the self-type is an unboxed closure type and hence is
2258         // in fact unparameterized (or at least does not reference any
2259         // regions bound in the obligation). Still probably some
2260         // refactoring could make this nicer.
2261         closure_trait_ref_and_return_type(
2262             self.tcx(),
2263             obligation.predicate.def_id(),
2264             obligation.predicate.skip_binder().self_ty(), // (1)
2265             closure_sig,
2266             util::TupleArgumentsFlag::No,
2267         )
2268         .map_bound(|(trait_ref, _)| trait_ref)
2269     }
2270
2271     fn generator_trait_ref_unnormalized(
2272         &mut self,
2273         obligation: &TraitObligation<'tcx>,
2274         substs: SubstsRef<'tcx>,
2275     ) -> ty::PolyTraitRef<'tcx> {
2276         let gen_sig = substs.as_generator().poly_sig();
2277
2278         // (1) Feels icky to skip the binder here, but OTOH we know
2279         // that the self-type is an generator type and hence is
2280         // in fact unparameterized (or at least does not reference any
2281         // regions bound in the obligation). Still probably some
2282         // refactoring could make this nicer.
2283
2284         super::util::generator_trait_ref_and_outputs(
2285             self.tcx(),
2286             obligation.predicate.def_id(),
2287             obligation.predicate.skip_binder().self_ty(), // (1)
2288             gen_sig,
2289         )
2290         .map_bound(|(trait_ref, ..)| trait_ref)
2291     }
2292
2293     /// Returns the obligations that are implied by instantiating an
2294     /// impl or trait. The obligations are substituted and fully
2295     /// normalized. This is used when confirming an impl or default
2296     /// impl.
2297     #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2298     fn impl_or_trait_obligations(
2299         &mut self,
2300         cause: ObligationCause<'tcx>,
2301         recursion_depth: usize,
2302         param_env: ty::ParamEnv<'tcx>,
2303         def_id: DefId,           // of impl or trait
2304         substs: SubstsRef<'tcx>, // for impl or trait
2305     ) -> Vec<PredicateObligation<'tcx>> {
2306         let tcx = self.tcx();
2307
2308         // To allow for one-pass evaluation of the nested obligation,
2309         // each predicate must be preceded by the obligations required
2310         // to normalize it.
2311         // for example, if we have:
2312         //    impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2313         // the impl will have the following predicates:
2314         //    <V as Iterator>::Item = U,
2315         //    U: Iterator, U: Sized,
2316         //    V: Iterator, V: Sized,
2317         //    <U as Iterator>::Item: Copy
2318         // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2319         // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2320         // `$1: Copy`, so we must ensure the obligations are emitted in
2321         // that order.
2322         let predicates = tcx.predicates_of(def_id);
2323         debug!(?predicates);
2324         assert_eq!(predicates.parent, None);
2325         let mut obligations = Vec::with_capacity(predicates.predicates.len());
2326         for (predicate, _) in predicates.predicates {
2327             debug!(?predicate);
2328             let predicate = normalize_with_depth_to(
2329                 self,
2330                 param_env,
2331                 cause.clone(),
2332                 recursion_depth,
2333                 predicate.subst(tcx, substs),
2334                 &mut obligations,
2335             );
2336             obligations.push(Obligation {
2337                 cause: cause.clone(),
2338                 recursion_depth,
2339                 param_env,
2340                 predicate,
2341             });
2342         }
2343
2344         // We are performing deduplication here to avoid exponential blowups
2345         // (#38528) from happening, but the real cause of the duplication is
2346         // unknown. What we know is that the deduplication avoids exponential
2347         // amount of predicates being propagated when processing deeply nested
2348         // types.
2349         //
2350         // This code is hot enough that it's worth avoiding the allocation
2351         // required for the FxHashSet when possible. Special-casing lengths 0,
2352         // 1 and 2 covers roughly 75-80% of the cases.
2353         if obligations.len() <= 1 {
2354             // No possibility of duplicates.
2355         } else if obligations.len() == 2 {
2356             // Only two elements. Drop the second if they are equal.
2357             if obligations[0] == obligations[1] {
2358                 obligations.truncate(1);
2359             }
2360         } else {
2361             // Three or more elements. Use a general deduplication process.
2362             let mut seen = FxHashSet::default();
2363             obligations.retain(|i| seen.insert(i.clone()));
2364         }
2365
2366         obligations
2367     }
2368 }
2369
2370 trait TraitObligationExt<'tcx> {
2371     fn derived_cause(
2372         &self,
2373         variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2374     ) -> ObligationCause<'tcx>;
2375 }
2376
2377 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2378     fn derived_cause(
2379         &self,
2380         variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2381     ) -> ObligationCause<'tcx> {
2382         /*!
2383          * Creates a cause for obligations that are derived from
2384          * `obligation` by a recursive search (e.g., for a builtin
2385          * bound, or eventually a `auto trait Foo`). If `obligation`
2386          * is itself a derived obligation, this is just a clone, but
2387          * otherwise we create a "derived obligation" cause so as to
2388          * keep track of the original root obligation for error
2389          * reporting.
2390          */
2391
2392         let obligation = self;
2393
2394         // NOTE(flaper87): As of now, it keeps track of the whole error
2395         // chain. Ideally, we should have a way to configure this either
2396         // by using -Z verbose or just a CLI argument.
2397         let derived_cause = DerivedObligationCause {
2398             parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2399             parent_code: Lrc::new(obligation.cause.code.clone()),
2400         };
2401         let derived_code = variant(derived_cause);
2402         ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2403     }
2404 }
2405
2406 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2407     fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2408         TraitObligationStackList::with(self)
2409     }
2410
2411     fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2412         self.previous.cache
2413     }
2414
2415     fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2416         self.list()
2417     }
2418
2419     /// Indicates that attempting to evaluate this stack entry
2420     /// required accessing something from the stack at depth `reached_depth`.
2421     fn update_reached_depth(&self, reached_depth: usize) {
2422         assert!(
2423             self.depth >= reached_depth,
2424             "invoked `update_reached_depth` with something under this stack: \
2425              self.depth={} reached_depth={}",
2426             self.depth,
2427             reached_depth,
2428         );
2429         debug!(reached_depth, "update_reached_depth");
2430         let mut p = self;
2431         while reached_depth < p.depth {
2432             debug!(?p.fresh_trait_ref, "update_reached_depth: marking as cycle participant");
2433             p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2434             p = p.previous.head.unwrap();
2435         }
2436     }
2437 }
2438
2439 /// The "provisional evaluation cache" is used to store intermediate cache results
2440 /// when solving auto traits. Auto traits are unusual in that they can support
2441 /// cycles. So, for example, a "proof tree" like this would be ok:
2442 ///
2443 /// - `Foo<T>: Send` :-
2444 ///   - `Bar<T>: Send` :-
2445 ///     - `Foo<T>: Send` -- cycle, but ok
2446 ///   - `Baz<T>: Send`
2447 ///
2448 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2449 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2450 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2451 /// they are coinductive) it is considered ok.
2452 ///
2453 /// However, there is a complication: at the point where we have
2454 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2455 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2456 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2457 /// find out this assumption is wrong?  Specifically, we could
2458 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2459 /// `Bar<T>: Send` didn't turn out to be true.
2460 ///
2461 /// In Issue #60010, we found a bug in rustc where it would cache
2462 /// these intermediate results. This was fixed in #60444 by disabling
2463 /// *all* caching for things involved in a cycle -- in our example,
2464 /// that would mean we don't cache that `Bar<T>: Send`.  But this led
2465 /// to large slowdowns.
2466 ///
2467 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2468 /// first requires proving `Bar<T>: Send` (which is true:
2469 ///
2470 /// - `Foo<T>: Send` :-
2471 ///   - `Bar<T>: Send` :-
2472 ///     - `Foo<T>: Send` -- cycle, but ok
2473 ///   - `Baz<T>: Send`
2474 ///     - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2475 ///     - `*const T: Send` -- but what if we later encounter an error?
2476 ///
2477 /// The *provisional evaluation cache* resolves this issue. It stores
2478 /// cache results that we've proven but which were involved in a cycle
2479 /// in some way. We track the minimal stack depth (i.e., the
2480 /// farthest from the top of the stack) that we are dependent on.
2481 /// The idea is that the cache results within are all valid -- so long as
2482 /// none of the nodes in between the current node and the node at that minimum
2483 /// depth result in an error (in which case the cached results are just thrown away).
2484 ///
2485 /// During evaluation, we consult this provisional cache and rely on
2486 /// it. Accessing a cached value is considered equivalent to accessing
2487 /// a result at `reached_depth`, so it marks the *current* solution as
2488 /// provisional as well. If an error is encountered, we toss out any
2489 /// provisional results added from the subtree that encountered the
2490 /// error.  When we pop the node at `reached_depth` from the stack, we
2491 /// can commit all the things that remain in the provisional cache.
2492 struct ProvisionalEvaluationCache<'tcx> {
2493     /// next "depth first number" to issue -- just a counter
2494     dfn: Cell<usize>,
2495
2496     /// Map from cache key to the provisionally evaluated thing.
2497     /// The cache entries contain the result but also the DFN in which they
2498     /// were added. The DFN is used to clear out values on failure.
2499     ///
2500     /// Imagine we have a stack like:
2501     ///
2502     /// - `A B C` and we add a cache for the result of C (DFN 2)
2503     /// - Then we have a stack `A B D` where `D` has DFN 3
2504     /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2505     /// - `E` generates various cache entries which have cyclic dependices on `B`
2506     ///   - `A B D E F` and so forth
2507     ///   - the DFN of `F` for example would be 5
2508     /// - then we determine that `E` is in error -- we will then clear
2509     ///   all cache values whose DFN is >= 4 -- in this case, that
2510     ///   means the cached value for `F`.
2511     map: RefCell<FxHashMap<ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, ProvisionalEvaluation>>,
2512 }
2513
2514 /// A cache value for the provisional cache: contains the depth-first
2515 /// number (DFN) and result.
2516 #[derive(Copy, Clone, Debug)]
2517 struct ProvisionalEvaluation {
2518     from_dfn: usize,
2519     reached_depth: usize,
2520     result: EvaluationResult,
2521 }
2522
2523 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2524     fn default() -> Self {
2525         Self { dfn: Cell::new(0), map: Default::default() }
2526     }
2527 }
2528
2529 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2530     /// Get the next DFN in sequence (basically a counter).
2531     fn next_dfn(&self) -> usize {
2532         let result = self.dfn.get();
2533         self.dfn.set(result + 1);
2534         result
2535     }
2536
2537     /// Check the provisional cache for any result for
2538     /// `fresh_trait_ref`. If there is a hit, then you must consider
2539     /// it an access to the stack slots at depth
2540     /// `reached_depth` (from the returned value).
2541     fn get_provisional(
2542         &self,
2543         fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2544     ) -> Option<ProvisionalEvaluation> {
2545         debug!(
2546             ?fresh_trait_ref,
2547             "get_provisional = {:#?}",
2548             self.map.borrow().get(&fresh_trait_ref),
2549         );
2550         Some(*self.map.borrow().get(&fresh_trait_ref)?)
2551     }
2552
2553     /// Insert a provisional result into the cache. The result came
2554     /// from the node with the given DFN. It accessed a minimum depth
2555     /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2556     /// and resulted in `result`.
2557     fn insert_provisional(
2558         &self,
2559         from_dfn: usize,
2560         reached_depth: usize,
2561         fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2562         result: EvaluationResult,
2563     ) {
2564         debug!(?from_dfn, ?fresh_trait_ref, ?result, "insert_provisional");
2565
2566         let mut map = self.map.borrow_mut();
2567
2568         // Subtle: when we complete working on the DFN `from_dfn`, anything
2569         // that remains in the provisional cache must be dependent on some older
2570         // stack entry than `from_dfn`. We have to update their depth with our transitive
2571         // depth in that case or else it would be referring to some popped note.
2572         //
2573         // Example:
2574         // A (reached depth 0)
2575         //   ...
2576         //      B // depth 1 -- reached depth = 0
2577         //          C // depth 2 -- reached depth = 1 (should be 0)
2578         //              B
2579         //          A // depth 0
2580         //   D (reached depth 1)
2581         //      C (cache -- reached depth = 2)
2582         for (_k, v) in &mut *map {
2583             if v.from_dfn >= from_dfn {
2584                 v.reached_depth = reached_depth.min(v.reached_depth);
2585             }
2586         }
2587
2588         map.insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, reached_depth, result });
2589     }
2590
2591     /// Invoked when the node with dfn `dfn` does not get a successful
2592     /// result.  This will clear out any provisional cache entries
2593     /// that were added since `dfn` was created. This is because the
2594     /// provisional entries are things which must assume that the
2595     /// things on the stack at the time of their creation succeeded --
2596     /// since the failing node is presently at the top of the stack,
2597     /// these provisional entries must either depend on it or some
2598     /// ancestor of it.
2599     fn on_failure(&self, dfn: usize) {
2600         debug!(?dfn, "on_failure");
2601         self.map.borrow_mut().retain(|key, eval| {
2602             if !eval.from_dfn >= dfn {
2603                 debug!("on_failure: removing {:?}", key);
2604                 false
2605             } else {
2606                 true
2607             }
2608         });
2609     }
2610
2611     /// Invoked when the node at depth `depth` completed without
2612     /// depending on anything higher in the stack (if that completion
2613     /// was a failure, then `on_failure` should have been invoked
2614     /// already). The callback `op` will be invoked for each
2615     /// provisional entry that we can now confirm.
2616     ///
2617     /// Note that we may still have provisional cache items remaining
2618     /// in the cache when this is done. For example, if there is a
2619     /// cycle:
2620     ///
2621     /// * A depends on...
2622     ///     * B depends on A
2623     ///     * C depends on...
2624     ///         * D depends on C
2625     ///     * ...
2626     ///
2627     /// Then as we complete the C node we will have a provisional cache
2628     /// with results for A, B, C, and D. This method would clear out
2629     /// the C and D results, but leave A and B provisional.
2630     ///
2631     /// This is determined based on the DFN: we remove any provisional
2632     /// results created since `dfn` started (e.g., in our example, dfn
2633     /// would be 2, representing the C node, and hence we would
2634     /// remove the result for D, which has DFN 3, but not the results for
2635     /// A and B, which have DFNs 0 and 1 respectively).
2636     fn on_completion(
2637         &self,
2638         dfn: usize,
2639         mut op: impl FnMut(ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, EvaluationResult),
2640     ) {
2641         debug!(?dfn, "on_completion");
2642
2643         for (fresh_trait_ref, eval) in
2644             self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2645         {
2646             debug!(?fresh_trait_ref, ?eval, "on_completion");
2647
2648             op(fresh_trait_ref, eval.result);
2649         }
2650     }
2651 }
2652
2653 #[derive(Copy, Clone)]
2654 struct TraitObligationStackList<'o, 'tcx> {
2655     cache: &'o ProvisionalEvaluationCache<'tcx>,
2656     head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2657 }
2658
2659 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2660     fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2661         TraitObligationStackList { cache, head: None }
2662     }
2663
2664     fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2665         TraitObligationStackList { cache: r.cache(), head: Some(r) }
2666     }
2667
2668     fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2669         self.head
2670     }
2671
2672     fn depth(&self) -> usize {
2673         if let Some(head) = self.head { head.depth } else { 0 }
2674     }
2675 }
2676
2677 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2678     type Item = &'o TraitObligationStack<'o, 'tcx>;
2679
2680     fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2681         let o = self.head?;
2682         *self = o.previous;
2683         Some(o)
2684     }
2685 }
2686
2687 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2688     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2689         write!(f, "TraitObligationStack({:?})", self.obligation)
2690     }
2691 }