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