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