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