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