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