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