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