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