]> git.lizzy.rs Git - rust.git/blob - src/librustc_trait_selection/traits/project.rs
Fix font color for help button in ayu and dark themes
[rust.git] / src / librustc_trait_selection / traits / project.rs
1 //! Code for projecting associated types out of trait references.
2
3 use super::elaborate_predicates;
4 use super::specialization_graph;
5 use super::translate_substs;
6 use super::util;
7 use super::MismatchedProjectionTypes;
8 use super::Obligation;
9 use super::ObligationCause;
10 use super::PredicateObligation;
11 use super::Selection;
12 use super::SelectionContext;
13 use super::SelectionError;
14 use super::{
15     ImplSourceClosureData, ImplSourceDiscriminantKindData, ImplSourceFnPointerData,
16     ImplSourceGeneratorData, ImplSourceUserDefinedData,
17 };
18 use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey};
19
20 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
21 use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
22 use crate::traits::error_reporting::InferCtxtExt;
23 use rustc_data_structures::stack::ensure_sufficient_stack;
24 use rustc_errors::ErrorReported;
25 use rustc_hir::def_id::DefId;
26 use rustc_hir::lang_items::{
27     DiscriminantTypeLangItem, FnOnceOutputLangItem, FnOnceTraitLangItem, GeneratorTraitLangItem,
28 };
29 use rustc_infer::infer::resolve::OpportunisticRegionResolver;
30 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
31 use rustc_middle::ty::subst::Subst;
32 use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, WithConstness};
33 use rustc_span::symbol::sym;
34 use rustc_span::DUMMY_SP;
35
36 pub use rustc_middle::traits::Reveal;
37
38 pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
39
40 pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
41
42 pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>;
43
44 /// When attempting to resolve `<T as TraitRef>::Name` ...
45 #[derive(Debug)]
46 pub enum ProjectionTyError<'tcx> {
47     /// ...we found multiple sources of information and couldn't resolve the ambiguity.
48     TooManyCandidates,
49
50     /// ...an error occurred matching `T : TraitRef`
51     TraitSelectionError(SelectionError<'tcx>),
52 }
53
54 #[derive(PartialEq, Eq, Debug)]
55 enum ProjectionTyCandidate<'tcx> {
56     // from a where-clause in the env or object type
57     ParamEnv(ty::PolyProjectionPredicate<'tcx>),
58
59     // from the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
60     TraitDef(ty::PolyProjectionPredicate<'tcx>),
61
62     // from a "impl" (or a "pseudo-impl" returned by select)
63     Select(Selection<'tcx>),
64 }
65
66 enum ProjectionTyCandidateSet<'tcx> {
67     None,
68     Single(ProjectionTyCandidate<'tcx>),
69     Ambiguous,
70     Error(SelectionError<'tcx>),
71 }
72
73 impl<'tcx> ProjectionTyCandidateSet<'tcx> {
74     fn mark_ambiguous(&mut self) {
75         *self = ProjectionTyCandidateSet::Ambiguous;
76     }
77
78     fn mark_error(&mut self, err: SelectionError<'tcx>) {
79         *self = ProjectionTyCandidateSet::Error(err);
80     }
81
82     // Returns true if the push was successful, or false if the candidate
83     // was discarded -- this could be because of ambiguity, or because
84     // a higher-priority candidate is already there.
85     fn push_candidate(&mut self, candidate: ProjectionTyCandidate<'tcx>) -> bool {
86         use self::ProjectionTyCandidate::*;
87         use self::ProjectionTyCandidateSet::*;
88
89         // This wacky variable is just used to try and
90         // make code readable and avoid confusing paths.
91         // It is assigned a "value" of `()` only on those
92         // paths in which we wish to convert `*self` to
93         // ambiguous (and return false, because the candidate
94         // was not used). On other paths, it is not assigned,
95         // and hence if those paths *could* reach the code that
96         // comes after the match, this fn would not compile.
97         let convert_to_ambiguous;
98
99         match self {
100             None => {
101                 *self = Single(candidate);
102                 return true;
103             }
104
105             Single(current) => {
106                 // Duplicates can happen inside ParamEnv. In the case, we
107                 // perform a lazy deduplication.
108                 if current == &candidate {
109                     return false;
110                 }
111
112                 // Prefer where-clauses. As in select, if there are multiple
113                 // candidates, we prefer where-clause candidates over impls.  This
114                 // may seem a bit surprising, since impls are the source of
115                 // "truth" in some sense, but in fact some of the impls that SEEM
116                 // applicable are not, because of nested obligations. Where
117                 // clauses are the safer choice. See the comment on
118                 // `select::SelectionCandidate` and #21974 for more details.
119                 match (current, candidate) {
120                     (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
121                     (ParamEnv(..), _) => return false,
122                     (_, ParamEnv(..)) => unreachable!(),
123                     (_, _) => convert_to_ambiguous = (),
124                 }
125             }
126
127             Ambiguous | Error(..) => {
128                 return false;
129             }
130         }
131
132         // We only ever get here when we moved from a single candidate
133         // to ambiguous.
134         let () = convert_to_ambiguous;
135         *self = Ambiguous;
136         false
137     }
138 }
139
140 /// Evaluates constraints of the form:
141 ///
142 ///     for<...> <T as Trait>::U == V
143 ///
144 /// If successful, this may result in additional obligations. Also returns
145 /// the projection cache key used to track these additional obligations.
146 pub fn poly_project_and_unify_type<'cx, 'tcx>(
147     selcx: &mut SelectionContext<'cx, 'tcx>,
148     obligation: &PolyProjectionObligation<'tcx>,
149 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
150     debug!("poly_project_and_unify_type(obligation={:?})", obligation);
151
152     let infcx = selcx.infcx();
153     infcx.commit_if_ok(|_snapshot| {
154         let (placeholder_predicate, _) =
155             infcx.replace_bound_vars_with_placeholders(&obligation.predicate);
156
157         let placeholder_obligation = obligation.with(placeholder_predicate);
158         let result = project_and_unify_type(selcx, &placeholder_obligation)?;
159         Ok(result)
160     })
161 }
162
163 /// Evaluates constraints of the form:
164 ///
165 ///     <T as Trait>::U == V
166 ///
167 /// If successful, this may result in additional obligations.
168 fn project_and_unify_type<'cx, 'tcx>(
169     selcx: &mut SelectionContext<'cx, 'tcx>,
170     obligation: &ProjectionObligation<'tcx>,
171 ) -> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>> {
172     debug!("project_and_unify_type(obligation={:?})", obligation);
173
174     let mut obligations = vec![];
175     let normalized_ty = match opt_normalize_projection_type(
176         selcx,
177         obligation.param_env,
178         obligation.predicate.projection_ty,
179         obligation.cause.clone(),
180         obligation.recursion_depth,
181         &mut obligations,
182     ) {
183         Some(n) => n,
184         None => return Ok(None),
185     };
186
187     debug!(
188         "project_and_unify_type: normalized_ty={:?} obligations={:?}",
189         normalized_ty, obligations
190     );
191
192     let infcx = selcx.infcx();
193     match infcx
194         .at(&obligation.cause, obligation.param_env)
195         .eq(normalized_ty, obligation.predicate.ty)
196     {
197         Ok(InferOk { obligations: inferred_obligations, value: () }) => {
198             obligations.extend(inferred_obligations);
199             Ok(Some(obligations))
200         }
201         Err(err) => {
202             debug!("project_and_unify_type: equating types encountered error {:?}", err);
203             Err(MismatchedProjectionTypes { err })
204         }
205     }
206 }
207
208 /// Normalizes any associated type projections in `value`, replacing
209 /// them with a fully resolved type where possible. The return value
210 /// combines the normalized result and any additional obligations that
211 /// were incurred as result.
212 pub fn normalize<'a, 'b, 'tcx, T>(
213     selcx: &'a mut SelectionContext<'b, 'tcx>,
214     param_env: ty::ParamEnv<'tcx>,
215     cause: ObligationCause<'tcx>,
216     value: &T,
217 ) -> Normalized<'tcx, T>
218 where
219     T: TypeFoldable<'tcx>,
220 {
221     let mut obligations = Vec::new();
222     let value = normalize_to(selcx, param_env, cause, value, &mut obligations);
223     Normalized { value, obligations }
224 }
225
226 pub fn normalize_to<'a, 'b, 'tcx, T>(
227     selcx: &'a mut SelectionContext<'b, 'tcx>,
228     param_env: ty::ParamEnv<'tcx>,
229     cause: ObligationCause<'tcx>,
230     value: &T,
231     obligations: &mut Vec<PredicateObligation<'tcx>>,
232 ) -> T
233 where
234     T: TypeFoldable<'tcx>,
235 {
236     normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations)
237 }
238
239 /// As `normalize`, but with a custom depth.
240 pub fn normalize_with_depth<'a, 'b, 'tcx, T>(
241     selcx: &'a mut SelectionContext<'b, 'tcx>,
242     param_env: ty::ParamEnv<'tcx>,
243     cause: ObligationCause<'tcx>,
244     depth: usize,
245     value: &T,
246 ) -> Normalized<'tcx, T>
247 where
248     T: TypeFoldable<'tcx>,
249 {
250     let mut obligations = Vec::new();
251     let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
252     Normalized { value, obligations }
253 }
254
255 pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
256     selcx: &'a mut SelectionContext<'b, 'tcx>,
257     param_env: ty::ParamEnv<'tcx>,
258     cause: ObligationCause<'tcx>,
259     depth: usize,
260     value: &T,
261     obligations: &mut Vec<PredicateObligation<'tcx>>,
262 ) -> T
263 where
264     T: TypeFoldable<'tcx>,
265 {
266     debug!("normalize_with_depth(depth={}, value={:?})", depth, value);
267     let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
268     let result = ensure_sufficient_stack(|| normalizer.fold(value));
269     debug!(
270         "normalize_with_depth: depth={} result={:?} with {} obligations",
271         depth,
272         result,
273         normalizer.obligations.len()
274     );
275     debug!("normalize_with_depth: depth={} obligations={:?}", depth, normalizer.obligations);
276     result
277 }
278
279 struct AssocTypeNormalizer<'a, 'b, 'tcx> {
280     selcx: &'a mut SelectionContext<'b, 'tcx>,
281     param_env: ty::ParamEnv<'tcx>,
282     cause: ObligationCause<'tcx>,
283     obligations: &'a mut Vec<PredicateObligation<'tcx>>,
284     depth: usize,
285 }
286
287 impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
288     fn new(
289         selcx: &'a mut SelectionContext<'b, 'tcx>,
290         param_env: ty::ParamEnv<'tcx>,
291         cause: ObligationCause<'tcx>,
292         depth: usize,
293         obligations: &'a mut Vec<PredicateObligation<'tcx>>,
294     ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
295         AssocTypeNormalizer { selcx, param_env, cause, obligations, depth }
296     }
297
298     fn fold<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
299         let value = self.selcx.infcx().resolve_vars_if_possible(value);
300
301         if !value.has_projections() { value } else { value.fold_with(self) }
302     }
303 }
304
305 impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
306     fn tcx<'c>(&'c self) -> TyCtxt<'tcx> {
307         self.selcx.tcx()
308     }
309
310     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
311         if !ty.has_projections() {
312             return ty;
313         }
314         // We don't want to normalize associated types that occur inside of region
315         // binders, because they may contain bound regions, and we can't cope with that.
316         //
317         // Example:
318         //
319         //     for<'a> fn(<T as Foo<&'a>>::A)
320         //
321         // Instead of normalizing `<T as Foo<&'a>>::A` here, we'll
322         // normalize it when we instantiate those bound regions (which
323         // should occur eventually).
324
325         let ty = ty.super_fold_with(self);
326         match ty.kind {
327             ty::Opaque(def_id, substs) => {
328                 // Only normalize `impl Trait` after type-checking, usually in codegen.
329                 match self.param_env.reveal() {
330                     Reveal::UserFacing => ty,
331
332                     Reveal::All => {
333                         let recursion_limit = self.tcx().sess.recursion_limit();
334                         if !recursion_limit.value_within_limit(self.depth) {
335                             let obligation = Obligation::with_depth(
336                                 self.cause.clone(),
337                                 recursion_limit.0,
338                                 self.param_env,
339                                 ty,
340                             );
341                             self.selcx.infcx().report_overflow_error(&obligation, true);
342                         }
343
344                         let generic_ty = self.tcx().type_of(def_id);
345                         let concrete_ty = generic_ty.subst(self.tcx(), substs);
346                         self.depth += 1;
347                         let folded_ty = self.fold_ty(concrete_ty);
348                         self.depth -= 1;
349                         folded_ty
350                     }
351                 }
352             }
353
354             ty::Projection(ref data) if !data.has_escaping_bound_vars() => {
355                 // This is kind of hacky -- we need to be able to
356                 // handle normalization within binders because
357                 // otherwise we wind up a need to normalize when doing
358                 // trait matching (since you can have a trait
359                 // obligation like `for<'a> T::B: Fn(&'a i32)`), but
360                 // we can't normalize with bound regions in scope. So
361                 // far now we just ignore binders but only normalize
362                 // if all bound regions are gone (and then we still
363                 // have to renormalize whenever we instantiate a
364                 // binder). It would be better to normalize in a
365                 // binding-aware fashion.
366
367                 let normalized_ty = normalize_projection_type(
368                     self.selcx,
369                     self.param_env,
370                     *data,
371                     self.cause.clone(),
372                     self.depth,
373                     &mut self.obligations,
374                 );
375                 debug!(
376                     "AssocTypeNormalizer: depth={} normalized {:?} to {:?}, \
377                      now with {} obligations",
378                     self.depth,
379                     ty,
380                     normalized_ty,
381                     self.obligations.len()
382                 );
383                 normalized_ty
384             }
385
386             _ => ty,
387         }
388     }
389
390     fn fold_const(&mut self, constant: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
391         if self.selcx.tcx().lazy_normalization() {
392             constant
393         } else {
394             let constant = constant.super_fold_with(self);
395             constant.eval(self.selcx.tcx(), self.param_env)
396         }
397     }
398 }
399
400 /// The guts of `normalize`: normalize a specific projection like `<T
401 /// as Trait>::Item`. The result is always a type (and possibly
402 /// additional obligations). If ambiguity arises, which implies that
403 /// there are unresolved type variables in the projection, we will
404 /// substitute a fresh type variable `$X` and generate a new
405 /// obligation `<T as Trait>::Item == $X` for later.
406 pub fn normalize_projection_type<'a, 'b, 'tcx>(
407     selcx: &'a mut SelectionContext<'b, 'tcx>,
408     param_env: ty::ParamEnv<'tcx>,
409     projection_ty: ty::ProjectionTy<'tcx>,
410     cause: ObligationCause<'tcx>,
411     depth: usize,
412     obligations: &mut Vec<PredicateObligation<'tcx>>,
413 ) -> Ty<'tcx> {
414     opt_normalize_projection_type(
415         selcx,
416         param_env,
417         projection_ty,
418         cause.clone(),
419         depth,
420         obligations,
421     )
422     .unwrap_or_else(move || {
423         // if we bottom out in ambiguity, create a type variable
424         // and a deferred predicate to resolve this when more type
425         // information is available.
426
427         let tcx = selcx.infcx().tcx;
428         let def_id = projection_ty.item_def_id;
429         let ty_var = selcx.infcx().next_ty_var(TypeVariableOrigin {
430             kind: TypeVariableOriginKind::NormalizeProjectionType,
431             span: tcx.def_span(def_id),
432         });
433         let projection = ty::Binder::dummy(ty::ProjectionPredicate { projection_ty, ty: ty_var });
434         let obligation =
435             Obligation::with_depth(cause, depth + 1, param_env, projection.to_predicate(tcx));
436         obligations.push(obligation);
437         ty_var
438     })
439 }
440
441 /// The guts of `normalize`: normalize a specific projection like `<T
442 /// as Trait>::Item`. The result is always a type (and possibly
443 /// additional obligations). Returns `None` in the case of ambiguity,
444 /// which indicates that there are unbound type variables.
445 ///
446 /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a
447 /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very
448 /// often immediately appended to another obligations vector. So now this
449 /// function takes an obligations vector and appends to it directly, which is
450 /// slightly uglier but avoids the need for an extra short-lived allocation.
451 fn opt_normalize_projection_type<'a, 'b, 'tcx>(
452     selcx: &'a mut SelectionContext<'b, 'tcx>,
453     param_env: ty::ParamEnv<'tcx>,
454     projection_ty: ty::ProjectionTy<'tcx>,
455     cause: ObligationCause<'tcx>,
456     depth: usize,
457     obligations: &mut Vec<PredicateObligation<'tcx>>,
458 ) -> Option<Ty<'tcx>> {
459     let infcx = selcx.infcx();
460
461     let projection_ty = infcx.resolve_vars_if_possible(&projection_ty);
462     let cache_key = ProjectionCacheKey::new(projection_ty);
463
464     debug!(
465         "opt_normalize_projection_type(\
466          projection_ty={:?}, \
467          depth={})",
468         projection_ty, depth
469     );
470
471     // FIXME(#20304) For now, I am caching here, which is good, but it
472     // means we don't capture the type variables that are created in
473     // the case of ambiguity. Which means we may create a large stream
474     // of such variables. OTOH, if we move the caching up a level, we
475     // would not benefit from caching when proving `T: Trait<U=Foo>`
476     // bounds. It might be the case that we want two distinct caches,
477     // or else another kind of cache entry.
478
479     let cache_result = infcx.inner.borrow_mut().projection_cache().try_start(cache_key);
480     match cache_result {
481         Ok(()) => {}
482         Err(ProjectionCacheEntry::Ambiguous) => {
483             // If we found ambiguity the last time, that means we will continue
484             // to do so until some type in the key changes (and we know it
485             // hasn't, because we just fully resolved it).
486             debug!(
487                 "opt_normalize_projection_type: \
488                  found cache entry: ambiguous"
489             );
490             return None;
491         }
492         Err(ProjectionCacheEntry::InProgress) => {
493             // If while normalized A::B, we are asked to normalize
494             // A::B, just return A::B itself. This is a conservative
495             // answer, in the sense that A::B *is* clearly equivalent
496             // to A::B, though there may be a better value we can
497             // find.
498
499             // Under lazy normalization, this can arise when
500             // bootstrapping.  That is, imagine an environment with a
501             // where-clause like `A::B == u32`. Now, if we are asked
502             // to normalize `A::B`, we will want to check the
503             // where-clauses in scope. So we will try to unify `A::B`
504             // with `A::B`, which can trigger a recursive
505             // normalization. In that case, I think we will want this code:
506             //
507             // ```
508             // let ty = selcx.tcx().mk_projection(projection_ty.item_def_id,
509             //                                    projection_ty.substs;
510             // return Some(NormalizedTy { value: v, obligations: vec![] });
511             // ```
512
513             debug!(
514                 "opt_normalize_projection_type: \
515                  found cache entry: in-progress"
516             );
517
518             // But for now, let's classify this as an overflow:
519             let recursion_limit = selcx.tcx().sess.recursion_limit();
520             let obligation =
521                 Obligation::with_depth(cause, recursion_limit.0, param_env, projection_ty);
522             selcx.infcx().report_overflow_error(&obligation, false);
523         }
524         Err(ProjectionCacheEntry::NormalizedTy(ty)) => {
525             // This is the hottest path in this function.
526             //
527             // If we find the value in the cache, then return it along
528             // with the obligations that went along with it. Note
529             // that, when using a fulfillment context, these
530             // obligations could in principle be ignored: they have
531             // already been registered when the cache entry was
532             // created (and hence the new ones will quickly be
533             // discarded as duplicated). But when doing trait
534             // evaluation this is not the case, and dropping the trait
535             // evaluations can causes ICEs (e.g., #43132).
536             debug!(
537                 "opt_normalize_projection_type: \
538                  found normalized ty `{:?}`",
539                 ty
540             );
541
542             // Once we have inferred everything we need to know, we
543             // can ignore the `obligations` from that point on.
544             if infcx.unresolved_type_vars(&ty.value).is_none() {
545                 infcx.inner.borrow_mut().projection_cache().complete_normalized(cache_key, &ty);
546             // No need to extend `obligations`.
547             } else {
548                 obligations.extend(ty.obligations);
549             }
550
551             obligations.push(get_paranoid_cache_value_obligation(
552                 infcx,
553                 param_env,
554                 projection_ty,
555                 cause,
556                 depth,
557             ));
558             return Some(ty.value);
559         }
560         Err(ProjectionCacheEntry::Error) => {
561             debug!(
562                 "opt_normalize_projection_type: \
563                  found error"
564             );
565             let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
566             obligations.extend(result.obligations);
567             return Some(result.value);
568         }
569     }
570
571     let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty);
572     match project_type(selcx, &obligation) {
573         Ok(ProjectedTy::Progress(Progress {
574             ty: projected_ty,
575             obligations: mut projected_obligations,
576         })) => {
577             // if projection succeeded, then what we get out of this
578             // is also non-normalized (consider: it was derived from
579             // an impl, where-clause etc) and hence we must
580             // re-normalize it
581
582             debug!(
583                 "opt_normalize_projection_type: \
584                  projected_ty={:?} \
585                  depth={} \
586                  projected_obligations={:?}",
587                 projected_ty, depth, projected_obligations
588             );
589
590             let result = if projected_ty.has_projections() {
591                 let mut normalizer = AssocTypeNormalizer::new(
592                     selcx,
593                     param_env,
594                     cause,
595                     depth + 1,
596                     &mut projected_obligations,
597                 );
598                 let normalized_ty = normalizer.fold(&projected_ty);
599
600                 debug!(
601                     "opt_normalize_projection_type: \
602                      normalized_ty={:?} depth={}",
603                     normalized_ty, depth
604                 );
605
606                 Normalized { value: normalized_ty, obligations: projected_obligations }
607             } else {
608                 Normalized { value: projected_ty, obligations: projected_obligations }
609             };
610
611             let cache_value = prune_cache_value_obligations(infcx, &result);
612             infcx.inner.borrow_mut().projection_cache().insert_ty(cache_key, cache_value);
613             obligations.extend(result.obligations);
614             Some(result.value)
615         }
616         Ok(ProjectedTy::NoProgress(projected_ty)) => {
617             debug!(
618                 "opt_normalize_projection_type: \
619                  projected_ty={:?} no progress",
620                 projected_ty
621             );
622             let result = Normalized { value: projected_ty, obligations: vec![] };
623             infcx.inner.borrow_mut().projection_cache().insert_ty(cache_key, result.clone());
624             // No need to extend `obligations`.
625             Some(result.value)
626         }
627         Err(ProjectionTyError::TooManyCandidates) => {
628             debug!(
629                 "opt_normalize_projection_type: \
630                  too many candidates"
631             );
632             infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key);
633             None
634         }
635         Err(ProjectionTyError::TraitSelectionError(_)) => {
636             debug!("opt_normalize_projection_type: ERROR");
637             // if we got an error processing the `T as Trait` part,
638             // just return `ty::err` but add the obligation `T :
639             // Trait`, which when processed will cause the error to be
640             // reported later
641
642             infcx.inner.borrow_mut().projection_cache().error(cache_key);
643             let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
644             obligations.extend(result.obligations);
645             Some(result.value)
646         }
647     }
648 }
649
650 /// If there are unresolved type variables, then we need to include
651 /// any subobligations that bind them, at least until those type
652 /// variables are fully resolved.
653 fn prune_cache_value_obligations<'a, 'tcx>(
654     infcx: &'a InferCtxt<'a, 'tcx>,
655     result: &NormalizedTy<'tcx>,
656 ) -> NormalizedTy<'tcx> {
657     if infcx.unresolved_type_vars(&result.value).is_none() {
658         return NormalizedTy { value: result.value, obligations: vec![] };
659     }
660
661     let mut obligations: Vec<_> = result
662         .obligations
663         .iter()
664         .filter(|obligation| {
665             match obligation.predicate.skip_binders() {
666                 // We found a `T: Foo<X = U>` predicate, let's check
667                 // if `U` references any unresolved type
668                 // variables. In principle, we only care if this
669                 // projection can help resolve any of the type
670                 // variables found in `result.value` -- but we just
671                 // check for any type variables here, for fear of
672                 // indirect obligations (e.g., we project to `?0`,
673                 // but we have `T: Foo<X = ?1>` and `?1: Bar<X =
674                 // ?0>`).
675                 ty::PredicateAtom::Projection(data) => {
676                     infcx.unresolved_type_vars(&ty::Binder::bind(data.ty)).is_some()
677                 }
678
679                 // We are only interested in `T: Foo<X = U>` predicates, whre
680                 // `U` references one of `unresolved_type_vars`. =)
681                 _ => false,
682             }
683         })
684         .cloned()
685         .collect();
686
687     obligations.shrink_to_fit();
688
689     NormalizedTy { value: result.value, obligations }
690 }
691
692 /// Whenever we give back a cache result for a projection like `<T as
693 /// Trait>::Item ==> X`, we *always* include the obligation to prove
694 /// that `T: Trait` (we may also include some other obligations). This
695 /// may or may not be necessary -- in principle, all the obligations
696 /// that must be proven to show that `T: Trait` were also returned
697 /// when the cache was first populated. But there are some vague concerns,
698 /// and so we take the precautionary measure of including `T: Trait` in
699 /// the result:
700 ///
701 /// Concern #1. The current setup is fragile. Perhaps someone could
702 /// have failed to prove the concerns from when the cache was
703 /// populated, but also not have used a snapshot, in which case the
704 /// cache could remain populated even though `T: Trait` has not been
705 /// shown. In this case, the "other code" is at fault -- when you
706 /// project something, you are supposed to either have a snapshot or
707 /// else prove all the resulting obligations -- but it's still easy to
708 /// get wrong.
709 ///
710 /// Concern #2. Even within the snapshot, if those original
711 /// obligations are not yet proven, then we are able to do projections
712 /// that may yet turn out to be wrong. This *may* lead to some sort
713 /// of trouble, though we don't have a concrete example of how that
714 /// can occur yet. But it seems risky at best.
715 fn get_paranoid_cache_value_obligation<'a, 'tcx>(
716     infcx: &'a InferCtxt<'a, 'tcx>,
717     param_env: ty::ParamEnv<'tcx>,
718     projection_ty: ty::ProjectionTy<'tcx>,
719     cause: ObligationCause<'tcx>,
720     depth: usize,
721 ) -> PredicateObligation<'tcx> {
722     let trait_ref = projection_ty.trait_ref(infcx.tcx).to_poly_trait_ref();
723     Obligation {
724         cause,
725         recursion_depth: depth,
726         param_env,
727         predicate: trait_ref.without_const().to_predicate(infcx.tcx),
728     }
729 }
730
731 /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
732 /// hold. In various error cases, we cannot generate a valid
733 /// normalized projection. Therefore, we create an inference variable
734 /// return an associated obligation that, when fulfilled, will lead to
735 /// an error.
736 ///
737 /// Note that we used to return `Error` here, but that was quite
738 /// dubious -- the premise was that an error would *eventually* be
739 /// reported, when the obligation was processed. But in general once
740 /// you see a `Error` you are supposed to be able to assume that an
741 /// error *has been* reported, so that you can take whatever heuristic
742 /// paths you want to take. To make things worse, it was possible for
743 /// cycles to arise, where you basically had a setup like `<MyType<$0>
744 /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
745 /// Trait>::Foo> to `[type error]` would lead to an obligation of
746 /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
747 /// an error for this obligation, but we legitimately should not,
748 /// because it contains `[type error]`. Yuck! (See issue #29857 for
749 /// one case where this arose.)
750 fn normalize_to_error<'a, 'tcx>(
751     selcx: &mut SelectionContext<'a, 'tcx>,
752     param_env: ty::ParamEnv<'tcx>,
753     projection_ty: ty::ProjectionTy<'tcx>,
754     cause: ObligationCause<'tcx>,
755     depth: usize,
756 ) -> NormalizedTy<'tcx> {
757     let trait_ref = projection_ty.trait_ref(selcx.tcx()).to_poly_trait_ref();
758     let trait_obligation = Obligation {
759         cause,
760         recursion_depth: depth,
761         param_env,
762         predicate: trait_ref.without_const().to_predicate(selcx.tcx()),
763     };
764     let tcx = selcx.infcx().tcx;
765     let def_id = projection_ty.item_def_id;
766     let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin {
767         kind: TypeVariableOriginKind::NormalizeProjectionType,
768         span: tcx.def_span(def_id),
769     });
770     Normalized { value: new_value, obligations: vec![trait_obligation] }
771 }
772
773 enum ProjectedTy<'tcx> {
774     Progress(Progress<'tcx>),
775     NoProgress(Ty<'tcx>),
776 }
777
778 struct Progress<'tcx> {
779     ty: Ty<'tcx>,
780     obligations: Vec<PredicateObligation<'tcx>>,
781 }
782
783 impl<'tcx> Progress<'tcx> {
784     fn error(tcx: TyCtxt<'tcx>) -> Self {
785         Progress { ty: tcx.ty_error(), obligations: vec![] }
786     }
787
788     fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self {
789         debug!(
790             "with_addl_obligations: self.obligations.len={} obligations.len={}",
791             self.obligations.len(),
792             obligations.len()
793         );
794
795         debug!(
796             "with_addl_obligations: self.obligations={:?} obligations={:?}",
797             self.obligations, obligations
798         );
799
800         self.obligations.append(&mut obligations);
801         self
802     }
803 }
804
805 /// Computes the result of a projection type (if we can).
806 ///
807 /// IMPORTANT:
808 /// - `obligation` must be fully normalized
809 fn project_type<'cx, 'tcx>(
810     selcx: &mut SelectionContext<'cx, 'tcx>,
811     obligation: &ProjectionTyObligation<'tcx>,
812 ) -> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>> {
813     debug!("project(obligation={:?})", obligation);
814
815     if !selcx.tcx().sess.recursion_limit().value_within_limit(obligation.recursion_depth) {
816         debug!("project: overflow!");
817         return Err(ProjectionTyError::TraitSelectionError(SelectionError::Overflow));
818     }
819
820     let obligation_trait_ref = &obligation.predicate.trait_ref(selcx.tcx());
821
822     debug!("project: obligation_trait_ref={:?}", obligation_trait_ref);
823
824     if obligation_trait_ref.references_error() {
825         return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx())));
826     }
827
828     let mut candidates = ProjectionTyCandidateSet::None;
829
830     // Make sure that the following procedures are kept in order. ParamEnv
831     // needs to be first because it has highest priority, and Select checks
832     // the return value of push_candidate which assumes it's ran at last.
833     assemble_candidates_from_param_env(selcx, obligation, &obligation_trait_ref, &mut candidates);
834
835     assemble_candidates_from_trait_def(selcx, obligation, &obligation_trait_ref, &mut candidates);
836
837     assemble_candidates_from_impls(selcx, obligation, &obligation_trait_ref, &mut candidates);
838
839     match candidates {
840         ProjectionTyCandidateSet::Single(candidate) => Ok(ProjectedTy::Progress(
841             confirm_candidate(selcx, obligation, &obligation_trait_ref, candidate),
842         )),
843         ProjectionTyCandidateSet::None => Ok(ProjectedTy::NoProgress(
844             selcx
845                 .tcx()
846                 .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs),
847         )),
848         // Error occurred while trying to processing impls.
849         ProjectionTyCandidateSet::Error(e) => Err(ProjectionTyError::TraitSelectionError(e)),
850         // Inherent ambiguity that prevents us from even enumerating the
851         // candidates.
852         ProjectionTyCandidateSet::Ambiguous => Err(ProjectionTyError::TooManyCandidates),
853     }
854 }
855
856 /// The first thing we have to do is scan through the parameter
857 /// environment to see whether there are any projection predicates
858 /// there that can answer this question.
859 fn assemble_candidates_from_param_env<'cx, 'tcx>(
860     selcx: &mut SelectionContext<'cx, 'tcx>,
861     obligation: &ProjectionTyObligation<'tcx>,
862     obligation_trait_ref: &ty::TraitRef<'tcx>,
863     candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
864 ) {
865     debug!("assemble_candidates_from_param_env(..)");
866     assemble_candidates_from_predicates(
867         selcx,
868         obligation,
869         obligation_trait_ref,
870         candidate_set,
871         ProjectionTyCandidate::ParamEnv,
872         obligation.param_env.caller_bounds().iter(),
873     );
874 }
875
876 /// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
877 /// that the definition of `Foo` has some clues:
878 ///
879 /// ```
880 /// trait Foo {
881 ///     type FooT : Bar<BarT=i32>
882 /// }
883 /// ```
884 ///
885 /// Here, for example, we could conclude that the result is `i32`.
886 fn assemble_candidates_from_trait_def<'cx, 'tcx>(
887     selcx: &mut SelectionContext<'cx, 'tcx>,
888     obligation: &ProjectionTyObligation<'tcx>,
889     obligation_trait_ref: &ty::TraitRef<'tcx>,
890     candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
891 ) {
892     debug!("assemble_candidates_from_trait_def(..)");
893
894     let tcx = selcx.tcx();
895     // Check whether the self-type is itself a projection.
896     // If so, extract what we know from the trait and try to come up with a good answer.
897     let bounds = match obligation_trait_ref.self_ty().kind {
898         ty::Projection(ref data) => {
899             tcx.projection_predicates(data.item_def_id).subst(tcx, data.substs)
900         }
901         ty::Opaque(def_id, substs) => tcx.projection_predicates(def_id).subst(tcx, substs),
902         ty::Infer(ty::TyVar(_)) => {
903             // If the self-type is an inference variable, then it MAY wind up
904             // being a projected type, so induce an ambiguity.
905             candidate_set.mark_ambiguous();
906             return;
907         }
908         _ => return,
909     };
910
911     assemble_candidates_from_predicates(
912         selcx,
913         obligation,
914         obligation_trait_ref,
915         candidate_set,
916         ProjectionTyCandidate::TraitDef,
917         bounds.iter(),
918     )
919 }
920
921 fn assemble_candidates_from_predicates<'cx, 'tcx>(
922     selcx: &mut SelectionContext<'cx, 'tcx>,
923     obligation: &ProjectionTyObligation<'tcx>,
924     obligation_trait_ref: &ty::TraitRef<'tcx>,
925     candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
926     ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
927     env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
928 ) {
929     debug!("assemble_candidates_from_predicates(obligation={:?})", obligation);
930     let infcx = selcx.infcx();
931     for predicate in env_predicates {
932         debug!("assemble_candidates_from_predicates: predicate={:?}", predicate);
933         if let ty::PredicateAtom::Projection(data) = predicate.skip_binders() {
934             let data = ty::Binder::bind(data);
935             let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id;
936
937             let is_match = same_def_id
938                 && infcx.probe(|_| {
939                     let data_poly_trait_ref = data.to_poly_trait_ref(infcx.tcx);
940                     let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
941                     infcx
942                         .at(&obligation.cause, obligation.param_env)
943                         .sup(obligation_poly_trait_ref, data_poly_trait_ref)
944                         .map(|InferOk { obligations: _, value: () }| {
945                             // FIXME(#32730) -- do we need to take obligations
946                             // into account in any way? At the moment, no.
947                         })
948                         .is_ok()
949                 });
950
951             debug!(
952                 "assemble_candidates_from_predicates: candidate={:?} \
953                  is_match={} same_def_id={}",
954                 data, is_match, same_def_id
955             );
956
957             if is_match {
958                 candidate_set.push_candidate(ctor(data));
959             }
960         }
961     }
962 }
963
964 fn assemble_candidates_from_impls<'cx, 'tcx>(
965     selcx: &mut SelectionContext<'cx, 'tcx>,
966     obligation: &ProjectionTyObligation<'tcx>,
967     obligation_trait_ref: &ty::TraitRef<'tcx>,
968     candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
969 ) {
970     // If we are resolving `<T as TraitRef<...>>::Item == Type`,
971     // start out by selecting the predicate `T as TraitRef<...>`:
972     let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
973     let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
974     let _ = selcx.infcx().commit_if_ok(|_| {
975         let impl_source = match selcx.select(&trait_obligation) {
976             Ok(Some(impl_source)) => impl_source,
977             Ok(None) => {
978                 candidate_set.mark_ambiguous();
979                 return Err(());
980             }
981             Err(e) => {
982                 debug!("assemble_candidates_from_impls: selection error {:?}", e);
983                 candidate_set.mark_error(e);
984                 return Err(());
985             }
986         };
987
988         let eligible = match &impl_source {
989             super::ImplSourceClosure(_)
990             | super::ImplSourceGenerator(_)
991             | super::ImplSourceFnPointer(_)
992             | super::ImplSourceObject(_)
993             | super::ImplSourceTraitAlias(_) => {
994                 debug!("assemble_candidates_from_impls: impl_source={:?}", impl_source);
995                 true
996             }
997             super::ImplSourceUserDefined(impl_data) => {
998                 // We have to be careful when projecting out of an
999                 // impl because of specialization. If we are not in
1000                 // codegen (i.e., projection mode is not "any"), and the
1001                 // impl's type is declared as default, then we disable
1002                 // projection (even if the trait ref is fully
1003                 // monomorphic). In the case where trait ref is not
1004                 // fully monomorphic (i.e., includes type parameters),
1005                 // this is because those type parameters may
1006                 // ultimately be bound to types from other crates that
1007                 // may have specialized impls we can't see. In the
1008                 // case where the trait ref IS fully monomorphic, this
1009                 // is a policy decision that we made in the RFC in
1010                 // order to preserve flexibility for the crate that
1011                 // defined the specializable impl to specialize later
1012                 // for existing types.
1013                 //
1014                 // In either case, we handle this by not adding a
1015                 // candidate for an impl if it contains a `default`
1016                 // type.
1017                 //
1018                 // NOTE: This should be kept in sync with the similar code in
1019                 // `rustc_ty::instance::resolve_associated_item()`.
1020                 let node_item =
1021                     assoc_ty_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id)
1022                         .map_err(|ErrorReported| ())?;
1023
1024                 if node_item.is_final() {
1025                     // Non-specializable items are always projectable.
1026                     true
1027                 } else {
1028                     // Only reveal a specializable default if we're past type-checking
1029                     // and the obligation is monomorphic, otherwise passes such as
1030                     // transmute checking and polymorphic MIR optimizations could
1031                     // get a result which isn't correct for all monomorphizations.
1032                     if obligation.param_env.reveal() == Reveal::All {
1033                         // NOTE(eddyb) inference variables can resolve to parameters, so
1034                         // assume `poly_trait_ref` isn't monomorphic, if it contains any.
1035                         let poly_trait_ref =
1036                             selcx.infcx().resolve_vars_if_possible(&poly_trait_ref);
1037                         !poly_trait_ref.still_further_specializable()
1038                     } else {
1039                         debug!(
1040                             "assemble_candidates_from_impls: not eligible due to default: \
1041                              assoc_ty={} predicate={}",
1042                             selcx.tcx().def_path_str(node_item.item.def_id),
1043                             obligation.predicate,
1044                         );
1045                         false
1046                     }
1047                 }
1048             }
1049             super::ImplSourceDiscriminantKind(..) => {
1050                 // While `DiscriminantKind` is automatically implemented for every type,
1051                 // the concrete discriminant may not be known yet.
1052                 //
1053                 // Any type with multiple potential discriminant types is therefore not eligible.
1054                 let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1055
1056                 match self_ty.kind {
1057                     ty::Bool
1058                     | ty::Char
1059                     | ty::Int(_)
1060                     | ty::Uint(_)
1061                     | ty::Float(_)
1062                     | ty::Adt(..)
1063                     | ty::Foreign(_)
1064                     | ty::Str
1065                     | ty::Array(..)
1066                     | ty::Slice(_)
1067                     | ty::RawPtr(..)
1068                     | ty::Ref(..)
1069                     | ty::FnDef(..)
1070                     | ty::FnPtr(..)
1071                     | ty::Dynamic(..)
1072                     | ty::Closure(..)
1073                     | ty::Generator(..)
1074                     | ty::GeneratorWitness(..)
1075                     | ty::Never
1076                     | ty::Tuple(..)
1077                     // Integers and floats always have `u8` as their discriminant.
1078                     | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true,
1079
1080                     ty::Projection(..)
1081                     | ty::Opaque(..)
1082                     | ty::Param(..)
1083                     | ty::Bound(..)
1084                     | ty::Placeholder(..)
1085                     | ty::Infer(..)
1086                     | ty::Error(_) => false,
1087                 }
1088             }
1089             super::ImplSourceParam(..) => {
1090                 // This case tell us nothing about the value of an
1091                 // associated type. Consider:
1092                 //
1093                 // ```
1094                 // trait SomeTrait { type Foo; }
1095                 // fn foo<T:SomeTrait>(...) { }
1096                 // ```
1097                 //
1098                 // If the user writes `<T as SomeTrait>::Foo`, then the `T
1099                 // : SomeTrait` binding does not help us decide what the
1100                 // type `Foo` is (at least, not more specifically than
1101                 // what we already knew).
1102                 //
1103                 // But wait, you say! What about an example like this:
1104                 //
1105                 // ```
1106                 // fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
1107                 // ```
1108                 //
1109                 // Doesn't the `T : Sometrait<Foo=usize>` predicate help
1110                 // resolve `T::Foo`? And of course it does, but in fact
1111                 // that single predicate is desugared into two predicates
1112                 // in the compiler: a trait predicate (`T : SomeTrait`) and a
1113                 // projection. And the projection where clause is handled
1114                 // in `assemble_candidates_from_param_env`.
1115                 false
1116             }
1117             super::ImplSourceAutoImpl(..) | super::ImplSourceBuiltin(..) => {
1118                 // These traits have no associated types.
1119                 span_bug!(
1120                     obligation.cause.span,
1121                     "Cannot project an associated type from `{:?}`",
1122                     impl_source
1123                 );
1124             }
1125         };
1126
1127         if eligible {
1128             if candidate_set.push_candidate(ProjectionTyCandidate::Select(impl_source)) {
1129                 Ok(())
1130             } else {
1131                 Err(())
1132             }
1133         } else {
1134             Err(())
1135         }
1136     });
1137 }
1138
1139 fn confirm_candidate<'cx, 'tcx>(
1140     selcx: &mut SelectionContext<'cx, 'tcx>,
1141     obligation: &ProjectionTyObligation<'tcx>,
1142     obligation_trait_ref: &ty::TraitRef<'tcx>,
1143     candidate: ProjectionTyCandidate<'tcx>,
1144 ) -> Progress<'tcx> {
1145     debug!("confirm_candidate(candidate={:?}, obligation={:?})", candidate, obligation);
1146
1147     let mut progress = match candidate {
1148         ProjectionTyCandidate::ParamEnv(poly_projection)
1149         | ProjectionTyCandidate::TraitDef(poly_projection) => {
1150             confirm_param_env_candidate(selcx, obligation, poly_projection)
1151         }
1152
1153         ProjectionTyCandidate::Select(impl_source) => {
1154             confirm_select_candidate(selcx, obligation, obligation_trait_ref, impl_source)
1155         }
1156     };
1157     // When checking for cycle during evaluation, we compare predicates with
1158     // "syntactic" equality. Since normalization generally introduces a type
1159     // with new region variables, we need to resolve them to existing variables
1160     // when possible for this to work. See `auto-trait-projection-recursion.rs`
1161     // for a case where this matters.
1162     if progress.ty.has_infer_regions() {
1163         progress.ty = OpportunisticRegionResolver::new(selcx.infcx()).fold_ty(progress.ty);
1164     }
1165     progress
1166 }
1167
1168 fn confirm_select_candidate<'cx, 'tcx>(
1169     selcx: &mut SelectionContext<'cx, 'tcx>,
1170     obligation: &ProjectionTyObligation<'tcx>,
1171     obligation_trait_ref: &ty::TraitRef<'tcx>,
1172     impl_source: Selection<'tcx>,
1173 ) -> Progress<'tcx> {
1174     match impl_source {
1175         super::ImplSourceUserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
1176         super::ImplSourceGenerator(data) => confirm_generator_candidate(selcx, obligation, data),
1177         super::ImplSourceClosure(data) => confirm_closure_candidate(selcx, obligation, data),
1178         super::ImplSourceFnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data),
1179         super::ImplSourceDiscriminantKind(data) => {
1180             confirm_discriminant_kind_candidate(selcx, obligation, data)
1181         }
1182         super::ImplSourceObject(_) => {
1183             confirm_object_candidate(selcx, obligation, obligation_trait_ref)
1184         }
1185         super::ImplSourceAutoImpl(..)
1186         | super::ImplSourceParam(..)
1187         | super::ImplSourceBuiltin(..)
1188         | super::ImplSourceTraitAlias(..) =>
1189         // we don't create Select candidates with this kind of resolution
1190         {
1191             span_bug!(
1192                 obligation.cause.span,
1193                 "Cannot project an associated type from `{:?}`",
1194                 impl_source
1195             )
1196         }
1197     }
1198 }
1199
1200 fn confirm_object_candidate<'cx, 'tcx>(
1201     selcx: &mut SelectionContext<'cx, 'tcx>,
1202     obligation: &ProjectionTyObligation<'tcx>,
1203     obligation_trait_ref: &ty::TraitRef<'tcx>,
1204 ) -> Progress<'tcx> {
1205     let self_ty = obligation_trait_ref.self_ty();
1206     let object_ty = selcx.infcx().shallow_resolve(self_ty);
1207     debug!("confirm_object_candidate(object_ty={:?})", object_ty);
1208     let data = match object_ty.kind {
1209         ty::Dynamic(ref data, ..) => data,
1210         _ => span_bug!(
1211             obligation.cause.span,
1212             "confirm_object_candidate called with non-object: {:?}",
1213             object_ty
1214         ),
1215     };
1216     let env_predicates = data
1217         .projection_bounds()
1218         .map(|p| p.with_self_ty(selcx.tcx(), object_ty).to_predicate(selcx.tcx()));
1219     let env_predicate = {
1220         let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
1221
1222         // select only those projections that are actually projecting an
1223         // item with the correct name
1224
1225         let env_predicates = env_predicates.filter_map(|o| match o.predicate.skip_binders() {
1226             ty::PredicateAtom::Projection(data)
1227                 if data.projection_ty.item_def_id == obligation.predicate.item_def_id =>
1228             {
1229                 Some(ty::Binder::bind(data))
1230             }
1231             _ => None,
1232         });
1233
1234         // select those with a relevant trait-ref
1235         let mut env_predicates = env_predicates.filter(|data| {
1236             let data_poly_trait_ref = data.to_poly_trait_ref(selcx.tcx());
1237             let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1238             selcx.infcx().probe(|_| {
1239                 selcx
1240                     .infcx()
1241                     .at(&obligation.cause, obligation.param_env)
1242                     .sup(obligation_poly_trait_ref, data_poly_trait_ref)
1243                     .is_ok()
1244             })
1245         });
1246
1247         // select the first matching one; there really ought to be one or
1248         // else the object type is not WF, since an object type should
1249         // include all of its projections explicitly
1250         match env_predicates.next() {
1251             Some(env_predicate) => env_predicate,
1252             None => {
1253                 debug!(
1254                     "confirm_object_candidate: no env-predicate \
1255                      found in object type `{:?}`; ill-formed",
1256                     object_ty
1257                 );
1258                 return Progress::error(selcx.tcx());
1259             }
1260         }
1261     };
1262
1263     confirm_param_env_candidate(selcx, obligation, env_predicate)
1264 }
1265
1266 fn confirm_generator_candidate<'cx, 'tcx>(
1267     selcx: &mut SelectionContext<'cx, 'tcx>,
1268     obligation: &ProjectionTyObligation<'tcx>,
1269     impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>,
1270 ) -> Progress<'tcx> {
1271     let gen_sig = impl_source.substs.as_generator().poly_sig();
1272     let Normalized { value: gen_sig, obligations } = normalize_with_depth(
1273         selcx,
1274         obligation.param_env,
1275         obligation.cause.clone(),
1276         obligation.recursion_depth + 1,
1277         &gen_sig,
1278     );
1279
1280     debug!(
1281         "confirm_generator_candidate: obligation={:?},gen_sig={:?},obligations={:?}",
1282         obligation, gen_sig, obligations
1283     );
1284
1285     let tcx = selcx.tcx();
1286
1287     let gen_def_id = tcx.require_lang_item(GeneratorTraitLangItem, None);
1288
1289     let predicate = super::util::generator_trait_ref_and_outputs(
1290         tcx,
1291         gen_def_id,
1292         obligation.predicate.self_ty(),
1293         gen_sig,
1294     )
1295     .map_bound(|(trait_ref, yield_ty, return_ty)| {
1296         let name = tcx.associated_item(obligation.predicate.item_def_id).ident.name;
1297         let ty = if name == sym::Return {
1298             return_ty
1299         } else if name == sym::Yield {
1300             yield_ty
1301         } else {
1302             bug!()
1303         };
1304
1305         ty::ProjectionPredicate {
1306             projection_ty: ty::ProjectionTy {
1307                 substs: trait_ref.substs,
1308                 item_def_id: obligation.predicate.item_def_id,
1309             },
1310             ty,
1311         }
1312     });
1313
1314     confirm_param_env_candidate(selcx, obligation, predicate)
1315         .with_addl_obligations(impl_source.nested)
1316         .with_addl_obligations(obligations)
1317 }
1318
1319 fn confirm_discriminant_kind_candidate<'cx, 'tcx>(
1320     selcx: &mut SelectionContext<'cx, 'tcx>,
1321     obligation: &ProjectionTyObligation<'tcx>,
1322     _: ImplSourceDiscriminantKindData,
1323 ) -> Progress<'tcx> {
1324     let tcx = selcx.tcx();
1325
1326     let self_ty = selcx.infcx().shallow_resolve(obligation.predicate.self_ty());
1327     let substs = tcx.mk_substs([self_ty.into()].iter());
1328
1329     let discriminant_def_id = tcx.require_lang_item(DiscriminantTypeLangItem, None);
1330
1331     let predicate = ty::ProjectionPredicate {
1332         projection_ty: ty::ProjectionTy { substs, item_def_id: discriminant_def_id },
1333         ty: self_ty.discriminant_ty(tcx),
1334     };
1335
1336     confirm_param_env_candidate(selcx, obligation, ty::Binder::bind(predicate))
1337 }
1338
1339 fn confirm_fn_pointer_candidate<'cx, 'tcx>(
1340     selcx: &mut SelectionContext<'cx, 'tcx>,
1341     obligation: &ProjectionTyObligation<'tcx>,
1342     fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>,
1343 ) -> Progress<'tcx> {
1344     let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty);
1345     let sig = fn_type.fn_sig(selcx.tcx());
1346     let Normalized { value: sig, obligations } = normalize_with_depth(
1347         selcx,
1348         obligation.param_env,
1349         obligation.cause.clone(),
1350         obligation.recursion_depth + 1,
1351         &sig,
1352     );
1353
1354     confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes)
1355         .with_addl_obligations(fn_pointer_impl_source.nested)
1356         .with_addl_obligations(obligations)
1357 }
1358
1359 fn confirm_closure_candidate<'cx, 'tcx>(
1360     selcx: &mut SelectionContext<'cx, 'tcx>,
1361     obligation: &ProjectionTyObligation<'tcx>,
1362     impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>,
1363 ) -> Progress<'tcx> {
1364     let closure_sig = impl_source.substs.as_closure().sig();
1365     let Normalized { value: closure_sig, obligations } = normalize_with_depth(
1366         selcx,
1367         obligation.param_env,
1368         obligation.cause.clone(),
1369         obligation.recursion_depth + 1,
1370         &closure_sig,
1371     );
1372
1373     debug!(
1374         "confirm_closure_candidate: obligation={:?},closure_sig={:?},obligations={:?}",
1375         obligation, closure_sig, obligations
1376     );
1377
1378     confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No)
1379         .with_addl_obligations(impl_source.nested)
1380         .with_addl_obligations(obligations)
1381 }
1382
1383 fn confirm_callable_candidate<'cx, 'tcx>(
1384     selcx: &mut SelectionContext<'cx, 'tcx>,
1385     obligation: &ProjectionTyObligation<'tcx>,
1386     fn_sig: ty::PolyFnSig<'tcx>,
1387     flag: util::TupleArgumentsFlag,
1388 ) -> Progress<'tcx> {
1389     let tcx = selcx.tcx();
1390
1391     debug!("confirm_callable_candidate({:?},{:?})", obligation, fn_sig);
1392
1393     let fn_once_def_id = tcx.require_lang_item(FnOnceTraitLangItem, None);
1394     let fn_once_output_def_id = tcx.require_lang_item(FnOnceOutputLangItem, None);
1395
1396     let predicate = super::util::closure_trait_ref_and_return_type(
1397         tcx,
1398         fn_once_def_id,
1399         obligation.predicate.self_ty(),
1400         fn_sig,
1401         flag,
1402     )
1403     .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
1404         projection_ty: ty::ProjectionTy {
1405             substs: trait_ref.substs,
1406             item_def_id: fn_once_output_def_id,
1407         },
1408         ty: ret_type,
1409     });
1410
1411     confirm_param_env_candidate(selcx, obligation, predicate)
1412 }
1413
1414 fn confirm_param_env_candidate<'cx, 'tcx>(
1415     selcx: &mut SelectionContext<'cx, 'tcx>,
1416     obligation: &ProjectionTyObligation<'tcx>,
1417     poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
1418 ) -> Progress<'tcx> {
1419     let infcx = selcx.infcx();
1420     let cause = &obligation.cause;
1421     let param_env = obligation.param_env;
1422
1423     let (cache_entry, _) = infcx.replace_bound_vars_with_fresh_vars(
1424         cause.span,
1425         LateBoundRegionConversionTime::HigherRankedType,
1426         &poly_cache_entry,
1427     );
1428
1429     let cache_trait_ref = cache_entry.projection_ty.trait_ref(infcx.tcx);
1430     let obligation_trait_ref = obligation.predicate.trait_ref(infcx.tcx);
1431     match infcx.at(cause, param_env).eq(cache_trait_ref, obligation_trait_ref) {
1432         Ok(InferOk { value: _, obligations }) => Progress { ty: cache_entry.ty, obligations },
1433         Err(e) => {
1434             let msg = format!(
1435                 "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}",
1436                 obligation, poly_cache_entry, e,
1437             );
1438             debug!("confirm_param_env_candidate: {}", msg);
1439             let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg);
1440             Progress { ty: err, obligations: vec![] }
1441         }
1442     }
1443 }
1444
1445 fn confirm_impl_candidate<'cx, 'tcx>(
1446     selcx: &mut SelectionContext<'cx, 'tcx>,
1447     obligation: &ProjectionTyObligation<'tcx>,
1448     impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
1449 ) -> Progress<'tcx> {
1450     let tcx = selcx.tcx();
1451
1452     let ImplSourceUserDefinedData { impl_def_id, substs, nested } = impl_impl_source;
1453     let assoc_item_id = obligation.predicate.item_def_id;
1454     let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1455
1456     let param_env = obligation.param_env;
1457     let assoc_ty = match assoc_ty_def(selcx, impl_def_id, assoc_item_id) {
1458         Ok(assoc_ty) => assoc_ty,
1459         Err(ErrorReported) => return Progress { ty: tcx.ty_error(), obligations: nested },
1460     };
1461
1462     if !assoc_ty.item.defaultness.has_value() {
1463         // This means that the impl is missing a definition for the
1464         // associated type. This error will be reported by the type
1465         // checker method `check_impl_items_against_trait`, so here we
1466         // just return Error.
1467         debug!(
1468             "confirm_impl_candidate: no associated type {:?} for {:?}",
1469             assoc_ty.item.ident, obligation.predicate
1470         );
1471         return Progress { ty: tcx.ty_error(), obligations: nested };
1472     }
1473     // If we're trying to normalize `<Vec<u32> as X>::A<S>` using
1474     //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
1475     //
1476     // * `obligation.predicate.substs` is `[Vec<u32>, S]`
1477     // * `substs` is `[u32]`
1478     // * `substs` ends up as `[u32, S]`
1479     let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs);
1480     let substs =
1481         translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node);
1482     let ty = tcx.type_of(assoc_ty.item.def_id);
1483     if substs.len() != tcx.generics_of(assoc_ty.item.def_id).count() {
1484         let err = tcx.ty_error_with_message(
1485             DUMMY_SP,
1486             "impl item and trait item have different parameter counts",
1487         );
1488         Progress { ty: err, obligations: nested }
1489     } else {
1490         Progress { ty: ty.subst(tcx, substs), obligations: nested }
1491     }
1492 }
1493
1494 /// Locate the definition of an associated type in the specialization hierarchy,
1495 /// starting from the given impl.
1496 ///
1497 /// Based on the "projection mode", this lookup may in fact only examine the
1498 /// topmost impl. See the comments for `Reveal` for more details.
1499 fn assoc_ty_def(
1500     selcx: &SelectionContext<'_, '_>,
1501     impl_def_id: DefId,
1502     assoc_ty_def_id: DefId,
1503 ) -> Result<specialization_graph::LeafDef, ErrorReported> {
1504     let tcx = selcx.tcx();
1505     let assoc_ty_name = tcx.associated_item(assoc_ty_def_id).ident;
1506     let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id;
1507     let trait_def = tcx.trait_def(trait_def_id);
1508
1509     // This function may be called while we are still building the
1510     // specialization graph that is queried below (via TraitDef::ancestors()),
1511     // so, in order to avoid unnecessary infinite recursion, we manually look
1512     // for the associated item at the given impl.
1513     // If there is no such item in that impl, this function will fail with a
1514     // cycle error if the specialization graph is currently being built.
1515     let impl_node = specialization_graph::Node::Impl(impl_def_id);
1516     for item in impl_node.items(tcx) {
1517         if matches!(item.kind, ty::AssocKind::Type)
1518             && tcx.hygienic_eq(item.ident, assoc_ty_name, trait_def_id)
1519         {
1520             return Ok(specialization_graph::LeafDef {
1521                 item: *item,
1522                 defining_node: impl_node,
1523                 finalizing_node: if item.defaultness.is_default() { None } else { Some(impl_node) },
1524             });
1525         }
1526     }
1527
1528     let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
1529     if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_ty_name, ty::AssocKind::Type) {
1530         Ok(assoc_item)
1531     } else {
1532         // This is saying that neither the trait nor
1533         // the impl contain a definition for this
1534         // associated type.  Normally this situation
1535         // could only arise through a compiler bug --
1536         // if the user wrote a bad item name, it
1537         // should have failed in astconv.
1538         bug!("No associated type `{}` for {}", assoc_ty_name, tcx.def_path_str(impl_def_id))
1539     }
1540 }
1541
1542 crate trait ProjectionCacheKeyExt<'tcx>: Sized {
1543     fn from_poly_projection_predicate(
1544         selcx: &mut SelectionContext<'cx, 'tcx>,
1545         predicate: ty::PolyProjectionPredicate<'tcx>,
1546     ) -> Option<Self>;
1547 }
1548
1549 impl<'tcx> ProjectionCacheKeyExt<'tcx> for ProjectionCacheKey<'tcx> {
1550     fn from_poly_projection_predicate(
1551         selcx: &mut SelectionContext<'cx, 'tcx>,
1552         predicate: ty::PolyProjectionPredicate<'tcx>,
1553     ) -> Option<Self> {
1554         let infcx = selcx.infcx();
1555         // We don't do cross-snapshot caching of obligations with escaping regions,
1556         // so there's no cache key to use
1557         predicate.no_bound_vars().map(|predicate| {
1558             ProjectionCacheKey::new(
1559                 // We don't attempt to match up with a specific type-variable state
1560                 // from a specific call to `opt_normalize_projection_type` - if
1561                 // there's no precise match, the original cache entry is "stranded"
1562                 // anyway.
1563                 infcx.resolve_vars_if_possible(&predicate.projection_ty),
1564             )
1565         })
1566     }
1567 }