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