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