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