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