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