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