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