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