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