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