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