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