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