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