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