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