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