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