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