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