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