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