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