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