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