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