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