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