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