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