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