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