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