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