]> git.lizzy.rs Git - rust.git/blob - src/librustc_trait_selection/traits/select.rs
rename `Predicate` to `PredicateKind`, introduce alias
[rust.git] / src / librustc_trait_selection / traits / select.rs
1 // ignore-tidy-filelength
2
3 //! Candidate selection. See the [rustc dev guide] for more information on how this works.
4 //!
5 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
6
7 use self::EvaluationResult::*;
8 use self::SelectionCandidate::*;
9
10 use super::coherence::{self, Conflict};
11 use super::project;
12 use super::project::{normalize_with_depth, normalize_with_depth_to};
13 use super::util;
14 use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
15 use super::wf;
16 use super::DerivedObligationCause;
17 use super::Selection;
18 use super::SelectionResult;
19 use super::TraitNotObjectSafe;
20 use super::TraitQueryMode;
21 use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
22 use super::{Normalized, ProjectionCacheKey};
23 use super::{ObjectCastObligation, Obligation};
24 use super::{ObligationCause, PredicateObligation, TraitObligation};
25 use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
26 use super::{
27     VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
28     VtableObject, VtableParam, VtableTraitAlias,
29 };
30 use super::{
31     VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
32     VtableGeneratorData, VtableImplData, VtableObjectData, VtableTraitAliasData,
33 };
34
35 use crate::infer::{CombinedSnapshot, InferCtxt, InferOk, PlaceholderMap, TypeFreshener};
36 use crate::traits::error_reporting::InferCtxtExt;
37 use crate::traits::project::ProjectionCacheKeyExt;
38 use rustc_ast::attr;
39 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
40 use rustc_data_structures::stack::ensure_sufficient_stack;
41 use rustc_errors::ErrorReported;
42 use rustc_hir as hir;
43 use rustc_hir::def_id::DefId;
44 use rustc_hir::lang_items;
45 use rustc_index::bit_set::GrowableBitSet;
46 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
47 use rustc_middle::mir::interpret::ErrorHandled;
48 use rustc_middle::ty::fast_reject;
49 use rustc_middle::ty::relate::TypeRelation;
50 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst, SubstsRef};
51 use rustc_middle::ty::{
52     self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
53 };
54 use rustc_span::symbol::sym;
55 use rustc_target::spec::abi::Abi;
56
57 use std::cell::{Cell, RefCell};
58 use std::cmp;
59 use std::fmt::{self, Display};
60 use std::iter;
61 use std::rc::Rc;
62
63 pub use rustc_middle::traits::select::*;
64
65 pub struct SelectionContext<'cx, 'tcx> {
66     infcx: &'cx InferCtxt<'cx, 'tcx>,
67
68     /// Freshener used specifically for entries on the obligation
69     /// stack. This ensures that all entries on the stack at one time
70     /// will have the same set of placeholder entries, which is
71     /// important for checking for trait bounds that recursively
72     /// require themselves.
73     freshener: TypeFreshener<'cx, 'tcx>,
74
75     /// If `true`, indicates that the evaluation should be conservative
76     /// and consider the possibility of types outside this crate.
77     /// This comes up primarily when resolving ambiguity. Imagine
78     /// there is some trait reference `$0: Bar` where `$0` is an
79     /// inference variable. If `intercrate` is true, then we can never
80     /// say for sure that this reference is not implemented, even if
81     /// there are *no impls at all for `Bar`*, because `$0` could be
82     /// bound to some type that in a downstream crate that implements
83     /// `Bar`. This is the suitable mode for coherence. Elsewhere,
84     /// though, we set this to false, because we are only interested
85     /// in types that the user could actually have written --- in
86     /// other words, we consider `$0: Bar` to be unimplemented if
87     /// there is no type that the user could *actually name* that
88     /// would satisfy it. This avoids crippling inference, basically.
89     intercrate: bool,
90
91     intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
92
93     /// Controls whether or not to filter out negative impls when selecting.
94     /// This is used in librustdoc to distinguish between the lack of an impl
95     /// and a negative impl
96     allow_negative_impls: bool,
97
98     /// The mode that trait queries run in, which informs our error handling
99     /// policy. In essence, canonicalized queries need their errors propagated
100     /// rather than immediately reported because we do not have accurate spans.
101     query_mode: TraitQueryMode,
102 }
103
104 // A stack that walks back up the stack frame.
105 struct TraitObligationStack<'prev, 'tcx> {
106     obligation: &'prev TraitObligation<'tcx>,
107
108     /// The trait ref from `obligation` but "freshened" with the
109     /// selection-context's freshener. Used to check for recursion.
110     fresh_trait_ref: ty::PolyTraitRef<'tcx>,
111
112     /// Starts out equal to `depth` -- if, during evaluation, we
113     /// encounter a cycle, then we will set this flag to the minimum
114     /// depth of that cycle for all participants in the cycle. These
115     /// participants will then forego caching their results. This is
116     /// not the most efficient solution, but it addresses #60010. The
117     /// problem we are trying to prevent:
118     ///
119     /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
120     /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
121     /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
122     ///
123     /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
124     /// is `EvaluatedToOk`; this is because they were only considered
125     /// ok on the premise that if `A: AutoTrait` held, but we indeed
126     /// encountered a problem (later on) with `A: AutoTrait. So we
127     /// currently set a flag on the stack node for `B: AutoTrait` (as
128     /// well as the second instance of `A: AutoTrait`) to suppress
129     /// caching.
130     ///
131     /// This is a simple, targeted fix. A more-performant fix requires
132     /// deeper changes, but would permit more caching: we could
133     /// basically defer caching until we have fully evaluated the
134     /// tree, and then cache the entire tree at once. In any case, the
135     /// performance impact here shouldn't be so horrible: every time
136     /// this is hit, we do cache at least one trait, so we only
137     /// evaluate each member of a cycle up to N times, where N is the
138     /// length of the cycle. This means the performance impact is
139     /// bounded and we shouldn't have any terrible worst-cases.
140     reached_depth: Cell<usize>,
141
142     previous: TraitObligationStackList<'prev, 'tcx>,
143
144     /// The number of parent frames plus one (thus, the topmost frame has depth 1).
145     depth: usize,
146
147     /// The depth-first number of this node in the search graph -- a
148     /// pre-order index. Basically, a freshly incremented counter.
149     dfn: usize,
150 }
151
152 struct SelectionCandidateSet<'tcx> {
153     // A list of candidates that definitely apply to the current
154     // obligation (meaning: types unify).
155     vec: Vec<SelectionCandidate<'tcx>>,
156
157     // If `true`, then there were candidates that might or might
158     // not have applied, but we couldn't tell. This occurs when some
159     // of the input types are type variables, in which case there are
160     // various "builtin" rules that might or might not trigger.
161     ambiguous: bool,
162 }
163
164 #[derive(PartialEq, Eq, Debug, Clone)]
165 struct EvaluatedCandidate<'tcx> {
166     candidate: SelectionCandidate<'tcx>,
167     evaluation: EvaluationResult,
168 }
169
170 /// When does the builtin impl for `T: Trait` apply?
171 enum BuiltinImplConditions<'tcx> {
172     /// The impl is conditional on `T1, T2, ...: Trait`.
173     Where(ty::Binder<Vec<Ty<'tcx>>>),
174     /// There is no built-in impl. There may be some other
175     /// candidate (a where-clause or user-defined impl).
176     None,
177     /// It is unknown whether there is an impl.
178     Ambiguous,
179 }
180
181 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
182     pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
183         SelectionContext {
184             infcx,
185             freshener: infcx.freshener(),
186             intercrate: false,
187             intercrate_ambiguity_causes: None,
188             allow_negative_impls: false,
189             query_mode: TraitQueryMode::Standard,
190         }
191     }
192
193     pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
194         SelectionContext {
195             infcx,
196             freshener: infcx.freshener(),
197             intercrate: true,
198             intercrate_ambiguity_causes: None,
199             allow_negative_impls: false,
200             query_mode: TraitQueryMode::Standard,
201         }
202     }
203
204     pub fn with_negative(
205         infcx: &'cx InferCtxt<'cx, 'tcx>,
206         allow_negative_impls: bool,
207     ) -> SelectionContext<'cx, 'tcx> {
208         debug!("with_negative({:?})", allow_negative_impls);
209         SelectionContext {
210             infcx,
211             freshener: infcx.freshener(),
212             intercrate: false,
213             intercrate_ambiguity_causes: None,
214             allow_negative_impls,
215             query_mode: TraitQueryMode::Standard,
216         }
217     }
218
219     pub fn with_query_mode(
220         infcx: &'cx InferCtxt<'cx, 'tcx>,
221         query_mode: TraitQueryMode,
222     ) -> SelectionContext<'cx, 'tcx> {
223         debug!("with_query_mode({:?})", query_mode);
224         SelectionContext {
225             infcx,
226             freshener: infcx.freshener(),
227             intercrate: false,
228             intercrate_ambiguity_causes: None,
229             allow_negative_impls: false,
230             query_mode,
231         }
232     }
233
234     /// Enables tracking of intercrate ambiguity causes. These are
235     /// used in coherence to give improved diagnostics. We don't do
236     /// this until we detect a coherence error because it can lead to
237     /// false overflow results (#47139) and because it costs
238     /// computation time.
239     pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
240         assert!(self.intercrate);
241         assert!(self.intercrate_ambiguity_causes.is_none());
242         self.intercrate_ambiguity_causes = Some(vec![]);
243         debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
244     }
245
246     /// Gets the intercrate ambiguity causes collected since tracking
247     /// was enabled and disables tracking at the same time. If
248     /// tracking is not enabled, just returns an empty vector.
249     pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
250         assert!(self.intercrate);
251         self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
252     }
253
254     pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
255         self.infcx
256     }
257
258     pub fn tcx(&self) -> TyCtxt<'tcx> {
259         self.infcx.tcx
260     }
261
262     pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
263         self.infcx
264     }
265
266     ///////////////////////////////////////////////////////////////////////////
267     // Selection
268     //
269     // The selection phase tries to identify *how* an obligation will
270     // be resolved. For example, it will identify which impl or
271     // parameter bound is to be used. The process can be inconclusive
272     // if the self type in the obligation is not fully inferred. Selection
273     // can result in an error in one of two ways:
274     //
275     // 1. If no applicable impl or parameter bound can be found.
276     // 2. If the output type parameters in the obligation do not match
277     //    those specified by the impl/bound. For example, if the obligation
278     //    is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
279     //    `impl<T> Iterable<T> for Vec<T>`, than an error would result.
280
281     /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
282     /// type environment by performing unification.
283     pub fn select(
284         &mut self,
285         obligation: &TraitObligation<'tcx>,
286     ) -> SelectionResult<'tcx, Selection<'tcx>> {
287         debug!("select({:?})", obligation);
288         debug_assert!(!obligation.predicate.has_escaping_bound_vars());
289
290         let pec = &ProvisionalEvaluationCache::default();
291         let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
292
293         let candidate = match self.candidate_from_obligation(&stack) {
294             Err(SelectionError::Overflow) => {
295                 // In standard mode, overflow must have been caught and reported
296                 // earlier.
297                 assert!(self.query_mode == TraitQueryMode::Canonical);
298                 return Err(SelectionError::Overflow);
299             }
300             Err(e) => {
301                 return Err(e);
302             }
303             Ok(None) => {
304                 return Ok(None);
305             }
306             Ok(Some(candidate)) => candidate,
307         };
308
309         match self.confirm_candidate(obligation, candidate) {
310             Err(SelectionError::Overflow) => {
311                 assert!(self.query_mode == TraitQueryMode::Canonical);
312                 Err(SelectionError::Overflow)
313             }
314             Err(e) => Err(e),
315             Ok(candidate) => Ok(Some(candidate)),
316         }
317     }
318
319     ///////////////////////////////////////////////////////////////////////////
320     // EVALUATION
321     //
322     // Tests whether an obligation can be selected or whether an impl
323     // can be applied to particular types. It skips the "confirmation"
324     // step and hence completely ignores output type parameters.
325     //
326     // The result is "true" if the obligation *may* hold and "false" if
327     // we can be sure it does not.
328
329     /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
330     pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
331         debug!("predicate_may_hold_fatal({:?})", obligation);
332
333         // This fatal query is a stopgap that should only be used in standard mode,
334         // where we do not expect overflow to be propagated.
335         assert!(self.query_mode == TraitQueryMode::Standard);
336
337         self.evaluate_root_obligation(obligation)
338             .expect("Overflow should be caught earlier in standard query mode")
339             .may_apply()
340     }
341
342     /// Evaluates whether the obligation `obligation` can be satisfied
343     /// and returns an `EvaluationResult`. This is meant for the
344     /// *initial* call.
345     pub fn evaluate_root_obligation(
346         &mut self,
347         obligation: &PredicateObligation<'tcx>,
348     ) -> Result<EvaluationResult, OverflowError> {
349         self.evaluation_probe(|this| {
350             this.evaluate_predicate_recursively(
351                 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
352                 obligation.clone(),
353             )
354         })
355     }
356
357     fn evaluation_probe(
358         &mut self,
359         op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
360     ) -> Result<EvaluationResult, OverflowError> {
361         self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
362             let result = op(self)?;
363             match self.infcx.region_constraints_added_in_snapshot(snapshot) {
364                 None => Ok(result),
365                 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
366             }
367         })
368     }
369
370     /// Evaluates the predicates in `predicates` recursively. Note that
371     /// this applies projections in the predicates, and therefore
372     /// is run within an inference probe.
373     fn evaluate_predicates_recursively<'o, I>(
374         &mut self,
375         stack: TraitObligationStackList<'o, 'tcx>,
376         predicates: I,
377     ) -> Result<EvaluationResult, OverflowError>
378     where
379         I: IntoIterator<Item = PredicateObligation<'tcx>>,
380     {
381         let mut result = EvaluatedToOk;
382         for obligation in predicates {
383             let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
384             debug!("evaluate_predicate_recursively({:?}) = {:?}", obligation, eval);
385             if let EvaluatedToErr = eval {
386                 // fast-path - EvaluatedToErr is the top of the lattice,
387                 // so we don't need to look on the other predicates.
388                 return Ok(EvaluatedToErr);
389             } else {
390                 result = cmp::max(result, eval);
391             }
392         }
393         Ok(result)
394     }
395
396     fn evaluate_predicate_recursively<'o>(
397         &mut self,
398         previous_stack: TraitObligationStackList<'o, 'tcx>,
399         obligation: PredicateObligation<'tcx>,
400     ) -> Result<EvaluationResult, OverflowError> {
401         debug!(
402             "evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
403             previous_stack.head(),
404             obligation
405         );
406
407         // `previous_stack` stores a `TraitObligatiom`, while `obligation` is
408         // a `PredicateObligation`. These are distinct types, so we can't
409         // use any `Option` combinator method that would force them to be
410         // the same.
411         match previous_stack.head() {
412             Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
413             None => self.check_recursion_limit(&obligation, &obligation)?,
414         }
415
416         match obligation.predicate {
417             ty::PredicateKind::Trait(ref t, _) => {
418                 debug_assert!(!t.has_escaping_bound_vars());
419                 let obligation = obligation.with(*t);
420                 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
421             }
422
423             ty::PredicateKind::Subtype(ref p) => {
424                 // Does this code ever run?
425                 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
426                     Some(Ok(InferOk { mut obligations, .. })) => {
427                         self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
428                         self.evaluate_predicates_recursively(
429                             previous_stack,
430                             obligations.into_iter(),
431                         )
432                     }
433                     Some(Err(_)) => Ok(EvaluatedToErr),
434                     None => Ok(EvaluatedToAmbig),
435                 }
436             }
437
438             ty::PredicateKind::WellFormed(ty) => match wf::obligations(
439                 self.infcx,
440                 obligation.param_env,
441                 obligation.cause.body_id,
442                 ty,
443                 obligation.cause.span,
444             ) {
445                 Some(mut obligations) => {
446                     self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
447                     self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
448                 }
449                 None => Ok(EvaluatedToAmbig),
450             },
451
452             ty::PredicateKind::TypeOutlives(..) | ty::PredicateKind::RegionOutlives(..) => {
453                 // We do not consider region relationships when evaluating trait matches.
454                 Ok(EvaluatedToOkModuloRegions)
455             }
456
457             ty::PredicateKind::ObjectSafe(trait_def_id) => {
458                 if self.tcx().is_object_safe(trait_def_id) {
459                     Ok(EvaluatedToOk)
460                 } else {
461                     Ok(EvaluatedToErr)
462                 }
463             }
464
465             ty::PredicateKind::Projection(ref data) => {
466                 let project_obligation = obligation.with(*data);
467                 match project::poly_project_and_unify_type(self, &project_obligation) {
468                     Ok(Some(mut subobligations)) => {
469                         self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
470                         let result = self.evaluate_predicates_recursively(
471                             previous_stack,
472                             subobligations.into_iter(),
473                         );
474                         if let Some(key) =
475                             ProjectionCacheKey::from_poly_projection_predicate(self, data)
476                         {
477                             self.infcx.inner.borrow_mut().projection_cache().complete(key);
478                         }
479                         result
480                     }
481                     Ok(None) => Ok(EvaluatedToAmbig),
482                     Err(_) => Ok(EvaluatedToErr),
483                 }
484             }
485
486             ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
487                 match self.infcx.closure_kind(closure_substs) {
488                     Some(closure_kind) => {
489                         if closure_kind.extends(kind) {
490                             Ok(EvaluatedToOk)
491                         } else {
492                             Ok(EvaluatedToErr)
493                         }
494                     }
495                     None => Ok(EvaluatedToAmbig),
496                 }
497             }
498
499             ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
500                 match self.tcx().const_eval_resolve(
501                     obligation.param_env,
502                     def_id,
503                     substs,
504                     None,
505                     None,
506                 ) {
507                     Ok(_) => Ok(EvaluatedToOk),
508                     Err(ErrorHandled::TooGeneric) => Ok(EvaluatedToAmbig),
509                     Err(_) => Ok(EvaluatedToErr),
510                 }
511             }
512
513             ty::Predicate::ConstEquate(c1, c2) => {
514                 debug!("evaluate_predicate_recursively: equating consts c1={:?} c2={:?}", c1, c2);
515
516                 let evaluate = |c: &'tcx ty::Const<'tcx>| {
517                     if let ty::ConstKind::Unevaluated(def_id, substs, promoted) = c.val {
518                         self.infcx
519                             .const_eval_resolve(
520                                 obligation.param_env,
521                                 def_id,
522                                 substs,
523                                 promoted,
524                                 Some(obligation.cause.span),
525                             )
526                             .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
527                     } else {
528                         Ok(c)
529                     }
530                 };
531
532                 match (evaluate(c1), evaluate(c2)) {
533                     (Ok(c1), Ok(c2)) => {
534                         match self.infcx().at(&obligation.cause, obligation.param_env).eq(c1, c2) {
535                             Ok(_) => Ok(EvaluatedToOk),
536                             Err(_) => Ok(EvaluatedToErr),
537                         }
538                     }
539                     (Err(ErrorHandled::Reported(ErrorReported)), _)
540                     | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
541                     (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => span_bug!(
542                         obligation.cause.span(self.tcx()),
543                         "ConstEquate: const_eval_resolve returned an unexpected error"
544                     ),
545                     (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
546                         Ok(EvaluatedToAmbig)
547                     }
548                 }
549             }
550         }
551     }
552
553     fn evaluate_trait_predicate_recursively<'o>(
554         &mut self,
555         previous_stack: TraitObligationStackList<'o, 'tcx>,
556         mut obligation: TraitObligation<'tcx>,
557     ) -> Result<EvaluationResult, OverflowError> {
558         debug!("evaluate_trait_predicate_recursively({:?})", obligation);
559
560         if !self.intercrate
561             && obligation.is_global()
562             && obligation.param_env.caller_bounds.iter().all(|bound| bound.needs_subst())
563         {
564             // If a param env has no global bounds, global obligations do not
565             // depend on its particular value in order to work, so we can clear
566             // out the param env and get better caching.
567             debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
568             obligation.param_env = obligation.param_env.without_caller_bounds();
569         }
570
571         let stack = self.push_stack(previous_stack, &obligation);
572         let fresh_trait_ref = stack.fresh_trait_ref;
573         if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
574             debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
575             return Ok(result);
576         }
577
578         if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
579             debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
580             stack.update_reached_depth(stack.cache().current_reached_depth());
581             return Ok(result);
582         }
583
584         // Check if this is a match for something already on the
585         // stack. If so, we don't want to insert the result into the
586         // main cache (it is cycle dependent) nor the provisional
587         // cache (which is meant for things that have completed but
588         // for a "backedge" -- this result *is* the backedge).
589         if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
590             return Ok(cycle_result);
591         }
592
593         let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
594         let result = result?;
595
596         if !result.must_apply_modulo_regions() {
597             stack.cache().on_failure(stack.dfn);
598         }
599
600         let reached_depth = stack.reached_depth.get();
601         if reached_depth >= stack.depth {
602             debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
603             self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
604
605             stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
606                 self.insert_evaluation_cache(
607                     obligation.param_env,
608                     fresh_trait_ref,
609                     dep_node,
610                     provisional_result.max(result),
611                 );
612             });
613         } else {
614             debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
615             debug!(
616                 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
617                  is a cycle participant (at depth {}, reached depth {})",
618                 fresh_trait_ref, stack.depth, reached_depth,
619             );
620
621             stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
622         }
623
624         Ok(result)
625     }
626
627     /// If there is any previous entry on the stack that precisely
628     /// matches this obligation, then we can assume that the
629     /// obligation is satisfied for now (still all other conditions
630     /// must be met of course). One obvious case this comes up is
631     /// marker traits like `Send`. Think of a linked list:
632     ///
633     ///    struct List<T> { data: T, next: Option<Box<List<T>>> }
634     ///
635     /// `Box<List<T>>` will be `Send` if `T` is `Send` and
636     /// `Option<Box<List<T>>>` is `Send`, and in turn
637     /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
638     /// `Send`.
639     ///
640     /// Note that we do this comparison using the `fresh_trait_ref`
641     /// fields. Because these have all been freshened using
642     /// `self.freshener`, we can be sure that (a) this will not
643     /// affect the inferencer state and (b) that if we see two
644     /// fresh regions with the same index, they refer to the same
645     /// unbound type variable.
646     fn check_evaluation_cycle(
647         &mut self,
648         stack: &TraitObligationStack<'_, 'tcx>,
649     ) -> Option<EvaluationResult> {
650         if let Some(cycle_depth) = stack
651             .iter()
652             .skip(1) // Skip top-most frame.
653             .find(|prev| {
654                 stack.obligation.param_env == prev.obligation.param_env
655                     && stack.fresh_trait_ref == prev.fresh_trait_ref
656             })
657             .map(|stack| stack.depth)
658         {
659             debug!(
660                 "evaluate_stack({:?}) --> recursive at depth {}",
661                 stack.fresh_trait_ref, cycle_depth,
662             );
663
664             // If we have a stack like `A B C D E A`, where the top of
665             // the stack is the final `A`, then this will iterate over
666             // `A, E, D, C, B` -- i.e., all the participants apart
667             // from the cycle head. We mark them as participating in a
668             // cycle. This suppresses caching for those nodes. See
669             // `in_cycle` field for more details.
670             stack.update_reached_depth(cycle_depth);
671
672             // Subtle: when checking for a coinductive cycle, we do
673             // not compare using the "freshened trait refs" (which
674             // have erased regions) but rather the fully explicit
675             // trait refs. This is important because it's only a cycle
676             // if the regions match exactly.
677             let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
678             let cycle = cycle.map(|stack| {
679                 ty::PredicateKind::Trait(stack.obligation.predicate, hir::Constness::NotConst)
680             });
681             if self.coinductive_match(cycle) {
682                 debug!("evaluate_stack({:?}) --> recursive, coinductive", stack.fresh_trait_ref);
683                 Some(EvaluatedToOk)
684             } else {
685                 debug!("evaluate_stack({:?}) --> recursive, inductive", stack.fresh_trait_ref);
686                 Some(EvaluatedToRecur)
687             }
688         } else {
689             None
690         }
691     }
692
693     fn evaluate_stack<'o>(
694         &mut self,
695         stack: &TraitObligationStack<'o, 'tcx>,
696     ) -> Result<EvaluationResult, OverflowError> {
697         // In intercrate mode, whenever any of the generics are unbound,
698         // there can always be an impl. Even if there are no impls in
699         // this crate, perhaps the type would be unified with
700         // something from another crate that does provide an impl.
701         //
702         // In intra mode, we must still be conservative. The reason is
703         // that we want to avoid cycles. Imagine an impl like:
704         //
705         //     impl<T:Eq> Eq for Vec<T>
706         //
707         // and a trait reference like `$0 : Eq` where `$0` is an
708         // unbound variable. When we evaluate this trait-reference, we
709         // will unify `$0` with `Vec<$1>` (for some fresh variable
710         // `$1`), on the condition that `$1 : Eq`. We will then wind
711         // up with many candidates (since that are other `Eq` impls
712         // that apply) and try to winnow things down. This results in
713         // a recursive evaluation that `$1 : Eq` -- as you can
714         // imagine, this is just where we started. To avoid that, we
715         // check for unbound variables and return an ambiguous (hence possible)
716         // match if we've seen this trait before.
717         //
718         // This suffices to allow chains like `FnMut` implemented in
719         // terms of `Fn` etc, but we could probably make this more
720         // precise still.
721         let unbound_input_types =
722             stack.fresh_trait_ref.skip_binder().substs.types().any(|ty| ty.is_fresh());
723         // This check was an imperfect workaround for a bug in the old
724         // intercrate mode; it should be removed when that goes away.
725         if unbound_input_types && self.intercrate {
726             debug!(
727                 "evaluate_stack({:?}) --> unbound argument, intercrate -->  ambiguous",
728                 stack.fresh_trait_ref
729             );
730             // Heuristics: show the diagnostics when there are no candidates in crate.
731             if self.intercrate_ambiguity_causes.is_some() {
732                 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
733                 if let Ok(candidate_set) = self.assemble_candidates(stack) {
734                     if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
735                         let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
736                         let self_ty = trait_ref.self_ty();
737                         let cause = IntercrateAmbiguityCause::DownstreamCrate {
738                             trait_desc: trait_ref.print_only_trait_path().to_string(),
739                             self_desc: if self_ty.has_concrete_skeleton() {
740                                 Some(self_ty.to_string())
741                             } else {
742                                 None
743                             },
744                         };
745                         debug!("evaluate_stack: pushing cause = {:?}", cause);
746                         self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
747                     }
748                 }
749             }
750             return Ok(EvaluatedToAmbig);
751         }
752         if unbound_input_types
753             && stack.iter().skip(1).any(|prev| {
754                 stack.obligation.param_env == prev.obligation.param_env
755                     && self.match_fresh_trait_refs(
756                         &stack.fresh_trait_ref,
757                         &prev.fresh_trait_ref,
758                         prev.obligation.param_env,
759                     )
760             })
761         {
762             debug!(
763                 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
764                 stack.fresh_trait_ref
765             );
766             return Ok(EvaluatedToUnknown);
767         }
768
769         match self.candidate_from_obligation(stack) {
770             Ok(Some(c)) => self.evaluate_candidate(stack, &c),
771             Ok(None) => Ok(EvaluatedToAmbig),
772             Err(Overflow) => Err(OverflowError),
773             Err(..) => Ok(EvaluatedToErr),
774         }
775     }
776
777     /// For defaulted traits, we use a co-inductive strategy to solve, so
778     /// that recursion is ok. This routine returns `true` if the top of the
779     /// stack (`cycle[0]`):
780     ///
781     /// - is a defaulted trait,
782     /// - it also appears in the backtrace at some position `X`,
783     /// - all the predicates at positions `X..` between `X` and the top are
784     ///   also defaulted traits.
785     pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
786     where
787         I: Iterator<Item = ty::Predicate<'tcx>>,
788     {
789         let mut cycle = cycle;
790         cycle.all(|predicate| self.coinductive_predicate(predicate))
791     }
792
793     fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
794         let result = match predicate {
795             ty::PredicateKind::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()),
796             _ => false,
797         };
798         debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
799         result
800     }
801
802     /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
803     /// obligations are met. Returns whether `candidate` remains viable after this further
804     /// scrutiny.
805     fn evaluate_candidate<'o>(
806         &mut self,
807         stack: &TraitObligationStack<'o, 'tcx>,
808         candidate: &SelectionCandidate<'tcx>,
809     ) -> Result<EvaluationResult, OverflowError> {
810         debug!(
811             "evaluate_candidate: depth={} candidate={:?}",
812             stack.obligation.recursion_depth, candidate
813         );
814         let result = self.evaluation_probe(|this| {
815             let candidate = (*candidate).clone();
816             match this.confirm_candidate(stack.obligation, candidate) {
817                 Ok(selection) => this.evaluate_predicates_recursively(
818                     stack.list(),
819                     selection.nested_obligations().into_iter(),
820                 ),
821                 Err(..) => Ok(EvaluatedToErr),
822             }
823         })?;
824         debug!(
825             "evaluate_candidate: depth={} result={:?}",
826             stack.obligation.recursion_depth, result
827         );
828         Ok(result)
829     }
830
831     fn check_evaluation_cache(
832         &self,
833         param_env: ty::ParamEnv<'tcx>,
834         trait_ref: ty::PolyTraitRef<'tcx>,
835     ) -> Option<EvaluationResult> {
836         let tcx = self.tcx();
837         if self.can_use_global_caches(param_env) {
838             let cache = tcx.evaluation_cache.hashmap.borrow();
839             if let Some(cached) = cache.get(&param_env.and(trait_ref)) {
840                 return Some(cached.get(tcx));
841             }
842         }
843         self.infcx
844             .evaluation_cache
845             .hashmap
846             .borrow()
847             .get(&param_env.and(trait_ref))
848             .map(|v| v.get(tcx))
849     }
850
851     fn insert_evaluation_cache(
852         &mut self,
853         param_env: ty::ParamEnv<'tcx>,
854         trait_ref: ty::PolyTraitRef<'tcx>,
855         dep_node: DepNodeIndex,
856         result: EvaluationResult,
857     ) {
858         // Avoid caching results that depend on more than just the trait-ref
859         // - the stack can create recursion.
860         if result.is_stack_dependent() {
861             return;
862         }
863
864         if self.can_use_global_caches(param_env) {
865             if !trait_ref.needs_infer() {
866                 debug!(
867                     "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
868                     trait_ref, result,
869                 );
870                 // This may overwrite the cache with the same value
871                 // FIXME: Due to #50507 this overwrites the different values
872                 // This should be changed to use HashMapExt::insert_same
873                 // when that is fixed
874                 self.tcx()
875                     .evaluation_cache
876                     .hashmap
877                     .borrow_mut()
878                     .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
879                 return;
880             }
881         }
882
883         debug!("insert_evaluation_cache(trait_ref={:?}, candidate={:?})", trait_ref, result,);
884         self.infcx
885             .evaluation_cache
886             .hashmap
887             .borrow_mut()
888             .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
889     }
890
891     /// For various reasons, it's possible for a subobligation
892     /// to have a *lower* recursion_depth than the obligation used to create it.
893     /// Projection sub-obligations may be returned from the projection cache,
894     /// which results in obligations with an 'old' `recursion_depth`.
895     /// Additionally, methods like `wf::obligations` and
896     /// `InferCtxt.subtype_predicate` produce subobligations without
897     /// taking in a 'parent' depth, causing the generated subobligations
898     /// to have a `recursion_depth` of `0`.
899     ///
900     /// To ensure that obligation_depth never decreasees, we force all subobligations
901     /// to have at least the depth of the original obligation.
902     fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
903         &self,
904         it: I,
905         min_depth: usize,
906     ) {
907         it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
908     }
909
910     /// Checks that the recursion limit has not been exceeded.
911     ///
912     /// The weird return type of this function allows it to be used with the `try` (`?`)
913     /// operator within certain functions.
914     fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
915         &self,
916         obligation: &Obligation<'tcx, T>,
917         error_obligation: &Obligation<'tcx, V>,
918     ) -> Result<(), OverflowError> {
919         let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
920         if obligation.recursion_depth >= recursion_limit {
921             match self.query_mode {
922                 TraitQueryMode::Standard => {
923                     self.infcx().report_overflow_error(error_obligation, true);
924                 }
925                 TraitQueryMode::Canonical => {
926                     return Err(OverflowError);
927                 }
928             }
929         }
930         Ok(())
931     }
932
933     ///////////////////////////////////////////////////////////////////////////
934     // CANDIDATE ASSEMBLY
935     //
936     // The selection process begins by examining all in-scope impls,
937     // caller obligations, and so forth and assembling a list of
938     // candidates. See the [rustc dev guide] for more details.
939     //
940     // [rustc dev guide]:
941     // https://rustc-dev-guide.rust-lang.org/traits/resolution.html#candidate-assembly
942
943     fn candidate_from_obligation<'o>(
944         &mut self,
945         stack: &TraitObligationStack<'o, 'tcx>,
946     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
947         // Watch out for overflow. This intentionally bypasses (and does
948         // not update) the cache.
949         self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
950
951         // Check the cache. Note that we freshen the trait-ref
952         // separately rather than using `stack.fresh_trait_ref` --
953         // this is because we want the unbound variables to be
954         // replaced with fresh types starting from index 0.
955         let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
956         debug!(
957             "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
958             cache_fresh_trait_pred, stack
959         );
960         debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
961
962         if let Some(c) =
963             self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
964         {
965             debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
966             return c;
967         }
968
969         // If no match, compute result and insert into cache.
970         //
971         // FIXME(nikomatsakis) -- this cache is not taking into
972         // account cycles that may have occurred in forming the
973         // candidate. I don't know of any specific problems that
974         // result but it seems awfully suspicious.
975         let (candidate, dep_node) =
976             self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
977
978         debug!("CACHE MISS: SELECT({:?})={:?}", cache_fresh_trait_pred, candidate);
979         self.insert_candidate_cache(
980             stack.obligation.param_env,
981             cache_fresh_trait_pred,
982             dep_node,
983             candidate.clone(),
984         );
985         candidate
986     }
987
988     fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
989     where
990         OP: FnOnce(&mut Self) -> R,
991     {
992         let (result, dep_node) =
993             self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || op(self));
994         self.tcx().dep_graph.read_index(dep_node);
995         (result, dep_node)
996     }
997
998     // Treat negative impls as unimplemented, and reservation impls as ambiguity.
999     fn filter_negative_and_reservation_impls(
1000         &mut self,
1001         candidate: SelectionCandidate<'tcx>,
1002     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1003         if let ImplCandidate(def_id) = candidate {
1004             let tcx = self.tcx();
1005             match tcx.impl_polarity(def_id) {
1006                 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1007                     return Err(Unimplemented);
1008                 }
1009                 ty::ImplPolarity::Reservation => {
1010                     if let Some(intercrate_ambiguity_clauses) =
1011                         &mut self.intercrate_ambiguity_causes
1012                     {
1013                         let attrs = tcx.get_attrs(def_id);
1014                         let attr = attr::find_by_name(&attrs, sym::rustc_reservation_impl);
1015                         let value = attr.and_then(|a| a.value_str());
1016                         if let Some(value) = value {
1017                             debug!(
1018                                 "filter_negative_and_reservation_impls: \
1019                                  reservation impl ambiguity on {:?}",
1020                                 def_id
1021                             );
1022                             intercrate_ambiguity_clauses.push(
1023                                 IntercrateAmbiguityCause::ReservationImpl {
1024                                     message: value.to_string(),
1025                                 },
1026                             );
1027                         }
1028                     }
1029                     return Ok(None);
1030                 }
1031                 _ => {}
1032             };
1033         }
1034         Ok(Some(candidate))
1035     }
1036
1037     fn candidate_from_obligation_no_cache<'o>(
1038         &mut self,
1039         stack: &TraitObligationStack<'o, 'tcx>,
1040     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1041         if stack.obligation.predicate.references_error() {
1042             // If we encounter a `Error`, we generally prefer the
1043             // most "optimistic" result in response -- that is, the
1044             // one least likely to report downstream errors. But
1045             // because this routine is shared by coherence and by
1046             // trait selection, there isn't an obvious "right" choice
1047             // here in that respect, so we opt to just return
1048             // ambiguity and let the upstream clients sort it out.
1049             return Ok(None);
1050         }
1051
1052         if let Some(conflict) = self.is_knowable(stack) {
1053             debug!("coherence stage: not knowable");
1054             if self.intercrate_ambiguity_causes.is_some() {
1055                 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1056                 // Heuristics: show the diagnostics when there are no candidates in crate.
1057                 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1058                     let mut no_candidates_apply = true;
1059                     {
1060                         let evaluated_candidates =
1061                             candidate_set.vec.iter().map(|c| self.evaluate_candidate(stack, &c));
1062
1063                         for ec in evaluated_candidates {
1064                             match ec {
1065                                 Ok(c) => {
1066                                     if c.may_apply() {
1067                                         no_candidates_apply = false;
1068                                         break;
1069                                     }
1070                                 }
1071                                 Err(e) => return Err(e.into()),
1072                             }
1073                         }
1074                     }
1075
1076                     if !candidate_set.ambiguous && no_candidates_apply {
1077                         let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1078                         let self_ty = trait_ref.self_ty();
1079                         let trait_desc = trait_ref.print_only_trait_path().to_string();
1080                         let self_desc = if self_ty.has_concrete_skeleton() {
1081                             Some(self_ty.to_string())
1082                         } else {
1083                             None
1084                         };
1085                         let cause = if let Conflict::Upstream = conflict {
1086                             IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1087                         } else {
1088                             IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1089                         };
1090                         debug!("evaluate_stack: pushing cause = {:?}", cause);
1091                         self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1092                     }
1093                 }
1094             }
1095             return Ok(None);
1096         }
1097
1098         let candidate_set = self.assemble_candidates(stack)?;
1099
1100         if candidate_set.ambiguous {
1101             debug!("candidate set contains ambig");
1102             return Ok(None);
1103         }
1104
1105         let mut candidates = candidate_set.vec;
1106
1107         debug!("assembled {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1108
1109         // At this point, we know that each of the entries in the
1110         // candidate set is *individually* applicable. Now we have to
1111         // figure out if they contain mutual incompatibilities. This
1112         // frequently arises if we have an unconstrained input type --
1113         // for example, we are looking for `$0: Eq` where `$0` is some
1114         // unconstrained type variable. In that case, we'll get a
1115         // candidate which assumes $0 == int, one that assumes `$0 ==
1116         // usize`, etc. This spells an ambiguity.
1117
1118         // If there is more than one candidate, first winnow them down
1119         // by considering extra conditions (nested obligations and so
1120         // forth). We don't winnow if there is exactly one
1121         // candidate. This is a relatively minor distinction but it
1122         // can lead to better inference and error-reporting. An
1123         // example would be if there was an impl:
1124         //
1125         //     impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1126         //
1127         // and we were to see some code `foo.push_clone()` where `boo`
1128         // is a `Vec<Bar>` and `Bar` does not implement `Clone`.  If
1129         // we were to winnow, we'd wind up with zero candidates.
1130         // Instead, we select the right impl now but report "`Bar` does
1131         // not implement `Clone`".
1132         if candidates.len() == 1 {
1133             return self.filter_negative_and_reservation_impls(candidates.pop().unwrap());
1134         }
1135
1136         // Winnow, but record the exact outcome of evaluation, which
1137         // is needed for specialization. Propagate overflow if it occurs.
1138         let mut candidates = candidates
1139             .into_iter()
1140             .map(|c| match self.evaluate_candidate(stack, &c) {
1141                 Ok(eval) if eval.may_apply() => {
1142                     Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
1143                 }
1144                 Ok(_) => Ok(None),
1145                 Err(OverflowError) => Err(Overflow),
1146             })
1147             .flat_map(Result::transpose)
1148             .collect::<Result<Vec<_>, _>>()?;
1149
1150         debug!("winnowed to {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1151
1152         let needs_infer = stack.obligation.predicate.needs_infer();
1153
1154         // If there are STILL multiple candidates, we can further
1155         // reduce the list by dropping duplicates -- including
1156         // resolving specializations.
1157         if candidates.len() > 1 {
1158             let mut i = 0;
1159             while i < candidates.len() {
1160                 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1161                     self.candidate_should_be_dropped_in_favor_of(
1162                         &candidates[i],
1163                         &candidates[j],
1164                         needs_infer,
1165                     )
1166                 });
1167                 if is_dup {
1168                     debug!("Dropping candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1169                     candidates.swap_remove(i);
1170                 } else {
1171                     debug!("Retaining candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1172                     i += 1;
1173
1174                     // If there are *STILL* multiple candidates, give up
1175                     // and report ambiguity.
1176                     if i > 1 {
1177                         debug!("multiple matches, ambig");
1178                         return Ok(None);
1179                     }
1180                 }
1181             }
1182         }
1183
1184         // If there are *NO* candidates, then there are no impls --
1185         // that we know of, anyway. Note that in the case where there
1186         // are unbound type variables within the obligation, it might
1187         // be the case that you could still satisfy the obligation
1188         // from another crate by instantiating the type variables with
1189         // a type from another crate that does have an impl. This case
1190         // is checked for in `evaluate_stack` (and hence users
1191         // who might care about this case, like coherence, should use
1192         // that function).
1193         if candidates.is_empty() {
1194             return Err(Unimplemented);
1195         }
1196
1197         // Just one candidate left.
1198         self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate)
1199     }
1200
1201     fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1202         debug!("is_knowable(intercrate={:?})", self.intercrate);
1203
1204         if !self.intercrate {
1205             return None;
1206         }
1207
1208         let obligation = &stack.obligation;
1209         let predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1210
1211         // Okay to skip binder because of the nature of the
1212         // trait-ref-is-knowable check, which does not care about
1213         // bound regions.
1214         let trait_ref = predicate.skip_binder().trait_ref;
1215
1216         coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1217     }
1218
1219     /// Returns `true` if the global caches can be used.
1220     /// Do note that if the type itself is not in the
1221     /// global tcx, the local caches will be used.
1222     fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1223         // If there are any inference variables in the `ParamEnv`, then we
1224         // always use a cache local to this particular scope. Otherwise, we
1225         // switch to a global cache.
1226         if param_env.needs_infer() {
1227             return false;
1228         }
1229
1230         // Avoid using the master cache during coherence and just rely
1231         // on the local cache. This effectively disables caching
1232         // during coherence. It is really just a simplification to
1233         // avoid us having to fear that coherence results "pollute"
1234         // the master cache. Since coherence executes pretty quickly,
1235         // it's not worth going to more trouble to increase the
1236         // hit-rate, I don't think.
1237         if self.intercrate {
1238             return false;
1239         }
1240
1241         // Otherwise, we can use the global cache.
1242         true
1243     }
1244
1245     fn check_candidate_cache(
1246         &mut self,
1247         param_env: ty::ParamEnv<'tcx>,
1248         cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1249     ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1250         let tcx = self.tcx();
1251         let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1252         if self.can_use_global_caches(param_env) {
1253             let cache = tcx.selection_cache.hashmap.borrow();
1254             if let Some(cached) = cache.get(&param_env.and(*trait_ref)) {
1255                 return Some(cached.get(tcx));
1256             }
1257         }
1258         self.infcx
1259             .selection_cache
1260             .hashmap
1261             .borrow()
1262             .get(&param_env.and(*trait_ref))
1263             .map(|v| v.get(tcx))
1264     }
1265
1266     /// Determines whether can we safely cache the result
1267     /// of selecting an obligation. This is almost always `true`,
1268     /// except when dealing with certain `ParamCandidate`s.
1269     ///
1270     /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1271     /// since it was usually produced directly from a `DefId`. However,
1272     /// certain cases (currently only librustdoc's blanket impl finder),
1273     /// a `ParamEnv` may be explicitly constructed with inference types.
1274     /// When this is the case, we do *not* want to cache the resulting selection
1275     /// candidate. This is due to the fact that it might not always be possible
1276     /// to equate the obligation's trait ref and the candidate's trait ref,
1277     /// if more constraints end up getting added to an inference variable.
1278     ///
1279     /// Because of this, we always want to re-run the full selection
1280     /// process for our obligation the next time we see it, since
1281     /// we might end up picking a different `SelectionCandidate` (or none at all).
1282     fn can_cache_candidate(
1283         &self,
1284         result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1285     ) -> bool {
1286         match result {
1287             Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1288             _ => true,
1289         }
1290     }
1291
1292     fn insert_candidate_cache(
1293         &mut self,
1294         param_env: ty::ParamEnv<'tcx>,
1295         cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1296         dep_node: DepNodeIndex,
1297         candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1298     ) {
1299         let tcx = self.tcx();
1300         let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1301
1302         if !self.can_cache_candidate(&candidate) {
1303             debug!(
1304                 "insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1305                  candidate is not cacheable",
1306                 trait_ref, candidate
1307             );
1308             return;
1309         }
1310
1311         if self.can_use_global_caches(param_env) {
1312             if let Err(Overflow) = candidate {
1313                 // Don't cache overflow globally; we only produce this in certain modes.
1314             } else if !trait_ref.needs_infer() {
1315                 if !candidate.needs_infer() {
1316                     debug!(
1317                         "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1318                         trait_ref, candidate,
1319                     );
1320                     // This may overwrite the cache with the same value.
1321                     tcx.selection_cache
1322                         .hashmap
1323                         .borrow_mut()
1324                         .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1325                     return;
1326                 }
1327             }
1328         }
1329
1330         debug!(
1331             "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1332             trait_ref, candidate,
1333         );
1334         self.infcx
1335             .selection_cache
1336             .hashmap
1337             .borrow_mut()
1338             .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1339     }
1340
1341     fn assemble_candidates<'o>(
1342         &mut self,
1343         stack: &TraitObligationStack<'o, 'tcx>,
1344     ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1345         let TraitObligationStack { obligation, .. } = *stack;
1346         let obligation = &Obligation {
1347             param_env: obligation.param_env,
1348             cause: obligation.cause.clone(),
1349             recursion_depth: obligation.recursion_depth,
1350             predicate: self.infcx().resolve_vars_if_possible(&obligation.predicate),
1351         };
1352
1353         if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1354             // Self is a type variable (e.g., `_: AsRef<str>`).
1355             //
1356             // This is somewhat problematic, as the current scheme can't really
1357             // handle it turning to be a projection. This does end up as truly
1358             // ambiguous in most cases anyway.
1359             //
1360             // Take the fast path out - this also improves
1361             // performance by preventing assemble_candidates_from_impls from
1362             // matching every impl for this trait.
1363             return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1364         }
1365
1366         let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
1367
1368         self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1369
1370         // Other bounds. Consider both in-scope bounds from fn decl
1371         // and applicable impls. There is a certain set of precedence rules here.
1372         let def_id = obligation.predicate.def_id();
1373         let lang_items = self.tcx().lang_items();
1374
1375         if lang_items.copy_trait() == Some(def_id) {
1376             debug!("obligation self ty is {:?}", obligation.predicate.skip_binder().self_ty());
1377
1378             // User-defined copy impls are permitted, but only for
1379             // structs and enums.
1380             self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1381
1382             // For other types, we'll use the builtin rules.
1383             let copy_conditions = self.copy_clone_conditions(obligation);
1384             self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1385         } else if lang_items.sized_trait() == Some(def_id) {
1386             // Sized is never implementable by end-users, it is
1387             // always automatically computed.
1388             let sized_conditions = self.sized_conditions(obligation);
1389             self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1390         } else if lang_items.unsize_trait() == Some(def_id) {
1391             self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1392         } else {
1393             if lang_items.clone_trait() == Some(def_id) {
1394                 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1395                 // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone`
1396                 // types have builtin support for `Clone`.
1397                 let clone_conditions = self.copy_clone_conditions(obligation);
1398                 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1399             }
1400
1401             self.assemble_generator_candidates(obligation, &mut candidates)?;
1402             self.assemble_closure_candidates(obligation, &mut candidates)?;
1403             self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1404             self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1405             self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1406         }
1407
1408         self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1409         self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1410         // Auto implementations have lower priority, so we only
1411         // consider triggering a default if there is no other impl that can apply.
1412         if candidates.vec.is_empty() {
1413             self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1414         }
1415         debug!("candidate list size: {}", candidates.vec.len());
1416         Ok(candidates)
1417     }
1418
1419     fn assemble_candidates_from_projected_tys(
1420         &mut self,
1421         obligation: &TraitObligation<'tcx>,
1422         candidates: &mut SelectionCandidateSet<'tcx>,
1423     ) {
1424         debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1425
1426         // Before we go into the whole placeholder thing, just
1427         // quickly check if the self-type is a projection at all.
1428         match obligation.predicate.skip_binder().trait_ref.self_ty().kind {
1429             ty::Projection(_) | ty::Opaque(..) => {}
1430             ty::Infer(ty::TyVar(_)) => {
1431                 span_bug!(
1432                     obligation.cause.span,
1433                     "Self=_ should have been handled by assemble_candidates"
1434                 );
1435             }
1436             _ => return,
1437         }
1438
1439         let result = self.infcx.probe(|snapshot| {
1440             self.match_projection_obligation_against_definition_bounds(obligation, snapshot)
1441         });
1442
1443         if result {
1444             candidates.vec.push(ProjectionCandidate);
1445         }
1446     }
1447
1448     fn match_projection_obligation_against_definition_bounds(
1449         &mut self,
1450         obligation: &TraitObligation<'tcx>,
1451         snapshot: &CombinedSnapshot<'_, 'tcx>,
1452     ) -> bool {
1453         let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1454         let (placeholder_trait_predicate, placeholder_map) =
1455             self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
1456         debug!(
1457             "match_projection_obligation_against_definition_bounds: \
1458              placeholder_trait_predicate={:?}",
1459             placeholder_trait_predicate,
1460         );
1461
1462         let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().kind {
1463             ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1464             ty::Opaque(def_id, substs) => (def_id, substs),
1465             _ => {
1466                 span_bug!(
1467                     obligation.cause.span,
1468                     "match_projection_obligation_against_definition_bounds() called \
1469                      but self-ty is not a projection: {:?}",
1470                     placeholder_trait_predicate.trait_ref.self_ty()
1471                 );
1472             }
1473         };
1474         debug!(
1475             "match_projection_obligation_against_definition_bounds: \
1476              def_id={:?}, substs={:?}",
1477             def_id, substs
1478         );
1479
1480         let predicates_of = self.tcx().predicates_of(def_id);
1481         let bounds = predicates_of.instantiate(self.tcx(), substs);
1482         debug!(
1483             "match_projection_obligation_against_definition_bounds: \
1484              bounds={:?}",
1485             bounds
1486         );
1487
1488         let elaborated_predicates =
1489             util::elaborate_predicates(self.tcx(), bounds.predicates.into_iter());
1490         let matching_bound = elaborated_predicates.filter_to_traits().find(|bound| {
1491             self.infcx.probe(|_| {
1492                 self.match_projection(
1493                     obligation,
1494                     *bound,
1495                     placeholder_trait_predicate.trait_ref,
1496                     &placeholder_map,
1497                     snapshot,
1498                 )
1499             })
1500         });
1501
1502         debug!(
1503             "match_projection_obligation_against_definition_bounds: \
1504              matching_bound={:?}",
1505             matching_bound
1506         );
1507         match matching_bound {
1508             None => false,
1509             Some(bound) => {
1510                 // Repeat the successful match, if any, this time outside of a probe.
1511                 let result = self.match_projection(
1512                     obligation,
1513                     bound,
1514                     placeholder_trait_predicate.trait_ref,
1515                     &placeholder_map,
1516                     snapshot,
1517                 );
1518
1519                 assert!(result);
1520                 true
1521             }
1522         }
1523     }
1524
1525     fn match_projection(
1526         &mut self,
1527         obligation: &TraitObligation<'tcx>,
1528         trait_bound: ty::PolyTraitRef<'tcx>,
1529         placeholder_trait_ref: ty::TraitRef<'tcx>,
1530         placeholder_map: &PlaceholderMap<'tcx>,
1531         snapshot: &CombinedSnapshot<'_, 'tcx>,
1532     ) -> bool {
1533         debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1534         self.infcx
1535             .at(&obligation.cause, obligation.param_env)
1536             .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1537             .is_ok()
1538             && self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1539     }
1540
1541     /// Given an obligation like `<SomeTrait for T>`, searches the obligations that the caller
1542     /// supplied to find out whether it is listed among them.
1543     ///
1544     /// Never affects the inference environment.
1545     fn assemble_candidates_from_caller_bounds<'o>(
1546         &mut self,
1547         stack: &TraitObligationStack<'o, 'tcx>,
1548         candidates: &mut SelectionCandidateSet<'tcx>,
1549     ) -> Result<(), SelectionError<'tcx>> {
1550         debug!("assemble_candidates_from_caller_bounds({:?})", stack.obligation);
1551
1552         let all_bounds = stack
1553             .obligation
1554             .param_env
1555             .caller_bounds
1556             .iter()
1557             .filter_map(|o| o.to_opt_poly_trait_ref());
1558
1559         // Micro-optimization: filter out predicates relating to different traits.
1560         let matching_bounds =
1561             all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1562
1563         // Keep only those bounds which may apply, and propagate overflow if it occurs.
1564         let mut param_candidates = vec![];
1565         for bound in matching_bounds {
1566             let wc = self.evaluate_where_clause(stack, bound)?;
1567             if wc.may_apply() {
1568                 param_candidates.push(ParamCandidate(bound));
1569             }
1570         }
1571
1572         candidates.vec.extend(param_candidates);
1573
1574         Ok(())
1575     }
1576
1577     fn evaluate_where_clause<'o>(
1578         &mut self,
1579         stack: &TraitObligationStack<'o, 'tcx>,
1580         where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1581     ) -> Result<EvaluationResult, OverflowError> {
1582         self.evaluation_probe(|this| {
1583             match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1584                 Ok(obligations) => {
1585                     this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1586                 }
1587                 Err(()) => Ok(EvaluatedToErr),
1588             }
1589         })
1590     }
1591
1592     fn assemble_generator_candidates(
1593         &mut self,
1594         obligation: &TraitObligation<'tcx>,
1595         candidates: &mut SelectionCandidateSet<'tcx>,
1596     ) -> Result<(), SelectionError<'tcx>> {
1597         if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1598             return Ok(());
1599         }
1600
1601         // Okay to skip binder because the substs on generator types never
1602         // touch bound regions, they just capture the in-scope
1603         // type/region parameters.
1604         let self_ty = *obligation.self_ty().skip_binder();
1605         match self_ty.kind {
1606             ty::Generator(..) => {
1607                 debug!(
1608                     "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1609                     self_ty, obligation
1610                 );
1611
1612                 candidates.vec.push(GeneratorCandidate);
1613             }
1614             ty::Infer(ty::TyVar(_)) => {
1615                 debug!("assemble_generator_candidates: ambiguous self-type");
1616                 candidates.ambiguous = true;
1617             }
1618             _ => {}
1619         }
1620
1621         Ok(())
1622     }
1623
1624     /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1625     /// FnMut<..>` where `X` is a closure type.
1626     ///
1627     /// Note: the type parameters on a closure candidate are modeled as *output* type
1628     /// parameters and hence do not affect whether this trait is a match or not. They will be
1629     /// unified during the confirmation step.
1630     fn assemble_closure_candidates(
1631         &mut self,
1632         obligation: &TraitObligation<'tcx>,
1633         candidates: &mut SelectionCandidateSet<'tcx>,
1634     ) -> Result<(), SelectionError<'tcx>> {
1635         let kind = match self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) {
1636             Some(k) => k,
1637             None => {
1638                 return Ok(());
1639             }
1640         };
1641
1642         // Okay to skip binder because the substs on closure types never
1643         // touch bound regions, they just capture the in-scope
1644         // type/region parameters
1645         match obligation.self_ty().skip_binder().kind {
1646             ty::Closure(_, closure_substs) => {
1647                 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}", kind, obligation);
1648                 match self.infcx.closure_kind(closure_substs) {
1649                     Some(closure_kind) => {
1650                         debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1651                         if closure_kind.extends(kind) {
1652                             candidates.vec.push(ClosureCandidate);
1653                         }
1654                     }
1655                     None => {
1656                         debug!("assemble_unboxed_candidates: closure_kind not yet known");
1657                         candidates.vec.push(ClosureCandidate);
1658                     }
1659                 }
1660             }
1661             ty::Infer(ty::TyVar(_)) => {
1662                 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1663                 candidates.ambiguous = true;
1664             }
1665             _ => {}
1666         }
1667
1668         Ok(())
1669     }
1670
1671     /// Implements one of the `Fn()` family for a fn pointer.
1672     fn assemble_fn_pointer_candidates(
1673         &mut self,
1674         obligation: &TraitObligation<'tcx>,
1675         candidates: &mut SelectionCandidateSet<'tcx>,
1676     ) -> Result<(), SelectionError<'tcx>> {
1677         // We provide impl of all fn traits for fn pointers.
1678         if self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()).is_none() {
1679             return Ok(());
1680         }
1681
1682         // Okay to skip binder because what we are inspecting doesn't involve bound regions.
1683         let self_ty = *obligation.self_ty().skip_binder();
1684         match self_ty.kind {
1685             ty::Infer(ty::TyVar(_)) => {
1686                 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1687                 candidates.ambiguous = true; // Could wind up being a fn() type.
1688             }
1689             // Provide an impl, but only for suitable `fn` pointers.
1690             ty::FnDef(..) | ty::FnPtr(_) => {
1691                 if let ty::FnSig {
1692                     unsafety: hir::Unsafety::Normal,
1693                     abi: Abi::Rust,
1694                     c_variadic: false,
1695                     ..
1696                 } = self_ty.fn_sig(self.tcx()).skip_binder()
1697                 {
1698                     candidates.vec.push(FnPointerCandidate);
1699                 }
1700             }
1701             _ => {}
1702         }
1703
1704         Ok(())
1705     }
1706
1707     /// Searches for impls that might apply to `obligation`.
1708     fn assemble_candidates_from_impls(
1709         &mut self,
1710         obligation: &TraitObligation<'tcx>,
1711         candidates: &mut SelectionCandidateSet<'tcx>,
1712     ) -> Result<(), SelectionError<'tcx>> {
1713         debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1714
1715         self.tcx().for_each_relevant_impl(
1716             obligation.predicate.def_id(),
1717             obligation.predicate.skip_binder().trait_ref.self_ty(),
1718             |impl_def_id| {
1719                 self.infcx.probe(|snapshot| {
1720                     if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot) {
1721                         candidates.vec.push(ImplCandidate(impl_def_id));
1722                     }
1723                 });
1724             },
1725         );
1726
1727         Ok(())
1728     }
1729
1730     fn assemble_candidates_from_auto_impls(
1731         &mut self,
1732         obligation: &TraitObligation<'tcx>,
1733         candidates: &mut SelectionCandidateSet<'tcx>,
1734     ) -> Result<(), SelectionError<'tcx>> {
1735         // Okay to skip binder here because the tests we do below do not involve bound regions.
1736         let self_ty = *obligation.self_ty().skip_binder();
1737         debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
1738
1739         let def_id = obligation.predicate.def_id();
1740
1741         if self.tcx().trait_is_auto(def_id) {
1742             match self_ty.kind {
1743                 ty::Dynamic(..) => {
1744                     // For object types, we don't know what the closed
1745                     // over types are. This means we conservatively
1746                     // say nothing; a candidate may be added by
1747                     // `assemble_candidates_from_object_ty`.
1748                 }
1749                 ty::Foreign(..) => {
1750                     // Since the contents of foreign types is unknown,
1751                     // we don't add any `..` impl. Default traits could
1752                     // still be provided by a manual implementation for
1753                     // this trait and type.
1754                 }
1755                 ty::Param(..) | ty::Projection(..) => {
1756                     // In these cases, we don't know what the actual
1757                     // type is.  Therefore, we cannot break it down
1758                     // into its constituent types. So we don't
1759                     // consider the `..` impl but instead just add no
1760                     // candidates: this means that typeck will only
1761                     // succeed if there is another reason to believe
1762                     // that this obligation holds. That could be a
1763                     // where-clause or, in the case of an object type,
1764                     // it could be that the object type lists the
1765                     // trait (e.g., `Foo+Send : Send`). See
1766                     // `compile-fail/typeck-default-trait-impl-send-param.rs`
1767                     // for an example of a test case that exercises
1768                     // this path.
1769                 }
1770                 ty::Infer(ty::TyVar(_)) => {
1771                     // The auto impl might apply; we don't know.
1772                     candidates.ambiguous = true;
1773                 }
1774                 ty::Generator(_, _, movability)
1775                     if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
1776                 {
1777                     match movability {
1778                         hir::Movability::Static => {
1779                             // Immovable generators are never `Unpin`, so
1780                             // suppress the normal auto-impl candidate for it.
1781                         }
1782                         hir::Movability::Movable => {
1783                             // Movable generators are always `Unpin`, so add an
1784                             // unconditional builtin candidate.
1785                             candidates.vec.push(BuiltinCandidate { has_nested: false });
1786                         }
1787                     }
1788                 }
1789
1790                 _ => candidates.vec.push(AutoImplCandidate(def_id)),
1791             }
1792         }
1793
1794         Ok(())
1795     }
1796
1797     /// Searches for impls that might apply to `obligation`.
1798     fn assemble_candidates_from_object_ty(
1799         &mut self,
1800         obligation: &TraitObligation<'tcx>,
1801         candidates: &mut SelectionCandidateSet<'tcx>,
1802     ) {
1803         debug!(
1804             "assemble_candidates_from_object_ty(self_ty={:?})",
1805             obligation.self_ty().skip_binder()
1806         );
1807
1808         self.infcx.probe(|_snapshot| {
1809             // The code below doesn't care about regions, and the
1810             // self-ty here doesn't escape this probe, so just erase
1811             // any LBR.
1812             let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
1813             let poly_trait_ref = match self_ty.kind {
1814                 ty::Dynamic(ref data, ..) => {
1815                     if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1816                         debug!(
1817                             "assemble_candidates_from_object_ty: matched builtin bound, \
1818                              pushing candidate"
1819                         );
1820                         candidates.vec.push(BuiltinObjectCandidate);
1821                         return;
1822                     }
1823
1824                     if let Some(principal) = data.principal() {
1825                         if !self.infcx.tcx.features().object_safe_for_dispatch {
1826                             principal.with_self_ty(self.tcx(), self_ty)
1827                         } else if self.tcx().is_object_safe(principal.def_id()) {
1828                             principal.with_self_ty(self.tcx(), self_ty)
1829                         } else {
1830                             return;
1831                         }
1832                     } else {
1833                         // Only auto trait bounds exist.
1834                         return;
1835                     }
1836                 }
1837                 ty::Infer(ty::TyVar(_)) => {
1838                     debug!("assemble_candidates_from_object_ty: ambiguous");
1839                     candidates.ambiguous = true; // could wind up being an object type
1840                     return;
1841                 }
1842                 _ => return,
1843             };
1844
1845             debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}", poly_trait_ref);
1846
1847             // Count only those upcast versions that match the trait-ref
1848             // we are looking for. Specifically, do not only check for the
1849             // correct trait, but also the correct type parameters.
1850             // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1851             // but `Foo` is declared as `trait Foo: Bar<u32>`.
1852             let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
1853                 .filter(|upcast_trait_ref| {
1854                     self.infcx
1855                         .probe(|_| self.match_poly_trait_ref(obligation, *upcast_trait_ref).is_ok())
1856                 })
1857                 .count();
1858
1859             if upcast_trait_refs > 1 {
1860                 // Can be upcast in many ways; need more type information.
1861                 candidates.ambiguous = true;
1862             } else if upcast_trait_refs == 1 {
1863                 candidates.vec.push(ObjectCandidate);
1864             }
1865         })
1866     }
1867
1868     /// Searches for unsizing that might apply to `obligation`.
1869     fn assemble_candidates_for_unsizing(
1870         &mut self,
1871         obligation: &TraitObligation<'tcx>,
1872         candidates: &mut SelectionCandidateSet<'tcx>,
1873     ) {
1874         // We currently never consider higher-ranked obligations e.g.
1875         // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1876         // because they are a priori invalid, and we could potentially add support
1877         // for them later, it's just that there isn't really a strong need for it.
1878         // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1879         // impl, and those are generally applied to concrete types.
1880         //
1881         // That said, one might try to write a fn with a where clause like
1882         //     for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1883         // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1884         // Still, you'd be more likely to write that where clause as
1885         //     T: Trait
1886         // so it seems ok if we (conservatively) fail to accept that `Unsize`
1887         // obligation above. Should be possible to extend this in the future.
1888         let source = match obligation.self_ty().no_bound_vars() {
1889             Some(t) => t,
1890             None => {
1891                 // Don't add any candidates if there are bound regions.
1892                 return;
1893             }
1894         };
1895         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1896
1897         debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})", source, target);
1898
1899         let may_apply = match (&source.kind, &target.kind) {
1900             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1901             (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
1902                 // Upcasts permit two things:
1903                 //
1904                 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
1905                 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
1906                 //
1907                 // Note that neither of these changes requires any
1908                 // change at runtime. Eventually this will be
1909                 // generalized.
1910                 //
1911                 // We always upcast when we can because of reason
1912                 // #2 (region bounds).
1913                 data_a.principal_def_id() == data_b.principal_def_id()
1914                     && data_b
1915                         .auto_traits()
1916                         // All of a's auto traits need to be in b's auto traits.
1917                         .all(|b| data_a.auto_traits().any(|a| a == b))
1918             }
1919
1920             // `T` -> `Trait`
1921             (_, &ty::Dynamic(..)) => true,
1922
1923             // Ambiguous handling is below `T` -> `Trait`, because inference
1924             // variables can still implement `Unsize<Trait>` and nested
1925             // obligations will have the final say (likely deferred).
1926             (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
1927                 debug!("assemble_candidates_for_unsizing: ambiguous");
1928                 candidates.ambiguous = true;
1929                 false
1930             }
1931
1932             // `[T; n]` -> `[T]`
1933             (&ty::Array(..), &ty::Slice(_)) => true,
1934
1935             // `Struct<T>` -> `Struct<U>`
1936             (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
1937                 def_id_a == def_id_b
1938             }
1939
1940             // `(.., T)` -> `(.., U)`
1941             (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
1942
1943             _ => false,
1944         };
1945
1946         if may_apply {
1947             candidates.vec.push(BuiltinUnsizeCandidate);
1948         }
1949     }
1950
1951     fn assemble_candidates_for_trait_alias(
1952         &mut self,
1953         obligation: &TraitObligation<'tcx>,
1954         candidates: &mut SelectionCandidateSet<'tcx>,
1955     ) -> Result<(), SelectionError<'tcx>> {
1956         // Okay to skip binder here because the tests we do below do not involve bound regions.
1957         let self_ty = *obligation.self_ty().skip_binder();
1958         debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
1959
1960         let def_id = obligation.predicate.def_id();
1961
1962         if self.tcx().is_trait_alias(def_id) {
1963             candidates.vec.push(TraitAliasCandidate(def_id));
1964         }
1965
1966         Ok(())
1967     }
1968
1969     ///////////////////////////////////////////////////////////////////////////
1970     // WINNOW
1971     //
1972     // Winnowing is the process of attempting to resolve ambiguity by
1973     // probing further. During the winnowing process, we unify all
1974     // type variables and then we also attempt to evaluate recursive
1975     // bounds to see if they are satisfied.
1976
1977     /// Returns `true` if `victim` should be dropped in favor of
1978     /// `other`. Generally speaking we will drop duplicate
1979     /// candidates and prefer where-clause candidates.
1980     ///
1981     /// See the comment for "SelectionCandidate" for more details.
1982     fn candidate_should_be_dropped_in_favor_of(
1983         &mut self,
1984         victim: &EvaluatedCandidate<'tcx>,
1985         other: &EvaluatedCandidate<'tcx>,
1986         needs_infer: bool,
1987     ) -> bool {
1988         if victim.candidate == other.candidate {
1989             return true;
1990         }
1991
1992         // Check if a bound would previously have been removed when normalizing
1993         // the param_env so that it can be given the lowest priority. See
1994         // #50825 for the motivation for this.
1995         let is_global =
1996             |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
1997
1998         match other.candidate {
1999             // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2000             // This is a fix for #53123 and prevents winnowing from accidentally extending the
2001             // lifetime of a variable.
2002             BuiltinCandidate { has_nested: false } => true,
2003             ParamCandidate(ref cand) => match victim.candidate {
2004                 AutoImplCandidate(..) => {
2005                     bug!(
2006                         "default implementations shouldn't be recorded \
2007                          when there are other valid candidates"
2008                     );
2009                 }
2010                 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2011                 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2012                 // lifetime of a variable.
2013                 BuiltinCandidate { has_nested: false } => false,
2014                 ImplCandidate(..)
2015                 | ClosureCandidate
2016                 | GeneratorCandidate
2017                 | FnPointerCandidate
2018                 | BuiltinObjectCandidate
2019                 | BuiltinUnsizeCandidate
2020                 | BuiltinCandidate { .. }
2021                 | TraitAliasCandidate(..) => {
2022                     // Global bounds from the where clause should be ignored
2023                     // here (see issue #50825). Otherwise, we have a where
2024                     // clause so don't go around looking for impls.
2025                     !is_global(cand)
2026                 }
2027                 ObjectCandidate | ProjectionCandidate => {
2028                     // Arbitrarily give param candidates priority
2029                     // over projection and object candidates.
2030                     !is_global(cand)
2031                 }
2032                 ParamCandidate(..) => false,
2033             },
2034             ObjectCandidate | ProjectionCandidate => match victim.candidate {
2035                 AutoImplCandidate(..) => {
2036                     bug!(
2037                         "default implementations shouldn't be recorded \
2038                          when there are other valid candidates"
2039                     );
2040                 }
2041                 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2042                 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2043                 // lifetime of a variable.
2044                 BuiltinCandidate { has_nested: false } => false,
2045                 ImplCandidate(..)
2046                 | ClosureCandidate
2047                 | GeneratorCandidate
2048                 | FnPointerCandidate
2049                 | BuiltinObjectCandidate
2050                 | BuiltinUnsizeCandidate
2051                 | BuiltinCandidate { .. }
2052                 | TraitAliasCandidate(..) => true,
2053                 ObjectCandidate | ProjectionCandidate => {
2054                     // Arbitrarily give param candidates priority
2055                     // over projection and object candidates.
2056                     true
2057                 }
2058                 ParamCandidate(ref cand) => is_global(cand),
2059             },
2060             ImplCandidate(other_def) => {
2061                 // See if we can toss out `victim` based on specialization.
2062                 // This requires us to know *for sure* that the `other` impl applies
2063                 // i.e., `EvaluatedToOk`.
2064                 if other.evaluation.must_apply_modulo_regions() {
2065                     match victim.candidate {
2066                         ImplCandidate(victim_def) => {
2067                             let tcx = self.tcx();
2068                             if tcx.specializes((other_def, victim_def)) {
2069                                 return true;
2070                             }
2071                             return match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
2072                                 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
2073                                     // Subtle: If the predicate we are evaluating has inference
2074                                     // variables, do *not* allow discarding candidates due to
2075                                     // marker trait impls.
2076                                     //
2077                                     // Without this restriction, we could end up accidentally
2078                                     // constrainting inference variables based on an arbitrarily
2079                                     // chosen trait impl.
2080                                     //
2081                                     // Imagine we have the following code:
2082                                     //
2083                                     // ```rust
2084                                     // #[marker] trait MyTrait {}
2085                                     // impl MyTrait for u8 {}
2086                                     // impl MyTrait for bool {}
2087                                     // ```
2088                                     //
2089                                     // And we are evaluating the predicate `<_#0t as MyTrait>`.
2090                                     //
2091                                     // During selection, we will end up with one candidate for each
2092                                     // impl of `MyTrait`. If we were to discard one impl in favor
2093                                     // of the other, we would be left with one candidate, causing
2094                                     // us to "successfully" select the predicate, unifying
2095                                     // _#0t with (for example) `u8`.
2096                                     //
2097                                     // However, we have no reason to believe that this unification
2098                                     // is correct - we've essentially just picked an arbitrary
2099                                     // *possibility* for _#0t, and required that this be the *only*
2100                                     // possibility.
2101                                     //
2102                                     // Eventually, we will either:
2103                                     // 1) Unify all inference variables in the predicate through
2104                                     // some other means (e.g. type-checking of a function). We will
2105                                     // then be in a position to drop marker trait candidates
2106                                     // without constraining inference variables (since there are
2107                                     // none left to constrin)
2108                                     // 2) Be left with some unconstrained inference variables. We
2109                                     // will then correctly report an inference error, since the
2110                                     // existence of multiple marker trait impls tells us nothing
2111                                     // about which one should actually apply.
2112                                     !needs_infer
2113                                 }
2114                                 Some(_) => true,
2115                                 None => false,
2116                             };
2117                         }
2118                         ParamCandidate(ref cand) => {
2119                             // Prefer the impl to a global where clause candidate.
2120                             return is_global(cand);
2121                         }
2122                         _ => (),
2123                     }
2124                 }
2125
2126                 false
2127             }
2128             ClosureCandidate
2129             | GeneratorCandidate
2130             | FnPointerCandidate
2131             | BuiltinObjectCandidate
2132             | BuiltinUnsizeCandidate
2133             | BuiltinCandidate { has_nested: true } => {
2134                 match victim.candidate {
2135                     ParamCandidate(ref cand) => {
2136                         // Prefer these to a global where-clause bound
2137                         // (see issue #50825).
2138                         is_global(cand) && other.evaluation.must_apply_modulo_regions()
2139                     }
2140                     _ => false,
2141                 }
2142             }
2143             _ => false,
2144         }
2145     }
2146
2147     ///////////////////////////////////////////////////////////////////////////
2148     // BUILTIN BOUNDS
2149     //
2150     // These cover the traits that are built-in to the language
2151     // itself: `Copy`, `Clone` and `Sized`.
2152
2153     fn assemble_builtin_bound_candidates(
2154         &mut self,
2155         conditions: BuiltinImplConditions<'tcx>,
2156         candidates: &mut SelectionCandidateSet<'tcx>,
2157     ) -> Result<(), SelectionError<'tcx>> {
2158         match conditions {
2159             BuiltinImplConditions::Where(nested) => {
2160                 debug!("builtin_bound: nested={:?}", nested);
2161                 candidates
2162                     .vec
2163                     .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
2164             }
2165             BuiltinImplConditions::None => {}
2166             BuiltinImplConditions::Ambiguous => {
2167                 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2168                 candidates.ambiguous = true;
2169             }
2170         }
2171
2172         Ok(())
2173     }
2174
2175     fn sized_conditions(
2176         &mut self,
2177         obligation: &TraitObligation<'tcx>,
2178     ) -> BuiltinImplConditions<'tcx> {
2179         use self::BuiltinImplConditions::{Ambiguous, None, Where};
2180
2181         // NOTE: binder moved to (*)
2182         let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2183
2184         match self_ty.kind {
2185             ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2186             | ty::Uint(_)
2187             | ty::Int(_)
2188             | ty::Bool
2189             | ty::Float(_)
2190             | ty::FnDef(..)
2191             | ty::FnPtr(_)
2192             | ty::RawPtr(..)
2193             | ty::Char
2194             | ty::Ref(..)
2195             | ty::Generator(..)
2196             | ty::GeneratorWitness(..)
2197             | ty::Array(..)
2198             | ty::Closure(..)
2199             | ty::Never
2200             | ty::Error => {
2201                 // safe for everything
2202                 Where(ty::Binder::dummy(Vec::new()))
2203             }
2204
2205             ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2206
2207             ty::Tuple(tys) => {
2208                 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2209             }
2210
2211             ty::Adt(def, substs) => {
2212                 let sized_crit = def.sized_constraint(self.tcx());
2213                 // (*) binder moved here
2214                 Where(ty::Binder::bind(
2215                     sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect(),
2216                 ))
2217             }
2218
2219             ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2220             ty::Infer(ty::TyVar(_)) => Ambiguous,
2221
2222             ty::Placeholder(..)
2223             | ty::Bound(..)
2224             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2225                 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2226             }
2227         }
2228     }
2229
2230     fn copy_clone_conditions(
2231         &mut self,
2232         obligation: &TraitObligation<'tcx>,
2233     ) -> BuiltinImplConditions<'tcx> {
2234         // NOTE: binder moved to (*)
2235         let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2236
2237         use self::BuiltinImplConditions::{Ambiguous, None, Where};
2238
2239         match self_ty.kind {
2240             ty::Infer(ty::IntVar(_))
2241             | ty::Infer(ty::FloatVar(_))
2242             | ty::FnDef(..)
2243             | ty::FnPtr(_)
2244             | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2245
2246             ty::Uint(_)
2247             | ty::Int(_)
2248             | ty::Bool
2249             | ty::Float(_)
2250             | ty::Char
2251             | ty::RawPtr(..)
2252             | ty::Never
2253             | ty::Ref(_, _, hir::Mutability::Not) => {
2254                 // Implementations provided in libcore
2255                 None
2256             }
2257
2258             ty::Dynamic(..)
2259             | ty::Str
2260             | ty::Slice(..)
2261             | ty::Generator(..)
2262             | ty::GeneratorWitness(..)
2263             | ty::Foreign(..)
2264             | ty::Ref(_, _, hir::Mutability::Mut) => None,
2265
2266             ty::Array(element_ty, _) => {
2267                 // (*) binder moved here
2268                 Where(ty::Binder::bind(vec![element_ty]))
2269             }
2270
2271             ty::Tuple(tys) => {
2272                 // (*) binder moved here
2273                 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2274             }
2275
2276             ty::Closure(_, substs) => {
2277                 // (*) binder moved here
2278                 Where(ty::Binder::bind(substs.as_closure().upvar_tys().collect()))
2279             }
2280
2281             ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2282                 // Fallback to whatever user-defined impls exist in this case.
2283                 None
2284             }
2285
2286             ty::Infer(ty::TyVar(_)) => {
2287                 // Unbound type variable. Might or might not have
2288                 // applicable impls and so forth, depending on what
2289                 // those type variables wind up being bound to.
2290                 Ambiguous
2291             }
2292
2293             ty::Placeholder(..)
2294             | ty::Bound(..)
2295             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2296                 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2297             }
2298         }
2299     }
2300
2301     /// For default impls, we need to break apart a type into its
2302     /// "constituent types" -- meaning, the types that it contains.
2303     ///
2304     /// Here are some (simple) examples:
2305     ///
2306     /// ```
2307     /// (i32, u32) -> [i32, u32]
2308     /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2309     /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2310     /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2311     /// ```
2312     fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2313         match t.kind {
2314             ty::Uint(_)
2315             | ty::Int(_)
2316             | ty::Bool
2317             | ty::Float(_)
2318             | ty::FnDef(..)
2319             | ty::FnPtr(_)
2320             | ty::Str
2321             | ty::Error
2322             | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2323             | ty::Never
2324             | ty::Char => Vec::new(),
2325
2326             ty::Placeholder(..)
2327             | ty::Dynamic(..)
2328             | ty::Param(..)
2329             | ty::Foreign(..)
2330             | ty::Projection(..)
2331             | ty::Bound(..)
2332             | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2333                 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2334             }
2335
2336             ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2337                 vec![element_ty]
2338             }
2339
2340             ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2341
2342             ty::Tuple(ref tys) => {
2343                 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2344                 tys.iter().map(|k| k.expect_ty()).collect()
2345             }
2346
2347             ty::Closure(_, ref substs) => substs.as_closure().upvar_tys().collect(),
2348
2349             ty::Generator(_, ref substs, _) => {
2350                 let witness = substs.as_generator().witness();
2351                 substs.as_generator().upvar_tys().chain(iter::once(witness)).collect()
2352             }
2353
2354             ty::GeneratorWitness(types) => {
2355                 // This is sound because no regions in the witness can refer to
2356                 // the binder outside the witness. So we'll effectivly reuse
2357                 // the implicit binder around the witness.
2358                 types.skip_binder().to_vec()
2359             }
2360
2361             // For `PhantomData<T>`, we pass `T`.
2362             ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2363
2364             ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2365
2366             ty::Opaque(def_id, substs) => {
2367                 // We can resolve the `impl Trait` to its concrete type,
2368                 // which enforces a DAG between the functions requiring
2369                 // the auto trait bounds in question.
2370                 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2371             }
2372         }
2373     }
2374
2375     fn collect_predicates_for_types(
2376         &mut self,
2377         param_env: ty::ParamEnv<'tcx>,
2378         cause: ObligationCause<'tcx>,
2379         recursion_depth: usize,
2380         trait_def_id: DefId,
2381         types: ty::Binder<Vec<Ty<'tcx>>>,
2382     ) -> Vec<PredicateObligation<'tcx>> {
2383         // Because the types were potentially derived from
2384         // higher-ranked obligations they may reference late-bound
2385         // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2386         // yield a type like `for<'a> &'a int`. In general, we
2387         // maintain the invariant that we never manipulate bound
2388         // regions, so we have to process these bound regions somehow.
2389         //
2390         // The strategy is to:
2391         //
2392         // 1. Instantiate those regions to placeholder regions (e.g.,
2393         //    `for<'a> &'a int` becomes `&0 int`.
2394         // 2. Produce something like `&'0 int : Copy`
2395         // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2396
2397         types
2398             .skip_binder()
2399             .iter()
2400             .flat_map(|ty| {
2401                 // binder moved -\
2402                 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2403
2404                 self.infcx.commit_unconditionally(|_| {
2405                     let (skol_ty, _) = self.infcx.replace_bound_vars_with_placeholders(&ty);
2406                     let Normalized { value: normalized_ty, mut obligations } =
2407                         ensure_sufficient_stack(|| {
2408                             project::normalize_with_depth(
2409                                 self,
2410                                 param_env,
2411                                 cause.clone(),
2412                                 recursion_depth,
2413                                 &skol_ty,
2414                             )
2415                         });
2416                     let skol_obligation = predicate_for_trait_def(
2417                         self.tcx(),
2418                         param_env,
2419                         cause.clone(),
2420                         trait_def_id,
2421                         recursion_depth,
2422                         normalized_ty,
2423                         &[],
2424                     );
2425                     obligations.push(skol_obligation);
2426                     obligations
2427                 })
2428             })
2429             .collect()
2430     }
2431
2432     ///////////////////////////////////////////////////////////////////////////
2433     // CONFIRMATION
2434     //
2435     // Confirmation unifies the output type parameters of the trait
2436     // with the values found in the obligation, possibly yielding a
2437     // type error.  See the [rustc dev guide] for more details.
2438     //
2439     // [rustc dev guide]:
2440     // https://rustc-dev-guide.rust-lang.org/traits/resolution.html#confirmation
2441
2442     fn confirm_candidate(
2443         &mut self,
2444         obligation: &TraitObligation<'tcx>,
2445         candidate: SelectionCandidate<'tcx>,
2446     ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2447         debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2448
2449         match candidate {
2450             BuiltinCandidate { has_nested } => {
2451                 let data = self.confirm_builtin_candidate(obligation, has_nested);
2452                 Ok(VtableBuiltin(data))
2453             }
2454
2455             ParamCandidate(param) => {
2456                 let obligations = self.confirm_param_candidate(obligation, param);
2457                 Ok(VtableParam(obligations))
2458             }
2459
2460             ImplCandidate(impl_def_id) => {
2461                 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2462             }
2463
2464             AutoImplCandidate(trait_def_id) => {
2465                 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2466                 Ok(VtableAutoImpl(data))
2467             }
2468
2469             ProjectionCandidate => {
2470                 self.confirm_projection_candidate(obligation);
2471                 Ok(VtableParam(Vec::new()))
2472             }
2473
2474             ClosureCandidate => {
2475                 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2476                 Ok(VtableClosure(vtable_closure))
2477             }
2478
2479             GeneratorCandidate => {
2480                 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2481                 Ok(VtableGenerator(vtable_generator))
2482             }
2483
2484             FnPointerCandidate => {
2485                 let data = self.confirm_fn_pointer_candidate(obligation)?;
2486                 Ok(VtableFnPointer(data))
2487             }
2488
2489             TraitAliasCandidate(alias_def_id) => {
2490                 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2491                 Ok(VtableTraitAlias(data))
2492             }
2493
2494             ObjectCandidate => {
2495                 let data = self.confirm_object_candidate(obligation);
2496                 Ok(VtableObject(data))
2497             }
2498
2499             BuiltinObjectCandidate => {
2500                 // This indicates something like `Trait + Send: Send`. In this case, we know that
2501                 // this holds because that's what the object type is telling us, and there's really
2502                 // no additional obligations to prove and no types in particular to unify, etc.
2503                 Ok(VtableParam(Vec::new()))
2504             }
2505
2506             BuiltinUnsizeCandidate => {
2507                 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2508                 Ok(VtableBuiltin(data))
2509             }
2510         }
2511     }
2512
2513     fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2514         self.infcx.commit_unconditionally(|snapshot| {
2515             let result =
2516                 self.match_projection_obligation_against_definition_bounds(obligation, snapshot);
2517             assert!(result);
2518         })
2519     }
2520
2521     fn confirm_param_candidate(
2522         &mut self,
2523         obligation: &TraitObligation<'tcx>,
2524         param: ty::PolyTraitRef<'tcx>,
2525     ) -> Vec<PredicateObligation<'tcx>> {
2526         debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2527
2528         // During evaluation, we already checked that this
2529         // where-clause trait-ref could be unified with the obligation
2530         // trait-ref. Repeat that unification now without any
2531         // transactional boundary; it should not fail.
2532         match self.match_where_clause_trait_ref(obligation, param) {
2533             Ok(obligations) => obligations,
2534             Err(()) => {
2535                 bug!(
2536                     "Where clause `{:?}` was applicable to `{:?}` but now is not",
2537                     param,
2538                     obligation
2539                 );
2540             }
2541         }
2542     }
2543
2544     fn confirm_builtin_candidate(
2545         &mut self,
2546         obligation: &TraitObligation<'tcx>,
2547         has_nested: bool,
2548     ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2549         debug!("confirm_builtin_candidate({:?}, {:?})", obligation, has_nested);
2550
2551         let lang_items = self.tcx().lang_items();
2552         let obligations = if has_nested {
2553             let trait_def = obligation.predicate.def_id();
2554             let conditions = if Some(trait_def) == lang_items.sized_trait() {
2555                 self.sized_conditions(obligation)
2556             } else if Some(trait_def) == lang_items.copy_trait() {
2557                 self.copy_clone_conditions(obligation)
2558             } else if Some(trait_def) == lang_items.clone_trait() {
2559                 self.copy_clone_conditions(obligation)
2560             } else {
2561                 bug!("unexpected builtin trait {:?}", trait_def)
2562             };
2563             let nested = match conditions {
2564                 BuiltinImplConditions::Where(nested) => nested,
2565                 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation),
2566             };
2567
2568             let cause = obligation.derived_cause(BuiltinDerivedObligation);
2569             ensure_sufficient_stack(|| {
2570                 self.collect_predicates_for_types(
2571                     obligation.param_env,
2572                     cause,
2573                     obligation.recursion_depth + 1,
2574                     trait_def,
2575                     nested,
2576                 )
2577             })
2578         } else {
2579             vec![]
2580         };
2581
2582         debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2583
2584         VtableBuiltinData { nested: obligations }
2585     }
2586
2587     /// This handles the case where a `auto trait Foo` impl is being used.
2588     /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2589     ///
2590     /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2591     /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2592     fn confirm_auto_impl_candidate(
2593         &mut self,
2594         obligation: &TraitObligation<'tcx>,
2595         trait_def_id: DefId,
2596     ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2597         debug!("confirm_auto_impl_candidate({:?}, {:?})", obligation, trait_def_id);
2598
2599         let types = obligation.predicate.map_bound(|inner| {
2600             let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2601             self.constituent_types_for_ty(self_ty)
2602         });
2603         self.vtable_auto_impl(obligation, trait_def_id, types)
2604     }
2605
2606     /// See `confirm_auto_impl_candidate`.
2607     fn vtable_auto_impl(
2608         &mut self,
2609         obligation: &TraitObligation<'tcx>,
2610         trait_def_id: DefId,
2611         nested: ty::Binder<Vec<Ty<'tcx>>>,
2612     ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2613         debug!("vtable_auto_impl: nested={:?}", nested);
2614         ensure_sufficient_stack(|| {
2615             let cause = obligation.derived_cause(BuiltinDerivedObligation);
2616             let mut obligations = self.collect_predicates_for_types(
2617                 obligation.param_env,
2618                 cause,
2619                 obligation.recursion_depth + 1,
2620                 trait_def_id,
2621                 nested,
2622             );
2623
2624             let trait_obligations: Vec<PredicateObligation<'_>> =
2625                 self.infcx.commit_unconditionally(|_| {
2626                     let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2627                     let (trait_ref, _) =
2628                         self.infcx.replace_bound_vars_with_placeholders(&poly_trait_ref);
2629                     let cause = obligation.derived_cause(ImplDerivedObligation);
2630                     self.impl_or_trait_obligations(
2631                         cause,
2632                         obligation.recursion_depth + 1,
2633                         obligation.param_env,
2634                         trait_def_id,
2635                         &trait_ref.substs,
2636                     )
2637                 });
2638
2639             // Adds the predicates from the trait.  Note that this contains a `Self: Trait`
2640             // predicate as usual.  It won't have any effect since auto traits are coinductive.
2641             obligations.extend(trait_obligations);
2642
2643             debug!("vtable_auto_impl: obligations={:?}", obligations);
2644
2645             VtableAutoImplData { trait_def_id, nested: obligations }
2646         })
2647     }
2648
2649     fn confirm_impl_candidate(
2650         &mut self,
2651         obligation: &TraitObligation<'tcx>,
2652         impl_def_id: DefId,
2653     ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2654         debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
2655
2656         // First, create the substitutions by matching the impl again,
2657         // this time not in a probe.
2658         self.infcx.commit_unconditionally(|snapshot| {
2659             let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
2660             debug!("confirm_impl_candidate: substs={:?}", substs);
2661             let cause = obligation.derived_cause(ImplDerivedObligation);
2662             ensure_sufficient_stack(|| {
2663                 self.vtable_impl(
2664                     impl_def_id,
2665                     substs,
2666                     cause,
2667                     obligation.recursion_depth + 1,
2668                     obligation.param_env,
2669                 )
2670             })
2671         })
2672     }
2673
2674     fn vtable_impl(
2675         &mut self,
2676         impl_def_id: DefId,
2677         mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
2678         cause: ObligationCause<'tcx>,
2679         recursion_depth: usize,
2680         param_env: ty::ParamEnv<'tcx>,
2681     ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2682         debug!(
2683             "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
2684             impl_def_id, substs, recursion_depth,
2685         );
2686
2687         let mut impl_obligations = self.impl_or_trait_obligations(
2688             cause,
2689             recursion_depth,
2690             param_env,
2691             impl_def_id,
2692             &substs.value,
2693         );
2694
2695         debug!(
2696             "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2697             impl_def_id, impl_obligations
2698         );
2699
2700         // Because of RFC447, the impl-trait-ref and obligations
2701         // are sufficient to determine the impl substs, without
2702         // relying on projections in the impl-trait-ref.
2703         //
2704         // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2705         impl_obligations.append(&mut substs.obligations);
2706
2707         VtableImplData { impl_def_id, substs: substs.value, nested: impl_obligations }
2708     }
2709
2710     fn confirm_object_candidate(
2711         &mut self,
2712         obligation: &TraitObligation<'tcx>,
2713     ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
2714         debug!("confirm_object_candidate({:?})", obligation);
2715
2716         // FIXME(nmatsakis) skipping binder here seems wrong -- we should
2717         // probably flatten the binder from the obligation and the binder
2718         // from the object. Have to try to make a broken test case that
2719         // results.
2720         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2721         let poly_trait_ref = match self_ty.kind {
2722             ty::Dynamic(ref data, ..) => data
2723                 .principal()
2724                 .unwrap_or_else(|| {
2725                     span_bug!(obligation.cause.span, "object candidate with no principal")
2726                 })
2727                 .with_self_ty(self.tcx(), self_ty),
2728             _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
2729         };
2730
2731         let mut upcast_trait_ref = None;
2732         let mut nested = vec![];
2733         let vtable_base;
2734
2735         {
2736             let tcx = self.tcx();
2737
2738             // We want to find the first supertrait in the list of
2739             // supertraits that we can unify with, and do that
2740             // unification. We know that there is exactly one in the list
2741             // where we can unify, because otherwise select would have
2742             // reported an ambiguity. (When we do find a match, also
2743             // record it for later.)
2744             let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(|&t| {
2745                 match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
2746                     Ok(obligations) => {
2747                         upcast_trait_ref = Some(t);
2748                         nested.extend(obligations);
2749                         false
2750                     }
2751                     Err(_) => true,
2752                 }
2753             });
2754
2755             // Additionally, for each of the non-matching predicates that
2756             // we pass over, we sum up the set of number of vtable
2757             // entries, so that we can compute the offset for the selected
2758             // trait.
2759             vtable_base = nonmatching.map(|t| super::util::count_own_vtable_entries(tcx, t)).sum();
2760         }
2761
2762         VtableObjectData { upcast_trait_ref: upcast_trait_ref.unwrap(), vtable_base, nested }
2763     }
2764
2765     fn confirm_fn_pointer_candidate(
2766         &mut self,
2767         obligation: &TraitObligation<'tcx>,
2768     ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2769         debug!("confirm_fn_pointer_candidate({:?})", obligation);
2770
2771         // Okay to skip binder; it is reintroduced below.
2772         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2773         let sig = self_ty.fn_sig(self.tcx());
2774         let trait_ref = closure_trait_ref_and_return_type(
2775             self.tcx(),
2776             obligation.predicate.def_id(),
2777             self_ty,
2778             sig,
2779             util::TupleArgumentsFlag::Yes,
2780         )
2781         .map_bound(|(trait_ref, _)| trait_ref);
2782
2783         let Normalized { value: trait_ref, obligations } = ensure_sufficient_stack(|| {
2784             project::normalize_with_depth(
2785                 self,
2786                 obligation.param_env,
2787                 obligation.cause.clone(),
2788                 obligation.recursion_depth + 1,
2789                 &trait_ref,
2790             )
2791         });
2792
2793         self.confirm_poly_trait_refs(
2794             obligation.cause.clone(),
2795             obligation.param_env,
2796             obligation.predicate.to_poly_trait_ref(),
2797             trait_ref,
2798         )?;
2799         Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2800     }
2801
2802     fn confirm_trait_alias_candidate(
2803         &mut self,
2804         obligation: &TraitObligation<'tcx>,
2805         alias_def_id: DefId,
2806     ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
2807         debug!("confirm_trait_alias_candidate({:?}, {:?})", obligation, alias_def_id);
2808
2809         self.infcx.commit_unconditionally(|_| {
2810             let (predicate, _) =
2811                 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
2812             let trait_ref = predicate.trait_ref;
2813             let trait_def_id = trait_ref.def_id;
2814             let substs = trait_ref.substs;
2815
2816             let trait_obligations = self.impl_or_trait_obligations(
2817                 obligation.cause.clone(),
2818                 obligation.recursion_depth,
2819                 obligation.param_env,
2820                 trait_def_id,
2821                 &substs,
2822             );
2823
2824             debug!(
2825                 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
2826                 trait_def_id, trait_obligations
2827             );
2828
2829             VtableTraitAliasData { alias_def_id, substs, nested: trait_obligations }
2830         })
2831     }
2832
2833     fn confirm_generator_candidate(
2834         &mut self,
2835         obligation: &TraitObligation<'tcx>,
2836     ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2837         // Okay to skip binder because the substs on generator types never
2838         // touch bound regions, they just capture the in-scope
2839         // type/region parameters.
2840         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2841         let (generator_def_id, substs) = match self_ty.kind {
2842             ty::Generator(id, substs, _) => (id, substs),
2843             _ => bug!("closure candidate for non-closure {:?}", obligation),
2844         };
2845
2846         debug!("confirm_generator_candidate({:?},{:?},{:?})", obligation, generator_def_id, substs);
2847
2848         let trait_ref = self.generator_trait_ref_unnormalized(obligation, substs);
2849         let Normalized { value: trait_ref, mut obligations } = ensure_sufficient_stack(|| {
2850             normalize_with_depth(
2851                 self,
2852                 obligation.param_env,
2853                 obligation.cause.clone(),
2854                 obligation.recursion_depth + 1,
2855                 &trait_ref,
2856             )
2857         });
2858
2859         debug!(
2860             "confirm_generator_candidate(generator_def_id={:?}, \
2861              trait_ref={:?}, obligations={:?})",
2862             generator_def_id, trait_ref, obligations
2863         );
2864
2865         obligations.extend(self.confirm_poly_trait_refs(
2866             obligation.cause.clone(),
2867             obligation.param_env,
2868             obligation.predicate.to_poly_trait_ref(),
2869             trait_ref,
2870         )?);
2871
2872         Ok(VtableGeneratorData { generator_def_id, substs, nested: obligations })
2873     }
2874
2875     fn confirm_closure_candidate(
2876         &mut self,
2877         obligation: &TraitObligation<'tcx>,
2878     ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2879         debug!("confirm_closure_candidate({:?})", obligation);
2880
2881         let kind = self
2882             .tcx()
2883             .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
2884             .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
2885
2886         // Okay to skip binder because the substs on closure types never
2887         // touch bound regions, they just capture the in-scope
2888         // type/region parameters.
2889         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2890         let (closure_def_id, substs) = match self_ty.kind {
2891             ty::Closure(id, substs) => (id, substs),
2892             _ => bug!("closure candidate for non-closure {:?}", obligation),
2893         };
2894
2895         let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
2896         let Normalized { value: trait_ref, mut obligations } = ensure_sufficient_stack(|| {
2897             normalize_with_depth(
2898                 self,
2899                 obligation.param_env,
2900                 obligation.cause.clone(),
2901                 obligation.recursion_depth + 1,
2902                 &trait_ref,
2903             )
2904         });
2905
2906         debug!(
2907             "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2908             closure_def_id, trait_ref, obligations
2909         );
2910
2911         obligations.extend(self.confirm_poly_trait_refs(
2912             obligation.cause.clone(),
2913             obligation.param_env,
2914             obligation.predicate.to_poly_trait_ref(),
2915             trait_ref,
2916         )?);
2917
2918         // FIXME: Chalk
2919
2920         if !self.tcx().sess.opts.debugging_opts.chalk {
2921             obligations.push(Obligation::new(
2922                 obligation.cause.clone(),
2923                 obligation.param_env,
2924                 ty::PredicateKind::ClosureKind(closure_def_id, substs, kind),
2925             ));
2926         }
2927
2928         Ok(VtableClosureData { closure_def_id, substs, nested: obligations })
2929     }
2930
2931     /// In the case of closure types and fn pointers,
2932     /// we currently treat the input type parameters on the trait as
2933     /// outputs. This means that when we have a match we have only
2934     /// considered the self type, so we have to go back and make sure
2935     /// to relate the argument types too. This is kind of wrong, but
2936     /// since we control the full set of impls, also not that wrong,
2937     /// and it DOES yield better error messages (since we don't report
2938     /// errors as if there is no applicable impl, but rather report
2939     /// errors are about mismatched argument types.
2940     ///
2941     /// Here is an example. Imagine we have a closure expression
2942     /// and we desugared it so that the type of the expression is
2943     /// `Closure`, and `Closure` expects an int as argument. Then it
2944     /// is "as if" the compiler generated this impl:
2945     ///
2946     ///     impl Fn(int) for Closure { ... }
2947     ///
2948     /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2949     /// we have matched the self type `Closure`. At this point we'll
2950     /// compare the `int` to `usize` and generate an error.
2951     ///
2952     /// Note that this checking occurs *after* the impl has selected,
2953     /// because these output type parameters should not affect the
2954     /// selection of the impl. Therefore, if there is a mismatch, we
2955     /// report an error to the user.
2956     fn confirm_poly_trait_refs(
2957         &mut self,
2958         obligation_cause: ObligationCause<'tcx>,
2959         obligation_param_env: ty::ParamEnv<'tcx>,
2960         obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2961         expected_trait_ref: ty::PolyTraitRef<'tcx>,
2962     ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2963         self.infcx
2964             .at(&obligation_cause, obligation_param_env)
2965             .sup(obligation_trait_ref, expected_trait_ref)
2966             .map(|InferOk { obligations, .. }| obligations)
2967             .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2968     }
2969
2970     fn confirm_builtin_unsize_candidate(
2971         &mut self,
2972         obligation: &TraitObligation<'tcx>,
2973     ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
2974         let tcx = self.tcx();
2975
2976         // `assemble_candidates_for_unsizing` should ensure there are no late-bound
2977         // regions here. See the comment there for more details.
2978         let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
2979         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2980         let target = self.infcx.shallow_resolve(target);
2981
2982         debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})", source, target);
2983
2984         let mut nested = vec![];
2985         match (&source.kind, &target.kind) {
2986             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2987             (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
2988                 // See `assemble_candidates_for_unsizing` for more info.
2989                 let existential_predicates = data_a.map_bound(|data_a| {
2990                     let iter = data_a
2991                         .principal()
2992                         .map(ty::ExistentialPredicate::Trait)
2993                         .into_iter()
2994                         .chain(data_a.projection_bounds().map(ty::ExistentialPredicate::Projection))
2995                         .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2996                     tcx.mk_existential_predicates(iter)
2997                 });
2998                 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
2999
3000                 // Require that the traits involved in this upcast are **equal**;
3001                 // only the **lifetime bound** is changed.
3002                 //
3003                 // FIXME: This condition is arguably too strong -- it would
3004                 // suffice for the source trait to be a *subtype* of the target
3005                 // trait. In particular, changing from something like
3006                 // `for<'a, 'b> Foo<'a, 'b>` to `for<'a> Foo<'a, 'a>` should be
3007                 // permitted. And, indeed, in the in commit
3008                 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3009                 // condition was loosened. However, when the leak check was
3010                 // added back, using subtype here actually guides the coercion
3011                 // code in such a way that it accepts `old-lub-glb-object.rs`.
3012                 // This is probably a good thing, but I've modified this to `.eq`
3013                 // because I want to continue rejecting that test (as we have
3014                 // done for quite some time) before we are firmly comfortable
3015                 // with what our behavior should be there. -nikomatsakis
3016                 let InferOk { obligations, .. } = self
3017                     .infcx
3018                     .at(&obligation.cause, obligation.param_env)
3019                     .eq(target, source_trait) // FIXME -- see below
3020                     .map_err(|_| Unimplemented)?;
3021                 nested.extend(obligations);
3022
3023                 // Register one obligation for 'a: 'b.
3024                 let cause = ObligationCause::new(
3025                     obligation.cause.span,
3026                     obligation.cause.body_id,
3027                     ObjectCastObligation(target),
3028                 );
3029                 let outlives = ty::OutlivesPredicate(r_a, r_b);
3030                 nested.push(Obligation::with_depth(
3031                     cause,
3032                     obligation.recursion_depth + 1,
3033                     obligation.param_env,
3034                     ty::Binder::bind(outlives).to_predicate(),
3035                 ));
3036             }
3037
3038             // `T` -> `Trait`
3039             (_, &ty::Dynamic(ref data, r)) => {
3040                 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
3041                 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3042                     return Err(TraitNotObjectSafe(did));
3043                 }
3044
3045                 let cause = ObligationCause::new(
3046                     obligation.cause.span,
3047                     obligation.cause.body_id,
3048                     ObjectCastObligation(target),
3049                 );
3050
3051                 let predicate_to_obligation = |predicate| {
3052                     Obligation::with_depth(
3053                         cause.clone(),
3054                         obligation.recursion_depth + 1,
3055                         obligation.param_env,
3056                         predicate,
3057                     )
3058                 };
3059
3060                 // Create obligations:
3061                 //  - Casting `T` to `Trait`
3062                 //  - For all the various builtin bounds attached to the object cast. (In other
3063                 //  words, if the object type is `Foo + Send`, this would create an obligation for
3064                 //  the `Send` check.)
3065                 //  - Projection predicates
3066                 nested.extend(
3067                     data.iter().map(|predicate| {
3068                         predicate_to_obligation(predicate.with_self_ty(tcx, source))
3069                     }),
3070                 );
3071
3072                 // We can only make objects from sized types.
3073                 let tr = ty::TraitRef::new(
3074                     tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
3075                     tcx.mk_substs_trait(source, &[]),
3076                 );
3077                 nested.push(predicate_to_obligation(tr.without_const().to_predicate()));
3078
3079                 // If the type is `Foo + 'a`, ensure that the type
3080                 // being cast to `Foo + 'a` outlives `'a`:
3081                 let outlives = ty::OutlivesPredicate(source, r);
3082                 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate()));
3083             }
3084
3085             // `[T; n]` -> `[T]`
3086             (&ty::Array(a, _), &ty::Slice(b)) => {
3087                 let InferOk { obligations, .. } = self
3088                     .infcx
3089                     .at(&obligation.cause, obligation.param_env)
3090                     .eq(b, a)
3091                     .map_err(|_| Unimplemented)?;
3092                 nested.extend(obligations);
3093             }
3094
3095             // `Struct<T>` -> `Struct<U>`
3096             (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3097                 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
3098                     GenericArgKind::Type(ty) => match ty.kind {
3099                         ty::Param(p) => Some(p.index),
3100                         _ => None,
3101                     },
3102
3103                     // Lifetimes aren't allowed to change during unsizing.
3104                     GenericArgKind::Lifetime(_) => None,
3105
3106                     GenericArgKind::Const(ct) => match ct.val {
3107                         ty::ConstKind::Param(p) => Some(p.index),
3108                         _ => None,
3109                     },
3110                 };
3111
3112                 // The last field of the structure has to exist and contain type/const parameters.
3113                 let (tail_field, prefix_fields) =
3114                     def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
3115                 let tail_field_ty = tcx.type_of(tail_field.did);
3116
3117                 let mut unsizing_params = GrowableBitSet::new_empty();
3118                 let mut found = false;
3119                 for arg in tail_field_ty.walk() {
3120                     if let Some(i) = maybe_unsizing_param_idx(arg) {
3121                         unsizing_params.insert(i);
3122                         found = true;
3123                     }
3124                 }
3125                 if !found {
3126                     return Err(Unimplemented);
3127                 }
3128
3129                 // Ensure none of the other fields mention the parameters used
3130                 // in unsizing.
3131                 // FIXME(eddyb) cache this (including computing `unsizing_params`)
3132                 // by putting it in a query; it would only need the `DefId` as it
3133                 // looks at declared field types, not anything substituted.
3134                 for field in prefix_fields {
3135                     for arg in tcx.type_of(field.did).walk() {
3136                         if let Some(i) = maybe_unsizing_param_idx(arg) {
3137                             if unsizing_params.contains(i) {
3138                                 return Err(Unimplemented);
3139                             }
3140                         }
3141                     }
3142                 }
3143
3144                 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`.
3145                 let source_tail = tail_field_ty.subst(tcx, substs_a);
3146                 let target_tail = tail_field_ty.subst(tcx, substs_b);
3147
3148                 // Check that the source struct with the target's
3149                 // unsizing parameters is equal to the target.
3150                 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, &k)| {
3151                     if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
3152                 }));
3153                 let new_struct = tcx.mk_adt(def, substs);
3154                 let InferOk { obligations, .. } = self
3155                     .infcx
3156                     .at(&obligation.cause, obligation.param_env)
3157                     .eq(target, new_struct)
3158                     .map_err(|_| Unimplemented)?;
3159                 nested.extend(obligations);
3160
3161                 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
3162                 nested.push(predicate_for_trait_def(
3163                     tcx,
3164                     obligation.param_env,
3165                     obligation.cause.clone(),
3166                     obligation.predicate.def_id(),
3167                     obligation.recursion_depth + 1,
3168                     source_tail,
3169                     &[target_tail.into()],
3170                 ));
3171             }
3172
3173             // `(.., T)` -> `(.., U)`
3174             (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3175                 assert_eq!(tys_a.len(), tys_b.len());
3176
3177                 // The last field of the tuple has to exist.
3178                 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3179                     x
3180                 } else {
3181                     return Err(Unimplemented);
3182                 };
3183                 let &b_last = tys_b.last().unwrap();
3184
3185                 // Check that the source tuple with the target's
3186                 // last element is equal to the target.
3187                 let new_tuple = tcx.mk_tup(
3188                     a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3189                 );
3190                 let InferOk { obligations, .. } = self
3191                     .infcx
3192                     .at(&obligation.cause, obligation.param_env)
3193                     .eq(target, new_tuple)
3194                     .map_err(|_| Unimplemented)?;
3195                 nested.extend(obligations);
3196
3197                 // Construct the nested `T: Unsize<U>` predicate.
3198                 nested.push(ensure_sufficient_stack(|| {
3199                     predicate_for_trait_def(
3200                         tcx,
3201                         obligation.param_env,
3202                         obligation.cause.clone(),
3203                         obligation.predicate.def_id(),
3204                         obligation.recursion_depth + 1,
3205                         a_last.expect_ty(),
3206                         &[b_last],
3207                     )
3208                 }));
3209             }
3210
3211             _ => bug!(),
3212         };
3213
3214         Ok(VtableBuiltinData { nested })
3215     }
3216
3217     ///////////////////////////////////////////////////////////////////////////
3218     // Matching
3219     //
3220     // Matching is a common path used for both evaluation and
3221     // confirmation.  It basically unifies types that appear in impls
3222     // and traits. This does affect the surrounding environment;
3223     // therefore, when used during evaluation, match routines must be
3224     // run inside of a `probe()` so that their side-effects are
3225     // contained.
3226
3227     fn rematch_impl(
3228         &mut self,
3229         impl_def_id: DefId,
3230         obligation: &TraitObligation<'tcx>,
3231         snapshot: &CombinedSnapshot<'_, 'tcx>,
3232     ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3233         match self.match_impl(impl_def_id, obligation, snapshot) {
3234             Ok(substs) => substs,
3235             Err(()) => {
3236                 bug!(
3237                     "Impl {:?} was matchable against {:?} but now is not",
3238                     impl_def_id,
3239                     obligation
3240                 );
3241             }
3242         }
3243     }
3244
3245     fn match_impl(
3246         &mut self,
3247         impl_def_id: DefId,
3248         obligation: &TraitObligation<'tcx>,
3249         snapshot: &CombinedSnapshot<'_, 'tcx>,
3250     ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3251         let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3252
3253         // Before we create the substitutions and everything, first
3254         // consider a "quick reject". This avoids creating more types
3255         // and so forth that we need to.
3256         if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3257             return Err(());
3258         }
3259
3260         let (skol_obligation, placeholder_map) =
3261             self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
3262         let skol_obligation_trait_ref = skol_obligation.trait_ref;
3263
3264         let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
3265
3266         let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3267
3268         let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
3269             ensure_sufficient_stack(|| {
3270                 project::normalize_with_depth(
3271                     self,
3272                     obligation.param_env,
3273                     obligation.cause.clone(),
3274                     obligation.recursion_depth + 1,
3275                     &impl_trait_ref,
3276                 )
3277             });
3278
3279         debug!(
3280             "match_impl(impl_def_id={:?}, obligation={:?}, \
3281              impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3282             impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3283         );
3284
3285         let InferOk { obligations, .. } = self
3286             .infcx
3287             .at(&obligation.cause, obligation.param_env)
3288             .eq(skol_obligation_trait_ref, impl_trait_ref)
3289             .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3290         nested_obligations.extend(obligations);
3291
3292         if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3293             debug!("match_impl: failed leak check due to `{}`", e);
3294             return Err(());
3295         }
3296
3297         if !self.intercrate
3298             && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
3299         {
3300             debug!("match_impl: reservation impls only apply in intercrate mode");
3301             return Err(());
3302         }
3303
3304         debug!("match_impl: success impl_substs={:?}", impl_substs);
3305         Ok(Normalized { value: impl_substs, obligations: nested_obligations })
3306     }
3307
3308     fn fast_reject_trait_refs(
3309         &mut self,
3310         obligation: &TraitObligation<'_>,
3311         impl_trait_ref: &ty::TraitRef<'_>,
3312     ) -> bool {
3313         // We can avoid creating type variables and doing the full
3314         // substitution if we find that any of the input types, when
3315         // simplified, do not match.
3316
3317         obligation.predicate.skip_binder().trait_ref.substs.iter().zip(impl_trait_ref.substs).any(
3318             |(obligation_arg, impl_arg)| {
3319                 match (obligation_arg.unpack(), impl_arg.unpack()) {
3320                     (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
3321                         let simplified_obligation_ty =
3322                             fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3323                         let simplified_impl_ty =
3324                             fast_reject::simplify_type(self.tcx(), impl_ty, false);
3325
3326                         simplified_obligation_ty.is_some()
3327                             && simplified_impl_ty.is_some()
3328                             && simplified_obligation_ty != simplified_impl_ty
3329                     }
3330                     (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
3331                         // Lifetimes can never cause a rejection.
3332                         false
3333                     }
3334                     (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
3335                         // Conservatively ignore consts (i.e. assume they might
3336                         // unify later) until we have `fast_reject` support for
3337                         // them (if we'll ever need it, even).
3338                         false
3339                     }
3340                     _ => unreachable!(),
3341                 }
3342             },
3343         )
3344     }
3345
3346     /// Normalize `where_clause_trait_ref` and try to match it against
3347     /// `obligation`. If successful, return any predicates that
3348     /// result from the normalization. Normalization is necessary
3349     /// because where-clauses are stored in the parameter environment
3350     /// unnormalized.
3351     fn match_where_clause_trait_ref(
3352         &mut self,
3353         obligation: &TraitObligation<'tcx>,
3354         where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3355     ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3356         self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3357     }
3358
3359     /// Returns `Ok` if `poly_trait_ref` being true implies that the
3360     /// obligation is satisfied.
3361     fn match_poly_trait_ref(
3362         &mut self,
3363         obligation: &TraitObligation<'tcx>,
3364         poly_trait_ref: ty::PolyTraitRef<'tcx>,
3365     ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3366         debug!(
3367             "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3368             obligation, poly_trait_ref
3369         );
3370
3371         self.infcx
3372             .at(&obligation.cause, obligation.param_env)
3373             .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3374             .map(|InferOk { obligations, .. }| obligations)
3375             .map_err(|_| ())
3376     }
3377
3378     ///////////////////////////////////////////////////////////////////////////
3379     // Miscellany
3380
3381     fn match_fresh_trait_refs(
3382         &self,
3383         previous: &ty::PolyTraitRef<'tcx>,
3384         current: &ty::PolyTraitRef<'tcx>,
3385         param_env: ty::ParamEnv<'tcx>,
3386     ) -> bool {
3387         let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
3388         matcher.relate(previous, current).is_ok()
3389     }
3390
3391     fn push_stack<'o>(
3392         &mut self,
3393         previous_stack: TraitObligationStackList<'o, 'tcx>,
3394         obligation: &'o TraitObligation<'tcx>,
3395     ) -> TraitObligationStack<'o, 'tcx> {
3396         let fresh_trait_ref =
3397             obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3398
3399         let dfn = previous_stack.cache.next_dfn();
3400         let depth = previous_stack.depth() + 1;
3401         TraitObligationStack {
3402             obligation,
3403             fresh_trait_ref,
3404             reached_depth: Cell::new(depth),
3405             previous: previous_stack,
3406             dfn,
3407             depth,
3408         }
3409     }
3410
3411     fn closure_trait_ref_unnormalized(
3412         &mut self,
3413         obligation: &TraitObligation<'tcx>,
3414         substs: SubstsRef<'tcx>,
3415     ) -> ty::PolyTraitRef<'tcx> {
3416         debug!("closure_trait_ref_unnormalized(obligation={:?}, substs={:?})", obligation, substs);
3417         let closure_sig = substs.as_closure().sig();
3418
3419         debug!("closure_trait_ref_unnormalized: closure_sig = {:?}", closure_sig);
3420
3421         // (1) Feels icky to skip the binder here, but OTOH we know
3422         // that the self-type is an unboxed closure type and hence is
3423         // in fact unparameterized (or at least does not reference any
3424         // regions bound in the obligation). Still probably some
3425         // refactoring could make this nicer.
3426         closure_trait_ref_and_return_type(
3427             self.tcx(),
3428             obligation.predicate.def_id(),
3429             obligation.predicate.skip_binder().self_ty(), // (1)
3430             closure_sig,
3431             util::TupleArgumentsFlag::No,
3432         )
3433         .map_bound(|(trait_ref, _)| trait_ref)
3434     }
3435
3436     fn generator_trait_ref_unnormalized(
3437         &mut self,
3438         obligation: &TraitObligation<'tcx>,
3439         substs: SubstsRef<'tcx>,
3440     ) -> ty::PolyTraitRef<'tcx> {
3441         let gen_sig = substs.as_generator().poly_sig();
3442
3443         // (1) Feels icky to skip the binder here, but OTOH we know
3444         // that the self-type is an generator type and hence is
3445         // in fact unparameterized (or at least does not reference any
3446         // regions bound in the obligation). Still probably some
3447         // refactoring could make this nicer.
3448
3449         super::util::generator_trait_ref_and_outputs(
3450             self.tcx(),
3451             obligation.predicate.def_id(),
3452             obligation.predicate.skip_binder().self_ty(), // (1)
3453             gen_sig,
3454         )
3455         .map_bound(|(trait_ref, ..)| trait_ref)
3456     }
3457
3458     /// Returns the obligations that are implied by instantiating an
3459     /// impl or trait. The obligations are substituted and fully
3460     /// normalized. This is used when confirming an impl or default
3461     /// impl.
3462     fn impl_or_trait_obligations(
3463         &mut self,
3464         cause: ObligationCause<'tcx>,
3465         recursion_depth: usize,
3466         param_env: ty::ParamEnv<'tcx>,
3467         def_id: DefId,           // of impl or trait
3468         substs: SubstsRef<'tcx>, // for impl or trait
3469     ) -> Vec<PredicateObligation<'tcx>> {
3470         debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3471         let tcx = self.tcx();
3472
3473         // To allow for one-pass evaluation of the nested obligation,
3474         // each predicate must be preceded by the obligations required
3475         // to normalize it.
3476         // for example, if we have:
3477         //    impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
3478         // the impl will have the following predicates:
3479         //    <V as Iterator>::Item = U,
3480         //    U: Iterator, U: Sized,
3481         //    V: Iterator, V: Sized,
3482         //    <U as Iterator>::Item: Copy
3483         // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3484         // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3485         // `$1: Copy`, so we must ensure the obligations are emitted in
3486         // that order.
3487         let predicates = tcx.predicates_of(def_id);
3488         assert_eq!(predicates.parent, None);
3489         let mut obligations = Vec::with_capacity(predicates.predicates.len());
3490         for (predicate, _) in predicates.predicates {
3491             let predicate = normalize_with_depth_to(
3492                 self,
3493                 param_env,
3494                 cause.clone(),
3495                 recursion_depth,
3496                 &predicate.subst(tcx, substs),
3497                 &mut obligations,
3498             );
3499             obligations.push(Obligation {
3500                 cause: cause.clone(),
3501                 recursion_depth,
3502                 param_env,
3503                 predicate,
3504             });
3505         }
3506
3507         // We are performing deduplication here to avoid exponential blowups
3508         // (#38528) from happening, but the real cause of the duplication is
3509         // unknown. What we know is that the deduplication avoids exponential
3510         // amount of predicates being propagated when processing deeply nested
3511         // types.
3512         //
3513         // This code is hot enough that it's worth avoiding the allocation
3514         // required for the FxHashSet when possible. Special-casing lengths 0,
3515         // 1 and 2 covers roughly 75-80% of the cases.
3516         if obligations.len() <= 1 {
3517             // No possibility of duplicates.
3518         } else if obligations.len() == 2 {
3519             // Only two elements. Drop the second if they are equal.
3520             if obligations[0] == obligations[1] {
3521                 obligations.truncate(1);
3522             }
3523         } else {
3524             // Three or more elements. Use a general deduplication process.
3525             let mut seen = FxHashSet::default();
3526             obligations.retain(|i| seen.insert(i.clone()));
3527         }
3528
3529         obligations
3530     }
3531 }
3532
3533 trait TraitObligationExt<'tcx> {
3534     fn derived_cause(
3535         &self,
3536         variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3537     ) -> ObligationCause<'tcx>;
3538 }
3539
3540 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
3541     #[allow(unused_comparisons)]
3542     fn derived_cause(
3543         &self,
3544         variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3545     ) -> ObligationCause<'tcx> {
3546         /*!
3547          * Creates a cause for obligations that are derived from
3548          * `obligation` by a recursive search (e.g., for a builtin
3549          * bound, or eventually a `auto trait Foo`). If `obligation`
3550          * is itself a derived obligation, this is just a clone, but
3551          * otherwise we create a "derived obligation" cause so as to
3552          * keep track of the original root obligation for error
3553          * reporting.
3554          */
3555
3556         let obligation = self;
3557
3558         // NOTE(flaper87): As of now, it keeps track of the whole error
3559         // chain. Ideally, we should have a way to configure this either
3560         // by using -Z verbose or just a CLI argument.
3561         let derived_cause = DerivedObligationCause {
3562             parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3563             parent_code: Rc::new(obligation.cause.code.clone()),
3564         };
3565         let derived_code = variant(derived_cause);
3566         ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3567     }
3568 }
3569
3570 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
3571     fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3572         TraitObligationStackList::with(self)
3573     }
3574
3575     fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
3576         self.previous.cache
3577     }
3578
3579     fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3580         self.list()
3581     }
3582
3583     /// Indicates that attempting to evaluate this stack entry
3584     /// required accessing something from the stack at depth `reached_depth`.
3585     fn update_reached_depth(&self, reached_depth: usize) {
3586         assert!(
3587             self.depth > reached_depth,
3588             "invoked `update_reached_depth` with something under this stack: \
3589              self.depth={} reached_depth={}",
3590             self.depth,
3591             reached_depth,
3592         );
3593         debug!("update_reached_depth(reached_depth={})", reached_depth);
3594         let mut p = self;
3595         while reached_depth < p.depth {
3596             debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
3597             p.reached_depth.set(p.reached_depth.get().min(reached_depth));
3598             p = p.previous.head.unwrap();
3599         }
3600     }
3601 }
3602
3603 /// The "provisional evaluation cache" is used to store intermediate cache results
3604 /// when solving auto traits. Auto traits are unusual in that they can support
3605 /// cycles. So, for example, a "proof tree" like this would be ok:
3606 ///
3607 /// - `Foo<T>: Send` :-
3608 ///   - `Bar<T>: Send` :-
3609 ///     - `Foo<T>: Send` -- cycle, but ok
3610 ///   - `Baz<T>: Send`
3611 ///
3612 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
3613 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
3614 /// For non-auto traits, this cycle would be an error, but for auto traits (because
3615 /// they are coinductive) it is considered ok.
3616 ///
3617 /// However, there is a complication: at the point where we have
3618 /// "proven" `Bar<T>: Send`, we have in fact only proven it
3619 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
3620 /// *under the assumption* that `Foo<T>: Send`. But what if we later
3621 /// find out this assumption is wrong?  Specifically, we could
3622 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
3623 /// `Bar<T>: Send` didn't turn out to be true.
3624 ///
3625 /// In Issue #60010, we found a bug in rustc where it would cache
3626 /// these intermediate results. This was fixed in #60444 by disabling
3627 /// *all* caching for things involved in a cycle -- in our example,
3628 /// that would mean we don't cache that `Bar<T>: Send`.  But this led
3629 /// to large slowdowns.
3630 ///
3631 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
3632 /// first requires proving `Bar<T>: Send` (which is true:
3633 ///
3634 /// - `Foo<T>: Send` :-
3635 ///   - `Bar<T>: Send` :-
3636 ///     - `Foo<T>: Send` -- cycle, but ok
3637 ///   - `Baz<T>: Send`
3638 ///     - `Bar<T>: Send` -- would be nice for this to be a cache hit!
3639 ///     - `*const T: Send` -- but what if we later encounter an error?
3640 ///
3641 /// The *provisional evaluation cache* resolves this issue. It stores
3642 /// cache results that we've proven but which were involved in a cycle
3643 /// in some way. We track the minimal stack depth (i.e., the
3644 /// farthest from the top of the stack) that we are dependent on.
3645 /// The idea is that the cache results within are all valid -- so long as
3646 /// none of the nodes in between the current node and the node at that minimum
3647 /// depth result in an error (in which case the cached results are just thrown away).
3648 ///
3649 /// During evaluation, we consult this provisional cache and rely on
3650 /// it. Accessing a cached value is considered equivalent to accessing
3651 /// a result at `reached_depth`, so it marks the *current* solution as
3652 /// provisional as well. If an error is encountered, we toss out any
3653 /// provisional results added from the subtree that encountered the
3654 /// error.  When we pop the node at `reached_depth` from the stack, we
3655 /// can commit all the things that remain in the provisional cache.
3656 struct ProvisionalEvaluationCache<'tcx> {
3657     /// next "depth first number" to issue -- just a counter
3658     dfn: Cell<usize>,
3659
3660     /// Stores the "coldest" depth (bottom of stack) reached by any of
3661     /// the evaluation entries. The idea here is that all things in the provisional
3662     /// cache are always dependent on *something* that is colder in the stack:
3663     /// therefore, if we add a new entry that is dependent on something *colder still*,
3664     /// we have to modify the depth for all entries at once.
3665     ///
3666     /// Example:
3667     ///
3668     /// Imagine we have a stack `A B C D E` (with `E` being the top of
3669     /// the stack).  We cache something with depth 2, which means that
3670     /// it was dependent on C.  Then we pop E but go on and process a
3671     /// new node F: A B C D F.  Now F adds something to the cache with
3672     /// depth 1, meaning it is dependent on B.  Our original cache
3673     /// entry is also dependent on B, because there is a path from E
3674     /// to C and then from C to F and from F to B.
3675     reached_depth: Cell<usize>,
3676
3677     /// Map from cache key to the provisionally evaluated thing.
3678     /// The cache entries contain the result but also the DFN in which they
3679     /// were added. The DFN is used to clear out values on failure.
3680     ///
3681     /// Imagine we have a stack like:
3682     ///
3683     /// - `A B C` and we add a cache for the result of C (DFN 2)
3684     /// - Then we have a stack `A B D` where `D` has DFN 3
3685     /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
3686     /// - `E` generates various cache entries which have cyclic dependices on `B`
3687     ///   - `A B D E F` and so forth
3688     ///   - the DFN of `F` for example would be 5
3689     /// - then we determine that `E` is in error -- we will then clear
3690     ///   all cache values whose DFN is >= 4 -- in this case, that
3691     ///   means the cached value for `F`.
3692     map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
3693 }
3694
3695 /// A cache value for the provisional cache: contains the depth-first
3696 /// number (DFN) and result.
3697 #[derive(Copy, Clone, Debug)]
3698 struct ProvisionalEvaluation {
3699     from_dfn: usize,
3700     result: EvaluationResult,
3701 }
3702
3703 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
3704     fn default() -> Self {
3705         Self { dfn: Cell::new(0), reached_depth: Cell::new(usize::MAX), map: Default::default() }
3706     }
3707 }
3708
3709 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
3710     /// Get the next DFN in sequence (basically a counter).
3711     fn next_dfn(&self) -> usize {
3712         let result = self.dfn.get();
3713         self.dfn.set(result + 1);
3714         result
3715     }
3716
3717     /// Check the provisional cache for any result for
3718     /// `fresh_trait_ref`. If there is a hit, then you must consider
3719     /// it an access to the stack slots at depth
3720     /// `self.current_reached_depth()` and above.
3721     fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
3722         debug!(
3723             "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
3724             fresh_trait_ref,
3725             self.map.borrow().get(&fresh_trait_ref),
3726             self.reached_depth.get(),
3727         );
3728         Some(self.map.borrow().get(&fresh_trait_ref)?.result)
3729     }
3730
3731     /// Current value of the `reached_depth` counter -- all the
3732     /// provisional cache entries are dependent on the item at this
3733     /// depth.
3734     fn current_reached_depth(&self) -> usize {
3735         self.reached_depth.get()
3736     }
3737
3738     /// Insert a provisional result into the cache. The result came
3739     /// from the node with the given DFN. It accessed a minimum depth
3740     /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
3741     /// and resulted in `result`.
3742     fn insert_provisional(
3743         &self,
3744         from_dfn: usize,
3745         reached_depth: usize,
3746         fresh_trait_ref: ty::PolyTraitRef<'tcx>,
3747         result: EvaluationResult,
3748     ) {
3749         debug!(
3750             "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
3751             from_dfn, reached_depth, fresh_trait_ref, result,
3752         );
3753         let r_d = self.reached_depth.get();
3754         self.reached_depth.set(r_d.min(reached_depth));
3755
3756         debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
3757
3758         self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
3759     }
3760
3761     /// Invoked when the node with dfn `dfn` does not get a successful
3762     /// result.  This will clear out any provisional cache entries
3763     /// that were added since `dfn` was created. This is because the
3764     /// provisional entries are things which must assume that the
3765     /// things on the stack at the time of their creation succeeded --
3766     /// since the failing node is presently at the top of the stack,
3767     /// these provisional entries must either depend on it or some
3768     /// ancestor of it.
3769     fn on_failure(&self, dfn: usize) {
3770         debug!("on_failure(dfn={:?})", dfn,);
3771         self.map.borrow_mut().retain(|key, eval| {
3772             if !eval.from_dfn >= dfn {
3773                 debug!("on_failure: removing {:?}", key);
3774                 false
3775             } else {
3776                 true
3777             }
3778         });
3779     }
3780
3781     /// Invoked when the node at depth `depth` completed without
3782     /// depending on anything higher in the stack (if that completion
3783     /// was a failure, then `on_failure` should have been invoked
3784     /// already). The callback `op` will be invoked for each
3785     /// provisional entry that we can now confirm.
3786     fn on_completion(
3787         &self,
3788         depth: usize,
3789         mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
3790     ) {
3791         debug!("on_completion(depth={}, reached_depth={})", depth, self.reached_depth.get(),);
3792
3793         if self.reached_depth.get() < depth {
3794             debug!("on_completion: did not yet reach depth to complete");
3795             return;
3796         }
3797
3798         for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
3799             debug!("on_completion: fresh_trait_ref={:?} eval={:?}", fresh_trait_ref, eval,);
3800
3801             op(fresh_trait_ref, eval.result);
3802         }
3803
3804         self.reached_depth.set(usize::MAX);
3805     }
3806 }
3807
3808 #[derive(Copy, Clone)]
3809 struct TraitObligationStackList<'o, 'tcx> {
3810     cache: &'o ProvisionalEvaluationCache<'tcx>,
3811     head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3812 }
3813
3814 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3815     fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3816         TraitObligationStackList { cache, head: None }
3817     }
3818
3819     fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3820         TraitObligationStackList { cache: r.cache(), head: Some(r) }
3821     }
3822
3823     fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3824         self.head
3825     }
3826
3827     fn depth(&self) -> usize {
3828         if let Some(head) = self.head { head.depth } else { 0 }
3829     }
3830 }
3831
3832 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
3833     type Item = &'o TraitObligationStack<'o, 'tcx>;
3834
3835     fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3836         match self.head {
3837             Some(o) => {
3838                 *self = o.previous;
3839                 Some(o)
3840             }
3841             None => None,
3842         }
3843     }
3844 }
3845
3846 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
3847     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3848         write!(f, "TraitObligationStack({:?})", self.obligation)
3849     }
3850 }